LCOV - differential code coverage report
Current view: top level - src/backend/access/heap - heapam.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 90.3 % 3305 2986 1 4 314 3 2 161 2820 1 3 225
Current Date: 2024-04-14 14:21:10 Functions: 97.8 % 93 91 2 23 68 9
Baseline: 16@8cea358b128 Branches: 68.8 % 2800 1925 15 5 855 2 93 1830 2
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed [..60] days: 98.5 % 197 194 1 2 1 160 33
(120,180] days: 100.0 % 8 8 8
(180,240] days: 100.0 % 2 2 2
(240..) days: 89.8 % 3098 2782 4 312 3 1 1 2777 1
Function coverage date bins:
[..60] days: 100.0 % 9 9 8 1
(240..) days: 97.6 % 84 82 2 15 67
Branch coverage date bins:
[..60] days: 85.5 % 124 106 15 3 93 13
(120,180] days: 75.0 % 16 12 4 12
(240..) days: 67.9 % 2662 1807 5 848 2 1805 2

 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-2024, 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/bufmask.h"
                                 35                 :                : #include "access/heapam.h"
                                 36                 :                : #include "access/heapam_xlog.h"
                                 37                 :                : #include "access/heaptoast.h"
                                 38                 :                : #include "access/hio.h"
                                 39                 :                : #include "access/multixact.h"
                                 40                 :                : #include "access/parallel.h"
                                 41                 :                : #include "access/relscan.h"
                                 42                 :                : #include "access/subtrans.h"
                                 43                 :                : #include "access/syncscan.h"
                                 44                 :                : #include "access/sysattr.h"
                                 45                 :                : #include "access/tableam.h"
                                 46                 :                : #include "access/transam.h"
                                 47                 :                : #include "access/valid.h"
                                 48                 :                : #include "access/visibilitymap.h"
                                 49                 :                : #include "access/xact.h"
                                 50                 :                : #include "access/xlog.h"
                                 51                 :                : #include "access/xloginsert.h"
                                 52                 :                : #include "access/xlogutils.h"
                                 53                 :                : #include "catalog/catalog.h"
                                 54                 :                : #include "commands/vacuum.h"
                                 55                 :                : #include "miscadmin.h"
                                 56                 :                : #include "pgstat.h"
                                 57                 :                : #include "port/atomics.h"
                                 58                 :                : #include "port/pg_bitutils.h"
                                 59                 :                : #include "storage/bufmgr.h"
                                 60                 :                : #include "storage/freespace.h"
                                 61                 :                : #include "storage/lmgr.h"
                                 62                 :                : #include "storage/predicate.h"
                                 63                 :                : #include "storage/procarray.h"
                                 64                 :                : #include "storage/standby.h"
                                 65                 :                : #include "utils/datum.h"
                                 66                 :                : #include "utils/inval.h"
                                 67                 :                : #include "utils/relcache.h"
                                 68                 :                : #include "utils/snapmgr.h"
                                 69                 :                : #include "utils/spccache.h"
                                 70                 :                : 
                                 71                 :                : 
                                 72                 :                : static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup,
                                 73                 :                :                                      TransactionId xid, CommandId cid, int options);
                                 74                 :                : static XLogRecPtr log_heap_update(Relation reln, Buffer oldbuf,
                                 75                 :                :                                   Buffer newbuf, HeapTuple oldtup,
                                 76                 :                :                                   HeapTuple newtup, HeapTuple old_key_tuple,
                                 77                 :                :                                   bool all_visible_cleared, bool new_all_visible_cleared);
                                 78                 :                : static Bitmapset *HeapDetermineColumnsInfo(Relation relation,
                                 79                 :                :                                            Bitmapset *interesting_cols,
                                 80                 :                :                                            Bitmapset *external_cols,
                                 81                 :                :                                            HeapTuple oldtup, HeapTuple newtup,
                                 82                 :                :                                            bool *has_external);
                                 83                 :                : static bool heap_acquire_tuplock(Relation relation, ItemPointer tid,
                                 84                 :                :                                  LockTupleMode mode, LockWaitPolicy wait_policy,
                                 85                 :                :                                  bool *have_tuple_lock);
                                 86                 :                : static inline BlockNumber heapgettup_advance_block(HeapScanDesc scan,
                                 87                 :                :                                                    BlockNumber block,
                                 88                 :                :                                                    ScanDirection dir);
                                 89                 :                : static pg_noinline BlockNumber heapgettup_initial_block(HeapScanDesc scan,
                                 90                 :                :                                                         ScanDirection dir);
                                 91                 :                : static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
                                 92                 :                :                                       uint16 old_infomask2, TransactionId add_to_xmax,
                                 93                 :                :                                       LockTupleMode mode, bool is_update,
                                 94                 :                :                                       TransactionId *result_xmax, uint16 *result_infomask,
                                 95                 :                :                                       uint16 *result_infomask2);
                                 96                 :                : static TM_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple,
                                 97                 :                :                                          ItemPointer ctid, TransactionId xid,
                                 98                 :                :                                          LockTupleMode mode);
                                 99                 :                : static void GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
                                100                 :                :                                    uint16 *new_infomask2);
                                101                 :                : static TransactionId MultiXactIdGetUpdateXid(TransactionId xmax,
                                102                 :                :                                              uint16 t_infomask);
                                103                 :                : static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
                                104                 :                :                                     LockTupleMode lockmode, bool *current_is_member);
                                105                 :                : static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
                                106                 :                :                             Relation rel, ItemPointer ctid, XLTW_Oper oper,
                                107                 :                :                             int *remaining);
                                108                 :                : static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                                109                 :                :                                        uint16 infomask, Relation rel, int *remaining);
                                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                 :                :  * Each tuple lock mode has a corresponding heavyweight lock, and one or two
                                119                 :                :  * corresponding MultiXactStatuses (one to merely lock tuples, another one to
                                120                 :                :  * update them).  This table (and the macros below) helps us determine the
                                121                 :                :  * heavyweight lock mode and MultiXactStatus values to use for any particular
                                122                 :                :  * tuple lock strength.
                                123                 :                :  *
                                124                 :                :  * Don't look at lockstatus/updstatus directly!  Use get_mxact_status_for_lock
                                125                 :                :  * instead.
                                126                 :                :  */
                                127                 :                : static const struct
                                128                 :                : {
                                129                 :                :     LOCKMODE    hwlock;
                                130                 :                :     int         lockstatus;
                                131                 :                :     int         updstatus;
                                132                 :                : }
                                133                 :                : 
                                134                 :                :             tupleLockExtraInfo[MaxLockTupleMode + 1] =
                                135                 :                : {
                                136                 :                :     {                           /* LockTupleKeyShare */
                                137                 :                :         AccessShareLock,
                                138                 :                :         MultiXactStatusForKeyShare,
                                139                 :                :         -1                      /* KeyShare does not allow updating tuples */
                                140                 :                :     },
                                141                 :                :     {                           /* LockTupleShare */
                                142                 :                :         RowShareLock,
                                143                 :                :         MultiXactStatusForShare,
                                144                 :                :         -1                      /* Share does not allow updating tuples */
                                145                 :                :     },
                                146                 :                :     {                           /* LockTupleNoKeyExclusive */
                                147                 :                :         ExclusiveLock,
                                148                 :                :         MultiXactStatusForNoKeyUpdate,
                                149                 :                :         MultiXactStatusNoKeyUpdate
                                150                 :                :     },
                                151                 :                :     {                           /* LockTupleExclusive */
                                152                 :                :         AccessExclusiveLock,
                                153                 :                :         MultiXactStatusForUpdate,
                                154                 :                :         MultiXactStatusUpdate
                                155                 :                :     }
                                156                 :                : };
                                157                 :                : 
                                158                 :                : /* Get the LOCKMODE for a given MultiXactStatus */
                                159                 :                : #define LOCKMODE_from_mxstatus(status) \
                                160                 :                :             (tupleLockExtraInfo[TUPLOCK_from_mxstatus((status))].hwlock)
                                161                 :                : 
                                162                 :                : /*
                                163                 :                :  * Acquire heavyweight locks on tuples, using a LockTupleMode strength value.
                                164                 :                :  * This is more readable than having every caller translate it to lock.h's
                                165                 :                :  * LOCKMODE.
                                166                 :                :  */
                                167                 :                : #define LockTupleTuplock(rel, tup, mode) \
                                168                 :                :     LockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
                                169                 :                : #define UnlockTupleTuplock(rel, tup, mode) \
                                170                 :                :     UnlockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
                                171                 :                : #define ConditionalLockTupleTuplock(rel, tup, mode) \
                                172                 :                :     ConditionalLockTuple((rel), (tup), tupleLockExtraInfo[mode].hwlock)
                                173                 :                : 
                                174                 :                : #ifdef USE_PREFETCH
                                175                 :                : /*
                                176                 :                :  * heap_index_delete_tuples and index_delete_prefetch_buffer use this
                                177                 :                :  * structure to coordinate prefetching activity
                                178                 :                :  */
                                179                 :                : typedef struct
                                180                 :                : {
                                181                 :                :     BlockNumber cur_hblkno;
                                182                 :                :     int         next_item;
                                183                 :                :     int         ndeltids;
                                184                 :                :     TM_IndexDelete *deltids;
                                185                 :                : } IndexDeletePrefetchState;
                                186                 :                : #endif
                                187                 :                : 
                                188                 :                : /* heap_index_delete_tuples bottom-up index deletion costing constants */
                                189                 :                : #define BOTTOMUP_MAX_NBLOCKS            6
                                190                 :                : #define BOTTOMUP_TOLERANCE_NBLOCKS      3
                                191                 :                : 
                                192                 :                : /*
                                193                 :                :  * heap_index_delete_tuples uses this when determining which heap blocks it
                                194                 :                :  * must visit to help its bottom-up index deletion caller
                                195                 :                :  */
                                196                 :                : typedef struct IndexDeleteCounts
                                197                 :                : {
                                198                 :                :     int16       npromisingtids; /* Number of "promising" TIDs in group */
                                199                 :                :     int16       ntids;          /* Number of TIDs in group */
                                200                 :                :     int16       ifirsttid;      /* Offset to group's first deltid */
                                201                 :                : } IndexDeleteCounts;
                                202                 :                : 
                                203                 :                : /*
                                204                 :                :  * This table maps tuple lock strength values for each particular
                                205                 :                :  * MultiXactStatus value.
                                206                 :                :  */
                                207                 :                : static const int MultiXactStatusLock[MaxMultiXactStatus + 1] =
                                208                 :                : {
                                209                 :                :     LockTupleKeyShare,          /* ForKeyShare */
                                210                 :                :     LockTupleShare,             /* ForShare */
                                211                 :                :     LockTupleNoKeyExclusive,    /* ForNoKeyUpdate */
                                212                 :                :     LockTupleExclusive,         /* ForUpdate */
                                213                 :                :     LockTupleNoKeyExclusive,    /* NoKeyUpdate */
                                214                 :                :     LockTupleExclusive          /* Update */
                                215                 :                : };
                                216                 :                : 
                                217                 :                : /* Get the LockTupleMode for a given MultiXactStatus */
                                218                 :                : #define TUPLOCK_from_mxstatus(status) \
                                219                 :                :             (MultiXactStatusLock[(status)])
                                220                 :                : 
                                221                 :                : /* ----------------------------------------------------------------
                                222                 :                :  *                       heap support routines
                                223                 :                :  * ----------------------------------------------------------------
                                224                 :                :  */
                                225                 :                : 
                                226                 :                : /*
                                227                 :                :  * Streaming read API callback for parallel sequential scans. Returns the next
                                228                 :                :  * block the caller wants from the read stream or InvalidBlockNumber when done.
                                229                 :                :  */
                                230                 :                : static BlockNumber
    6 tmunro@postgresql.or      231                 :GNC      100170 : heap_scan_stream_read_next_parallel(ReadStream *stream,
                                232                 :                :                                     void *callback_private_data,
                                233                 :                :                                     void *per_buffer_data)
                                234                 :                : {
                                235                 :         100170 :     HeapScanDesc scan = (HeapScanDesc) callback_private_data;
                                236                 :                : 
                                237         [ -  + ]:         100170 :     Assert(ScanDirectionIsForward(scan->rs_dir));
                                238         [ -  + ]:         100170 :     Assert(scan->rs_base.rs_parallel);
                                239                 :                : 
                                240         [ +  + ]:         100170 :     if (unlikely(!scan->rs_inited))
                                241                 :                :     {
                                242                 :                :         /* parallel scan */
                                243                 :           1544 :         table_block_parallelscan_startblock_init(scan->rs_base.rs_rd,
                                244                 :           1544 :                                                  scan->rs_parallelworkerdata,
                                245                 :           1544 :                                                  (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
                                246                 :                : 
                                247                 :                :         /* may return InvalidBlockNumber if there are no more blocks */
                                248                 :           3088 :         scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
                                249                 :           1544 :                                                                     scan->rs_parallelworkerdata,
                                250                 :           1544 :                                                                     (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel);
                                251                 :           1544 :         scan->rs_inited = true;
                                252                 :                :     }
                                253                 :                :     else
                                254                 :                :     {
                                255                 :          98626 :         scan->rs_prefetch_block = table_block_parallelscan_nextpage(scan->rs_base.rs_rd,
                                256                 :          98626 :                                                                     scan->rs_parallelworkerdata, (ParallelBlockTableScanDesc)
                                257                 :          98626 :                                                                     scan->rs_base.rs_parallel);
                                258                 :                :     }
                                259                 :                : 
                                260                 :         100170 :     return scan->rs_prefetch_block;
                                261                 :                : }
                                262                 :                : 
                                263                 :                : /*
                                264                 :                :  * Streaming read API callback for serial sequential and TID range scans.
                                265                 :                :  * Returns the next block the caller wants from the read stream or
                                266                 :                :  * InvalidBlockNumber when done.
                                267                 :                :  */
                                268                 :                : static BlockNumber
                                269                 :        3191371 : heap_scan_stream_read_next_serial(ReadStream *stream,
                                270                 :                :                                   void *callback_private_data,
                                271                 :                :                                   void *per_buffer_data)
                                272                 :                : {
                                273                 :        3191371 :     HeapScanDesc scan = (HeapScanDesc) callback_private_data;
                                274                 :                : 
                                275         [ +  + ]:        3191371 :     if (unlikely(!scan->rs_inited))
                                276                 :                :     {
                                277                 :         799536 :         scan->rs_prefetch_block = heapgettup_initial_block(scan, scan->rs_dir);
                                278                 :         799536 :         scan->rs_inited = true;
                                279                 :                :     }
                                280                 :                :     else
                                281                 :        2391835 :         scan->rs_prefetch_block = heapgettup_advance_block(scan,
                                282                 :                :                                                            scan->rs_prefetch_block,
                                283                 :                :                                                            scan->rs_dir);
                                284                 :                : 
                                285                 :        3191371 :     return scan->rs_prefetch_block;
                                286                 :                : }
                                287                 :                : 
                                288                 :                : /* ----------------
                                289                 :                :  *      initscan - scan code common to heap_beginscan and heap_rescan
                                290                 :                :  * ----------------
                                291                 :                :  */
                                292                 :                : static void
 3186 tgl@sss.pgh.pa.us         293                 :CBC      818193 : initscan(HeapScanDesc scan, ScanKey key, bool keep_startblock)
                                294                 :                : {
 1861 andres@anarazel.de        295                 :         818193 :     ParallelBlockTableScanDesc bpscan = NULL;
                                296                 :                :     bool        allow_strat;
                                297                 :                :     bool        allow_sync;
                                298                 :                : 
                                299                 :                :     /*
                                300                 :                :      * Determine the number of blocks we have to scan.
                                301                 :                :      *
                                302                 :                :      * It is sufficient to do this once at scan start, since any tuples added
                                303                 :                :      * while the scan is in progress will be invisible to my snapshot anyway.
                                304                 :                :      * (That is not true when using a non-MVCC snapshot.  However, we couldn't
                                305                 :                :      * guarantee to return tuples added after scan start anyway, since they
                                306                 :                :      * might go into pages we already scanned.  To guarantee consistent
                                307                 :                :      * results for a non-MVCC snapshot, the caller must hold some higher-level
                                308                 :                :      * lock that ensures the interesting tuple(s) won't change.)
                                309                 :                :      */
                                310         [ +  + ]:         818193 :     if (scan->rs_base.rs_parallel != NULL)
                                311                 :                :     {
                                312                 :           1983 :         bpscan = (ParallelBlockTableScanDesc) scan->rs_base.rs_parallel;
                                313                 :           1983 :         scan->rs_nblocks = bpscan->phs_nblocks;
                                314                 :                :     }
                                315                 :                :     else
                                316                 :         816210 :         scan->rs_nblocks = RelationGetNumberOfBlocks(scan->rs_base.rs_rd);
                                317                 :                : 
                                318                 :                :     /*
                                319                 :                :      * If the table is large relative to NBuffers, use a bulk-read access
                                320                 :                :      * strategy and enable synchronized scanning (see syncscan.c).  Although
                                321                 :                :      * the thresholds for these features could be different, we make them the
                                322                 :                :      * same so that there are only two behaviors to tune rather than four.
                                323                 :                :      * (However, some callers need to be able to disable one or both of these
                                324                 :                :      * behaviors, independently of the size of the table; also there is a GUC
                                325                 :                :      * variable that can disable synchronized scanning.)
                                326                 :                :      *
                                327                 :                :      * Note that table_block_parallelscan_initialize has a very similar test;
                                328                 :                :      * if you change this, consider changing that one, too.
                                329                 :                :      */
                                330         [ +  + ]:         818191 :     if (!RelationUsesLocalBuffers(scan->rs_base.rs_rd) &&
 6154 tgl@sss.pgh.pa.us         331         [ +  + ]:         812312 :         scan->rs_nblocks > NBuffers / 4)
                                332                 :                :     {
 1792 andres@anarazel.de        333                 :          10865 :         allow_strat = (scan->rs_base.rs_flags & SO_ALLOW_STRAT) != 0;
                                334                 :          10865 :         allow_sync = (scan->rs_base.rs_flags & SO_ALLOW_SYNC) != 0;
                                335                 :                :     }
                                336                 :                :     else
 5935 tgl@sss.pgh.pa.us         337                 :         807326 :         allow_strat = allow_sync = false;
                                338                 :                : 
                                339         [ +  + ]:         818191 :     if (allow_strat)
                                340                 :                :     {
                                341                 :                :         /* During a rescan, keep the previous strategy object. */
 6164                           342         [ +  + ]:           9617 :         if (scan->rs_strategy == NULL)
                                343                 :           9510 :             scan->rs_strategy = GetAccessStrategy(BAS_BULKREAD);
                                344                 :                :     }
                                345                 :                :     else
                                346                 :                :     {
                                347         [ -  + ]:         808574 :         if (scan->rs_strategy != NULL)
 6164 tgl@sss.pgh.pa.us         348                 :UBC           0 :             FreeAccessStrategy(scan->rs_strategy);
 6164 tgl@sss.pgh.pa.us         349                 :CBC      808574 :         scan->rs_strategy = NULL;
                                350                 :                :     }
                                351                 :                : 
 1861 andres@anarazel.de        352         [ +  + ]:         818191 :     if (scan->rs_base.rs_parallel != NULL)
                                353                 :                :     {
                                354                 :                :         /* For parallel scan, believe whatever ParallelTableScanDesc says. */
 1792                           355         [ +  + ]:           1983 :         if (scan->rs_base.rs_parallel->phs_syncscan)
                                356                 :              2 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                                357                 :                :         else
                                358                 :           1981 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                359                 :                :     }
 3103 rhaas@postgresql.org      360         [ +  + ]:         816208 :     else if (keep_startblock)
                                361                 :                :     {
                                362                 :                :         /*
                                363                 :                :          * When rescanning, we want to keep the previous startblock setting,
                                364                 :                :          * so that rewinding a cursor doesn't generate surprising results.
                                365                 :                :          * Reset the active syncscan setting, though.
                                366                 :                :          */
 1792 andres@anarazel.de        367   [ +  +  +  + ]:         499442 :         if (allow_sync && synchronize_seqscans)
 1792 andres@anarazel.de        368                 :GBC          20 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                                369                 :                :         else
 1792 andres@anarazel.de        370                 :CBC      499422 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                371                 :                :     }
 5422 tgl@sss.pgh.pa.us         372   [ +  +  +  + ]:         316766 :     else if (allow_sync && synchronize_seqscans)
                                373                 :                :     {
 1792 andres@anarazel.de        374                 :             58 :         scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
 1861                           375                 :             58 :         scan->rs_startblock = ss_get_location(scan->rs_base.rs_rd, scan->rs_nblocks);
                                376                 :                :     }
                                377                 :                :     else
                                378                 :                :     {
 1792                           379                 :         316708 :         scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
 6155 tgl@sss.pgh.pa.us         380                 :         316708 :         scan->rs_startblock = 0;
                                381                 :                :     }
                                382                 :                : 
 3446 alvherre@alvh.no-ip.      383                 :         818191 :     scan->rs_numblocks = InvalidBlockNumber;
 6714 tgl@sss.pgh.pa.us         384                 :         818191 :     scan->rs_inited = false;
 8345                           385                 :         818191 :     scan->rs_ctup.t_data = NULL;
 6714                           386                 :         818191 :     ItemPointerSetInvalid(&scan->rs_ctup.t_self);
 8345                           387                 :         818191 :     scan->rs_cbuf = InvalidBuffer;
 6714                           388                 :         818191 :     scan->rs_cblock = InvalidBlockNumber;
                                389                 :                : 
                                390                 :                :     /*
                                391                 :                :      * Initialize to ForwardScanDirection because it is most common and
                                392                 :                :      * because heap scans go forward before going backward (e.g. CURSORs).
                                393                 :                :      */
    6 tmunro@postgresql.or      394                 :GNC      818191 :     scan->rs_dir = ForwardScanDirection;
                                395                 :         818191 :     scan->rs_prefetch_block = InvalidBlockNumber;
                                396                 :                : 
                                397                 :                :     /* page-at-a-time fields are always invalid when not rs_inited */
                                398                 :                : 
                                399                 :                :     /*
                                400                 :                :      * copy the scan key, if appropriate
                                401                 :                :      */
  773 tgl@sss.pgh.pa.us         402   [ +  +  +  + ]:CBC      818191 :     if (key != NULL && scan->rs_base.rs_nkeys > 0)
 1861 andres@anarazel.de        403                 :         181972 :         memcpy(scan->rs_base.rs_key, key, scan->rs_base.rs_nkeys * sizeof(ScanKeyData));
                                404                 :                : 
                                405                 :                :     /*
                                406                 :                :      * Currently, we only have a stats counter for sequential heap scans (but
                                407                 :                :      * e.g for bitmap scans the underlying bitmap index scans will be counted,
                                408                 :                :      * and for sample scans we update stats for tuple fetches).
                                409                 :                :      */
 1792                           410         [ +  + ]:         818191 :     if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN)
 1861                           411   [ +  +  +  +  :         801548 :         pgstat_count_heap_scan(scan->rs_base.rs_rd);
                                              +  + ]
10141 scrappy@hub.org           412                 :         818191 : }
                                413                 :                : 
                                414                 :                : /*
                                415                 :                :  * heap_setscanlimits - restrict range of a heapscan
                                416                 :                :  *
                                417                 :                :  * startBlk is the page to start at
                                418                 :                :  * numBlks is number of pages to scan (InvalidBlockNumber means "all")
                                419                 :                :  */
                                420                 :                : void
 1861 andres@anarazel.de        421                 :           1878 : heap_setscanlimits(TableScanDesc sscan, BlockNumber startBlk, BlockNumber numBlks)
                                422                 :                : {
                                423                 :           1878 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                                424                 :                : 
 3190 tgl@sss.pgh.pa.us         425         [ -  + ]:           1878 :     Assert(!scan->rs_inited);    /* else too late to change */
                                426                 :                :     /* else rs_startblock is significant */
 1792 andres@anarazel.de        427         [ -  + ]:           1878 :     Assert(!(scan->rs_base.rs_flags & SO_ALLOW_SYNC));
                                428                 :                : 
                                429                 :                :     /* Check startBlk is valid (but allow case of zero blocks...) */
 3190 tgl@sss.pgh.pa.us         430   [ +  +  -  + ]:           1878 :     Assert(startBlk == 0 || startBlk < scan->rs_nblocks);
                                431                 :                : 
 3446 alvherre@alvh.no-ip.      432                 :           1878 :     scan->rs_startblock = startBlk;
                                433                 :           1878 :     scan->rs_numblocks = numBlks;
                                434                 :           1878 : }
                                435                 :                : 
                                436                 :                : /*
                                437                 :                :  * Per-tuple loop for heap_prepare_pagescan(). Pulled out so it can be called
                                438                 :                :  * multiple times, with constant arguments for all_visible,
                                439                 :                :  * check_serializable.
                                440                 :                :  */
                                441                 :                : pg_attribute_always_inline
                                442                 :                : static int
    7 andres@anarazel.de        443                 :GNC     1966403 : page_collect_tuples(HeapScanDesc scan, Snapshot snapshot,
                                444                 :                :                     Page page, Buffer buffer,
                                445                 :                :                     BlockNumber block, int lines,
                                446                 :                :                     bool all_visible, bool check_serializable)
                                447                 :                : {
    8                           448                 :        1966403 :     int         ntup = 0;
                                449                 :                :     OffsetNumber lineoff;
                                450                 :                : 
                                451         [ +  + ]:      101458717 :     for (lineoff = FirstOffsetNumber; lineoff <= lines; lineoff++)
                                452                 :                :     {
                                453                 :       99492322 :         ItemId      lpp = PageGetItemId(page, lineoff);
                                454                 :                :         HeapTupleData loctup;
                                455                 :                :         bool        valid;
                                456                 :                : 
                                457         [ +  + ]:       99492322 :         if (!ItemIdIsNormal(lpp))
                                458                 :       14234086 :             continue;
                                459                 :                : 
                                460                 :       85258236 :         loctup.t_data = (HeapTupleHeader) PageGetItem(page, lpp);
                                461                 :       85258236 :         loctup.t_len = ItemIdGetLength(lpp);
                                462                 :       85258236 :         loctup.t_tableOid = RelationGetRelid(scan->rs_base.rs_rd);
                                463                 :       85258236 :         ItemPointerSet(&(loctup.t_self), block, lineoff);
                                464                 :                : 
                                465         [ +  + ]:       85258236 :         if (all_visible)
                                466                 :       33135767 :             valid = true;
                                467                 :                :         else
                                468                 :       52122469 :             valid = HeapTupleSatisfiesVisibility(&loctup, snapshot, buffer);
                                469                 :                : 
                                470         [ +  + ]:       85258236 :         if (check_serializable)
                                471                 :           1417 :             HeapCheckForSerializableConflictOut(valid, scan->rs_base.rs_rd,
                                472                 :                :                                                 &loctup, buffer, snapshot);
                                473                 :                : 
                                474         [ +  + ]:       85258228 :         if (valid)
                                475                 :                :         {
                                476                 :       80135615 :             scan->rs_vistuples[ntup] = lineoff;
                                477                 :       80135615 :             ntup++;
                                478                 :                :         }
                                479                 :                :     }
                                480                 :                : 
                                481         [ -  + ]:        1966395 :     Assert(ntup <= MaxHeapTuplesPerPage);
                                482                 :                : 
                                483                 :        1966395 :     return ntup;
                                484                 :                : }
                                485                 :                : 
                                486                 :                : /*
                                487                 :                :  * heap_prepare_pagescan - Prepare current scan page to be scanned in pagemode
                                488                 :                :  *
                                489                 :                :  * Preparation currently consists of 1. prune the scan's rs_cbuf page, and 2.
                                490                 :                :  * fill the rs_vistuples[] array with the OffsetNumbers of visible tuples.
                                491                 :                :  */
                                492                 :                : void
   10 drowley@postgresql.o      493                 :        1966403 : heap_prepare_pagescan(TableScanDesc sscan)
                                494                 :                : {
 1861 andres@anarazel.de        495                 :CBC     1966403 :     HeapScanDesc scan = (HeapScanDesc) sscan;
   10 drowley@postgresql.o      496                 :GNC     1966403 :     Buffer      buffer = scan->rs_cbuf;
                                497                 :        1966403 :     BlockNumber block = scan->rs_cblock;
                                498                 :                :     Snapshot    snapshot;
                                499                 :                :     Page        page;
                                500                 :                :     int         lines;
                                501                 :                :     bool        all_visible;
                                502                 :                :     bool        check_serializable;
                                503                 :                : 
                                504         [ -  + ]:        1966403 :     Assert(BufferGetBlockNumber(buffer) == block);
                                505                 :                : 
                                506                 :                :     /* ensure we're not accidentally being used when not in pagemode */
                                507         [ -  + ]:        1966403 :     Assert(scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE);
 1861 andres@anarazel.de        508                 :CBC     1966403 :     snapshot = scan->rs_base.rs_snapshot;
                                509                 :                : 
                                510                 :                :     /*
                                511                 :                :      * Prune and repair fragmentation for the whole page, if possible.
                                512                 :                :      */
                                513                 :        1966403 :     heap_page_prune_opt(scan->rs_base.rs_rd, buffer);
                                514                 :                : 
                                515                 :                :     /*
                                516                 :                :      * We must hold share lock on the buffer content while examining tuple
                                517                 :                :      * visibility.  Afterwards, however, the tuples we have found to be
                                518                 :                :      * visible are guaranteed good as long as we hold the buffer pin.
                                519                 :                :      */
 6714 tgl@sss.pgh.pa.us         520                 :        1966403 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
                                521                 :                : 
  515 peter@eisentraut.org      522                 :        1966403 :     page = BufferGetPage(buffer);
                                523                 :        1966403 :     lines = PageGetMaxOffsetNumber(page);
                                524                 :                : 
                                525                 :                :     /*
                                526                 :                :      * If the all-visible flag indicates that all tuples on the page are
                                527                 :                :      * visible to everyone, we can skip the per-tuple visibility tests.
                                528                 :                :      *
                                529                 :                :      * Note: In hot standby, a tuple that's already visible to all
                                530                 :                :      * transactions on the primary might still be invisible to a read-only
                                531                 :                :      * transaction in the standby. We partly handle this problem by tracking
                                532                 :                :      * the minimum xmin of visible tuples as the cut-off XID while marking a
                                533                 :                :      * page all-visible on the primary and WAL log that along with the
                                534                 :                :      * visibility map SET operation. In hot standby, we wait for (or abort)
                                535                 :                :      * all transactions that can potentially may not see one or more tuples on
                                536                 :                :      * the page. That's how index-only scans work fine in hot standby. A
                                537                 :                :      * crucial difference between index-only scans and heap scans is that the
                                538                 :                :      * index-only scan completely relies on the visibility map where as heap
                                539                 :                :      * scan looks at the page-level PD_ALL_VISIBLE flag. We are not sure if
                                540                 :                :      * the page-level flag can be trusted in the same way, because it might
                                541                 :                :      * get propagated somehow without being explicitly WAL-logged, e.g. via a
                                542                 :                :      * full page write. Until we can prove that beyond doubt, let's check each
                                543                 :                :      * tuple for visibility the hard way.
                                544                 :                :      */
                                545   [ +  +  +  + ]:        1966403 :     all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery;
                                546                 :                :     check_serializable =
    8 andres@anarazel.de        547                 :GNC     1966403 :         CheckForSerializableConflictOutNeeded(scan->rs_base.rs_rd, snapshot);
                                548                 :                : 
                                549                 :                :     /*
                                550                 :                :      * We call page_collect_tuples() with constant arguments, to get the
                                551                 :                :      * compiler to constant fold the constant arguments. Separate calls with
                                552                 :                :      * constant arguments, rather than variables, are needed on several
                                553                 :                :      * compilers to actually perform constant folding.
                                554                 :                :      */
                                555         [ +  + ]:        1966403 :     if (likely(all_visible))
                                556                 :                :     {
                                557         [ +  - ]:         746346 :         if (likely(!check_serializable))
    7                           558                 :         746346 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                559                 :                :                                                    block, lines, true, false);
                                560                 :                :         else
    7 andres@anarazel.de        561                 :UNC           0 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                562                 :                :                                                    block, lines, true, true);
                                563                 :                :     }
                                564                 :                :     else
                                565                 :                :     {
    8 andres@anarazel.de        566         [ +  + ]:GNC     1220057 :         if (likely(!check_serializable))
    7                           567                 :        1219429 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                568                 :                :                                                    block, lines, false, false);
                                569                 :                :         else
                                570                 :            628 :             scan->rs_ntuples = page_collect_tuples(scan, snapshot, page, buffer,
                                571                 :                :                                                    block, lines, false, true);
                                572                 :                :     }
                                573                 :                : 
 6714 tgl@sss.pgh.pa.us         574                 :CBC     1966395 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
 6714 tgl@sss.pgh.pa.us         575                 :GNC     1966395 : }
                                576                 :                : 
                                577                 :                : /*
                                578                 :                :  * heap_fetch_next_buffer - read and pin the next block from MAIN_FORKNUM.
                                579                 :                :  *
                                580                 :                :  * Read the next block of the scan relation from the read stream and save it
                                581                 :                :  * in the scan descriptor.  It is already pinned.
                                582                 :                :  */
                                583                 :                : static inline void
   10 drowley@postgresql.o      584                 :        2722165 : heap_fetch_next_buffer(HeapScanDesc scan, ScanDirection dir)
                                585                 :                : {
    6 tmunro@postgresql.or      586         [ -  + ]:        2722165 :     Assert(scan->rs_read_stream);
                                587                 :                : 
                                588                 :                :     /* release previous scan buffer, if any */
   10 drowley@postgresql.o      589         [ +  + ]:        2722165 :     if (BufferIsValid(scan->rs_cbuf))
                                590                 :                :     {
                                591                 :        1921085 :         ReleaseBuffer(scan->rs_cbuf);
                                592                 :        1921085 :         scan->rs_cbuf = InvalidBuffer;
                                593                 :                :     }
                                594                 :                : 
                                595                 :                :     /*
                                596                 :                :      * Be sure to check for interrupts at least once per page.  Checks at
                                597                 :                :      * higher code levels won't be able to stop a seqscan that encounters many
                                598                 :                :      * pages' worth of consecutive dead tuples.
                                599                 :                :      */
                                600         [ +  + ]:        2722165 :     CHECK_FOR_INTERRUPTS();
                                601                 :                : 
                                602                 :                :     /*
                                603                 :                :      * If the scan direction is changing, reset the prefetch block to the
                                604                 :                :      * current block. Otherwise, we will incorrectly prefetch the blocks
                                605                 :                :      * between the prefetch block and the current block again before
                                606                 :                :      * prefetching blocks in the new, correct scan direction.
                                607                 :                :      */
    6 tmunro@postgresql.or      608         [ +  + ]:        2722161 :     if (unlikely(scan->rs_dir != dir))
                                609                 :                :     {
                                610                 :             76 :         scan->rs_prefetch_block = scan->rs_cblock;
                                611                 :             76 :         read_stream_reset(scan->rs_read_stream);
                                612                 :                :     }
                                613                 :                : 
                                614                 :        2722161 :     scan->rs_dir = dir;
                                615                 :                : 
                                616                 :        2722161 :     scan->rs_cbuf = read_stream_next_buffer(scan->rs_read_stream, NULL);
                                617         [ +  + ]:        2722161 :     if (BufferIsValid(scan->rs_cbuf))
                                618                 :        2054330 :         scan->rs_cblock = BufferGetBlockNumber(scan->rs_cbuf);
   10 drowley@postgresql.o      619                 :GIC     2722161 : }
                                620                 :                : 
                                621                 :                : /*
                                622                 :                :  * heapgettup_initial_block - return the first BlockNumber to scan
                                623                 :                :  *
                                624                 :                :  * Returns InvalidBlockNumber when there are no blocks to scan.  This can
                                625                 :                :  * occur with empty tables and in parallel scans when parallel workers get all
                                626                 :                :  * of the pages before we can get a chance to get our first page.
                                627                 :                :  */
                                628                 :                : static pg_noinline BlockNumber
  437 drowley@postgresql.o      629                 :CBC      799536 : heapgettup_initial_block(HeapScanDesc scan, ScanDirection dir)
                                630                 :                : {
                                631         [ -  + ]:         799536 :     Assert(!scan->rs_inited);
    6 tmunro@postgresql.or      632         [ -  + ]:GNC      799536 :     Assert(scan->rs_base.rs_parallel == NULL);
                                633                 :                : 
                                634                 :                :     /* When there are no pages to scan, return InvalidBlockNumber */
  437 drowley@postgresql.o      635   [ +  +  +  + ]:CBC      799536 :     if (scan->rs_nblocks == 0 || scan->rs_numblocks == 0)
                                636                 :         380715 :         return InvalidBlockNumber;
                                637                 :                : 
                                638         [ +  + ]:         418821 :     if (ScanDirectionIsForward(dir))
                                639                 :                :     {
    6 tmunro@postgresql.or      640                 :GNC      418790 :         return scan->rs_startblock;
                                641                 :                :     }
                                642                 :                :     else
                                643                 :                :     {
                                644                 :                :         /*
                                645                 :                :          * Disable reporting to syncscan logic in a backwards scan; it's not
                                646                 :                :          * very likely anyone else is doing the same thing at the same time,
                                647                 :                :          * and much more likely that we'll just bollix things for forward
                                648                 :                :          * scanners.
                                649                 :                :          */
  437 drowley@postgresql.o      650                 :CBC          31 :         scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                                651                 :                : 
                                652                 :                :         /*
                                653                 :                :          * Start from last page of the scan.  Ensure we take into account
                                654                 :                :          * rs_numblocks if it's been adjusted by heap_setscanlimits().
                                655                 :                :          */
                                656         [ +  + ]:             31 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                657                 :              3 :             return (scan->rs_startblock + scan->rs_numblocks - 1) % scan->rs_nblocks;
                                658                 :                : 
                                659         [ -  + ]:             28 :         if (scan->rs_startblock > 0)
  437 drowley@postgresql.o      660                 :UBC           0 :             return scan->rs_startblock - 1;
                                661                 :                : 
  437 drowley@postgresql.o      662                 :CBC          28 :         return scan->rs_nblocks - 1;
                                663                 :                :     }
                                664                 :                : }
                                665                 :                : 
                                666                 :                : 
                                667                 :                : /*
                                668                 :                :  * heapgettup_start_page - helper function for heapgettup()
                                669                 :                :  *
                                670                 :                :  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
                                671                 :                :  * to the number of tuples on this page.  Also set *lineoff to the first
                                672                 :                :  * offset to scan with forward scans getting the first offset and backward
                                673                 :                :  * getting the final offset on the page.
                                674                 :                :  */
                                675                 :                : static Page
  436                           676                 :          92202 : heapgettup_start_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
                                677                 :                :                       OffsetNumber *lineoff)
                                678                 :                : {
                                679                 :                :     Page        page;
                                680                 :                : 
                                681         [ -  + ]:          92202 :     Assert(scan->rs_inited);
                                682         [ -  + ]:          92202 :     Assert(BufferIsValid(scan->rs_cbuf));
                                683                 :                : 
                                684                 :                :     /* Caller is responsible for ensuring buffer is locked if needed */
                                685                 :          92202 :     page = BufferGetPage(scan->rs_cbuf);
                                686                 :                : 
  432                           687                 :          92202 :     *linesleft = PageGetMaxOffsetNumber(page) - FirstOffsetNumber + 1;
                                688                 :                : 
  436                           689         [ +  - ]:          92202 :     if (ScanDirectionIsForward(dir))
                                690                 :          92202 :         *lineoff = FirstOffsetNumber;
                                691                 :                :     else
  436 drowley@postgresql.o      692                 :UBC           0 :         *lineoff = (OffsetNumber) (*linesleft);
                                693                 :                : 
                                694                 :                :     /* lineoff now references the physically previous or next tid */
  436 drowley@postgresql.o      695                 :CBC       92202 :     return page;
                                696                 :                : }
                                697                 :                : 
                                698                 :                : 
                                699                 :                : /*
                                700                 :                :  * heapgettup_continue_page - helper function for heapgettup()
                                701                 :                :  *
                                702                 :                :  * Return the next page to scan based on the scan->rs_cbuf and set *linesleft
                                703                 :                :  * to the number of tuples left to scan on this page.  Also set *lineoff to
                                704                 :                :  * the next offset to scan according to the ScanDirection in 'dir'.
                                705                 :                :  */
                                706                 :                : static inline Page
                                707                 :        7744809 : heapgettup_continue_page(HeapScanDesc scan, ScanDirection dir, int *linesleft,
                                708                 :                :                          OffsetNumber *lineoff)
                                709                 :                : {
                                710                 :                :     Page        page;
                                711                 :                : 
                                712         [ -  + ]:        7744809 :     Assert(scan->rs_inited);
                                713         [ -  + ]:        7744809 :     Assert(BufferIsValid(scan->rs_cbuf));
                                714                 :                : 
                                715                 :                :     /* Caller is responsible for ensuring buffer is locked if needed */
                                716                 :        7744809 :     page = BufferGetPage(scan->rs_cbuf);
                                717                 :                : 
                                718         [ +  - ]:        7744809 :     if (ScanDirectionIsForward(dir))
                                719                 :                :     {
                                720                 :        7744809 :         *lineoff = OffsetNumberNext(scan->rs_coffset);
                                721                 :        7744809 :         *linesleft = PageGetMaxOffsetNumber(page) - (*lineoff) + 1;
                                722                 :                :     }
                                723                 :                :     else
                                724                 :                :     {
                                725                 :                :         /*
                                726                 :                :          * The previous returned tuple may have been vacuumed since the
                                727                 :                :          * previous scan when we use a non-MVCC snapshot, so we must
                                728                 :                :          * re-establish the lineoff <= PageGetMaxOffsetNumber(page) invariant
                                729                 :                :          */
  436 drowley@postgresql.o      730         [ #  # ]:UBC           0 :         *lineoff = Min(PageGetMaxOffsetNumber(page), OffsetNumberPrev(scan->rs_coffset));
                                731                 :              0 :         *linesleft = *lineoff;
                                732                 :                :     }
                                733                 :                : 
                                734                 :                :     /* lineoff now references the physically previous or next tid */
  436 drowley@postgresql.o      735                 :CBC     7744809 :     return page;
                                736                 :                : }
                                737                 :                : 
                                738                 :                : /*
                                739                 :                :  * heapgettup_advance_block - helper for heap_fetch_next_buffer()
                                740                 :                :  *
                                741                 :                :  * Given the current block number, the scan direction, and various information
                                742                 :                :  * contained in the scan descriptor, calculate the BlockNumber to scan next
                                743                 :                :  * and return it.  If there are no further blocks to scan, return
                                744                 :                :  * InvalidBlockNumber to indicate this fact to the caller.
                                745                 :                :  *
                                746                 :                :  * This should not be called to determine the initial block number -- only for
                                747                 :                :  * subsequent blocks.
                                748                 :                :  *
                                749                 :                :  * This also adjusts rs_numblocks when a limit has been imposed by
                                750                 :                :  * heap_setscanlimits().
                                751                 :                :  */
                                752                 :                : static inline BlockNumber
                                753                 :        2391835 : heapgettup_advance_block(HeapScanDesc scan, BlockNumber block, ScanDirection dir)
                                754                 :                : {
    6 tmunro@postgresql.or      755         [ -  + ]:GNC     2391835 :     Assert(scan->rs_base.rs_parallel == NULL);
                                756                 :                : 
                                757         [ +  + ]:        2391835 :     if (likely(ScanDirectionIsForward(dir)))
                                758                 :                :     {
                                759                 :        2391777 :         block++;
                                760                 :                : 
                                761                 :                :         /* wrap back to the start of the heap */
                                762         [ +  + ]:        2391777 :         if (block >= scan->rs_nblocks)
                                763                 :         367070 :             block = 0;
                                764                 :                : 
                                765                 :                :         /*
                                766                 :                :          * Report our new scan position for synchronization purposes. We don't
                                767                 :                :          * do that when moving backwards, however. That would just mess up any
                                768                 :                :          * other forward-moving scanners.
                                769                 :                :          *
                                770                 :                :          * Note: we do this before checking for end of scan so that the final
                                771                 :                :          * state of the position hint is back at the start of the rel.  That's
                                772                 :                :          * not strictly necessary, but otherwise when you run the same query
                                773                 :                :          * multiple times the starting position would shift a little bit
                                774                 :                :          * backwards on every invocation, which is confusing. We don't
                                775                 :                :          * guarantee any specific ordering in general, though.
                                776                 :                :          */
                                777         [ +  + ]:        2391777 :         if (scan->rs_base.rs_flags & SO_ALLOW_SYNC)
                                778                 :           8698 :             ss_report_location(scan->rs_base.rs_rd, block);
                                779                 :                : 
                                780                 :                :         /* we're done if we're back at where we started */
                                781         [ +  + ]:        2391777 :         if (block == scan->rs_startblock)
                                782                 :         367029 :             return InvalidBlockNumber;
                                783                 :                : 
                                784                 :                :         /* check if the limit imposed by heap_setscanlimits() is met */
                                785         [ +  + ]:        2024748 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                786                 :                :         {
                                787         [ +  + ]:           1596 :             if (--scan->rs_numblocks == 0)
    6 tmunro@postgresql.or      788                 :CBC        1532 :                 return InvalidBlockNumber;
                                789                 :                :         }
                                790                 :                : 
    6 tmunro@postgresql.or      791                 :GNC     2023216 :         return block;
                                792                 :                :     }
                                793                 :                :     else
                                794                 :                :     {
                                795                 :                :         /* we're done if the last block is the start position */
  436 drowley@postgresql.o      796         [ +  - ]:CBC          58 :         if (block == scan->rs_startblock)
                                797                 :             58 :             return InvalidBlockNumber;
                                798                 :                : 
                                799                 :                :         /* check if the limit imposed by heap_setscanlimits() is met */
  436 drowley@postgresql.o      800         [ #  # ]:UBC           0 :         if (scan->rs_numblocks != InvalidBlockNumber)
                                801                 :                :         {
                                802         [ #  # ]:              0 :             if (--scan->rs_numblocks == 0)
                                803                 :              0 :                 return InvalidBlockNumber;
                                804                 :                :         }
                                805                 :                : 
                                806                 :                :         /* wrap to the end of the heap when the last page was page 0 */
                                807         [ #  # ]:              0 :         if (block == 0)
                                808                 :              0 :             block = scan->rs_nblocks;
                                809                 :                : 
                                810                 :              0 :         block--;
                                811                 :                : 
                                812                 :              0 :         return block;
                                813                 :                :     }
                                814                 :                : }
                                815                 :                : 
                                816                 :                : /* ----------------
                                817                 :                :  *      heapgettup - fetch next heap tuple
                                818                 :                :  *
                                819                 :                :  *      Initialize the scan if not already done; then advance to the next
                                820                 :                :  *      tuple as indicated by "dir"; return the next tuple in scan->rs_ctup,
                                821                 :                :  *      or set scan->rs_ctup.t_data = NULL if no more tuples.
                                822                 :                :  *
                                823                 :                :  * Note: the reason nkeys/key are passed separately, even though they are
                                824                 :                :  * kept in the scan descriptor, is that the caller may not want us to check
                                825                 :                :  * the scankeys.
                                826                 :                :  *
                                827                 :                :  * Note: when we fall off the end of the scan in either direction, we
                                828                 :                :  * reset rs_inited.  This means that a further request with the same
                                829                 :                :  * scan direction will restart the scan, which is a bit odd, but a
                                830                 :                :  * request with the opposite scan direction will start a fresh scan
                                831                 :                :  * in the proper direction.  The latter is required behavior for cursors,
                                832                 :                :  * while the former case is generally undefined behavior in Postgres
                                833                 :                :  * so we don't care too much.
                                834                 :                :  * ----------------
                                835                 :                :  */
                                836                 :                : static void
 6714 tgl@sss.pgh.pa.us         837                 :CBC     7764019 : heapgettup(HeapScanDesc scan,
                                838                 :                :            ScanDirection dir,
                                839                 :                :            int nkeys,
                                840                 :                :            ScanKey key)
                                841                 :                : {
                                842                 :        7764019 :     HeapTuple   tuple = &(scan->rs_ctup);
                                843                 :                :     Page        page;
                                844                 :                :     OffsetNumber lineoff;
                                845                 :                :     int         linesleft;
                                846                 :                : 
   10 drowley@postgresql.o      847         [ +  + ]:GNC     7764019 :     if (likely(scan->rs_inited))
                                848                 :                :     {
                                849                 :                :         /* continue from previously returned page/tuple */
  436 drowley@postgresql.o      850                 :CBC     7744809 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
                                851                 :        7744809 :         page = heapgettup_continue_page(scan, dir, &linesleft, &lineoff);
  432                           852                 :        7744809 :         goto continue_page;
                                853                 :                :     }
                                854                 :                : 
                                855                 :                :     /*
                                856                 :                :      * advance the scan until we find a qualifying tuple or run out of stuff
                                857                 :                :      * to scan
                                858                 :                :      */
                                859                 :                :     while (true)
                                860                 :                :     {
   10 drowley@postgresql.o      861                 :GNC      111263 :         heap_fetch_next_buffer(scan, dir);
                                862                 :                : 
                                863                 :                :         /* did we run out of blocks to scan? */
                                864         [ +  + ]:         111263 :         if (!BufferIsValid(scan->rs_cbuf))
                                865                 :          19061 :             break;
                                866                 :                : 
                                867         [ -  + ]:          92202 :         Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
                                868                 :                : 
  432 drowley@postgresql.o      869                 :CBC       92202 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_SHARE);
                                870                 :          92202 :         page = heapgettup_start_page(scan, dir, &linesleft, &lineoff);
                                871                 :        7837011 : continue_page:
                                872                 :                : 
                                873                 :                :         /*
                                874                 :                :          * Only continue scanning the page while we have lines left.
                                875                 :                :          *
                                876                 :                :          * Note that this protects us from accessing line pointers past
                                877                 :                :          * PageGetMaxOffsetNumber(); both for forward scans when we resume the
                                878                 :                :          * table scan, and for when we start scanning a new page.
                                879                 :                :          */
                                880         [ +  + ]:        7871455 :         for (; linesleft > 0; linesleft--, lineoff += dir)
                                881                 :                :         {
                                882                 :                :             bool        visible;
                                883                 :        7779402 :             ItemId      lpp = PageGetItemId(page, lineoff);
                                884                 :                : 
                                885         [ +  + ]:        7779402 :             if (!ItemIdIsNormal(lpp))
                                886                 :          29261 :                 continue;
                                887                 :                : 
                                888                 :        7750141 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
                                889                 :        7750141 :             tuple->t_len = ItemIdGetLength(lpp);
   10 drowley@postgresql.o      890                 :GNC     7750141 :             ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
                                891                 :                : 
  432 drowley@postgresql.o      892                 :CBC     7750141 :             visible = HeapTupleSatisfiesVisibility(tuple,
                                893                 :                :                                                    scan->rs_base.rs_snapshot,
                                894                 :                :                                                    scan->rs_cbuf);
                                895                 :                : 
                                896                 :        7750141 :             HeapCheckForSerializableConflictOut(visible, scan->rs_base.rs_rd,
                                897                 :                :                                                 tuple, scan->rs_cbuf,
                                898                 :                :                                                 scan->rs_base.rs_snapshot);
                                899                 :                : 
                                900                 :                :             /* skip tuples not visible to this snapshot */
                                901         [ +  + ]:        7750141 :             if (!visible)
                                902                 :           5183 :                 continue;
                                903                 :                : 
                                904                 :                :             /* skip any tuples that don't match the scan key */
                                905         [ -  + ]:        7744958 :             if (key != NULL &&
  432 drowley@postgresql.o      906         [ #  # ]:UBC           0 :                 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
                                907                 :                :                              nkeys, key))
                                908                 :              0 :                 continue;
                                909                 :                : 
  432 drowley@postgresql.o      910                 :CBC     7744958 :             LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                                911                 :        7744958 :             scan->rs_coffset = lineoff;
                                912                 :        7744958 :             return;
                                913                 :                :         }
                                914                 :                : 
                                915                 :                :         /*
                                916                 :                :          * if we get here, it means we've exhausted the items on this page and
                                917                 :                :          * it's time to move to the next.
                                918                 :                :          */
 6714 tgl@sss.pgh.pa.us         919                 :          92053 :         LockBuffer(scan->rs_cbuf, BUFFER_LOCK_UNLOCK);
                                920                 :                :     }
                                921                 :                : 
                                922                 :                :     /* end of scan */
  432 drowley@postgresql.o      923         [ -  + ]:          19061 :     if (BufferIsValid(scan->rs_cbuf))
  432 drowley@postgresql.o      924                 :LBC      (3840) :         ReleaseBuffer(scan->rs_cbuf);
                                925                 :                : 
  432 drowley@postgresql.o      926                 :CBC       19061 :     scan->rs_cbuf = InvalidBuffer;
                                927                 :          19061 :     scan->rs_cblock = InvalidBlockNumber;
    6 tmunro@postgresql.or      928                 :GNC       19061 :     scan->rs_prefetch_block = InvalidBlockNumber;
  432 drowley@postgresql.o      929                 :CBC       19061 :     tuple->t_data = NULL;
                                930                 :          19061 :     scan->rs_inited = false;
                                931                 :                : }
                                932                 :                : 
                                933                 :                : /* ----------------
                                934                 :                :  *      heapgettup_pagemode - fetch next heap tuple in page-at-a-time mode
                                935                 :                :  *
                                936                 :                :  *      Same API as heapgettup, but used in page-at-a-time mode
                                937                 :                :  *
                                938                 :                :  * The internal logic is much the same as heapgettup's too, but there are some
                                939                 :                :  * differences: we do not take the buffer content lock (that only needs to
                                940                 :                :  * happen inside heap_prepare_pagescan), and we iterate through just the
                                941                 :                :  * tuples listed in rs_vistuples[] rather than all tuples on the page.  Notice
                                942                 :                :  * that lineindex is 0-based, where the corresponding loop variable lineoff in
                                943                 :                :  * heapgettup is 1-based.
                                944                 :                :  * ----------------
                                945                 :                :  */
                                946                 :                : static void
 6714 tgl@sss.pgh.pa.us         947                 :       39152766 : heapgettup_pagemode(HeapScanDesc scan,
                                948                 :                :                     ScanDirection dir,
                                949                 :                :                     int nkeys,
                                950                 :                :                     ScanKey key)
                                951                 :                : {
                                952                 :       39152766 :     HeapTuple   tuple = &(scan->rs_ctup);
                                953                 :                :     Page        page;
                                954                 :                :     int         lineindex;
                                955                 :                :     int         linesleft;
                                956                 :                : 
   10 drowley@postgresql.o      957         [ +  + ]:GNC    39152766 :     if (likely(scan->rs_inited))
                                958                 :                :     {
                                959                 :                :         /* continue from previously returned page/tuple */
  436 drowley@postgresql.o      960                 :CBC    38370896 :         page = BufferGetPage(scan->rs_cbuf);
                                961                 :                : 
                                962                 :       38370896 :         lineindex = scan->rs_cindex + dir;
                                963         [ +  + ]:       38370896 :         if (ScanDirectionIsForward(dir))
                                964                 :       38370568 :             linesleft = scan->rs_ntuples - lineindex;
                                965                 :                :         else
                                966                 :            328 :             linesleft = scan->rs_cindex;
                                967                 :                :         /* lineindex now references the next or previous visible tid */
                                968                 :                : 
  432                           969                 :       38370896 :         goto continue_page;
                                970                 :                :     }
                                971                 :                : 
                                972                 :                :     /*
                                973                 :                :      * advance the scan until we find a qualifying tuple or run out of stuff
                                974                 :                :      * to scan
                                975                 :                :      */
                                976                 :                :     while (true)
                                977                 :                :     {
   10 drowley@postgresql.o      978                 :GNC     2610902 :         heap_fetch_next_buffer(scan, dir);
                                979                 :                : 
                                980                 :                :         /* did we run out of blocks to scan? */
                                981         [ +  + ]:        2610898 :         if (!BufferIsValid(scan->rs_cbuf))
                                982                 :         648770 :             break;
                                983                 :                : 
                                984         [ -  + ]:        1962128 :         Assert(BufferGetBlockNumber(scan->rs_cbuf) == scan->rs_cblock);
                                985                 :                : 
                                986                 :                :         /* prune the page and determine visible tuple offsets */
                                987                 :        1962128 :         heap_prepare_pagescan((TableScanDesc) scan);
  432 drowley@postgresql.o      988                 :CBC     1962120 :         page = BufferGetPage(scan->rs_cbuf);
                                989                 :        1962120 :         linesleft = scan->rs_ntuples;
                                990         [ +  + ]:        1962120 :         lineindex = ScanDirectionIsForward(dir) ? 0 : linesleft - 1;
                                991                 :                : 
                                992                 :                :         /* lineindex now references the next or previous visible tid */
                                993                 :       40333016 : continue_page:
                                994                 :                : 
                                995         [ +  + ]:       79325552 :         for (; linesleft > 0; linesleft--, lineindex += dir)
                                996                 :                :         {
                                997                 :                :             ItemId      lpp;
                                998                 :                :             OffsetNumber lineoff;
                                999                 :                : 
 6714 tgl@sss.pgh.pa.us        1000                 :       77496520 :             lineoff = scan->rs_vistuples[lineindex];
  515 peter@eisentraut.org     1001                 :       77496520 :             lpp = PageGetItemId(page, lineoff);
 6059 tgl@sss.pgh.pa.us        1002         [ -  + ]:       77496520 :             Assert(ItemIdIsNormal(lpp));
                               1003                 :                : 
  515 peter@eisentraut.org     1004                 :       77496520 :             tuple->t_data = (HeapTupleHeader) PageGetItem(page, lpp);
 6714 tgl@sss.pgh.pa.us        1005                 :       77496520 :             tuple->t_len = ItemIdGetLength(lpp);
   10 drowley@postgresql.o     1006                 :GNC    77496520 :             ItemPointerSet(&(tuple->t_self), scan->rs_cblock, lineoff);
                               1007                 :                : 
                               1008                 :                :             /* skip any tuples that don't match the scan key */
  432 drowley@postgresql.o     1009         [ +  + ]:CBC    77496520 :             if (key != NULL &&
                               1010         [ +  + ]:       39293587 :                 !HeapKeyTest(tuple, RelationGetDescr(scan->rs_base.rs_rd),
                               1011                 :                :                              nkeys, key))
                               1012                 :       38992536 :                 continue;
                               1013                 :                : 
                               1014                 :       38503984 :             scan->rs_cindex = lineindex;
                               1015                 :       38503984 :             return;
                               1016                 :                :         }
                               1017                 :                :     }
                               1018                 :                : 
                               1019                 :                :     /* end of scan */
                               1020         [ -  + ]:         648770 :     if (BufferIsValid(scan->rs_cbuf))
  432 drowley@postgresql.o     1021                 :LBC    (445653) :         ReleaseBuffer(scan->rs_cbuf);
  432 drowley@postgresql.o     1022                 :CBC      648770 :     scan->rs_cbuf = InvalidBuffer;
                               1023                 :         648770 :     scan->rs_cblock = InvalidBlockNumber;
    6 tmunro@postgresql.or     1024                 :GNC      648770 :     scan->rs_prefetch_block = InvalidBlockNumber;
  432 drowley@postgresql.o     1025                 :CBC      648770 :     tuple->t_data = NULL;
                               1026                 :         648770 :     scan->rs_inited = false;
                               1027                 :                : }
                               1028                 :                : 
                               1029                 :                : 
                               1030                 :                : /* ----------------------------------------------------------------
                               1031                 :                :  *                   heap access method interface
                               1032                 :                :  * ----------------------------------------------------------------
                               1033                 :                :  */
                               1034                 :                : 
                               1035                 :                : 
                               1036                 :                : TableScanDesc
 8000 tgl@sss.pgh.pa.us        1037                 :         318697 : heap_beginscan(Relation relation, Snapshot snapshot,
                               1038                 :                :                int nkeys, ScanKey key,
                               1039                 :                :                ParallelTableScanDesc parallel_scan,
                               1040                 :                :                uint32 flags)
                               1041                 :                : {
                               1042                 :                :     HeapScanDesc scan;
                               1043                 :                : 
                               1044                 :                :     /*
                               1045                 :                :      * increment relation ref count while scanning relation
                               1046                 :                :      *
                               1047                 :                :      * This is just to make really sure the relcache entry won't go away while
                               1048                 :                :      * the scan has a pointer to it.  Caller should be holding the rel open
                               1049                 :                :      * anyway, so this is redundant in all normal scenarios...
                               1050                 :                :      */
 8558                          1051                 :         318697 :     RelationIncrementReferenceCount(relation);
                               1052                 :                : 
                               1053                 :                :     /*
                               1054                 :                :      * allocate and initialize scan descriptor
                               1055                 :                :      */
 9370 bruce@momjian.us         1056                 :         318697 :     scan = (HeapScanDesc) palloc(sizeof(HeapScanDescData));
                               1057                 :                : 
 1861 andres@anarazel.de       1058                 :         318697 :     scan->rs_base.rs_rd = relation;
                               1059                 :         318697 :     scan->rs_base.rs_snapshot = snapshot;
                               1060                 :         318697 :     scan->rs_base.rs_nkeys = nkeys;
 1792                          1061                 :         318697 :     scan->rs_base.rs_flags = flags;
 1861                          1062                 :         318697 :     scan->rs_base.rs_parallel = parallel_scan;
 1792                          1063                 :         318697 :     scan->rs_strategy = NULL;    /* set in initscan */
    7 tomas.vondra@postgre     1064                 :GNC      318697 :     scan->rs_vmbuffer = InvalidBuffer;
                               1065                 :         318697 :     scan->rs_empty_tuples_pending = 0;
                               1066                 :                : 
                               1067                 :                :     /*
                               1068                 :                :      * Disable page-at-a-time mode if it's not a MVCC-safe snapshot.
                               1069                 :                :      */
 1792 andres@anarazel.de       1070   [ +  +  +  +  :CBC      318697 :     if (!(snapshot && IsMVCCSnapshot(snapshot)))
                                              +  + ]
                               1071                 :          26031 :         scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
                               1072                 :                : 
                               1073                 :                :     /*
                               1074                 :                :      * For seqscan and sample scans in a serializable transaction, acquire a
                               1075                 :                :      * predicate lock on the entire relation. This is required not only to
                               1076                 :                :      * lock all the matching tuples, but also to conflict with new insertions
                               1077                 :                :      * into the table. In an indexscan, we take page locks on the index pages
                               1078                 :                :      * covering the range specified in the scan qual, but in a heap scan there
                               1079                 :                :      * is nothing more fine-grained to lock. A bitmap scan is a different
                               1080                 :                :      * story, there we have already scanned the index and locked the index
                               1081                 :                :      * pages covering the predicate. But in that case we still have to lock
                               1082                 :                :      * any matching heap tuples. For sample scan we could optimize the locking
                               1083                 :                :      * to be at least page-level granularity, but we'd need to add per-tuple
                               1084                 :                :      * locking for that.
                               1085                 :                :      */
                               1086         [ +  + ]:         318697 :     if (scan->rs_base.rs_flags & (SO_TYPE_SEQSCAN | SO_TYPE_SAMPLESCAN))
                               1087                 :                :     {
                               1088                 :                :         /*
                               1089                 :                :          * Ensure a missing snapshot is noticed reliably, even if the
                               1090                 :                :          * isolation mode means predicate locking isn't performed (and
                               1091                 :                :          * therefore the snapshot isn't used here).
                               1092                 :                :          */
                               1093         [ -  + ]:         304168 :         Assert(snapshot);
 4673 heikki.linnakangas@i     1094                 :         304168 :         PredicateLockRelation(relation, snapshot);
                               1095                 :                :     }
                               1096                 :                : 
                               1097                 :                :     /* we only need to set this up once */
 6714 tgl@sss.pgh.pa.us        1098                 :         318697 :     scan->rs_ctup.t_tableOid = RelationGetRelid(relation);
                               1099                 :                : 
                               1100                 :                :     /*
                               1101                 :                :      * Allocate memory to keep track of page allocation for parallel workers
                               1102                 :                :      * when doing a parallel scan.
                               1103                 :                :      */
 1111 drowley@postgresql.o     1104         [ +  + ]:         318697 :     if (parallel_scan != NULL)
                               1105                 :           1929 :         scan->rs_parallelworkerdata = palloc(sizeof(ParallelBlockTableScanWorkerData));
                               1106                 :                :     else
                               1107                 :         316768 :         scan->rs_parallelworkerdata = NULL;
                               1108                 :                : 
                               1109                 :                :     /*
                               1110                 :                :      * we do this here instead of in initscan() because heap_rescan also calls
                               1111                 :                :      * initscan() and we don't want to allocate memory again
                               1112                 :                :      */
 8000 tgl@sss.pgh.pa.us        1113         [ +  + ]:         318697 :     if (nkeys > 0)
 1861 andres@anarazel.de       1114                 :         181972 :         scan->rs_base.rs_key = (ScanKey) palloc(sizeof(ScanKeyData) * nkeys);
                               1115                 :                :     else
                               1116                 :         136725 :         scan->rs_base.rs_key = NULL;
                               1117                 :                : 
 5422 tgl@sss.pgh.pa.us        1118                 :         318697 :     initscan(scan, key, false);
                               1119                 :                : 
    6 tmunro@postgresql.or     1120                 :GNC      318695 :     scan->rs_read_stream = NULL;
                               1121                 :                : 
                               1122                 :                :     /*
                               1123                 :                :      * Set up a read stream for sequential scans and TID range scans. This
                               1124                 :                :      * should be done after initscan() because initscan() allocates the
                               1125                 :                :      * BufferAccessStrategy object passed to the streaming read API.
                               1126                 :                :      */
                               1127         [ +  + ]:         318695 :     if (scan->rs_base.rs_flags & SO_TYPE_SEQSCAN ||
                               1128         [ +  + ]:          14602 :         scan->rs_base.rs_flags & SO_TYPE_TIDRANGESCAN)
                               1129                 :                :     {
                               1130                 :                :         ReadStreamBlockNumberCB cb;
                               1131                 :                : 
                               1132         [ +  + ]:         304149 :         if (scan->rs_base.rs_parallel)
                               1133                 :           1929 :             cb = heap_scan_stream_read_next_parallel;
                               1134                 :                :         else
                               1135                 :         302220 :             cb = heap_scan_stream_read_next_serial;
                               1136                 :                : 
                               1137                 :         304149 :         scan->rs_read_stream = read_stream_begin_relation(READ_STREAM_SEQUENTIAL,
                               1138                 :                :                                                           scan->rs_strategy,
                               1139                 :                :                                                           scan->rs_base.rs_rd,
                               1140                 :                :                                                           MAIN_FORKNUM,
                               1141                 :                :                                                           cb,
                               1142                 :                :                                                           scan,
                               1143                 :                :                                                           0);
                               1144                 :                :     }
                               1145                 :                : 
                               1146                 :                : 
 1861 andres@anarazel.de       1147                 :CBC      318695 :     return (TableScanDesc) scan;
                               1148                 :                : }
                               1149                 :                : 
                               1150                 :                : void
                               1151                 :         499496 : heap_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
                               1152                 :                :             bool allow_strat, bool allow_sync, bool allow_pagemode)
                               1153                 :                : {
                               1154                 :         499496 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1155                 :                : 
                               1156         [ +  + ]:         499496 :     if (set_params)
                               1157                 :                :     {
 1792                          1158         [ +  - ]:             15 :         if (allow_strat)
                               1159                 :             15 :             scan->rs_base.rs_flags |= SO_ALLOW_STRAT;
                               1160                 :                :         else
 1792 andres@anarazel.de       1161                 :UBC           0 :             scan->rs_base.rs_flags &= ~SO_ALLOW_STRAT;
                               1162                 :                : 
 1792 andres@anarazel.de       1163         [ +  + ]:CBC          15 :         if (allow_sync)
                               1164                 :              6 :             scan->rs_base.rs_flags |= SO_ALLOW_SYNC;
                               1165                 :                :         else
                               1166                 :              9 :             scan->rs_base.rs_flags &= ~SO_ALLOW_SYNC;
                               1167                 :                : 
                               1168   [ +  -  +  - ]:             15 :         if (allow_pagemode && scan->rs_base.rs_snapshot &&
                               1169   [ -  +  -  - ]:             15 :             IsMVCCSnapshot(scan->rs_base.rs_snapshot))
                               1170                 :             15 :             scan->rs_base.rs_flags |= SO_ALLOW_PAGEMODE;
                               1171                 :                :         else
 1792 andres@anarazel.de       1172                 :UBC           0 :             scan->rs_base.rs_flags &= ~SO_ALLOW_PAGEMODE;
                               1173                 :                :     }
                               1174                 :                : 
                               1175                 :                :     /*
                               1176                 :                :      * unpin scan buffers
                               1177                 :                :      */
 8345 tgl@sss.pgh.pa.us        1178         [ +  + ]:CBC      499496 :     if (BufferIsValid(scan->rs_cbuf))
                               1179                 :           2729 :         ReleaseBuffer(scan->rs_cbuf);
                               1180                 :                : 
    7 tomas.vondra@postgre     1181         [ +  + ]:GNC      499496 :     if (BufferIsValid(scan->rs_vmbuffer))
                               1182                 :                :     {
                               1183                 :             27 :         ReleaseBuffer(scan->rs_vmbuffer);
                               1184                 :             27 :         scan->rs_vmbuffer = InvalidBuffer;
                               1185                 :                :     }
                               1186                 :                : 
                               1187         [ -  + ]:         499496 :     Assert(scan->rs_empty_tuples_pending == 0);
                               1188                 :                : 
                               1189                 :                :     /*
                               1190                 :                :      * The read stream is reset on rescan. This must be done before
                               1191                 :                :      * initscan(), as some state referred to by read_stream_reset() is reset
                               1192                 :                :      * in initscan().
                               1193                 :                :      */
    6 tmunro@postgresql.or     1194         [ +  + ]:         499496 :     if (scan->rs_read_stream)
                               1195                 :         497488 :         read_stream_reset(scan->rs_read_stream);
                               1196                 :                : 
                               1197                 :                :     /*
                               1198                 :                :      * reinitialize scan descriptor
                               1199                 :                :      */
 5422 tgl@sss.pgh.pa.us        1200                 :CBC      499496 :     initscan(scan, key, true);
10141 scrappy@hub.org          1201                 :         499496 : }
                               1202                 :                : 
                               1203                 :                : void
 1861 andres@anarazel.de       1204                 :         317441 : heap_endscan(TableScanDesc sscan)
                               1205                 :                : {
                               1206                 :         317441 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1207                 :                : 
                               1208                 :                :     /* Note: no locking manipulations needed */
                               1209                 :                : 
                               1210                 :                :     /*
                               1211                 :                :      * unpin scan buffers
                               1212                 :                :      */
 8345 tgl@sss.pgh.pa.us        1213         [ +  + ]:         317441 :     if (BufferIsValid(scan->rs_cbuf))
                               1214                 :         136934 :         ReleaseBuffer(scan->rs_cbuf);
                               1215                 :                : 
    7 tomas.vondra@postgre     1216         [ +  + ]:GNC      317441 :     if (BufferIsValid(scan->rs_vmbuffer))
                               1217                 :            133 :         ReleaseBuffer(scan->rs_vmbuffer);
                               1218                 :                : 
                               1219         [ -  + ]:         317441 :     Assert(scan->rs_empty_tuples_pending == 0);
                               1220                 :                : 
                               1221                 :                :     /*
                               1222                 :                :      * Must free the read stream before freeing the BufferAccessStrategy.
                               1223                 :                :      */
    6 tmunro@postgresql.or     1224         [ +  + ]:         317441 :     if (scan->rs_read_stream)
                               1225                 :         302984 :         read_stream_end(scan->rs_read_stream);
                               1226                 :                : 
                               1227                 :                :     /*
                               1228                 :                :      * decrement relation reference count and free scan descriptor storage
                               1229                 :                :      */
 1861 andres@anarazel.de       1230                 :CBC      317441 :     RelationDecrementReferenceCount(scan->rs_base.rs_rd);
                               1231                 :                : 
                               1232         [ +  + ]:         317441 :     if (scan->rs_base.rs_key)
                               1233                 :         181941 :         pfree(scan->rs_base.rs_key);
                               1234                 :                : 
 6164 tgl@sss.pgh.pa.us        1235         [ +  + ]:         317441 :     if (scan->rs_strategy != NULL)
                               1236                 :           9501 :         FreeAccessStrategy(scan->rs_strategy);
                               1237                 :                : 
 1111 drowley@postgresql.o     1238         [ +  + ]:         317441 :     if (scan->rs_parallelworkerdata != NULL)
                               1239                 :           1929 :         pfree(scan->rs_parallelworkerdata);
                               1240                 :                : 
 1792 andres@anarazel.de       1241         [ +  + ]:         317441 :     if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
 1861                          1242                 :          44927 :         UnregisterSnapshot(scan->rs_base.rs_snapshot);
                               1243                 :                : 
 8975 tgl@sss.pgh.pa.us        1244                 :         317441 :     pfree(scan);
10141 scrappy@hub.org          1245                 :         317441 : }
                               1246                 :                : 
                               1247                 :                : HeapTuple
 1861 andres@anarazel.de       1248                 :        8815957 : heap_getnext(TableScanDesc sscan, ScanDirection direction)
                               1249                 :                : {
                               1250                 :        8815957 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1251                 :                : 
                               1252                 :                :     /*
                               1253                 :                :      * This is still widely used directly, without going through table AM, so
                               1254                 :                :      * add a safety check.  It's possible we should, at a later point,
                               1255                 :                :      * downgrade this to an assert. The reason for checking the AM routine,
                               1256                 :                :      * rather than the AM oid, is that this allows to write regression tests
                               1257                 :                :      * that create another AM reusing the heap handler.
                               1258                 :                :      */
                               1259         [ -  + ]:        8815957 :     if (unlikely(sscan->rs_rd->rd_tableam != GetHeapamTableAmRoutine()))
 1861 andres@anarazel.de       1260         [ #  # ]:UBC           0 :         ereport(ERROR,
                               1261                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                               1262                 :                :                  errmsg_internal("only heap AM is supported")));
                               1263                 :                : 
                               1264                 :                :     /*
                               1265                 :                :      * We don't expect direct calls to heap_getnext with valid CheckXidAlive
                               1266                 :                :      * for catalog or regular tables.  See detailed comments in xact.c where
                               1267                 :                :      * these variables are declared.  Normally we have such a check at tableam
                               1268                 :                :      * level API but this is called from many places so we need to ensure it
                               1269                 :                :      * here.
                               1270                 :                :      */
 1345 akapila@postgresql.o     1271   [ -  +  -  -  :CBC     8815957 :     if (unlikely(TransactionIdIsValid(CheckXidAlive) && !bsysscan))
                                              -  + ]
 1345 akapila@postgresql.o     1272         [ #  # ]:UBC           0 :         elog(ERROR, "unexpected heap_getnext call during logical decoding");
                               1273                 :                : 
                               1274                 :                :     /* Note: no locking manipulations needed */
                               1275                 :                : 
 1792 andres@anarazel.de       1276         [ +  + ]:CBC     8815957 :     if (scan->rs_base.rs_flags & SO_ALLOW_PAGEMODE)
 6627 neilc@samurai.com        1277                 :        1547545 :         heapgettup_pagemode(scan, direction,
 1861 andres@anarazel.de       1278                 :        1547545 :                             scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
                               1279                 :                :     else
                               1280                 :        7268412 :         heapgettup(scan, direction,
                               1281                 :        7268412 :                    scan->rs_base.rs_nkeys, scan->rs_base.rs_key);
                               1282                 :                : 
 6714 tgl@sss.pgh.pa.us        1283         [ +  + ]:        8815957 :     if (scan->rs_ctup.t_data == NULL)
 8000                          1284                 :          55682 :         return NULL;
                               1285                 :                : 
                               1286                 :                :     /*
                               1287                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1288                 :                :      * the proper return buffer and return the tuple.
                               1289                 :                :      */
                               1290                 :                : 
 1861 andres@anarazel.de       1291   [ -  +  -  -  :        8760275 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  - ]
                               1292                 :                : 
                               1293                 :        8760275 :     return &scan->rs_ctup;
                               1294                 :                : }
                               1295                 :                : 
                               1296                 :                : bool
                               1297                 :       38097765 : heap_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
                               1298                 :                : {
                               1299                 :       38097765 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1300                 :                : 
                               1301                 :                :     /* Note: no locking manipulations needed */
                               1302                 :                : 
 1792                          1303         [ +  + ]:       38097765 :     if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
                               1304                 :       37602158 :         heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1305                 :                :     else
                               1306                 :         495607 :         heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1307                 :                : 
 1861                          1308         [ +  + ]:       38097753 :     if (scan->rs_ctup.t_data == NULL)
                               1309                 :                :     {
                               1310                 :         612102 :         ExecClearTuple(slot);
                               1311                 :         612102 :         return false;
                               1312                 :                :     }
                               1313                 :                : 
                               1314                 :                :     /*
                               1315                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1316                 :                :      * the proper return buffer and return the tuple.
                               1317                 :                :      */
                               1318                 :                : 
                               1319   [ +  +  -  +  :       37485651 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  + ]
                               1320                 :                : 
                               1321                 :       37485651 :     ExecStoreBufferHeapTuple(&scan->rs_ctup, slot,
                               1322                 :                :                              scan->rs_cbuf);
                               1323                 :       37485651 :     return true;
                               1324                 :                : }
                               1325                 :                : 
                               1326                 :                : void
 1142 drowley@postgresql.o     1327                 :             89 : heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
                               1328                 :                :                   ItemPointer maxtid)
                               1329                 :                : {
                               1330                 :             89 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1331                 :                :     BlockNumber startBlk;
                               1332                 :                :     BlockNumber numBlks;
                               1333                 :                :     ItemPointerData highestItem;
                               1334                 :                :     ItemPointerData lowestItem;
                               1335                 :                : 
                               1336                 :                :     /*
                               1337                 :                :      * For relations without any pages, we can simply leave the TID range
                               1338                 :                :      * unset.  There will be no tuples to scan, therefore no tuples outside
                               1339                 :                :      * the given TID range.
                               1340                 :                :      */
                               1341         [ +  + ]:             89 :     if (scan->rs_nblocks == 0)
                               1342                 :             24 :         return;
                               1343                 :                : 
                               1344                 :                :     /*
                               1345                 :                :      * Set up some ItemPointers which point to the first and last possible
                               1346                 :                :      * tuples in the heap.
                               1347                 :                :      */
                               1348                 :             83 :     ItemPointerSet(&highestItem, scan->rs_nblocks - 1, MaxOffsetNumber);
                               1349                 :             83 :     ItemPointerSet(&lowestItem, 0, FirstOffsetNumber);
                               1350                 :                : 
                               1351                 :                :     /*
                               1352                 :                :      * If the given maximum TID is below the highest possible TID in the
                               1353                 :                :      * relation, then restrict the range to that, otherwise we scan to the end
                               1354                 :                :      * of the relation.
                               1355                 :                :      */
                               1356         [ +  + ]:             83 :     if (ItemPointerCompare(maxtid, &highestItem) < 0)
                               1357                 :             66 :         ItemPointerCopy(maxtid, &highestItem);
                               1358                 :                : 
                               1359                 :                :     /*
                               1360                 :                :      * If the given minimum TID is above the lowest possible TID in the
                               1361                 :                :      * relation, then restrict the range to only scan for TIDs above that.
                               1362                 :                :      */
                               1363         [ +  + ]:             83 :     if (ItemPointerCompare(mintid, &lowestItem) > 0)
                               1364                 :             26 :         ItemPointerCopy(mintid, &lowestItem);
                               1365                 :                : 
                               1366                 :                :     /*
                               1367                 :                :      * Check for an empty range and protect from would be negative results
                               1368                 :                :      * from the numBlks calculation below.
                               1369                 :                :      */
                               1370         [ +  + ]:             83 :     if (ItemPointerCompare(&highestItem, &lowestItem) < 0)
                               1371                 :                :     {
                               1372                 :                :         /* Set an empty range of blocks to scan */
                               1373                 :             18 :         heap_setscanlimits(sscan, 0, 0);
                               1374                 :             18 :         return;
                               1375                 :                :     }
                               1376                 :                : 
                               1377                 :                :     /*
                               1378                 :                :      * Calculate the first block and the number of blocks we must scan. We
                               1379                 :                :      * could be more aggressive here and perform some more validation to try
                               1380                 :                :      * and further narrow the scope of blocks to scan by checking if the
                               1381                 :                :      * lowestItem has an offset above MaxOffsetNumber.  In this case, we could
                               1382                 :                :      * advance startBlk by one.  Likewise, if highestItem has an offset of 0
                               1383                 :                :      * we could scan one fewer blocks.  However, such an optimization does not
                               1384                 :                :      * seem worth troubling over, currently.
                               1385                 :                :      */
                               1386                 :             65 :     startBlk = ItemPointerGetBlockNumberNoCheck(&lowestItem);
                               1387                 :                : 
                               1388                 :             65 :     numBlks = ItemPointerGetBlockNumberNoCheck(&highestItem) -
                               1389                 :             65 :         ItemPointerGetBlockNumberNoCheck(&lowestItem) + 1;
                               1390                 :                : 
                               1391                 :                :     /* Set the start block and number of blocks to scan */
                               1392                 :             65 :     heap_setscanlimits(sscan, startBlk, numBlks);
                               1393                 :                : 
                               1394                 :                :     /* Finally, set the TID range in sscan */
                               1395                 :             65 :     ItemPointerCopy(&lowestItem, &sscan->rs_mintid);
                               1396                 :             65 :     ItemPointerCopy(&highestItem, &sscan->rs_maxtid);
                               1397                 :                : }
                               1398                 :                : 
                               1399                 :                : bool
                               1400                 :           2970 : heap_getnextslot_tidrange(TableScanDesc sscan, ScanDirection direction,
                               1401                 :                :                           TupleTableSlot *slot)
                               1402                 :                : {
                               1403                 :           2970 :     HeapScanDesc scan = (HeapScanDesc) sscan;
                               1404                 :           2970 :     ItemPointer mintid = &sscan->rs_mintid;
                               1405                 :           2970 :     ItemPointer maxtid = &sscan->rs_maxtid;
                               1406                 :                : 
                               1407                 :                :     /* Note: no locking manipulations needed */
                               1408                 :                :     for (;;)
                               1409                 :                :     {
                               1410         [ +  - ]:           3063 :         if (sscan->rs_flags & SO_ALLOW_PAGEMODE)
                               1411                 :           3063 :             heapgettup_pagemode(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1412                 :                :         else
 1142 drowley@postgresql.o     1413                 :UBC           0 :             heapgettup(scan, direction, sscan->rs_nkeys, sscan->rs_key);
                               1414                 :                : 
 1142 drowley@postgresql.o     1415         [ +  + ]:CBC        3063 :         if (scan->rs_ctup.t_data == NULL)
                               1416                 :                :         {
                               1417                 :             47 :             ExecClearTuple(slot);
                               1418                 :             47 :             return false;
                               1419                 :                :         }
                               1420                 :                : 
                               1421                 :                :         /*
                               1422                 :                :          * heap_set_tidrange will have used heap_setscanlimits to limit the
                               1423                 :                :          * range of pages we scan to only ones that can contain the TID range
                               1424                 :                :          * we're scanning for.  Here we must filter out any tuples from these
                               1425                 :                :          * pages that are outside of that range.
                               1426                 :                :          */
                               1427         [ +  + ]:           3016 :         if (ItemPointerCompare(&scan->rs_ctup.t_self, mintid) < 0)
                               1428                 :                :         {
                               1429                 :             93 :             ExecClearTuple(slot);
                               1430                 :                : 
                               1431                 :                :             /*
                               1432                 :                :              * When scanning backwards, the TIDs will be in descending order.
                               1433                 :                :              * Future tuples in this direction will be lower still, so we can
                               1434                 :                :              * just return false to indicate there will be no more tuples.
                               1435                 :                :              */
                               1436         [ -  + ]:             93 :             if (ScanDirectionIsBackward(direction))
 1142 drowley@postgresql.o     1437                 :UBC           0 :                 return false;
                               1438                 :                : 
 1142 drowley@postgresql.o     1439                 :CBC          93 :             continue;
                               1440                 :                :         }
                               1441                 :                : 
                               1442                 :                :         /*
                               1443                 :                :          * Likewise for the final page, we must filter out TIDs greater than
                               1444                 :                :          * maxtid.
                               1445                 :                :          */
                               1446         [ +  + ]:           2923 :         if (ItemPointerCompare(&scan->rs_ctup.t_self, maxtid) > 0)
                               1447                 :                :         {
                               1448                 :             36 :             ExecClearTuple(slot);
                               1449                 :                : 
                               1450                 :                :             /*
                               1451                 :                :              * When scanning forward, the TIDs will be in ascending order.
                               1452                 :                :              * Future tuples in this direction will be higher still, so we can
                               1453                 :                :              * just return false to indicate there will be no more tuples.
                               1454                 :                :              */
                               1455         [ +  - ]:             36 :             if (ScanDirectionIsForward(direction))
                               1456                 :             36 :                 return false;
 1142 drowley@postgresql.o     1457                 :UBC           0 :             continue;
                               1458                 :                :         }
                               1459                 :                : 
 1142 drowley@postgresql.o     1460                 :CBC        2887 :         break;
                               1461                 :                :     }
                               1462                 :                : 
                               1463                 :                :     /*
                               1464                 :                :      * if we get here it means we have a new current scan tuple, so point to
                               1465                 :                :      * the proper return buffer and return the tuple.
                               1466                 :                :      */
                               1467   [ -  +  -  -  :           2887 :     pgstat_count_heap_getnext(scan->rs_base.rs_rd);
                                              +  - ]
                               1468                 :                : 
                               1469                 :           2887 :     ExecStoreBufferHeapTuple(&scan->rs_ctup, slot, scan->rs_cbuf);
                               1470                 :           2887 :     return true;
                               1471                 :                : }
                               1472                 :                : 
                               1473                 :                : /*
                               1474                 :                :  *  heap_fetch      - retrieve tuple with given tid
                               1475                 :                :  *
                               1476                 :                :  * On entry, tuple->t_self is the TID to fetch.  We pin the buffer holding
                               1477                 :                :  * the tuple, fill in the remaining fields of *tuple, and check the tuple
                               1478                 :                :  * against the specified snapshot.
                               1479                 :                :  *
                               1480                 :                :  * If successful (tuple found and passes snapshot time qual), then *userbuf
                               1481                 :                :  * is set to the buffer holding the tuple and true is returned.  The caller
                               1482                 :                :  * must unpin the buffer when done with the tuple.
                               1483                 :                :  *
                               1484                 :                :  * If the tuple is not found (ie, item number references a deleted slot),
                               1485                 :                :  * then tuple->t_data is set to NULL, *userbuf is set to InvalidBuffer,
                               1486                 :                :  * and false is returned.
                               1487                 :                :  *
                               1488                 :                :  * If the tuple is found but fails the time qual check, then the behavior
                               1489                 :                :  * depends on the keep_buf parameter.  If keep_buf is false, the results
                               1490                 :                :  * are the same as for the tuple-not-found case.  If keep_buf is true,
                               1491                 :                :  * then tuple->t_data and *userbuf are returned as for the success case,
                               1492                 :                :  * and again the caller must unpin the buffer; but false is returned.
                               1493                 :                :  *
                               1494                 :                :  * heap_fetch does not follow HOT chains: only the exact TID requested will
                               1495                 :                :  * be fetched.
                               1496                 :                :  *
                               1497                 :                :  * It is somewhat inconsistent that we ereport() on invalid block number but
                               1498                 :                :  * return false on invalid item number.  There are a couple of reasons though.
                               1499                 :                :  * One is that the caller can relatively easily check the block number for
                               1500                 :                :  * validity, but cannot check the item number without reading the page
                               1501                 :                :  * himself.  Another is that when we are following a t_ctid link, we can be
                               1502                 :                :  * reasonably confident that the page number is valid (since VACUUM shouldn't
                               1503                 :                :  * truncate off the destination page without having killed the referencing
                               1504                 :                :  * tuple first), but the item number might well not be good.
                               1505                 :                :  */
                               1506                 :                : bool
10141 scrappy@hub.org          1507                 :         312668 : heap_fetch(Relation relation,
                               1508                 :                :            Snapshot snapshot,
                               1509                 :                :            HeapTuple tuple,
                               1510                 :                :            Buffer *userbuf,
                               1511                 :                :            bool keep_buf)
                               1512                 :                : {
 7996 tgl@sss.pgh.pa.us        1513                 :         312668 :     ItemPointer tid = &(tuple->t_self);
                               1514                 :                :     ItemId      lp;
                               1515                 :                :     Buffer      buffer;
                               1516                 :                :     Page        page;
                               1517                 :                :     OffsetNumber offnum;
                               1518                 :                :     bool        valid;
                               1519                 :                : 
                               1520                 :                :     /*
                               1521                 :                :      * Fetch and pin the appropriate page of the relation.
                               1522                 :                :      */
 5855                          1523                 :         312668 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
                               1524                 :                : 
                               1525                 :                :     /*
                               1526                 :                :      * Need share lock on buffer to examine tuple commit status.
                               1527                 :                :      */
 9252 vadim4o@yahoo.com        1528                 :         312668 :     LockBuffer(buffer, BUFFER_LOCK_SHARE);
 2916 kgrittn@postgresql.o     1529                 :         312668 :     page = BufferGetPage(buffer);
                               1530                 :                : 
                               1531                 :                :     /*
                               1532                 :                :      * We'd better check for out-of-range offnum in case of VACUUM since the
                               1533                 :                :      * TID was obtained.
                               1534                 :                :      */
 9716 bruce@momjian.us         1535                 :         312668 :     offnum = ItemPointerGetOffsetNumber(tid);
 5754 tgl@sss.pgh.pa.us        1536   [ +  -  -  + ]:         312668 :     if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
                               1537                 :                :     {
 6958 tgl@sss.pgh.pa.us        1538                 :UBC           0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
 1849 andres@anarazel.de       1539                 :              0 :         ReleaseBuffer(buffer);
                               1540                 :              0 :         *userbuf = InvalidBuffer;
 6958 tgl@sss.pgh.pa.us        1541                 :              0 :         tuple->t_data = NULL;
                               1542                 :              0 :         return false;
                               1543                 :                :     }
                               1544                 :                : 
                               1545                 :                :     /*
                               1546                 :                :      * get the item line pointer corresponding to the requested tid
                               1547                 :                :      */
 5754 tgl@sss.pgh.pa.us        1548                 :CBC      312668 :     lp = PageGetItemId(page, offnum);
                               1549                 :                : 
                               1550                 :                :     /*
                               1551                 :                :      * Must check for deleted tuple.
                               1552                 :                :      */
 6059                          1553         [ +  + ]:         312668 :     if (!ItemIdIsNormal(lp))
                               1554                 :                :     {
 8685 vadim4o@yahoo.com        1555                 :           1857 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
 1849 andres@anarazel.de       1556                 :           1857 :         ReleaseBuffer(buffer);
                               1557                 :           1857 :         *userbuf = InvalidBuffer;
 7996 tgl@sss.pgh.pa.us        1558                 :           1857 :         tuple->t_data = NULL;
                               1559                 :           1857 :         return false;
                               1560                 :                :     }
                               1561                 :                : 
                               1562                 :                :     /*
                               1563                 :                :      * fill in *tuple fields
                               1564                 :                :      */
 5754                          1565                 :         310811 :     tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
 9270 vadim4o@yahoo.com        1566                 :         310811 :     tuple->t_len = ItemIdGetLength(lp);
 6812 tgl@sss.pgh.pa.us        1567                 :         310811 :     tuple->t_tableOid = RelationGetRelid(relation);
                               1568                 :                : 
                               1569                 :                :     /*
                               1570                 :                :      * check tuple visibility, then release lock
                               1571                 :                :      */
 6714                          1572                 :         310811 :     valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
                               1573                 :                : 
 4815 heikki.linnakangas@i     1574         [ +  + ]:         310811 :     if (valid)
 1538 tmunro@postgresql.or     1575                 :         310753 :         PredicateLockTID(relation, &(tuple->t_self), snapshot,
                               1576         [ +  + ]:         310753 :                          HeapTupleHeaderGetXmin(tuple->t_data));
                               1577                 :                : 
                               1578                 :         310811 :     HeapCheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
                               1579                 :                : 
 4790 heikki.linnakangas@i     1580                 :         310811 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               1581                 :                : 
 7996 tgl@sss.pgh.pa.us        1582         [ +  + ]:         310811 :     if (valid)
                               1583                 :                :     {
                               1584                 :                :         /*
                               1585                 :                :          * All checks passed, so return the tuple as valid. Caller is now
                               1586                 :                :          * responsible for releasing the buffer.
                               1587                 :                :          */
 8969                          1588                 :         310753 :         *userbuf = buffer;
                               1589                 :                : 
 7996                          1590                 :         310753 :         return true;
                               1591                 :                :     }
                               1592                 :                : 
                               1593                 :                :     /* Tuple failed time qual, but maybe caller wants to see it anyway. */
  732                          1594         [ +  + ]:             58 :     if (keep_buf)
                               1595                 :             29 :         *userbuf = buffer;
                               1596                 :                :     else
                               1597                 :                :     {
                               1598                 :             29 :         ReleaseBuffer(buffer);
                               1599                 :             29 :         *userbuf = InvalidBuffer;
                               1600                 :             29 :         tuple->t_data = NULL;
                               1601                 :                :     }
                               1602                 :                : 
 7996                          1603                 :             58 :     return false;
                               1604                 :                : }
                               1605                 :                : 
                               1606                 :                : /*
                               1607                 :                :  *  heap_hot_search_buffer  - search HOT chain for tuple satisfying snapshot
                               1608                 :                :  *
                               1609                 :                :  * On entry, *tid is the TID of a tuple (either a simple tuple, or the root
                               1610                 :                :  * of a HOT chain), and buffer is the buffer holding this tuple.  We search
                               1611                 :                :  * for the first chain member satisfying the given snapshot.  If one is
                               1612                 :                :  * found, we update *tid to reference that tuple's offset number, and
                               1613                 :                :  * return true.  If no match, return false without modifying *tid.
                               1614                 :                :  *
                               1615                 :                :  * heapTuple is a caller-supplied buffer.  When a match is found, we return
                               1616                 :                :  * the tuple here, in addition to updating *tid.  If no match is found, the
                               1617                 :                :  * contents of this buffer on return are undefined.
                               1618                 :                :  *
                               1619                 :                :  * If all_dead is not NULL, we check non-visible tuples to see if they are
                               1620                 :                :  * globally dead; *all_dead is set true if all members of the HOT chain
                               1621                 :                :  * are vacuumable, false if not.
                               1622                 :                :  *
                               1623                 :                :  * Unlike heap_fetch, the caller must already have pin and (at least) share
                               1624                 :                :  * lock on the buffer; it is still pinned/locked at exit.
                               1625                 :                :  */
                               1626                 :                : bool
 4815 heikki.linnakangas@i     1627                 :       19475875 : heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer,
                               1628                 :                :                        Snapshot snapshot, HeapTuple heapTuple,
                               1629                 :                :                        bool *all_dead, bool first_call)
                               1630                 :                : {
  515 peter@eisentraut.org     1631                 :       19475875 :     Page        page = BufferGetPage(buffer);
 6051 tgl@sss.pgh.pa.us        1632                 :       19475875 :     TransactionId prev_xmax = InvalidTransactionId;
                               1633                 :                :     BlockNumber blkno;
                               1634                 :                :     OffsetNumber offnum;
                               1635                 :                :     bool        at_chain_start;
                               1636                 :                :     bool        valid;
                               1637                 :                :     bool        skip;
 1341 andres@anarazel.de       1638                 :       19475875 :     GlobalVisState *vistest = NULL;
                               1639                 :                : 
                               1640                 :                :     /* If this is not the first call, previous call returned a (live!) tuple */
 6051 tgl@sss.pgh.pa.us        1641         [ +  + ]:       19475875 :     if (all_dead)
 4675 rhaas@postgresql.org     1642                 :       16627156 :         *all_dead = first_call;
                               1643                 :                : 
 1712 heikki.linnakangas@i     1644                 :       19475875 :     blkno = ItemPointerGetBlockNumber(tid);
 6051 tgl@sss.pgh.pa.us        1645                 :       19475875 :     offnum = ItemPointerGetOffsetNumber(tid);
 4675 rhaas@postgresql.org     1646                 :       19475875 :     at_chain_start = first_call;
                               1647                 :       19475875 :     skip = !first_call;
                               1648                 :                : 
                               1649                 :                :     /* XXX: we should assert that a snapshot is pushed or registered */
 1341 andres@anarazel.de       1650         [ -  + ]:       19475875 :     Assert(TransactionIdIsValid(RecentXmin));
 1712 heikki.linnakangas@i     1651         [ +  - ]:       19475875 :     Assert(BufferGetBlockNumber(buffer) == blkno);
                               1652                 :                : 
                               1653                 :                :     /* Scan through possible multiple members of HOT-chain */
                               1654                 :                :     for (;;)
 6051 tgl@sss.pgh.pa.us        1655                 :         873252 :     {
                               1656                 :                :         ItemId      lp;
                               1657                 :                : 
                               1658                 :                :         /* check for bogus TID */
  515 peter@eisentraut.org     1659   [ +  -  +  - ]:       20349127 :         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
                               1660                 :                :             break;
                               1661                 :                : 
                               1662                 :       20349127 :         lp = PageGetItemId(page, offnum);
                               1663                 :                : 
                               1664                 :                :         /* check for unused, dead, or redirected items */
 6051 tgl@sss.pgh.pa.us        1665         [ +  + ]:       20349127 :         if (!ItemIdIsNormal(lp))
                               1666                 :                :         {
                               1667                 :                :             /* We should only see a redirect at start of chain */
                               1668   [ +  +  +  - ]:         713826 :             if (ItemIdIsRedirected(lp) && at_chain_start)
                               1669                 :                :             {
                               1670                 :                :                 /* Follow the redirect */
                               1671                 :         397984 :                 offnum = ItemIdGetRedirect(lp);
                               1672                 :         397984 :                 at_chain_start = false;
                               1673                 :         397984 :                 continue;
                               1674                 :                :             }
                               1675                 :                :             /* else must be end of chain */
                               1676                 :         315842 :             break;
                               1677                 :                :         }
                               1678                 :                : 
                               1679                 :                :         /*
                               1680                 :                :          * Update heapTuple to point to the element of the HOT chain we're
                               1681                 :                :          * currently investigating. Having t_self set correctly is important
                               1682                 :                :          * because the SSI checks and the *Satisfies routine for historical
                               1683                 :                :          * MVCC snapshots need the correct tid to decide about the visibility.
                               1684                 :                :          */
  515 peter@eisentraut.org     1685                 :       19635301 :         heapTuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
 4675 rhaas@postgresql.org     1686                 :       19635301 :         heapTuple->t_len = ItemIdGetLength(lp);
 3919                          1687                 :       19635301 :         heapTuple->t_tableOid = RelationGetRelid(relation);
 1712 heikki.linnakangas@i     1688                 :       19635301 :         ItemPointerSet(&heapTuple->t_self, blkno, offnum);
                               1689                 :                : 
                               1690                 :                :         /*
                               1691                 :                :          * Shouldn't see a HEAP_ONLY tuple at chain start.
                               1692                 :                :          */
 4675 rhaas@postgresql.org     1693   [ +  +  -  + ]:       19635301 :         if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
 6051 tgl@sss.pgh.pa.us        1694                 :UBC           0 :             break;
                               1695                 :                : 
                               1696                 :                :         /*
                               1697                 :                :          * The xmin should match the previous xmax value, else chain is
                               1698                 :                :          * broken.
                               1699                 :                :          */
 6051 tgl@sss.pgh.pa.us        1700   [ +  +  -  + ]:CBC    20110569 :         if (TransactionIdIsValid(prev_xmax) &&
 2355 alvherre@alvh.no-ip.     1701         [ +  - ]:         475268 :             !TransactionIdEquals(prev_xmax,
                               1702                 :                :                                  HeapTupleHeaderGetXmin(heapTuple->t_data)))
 6051 tgl@sss.pgh.pa.us        1703                 :UBC           0 :             break;
                               1704                 :                : 
                               1705                 :                :         /*
                               1706                 :                :          * When first_call is true (and thus, skip is initially false) we'll
                               1707                 :                :          * return the first tuple we find.  But on later passes, heapTuple
                               1708                 :                :          * will initially be pointing to the tuple we returned last time.
                               1709                 :                :          * Returning it again would be incorrect (and would loop forever), so
                               1710                 :                :          * we skip it and return the next match we find.
                               1711                 :                :          */
 4675 rhaas@postgresql.org     1712         [ +  + ]:CBC    19635301 :         if (!skip)
                               1713                 :                :         {
                               1714                 :                :             /* If it's visible per the snapshot, we must return it */
                               1715                 :       19563421 :             valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
 1538 tmunro@postgresql.or     1716                 :       19563421 :             HeapCheckForSerializableConflictOut(valid, relation, heapTuple,
                               1717                 :                :                                                 buffer, snapshot);
                               1718                 :                : 
 4675 rhaas@postgresql.org     1719         [ +  + ]:       19563416 :             if (valid)
                               1720                 :                :             {
                               1721                 :       13048746 :                 ItemPointerSetOffsetNumber(tid, offnum);
 1538 tmunro@postgresql.or     1722                 :       13048746 :                 PredicateLockTID(relation, &heapTuple->t_self, snapshot,
                               1723         [ +  + ]:       13048746 :                                  HeapTupleHeaderGetXmin(heapTuple->t_data));
 4675 rhaas@postgresql.org     1724         [ +  + ]:       13048746 :                 if (all_dead)
                               1725                 :       10451460 :                     *all_dead = false;
                               1726                 :       13048746 :                 return true;
                               1727                 :                :             }
                               1728                 :                :         }
                               1729                 :        6586550 :         skip = false;
                               1730                 :                : 
                               1731                 :                :         /*
                               1732                 :                :          * If we can't see it, maybe no one else can either.  At caller
                               1733                 :                :          * request, check whether all chain members are dead to all
                               1734                 :                :          * transactions.
                               1735                 :                :          *
                               1736                 :                :          * Note: if you change the criterion here for what is "dead", fix the
                               1737                 :                :          * planner's get_actual_variable_range() function to match.
                               1738                 :                :          */
 1341 andres@anarazel.de       1739   [ +  +  +  + ]:        6586550 :         if (all_dead && *all_dead)
                               1740                 :                :         {
                               1741         [ +  + ]:        6285392 :             if (!vistest)
                               1742                 :        6197614 :                 vistest = GlobalVisTestFor(relation);
                               1743                 :                : 
                               1744         [ +  + ]:        6285392 :             if (!HeapTupleIsSurelyDead(heapTuple, vistest))
                               1745                 :        5998055 :                 *all_dead = false;
                               1746                 :                :         }
                               1747                 :                : 
                               1748                 :                :         /*
                               1749                 :                :          * Check to see if HOT chain continues past this tuple; if so fetch
                               1750                 :                :          * the next offnum and loop around.
                               1751                 :                :          */
 4675 rhaas@postgresql.org     1752   [ +  +  +  -  :        6586550 :         if (HeapTupleIsHotUpdated(heapTuple))
                                              +  + ]
                               1753                 :                :         {
                               1754         [ -  + ]:         475268 :             Assert(ItemPointerGetBlockNumber(&heapTuple->t_data->t_ctid) ==
                               1755                 :                :                    blkno);
                               1756                 :         475268 :             offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
 6051 tgl@sss.pgh.pa.us        1757                 :         475268 :             at_chain_start = false;
 4099 alvherre@alvh.no-ip.     1758   [ +  -  +  +  :         475268 :             prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
                                              +  - ]
                               1759                 :                :         }
                               1760                 :                :         else
                               1761                 :                :             break;              /* end of chain */
                               1762                 :                :     }
                               1763                 :                : 
 4703 heikki.linnakangas@i     1764                 :        6427124 :     return false;
                               1765                 :                : }
                               1766                 :                : 
                               1767                 :                : /*
                               1768                 :                :  *  heap_get_latest_tid -  get the latest tid of a specified tuple
                               1769                 :                :  *
                               1770                 :                :  * Actually, this gets the latest version that is visible according to the
                               1771                 :                :  * scan's snapshot.  Create a scan using SnapshotDirty to get the very latest,
                               1772                 :                :  * possibly uncommitted version.
                               1773                 :                :  *
                               1774                 :                :  * *tid is both an input and an output parameter: it is updated to
                               1775                 :                :  * show the latest version of the row.  Note that it will not be changed
                               1776                 :                :  * if no version of the row passes the snapshot test.
                               1777                 :                :  */
                               1778                 :                : void
 1794 andres@anarazel.de       1779                 :            147 : heap_get_latest_tid(TableScanDesc sscan,
                               1780                 :                :                     ItemPointer tid)
                               1781                 :                : {
 1789 tgl@sss.pgh.pa.us        1782                 :            147 :     Relation    relation = sscan->rs_rd;
                               1783                 :            147 :     Snapshot    snapshot = sscan->rs_snapshot;
                               1784                 :                :     ItemPointerData ctid;
                               1785                 :                :     TransactionId priorXmax;
                               1786                 :                : 
                               1787                 :                :     /*
                               1788                 :                :      * table_tuple_get_latest_tid() verified that the passed in tid is valid.
                               1789                 :                :      * Assume that t_ctid links are valid however - there shouldn't be invalid
                               1790                 :                :      * ones in the table.
                               1791                 :                :      */
 1794 andres@anarazel.de       1792         [ -  + ]:            147 :     Assert(ItemPointerIsValid(tid));
                               1793                 :                : 
                               1794                 :                :     /*
                               1795                 :                :      * Loop to chase down t_ctid links.  At top of loop, ctid is the tuple we
                               1796                 :                :      * need to examine, and *tid is the TID we will return if ctid turns out
                               1797                 :                :      * to be bogus.
                               1798                 :                :      *
                               1799                 :                :      * Note that we will loop until we reach the end of the t_ctid chain.
                               1800                 :                :      * Depending on the snapshot passed, there might be at most one visible
                               1801                 :                :      * version of the row, but we don't try to optimize for that.
                               1802                 :                :      */
 6812 tgl@sss.pgh.pa.us        1803                 :            147 :     ctid = *tid;
                               1804                 :            147 :     priorXmax = InvalidTransactionId;   /* cannot check first XMIN */
                               1805                 :                :     for (;;)
                               1806                 :             45 :     {
                               1807                 :                :         Buffer      buffer;
                               1808                 :                :         Page        page;
                               1809                 :                :         OffsetNumber offnum;
                               1810                 :                :         ItemId      lp;
                               1811                 :                :         HeapTupleData tp;
                               1812                 :                :         bool        valid;
                               1813                 :                : 
                               1814                 :                :         /*
                               1815                 :                :          * Read, pin, and lock the page.
                               1816                 :                :          */
                               1817                 :            192 :         buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
                               1818                 :            192 :         LockBuffer(buffer, BUFFER_LOCK_SHARE);
 2916 kgrittn@postgresql.o     1819                 :            192 :         page = BufferGetPage(buffer);
                               1820                 :                : 
                               1821                 :                :         /*
                               1822                 :                :          * Check for bogus item number.  This is not treated as an error
                               1823                 :                :          * condition because it can happen while following a t_ctid link. We
                               1824                 :                :          * just assume that the prior tid is OK and return it unchanged.
                               1825                 :                :          */
 6812 tgl@sss.pgh.pa.us        1826                 :            192 :         offnum = ItemPointerGetOffsetNumber(&ctid);
 5754                          1827   [ +  -  -  + ]:            192 :         if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
                               1828                 :                :         {
 6589 tgl@sss.pgh.pa.us        1829                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 6812                          1830                 :              0 :             break;
                               1831                 :                :         }
 5754 tgl@sss.pgh.pa.us        1832                 :CBC         192 :         lp = PageGetItemId(page, offnum);
 6059                          1833         [ -  + ]:            192 :         if (!ItemIdIsNormal(lp))
                               1834                 :                :         {
 6589 tgl@sss.pgh.pa.us        1835                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 6812                          1836                 :              0 :             break;
                               1837                 :                :         }
                               1838                 :                : 
                               1839                 :                :         /* OK to access the tuple */
 6812 tgl@sss.pgh.pa.us        1840                 :CBC         192 :         tp.t_self = ctid;
 5754                          1841                 :            192 :         tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
 6812                          1842                 :            192 :         tp.t_len = ItemIdGetLength(lp);
 3919 rhaas@postgresql.org     1843                 :            192 :         tp.t_tableOid = RelationGetRelid(relation);
                               1844                 :                : 
                               1845                 :                :         /*
                               1846                 :                :          * After following a t_ctid link, we might arrive at an unrelated
                               1847                 :                :          * tuple.  Check for XMIN match.
                               1848                 :                :          */
 6812 tgl@sss.pgh.pa.us        1849   [ +  +  -  + ]:            237 :         if (TransactionIdIsValid(priorXmax) &&
 2355 alvherre@alvh.no-ip.     1850         [ +  - ]:             45 :             !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(tp.t_data)))
                               1851                 :                :         {
 6589 tgl@sss.pgh.pa.us        1852                 :UBC           0 :             UnlockReleaseBuffer(buffer);
 6812                          1853                 :              0 :             break;
                               1854                 :                :         }
                               1855                 :                : 
                               1856                 :                :         /*
                               1857                 :                :          * Check tuple visibility; if visible, set it as the new result
                               1858                 :                :          * candidate.
                               1859                 :                :          */
 6714 tgl@sss.pgh.pa.us        1860                 :CBC         192 :         valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
 1538 tmunro@postgresql.or     1861                 :            192 :         HeapCheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
 6812 tgl@sss.pgh.pa.us        1862         [ +  + ]:            192 :         if (valid)
                               1863                 :            135 :             *tid = ctid;
                               1864                 :                : 
                               1865                 :                :         /*
                               1866                 :                :          * If there's a valid t_ctid link, follow it, else we're done.
                               1867                 :                :          */
 4099 alvherre@alvh.no-ip.     1868   [ +  +  +  + ]:            273 :         if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               1869         [ +  - ]:            138 :             HeapTupleHeaderIsOnlyLocked(tp.t_data) ||
 2199 andres@anarazel.de       1870         [ +  + ]:            114 :             HeapTupleHeaderIndicatesMovedPartitions(tp.t_data) ||
 6812 tgl@sss.pgh.pa.us        1871                 :             57 :             ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
                               1872                 :                :         {
 6589                          1873                 :            147 :             UnlockReleaseBuffer(buffer);
 6812                          1874                 :            147 :             break;
                               1875                 :                :         }
                               1876                 :                : 
                               1877                 :             45 :         ctid = tp.t_data->t_ctid;
 4099 alvherre@alvh.no-ip.     1878   [ +  -  -  +  :             45 :         priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
                                              -  - ]
 6589 tgl@sss.pgh.pa.us        1879                 :             45 :         UnlockReleaseBuffer(buffer);
                               1880                 :                :     }                           /* end of loop */
 8952 inoue@tpf.co.jp          1881                 :            147 : }
                               1882                 :                : 
                               1883                 :                : 
                               1884                 :                : /*
                               1885                 :                :  * UpdateXmaxHintBits - update tuple hint bits after xmax transaction ends
                               1886                 :                :  *
                               1887                 :                :  * This is called after we have waited for the XMAX transaction to terminate.
                               1888                 :                :  * If the transaction aborted, we guarantee the XMAX_INVALID hint bit will
                               1889                 :                :  * be set on exit.  If the transaction committed, we set the XMAX_COMMITTED
                               1890                 :                :  * hint bit if possible --- but beware that that may not yet be possible,
                               1891                 :                :  * if the transaction committed asynchronously.
                               1892                 :                :  *
                               1893                 :                :  * Note that if the transaction was a locker only, we set HEAP_XMAX_INVALID
                               1894                 :                :  * even if it commits.
                               1895                 :                :  *
                               1896                 :                :  * Hence callers should look only at XMAX_INVALID.
                               1897                 :                :  *
                               1898                 :                :  * Note this is not allowed for tuples whose xmax is a multixact.
                               1899                 :                :  */
                               1900                 :                : static void
 6088 tgl@sss.pgh.pa.us        1901                 :            172 : UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
                               1902                 :                : {
 4099 alvherre@alvh.no-ip.     1903         [ -  + ]:            172 :     Assert(TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple), xid));
                               1904         [ -  + ]:            172 :     Assert(!(tuple->t_infomask & HEAP_XMAX_IS_MULTI));
                               1905                 :                : 
 6088 tgl@sss.pgh.pa.us        1906         [ +  - ]:            172 :     if (!(tuple->t_infomask & (HEAP_XMAX_COMMITTED | HEAP_XMAX_INVALID)))
                               1907                 :                :     {
 4099 alvherre@alvh.no-ip.     1908   [ +  +  +  -  :            314 :         if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask) &&
                                              +  + ]
                               1909                 :            142 :             TransactionIdDidCommit(xid))
 6088 tgl@sss.pgh.pa.us        1910                 :            116 :             HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_COMMITTED,
                               1911                 :                :                                  xid);
                               1912                 :                :         else
                               1913                 :             56 :             HeapTupleSetHintBits(tuple, buffer, HEAP_XMAX_INVALID,
                               1914                 :                :                                  InvalidTransactionId);
                               1915                 :                :     }
                               1916                 :            172 : }
                               1917                 :                : 
                               1918                 :                : 
                               1919                 :                : /*
                               1920                 :                :  * GetBulkInsertState - prepare status object for a bulk insert
                               1921                 :                :  */
                               1922                 :                : BulkInsertState
 5638                          1923                 :           2309 : GetBulkInsertState(void)
                               1924                 :                : {
                               1925                 :                :     BulkInsertState bistate;
                               1926                 :                : 
                               1927                 :           2309 :     bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
                               1928                 :           2309 :     bistate->strategy = GetAccessStrategy(BAS_BULKWRITE);
                               1929                 :           2309 :     bistate->current_buf = InvalidBuffer;
  374 andres@anarazel.de       1930                 :           2309 :     bistate->next_free = InvalidBlockNumber;
                               1931                 :           2309 :     bistate->last_free = InvalidBlockNumber;
  244                          1932                 :           2309 :     bistate->already_extended_by = 0;
 5638 tgl@sss.pgh.pa.us        1933                 :           2309 :     return bistate;
                               1934                 :                : }
                               1935                 :                : 
                               1936                 :                : /*
                               1937                 :                :  * FreeBulkInsertState - clean up after finishing a bulk insert
                               1938                 :                :  */
                               1939                 :                : void
                               1940                 :           2194 : FreeBulkInsertState(BulkInsertState bistate)
                               1941                 :                : {
                               1942         [ +  + ]:           2194 :     if (bistate->current_buf != InvalidBuffer)
 5421 bruce@momjian.us         1943                 :           1742 :         ReleaseBuffer(bistate->current_buf);
 5638 tgl@sss.pgh.pa.us        1944                 :           2194 :     FreeAccessStrategy(bistate->strategy);
                               1945                 :           2194 :     pfree(bistate);
                               1946                 :           2194 : }
                               1947                 :                : 
                               1948                 :                : /*
                               1949                 :                :  * ReleaseBulkInsertStatePin - release a buffer currently held in bistate
                               1950                 :                :  */
                               1951                 :                : void
 2637 rhaas@postgresql.org     1952                 :          80756 : ReleaseBulkInsertStatePin(BulkInsertState bistate)
                               1953                 :                : {
                               1954         [ +  + ]:          80756 :     if (bistate->current_buf != InvalidBuffer)
                               1955                 :          30021 :         ReleaseBuffer(bistate->current_buf);
                               1956                 :          80756 :     bistate->current_buf = InvalidBuffer;
                               1957                 :                : 
                               1958                 :                :     /*
                               1959                 :                :      * Despite the name, we also reset bulk relation extension state.
                               1960                 :                :      * Otherwise we can end up erroring out due to looking for free space in
                               1961                 :                :      * ->next_free of one partition, even though ->next_free was set when
                               1962                 :                :      * extending another partition. It could obviously also be bad for
                               1963                 :                :      * efficiency to look at existing blocks at offsets from another
                               1964                 :                :      * partition, even if we don't error out.
                               1965                 :                :      */
  184 andres@anarazel.de       1966                 :          80756 :     bistate->next_free = InvalidBlockNumber;
                               1967                 :          80756 :     bistate->last_free = InvalidBlockNumber;
 2637 rhaas@postgresql.org     1968                 :          80756 : }
                               1969                 :                : 
                               1970                 :                : 
                               1971                 :                : /*
                               1972                 :                :  *  heap_insert     - insert tuple into a heap
                               1973                 :                :  *
                               1974                 :                :  * The new tuple is stamped with current transaction ID and the specified
                               1975                 :                :  * command ID.
                               1976                 :                :  *
                               1977                 :                :  * See table_tuple_insert for comments about most of the input flags, except
                               1978                 :                :  * that this routine directly takes a tuple rather than a slot.
                               1979                 :                :  *
                               1980                 :                :  * There's corresponding HEAP_INSERT_ options to all the TABLE_INSERT_
                               1981                 :                :  * options, and there additionally is HEAP_INSERT_SPECULATIVE which is used to
                               1982                 :                :  * implement table_tuple_insert_speculative().
                               1983                 :                :  *
                               1984                 :                :  * On return the header fields of *tup are updated to match the stored tuple;
                               1985                 :                :  * in particular tup->t_self receives the actual TID where the tuple was
                               1986                 :                :  * stored.  But note that any toasting of fields within the tuple data is NOT
                               1987                 :                :  * reflected into *tup.
                               1988                 :                :  */
                               1989                 :                : void
 6873 tgl@sss.pgh.pa.us        1990                 :        7654548 : heap_insert(Relation relation, HeapTuple tup, CommandId cid,
                               1991                 :                :             int options, BulkInsertState bistate)
                               1992                 :                : {
 7150                          1993                 :        7654548 :     TransactionId xid = GetCurrentTransactionId();
                               1994                 :                :     HeapTuple   heaptup;
                               1995                 :                :     Buffer      buffer;
 4681 rhaas@postgresql.org     1996                 :        7654545 :     Buffer      vmbuffer = InvalidBuffer;
 5611 heikki.linnakangas@i     1997                 :        7654545 :     bool        all_visible_cleared = false;
                               1998                 :                : 
                               1999                 :                :     /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
 1070 tgl@sss.pgh.pa.us        2000         [ -  + ]:        7654545 :     Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
                               2001                 :                :            RelationGetNumberOfAttributes(relation));
                               2002                 :                : 
                               2003                 :                :     /*
                               2004                 :                :      * Fill in tuple header fields and toast the tuple if necessary.
                               2005                 :                :      *
                               2006                 :                :      * Note: below this point, heaptup is the data we actually intend to store
                               2007                 :                :      * into the relation; tup is the caller's original untoasted data.
                               2008                 :                :      */
 4540 heikki.linnakangas@i     2009                 :        7654545 :     heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
                               2010                 :                : 
                               2011                 :                :     /*
                               2012                 :                :      * Find buffer to insert this tuple into.  If the page is all visible,
                               2013                 :                :      * this will also pin the requisite visibility map page.
                               2014                 :                :      */
 3088 kgrittn@postgresql.o     2015                 :        7654545 :     buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
                               2016                 :                :                                        InvalidBuffer, options, bistate,
                               2017                 :                :                                        &vmbuffer, NULL,
                               2018                 :                :                                        0);
                               2019                 :                : 
                               2020                 :                :     /*
                               2021                 :                :      * We're about to do the actual insert -- but check for conflict first, to
                               2022                 :                :      * avoid possibly having to roll back work we've just done.
                               2023                 :                :      *
                               2024                 :                :      * This is safe without a recheck as long as there is no possibility of
                               2025                 :                :      * another process scanning the page between this check and the insert
                               2026                 :                :      * being visible to the scan (i.e., an exclusive buffer content lock is
                               2027                 :                :      * continuously held from this point until the tuple insert is visible).
                               2028                 :                :      *
                               2029                 :                :      * For a heap insert, we only need to check for table-level SSI locks. Our
                               2030                 :                :      * new tuple can't possibly conflict with existing tuple locks, and heap
                               2031                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2032                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2033                 :                :      * buffer when making the call, which makes for a faster check.
                               2034                 :                :      */
 1538 tmunro@postgresql.or     2035                 :        7654545 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2036                 :                : 
                               2037                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
 8493 tgl@sss.pgh.pa.us        2038                 :        7654533 :     START_CRIT_SECTION();
                               2039                 :                : 
 3264 andres@anarazel.de       2040                 :        7654533 :     RelationPutHeapTuple(relation, buffer, heaptup,
                               2041                 :        7654533 :                          (options & HEAP_INSERT_SPECULATIVE) != 0);
                               2042                 :                : 
 1046 tomas.vondra@postgre     2043         [ +  + ]:        7654533 :     if (PageIsAllVisible(BufferGetPage(buffer)))
                               2044                 :                :     {
 5611 heikki.linnakangas@i     2045                 :           6499 :         all_visible_cleared = true;
 2916 kgrittn@postgresql.o     2046                 :           6499 :         PageClearAllVisible(BufferGetPage(buffer));
 4681 rhaas@postgresql.org     2047                 :           6499 :         visibilitymap_clear(relation,
                               2048                 :           6499 :                             ItemPointerGetBlockNumber(&(heaptup->t_self)),
                               2049                 :                :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
                               2050                 :                :     }
                               2051                 :                : 
                               2052                 :                :     /*
                               2053                 :                :      * XXX Should we set PageSetPrunable on this page ?
                               2054                 :                :      *
                               2055                 :                :      * The inserting transaction may eventually abort thus making this tuple
                               2056                 :                :      * DEAD and hence available for pruning. Though we don't want to optimize
                               2057                 :                :      * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
                               2058                 :                :      * aborted tuple will never be pruned until next vacuum is triggered.
                               2059                 :                :      *
                               2060                 :                :      * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
                               2061                 :                :      */
                               2062                 :                : 
 6589 tgl@sss.pgh.pa.us        2063                 :        7654533 :     MarkBufferDirty(buffer);
                               2064                 :                : 
                               2065                 :                :     /* XLOG stuff */
 1471 noah@leadboat.com        2066   [ +  +  +  +  :        7654533 :     if (RelationNeedsWAL(relation))
                                        +  +  +  + ]
                               2067                 :                :     {
                               2068                 :                :         xl_heap_insert xlrec;
                               2069                 :                :         xl_heap_header xlhdr;
                               2070                 :                :         XLogRecPtr  recptr;
 2916 kgrittn@postgresql.o     2071                 :        6659531 :         Page        page = BufferGetPage(buffer);
 8424 bruce@momjian.us         2072                 :        6659531 :         uint8       info = XLOG_HEAP_INSERT;
 3433 heikki.linnakangas@i     2073                 :        6659531 :         int         bufflags = 0;
                               2074                 :                : 
                               2075                 :                :         /*
                               2076                 :                :          * If this is a catalog, we need to transmit combo CIDs to properly
                               2077                 :                :          * decode, so log that as well.
                               2078                 :                :          */
 3778 rhaas@postgresql.org     2079   [ +  +  +  -  :        6659531 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     -  +  -  -  -  
                                     -  +  +  +  +  
                                     -  +  -  -  +  
                                                 + ]
                               2080                 :           2833 :             log_heap_new_cid(relation, heaptup);
                               2081                 :                : 
                               2082                 :                :         /*
                               2083                 :                :          * If this is the single and first tuple on page, we can reinit the
                               2084                 :                :          * page instead of restoring the whole thing.  Set flag, and hide
                               2085                 :                :          * buffer references from XLogInsert.
                               2086                 :                :          */
 3433 heikki.linnakangas@i     2087   [ +  +  +  + ]:        6740277 :         if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
                               2088                 :          80746 :             PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
                               2089                 :                :         {
                               2090                 :          79950 :             info |= XLOG_HEAP_INIT_PAGE;
                               2091                 :          79950 :             bufflags |= REGBUF_WILL_INIT;
                               2092                 :                :         }
                               2093                 :                : 
                               2094                 :        6659531 :         xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
 3264 andres@anarazel.de       2095                 :        6659531 :         xlrec.flags = 0;
                               2096         [ +  + ]:        6659531 :         if (all_visible_cleared)
                               2097                 :           6496 :             xlrec.flags |= XLH_INSERT_ALL_VISIBLE_CLEARED;
                               2098         [ +  + ]:        6659531 :         if (options & HEAP_INSERT_SPECULATIVE)
                               2099                 :           2007 :             xlrec.flags |= XLH_INSERT_IS_SPECULATIVE;
 3433 heikki.linnakangas@i     2100         [ -  + ]:        6659531 :         Assert(ItemPointerGetBlockNumber(&heaptup->t_self) == BufferGetBlockNumber(buffer));
                               2101                 :                : 
                               2102                 :                :         /*
                               2103                 :                :          * For logical decoding, we need the tuple even if we're doing a full
                               2104                 :                :          * page write, so make sure it's included even if we take a full-page
                               2105                 :                :          * image. (XXX We could alternatively store a pointer into the FPW).
                               2106                 :                :          */
 2013 andres@anarazel.de       2107   [ +  +  +  -  :        6659531 :         if (RelationIsLogicallyLogged(relation) &&
                                     -  +  -  -  -  
                                        -  +  -  +  
                                                 + ]
                               2108         [ +  + ]:         244691 :             !(options & HEAP_INSERT_NO_LOGICAL))
                               2109                 :                :         {
 3264                          2110                 :         244664 :             xlrec.flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
 3433 heikki.linnakangas@i     2111                 :         244664 :             bufflags |= REGBUF_KEEP_DATA;
                               2112                 :                : 
 1345 akapila@postgresql.o     2113         [ +  + ]:         244664 :             if (IsToastRelation(relation))
                               2114                 :           1684 :                 xlrec.flags |= XLH_INSERT_ON_TOAST_RELATION;
                               2115                 :                :         }
                               2116                 :                : 
 3433 heikki.linnakangas@i     2117                 :        6659531 :         XLogBeginInsert();
                               2118                 :        6659531 :         XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
                               2119                 :                : 
                               2120                 :        6659531 :         xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
                               2121                 :        6659531 :         xlhdr.t_infomask = heaptup->t_data->t_infomask;
                               2122                 :        6659531 :         xlhdr.t_hoff = heaptup->t_data->t_hoff;
                               2123                 :                : 
                               2124                 :                :         /*
                               2125                 :                :          * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
                               2126                 :                :          * write the whole page to the xlog, we don't need to store
                               2127                 :                :          * xl_heap_header in the xlog.
                               2128                 :                :          */
                               2129                 :        6659531 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
                               2130                 :        6659531 :         XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
                               2131                 :                :         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
                               2132                 :        6659531 :         XLogRegisterBufData(0,
 3340 tgl@sss.pgh.pa.us        2133                 :        6659531 :                             (char *) heaptup->t_data + SizeofHeapTupleHeader,
                               2134                 :        6659531 :                             heaptup->t_len - SizeofHeapTupleHeader);
                               2135                 :                : 
                               2136                 :                :         /* filtering by origin on a row level is much more efficient */
 2670 andres@anarazel.de       2137                 :        6659531 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               2138                 :                : 
 3433 heikki.linnakangas@i     2139                 :        6659531 :         recptr = XLogInsert(RM_HEAP_ID, info);
                               2140                 :                : 
 8508 vadim4o@yahoo.com        2141                 :        6659531 :         PageSetLSN(page, recptr);
                               2142                 :                :     }
                               2143                 :                : 
 8493 tgl@sss.pgh.pa.us        2144         [ -  + ]:        7654533 :     END_CRIT_SECTION();
                               2145                 :                : 
 6589                          2146                 :        7654533 :     UnlockReleaseBuffer(buffer);
 4681 rhaas@postgresql.org     2147         [ +  + ]:        7654533 :     if (vmbuffer != InvalidBuffer)
                               2148                 :           6637 :         ReleaseBuffer(vmbuffer);
                               2149                 :                : 
                               2150                 :                :     /*
                               2151                 :                :      * If tuple is cachable, mark it for invalidation from the caches in case
                               2152                 :                :      * we abort.  Note it is OK to do this after releasing the buffer, because
                               2153                 :                :      * the heaptup data structure is all in local memory, not in the shared
                               2154                 :                :      * buffer.
                               2155                 :                :      */
 4625 tgl@sss.pgh.pa.us        2156                 :        7654533 :     CacheInvalidateHeapTuple(relation, heaptup, NULL);
                               2157                 :                : 
                               2158                 :                :     /* Note: speculative insertions are counted too, even if aborted later */
 4540 heikki.linnakangas@i     2159                 :        7654533 :     pgstat_count_heap_insert(relation, 1);
                               2160                 :                : 
                               2161                 :                :     /*
                               2162                 :                :      * If heaptup is a private copy, release it.  Don't forget to copy t_self
                               2163                 :                :      * back to the caller's image, too.
                               2164                 :                :      */
 6720 tgl@sss.pgh.pa.us        2165         [ +  + ]:        7654533 :     if (heaptup != tup)
                               2166                 :                :     {
                               2167                 :          15774 :         tup->t_self = heaptup->t_self;
                               2168                 :          15774 :         heap_freetuple(heaptup);
                               2169                 :                :     }
10141 scrappy@hub.org          2170                 :        7654533 : }
                               2171                 :                : 
                               2172                 :                : /*
                               2173                 :                :  * Subroutine for heap_insert(). Prepares a tuple for insertion. This sets the
                               2174                 :                :  * tuple header fields and toasts the tuple if necessary.  Returns a toasted
                               2175                 :                :  * version of the tuple if it was toasted, or the original tuple if not. Note
                               2176                 :                :  * that in any case, the header fields are also set in the original tuple.
                               2177                 :                :  */
                               2178                 :                : static HeapTuple
 4540 heikki.linnakangas@i     2179                 :        9107803 : heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid,
                               2180                 :                :                     CommandId cid, int options)
                               2181                 :                : {
                               2182                 :                :     /*
                               2183                 :                :      * To allow parallel inserts, we need to ensure that they are safe to be
                               2184                 :                :      * performed in workers. We have the infrastructure to allow parallel
                               2185                 :                :      * inserts in general except for the cases where inserts generate a new
                               2186                 :                :      * CommandId (eg. inserts into a table having a foreign key column).
                               2187                 :                :      */
 2383 rhaas@postgresql.org     2188         [ -  + ]:        9107803 :     if (IsParallelWorker())
 3272 rhaas@postgresql.org     2189         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2190                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               2191                 :                :                  errmsg("cannot insert tuples in a parallel worker")));
                               2192                 :                : 
 4540 heikki.linnakangas@i     2193                 :CBC     9107803 :     tup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
                               2194                 :        9107803 :     tup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
                               2195                 :        9107803 :     tup->t_data->t_infomask |= HEAP_XMAX_INVALID;
 3766 rhaas@postgresql.org     2196                 :        9107803 :     HeapTupleHeaderSetXmin(tup->t_data, xid);
 4151 simon@2ndQuadrant.co     2197         [ +  + ]:        9107803 :     if (options & HEAP_INSERT_FROZEN)
 3766 rhaas@postgresql.org     2198         [ -  + ]:         100362 :         HeapTupleHeaderSetXminFrozen(tup->t_data);
                               2199                 :                : 
 4540 heikki.linnakangas@i     2200         [ -  + ]:        9107803 :     HeapTupleHeaderSetCmin(tup->t_data, cid);
 2489 tgl@sss.pgh.pa.us        2201                 :        9107803 :     HeapTupleHeaderSetXmax(tup->t_data, 0); /* for cleanliness */
 4540 heikki.linnakangas@i     2202                 :        9107803 :     tup->t_tableOid = RelationGetRelid(relation);
                               2203                 :                : 
                               2204                 :                :     /*
                               2205                 :                :      * If the new tuple is too big for storage or contains already toasted
                               2206                 :                :      * out-of-line attributes from some other relation, invoke the toaster.
                               2207                 :                :      */
 4060 kgrittn@postgresql.o     2208         [ +  + ]:        9107803 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
                               2209         [ +  + ]:          27379 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               2210                 :                :     {
                               2211                 :                :         /* toast table entries should never be recursively toasted */
 4540 heikki.linnakangas@i     2212         [ -  + ]:          25717 :         Assert(!HeapTupleHasExternal(tup));
                               2213                 :          25717 :         return tup;
                               2214                 :                :     }
                               2215   [ +  +  +  + ]:        9082086 :     else if (HeapTupleHasExternal(tup) || tup->t_len > TOAST_TUPLE_THRESHOLD)
 1654 rhaas@postgresql.org     2216                 :          15815 :         return heap_toast_insert_or_update(relation, tup, NULL, options);
                               2217                 :                :     else
 4540 heikki.linnakangas@i     2218                 :        9066271 :         return tup;
                               2219                 :                : }
                               2220                 :                : 
                               2221                 :                : /*
                               2222                 :                :  * Helper for heap_multi_insert() that computes the number of entire pages
                               2223                 :                :  * that inserting the remaining heaptuples requires. Used to determine how
                               2224                 :                :  * much the relation needs to be extended by.
                               2225                 :                :  */
                               2226                 :                : static int
  374 andres@anarazel.de       2227                 :         308974 : heap_multi_insert_pages(HeapTuple *heaptuples, int done, int ntuples, Size saveFreeSpace)
                               2228                 :                : {
                               2229                 :         308974 :     size_t      page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
                               2230                 :         308974 :     int         npages = 1;
                               2231                 :                : 
                               2232         [ +  + ]:        2437449 :     for (int i = done; i < ntuples; i++)
                               2233                 :                :     {
                               2234                 :        2128475 :         size_t      tup_sz = sizeof(ItemIdData) + MAXALIGN(heaptuples[i]->t_len);
                               2235                 :                : 
                               2236         [ +  + ]:        2128475 :         if (page_avail < tup_sz)
                               2237                 :                :         {
                               2238                 :          16235 :             npages++;
                               2239                 :          16235 :             page_avail = BLCKSZ - SizeOfPageHeaderData - saveFreeSpace;
                               2240                 :                :         }
                               2241                 :        2128475 :         page_avail -= tup_sz;
                               2242                 :                :     }
                               2243                 :                : 
                               2244                 :         308974 :     return npages;
                               2245                 :                : }
                               2246                 :                : 
                               2247                 :                : /*
                               2248                 :                :  *  heap_multi_insert   - insert multiple tuples into a heap
                               2249                 :                :  *
                               2250                 :                :  * This is like heap_insert(), but inserts multiple tuples in one operation.
                               2251                 :                :  * That's faster than calling heap_insert() in a loop, because when multiple
                               2252                 :                :  * tuples can be inserted on a single page, we can write just a single WAL
                               2253                 :                :  * record covering all of them, and only need to lock/unlock the page once.
                               2254                 :                :  *
                               2255                 :                :  * Note: this leaks memory into the current memory context. You can create a
                               2256                 :                :  * temporary context before calling this, if that's a problem.
                               2257                 :                :  */
                               2258                 :                : void
 1837                          2259                 :         302969 : heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
                               2260                 :                :                   CommandId cid, int options, BulkInsertState bistate)
                               2261                 :                : {
 4540 heikki.linnakangas@i     2262                 :         302969 :     TransactionId xid = GetCurrentTransactionId();
                               2263                 :                :     HeapTuple  *heaptuples;
                               2264                 :                :     int         i;
                               2265                 :                :     int         ndone;
                               2266                 :                :     PGAlignedBlock scratch;
                               2267                 :                :     Page        page;
 1183 tomas.vondra@postgre     2268                 :         302969 :     Buffer      vmbuffer = InvalidBuffer;
                               2269                 :                :     bool        needwal;
                               2270                 :                :     Size        saveFreeSpace;
 3778 rhaas@postgresql.org     2271   [ +  +  +  -  :         302969 :     bool        need_tuple_data = RelationIsLogicallyLogged(relation);
                                     -  +  -  -  -  
                                        -  +  -  +  
                                                 + ]
                               2272   [ +  +  +  -  :         302969 :     bool        need_cids = RelationIsAccessibleInLogicalDecoding(relation);
                                     -  +  -  -  -  
                                     -  +  +  -  +  
                                     -  -  -  -  -  
                                                 - ]
  374 andres@anarazel.de       2273                 :         302969 :     bool        starting_with_empty_page = false;
                               2274                 :         302969 :     int         npages = 0;
                               2275                 :         302969 :     int         npages_used = 0;
                               2276                 :                : 
                               2277                 :                :     /* currently not needed (thus unsupported) for heap_multi_insert() */
  534 peter@eisentraut.org     2278         [ -  + ]:         302969 :     Assert(!(options & HEAP_INSERT_NO_LOGICAL));
                               2279                 :                : 
 1471 noah@leadboat.com        2280   [ +  +  +  +  :         302969 :     needwal = RelationNeedsWAL(relation);
                                        +  +  +  + ]
    3 akorotkov@postgresql     2281         [ +  + ]:         302969 :     saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
                               2282                 :                :                                                    HEAP_DEFAULT_FILLFACTOR);
                               2283                 :                : 
                               2284                 :                :     /* Toast and set header data in all the slots */
 4540 heikki.linnakangas@i     2285                 :         302969 :     heaptuples = palloc(ntuples * sizeof(HeapTuple));
                               2286         [ +  + ]:        1756227 :     for (i = 0; i < ntuples; i++)
                               2287                 :                :     {
                               2288                 :                :         HeapTuple   tuple;
                               2289                 :                : 
 1837 andres@anarazel.de       2290                 :        1453258 :         tuple = ExecFetchSlotHeapTuple(slots[i], true, NULL);
                               2291                 :        1453258 :         slots[i]->tts_tableOid = RelationGetRelid(relation);
                               2292                 :        1453258 :         tuple->t_tableOid = slots[i]->tts_tableOid;
                               2293                 :        1453258 :         heaptuples[i] = heap_prepare_insert(relation, tuple, xid, cid,
                               2294                 :                :                                             options);
                               2295                 :                :     }
                               2296                 :                : 
                               2297                 :                :     /*
                               2298                 :                :      * We're about to do the actual inserts -- but check for conflict first,
                               2299                 :                :      * to minimize the possibility of having to roll back work we've just
                               2300                 :                :      * done.
                               2301                 :                :      *
                               2302                 :                :      * A check here does not definitively prevent a serialization anomaly;
                               2303                 :                :      * that check MUST be done at least past the point of acquiring an
                               2304                 :                :      * exclusive buffer content lock on every buffer that will be affected,
                               2305                 :                :      * and MAY be done after all inserts are reflected in the buffers and
                               2306                 :                :      * those locks are released; otherwise there is a race condition.  Since
                               2307                 :                :      * multiple buffers can be locked and unlocked in the loop below, and it
                               2308                 :                :      * would not be feasible to identify and lock all of those buffers before
                               2309                 :                :      * the loop, we must do a final check at the end.
                               2310                 :                :      *
                               2311                 :                :      * The check here could be omitted with no loss of correctness; it is
                               2312                 :                :      * present strictly as an optimization.
                               2313                 :                :      *
                               2314                 :                :      * For heap inserts, we only need to check for table-level SSI locks. Our
                               2315                 :                :      * new tuples can't possibly conflict with existing tuple locks, and heap
                               2316                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2317                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2318                 :                :      * buffer when making the call, which makes for a faster check.
                               2319                 :                :      */
 1538 tmunro@postgresql.or     2320                 :         302969 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2321                 :                : 
 4540 heikki.linnakangas@i     2322                 :         302969 :     ndone = 0;
                               2323         [ +  + ]:         620358 :     while (ndone < ntuples)
                               2324                 :                :     {
                               2325                 :                :         Buffer      buffer;
                               2326                 :         317389 :         bool        all_visible_cleared = false;
 1183 tomas.vondra@postgre     2327                 :         317389 :         bool        all_frozen_set = false;
                               2328                 :                :         int         nthispage;
                               2329                 :                : 
 3583 rhaas@postgresql.org     2330         [ +  + ]:         317389 :         CHECK_FOR_INTERRUPTS();
                               2331                 :                : 
                               2332                 :                :         /*
                               2333                 :                :          * Compute number of pages needed to fit the to-be-inserted tuples in
                               2334                 :                :          * the worst case.  This will be used to determine how much to extend
                               2335                 :                :          * the relation by in RelationGetBufferForTuple(), if needed.  If we
                               2336                 :                :          * filled a prior page from scratch, we can just update our last
                               2337                 :                :          * computation, but if we started with a partially filled page,
                               2338                 :                :          * recompute from scratch, the number of potentially required pages
                               2339                 :                :          * can vary due to tuples needing to fit onto the page, page headers
                               2340                 :                :          * etc.
                               2341                 :                :          */
  374 andres@anarazel.de       2342   [ +  +  +  + ]:         317389 :         if (ndone == 0 || !starting_with_empty_page)
                               2343                 :                :         {
                               2344                 :         308974 :             npages = heap_multi_insert_pages(heaptuples, ndone, ntuples,
                               2345                 :                :                                              saveFreeSpace);
                               2346                 :         308974 :             npages_used = 0;
                               2347                 :                :         }
                               2348                 :                :         else
                               2349                 :           8415 :             npages_used++;
                               2350                 :                : 
                               2351                 :                :         /*
                               2352                 :                :          * Find buffer where at least the next tuple will fit.  If the page is
                               2353                 :                :          * all-visible, this will also pin the requisite visibility map page.
                               2354                 :                :          *
                               2355                 :                :          * Also pin visibility map page if COPY FREEZE inserts tuples into an
                               2356                 :                :          * empty page. See all_frozen_set below.
                               2357                 :                :          */
 4540 heikki.linnakangas@i     2358                 :         317389 :         buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
                               2359                 :                :                                            InvalidBuffer, options, bistate,
                               2360                 :                :                                            &vmbuffer, NULL,
                               2361                 :                :                                            npages - npages_used);
 2916 kgrittn@postgresql.o     2362                 :         317389 :         page = BufferGetPage(buffer);
                               2363                 :                : 
 1183 tomas.vondra@postgre     2364                 :         317389 :         starting_with_empty_page = PageGetMaxOffsetNumber(page) == 0;
                               2365                 :                : 
                               2366   [ +  +  +  + ]:         317389 :         if (starting_with_empty_page && (options & HEAP_INSERT_FROZEN))
                               2367                 :           1661 :             all_frozen_set = true;
                               2368                 :                : 
                               2369                 :                :         /* NO EREPORT(ERROR) from here till changes are logged */
 4540 heikki.linnakangas@i     2370                 :         317389 :         START_CRIT_SECTION();
                               2371                 :                : 
                               2372                 :                :         /*
                               2373                 :                :          * RelationGetBufferForTuple has ensured that the first tuple fits.
                               2374                 :                :          * Put that on the page, and then as many other tuples as fit.
                               2375                 :                :          */
 3264 andres@anarazel.de       2376                 :         317389 :         RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
                               2377                 :                : 
                               2378                 :                :         /*
                               2379                 :                :          * For logical decoding we need combo CIDs to properly decode the
                               2380                 :                :          * catalog.
                               2381                 :                :          */
 1510 michael@paquier.xyz      2382   [ +  +  +  + ]:         317389 :         if (needwal && need_cids)
                               2383                 :           4263 :             log_heap_new_cid(relation, heaptuples[ndone]);
                               2384                 :                : 
 4141 heikki.linnakangas@i     2385         [ +  + ]:        1453258 :         for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
                               2386                 :                :         {
 4540                          2387                 :        1150289 :             HeapTuple   heaptup = heaptuples[ndone + nthispage];
                               2388                 :                : 
 4351                          2389         [ +  + ]:        1150289 :             if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
 4540                          2390                 :          14420 :                 break;
                               2391                 :                : 
 3264 andres@anarazel.de       2392                 :        1135869 :             RelationPutHeapTuple(relation, buffer, heaptup, false);
                               2393                 :                : 
                               2394                 :                :             /*
                               2395                 :                :              * For logical decoding we need combo CIDs to properly decode the
                               2396                 :                :              * catalog.
                               2397                 :                :              */
 3433 heikki.linnakangas@i     2398   [ +  +  +  + ]:        1135869 :             if (needwal && need_cids)
                               2399                 :           4229 :                 log_heap_new_cid(relation, heaptup);
                               2400                 :                :         }
                               2401                 :                : 
                               2402                 :                :         /*
                               2403                 :                :          * If the page is all visible, need to clear that, unless we're only
                               2404                 :                :          * going to add further frozen rows to it.
                               2405                 :                :          *
                               2406                 :                :          * If we're only adding already frozen rows to a previously empty
                               2407                 :                :          * page, mark it as all-visible.
                               2408                 :                :          */
 1183 tomas.vondra@postgre     2409   [ +  +  +  + ]:         317389 :         if (PageIsAllVisible(page) && !(options & HEAP_INSERT_FROZEN))
                               2410                 :                :         {
 4329 rhaas@postgresql.org     2411                 :           3514 :             all_visible_cleared = true;
                               2412                 :           3514 :             PageClearAllVisible(page);
                               2413                 :           3514 :             visibilitymap_clear(relation,
                               2414                 :                :                                 BufferGetBlockNumber(buffer),
                               2415                 :                :                                 vmbuffer, VISIBILITYMAP_VALID_BITS);
                               2416                 :                :         }
 1183 tomas.vondra@postgre     2417         [ +  + ]:         313875 :         else if (all_frozen_set)
                               2418                 :           1661 :             PageSetAllVisible(page);
                               2419                 :                : 
                               2420                 :                :         /*
                               2421                 :                :          * XXX Should we set PageSetPrunable on this page ? See heap_insert()
                               2422                 :                :          */
                               2423                 :                : 
 4540 heikki.linnakangas@i     2424                 :         317389 :         MarkBufferDirty(buffer);
                               2425                 :                : 
                               2426                 :                :         /* XLOG stuff */
                               2427         [ +  + ]:         317389 :         if (needwal)
                               2428                 :                :         {
                               2429                 :                :             XLogRecPtr  recptr;
                               2430                 :                :             xl_heap_multi_insert *xlrec;
                               2431                 :         313029 :             uint8       info = XLOG_HEAP2_MULTI_INSERT;
                               2432                 :                :             char       *tupledata;
                               2433                 :                :             int         totaldatalen;
 2052 tgl@sss.pgh.pa.us        2434                 :         313029 :             char       *scratchptr = scratch.data;
                               2435                 :                :             bool        init;
 3433 heikki.linnakangas@i     2436                 :         313029 :             int         bufflags = 0;
                               2437                 :                : 
                               2438                 :                :             /*
                               2439                 :                :              * If the page was previously empty, we can reinit the page
                               2440                 :                :              * instead of restoring the whole thing.
                               2441                 :                :              */
 1183 tomas.vondra@postgre     2442                 :         313029 :             init = starting_with_empty_page;
                               2443                 :                : 
                               2444                 :                :             /* allocate xl_heap_multi_insert struct from the scratch area */
 4540 heikki.linnakangas@i     2445                 :         313029 :             xlrec = (xl_heap_multi_insert *) scratchptr;
                               2446                 :         313029 :             scratchptr += SizeOfHeapMultiInsert;
                               2447                 :                : 
                               2448                 :                :             /*
                               2449                 :                :              * Allocate offsets array. Unless we're reinitializing the page,
                               2450                 :                :              * in that case the tuples are stored in order starting at
                               2451                 :                :              * FirstOffsetNumber and we don't need to store the offsets
                               2452                 :                :              * explicitly.
                               2453                 :                :              */
                               2454         [ +  + ]:         313029 :             if (!init)
                               2455                 :         301732 :                 scratchptr += nthispage * sizeof(OffsetNumber);
                               2456                 :                : 
                               2457                 :                :             /* the rest of the scratch space is used for tuple data */
                               2458                 :         313029 :             tupledata = scratchptr;
                               2459                 :                : 
                               2460                 :                :             /* check that the mutually exclusive flags are not both set */
 1068 tgl@sss.pgh.pa.us        2461   [ +  +  -  + ]:         313029 :             Assert(!(all_visible_cleared && all_frozen_set));
                               2462                 :                : 
 1183 tomas.vondra@postgre     2463                 :         313029 :             xlrec->flags = 0;
                               2464         [ +  + ]:         313029 :             if (all_visible_cleared)
                               2465                 :           3514 :                 xlrec->flags = XLH_INSERT_ALL_VISIBLE_CLEARED;
                               2466         [ +  + ]:         313029 :             if (all_frozen_set)
                               2467                 :             13 :                 xlrec->flags = XLH_INSERT_ALL_FROZEN_SET;
                               2468                 :                : 
 4540 heikki.linnakangas@i     2469                 :         313029 :             xlrec->ntuples = nthispage;
                               2470                 :                : 
                               2471                 :                :             /*
                               2472                 :                :              * Write out an xl_multi_insert_tuple and the tuple data itself
                               2473                 :                :              * for each tuple.
                               2474                 :                :              */
                               2475         [ +  + ]:        1460895 :             for (i = 0; i < nthispage; i++)
                               2476                 :                :             {
                               2477                 :        1147866 :                 HeapTuple   heaptup = heaptuples[ndone + i];
                               2478                 :                :                 xl_multi_insert_tuple *tuphdr;
                               2479                 :                :                 int         datalen;
                               2480                 :                : 
                               2481         [ +  + ]:        1147866 :                 if (!init)
                               2482                 :         643078 :                     xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
                               2483                 :                :                 /* xl_multi_insert_tuple needs two-byte alignment. */
                               2484                 :        1147866 :                 tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
                               2485                 :        1147866 :                 scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
                               2486                 :                : 
                               2487                 :        1147866 :                 tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
                               2488                 :        1147866 :                 tuphdr->t_infomask = heaptup->t_data->t_infomask;
                               2489                 :        1147866 :                 tuphdr->t_hoff = heaptup->t_data->t_hoff;
                               2490                 :                : 
                               2491                 :                :                 /* write bitmap [+ padding] [+ oid] + data */
 3340 tgl@sss.pgh.pa.us        2492                 :        1147866 :                 datalen = heaptup->t_len - SizeofHeapTupleHeader;
 4540 heikki.linnakangas@i     2493                 :        1147866 :                 memcpy(scratchptr,
 3340 tgl@sss.pgh.pa.us        2494                 :        1147866 :                        (char *) heaptup->t_data + SizeofHeapTupleHeader,
                               2495                 :                :                        datalen);
 4540 heikki.linnakangas@i     2496                 :        1147866 :                 tuphdr->datalen = datalen;
                               2497                 :        1147866 :                 scratchptr += datalen;
                               2498                 :                :             }
                               2499                 :         313029 :             totaldatalen = scratchptr - tupledata;
 2052 tgl@sss.pgh.pa.us        2500         [ -  + ]:         313029 :             Assert((scratchptr - scratch.data) < BLCKSZ);
                               2501                 :                : 
 3778 rhaas@postgresql.org     2502         [ +  + ]:         313029 :             if (need_tuple_data)
 3264 andres@anarazel.de       2503                 :             73 :                 xlrec->flags |= XLH_INSERT_CONTAINS_NEW_TUPLE;
                               2504                 :                : 
                               2505                 :                :             /*
                               2506                 :                :              * Signal that this is the last xl_heap_multi_insert record
                               2507                 :                :              * emitted by this call to heap_multi_insert(). Needed for logical
                               2508                 :                :              * decoding so it knows when to cleanup temporary data.
                               2509                 :                :              */
 3433 heikki.linnakangas@i     2510         [ +  + ]:         313029 :             if (ndone + nthispage == ntuples)
 3264 andres@anarazel.de       2511                 :         302460 :                 xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
                               2512                 :                : 
 4540 heikki.linnakangas@i     2513         [ +  + ]:         313029 :             if (init)
                               2514                 :                :             {
                               2515                 :          11297 :                 info |= XLOG_HEAP_INIT_PAGE;
 3433                          2516                 :          11297 :                 bufflags |= REGBUF_WILL_INIT;
                               2517                 :                :             }
                               2518                 :                : 
                               2519                 :                :             /*
                               2520                 :                :              * If we're doing logical decoding, include the new tuple data
                               2521                 :                :              * even if we take a full-page image of the page.
                               2522                 :                :              */
                               2523         [ +  + ]:         313029 :             if (need_tuple_data)
                               2524                 :             73 :                 bufflags |= REGBUF_KEEP_DATA;
                               2525                 :                : 
                               2526                 :         313029 :             XLogBeginInsert();
 2052 tgl@sss.pgh.pa.us        2527                 :         313029 :             XLogRegisterData((char *) xlrec, tupledata - scratch.data);
 3433 heikki.linnakangas@i     2528                 :         313029 :             XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
                               2529                 :                : 
                               2530                 :         313029 :             XLogRegisterBufData(0, tupledata, totaldatalen);
                               2531                 :                : 
                               2532                 :                :             /* filtering by origin on a row level is much more efficient */
 2670 andres@anarazel.de       2533                 :         313029 :             XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               2534                 :                : 
 3433 heikki.linnakangas@i     2535                 :         313029 :             recptr = XLogInsert(RM_HEAP2_ID, info);
                               2536                 :                : 
 4540                          2537                 :         313029 :             PageSetLSN(page, recptr);
                               2538                 :                :         }
                               2539                 :                : 
                               2540         [ -  + ]:         317389 :         END_CRIT_SECTION();
                               2541                 :                : 
                               2542                 :                :         /*
                               2543                 :                :          * If we've frozen everything on the page, update the visibilitymap.
                               2544                 :                :          * We're already holding pin on the vmbuffer.
                               2545                 :                :          */
 1183 tomas.vondra@postgre     2546         [ +  + ]:         317389 :         if (all_frozen_set)
                               2547                 :                :         {
                               2548         [ -  + ]:           1661 :             Assert(PageIsAllVisible(page));
                               2549         [ -  + ]:           1661 :             Assert(visibilitymap_pin_ok(BufferGetBlockNumber(buffer), vmbuffer));
                               2550                 :                : 
                               2551                 :                :             /*
                               2552                 :                :              * It's fine to use InvalidTransactionId here - this is only used
                               2553                 :                :              * when HEAP_INSERT_FROZEN is specified, which intentionally
                               2554                 :                :              * violates visibility rules.
                               2555                 :                :              */
                               2556                 :           1661 :             visibilitymap_set(relation, BufferGetBlockNumber(buffer), buffer,
                               2557                 :                :                               InvalidXLogRecPtr, vmbuffer,
                               2558                 :                :                               InvalidTransactionId,
                               2559                 :                :                               VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN);
                               2560                 :                :         }
                               2561                 :                : 
                               2562                 :         317389 :         UnlockReleaseBuffer(buffer);
 4540 heikki.linnakangas@i     2563                 :         317389 :         ndone += nthispage;
                               2564                 :                : 
                               2565                 :                :         /*
                               2566                 :                :          * NB: Only release vmbuffer after inserting all tuples - it's fairly
                               2567                 :                :          * likely that we'll insert into subsequent heap pages that are likely
                               2568                 :                :          * to use the same vm page.
                               2569                 :                :          */
                               2570                 :                :     }
                               2571                 :                : 
                               2572                 :                :     /* We're done with inserting all tuples, so release the last vmbuffer. */
 1183 tomas.vondra@postgre     2573         [ +  + ]:         302969 :     if (vmbuffer != InvalidBuffer)
                               2574                 :           3601 :         ReleaseBuffer(vmbuffer);
                               2575                 :                : 
                               2576                 :                :     /*
                               2577                 :                :      * We're done with the actual inserts.  Check for conflicts again, to
                               2578                 :                :      * ensure that all rw-conflicts in to these inserts are detected.  Without
                               2579                 :                :      * this final check, a sequential scan of the heap may have locked the
                               2580                 :                :      * table after the "before" check, missing one opportunity to detect the
                               2581                 :                :      * conflict, and then scanned the table before the new tuples were there,
                               2582                 :                :      * missing the other chance to detect the conflict.
                               2583                 :                :      *
                               2584                 :                :      * For heap inserts, we only need to check for table-level SSI locks. Our
                               2585                 :                :      * new tuples can't possibly conflict with existing tuple locks, and heap
                               2586                 :                :      * page locks are only consolidated versions of tuple locks; they do not
                               2587                 :                :      * lock "gaps" as index page locks do.  So we don't need to specify a
                               2588                 :                :      * buffer when making the call.
                               2589                 :                :      */
 1538 tmunro@postgresql.or     2590                 :         302969 :     CheckForSerializableConflictIn(relation, NULL, InvalidBlockNumber);
                               2591                 :                : 
                               2592                 :                :     /*
                               2593                 :                :      * If tuples are cachable, mark them for invalidation from the caches in
                               2594                 :                :      * case we abort.  Note it is OK to do this after releasing the buffer,
                               2595                 :                :      * because the heaptuples data structure is all in local memory, not in
                               2596                 :                :      * the shared buffer.
                               2597                 :                :      */
 3790 rhaas@postgresql.org     2598         [ +  + ]:         302969 :     if (IsCatalogRelation(relation))
                               2599                 :                :     {
 4540 heikki.linnakangas@i     2600         [ +  + ]:        1061783 :         for (i = 0; i < ntuples; i++)
                               2601                 :         760073 :             CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
                               2602                 :                :     }
                               2603                 :                : 
                               2604                 :                :     /* copy t_self fields back to the caller's slots */
 4444                          2605         [ +  + ]:        1756227 :     for (i = 0; i < ntuples; i++)
 1837 andres@anarazel.de       2606                 :        1453258 :         slots[i]->tts_tid = heaptuples[i]->t_self;
                               2607                 :                : 
 4540 heikki.linnakangas@i     2608                 :         302969 :     pgstat_count_heap_insert(relation, ntuples);
                               2609                 :         302969 : }
                               2610                 :                : 
                               2611                 :                : /*
                               2612                 :                :  *  simple_heap_insert - insert a tuple
                               2613                 :                :  *
                               2614                 :                :  * Currently, this routine differs from heap_insert only in supplying
                               2615                 :                :  * a default command ID and not allowing access to the speedup options.
                               2616                 :                :  *
                               2617                 :                :  * This should be used rather than using heap_insert directly in most places
                               2618                 :                :  * where we are modifying system catalogs.
                               2619                 :                :  */
                               2620                 :                : void
 7999 tgl@sss.pgh.pa.us        2621                 :         728122 : simple_heap_insert(Relation relation, HeapTuple tup)
                               2622                 :                : {
 1972 andres@anarazel.de       2623                 :         728122 :     heap_insert(relation, tup, GetCurrentCommandId(true), 0, NULL);
 7999 tgl@sss.pgh.pa.us        2624                 :         728122 : }
                               2625                 :                : 
                               2626                 :                : /*
                               2627                 :                :  * Given infomask/infomask2, compute the bits that must be saved in the
                               2628                 :                :  * "infobits" field of xl_heap_delete, xl_heap_update, xl_heap_lock,
                               2629                 :                :  * xl_heap_lock_updated WAL records.
                               2630                 :                :  *
                               2631                 :                :  * See fix_infomask_from_infobits.
                               2632                 :                :  */
                               2633                 :                : static uint8
 4099 alvherre@alvh.no-ip.     2634                 :        1849505 : compute_infobits(uint16 infomask, uint16 infomask2)
                               2635                 :                : {
                               2636                 :                :     return
                               2637                 :        1849505 :         ((infomask & HEAP_XMAX_IS_MULTI) != 0 ? XLHL_XMAX_IS_MULTI : 0) |
                               2638                 :        1849505 :         ((infomask & HEAP_XMAX_LOCK_ONLY) != 0 ? XLHL_XMAX_LOCK_ONLY : 0) |
                               2639                 :        1849505 :         ((infomask & HEAP_XMAX_EXCL_LOCK) != 0 ? XLHL_XMAX_EXCL_LOCK : 0) |
                               2640                 :                :     /* note we ignore HEAP_XMAX_SHR_LOCK here */
                               2641                 :        3699010 :         ((infomask & HEAP_XMAX_KEYSHR_LOCK) != 0 ? XLHL_XMAX_KEYSHR_LOCK : 0) |
                               2642                 :                :         ((infomask2 & HEAP_KEYS_UPDATED) != 0 ?
                               2643                 :        1849505 :          XLHL_KEYS_UPDATED : 0);
                               2644                 :                : }
                               2645                 :                : 
                               2646                 :                : /*
                               2647                 :                :  * Given two versions of the same t_infomask for a tuple, compare them and
                               2648                 :                :  * return whether the relevant status for a tuple Xmax has changed.  This is
                               2649                 :                :  * used after a buffer lock has been released and reacquired: we want to ensure
                               2650                 :                :  * that the tuple state continues to be the same it was when we previously
                               2651                 :                :  * examined it.
                               2652                 :                :  *
                               2653                 :                :  * Note the Xmax field itself must be compared separately.
                               2654                 :                :  */
                               2655                 :                : static inline bool
 3643                          2656                 :           5323 : xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
                               2657                 :                : {
 3631 bruce@momjian.us         2658                 :           5323 :     const uint16 interesting =
                               2659                 :                :         HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY | HEAP_LOCK_MASK;
                               2660                 :                : 
 3643 alvherre@alvh.no-ip.     2661         [ +  + ]:           5323 :     if ((new_infomask & interesting) != (old_infomask & interesting))
                               2662                 :             13 :         return true;
                               2663                 :                : 
                               2664                 :           5310 :     return false;
                               2665                 :                : }
                               2666                 :                : 
                               2667                 :                : /*
                               2668                 :                :  *  heap_delete - delete a tuple
                               2669                 :                :  *
                               2670                 :                :  * See table_tuple_delete() for an explanation of the parameters, except that
                               2671                 :                :  * this routine directly takes a tuple rather than a slot.
                               2672                 :                :  *
                               2673                 :                :  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
                               2674                 :                :  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
                               2675                 :                :  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
                               2676                 :                :  * generated by another transaction).
                               2677                 :                :  */
                               2678                 :                : TM_Result
 7999 tgl@sss.pgh.pa.us        2679                 :        1432659 : heap_delete(Relation relation, ItemPointer tid,
                               2680                 :                :             CommandId cid, Snapshot crosscheck, bool wait,
                               2681                 :                :             TM_FailureData *tmfd, bool changingPart)
                               2682                 :                : {
                               2683                 :                :     TM_Result   result;
 7150                          2684                 :        1432659 :     TransactionId xid = GetCurrentTransactionId();
                               2685                 :                :     ItemId      lp;
                               2686                 :                :     HeapTupleData tp;
                               2687                 :                :     Page        page;
                               2688                 :                :     BlockNumber block;
                               2689                 :                :     Buffer      buffer;
 4681 rhaas@postgresql.org     2690                 :        1432659 :     Buffer      vmbuffer = InvalidBuffer;
                               2691                 :                :     TransactionId new_xmax;
                               2692                 :                :     uint16      new_infomask,
                               2693                 :                :                 new_infomask2;
 6924 tgl@sss.pgh.pa.us        2694                 :        1432659 :     bool        have_tuple_lock = false;
                               2695                 :                :     bool        iscombo;
 5611 heikki.linnakangas@i     2696                 :        1432659 :     bool        all_visible_cleared = false;
 3631 bruce@momjian.us         2697                 :        1432659 :     HeapTuple   old_key_tuple = NULL;   /* replica identity of the tuple */
 3778 rhaas@postgresql.org     2698                 :        1432659 :     bool        old_key_copied = false;
                               2699                 :                : 
 9716 bruce@momjian.us         2700         [ -  + ]:        1432659 :     Assert(ItemPointerIsValid(tid));
                               2701                 :                : 
                               2702                 :                :     /*
                               2703                 :                :      * Forbid this during a parallel operation, lest it allocate a combo CID.
                               2704                 :                :      * Other workers might need that combo CID for visibility checks, and we
                               2705                 :                :      * have no provision for broadcasting it to them.
                               2706                 :                :      */
 3272 rhaas@postgresql.org     2707         [ -  + ]:        1432659 :     if (IsInParallelMode())
 3272 rhaas@postgresql.org     2708         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2709                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               2710                 :                :                  errmsg("cannot delete tuples during a parallel operation")));
                               2711                 :                : 
 4681 rhaas@postgresql.org     2712                 :CBC     1432659 :     block = ItemPointerGetBlockNumber(tid);
                               2713                 :        1432659 :     buffer = ReadBuffer(relation, block);
 2916 kgrittn@postgresql.o     2714                 :        1432659 :     page = BufferGetPage(buffer);
                               2715                 :                : 
                               2716                 :                :     /*
                               2717                 :                :      * Before locking the buffer, pin the visibility map page if it appears to
                               2718                 :                :      * be necessary.  Since we haven't got the lock yet, someone else might be
                               2719                 :                :      * in the middle of changing this, so we'll need to recheck after we have
                               2720                 :                :      * the lock.
                               2721                 :                :      */
 4681 rhaas@postgresql.org     2722         [ +  + ]:        1432659 :     if (PageIsAllVisible(page))
                               2723                 :            130 :         visibilitymap_pin(relation, block, &vmbuffer);
                               2724                 :                : 
 9252 vadim4o@yahoo.com        2725                 :        1432659 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2726                 :                : 
  570 jdavis@postgresql.or     2727                 :        1432659 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
                               2728         [ -  + ]:        1432659 :     Assert(ItemIdIsNormal(lp));
                               2729                 :                : 
                               2730                 :        1432659 :     tp.t_tableOid = RelationGetRelid(relation);
                               2731                 :        1432659 :     tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
                               2732                 :        1432659 :     tp.t_len = ItemIdGetLength(lp);
                               2733                 :        1432659 :     tp.t_self = *tid;
                               2734                 :                : 
                               2735                 :              1 : l1:
                               2736                 :                : 
                               2737                 :                :     /*
                               2738                 :                :      * If we didn't pin the visibility map page and the page has become all
                               2739                 :                :      * visible while we were busy locking the buffer, we'll have to unlock and
                               2740                 :                :      * re-lock, to avoid holding the buffer lock across an I/O.  That's a bit
                               2741                 :                :      * unfortunate, but hopefully shouldn't happen often.
                               2742                 :                :      */
 4681 rhaas@postgresql.org     2743   [ +  +  -  + ]:        1432660 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               2744                 :                :     {
 4681 rhaas@postgresql.org     2745                 :UBC           0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2746                 :              0 :         visibilitymap_pin(relation, block, &vmbuffer);
                               2747                 :              0 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2748                 :                :     }
                               2749                 :                : 
 3919 rhaas@postgresql.org     2750                 :CBC     1432660 :     result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
                               2751                 :                : 
 1849 andres@anarazel.de       2752         [ -  + ]:        1432660 :     if (result == TM_Invisible)
                               2753                 :                :     {
 6589 tgl@sss.pgh.pa.us        2754                 :UBC           0 :         UnlockReleaseBuffer(buffer);
 3178                          2755         [ #  # ]:              0 :         ereport(ERROR,
                               2756                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               2757                 :                :                  errmsg("attempted to delete invisible tuple")));
                               2758                 :                :     }
    3 akorotkov@postgresql     2759   [ +  +  +  - ]:CBC     1432660 :     else if (result == TM_BeingModified && wait)
                               2760                 :                :     {
                               2761                 :                :         TransactionId xwait;
                               2762                 :                :         uint16      infomask;
                               2763                 :                : 
                               2764                 :                :         /* must copy state data before unlocking buffer */
 4099 alvherre@alvh.no-ip.     2765                 :          40549 :         xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
 6924 tgl@sss.pgh.pa.us        2766                 :          40549 :         infomask = tp.t_data->t_infomask;
                               2767                 :                : 
                               2768                 :                :         /*
                               2769                 :                :          * Sleep until concurrent transaction ends -- except when there's a
                               2770                 :                :          * single locker and it's our own transaction.  Note we don't care
                               2771                 :                :          * which lock mode the locker has, because we need the strongest one.
                               2772                 :                :          *
                               2773                 :                :          * Before sleeping, we need to acquire tuple lock to establish our
                               2774                 :                :          * priority for the tuple (see heap_lock_tuple).  LockTuple will
                               2775                 :                :          * release us when we are next-in-line for the tuple.
                               2776                 :                :          *
                               2777                 :                :          * If we are forced to "start over" below, we keep the tuple lock;
                               2778                 :                :          * this arranges that we stay at the head of the line while rechecking
                               2779                 :                :          * tuple state.
                               2780                 :                :          */
 6926                          2781         [ +  + ]:          40549 :         if (infomask & HEAP_XMAX_IS_MULTI)
                               2782                 :                :         {
 1762 alvherre@alvh.no-ip.     2783                 :              8 :             bool        current_is_member = false;
                               2784                 :                : 
 3292                          2785         [ +  - ]:              8 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               2786                 :                :                                         LockTupleExclusive, &current_is_member))
                               2787                 :                :             {
                               2788                 :              8 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2789                 :                : 
                               2790                 :                :                 /*
                               2791                 :                :                  * Acquire the lock, if necessary (but skip it when we're
                               2792                 :                :                  * requesting a lock and already have one; avoids deadlock).
                               2793                 :                :                  */
 1762                          2794         [ +  + ]:              8 :                 if (!current_is_member)
                               2795                 :              6 :                     heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
                               2796                 :                :                                          LockWaitBlock, &have_tuple_lock);
                               2797                 :                : 
                               2798                 :                :                 /* wait for multixact */
 3292                          2799                 :              8 :                 MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, infomask,
                               2800                 :                :                                 relation, &(tp.t_self), XLTW_Delete,
                               2801                 :                :                                 NULL);
                               2802                 :              8 :                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2803                 :                : 
                               2804                 :                :                 /*
                               2805                 :                :                  * If xwait had just locked the tuple then some other xact
                               2806                 :                :                  * could update this tuple before we get to this point.  Check
                               2807                 :                :                  * for xmax change, and start over if so.
                               2808                 :                :                  *
                               2809                 :                :                  * We also must start over if we didn't pin the VM page, and
                               2810                 :                :                  * the page has become all visible.
                               2811                 :                :                  */
  570 jdavis@postgresql.or     2812   [ +  -  +  -  :             16 :                 if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
                                              +  - ]
                               2813                 :              8 :                     xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
 3292 alvherre@alvh.no-ip.     2814         [ -  + ]:              8 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
                               2815                 :                :                                          xwait))
 3292 alvherre@alvh.no-ip.     2816                 :UBC           0 :                     goto l1;
                               2817                 :                :             }
                               2818                 :                : 
                               2819                 :                :             /*
                               2820                 :                :              * You might think the multixact is necessarily done here, but not
                               2821                 :                :              * so: it could have surviving members, namely our own xact or
                               2822                 :                :              * other subxacts of this backend.  It is legal for us to delete
                               2823                 :                :              * the tuple in either case, however (the latter case is
                               2824                 :                :              * essentially a situation of upgrading our former shared lock to
                               2825                 :                :              * exclusive).  We don't bother changing the on-disk hint bits
                               2826                 :                :              * since we are about to overwrite the xmax altogether.
                               2827                 :                :              */
                               2828                 :                :         }
 3292 alvherre@alvh.no-ip.     2829         [ +  + ]:CBC       40541 :         else if (!TransactionIdIsCurrentTransactionId(xwait))
                               2830                 :                :         {
                               2831                 :                :             /*
                               2832                 :                :              * Wait for regular transaction to end; but first, acquire tuple
                               2833                 :                :              * lock.
                               2834                 :                :              */
                               2835                 :             40 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               2836                 :             40 :             heap_acquire_tuplock(relation, &(tp.t_self), LockTupleExclusive,
                               2837                 :                :                                  LockWaitBlock, &have_tuple_lock);
 3357 heikki.linnakangas@i     2838                 :             40 :             XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
 6926 tgl@sss.pgh.pa.us        2839                 :             36 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               2840                 :                : 
                               2841                 :                :             /*
                               2842                 :                :              * xwait is done, but if xwait had just locked the tuple then some
                               2843                 :                :              * other xact could update this tuple before we get to this point.
                               2844                 :                :              * Check for xmax change, and start over if so.
                               2845                 :                :              *
                               2846                 :                :              * We also must start over if we didn't pin the VM page, and the
                               2847                 :                :              * page has become all visible.
                               2848                 :                :              */
  570 jdavis@postgresql.or     2849   [ +  -  +  -  :             72 :             if ((vmbuffer == InvalidBuffer && PageIsAllVisible(page)) ||
                                              +  + ]
                               2850                 :             36 :                 xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
 4099 alvherre@alvh.no-ip.     2851         [ -  + ]:             35 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data),
                               2852                 :                :                                      xwait))
 6926 tgl@sss.pgh.pa.us        2853                 :              1 :                 goto l1;
                               2854                 :                : 
                               2855                 :                :             /* Otherwise check if it committed or aborted */
 6088                          2856                 :             35 :             UpdateXmaxHintBits(tp.t_data, buffer, xwait);
                               2857                 :                :         }
                               2858                 :                : 
                               2859                 :                :         /*
                               2860                 :                :          * We may overwrite if previous xmax aborted, or if it committed but
                               2861                 :                :          * only locked the tuple without updating it.
                               2862                 :                :          */
 4099 alvherre@alvh.no-ip.     2863         [ +  + ]:          40544 :         if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               2864   [ +  +  +  -  :          40555 :             HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask) ||
                                              +  + ]
                               2865                 :             25 :             HeapTupleHeaderIsOnlyLocked(tp.t_data))
 1849 andres@anarazel.de       2866                 :          40523 :             result = TM_Ok;
 1147 alvherre@alvh.no-ip.     2867         [ +  + ]:             21 :         else if (!ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid))
 1849 andres@anarazel.de       2868                 :             17 :             result = TM_Updated;
                               2869                 :                :         else
                               2870                 :              4 :             result = TM_Deleted;
                               2871                 :                :     }
                               2872                 :                : 
                               2873                 :                :     /* sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
                               2874         [ +  + ]:        1432655 :     if (result != TM_Ok)
                               2875                 :                :     {
                               2876   [ +  +  +  +  :             55 :         Assert(result == TM_SelfModified ||
                                        -  +  -  - ]
                               2877                 :                :                result == TM_Updated ||
                               2878                 :                :                result == TM_Deleted ||
                               2879                 :                :                result == TM_BeingModified);
 6812 tgl@sss.pgh.pa.us        2880         [ -  + ]:             55 :         Assert(!(tp.t_data->t_infomask & HEAP_XMAX_INVALID));
 1849 andres@anarazel.de       2881   [ +  +  -  + ]:             55 :         Assert(result != TM_Updated ||
                               2882                 :                :                !ItemPointerEquals(&tp.t_self, &tp.t_data->t_ctid));
                               2883                 :                :     }
                               2884                 :                : 
  138 heikki.linnakangas@i     2885   [ +  +  +  - ]:        1432655 :     if (crosscheck != InvalidSnapshot && result == TM_Ok)
                               2886                 :                :     {
                               2887                 :                :         /* Perform additional check for transaction-snapshot mode RI updates */
                               2888         [ +  - ]:              1 :         if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
                               2889                 :              1 :             result = TM_Updated;
                               2890                 :                :     }
                               2891                 :                : 
                               2892         [ +  + ]:        1432655 :     if (result != TM_Ok)
                               2893                 :                :     {
 1849 andres@anarazel.de       2894                 :             56 :         tmfd->ctid = tp.t_data->t_ctid;
                               2895   [ +  +  -  +  :             56 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
                                              -  - ]
                               2896         [ +  + ]:             56 :         if (result == TM_SelfModified)
                               2897                 :             21 :             tmfd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
                               2898                 :                :         else
                               2899                 :             35 :             tmfd->cmax = InvalidCommandId;
    3 akorotkov@postgresql     2900                 :             56 :         UnlockReleaseBuffer(buffer);
 6924 tgl@sss.pgh.pa.us        2901         [ +  + ]:             56 :         if (have_tuple_lock)
 4099 alvherre@alvh.no-ip.     2902                 :             21 :             UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
 4681 rhaas@postgresql.org     2903         [ -  + ]:             56 :         if (vmbuffer != InvalidBuffer)
 4681 rhaas@postgresql.org     2904                 :UBC           0 :             ReleaseBuffer(vmbuffer);
 9252 vadim4o@yahoo.com        2905                 :CBC          56 :         return result;
                               2906                 :                :     }
                               2907                 :                : 
                               2908                 :                :     /*
                               2909                 :                :      * We're about to do the actual delete -- check for conflict first, to
                               2910                 :                :      * avoid possibly having to roll back work we've just done.
                               2911                 :                :      *
                               2912                 :                :      * This is safe without a recheck as long as there is no possibility of
                               2913                 :                :      * another process scanning the page between this check and the delete
                               2914                 :                :      * being visible to the scan (i.e., an exclusive buffer content lock is
                               2915                 :                :      * continuously held from this point until the tuple delete is visible).
                               2916                 :                :      */
 1538 tmunro@postgresql.or     2917                 :        1432599 :     CheckForSerializableConflictIn(relation, tid, BufferGetBlockNumber(buffer));
                               2918                 :                : 
                               2919                 :                :     /* replace cid with a combo CID if necessary */
 6274 tgl@sss.pgh.pa.us        2920                 :        1432585 :     HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
                               2921                 :                : 
                               2922                 :                :     /*
                               2923                 :                :      * Compute replica identity tuple before entering the critical section so
                               2924                 :                :      * we don't PANIC upon a memory allocation failure.
                               2925                 :                :      */
 3778 rhaas@postgresql.org     2926                 :        1432585 :     old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
                               2927                 :                : 
                               2928                 :                :     /*
                               2929                 :                :      * If this is the first possibly-multixact-able operation in the current
                               2930                 :                :      * transaction, set my per-backend OldestMemberMXactId setting. We can be
                               2931                 :                :      * certain that the transaction will never become a member of any older
                               2932                 :                :      * MultiXactIds than that.  (We have to do this even if we end up just
                               2933                 :                :      * using our own TransactionId below, since some other backend could
                               2934                 :                :      * incorporate our XID into a MultiXact immediately afterwards.)
                               2935                 :                :      */
 3663 heikki.linnakangas@i     2936                 :        1432585 :     MultiXactIdSetOldestMember();
                               2937                 :                : 
                               2938                 :        1432585 :     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(tp.t_data),
                               2939                 :        1432585 :                               tp.t_data->t_infomask, tp.t_data->t_infomask2,
                               2940                 :                :                               xid, LockTupleExclusive, true,
                               2941                 :                :                               &new_xmax, &new_infomask, &new_infomask2);
                               2942                 :                : 
 8493 tgl@sss.pgh.pa.us        2943                 :        1432585 :     START_CRIT_SECTION();
                               2944                 :                : 
                               2945                 :                :     /*
                               2946                 :                :      * If this transaction commits, the tuple will become DEAD sooner or
                               2947                 :                :      * later.  Set flag that this page is a candidate for pruning once our xid
                               2948                 :                :      * falls below the OldestXmin horizon.  If the transaction finally aborts,
                               2949                 :                :      * the subsequent page pruning will be a no-op and the hint will be
                               2950                 :                :      * cleared.
                               2951                 :                :      */
 5754                          2952   [ -  +  +  +  :        1432585 :     PageSetPrunable(page, xid);
                                              +  + ]
                               2953                 :                : 
 5611 heikki.linnakangas@i     2954         [ +  + ]:        1432585 :     if (PageIsAllVisible(page))
                               2955                 :                :     {
                               2956                 :            130 :         all_visible_cleared = true;
                               2957                 :            130 :         PageClearAllVisible(page);
 4681 rhaas@postgresql.org     2958                 :            130 :         visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
                               2959                 :                :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
                               2960                 :                :     }
                               2961                 :                : 
                               2962                 :                :     /* store transaction information of xact deleting the tuple */
 4099 alvherre@alvh.no-ip.     2963                 :        1432585 :     tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               2964                 :        1432585 :     tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               2965                 :        1432585 :     tp.t_data->t_infomask |= new_infomask;
                               2966                 :        1432585 :     tp.t_data->t_infomask2 |= new_infomask2;
 6051 tgl@sss.pgh.pa.us        2967                 :        1432585 :     HeapTupleHeaderClearHotUpdated(tp.t_data);
 4099 alvherre@alvh.no-ip.     2968                 :        1432585 :     HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
 6274 tgl@sss.pgh.pa.us        2969   [ -  +  +  + ]:        1432585 :     HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
                               2970                 :                :     /* Make sure there is no forward chain link in t_ctid */
 7915                          2971                 :        1432585 :     tp.t_data->t_ctid = tp.t_self;
                               2972                 :                : 
                               2973                 :                :     /* Signal that this is actually a move into another partition */
 2199 andres@anarazel.de       2974         [ +  + ]:        1432585 :     if (changingPart)
                               2975                 :            446 :         HeapTupleHeaderSetMovedPartitions(tp.t_data);
                               2976                 :                : 
 6589 tgl@sss.pgh.pa.us        2977                 :        1432585 :     MarkBufferDirty(buffer);
                               2978                 :                : 
                               2979                 :                :     /*
                               2980                 :                :      * XLOG stuff
                               2981                 :                :      *
                               2982                 :                :      * NB: heap_abort_speculative() uses the same xlog record and replay
                               2983                 :                :      * routines.
                               2984                 :                :      */
 4871 rhaas@postgresql.org     2985   [ +  +  +  +  :        1432585 :     if (RelationNeedsWAL(relation))
                                        +  +  +  + ]
                               2986                 :                :     {
                               2987                 :                :         xl_heap_delete xlrec;
                               2988                 :                :         xl_heap_header xlhdr;
                               2989                 :                :         XLogRecPtr  recptr;
                               2990                 :                : 
                               2991                 :                :         /*
                               2992                 :                :          * For logical decode we need combo CIDs to properly decode the
                               2993                 :                :          * catalog
                               2994                 :                :          */
 3778                          2995   [ +  +  +  -  :        1372003 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     -  +  -  -  -  
                                     -  +  +  -  +  
                                     -  -  -  -  -  
                                                 - ]
                               2996                 :           5286 :             log_heap_new_cid(relation, &tp);
                               2997                 :                : 
 2199 andres@anarazel.de       2998                 :        1372003 :         xlrec.flags = 0;
                               2999         [ +  + ]:        1372003 :         if (all_visible_cleared)
                               3000                 :            130 :             xlrec.flags |= XLH_DELETE_ALL_VISIBLE_CLEARED;
                               3001         [ +  + ]:        1372003 :         if (changingPart)
                               3002                 :            446 :             xlrec.flags |= XLH_DELETE_IS_PARTITION_MOVE;
 4099 alvherre@alvh.no-ip.     3003                 :        2744006 :         xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
                               3004                 :        1372003 :                                               tp.t_data->t_infomask2);
 3433 heikki.linnakangas@i     3005                 :        1372003 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
 4099 alvherre@alvh.no-ip.     3006                 :        1372003 :         xlrec.xmax = new_xmax;
                               3007                 :                : 
 3433 heikki.linnakangas@i     3008         [ +  + ]:        1372003 :         if (old_key_tuple != NULL)
                               3009                 :                :         {
                               3010         [ +  + ]:          47000 :             if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
 3264 andres@anarazel.de       3011                 :            121 :                 xlrec.flags |= XLH_DELETE_CONTAINS_OLD_TUPLE;
                               3012                 :                :             else
                               3013                 :          46879 :                 xlrec.flags |= XLH_DELETE_CONTAINS_OLD_KEY;
                               3014                 :                :         }
                               3015                 :                : 
 3433 heikki.linnakangas@i     3016                 :        1372003 :         XLogBeginInsert();
                               3017                 :        1372003 :         XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
                               3018                 :                : 
                               3019                 :        1372003 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               3020                 :                : 
                               3021                 :                :         /*
                               3022                 :                :          * Log replica identity of the deleted tuple if there is one
                               3023                 :                :          */
 3778 rhaas@postgresql.org     3024         [ +  + ]:        1372003 :         if (old_key_tuple != NULL)
                               3025                 :                :         {
                               3026                 :          47000 :             xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
                               3027                 :          47000 :             xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
                               3028                 :          47000 :             xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
                               3029                 :                : 
 3433 heikki.linnakangas@i     3030                 :          47000 :             XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
                               3031                 :          47000 :             XLogRegisterData((char *) old_key_tuple->t_data
                               3032                 :                :                              + SizeofHeapTupleHeader,
                               3033                 :          47000 :                              old_key_tuple->t_len
                               3034                 :                :                              - SizeofHeapTupleHeader);
                               3035                 :                :         }
                               3036                 :                : 
                               3037                 :                :         /* filtering by origin on a row level is much more efficient */
 2670 andres@anarazel.de       3038                 :        1372003 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               3039                 :                : 
 3433 heikki.linnakangas@i     3040                 :        1372003 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
                               3041                 :                : 
 5754 tgl@sss.pgh.pa.us        3042                 :        1372003 :         PageSetLSN(page, recptr);
                               3043                 :                :     }
                               3044                 :                : 
 8493                          3045         [ -  + ]:        1432585 :     END_CRIT_SECTION();
                               3046                 :                : 
 8490                          3047                 :        1432585 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3048                 :                : 
 4681 rhaas@postgresql.org     3049         [ +  + ]:        1432585 :     if (vmbuffer != InvalidBuffer)
                               3050                 :            130 :         ReleaseBuffer(vmbuffer);
                               3051                 :                : 
                               3052                 :                :     /*
                               3053                 :                :      * If the tuple has toasted out-of-line attributes, we need to delete
                               3054                 :                :      * those items too.  We have to do this before releasing the buffer
                               3055                 :                :      * because we need to look at the contents of the tuple, but it's OK to
                               3056                 :                :      * release the content lock on the buffer first.
                               3057                 :                :      */
 4060 kgrittn@postgresql.o     3058         [ +  + ]:        1432585 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
                               3059         [ +  + ]:           1706 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               3060                 :                :     {
                               3061                 :                :         /* toast table entries should never be recursively toasted */
 6221 tgl@sss.pgh.pa.us        3062         [ -  + ]:           1696 :         Assert(!HeapTupleHasExternal(&tp));
                               3063                 :                :     }
                               3064         [ +  + ]:        1430889 :     else if (HeapTupleHasExternal(&tp))
 1654 rhaas@postgresql.org     3065                 :            256 :         heap_toast_delete(relation, &tp, false);
                               3066                 :                : 
                               3067                 :                :     /*
                               3068                 :                :      * Mark tuple for invalidation from system caches at next command
                               3069                 :                :      * boundary. We have to do this before releasing the buffer because we
                               3070                 :                :      * need to look at the contents of the tuple.
                               3071                 :                :      */
 4625 tgl@sss.pgh.pa.us        3072                 :        1432585 :     CacheInvalidateHeapTuple(relation, &tp, NULL);
                               3073                 :                : 
                               3074                 :                :     /* Now we can release the buffer */
    3 akorotkov@postgresql     3075                 :        1432585 :     ReleaseBuffer(buffer);
                               3076                 :                : 
                               3077                 :                :     /*
                               3078                 :                :      * Release the lmgr tuple lock, if we had it.
                               3079                 :                :      */
 6924 tgl@sss.pgh.pa.us        3080         [ +  + ]:        1432585 :     if (have_tuple_lock)
 4099 alvherre@alvh.no-ip.     3081                 :             20 :         UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
                               3082                 :                : 
 6167 tgl@sss.pgh.pa.us        3083                 :        1432585 :     pgstat_count_heap_delete(relation);
                               3084                 :                : 
 3778 rhaas@postgresql.org     3085   [ +  +  +  + ]:        1432585 :     if (old_key_tuple != NULL && old_key_copied)
                               3086                 :          46880 :         heap_freetuple(old_key_tuple);
                               3087                 :                : 
 1849 andres@anarazel.de       3088                 :        1432585 :     return TM_Ok;
                               3089                 :                : }
                               3090                 :                : 
                               3091                 :                : /*
                               3092                 :                :  *  simple_heap_delete - delete a tuple
                               3093                 :                :  *
                               3094                 :                :  * This routine may be used to delete a tuple when concurrent updates of
                               3095                 :                :  * the target tuple are not expected (for example, because we have a lock
                               3096                 :                :  * on the relation associated with the tuple).  Any failure is reported
                               3097                 :                :  * via ereport().
                               3098                 :                :  */
                               3099                 :                : void
 8482 tgl@sss.pgh.pa.us        3100                 :         571865 : simple_heap_delete(Relation relation, ItemPointer tid)
                               3101                 :                : {
                               3102                 :                :     TM_Result   result;
                               3103                 :                :     TM_FailureData tmfd;
                               3104                 :                : 
 7517                          3105                 :         571865 :     result = heap_delete(relation, tid,
                               3106                 :                :                          GetCurrentCommandId(true), InvalidSnapshot,
                               3107                 :                :                          true /* wait for commit */ ,
                               3108                 :                :                          &tmfd, false /* changingPart */ );
 8482                          3109   [ -  +  -  -  :         571865 :     switch (result)
                                                 - ]
                               3110                 :                :     {
 1849 andres@anarazel.de       3111                 :UBC           0 :         case TM_SelfModified:
                               3112                 :                :             /* Tuple was already updated in current command? */
 7573 tgl@sss.pgh.pa.us        3113         [ #  # ]:              0 :             elog(ERROR, "tuple already updated by self");
                               3114                 :                :             break;
                               3115                 :                : 
 1849 andres@anarazel.de       3116                 :CBC      571865 :         case TM_Ok:
                               3117                 :                :             /* done successfully */
 8482 tgl@sss.pgh.pa.us        3118                 :         571865 :             break;
                               3119                 :                : 
 1849 andres@anarazel.de       3120                 :UBC           0 :         case TM_Updated:
 7573 tgl@sss.pgh.pa.us        3121         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently updated");
                               3122                 :                :             break;
                               3123                 :                : 
 1849 andres@anarazel.de       3124                 :              0 :         case TM_Deleted:
                               3125         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently deleted");
                               3126                 :                :             break;
                               3127                 :                : 
 8482 tgl@sss.pgh.pa.us        3128                 :              0 :         default:
 7573                          3129         [ #  # ]:              0 :             elog(ERROR, "unrecognized heap_delete status: %u", result);
                               3130                 :                :             break;
                               3131                 :                :     }
 8482 tgl@sss.pgh.pa.us        3132                 :CBC      571865 : }
                               3133                 :                : 
                               3134                 :                : /*
                               3135                 :                :  *  heap_update - replace a tuple
                               3136                 :                :  *
                               3137                 :                :  * See table_tuple_update() for an explanation of the parameters, except that
                               3138                 :                :  * this routine directly takes a tuple rather than a slot.
                               3139                 :                :  *
                               3140                 :                :  * In the failure cases, the routine fills *tmfd with the tuple's t_ctid,
                               3141                 :                :  * t_xmax (resolving a possible MultiXact, if necessary), and t_cmax (the last
                               3142                 :                :  * only for TM_SelfModified, since we cannot obtain cmax from a combo CID
                               3143                 :                :  * generated by another transaction).
                               3144                 :                :  */
                               3145                 :                : TM_Result
 8908 bruce@momjian.us         3146                 :         277144 : heap_update(Relation relation, ItemPointer otid, HeapTuple newtup,
                               3147                 :                :             CommandId cid, Snapshot crosscheck, bool wait,
                               3148                 :                :             TM_FailureData *tmfd, LockTupleMode *lockmode,
                               3149                 :                :             TU_UpdateIndexes *update_indexes)
                               3150                 :                : {
                               3151                 :                :     TM_Result   result;
 7150 tgl@sss.pgh.pa.us        3152                 :         277144 :     TransactionId xid = GetCurrentTransactionId();
                               3153                 :                :     Bitmapset  *hot_attrs;
                               3154                 :                :     Bitmapset  *sum_attrs;
                               3155                 :                :     Bitmapset  *key_attrs;
                               3156                 :                :     Bitmapset  *id_attrs;
                               3157                 :                :     Bitmapset  *interesting_attrs;
                               3158                 :                :     Bitmapset  *modified_attrs;
                               3159                 :                :     ItemId      lp;
                               3160                 :                :     HeapTupleData oldtup;
                               3161                 :                :     HeapTuple   heaptup;
 3778 rhaas@postgresql.org     3162                 :         277144 :     HeapTuple   old_key_tuple = NULL;
                               3163                 :         277144 :     bool        old_key_copied = false;
                               3164                 :                :     Page        page;
                               3165                 :                :     BlockNumber block;
                               3166                 :                :     MultiXactStatus mxact_status;
                               3167                 :                :     Buffer      buffer,
                               3168                 :                :                 newbuf,
 4681                          3169                 :         277144 :                 vmbuffer = InvalidBuffer,
                               3170                 :         277144 :                 vmbuffer_new = InvalidBuffer;
                               3171                 :                :     bool        need_toast;
                               3172                 :                :     Size        newtupsize,
                               3173                 :                :                 pagefree;
 6924 tgl@sss.pgh.pa.us        3174                 :         277144 :     bool        have_tuple_lock = false;
                               3175                 :                :     bool        iscombo;
 6051                          3176                 :         277144 :     bool        use_hot_update = false;
  391 tomas.vondra@postgre     3177                 :         277144 :     bool        summarized_update = false;
                               3178                 :                :     bool        key_intact;
 5611 heikki.linnakangas@i     3179                 :         277144 :     bool        all_visible_cleared = false;
                               3180                 :         277144 :     bool        all_visible_cleared_new = false;
                               3181                 :                :     bool        checked_lockers;
                               3182                 :                :     bool        locker_remains;
  790 akapila@postgresql.o     3183                 :         277144 :     bool        id_has_external = false;
                               3184                 :                :     TransactionId xmax_new_tuple,
                               3185                 :                :                 xmax_old_tuple;
                               3186                 :                :     uint16      infomask_old_tuple,
                               3187                 :                :                 infomask2_old_tuple,
                               3188                 :                :                 infomask_new_tuple,
                               3189                 :                :                 infomask2_new_tuple;
                               3190                 :                : 
 9716 bruce@momjian.us         3191         [ -  + ]:         277144 :     Assert(ItemPointerIsValid(otid));
                               3192                 :                : 
                               3193                 :                :     /* Cheap, simplistic check that the tuple matches the rel's rowtype. */
 1070 tgl@sss.pgh.pa.us        3194         [ -  + ]:         277144 :     Assert(HeapTupleHeaderGetNatts(newtup->t_data) <=
                               3195                 :                :            RelationGetNumberOfAttributes(relation));
                               3196                 :                : 
                               3197                 :                :     /*
                               3198                 :                :      * Forbid this during a parallel operation, lest it allocate a combo CID.
                               3199                 :                :      * Other workers might need that combo CID for visibility checks, and we
                               3200                 :                :      * have no provision for broadcasting it to them.
                               3201                 :                :      */
 3272 rhaas@postgresql.org     3202         [ -  + ]:         277144 :     if (IsInParallelMode())
 3272 rhaas@postgresql.org     3203         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3204                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               3205                 :                :                  errmsg("cannot update tuples during a parallel operation")));
                               3206                 :                : 
                               3207                 :                :     /*
                               3208                 :                :      * Fetch the list of attributes to be checked for various operations.
                               3209                 :                :      *
                               3210                 :                :      * For HOT considerations, this is wasted effort if we fail to update or
                               3211                 :                :      * have to put the new tuple on a different page.  But we must compute the
                               3212                 :                :      * list before obtaining buffer lock --- in the worst case, if we are
                               3213                 :                :      * doing an update on one of the relevant system catalogs, we could
                               3214                 :                :      * deadlock if we try to fetch the list later.  In any case, the relcache
                               3215                 :                :      * caches the data so this is usually pretty cheap.
                               3216                 :                :      *
                               3217                 :                :      * We also need columns used by the replica identity and columns that are
                               3218                 :                :      * considered the "key" of rows in the table.
                               3219                 :                :      *
                               3220                 :                :      * Note that we get copies of each bitmap, so we need not worry about
                               3221                 :                :      * relcache flush happening midway through.
                               3222                 :                :      */
  391 tomas.vondra@postgre     3223                 :CBC      277144 :     hot_attrs = RelationGetIndexAttrBitmap(relation,
                               3224                 :                :                                            INDEX_ATTR_BITMAP_HOT_BLOCKING);
                               3225                 :         277144 :     sum_attrs = RelationGetIndexAttrBitmap(relation,
                               3226                 :                :                                            INDEX_ATTR_BITMAP_SUMMARIZED);
 3778 rhaas@postgresql.org     3227                 :         277144 :     key_attrs = RelationGetIndexAttrBitmap(relation, INDEX_ATTR_BITMAP_KEY);
                               3228                 :         277144 :     id_attrs = RelationGetIndexAttrBitmap(relation,
                               3229                 :                :                                           INDEX_ATTR_BITMAP_IDENTITY_KEY);
  870 pg@bowt.ie               3230                 :         277144 :     interesting_attrs = NULL;
                               3231                 :         277144 :     interesting_attrs = bms_add_members(interesting_attrs, hot_attrs);
  391 tomas.vondra@postgre     3232                 :         277144 :     interesting_attrs = bms_add_members(interesting_attrs, sum_attrs);
  870 pg@bowt.ie               3233                 :         277144 :     interesting_attrs = bms_add_members(interesting_attrs, key_attrs);
                               3234                 :         277144 :     interesting_attrs = bms_add_members(interesting_attrs, id_attrs);
                               3235                 :                : 
 4681 rhaas@postgresql.org     3236                 :         277144 :     block = ItemPointerGetBlockNumber(otid);
                               3237                 :         277144 :     buffer = ReadBuffer(relation, block);
 2916 kgrittn@postgresql.o     3238                 :         277144 :     page = BufferGetPage(buffer);
                               3239                 :                : 
                               3240                 :                :     /*
                               3241                 :                :      * Before locking the buffer, pin the visibility map page if it appears to
                               3242                 :                :      * be necessary.  Since we haven't got the lock yet, someone else might be
                               3243                 :                :      * in the middle of changing this, so we'll need to recheck after we have
                               3244                 :                :      * the lock.
                               3245                 :                :      */
 4681 rhaas@postgresql.org     3246         [ +  + ]:         277144 :     if (PageIsAllVisible(page))
                               3247                 :           1176 :         visibilitymap_pin(relation, block, &vmbuffer);
                               3248                 :                : 
 9252 vadim4o@yahoo.com        3249                 :         277144 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               3250                 :                : 
 5754 tgl@sss.pgh.pa.us        3251                 :         277144 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(otid));
 6059                          3252         [ -  + ]:         277144 :     Assert(ItemIdIsNormal(lp));
                               3253                 :                : 
                               3254                 :                :     /*
                               3255                 :                :      * Fill in enough data in oldtup for HeapDetermineColumnsInfo to work
                               3256                 :                :      * properly.
                               3257                 :                :      */
 4090 alvherre@alvh.no-ip.     3258                 :         277144 :     oldtup.t_tableOid = RelationGetRelid(relation);
 5754 tgl@sss.pgh.pa.us        3259                 :         277144 :     oldtup.t_data = (HeapTupleHeader) PageGetItem(page, lp);
 9270 vadim4o@yahoo.com        3260                 :         277144 :     oldtup.t_len = ItemIdGetLength(lp);
                               3261                 :         277144 :     oldtup.t_self = *otid;
                               3262                 :                : 
                               3263                 :                :     /* the new tuple is ready, except for this: */
 4090 alvherre@alvh.no-ip.     3264                 :         277144 :     newtup->t_tableOid = RelationGetRelid(relation);
                               3265                 :                : 
                               3266                 :                :     /*
                               3267                 :                :      * Determine columns modified by the update.  Additionally, identify
                               3268                 :                :      * whether any of the unmodified replica identity key attributes in the
                               3269                 :                :      * old tuple is externally stored or not.  This is required because for
                               3270                 :                :      * such attributes the flattened value won't be WAL logged as part of the
                               3271                 :                :      * new tuple so we must include it as part of the old_key_tuple.  See
                               3272                 :                :      * ExtractReplicaIdentity.
                               3273                 :                :      */
  790 akapila@postgresql.o     3274                 :         277144 :     modified_attrs = HeapDetermineColumnsInfo(relation, interesting_attrs,
                               3275                 :                :                                               id_attrs, &oldtup,
                               3276                 :                :                                               newtup, &id_has_external);
                               3277                 :                : 
                               3278                 :                :     /*
                               3279                 :                :      * If we're not updating any "key" column, we can grab a weaker lock type.
                               3280                 :                :      * This allows for more concurrency when we are running simultaneously
                               3281                 :                :      * with foreign key checks.
                               3282                 :                :      *
                               3283                 :                :      * Note that if a column gets detoasted while executing the update, but
                               3284                 :                :      * the value ends up being the same, this test will fail and we will use
                               3285                 :                :      * the stronger lock.  This is acceptable; the important case to optimize
                               3286                 :                :      * is updates that don't manipulate key columns, not those that
                               3287                 :                :      * serendipitously arrive at the same key values.
                               3288                 :                :      */
 2573 alvherre@alvh.no-ip.     3289         [ +  + ]:         277144 :     if (!bms_overlap(modified_attrs, key_attrs))
                               3290                 :                :     {
 2194 simon@2ndQuadrant.co     3291                 :         273387 :         *lockmode = LockTupleNoKeyExclusive;
 4099 alvherre@alvh.no-ip.     3292                 :         273387 :         mxact_status = MultiXactStatusNoKeyUpdate;
                               3293                 :         273387 :         key_intact = true;
                               3294                 :                : 
                               3295                 :                :         /*
                               3296                 :                :          * If this is the first possibly-multixact-able operation in the
                               3297                 :                :          * current transaction, set my per-backend OldestMemberMXactId
                               3298                 :                :          * setting. We can be certain that the transaction will never become a
                               3299                 :                :          * member of any older MultiXactIds than that.  (We have to do this
                               3300                 :                :          * even if we end up just using our own TransactionId below, since
                               3301                 :                :          * some other backend could incorporate our XID into a MultiXact
                               3302                 :                :          * immediately afterwards.)
                               3303                 :                :          */
                               3304                 :         273387 :         MultiXactIdSetOldestMember();
                               3305                 :                :     }
                               3306                 :                :     else
                               3307                 :                :     {
 2194 simon@2ndQuadrant.co     3308                 :           3757 :         *lockmode = LockTupleExclusive;
 4099 alvherre@alvh.no-ip.     3309                 :           3757 :         mxact_status = MultiXactStatusUpdate;
                               3310                 :           3757 :         key_intact = false;
                               3311                 :                :     }
                               3312                 :                : 
                               3313                 :                :     /*
                               3314                 :                :      * Note: beyond this point, use oldtup not otid to refer to old tuple.
                               3315                 :                :      * otid may very well point at newtup->t_self, which we will overwrite
                               3316                 :                :      * with the new tuple's location, so there's great risk of confusion if we
                               3317                 :                :      * use otid anymore.
                               3318                 :                :      */
                               3319                 :                : 
 9252 vadim4o@yahoo.com        3320                 :              1 : l2:
 4099 alvherre@alvh.no-ip.     3321                 :         277145 :     checked_lockers = false;
                               3322                 :         277145 :     locker_remains = false;
 3919 rhaas@postgresql.org     3323                 :         277145 :     result = HeapTupleSatisfiesUpdate(&oldtup, cid, buffer);
                               3324                 :                : 
                               3325                 :                :     /* see below about the "no wait" case */
    3 akorotkov@postgresql     3326   [ +  +  -  + ]:         277145 :     Assert(result != TM_BeingModified || wait);
                               3327                 :                : 
 1849 andres@anarazel.de       3328         [ -  + ]:         277145 :     if (result == TM_Invisible)
                               3329                 :                :     {
 6589 tgl@sss.pgh.pa.us        3330                 :UBC           0 :         UnlockReleaseBuffer(buffer);
 3178                          3331         [ #  # ]:              0 :         ereport(ERROR,
                               3332                 :                :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                               3333                 :                :                  errmsg("attempted to update invisible tuple")));
                               3334                 :                :     }
    3 akorotkov@postgresql     3335   [ +  +  +  - ]:CBC      277145 :     else if (result == TM_BeingModified && wait)
                               3336                 :                :     {
                               3337                 :                :         TransactionId xwait;
                               3338                 :                :         uint16      infomask;
 4099 alvherre@alvh.no-ip.     3339                 :          35904 :         bool        can_continue = false;
                               3340                 :                : 
                               3341                 :                :         /*
                               3342                 :                :          * XXX note that we don't consider the "no wait" case here.  This
                               3343                 :                :          * isn't a problem currently because no caller uses that case, but it
                               3344                 :                :          * should be fixed if such a caller is introduced.  It wasn't a
                               3345                 :                :          * problem previously because this code would always wait, but now
                               3346                 :                :          * that some tuple locks do not conflict with one of the lock modes we
                               3347                 :                :          * use, it is possible that this case is interesting to handle
                               3348                 :                :          * specially.
                               3349                 :                :          *
                               3350                 :                :          * This may cause failures with third-party code that calls
                               3351                 :                :          * heap_update directly.
                               3352                 :                :          */
                               3353                 :                : 
                               3354                 :                :         /* must copy state data before unlocking buffer */
                               3355                 :          35904 :         xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data);
 6924 tgl@sss.pgh.pa.us        3356                 :          35904 :         infomask = oldtup.t_data->t_infomask;
                               3357                 :                : 
                               3358                 :                :         /*
                               3359                 :                :          * Now we have to do something about the existing locker.  If it's a
                               3360                 :                :          * multi, sleep on it; we might be awakened before it is completely
                               3361                 :                :          * gone (or even not sleep at all in some cases); we need to preserve
                               3362                 :                :          * it as locker, unless it is gone completely.
                               3363                 :                :          *
                               3364                 :                :          * If it's not a multi, we need to check for sleeping conditions
                               3365                 :                :          * before actually going to sleep.  If the update doesn't conflict
                               3366                 :                :          * with the locks, we just continue without sleeping (but making sure
                               3367                 :                :          * it is preserved).
                               3368                 :                :          *
                               3369                 :                :          * Before sleeping, we need to acquire tuple lock to establish our
                               3370                 :                :          * priority for the tuple (see heap_lock_tuple).  LockTuple will
                               3371                 :                :          * release us when we are next-in-line for the tuple.  Note we must
                               3372                 :                :          * not acquire the tuple lock until we're sure we're going to sleep;
                               3373                 :                :          * otherwise we're open for race conditions with other transactions
                               3374                 :                :          * holding the tuple lock which sleep on us.
                               3375                 :                :          *
                               3376                 :                :          * If we are forced to "start over" below, we keep the tuple lock;
                               3377                 :                :          * this arranges that we stay at the head of the line while rechecking
                               3378                 :                :          * tuple state.
                               3379                 :                :          */
 6926                          3380         [ +  + ]:          35904 :         if (infomask & HEAP_XMAX_IS_MULTI)
                               3381                 :                :         {
                               3382                 :                :             TransactionId update_xact;
                               3383                 :                :             int         remain;
 1762 alvherre@alvh.no-ip.     3384                 :             60 :             bool        current_is_member = false;
                               3385                 :                : 
 3292                          3386         [ +  + ]:             60 :             if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               3387                 :                :                                         *lockmode, &current_is_member))
                               3388                 :                :             {
                               3389                 :              8 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3390                 :                : 
                               3391                 :                :                 /*
                               3392                 :                :                  * Acquire the lock, if necessary (but skip it when we're
                               3393                 :                :                  * requesting a lock and already have one; avoids deadlock).
                               3394                 :                :                  */
 1762                          3395         [ -  + ]:              8 :                 if (!current_is_member)
 1762 alvherre@alvh.no-ip.     3396                 :UBC           0 :                     heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
                               3397                 :                :                                          LockWaitBlock, &have_tuple_lock);
                               3398                 :                : 
                               3399                 :                :                 /* wait for multixact */
 3292 alvherre@alvh.no-ip.     3400                 :CBC           8 :                 MultiXactIdWait((MultiXactId) xwait, mxact_status, infomask,
                               3401                 :                :                                 relation, &oldtup.t_self, XLTW_Update,
                               3402                 :                :                                 &remain);
                               3403                 :              8 :                 checked_lockers = true;
                               3404                 :              8 :                 locker_remains = remain != 0;
                               3405                 :              8 :                 LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               3406                 :                : 
                               3407                 :                :                 /*
                               3408                 :                :                  * If xwait had just locked the tuple then some other xact
                               3409                 :                :                  * could update this tuple before we get to this point.  Check
                               3410                 :                :                  * for xmax change, and start over if so.
                               3411                 :                :                  */
                               3412         [ +  - ]:              8 :                 if (xmax_infomask_changed(oldtup.t_data->t_infomask,
                               3413                 :              8 :                                           infomask) ||
 2489 tgl@sss.pgh.pa.us        3414         [ -  + ]:              8 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3415                 :                :                                          xwait))
 3292 alvherre@alvh.no-ip.     3416                 :UBC           0 :                     goto l2;
                               3417                 :                :             }
                               3418                 :                : 
                               3419                 :                :             /*
                               3420                 :                :              * Note that the multixact may not be done by now.  It could have
                               3421                 :                :              * surviving members; our own xact or other subxacts of this
                               3422                 :                :              * backend, and also any other concurrent transaction that locked
                               3423                 :                :              * the tuple with LockTupleKeyShare if we only got
                               3424                 :                :              * LockTupleNoKeyExclusive.  If this is the case, we have to be
                               3425                 :                :              * careful to mark the updated tuple with the surviving members in
                               3426                 :                :              * Xmax.
                               3427                 :                :              *
                               3428                 :                :              * Note that there could have been another update in the
                               3429                 :                :              * MultiXact. In that case, we need to check whether it committed
                               3430                 :                :              * or aborted. If it aborted we are safe to update it again;
                               3431                 :                :              * otherwise there is an update conflict, and we have to return
                               3432                 :                :              * TableTuple{Deleted, Updated} below.
                               3433                 :                :              *
                               3434                 :                :              * In the LockTupleExclusive case, we still need to preserve the
                               3435                 :                :              * surviving members: those would include the tuple locks we had
                               3436                 :                :              * before this one, which are important to keep in case this
                               3437                 :                :              * subxact aborts.
                               3438                 :                :              */
 4099 alvherre@alvh.no-ip.     3439   [ +  +  +  - ]:CBC          60 :             if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask))
                               3440                 :              8 :                 update_xact = HeapTupleGetUpdateXid(oldtup.t_data);
                               3441                 :                :             else
 3292                          3442                 :             52 :                 update_xact = InvalidTransactionId;
                               3443                 :                : 
                               3444                 :                :             /*
                               3445                 :                :              * There was no UPDATE in the MultiXact; or it aborted. No
                               3446                 :                :              * TransactionIdIsInProgress() call needed here, since we called
                               3447                 :                :              * MultiXactIdWait() above.
                               3448                 :                :              */
 4099                          3449   [ +  +  +  + ]:             68 :             if (!TransactionIdIsValid(update_xact) ||
                               3450                 :              8 :                 TransactionIdDidAbort(update_xact))
                               3451                 :             53 :                 can_continue = true;
                               3452                 :                :         }
 3292                          3453         [ +  + ]:          35844 :         else if (TransactionIdIsCurrentTransactionId(xwait))
                               3454                 :                :         {
                               3455                 :                :             /*
                               3456                 :                :              * The only locker is ourselves; we can avoid grabbing the tuple
                               3457                 :                :              * lock here, but must preserve our locking information.
                               3458                 :                :              */
                               3459                 :          35753 :             checked_lockers = true;
                               3460                 :          35753 :             locker_remains = true;
                               3461                 :          35753 :             can_continue = true;
                               3462                 :                :         }
                               3463   [ +  +  +  + ]:             91 :         else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact)
                               3464                 :                :         {
                               3465                 :                :             /*
                               3466                 :                :              * If it's just a key-share locker, and we're not changing the key
                               3467                 :                :              * columns, we don't need to wait for it to end; but we need to
                               3468                 :                :              * preserve it as locker.
                               3469                 :                :              */
                               3470                 :             29 :             checked_lockers = true;
                               3471                 :             29 :             locker_remains = true;
                               3472                 :             29 :             can_continue = true;
                               3473                 :                :         }
                               3474                 :                :         else
                               3475                 :                :         {
                               3476                 :                :             /*
                               3477                 :                :              * Wait for regular transaction to end; but first, acquire tuple
                               3478                 :                :              * lock.
                               3479                 :                :              */
                               3480                 :             62 :             LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
 2194 simon@2ndQuadrant.co     3481                 :             62 :             heap_acquire_tuplock(relation, &(oldtup.t_self), *lockmode,
                               3482                 :                :                                  LockWaitBlock, &have_tuple_lock);
 3292 alvherre@alvh.no-ip.     3483                 :             62 :             XactLockTableWait(xwait, relation, &oldtup.t_self,
                               3484                 :                :                               XLTW_Update);
                               3485                 :             62 :             checked_lockers = true;
                               3486                 :             62 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               3487                 :                : 
                               3488                 :                :             /*
                               3489                 :                :              * xwait is done, but if xwait had just locked the tuple then some
                               3490                 :                :              * other xact could update this tuple before we get to this point.
                               3491                 :                :              * Check for xmax change, and start over if so.
                               3492                 :                :              */
                               3493         [ +  + ]:             62 :             if (xmax_infomask_changed(oldtup.t_data->t_infomask, infomask) ||
                               3494         [ -  + ]:             61 :                 !TransactionIdEquals(xwait,
                               3495                 :                :                                      HeapTupleHeaderGetRawXmax(oldtup.t_data)))
                               3496                 :              1 :                 goto l2;
                               3497                 :                : 
                               3498                 :                :             /* Otherwise check if it committed or aborted */
                               3499                 :             61 :             UpdateXmaxHintBits(oldtup.t_data, buffer, xwait);
                               3500         [ +  + ]:             61 :             if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID)
 4099                          3501                 :             12 :                 can_continue = true;
                               3502                 :                :         }
                               3503                 :                : 
 1849 andres@anarazel.de       3504         [ +  + ]:          35903 :         if (can_continue)
                               3505                 :          35847 :             result = TM_Ok;
 1147 alvherre@alvh.no-ip.     3506         [ +  + ]:             56 :         else if (!ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid))
 1849 andres@anarazel.de       3507                 :             51 :             result = TM_Updated;
                               3508                 :                :         else
                               3509                 :              5 :             result = TM_Deleted;
                               3510                 :                :     }
                               3511                 :                : 
                               3512                 :                :     /* Sanity check the result HeapTupleSatisfiesUpdate() and the logic above */
                               3513         [ +  + ]:         277144 :     if (result != TM_Ok)
                               3514                 :                :     {
                               3515   [ +  +  +  +  :            153 :         Assert(result == TM_SelfModified ||
                                        -  +  -  - ]
                               3516                 :                :                result == TM_Updated ||
                               3517                 :                :                result == TM_Deleted ||
                               3518                 :                :                result == TM_BeingModified);
 6812 tgl@sss.pgh.pa.us        3519         [ -  + ]:            153 :         Assert(!(oldtup.t_data->t_infomask & HEAP_XMAX_INVALID));
 1849 andres@anarazel.de       3520   [ +  +  -  + ]:            153 :         Assert(result != TM_Updated ||
                               3521                 :                :                !ItemPointerEquals(&oldtup.t_self, &oldtup.t_data->t_ctid));
                               3522                 :                :     }
                               3523                 :                : 
  138 heikki.linnakangas@i     3524   [ +  +  +  - ]:         277144 :     if (crosscheck != InvalidSnapshot && result == TM_Ok)
                               3525                 :                :     {
                               3526                 :                :         /* Perform additional check for transaction-snapshot mode RI updates */
                               3527         [ +  - ]:              1 :         if (!HeapTupleSatisfiesVisibility(&oldtup, crosscheck, buffer))
                               3528                 :              1 :             result = TM_Updated;
                               3529                 :                :     }
                               3530                 :                : 
                               3531         [ +  + ]:         277144 :     if (result != TM_Ok)
                               3532                 :                :     {
 1849 andres@anarazel.de       3533                 :            154 :         tmfd->ctid = oldtup.t_data->t_ctid;
                               3534   [ +  +  +  +  :            154 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(oldtup.t_data);
                                              +  - ]
                               3535         [ +  + ]:            154 :         if (result == TM_SelfModified)
                               3536                 :             52 :             tmfd->cmax = HeapTupleHeaderGetCmax(oldtup.t_data);
                               3537                 :                :         else
                               3538                 :            102 :             tmfd->cmax = InvalidCommandId;
    3 akorotkov@postgresql     3539                 :            154 :         UnlockReleaseBuffer(buffer);
 6924 tgl@sss.pgh.pa.us        3540         [ +  + ]:            154 :         if (have_tuple_lock)
 2194 simon@2ndQuadrant.co     3541                 :             49 :             UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
 4681 rhaas@postgresql.org     3542         [ -  + ]:            154 :         if (vmbuffer != InvalidBuffer)
 4681 rhaas@postgresql.org     3543                 :UBC           0 :             ReleaseBuffer(vmbuffer);
  391 tomas.vondra@postgre     3544                 :CBC         154 :         *update_indexes = TU_None;
                               3545                 :                : 
 6051 tgl@sss.pgh.pa.us        3546                 :            154 :         bms_free(hot_attrs);
  391 tomas.vondra@postgre     3547                 :            154 :         bms_free(sum_attrs);
 4099 alvherre@alvh.no-ip.     3548                 :            154 :         bms_free(key_attrs);
 2790 tgl@sss.pgh.pa.us        3549                 :            154 :         bms_free(id_attrs);
 2573 alvherre@alvh.no-ip.     3550                 :            154 :         bms_free(modified_attrs);
                               3551                 :            154 :         bms_free(interesting_attrs);
 9252 vadim4o@yahoo.com        3552                 :            154 :         return result;
                               3553                 :                :     }
                               3554                 :                : 
                               3555                 :                :     /*
                               3556                 :                :      * If we didn't pin the visibility map page and the page has become all
                               3557                 :                :      * visible while we were busy locking the buffer, or during some
                               3558                 :                :      * subsequent window during which we had it unlocked, we'll have to unlock
                               3559                 :                :      * and re-lock, to avoid holding the buffer lock across an I/O.  That's a
                               3560                 :                :      * bit unfortunate, especially since we'll now have to recheck whether the
                               3561                 :                :      * tuple has been locked or updated under us, but hopefully it won't
                               3562                 :                :      * happen very often.
                               3563                 :                :      */
 4675 rhaas@postgresql.org     3564   [ +  +  -  + ]:         276990 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               3565                 :                :     {
 4675 rhaas@postgresql.org     3566                 :UBC           0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3567                 :              0 :         visibilitymap_pin(relation, block, &vmbuffer);
                               3568                 :              0 :         LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
 4583                          3569                 :              0 :         goto l2;
                               3570                 :                :     }
                               3571                 :                : 
                               3572                 :                :     /* Fill in transaction status data */
                               3573                 :                : 
                               3574                 :                :     /*
                               3575                 :                :      * If the tuple we're updating is locked, we need to preserve the locking
                               3576                 :                :      * info in the old tuple's Xmax.  Prepare a new Xmax value for this.
                               3577                 :                :      */
 4099 alvherre@alvh.no-ip.     3578                 :CBC      276990 :     compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3579                 :         276990 :                               oldtup.t_data->t_infomask,
                               3580                 :         276990 :                               oldtup.t_data->t_infomask2,
                               3581                 :                :                               xid, *lockmode, true,
                               3582                 :                :                               &xmax_old_tuple, &infomask_old_tuple,
                               3583                 :                :                               &infomask2_old_tuple);
                               3584                 :                : 
                               3585                 :                :     /*
                               3586                 :                :      * And also prepare an Xmax value for the new copy of the tuple.  If there
                               3587                 :                :      * was no xmax previously, or there was one but all lockers are now gone,
                               3588                 :                :      * then use InvalidTransactionId; otherwise, get the xmax from the old
                               3589                 :                :      * tuple.  (In rare cases that might also be InvalidTransactionId and yet
                               3590                 :                :      * not have the HEAP_XMAX_INVALID bit set; that's fine.)
                               3591                 :                :      */
                               3592         [ +  + ]:         276990 :     if ((oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) ||
 2851                          3593   [ +  +  +  +  :          35835 :         HEAP_LOCKED_UPGRADED(oldtup.t_data->t_infomask) ||
                                        +  -  +  + ]
 4099                          3594         [ -  + ]:          35783 :         (checked_lockers && !locker_remains))
                               3595                 :         241155 :         xmax_new_tuple = InvalidTransactionId;
                               3596                 :                :     else
                               3597                 :          35835 :         xmax_new_tuple = HeapTupleHeaderGetRawXmax(oldtup.t_data);
                               3598                 :                : 
                               3599         [ +  + ]:         276990 :     if (!TransactionIdIsValid(xmax_new_tuple))
                               3600                 :                :     {
                               3601                 :         241155 :         infomask_new_tuple = HEAP_XMAX_INVALID;
                               3602                 :         241155 :         infomask2_new_tuple = 0;
                               3603                 :                :     }
                               3604                 :                :     else
                               3605                 :                :     {
                               3606                 :                :         /*
                               3607                 :                :          * If we found a valid Xmax for the new tuple, then the infomask bits
                               3608                 :                :          * to use on the new tuple depend on what was there on the old one.
                               3609                 :                :          * Note that since we're doing an update, the only possibility is that
                               3610                 :                :          * the lockers had FOR KEY SHARE lock.
                               3611                 :                :          */
                               3612         [ +  + ]:          35835 :         if (oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI)
                               3613                 :                :         {
                               3614                 :             53 :             GetMultiXactIdHintBits(xmax_new_tuple, &infomask_new_tuple,
                               3615                 :                :                                    &infomask2_new_tuple);
                               3616                 :                :         }
                               3617                 :                :         else
                               3618                 :                :         {
                               3619                 :          35782 :             infomask_new_tuple = HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_LOCK_ONLY;
                               3620                 :          35782 :             infomask2_new_tuple = 0;
                               3621                 :                :         }
                               3622                 :                :     }
                               3623                 :                : 
                               3624                 :                :     /*
                               3625                 :                :      * Prepare the new tuple with the appropriate initial values of Xmin and
                               3626                 :                :      * Xmax, as well as initial infomask bits as computed above.
                               3627                 :                :      */
 9270 vadim4o@yahoo.com        3628                 :         276990 :     newtup->t_data->t_infomask &= ~(HEAP_XACT_MASK);
 6051 tgl@sss.pgh.pa.us        3629                 :         276990 :     newtup->t_data->t_infomask2 &= ~(HEAP2_XACT_MASK);
 7150                          3630                 :         276990 :     HeapTupleHeaderSetXmin(newtup->t_data, xid);
 7974 bruce@momjian.us         3631         [ -  + ]:         276990 :     HeapTupleHeaderSetCmin(newtup->t_data, cid);
 4099 alvherre@alvh.no-ip.     3632                 :         276990 :     newtup->t_data->t_infomask |= HEAP_UPDATED | infomask_new_tuple;
                               3633                 :         276990 :     newtup->t_data->t_infomask2 |= infomask2_new_tuple;
                               3634                 :         276990 :     HeapTupleHeaderSetXmax(newtup->t_data, xmax_new_tuple);
                               3635                 :                : 
                               3636                 :                :     /*
                               3637                 :                :      * Replace cid with a combo CID if necessary.  Note that we already put
                               3638                 :                :      * the plain cid into the new tuple.
                               3639                 :                :      */
 6274 tgl@sss.pgh.pa.us        3640                 :         276990 :     HeapTupleHeaderAdjustCmax(oldtup.t_data, &cid, &iscombo);
                               3641                 :                : 
                               3642                 :                :     /*
                               3643                 :                :      * If the toaster needs to be activated, OR if the new tuple will not fit
                               3644                 :                :      * on the same page as the old, then we need to release the content lock
                               3645                 :                :      * (but not the pin!) on the old tuple's buffer while we are off doing
                               3646                 :                :      * TOAST and/or table-file-extension work.  We must mark the old tuple to
                               3647                 :                :      * show that it's locked, else other processes may try to update it
                               3648                 :                :      * themselves.
                               3649                 :                :      *
                               3650                 :                :      * We need to invoke the toaster if there are already any out-of-line
                               3651                 :                :      * toasted values present, or if the new tuple is over-threshold.
                               3652                 :                :      */
 4060 kgrittn@postgresql.o     3653         [ -  + ]:         276990 :     if (relation->rd_rel->relkind != RELKIND_RELATION &&
 4060 kgrittn@postgresql.o     3654         [ #  # ]:UBC           0 :         relation->rd_rel->relkind != RELKIND_MATVIEW)
                               3655                 :                :     {
                               3656                 :                :         /* toast table entries should never be recursively toasted */
 6221 tgl@sss.pgh.pa.us        3657         [ #  # ]:              0 :         Assert(!HeapTupleHasExternal(&oldtup));
                               3658         [ #  # ]:              0 :         Assert(!HeapTupleHasExternal(newtup));
                               3659                 :              0 :         need_toast = false;
                               3660                 :                :     }
                               3661                 :                :     else
 6221 tgl@sss.pgh.pa.us        3662                 :CBC      276990 :         need_toast = (HeapTupleHasExternal(&oldtup) ||
                               3663   [ +  +  +  + ]:         553695 :                       HeapTupleHasExternal(newtup) ||
                               3664         [ +  + ]:         276705 :                       newtup->t_len > TOAST_TUPLE_THRESHOLD);
                               3665                 :                : 
 5754                          3666                 :         276990 :     pagefree = PageGetHeapFreeSpace(page);
                               3667                 :                : 
 6279                          3668                 :         276990 :     newtupsize = MAXALIGN(newtup->t_len);
                               3669                 :                : 
 8369                          3670   [ +  +  +  + ]:         276990 :     if (need_toast || newtupsize > pagefree)
 8620 vadim4o@yahoo.com        3671                 :         140457 :     {
                               3672                 :                :         TransactionId xmax_lock_old_tuple;
                               3673                 :                :         uint16      infomask_lock_old_tuple,
                               3674                 :                :                     infomask2_lock_old_tuple;
 2827 andres@anarazel.de       3675                 :         140457 :         bool        cleared_all_frozen = false;
                               3676                 :                : 
                               3677                 :                :         /*
                               3678                 :                :          * To prevent concurrent sessions from updating the tuple, we have to
                               3679                 :                :          * temporarily mark it locked, while we release the page-level lock.
                               3680                 :                :          *
                               3681                 :                :          * To satisfy the rule that any xid potentially appearing in a buffer
                               3682                 :                :          * written out to disk, we unfortunately have to WAL log this
                               3683                 :                :          * temporary modification.  We can reuse xl_heap_lock for this
                               3684                 :                :          * purpose.  If we crash/error before following through with the
                               3685                 :                :          * actual update, xmax will be of an aborted transaction, allowing
                               3686                 :                :          * other sessions to proceed.
                               3687                 :                :          */
                               3688                 :                : 
                               3689                 :                :         /*
                               3690                 :                :          * Compute xmax / infomask appropriate for locking the tuple. This has
                               3691                 :                :          * to be done separately from the combo that's going to be used for
                               3692                 :                :          * updating, because the potentially created multixact would otherwise
                               3693                 :                :          * be wrong.
                               3694                 :                :          */
 2830                          3695                 :         140457 :         compute_new_xmax_infomask(HeapTupleHeaderGetRawXmax(oldtup.t_data),
                               3696                 :         140457 :                                   oldtup.t_data->t_infomask,
                               3697                 :         140457 :                                   oldtup.t_data->t_infomask2,
                               3698                 :                :                                   xid, *lockmode, false,
                               3699                 :                :                                   &xmax_lock_old_tuple, &infomask_lock_old_tuple,
                               3700                 :                :                                   &infomask2_lock_old_tuple);
                               3701                 :                : 
                               3702   [ -  +  -  - ]:         140457 :         Assert(HEAP_XMAX_IS_LOCKED_ONLY(infomask_lock_old_tuple));
                               3703                 :                : 
                               3704                 :         140457 :         START_CRIT_SECTION();
                               3705                 :                : 
                               3706                 :                :         /* Clear obsolete visibility flags ... */
 4099 alvherre@alvh.no-ip.     3707                 :         140457 :         oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               3708                 :         140457 :         oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 6051 tgl@sss.pgh.pa.us        3709                 :         140457 :         HeapTupleClearHotUpdated(&oldtup);
                               3710                 :                :         /* ... and store info about transaction updating this tuple */
 2830 andres@anarazel.de       3711         [ -  + ]:         140457 :         Assert(TransactionIdIsValid(xmax_lock_old_tuple));
                               3712                 :         140457 :         HeapTupleHeaderSetXmax(oldtup.t_data, xmax_lock_old_tuple);
                               3713                 :         140457 :         oldtup.t_data->t_infomask |= infomask_lock_old_tuple;
                               3714                 :         140457 :         oldtup.t_data->t_infomask2 |= infomask2_lock_old_tuple;
 6274 tgl@sss.pgh.pa.us        3715   [ -  +  +  + ]:         140457 :         HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
                               3716                 :                : 
                               3717                 :                :         /* temporarily make it look not-updated, but locked */
 6720                          3718                 :         140457 :         oldtup.t_data->t_ctid = oldtup.t_self;
                               3719                 :                : 
                               3720                 :                :         /*
                               3721                 :                :          * Clear all-frozen bit on visibility map if needed. We could
                               3722                 :                :          * immediately reset ALL_VISIBLE, but given that the WAL logging
                               3723                 :                :          * overhead would be unchanged, that doesn't seem necessarily
                               3724                 :                :          * worthwhile.
                               3725                 :                :          */
 1097                          3726   [ +  +  +  + ]:         141097 :         if (PageIsAllVisible(page) &&
 2827 andres@anarazel.de       3727                 :            640 :             visibilitymap_clear(relation, block, vmbuffer,
                               3728                 :                :                                 VISIBILITYMAP_ALL_FROZEN))
                               3729                 :            465 :             cleared_all_frozen = true;
                               3730                 :                : 
 2830                          3731                 :         140457 :         MarkBufferDirty(buffer);
                               3732                 :                : 
                               3733   [ +  +  +  +  :         140457 :         if (RelationNeedsWAL(relation))
                                        +  -  +  + ]
                               3734                 :                :         {
                               3735                 :                :             xl_heap_lock xlrec;
                               3736                 :                :             XLogRecPtr  recptr;
                               3737                 :                : 
                               3738                 :         130325 :             XLogBeginInsert();
                               3739                 :         130325 :             XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               3740                 :                : 
                               3741                 :         130325 :             xlrec.offnum = ItemPointerGetOffsetNumber(&oldtup.t_self);
  369 pg@bowt.ie               3742                 :         130325 :             xlrec.xmax = xmax_lock_old_tuple;
 2830 andres@anarazel.de       3743                 :         260650 :             xlrec.infobits_set = compute_infobits(oldtup.t_data->t_infomask,
                               3744                 :         130325 :                                                   oldtup.t_data->t_infomask2);
 2827                          3745                 :         130325 :             xlrec.flags =
                               3746                 :         130325 :                 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
 2830                          3747                 :         130325 :             XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
                               3748                 :         130325 :             recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
                               3749                 :         130325 :             PageSetLSN(page, recptr);
                               3750                 :                :         }
                               3751                 :                : 
                               3752         [ -  + ]:         140457 :         END_CRIT_SECTION();
                               3753                 :                : 
 8620 vadim4o@yahoo.com        3754                 :         140457 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3755                 :                : 
                               3756                 :                :         /*
                               3757                 :                :          * Let the toaster do its thing, if needed.
                               3758                 :                :          *
                               3759                 :                :          * Note: below this point, heaptup is the data we actually intend to
                               3760                 :                :          * store into the relation; newtup is the caller's original untoasted
                               3761                 :                :          * data.
                               3762                 :                :          */
 8490 tgl@sss.pgh.pa.us        3763         [ +  + ]:         140457 :         if (need_toast)
                               3764                 :                :         {
                               3765                 :                :             /* Note we always use WAL and FSM during updates */
 1654 rhaas@postgresql.org     3766                 :           1096 :             heaptup = heap_toast_insert_or_update(relation, newtup, &oldtup, 0);
 6720 tgl@sss.pgh.pa.us        3767                 :           1096 :             newtupsize = MAXALIGN(heaptup->t_len);
                               3768                 :                :         }
                               3769                 :                :         else
                               3770                 :         139361 :             heaptup = newtup;
                               3771                 :                : 
                               3772                 :                :         /*
                               3773                 :                :          * Now, do we need a new page for the tuple, or not?  This is a bit
                               3774                 :                :          * tricky since someone else could have added tuples to the page while
                               3775                 :                :          * we weren't looking.  We have to recheck the available space after
                               3776                 :                :          * reacquiring the buffer lock.  But don't bother to do that if the
                               3777                 :                :          * former amount of free space is still not enough; it's unlikely
                               3778                 :                :          * there's more free now than before.
                               3779                 :                :          *
                               3780                 :                :          * What's more, if we need to get a new page, we will need to acquire
                               3781                 :                :          * buffer locks on both old and new pages.  To avoid deadlock against
                               3782                 :                :          * some other backend trying to get the same two locks in the other
                               3783                 :                :          * order, we must be consistent about the order we get the locks in.
                               3784                 :                :          * We use the rule "lock the lower-numbered page of the relation
                               3785                 :                :          * first".  To implement this, we must do RelationGetBufferForTuple
                               3786                 :                :          * while not holding the lock on the old page, and we must rely on it
                               3787                 :                :          * to get the locks on both pages in the correct order.
                               3788                 :                :          *
                               3789                 :                :          * Another consideration is that we need visibility map page pin(s) if
                               3790                 :                :          * we will have to clear the all-visible flag on either page.  If we
                               3791                 :                :          * call RelationGetBufferForTuple, we rely on it to acquire any such
                               3792                 :                :          * pins; but if we don't, we have to handle that here.  Hence we need
                               3793                 :                :          * a loop.
                               3794                 :                :          */
                               3795                 :                :         for (;;)
                               3796                 :                :         {
 1097                          3797         [ +  + ]:         140457 :             if (newtupsize > pagefree)
                               3798                 :                :             {
                               3799                 :                :                 /* It doesn't fit, must use RelationGetBufferForTuple. */
                               3800                 :         140150 :                 newbuf = RelationGetBufferForTuple(relation, heaptup->t_len,
                               3801                 :                :                                                    buffer, 0, NULL,
                               3802                 :                :                                                    &vmbuffer_new, &vmbuffer,
                               3803                 :                :                                                    0);
                               3804                 :                :                 /* We're all done. */
                               3805                 :         140150 :                 break;
                               3806                 :                :             }
                               3807                 :                :             /* Acquire VM page pin if needed and we don't have it. */
                               3808   [ +  +  -  + ]:            307 :             if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
 1097 tgl@sss.pgh.pa.us        3809                 :UBC           0 :                 visibilitymap_pin(relation, block, &vmbuffer);
                               3810                 :                :             /* Re-acquire the lock on the old tuple's page. */
 8369 tgl@sss.pgh.pa.us        3811                 :CBC         307 :             LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               3812                 :                :             /* Re-check using the up-to-date free space */
 5754                          3813                 :            307 :             pagefree = PageGetHeapFreeSpace(page);
 1097                          3814         [ +  - ]:            307 :             if (newtupsize > pagefree ||
                               3815   [ +  +  -  + ]:            307 :                 (vmbuffer == InvalidBuffer && PageIsAllVisible(page)))
                               3816                 :                :             {
                               3817                 :                :                 /*
                               3818                 :                :                  * Rats, it doesn't fit anymore, or somebody just now set the
                               3819                 :                :                  * all-visible flag.  We must now unlock and loop to avoid
                               3820                 :                :                  * deadlock.  Fortunately, this path should seldom be taken.
                               3821                 :                :                  */
 8369 tgl@sss.pgh.pa.us        3822                 :UBC           0 :                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               3823                 :                :             }
                               3824                 :                :             else
                               3825                 :                :             {
                               3826                 :                :                 /* We're all done. */
 8369 tgl@sss.pgh.pa.us        3827                 :CBC         307 :                 newbuf = buffer;
 1097                          3828                 :            307 :                 break;
                               3829                 :                :             }
                               3830                 :                :         }
                               3831                 :                :     }
                               3832                 :                :     else
                               3833                 :                :     {
                               3834                 :                :         /* No TOAST work needed, and it'll fit on same page */
 8490                          3835                 :         136533 :         newbuf = buffer;
 6720                          3836                 :         136533 :         heaptup = newtup;
                               3837                 :                :     }
                               3838                 :                : 
                               3839                 :                :     /*
                               3840                 :                :      * We're about to do the actual update -- check for conflict first, to
                               3841                 :                :      * avoid possibly having to roll back work we've just done.
                               3842                 :                :      *
                               3843                 :                :      * This is safe without a recheck as long as there is no possibility of
                               3844                 :                :      * another process scanning the pages between this check and the update
                               3845                 :                :      * being visible to the scan (i.e., exclusive buffer content lock(s) are
                               3846                 :                :      * continuously held from this point until the tuple update is visible).
                               3847                 :                :      *
                               3848                 :                :      * For the new tuple the only check needed is at the relation level, but
                               3849                 :                :      * since both tuples are in the same relation and the check for oldtup
                               3850                 :                :      * will include checking the relation level, there is no benefit to a
                               3851                 :                :      * separate check for the new tuple.
                               3852                 :                :      */
 1097 tmunro@postgresql.or     3853                 :         276990 :     CheckForSerializableConflictIn(relation, &oldtup.t_self,
                               3854                 :                :                                    BufferGetBlockNumber(buffer));
                               3855                 :                : 
                               3856                 :                :     /*
                               3857                 :                :      * At this point newbuf and buffer are both pinned and locked, and newbuf
                               3858                 :                :      * has enough space for the new tuple.  If they are the same buffer, only
                               3859                 :                :      * one pin is held.
                               3860                 :                :      */
                               3861                 :                : 
 6051 tgl@sss.pgh.pa.us        3862         [ +  + ]:         276978 :     if (newbuf == buffer)
                               3863                 :                :     {
                               3864                 :                :         /*
                               3865                 :                :          * Since the new tuple is going into the same page, we might be able
                               3866                 :                :          * to do a HOT update.  Check if any of the index columns have been
                               3867                 :                :          * changed.
                               3868                 :                :          */
  870 pg@bowt.ie               3869         [ +  + ]:         136828 :         if (!bms_overlap(modified_attrs, hot_attrs))
                               3870                 :                :         {
 6051 tgl@sss.pgh.pa.us        3871                 :         126107 :             use_hot_update = true;
                               3872                 :                : 
                               3873                 :                :             /*
                               3874                 :                :              * If none of the columns that are used in hot-blocking indexes
                               3875                 :                :              * were updated, we can apply HOT, but we do still need to check
                               3876                 :                :              * if we need to update the summarizing indexes, and update those
                               3877                 :                :              * indexes if the columns were updated, or we may fail to detect
                               3878                 :                :              * e.g. value bound changes in BRIN minmax indexes.
                               3879                 :                :              */
  391 tomas.vondra@postgre     3880         [ +  + ]:         126107 :             if (bms_overlap(modified_attrs, sum_attrs))
                               3881                 :           1641 :                 summarized_update = true;
                               3882                 :                :         }
                               3883                 :                :     }
                               3884                 :                :     else
                               3885                 :                :     {
                               3886                 :                :         /* Set a hint that the old page could use prune/defrag */
 5754 tgl@sss.pgh.pa.us        3887                 :         140150 :         PageSetFull(page);
                               3888                 :                :     }
                               3889                 :                : 
                               3890                 :                :     /*
                               3891                 :                :      * Compute replica identity tuple before entering the critical section so
                               3892                 :                :      * we don't PANIC upon a memory allocation failure.
                               3893                 :                :      * ExtractReplicaIdentity() will return NULL if nothing needs to be
                               3894                 :                :      * logged.  Pass old key required as true only if the replica identity key
                               3895                 :                :      * columns are modified or it has external data.
                               3896                 :                :      */
 2573 alvherre@alvh.no-ip.     3897                 :         276978 :     old_key_tuple = ExtractReplicaIdentity(relation, &oldtup,
  790 akapila@postgresql.o     3898   [ +  +  +  + ]:         276978 :                                            bms_overlap(modified_attrs, id_attrs) ||
                               3899                 :                :                                            id_has_external,
 2573 alvherre@alvh.no-ip.     3900                 :ECB    (424274) :                                            &old_key_copied);
                               3901                 :                : 
                               3902                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
 8493 tgl@sss.pgh.pa.us        3903                 :CBC      276978 :     START_CRIT_SECTION();
                               3904                 :                : 
                               3905                 :                :     /*
                               3906                 :                :      * If this transaction commits, the old tuple will become DEAD sooner or
                               3907                 :                :      * later.  Set flag that this page is a candidate for pruning once our xid
                               3908                 :                :      * falls below the OldestXmin horizon.  If the transaction finally aborts,
                               3909                 :                :      * the subsequent page pruning will be a no-op and the hint will be
                               3910                 :                :      * cleared.
                               3911                 :                :      *
                               3912                 :                :      * XXX Should we set hint on newbuf as well?  If the transaction aborts,
                               3913                 :                :      * there would be a prunable tuple in the newbuf; but for now we choose
                               3914                 :                :      * not to optimize for aborts.  Note that heap_xlog_update must be kept in
                               3915                 :                :      * sync if this decision changes.
                               3916                 :                :      */
 5754                          3917   [ -  +  +  +  :         276978 :     PageSetPrunable(page, xid);
                                              +  + ]
                               3918                 :                : 
 6051                          3919         [ +  + ]:         276978 :     if (use_hot_update)
                               3920                 :                :     {
                               3921                 :                :         /* Mark the old tuple as HOT-updated */
                               3922                 :         126107 :         HeapTupleSetHotUpdated(&oldtup);
                               3923                 :                :         /* And mark the new tuple as heap-only */
                               3924                 :         126107 :         HeapTupleSetHeapOnly(heaptup);
                               3925                 :                :         /* Mark the caller's copy too, in case different from heaptup */
                               3926                 :         126107 :         HeapTupleSetHeapOnly(newtup);
                               3927                 :                :     }
                               3928                 :                :     else
                               3929                 :                :     {
                               3930                 :                :         /* Make sure tuples are correctly marked as not-HOT */
                               3931                 :         150871 :         HeapTupleClearHotUpdated(&oldtup);
                               3932                 :         150871 :         HeapTupleClearHeapOnly(heaptup);
                               3933                 :         150871 :         HeapTupleClearHeapOnly(newtup);
                               3934                 :                :     }
                               3935                 :                : 
 2489                          3936                 :         276978 :     RelationPutHeapTuple(relation, newbuf, heaptup, false); /* insert new tuple */
                               3937                 :                : 
                               3938                 :                : 
                               3939                 :                :     /* Clear obsolete visibility flags, possibly set by ourselves above... */
 2830 andres@anarazel.de       3940                 :         276978 :     oldtup.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               3941                 :         276978 :     oldtup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               3942                 :                :     /* ... and store info about transaction updating this tuple */
                               3943         [ -  + ]:         276978 :     Assert(TransactionIdIsValid(xmax_old_tuple));
                               3944                 :         276978 :     HeapTupleHeaderSetXmax(oldtup.t_data, xmax_old_tuple);
                               3945                 :         276978 :     oldtup.t_data->t_infomask |= infomask_old_tuple;
                               3946                 :         276978 :     oldtup.t_data->t_infomask2 |= infomask2_old_tuple;
                               3947   [ -  +  +  + ]:         276978 :     HeapTupleHeaderSetCmax(oldtup.t_data, cid, iscombo);
                               3948                 :                : 
                               3949                 :                :     /* record address of new tuple in t_ctid of old one */
 6720 tgl@sss.pgh.pa.us        3950                 :         276978 :     oldtup.t_data->t_ctid = heaptup->t_self;
                               3951                 :                : 
                               3952                 :                :     /* clear PD_ALL_VISIBLE flags, reset all visibilitymap bits */
 2916 kgrittn@postgresql.o     3953         [ +  + ]:         276978 :     if (PageIsAllVisible(BufferGetPage(buffer)))
                               3954                 :                :     {
 5347 tgl@sss.pgh.pa.us        3955                 :           1176 :         all_visible_cleared = true;
 2916 kgrittn@postgresql.o     3956                 :           1176 :         PageClearAllVisible(BufferGetPage(buffer));
 4675 rhaas@postgresql.org     3957                 :           1176 :         visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
                               3958                 :                :                             vmbuffer, VISIBILITYMAP_VALID_BITS);
                               3959                 :                :     }
 2916 kgrittn@postgresql.o     3960   [ +  +  +  + ]:         276978 :     if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf)))
                               3961                 :                :     {
 5347 tgl@sss.pgh.pa.us        3962                 :            815 :         all_visible_cleared_new = true;
 2916 kgrittn@postgresql.o     3963                 :            815 :         PageClearAllVisible(BufferGetPage(newbuf));
 4675 rhaas@postgresql.org     3964                 :            815 :         visibilitymap_clear(relation, BufferGetBlockNumber(newbuf),
                               3965                 :                :                             vmbuffer_new, VISIBILITYMAP_VALID_BITS);
                               3966                 :                :     }
                               3967                 :                : 
 6589 tgl@sss.pgh.pa.us        3968         [ +  + ]:         276978 :     if (newbuf != buffer)
                               3969                 :         140150 :         MarkBufferDirty(newbuf);
                               3970                 :         276978 :     MarkBufferDirty(buffer);
                               3971                 :                : 
                               3972                 :                :     /* XLOG stuff */
 4871 rhaas@postgresql.org     3973   [ +  +  +  +  :         276978 :     if (RelationNeedsWAL(relation))
                                        +  +  +  + ]
                               3974                 :                :     {
                               3975                 :                :         XLogRecPtr  recptr;
                               3976                 :                : 
                               3977                 :                :         /*
                               3978                 :                :          * For logical decoding we need combo CIDs to properly decode the
                               3979                 :                :          * catalog.
                               3980                 :                :          */
 3778                          3981   [ +  +  +  -  :         265654 :         if (RelationIsAccessibleInLogicalDecoding(relation))
                                     -  +  -  -  -  
                                     -  +  +  +  +  
                                     -  +  -  -  +  
                                                 - ]
                               3982                 :                :         {
                               3983                 :           2423 :             log_heap_new_cid(relation, &oldtup);
                               3984                 :           2423 :             log_heap_new_cid(relation, heaptup);
                               3985                 :                :         }
                               3986                 :                : 
                               3987                 :         265654 :         recptr = log_heap_update(relation, buffer,
                               3988                 :                :                                  newbuf, &oldtup, heaptup,
                               3989                 :                :                                  old_key_tuple,
                               3990                 :                :                                  all_visible_cleared,
                               3991                 :                :                                  all_visible_cleared_new);
 8686 vadim4o@yahoo.com        3992         [ +  + ]:         265654 :         if (newbuf != buffer)
                               3993                 :                :         {
 2916 kgrittn@postgresql.o     3994                 :         130024 :             PageSetLSN(BufferGetPage(newbuf), recptr);
                               3995                 :                :         }
                               3996                 :         265654 :         PageSetLSN(BufferGetPage(buffer), recptr);
                               3997                 :                :     }
                               3998                 :                : 
 8493 tgl@sss.pgh.pa.us        3999         [ -  + ]:         276978 :     END_CRIT_SECTION();
                               4000                 :                : 
 8686 vadim4o@yahoo.com        4001         [ +  + ]:         276978 :     if (newbuf != buffer)
                               4002                 :         140150 :         LockBuffer(newbuf, BUFFER_LOCK_UNLOCK);
 9252                          4003                 :         276978 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               4004                 :                : 
                               4005                 :                :     /*
                               4006                 :                :      * Mark old tuple for invalidation from system caches at next command
                               4007                 :                :      * boundary, and mark the new tuple for invalidation in case we abort. We
                               4008                 :                :      * have to do this before releasing the buffer because oldtup is in the
                               4009                 :                :      * buffer.  (heaptup is all in local memory, but it's necessary to process
                               4010                 :                :      * both tuple versions in one call to inval.c so we can avoid redundant
                               4011                 :                :      * sinval messages.)
                               4012                 :                :      */
 4625 tgl@sss.pgh.pa.us        4013                 :         276978 :     CacheInvalidateHeapTuple(relation, &oldtup, heaptup);
                               4014                 :                : 
                               4015                 :                :     /* Now we can release the buffer(s) */
 8498                          4016         [ +  + ]:         276978 :     if (newbuf != buffer)
 6589                          4017                 :         140150 :         ReleaseBuffer(newbuf);
    3 akorotkov@postgresql     4018                 :         276978 :     ReleaseBuffer(buffer);
 4681 rhaas@postgresql.org     4019         [ +  + ]:         276978 :     if (BufferIsValid(vmbuffer_new))
                               4020                 :            815 :         ReleaseBuffer(vmbuffer_new);
                               4021         [ +  + ]:         276978 :     if (BufferIsValid(vmbuffer))
                               4022                 :           1176 :         ReleaseBuffer(vmbuffer);
                               4023                 :                : 
                               4024                 :                :     /*
                               4025                 :                :      * Release the lmgr tuple lock, if we had it.
                               4026                 :                :      */
 6924 tgl@sss.pgh.pa.us        4027         [ +  + ]:         276978 :     if (have_tuple_lock)
 2194 simon@2ndQuadrant.co     4028                 :             12 :         UnlockTupleTuplock(relation, &(oldtup.t_self), *lockmode);
                               4029                 :                : 
  388 pg@bowt.ie               4030                 :         276978 :     pgstat_count_heap_update(relation, use_hot_update, newbuf != buffer);
                               4031                 :                : 
                               4032                 :                :     /*
                               4033                 :                :      * If heaptup is a private copy, release it.  Don't forget to copy t_self
                               4034                 :                :      * back to the caller's image, too.
                               4035                 :                :      */
 6720 tgl@sss.pgh.pa.us        4036         [ +  + ]:         276978 :     if (heaptup != newtup)
                               4037                 :                :     {
                               4038                 :           1049 :         newtup->t_self = heaptup->t_self;
                               4039                 :           1049 :         heap_freetuple(heaptup);
                               4040                 :                :     }
                               4041                 :                : 
                               4042                 :                :     /*
                               4043                 :                :      * If it is a HOT update, the update may still need to update summarized
                               4044                 :                :      * indexes, lest we fail to update those summaries and get incorrect
                               4045                 :                :      * results (for example, minmax bounds of the block may change with this
                               4046                 :                :      * update).
                               4047                 :                :      */
  391 tomas.vondra@postgre     4048         [ +  + ]:         276978 :     if (use_hot_update)
                               4049                 :                :     {
                               4050         [ +  + ]:         126107 :         if (summarized_update)
                               4051                 :           1641 :             *update_indexes = TU_Summarizing;
                               4052                 :                :         else
                               4053                 :         124466 :             *update_indexes = TU_None;
                               4054                 :                :     }
                               4055                 :                :     else
                               4056                 :         150871 :         *update_indexes = TU_All;
                               4057                 :                : 
 3778 rhaas@postgresql.org     4058   [ +  +  +  + ]:         276978 :     if (old_key_tuple != NULL && old_key_copied)
                               4059                 :             80 :         heap_freetuple(old_key_tuple);
                               4060                 :                : 
 6051 tgl@sss.pgh.pa.us        4061                 :         276978 :     bms_free(hot_attrs);
  391 tomas.vondra@postgre     4062                 :         276978 :     bms_free(sum_attrs);
 4099 alvherre@alvh.no-ip.     4063                 :         276978 :     bms_free(key_attrs);
 2790 tgl@sss.pgh.pa.us        4064                 :         276978 :     bms_free(id_attrs);
 2573 alvherre@alvh.no-ip.     4065                 :         276978 :     bms_free(modified_attrs);
                               4066                 :         276978 :     bms_free(interesting_attrs);
                               4067                 :                : 
 1849 andres@anarazel.de       4068                 :         276978 :     return TM_Ok;
                               4069                 :                : }
                               4070                 :                : 
                               4071                 :                : /*
                               4072                 :                :  * Check if the specified attribute's values are the same.  Subroutine for
                               4073                 :                :  * HeapDetermineColumnsInfo.
                               4074                 :                :  */
                               4075                 :                : static bool
  790 akapila@postgresql.o     4076                 :         619520 : heap_attr_equals(TupleDesc tupdesc, int attrnum, Datum value1, Datum value2,
                               4077                 :                :                  bool isnull1, bool isnull2)
                               4078                 :                : {
                               4079                 :                :     Form_pg_attribute att;
                               4080                 :                : 
                               4081                 :                :     /*
                               4082                 :                :      * If one value is NULL and other is not, then they are certainly not
                               4083                 :                :      * equal
                               4084                 :                :      */
 6051 tgl@sss.pgh.pa.us        4085         [ +  + ]:         619520 :     if (isnull1 != isnull2)
                               4086                 :              3 :         return false;
                               4087                 :                : 
                               4088                 :                :     /*
                               4089                 :                :      * If both are NULL, they can be considered equal.
                               4090                 :                :      */
                               4091         [ +  + ]:         619517 :     if (isnull1)
                               4092                 :           4991 :         return true;
                               4093                 :                : 
                               4094                 :                :     /*
                               4095                 :                :      * We do simple binary comparison of the two datums.  This may be overly
                               4096                 :                :      * strict because there can be multiple binary representations for the
                               4097                 :                :      * same logical value.  But we should be OK as long as there are no false
                               4098                 :                :      * positives.  Using a type-specific equality operator is messy because
                               4099                 :                :      * there could be multiple notions of equality in different operator
                               4100                 :                :      * classes; furthermore, we cannot safely invoke user-defined functions
                               4101                 :                :      * while holding exclusive buffer lock.
                               4102                 :                :      */
                               4103         [ -  + ]:         614526 :     if (attrnum <= 0)
                               4104                 :                :     {
                               4105                 :                :         /* The only allowed system columns are OIDs, so do this */
 6051 tgl@sss.pgh.pa.us        4106                 :UBC           0 :         return (DatumGetObjectId(value1) == DatumGetObjectId(value2));
                               4107                 :                :     }
                               4108                 :                :     else
                               4109                 :                :     {
 6051 tgl@sss.pgh.pa.us        4110         [ -  + ]:CBC      614526 :         Assert(attrnum <= tupdesc->natts);
 2429 andres@anarazel.de       4111                 :         614526 :         att = TupleDescAttr(tupdesc, attrnum - 1);
 6051 tgl@sss.pgh.pa.us        4112                 :         614526 :         return datumIsEqual(value1, value2, att->attbyval, att->attlen);
                               4113                 :                :     }
                               4114                 :                : }
                               4115                 :                : 
                               4116                 :                : /*
                               4117                 :                :  * Check which columns are being updated.
                               4118                 :                :  *
                               4119                 :                :  * Given an updated tuple, determine (and return into the output bitmapset),
                               4120                 :                :  * from those listed as interesting, the set of columns that changed.
                               4121                 :                :  *
                               4122                 :                :  * has_external indicates if any of the unmodified attributes (from those
                               4123                 :                :  * listed as interesting) of the old tuple is a member of external_cols and is
                               4124                 :                :  * stored externally.
                               4125                 :                :  */
                               4126                 :                : static Bitmapset *
  790 akapila@postgresql.o     4127                 :         277144 : HeapDetermineColumnsInfo(Relation relation,
                               4128                 :                :                          Bitmapset *interesting_cols,
                               4129                 :                :                          Bitmapset *external_cols,
                               4130                 :                :                          HeapTuple oldtup, HeapTuple newtup,
                               4131                 :                :                          bool *has_external)
                               4132                 :                : {
                               4133                 :                :     int         attidx;
 2524 bruce@momjian.us         4134                 :         277144 :     Bitmapset  *modified = NULL;
  790 akapila@postgresql.o     4135                 :         277144 :     TupleDesc   tupdesc = RelationGetDescr(relation);
                               4136                 :                : 
  409 tgl@sss.pgh.pa.us        4137                 :         277144 :     attidx = -1;
                               4138         [ +  + ]:         896664 :     while ((attidx = bms_next_member(interesting_cols, attidx)) >= 0)
                               4139                 :                :     {
                               4140                 :                :         /* attidx is zero-based, attrnum is the normal attribute number */
                               4141                 :         619520 :         AttrNumber  attrnum = attidx + FirstLowInvalidHeapAttributeNumber;
                               4142                 :                :         Datum       value1,
                               4143                 :                :                     value2;
                               4144                 :                :         bool        isnull1,
                               4145                 :                :                     isnull2;
                               4146                 :                : 
                               4147                 :                :         /*
                               4148                 :                :          * If it's a whole-tuple reference, say "not equal".  It's not really
                               4149                 :                :          * worth supporting this case, since it could only succeed after a
                               4150                 :                :          * no-op update, which is hardly a case worth optimizing for.
                               4151                 :                :          */
  790 akapila@postgresql.o     4152         [ -  + ]:         619520 :         if (attrnum == 0)
                               4153                 :                :         {
  409 tgl@sss.pgh.pa.us        4154                 :UBC           0 :             modified = bms_add_member(modified, attidx);
  790 akapila@postgresql.o     4155                 :              0 :             continue;
                               4156                 :                :         }
                               4157                 :                : 
                               4158                 :                :         /*
                               4159                 :                :          * Likewise, automatically say "not equal" for any system attribute
                               4160                 :                :          * other than tableOID; we cannot expect these to be consistent in a
                               4161                 :                :          * HOT chain, or even to be set correctly yet in the new tuple.
                               4162                 :                :          */
  790 akapila@postgresql.o     4163         [ -  + ]:CBC      619520 :         if (attrnum < 0)
                               4164                 :                :         {
  790 akapila@postgresql.o     4165         [ #  # ]:UBC           0 :             if (attrnum != TableOidAttributeNumber)
                               4166                 :                :             {
  409 tgl@sss.pgh.pa.us        4167                 :              0 :                 modified = bms_add_member(modified, attidx);
  790 akapila@postgresql.o     4168                 :              0 :                 continue;
                               4169                 :                :             }
                               4170                 :                :         }
                               4171                 :                : 
                               4172                 :                :         /*
                               4173                 :                :          * Extract the corresponding values.  XXX this is pretty inefficient
                               4174                 :                :          * if there are many indexed columns.  Should we do a single
                               4175                 :                :          * heap_deform_tuple call on each tuple, instead?   But that doesn't
                               4176                 :                :          * work for system columns ...
                               4177                 :                :          */
  790 akapila@postgresql.o     4178                 :CBC      619520 :         value1 = heap_getattr(oldtup, attrnum, tupdesc, &isnull1);
                               4179                 :         619520 :         value2 = heap_getattr(newtup, attrnum, tupdesc, &isnull2);
                               4180                 :                : 
                               4181         [ +  + ]:         619520 :         if (!heap_attr_equals(tupdesc, attrnum, value1,
                               4182                 :                :                               value2, isnull1, isnull2))
                               4183                 :                :         {
  409 tgl@sss.pgh.pa.us        4184                 :          25188 :             modified = bms_add_member(modified, attidx);
  790 akapila@postgresql.o     4185                 :          25188 :             continue;
                               4186                 :                :         }
                               4187                 :                : 
                               4188                 :                :         /*
                               4189                 :                :          * No need to check attributes that can't be stored externally. Note
                               4190                 :                :          * that system attributes can't be stored externally.
                               4191                 :                :          */
                               4192   [ +  -  +  + ]:         594332 :         if (attrnum < 0 || isnull1 ||
                               4193         [ +  + ]:         589341 :             TupleDescAttr(tupdesc, attrnum - 1)->attlen != -1)
                               4194                 :         565087 :             continue;
                               4195                 :                : 
                               4196                 :                :         /*
                               4197                 :                :          * Check if the old tuple's attribute is stored externally and is a
                               4198                 :                :          * member of external_cols.
                               4199                 :                :          */
                               4200   [ +  +  +  + ]:          29250 :         if (VARATT_IS_EXTERNAL((struct varlena *) DatumGetPointer(value1)) &&
  409 tgl@sss.pgh.pa.us        4201                 :              5 :             bms_is_member(attidx, external_cols))
  790 akapila@postgresql.o     4202                 :              2 :             *has_external = true;
                               4203                 :                :     }
                               4204                 :                : 
 2573 alvherre@alvh.no-ip.     4205                 :         277144 :     return modified;
                               4206                 :                : }
                               4207                 :                : 
                               4208                 :                : /*
                               4209                 :                :  *  simple_heap_update - replace a tuple
                               4210                 :                :  *
                               4211                 :                :  * This routine may be used to update a tuple when concurrent updates of
                               4212                 :                :  * the target tuple are not expected (for example, because we have a lock
                               4213                 :                :  * on the relation associated with the tuple).  Any failure is reported
                               4214                 :                :  * via ereport().
                               4215                 :                :  */
                               4216                 :                : void
  391 tomas.vondra@postgre     4217                 :          88998 : simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup,
                               4218                 :                :                    TU_UpdateIndexes *update_indexes)
                               4219                 :                : {
                               4220                 :                :     TM_Result   result;
                               4221                 :                :     TM_FailureData tmfd;
                               4222                 :                :     LockTupleMode lockmode;
                               4223                 :                : 
 7517 tgl@sss.pgh.pa.us        4224                 :          88998 :     result = heap_update(relation, otid, tup,
                               4225                 :                :                          GetCurrentCommandId(true), InvalidSnapshot,
                               4226                 :                :                          true /* wait for commit */ ,
                               4227                 :                :                          &tmfd, &lockmode, update_indexes);
 8482                          4228   [ -  +  -  -  :          88998 :     switch (result)
                                                 - ]
                               4229                 :                :     {
 1849 andres@anarazel.de       4230                 :UBC           0 :         case TM_SelfModified:
                               4231                 :                :             /* Tuple was already updated in current command? */
 7573 tgl@sss.pgh.pa.us        4232         [ #  # ]:              0 :             elog(ERROR, "tuple already updated by self");
                               4233                 :                :             break;
                               4234                 :                : 
 1849 andres@anarazel.de       4235                 :CBC       88998 :         case TM_Ok:
                               4236                 :                :             /* done successfully */
 8482 tgl@sss.pgh.pa.us        4237                 :          88998 :             break;
                               4238                 :                : 
 1849 andres@anarazel.de       4239                 :UBC           0 :         case TM_Updated:
 7573 tgl@sss.pgh.pa.us        4240         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently updated");
                               4241                 :                :             break;
                               4242                 :                : 
 1849 andres@anarazel.de       4243                 :              0 :         case TM_Deleted:
                               4244         [ #  # ]:              0 :             elog(ERROR, "tuple concurrently deleted");
                               4245                 :                :             break;
                               4246                 :                : 
 8482 tgl@sss.pgh.pa.us        4247                 :              0 :         default:
 7573                          4248         [ #  # ]:              0 :             elog(ERROR, "unrecognized heap_update status: %u", result);
                               4249                 :                :             break;
                               4250                 :                :     }
 8482 tgl@sss.pgh.pa.us        4251                 :CBC       88998 : }
                               4252                 :                : 
                               4253                 :                : 
                               4254                 :                : /*
                               4255                 :                :  * Return the MultiXactStatus corresponding to the given tuple lock mode.
                               4256                 :                :  */
                               4257                 :                : static MultiXactStatus
 4099 alvherre@alvh.no-ip.     4258                 :           1196 : get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
                               4259                 :                : {
                               4260                 :                :     int         retval;
                               4261                 :                : 
                               4262         [ +  + ]:           1196 :     if (is_update)
                               4263                 :             96 :         retval = tupleLockExtraInfo[mode].updstatus;
                               4264                 :                :     else
                               4265                 :           1100 :         retval = tupleLockExtraInfo[mode].lockstatus;
                               4266                 :                : 
                               4267         [ -  + ]:           1196 :     if (retval == -1)
 4099 alvherre@alvh.no-ip.     4268   [ #  #  #  # ]:UBC           0 :         elog(ERROR, "invalid lock tuple mode %d/%s", mode,
                               4269                 :                :              is_update ? "true" : "false");
                               4270                 :                : 
 3946 alvherre@alvh.no-ip.     4271                 :CBC        1196 :     return (MultiXactStatus) retval;
                               4272                 :                : }
                               4273                 :                : 
                               4274                 :                : /*
                               4275                 :                :  *  heap_lock_tuple - lock a tuple in shared or exclusive mode
                               4276                 :                :  *
                               4277                 :                :  * Note that this acquires a buffer pin, which the caller must release.
                               4278                 :                :  *
                               4279                 :                :  * Input parameters:
                               4280                 :                :  *  relation: relation containing tuple (caller must hold suitable lock)
                               4281                 :                :  *  tid: TID of tuple to lock
                               4282                 :                :  *  cid: current command ID (used for visibility test, and stored into
                               4283                 :                :  *      tuple's cmax if lock is successful)
                               4284                 :                :  *  mode: indicates if shared or exclusive tuple lock is desired
                               4285                 :                :  *  wait_policy: what to do if tuple lock is not available
                               4286                 :                :  *  follow_updates: if true, follow the update chain to also lock descendant
                               4287                 :                :  *      tuples.
                               4288                 :                :  *
                               4289                 :                :  * Output parameters:
                               4290                 :                :  *  *tuple: all fields filled in
                               4291                 :                :  *  *buffer: set to buffer holding tuple (pinned but not locked at exit)
                               4292                 :                :  *  *tmfd: filled in failure cases (see below)
                               4293                 :                :  *
                               4294                 :                :  * Function results are the same as the ones for table_tuple_lock().
                               4295                 :                :  *
                               4296                 :                :  * In the failure cases other than TM_Invisible, the routine fills
                               4297                 :                :  * *tmfd with the tuple's t_ctid, t_xmax (resolving a possible MultiXact,
                               4298                 :                :  * if necessary), and t_cmax (the last only for TM_SelfModified,
                               4299                 :                :  * since we cannot obtain cmax from a combo CID generated by another
                               4300                 :                :  * transaction).
                               4301                 :                :  * See comments for struct TM_FailureData for additional info.
                               4302                 :                :  *
                               4303                 :                :  * See README.tuplock for a thorough explanation of this mechanism.
                               4304                 :                :  */
                               4305                 :                : TM_Result
    3 akorotkov@postgresql     4306                 :          82709 : heap_lock_tuple(Relation relation, HeapTuple tuple,
                               4307                 :                :                 CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
                               4308                 :                :                 bool follow_updates,
                               4309                 :                :                 Buffer *buffer, TM_FailureData *tmfd)
                               4310                 :                : {
                               4311                 :                :     TM_Result   result;
                               4312                 :          82709 :     ItemPointer tid = &(tuple->t_self);
                               4313                 :                :     ItemId      lp;
                               4314                 :                :     Page        page;
 2827 andres@anarazel.de       4315                 :          82709 :     Buffer      vmbuffer = InvalidBuffer;
                               4316                 :                :     BlockNumber block;
                               4317                 :                :     TransactionId xid,
                               4318                 :                :                 xmax;
                               4319                 :                :     uint16      old_infomask,
                               4320                 :                :                 new_infomask,
                               4321                 :                :                 new_infomask2;
 3292 alvherre@alvh.no-ip.     4322                 :          82709 :     bool        first_time = true;
 1762                          4323                 :          82709 :     bool        skip_tuple_lock = false;
 6924 tgl@sss.pgh.pa.us        4324                 :          82709 :     bool        have_tuple_lock = false;
 2827 andres@anarazel.de       4325                 :          82709 :     bool        cleared_all_frozen = false;
                               4326                 :                : 
    3 akorotkov@postgresql     4327                 :          82709 :     *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
 2827 andres@anarazel.de       4328                 :          82709 :     block = ItemPointerGetBlockNumber(tid);
                               4329                 :                : 
                               4330                 :                :     /*
                               4331                 :                :      * Before locking the buffer, pin the visibility map page if it appears to
                               4332                 :                :      * be necessary.  Since we haven't got the lock yet, someone else might be
                               4333                 :                :      * in the middle of changing this, so we'll need to recheck after we have
                               4334                 :                :      * the lock.
                               4335                 :                :      */
    3 akorotkov@postgresql     4336         [ +  + ]:          82709 :     if (PageIsAllVisible(BufferGetPage(*buffer)))
 2827 andres@anarazel.de       4337                 :           1658 :         visibilitymap_pin(relation, block, &vmbuffer);
                               4338                 :                : 
    3 akorotkov@postgresql     4339                 :          82709 :     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4340                 :                : 
                               4341                 :          82709 :     page = BufferGetPage(*buffer);
 5754 tgl@sss.pgh.pa.us        4342                 :          82709 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
 6059                          4343         [ -  + ]:          82709 :     Assert(ItemIdIsNormal(lp));
                               4344                 :                : 
 5754                          4345                 :          82709 :     tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
 9252 vadim4o@yahoo.com        4346                 :          82709 :     tuple->t_len = ItemIdGetLength(lp);
 6812 tgl@sss.pgh.pa.us        4347                 :          82709 :     tuple->t_tableOid = RelationGetRelid(relation);
                               4348                 :                : 
 9252 vadim4o@yahoo.com        4349                 :             13 : l3:
    3 akorotkov@postgresql     4350                 :          82722 :     result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
                               4351                 :                : 
 1849 andres@anarazel.de       4352         [ +  + ]:          82722 :     if (result == TM_Invisible)
                               4353                 :                :     {
                               4354                 :                :         /*
                               4355                 :                :          * This is possible, but only when locking a tuple for ON CONFLICT
                               4356                 :                :          * UPDATE.  We return this value here rather than throwing an error in
                               4357                 :                :          * order to give that case the opportunity to throw a more specific
                               4358                 :                :          * error.
                               4359                 :                :          */
                               4360                 :             12 :         result = TM_Invisible;
 2827                          4361                 :             12 :         goto out_locked;
                               4362                 :                :     }
 1849                          4363   [ +  +  +  + ]:          82710 :     else if (result == TM_BeingModified ||
                               4364         [ +  + ]:          75903 :              result == TM_Updated ||
                               4365                 :                :              result == TM_Deleted)
                               4366                 :                :     {
                               4367                 :                :         TransactionId xwait;
                               4368                 :                :         uint16      infomask;
                               4369                 :                :         uint16      infomask2;
                               4370                 :                :         bool        require_sleep;
                               4371                 :                :         ItemPointerData t_ctid;
                               4372                 :                : 
                               4373                 :                :         /* must copy state data before unlocking buffer */
 4099 alvherre@alvh.no-ip.     4374                 :           6808 :         xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
 6924 tgl@sss.pgh.pa.us        4375                 :           6808 :         infomask = tuple->t_data->t_infomask;
 4099 alvherre@alvh.no-ip.     4376                 :           6808 :         infomask2 = tuple->t_data->t_infomask2;
                               4377                 :           6808 :         ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
                               4378                 :                : 
    3 akorotkov@postgresql     4379                 :           6808 :         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
                               4380                 :                : 
                               4381                 :                :         /*
                               4382                 :                :          * If any subtransaction of the current top transaction already holds
                               4383                 :                :          * a lock as strong as or stronger than what we're requesting, we
                               4384                 :                :          * effectively hold the desired lock already.  We *must* succeed
                               4385                 :                :          * without trying to take the tuple lock, else we will deadlock
                               4386                 :                :          * against anyone wanting to acquire a stronger lock.
                               4387                 :                :          *
                               4388                 :                :          * Note we only do this the first time we loop on the HTSU result;
                               4389                 :                :          * there is no point in testing in subsequent passes, because
                               4390                 :                :          * evidently our own transaction cannot have acquired a new lock after
                               4391                 :                :          * the first time we checked.
                               4392                 :                :          */
 3292 alvherre@alvh.no-ip.     4393         [ +  + ]:           6808 :         if (first_time)
                               4394                 :                :         {
                               4395                 :           6799 :             first_time = false;
                               4396                 :                : 
                               4397         [ +  + ]:           6799 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               4398                 :                :             {
                               4399                 :                :                 int         i;
                               4400                 :                :                 int         nmembers;
                               4401                 :                :                 MultiXactMember *members;
                               4402                 :                : 
                               4403                 :                :                 /*
                               4404                 :                :                  * We don't need to allow old multixacts here; if that had
                               4405                 :                :                  * been the case, HeapTupleSatisfiesUpdate would have returned
                               4406                 :                :                  * MayBeUpdated and we wouldn't be here.
                               4407                 :                :                  */
                               4408                 :                :                 nmembers =
                               4409                 :             84 :                     GetMultiXactIdMembers(xwait, &members, false,
                               4410   [ +  +  -  + ]:             84 :                                           HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               4411                 :                : 
                               4412         [ +  + ]:            251 :                 for (i = 0; i < nmembers; i++)
                               4413                 :                :                 {
                               4414                 :                :                     /* only consider members of our own transaction */
                               4415         [ +  + ]:            181 :                     if (!TransactionIdIsCurrentTransactionId(members[i].xid))
                               4416                 :            132 :                         continue;
                               4417                 :                : 
                               4418         [ +  + ]:             49 :                     if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
                               4419                 :                :                     {
 4099                          4420                 :             14 :                         pfree(members);
 1849 andres@anarazel.de       4421                 :             14 :                         result = TM_Ok;
 2827                          4422                 :             14 :                         goto out_unlocked;
                               4423                 :                :                     }
                               4424                 :                :                     else
                               4425                 :                :                     {
                               4426                 :                :                         /*
                               4427                 :                :                          * Disable acquisition of the heavyweight tuple lock.
                               4428                 :                :                          * Otherwise, when promoting a weaker lock, we might
                               4429                 :                :                          * deadlock with another locker that has acquired the
                               4430                 :                :                          * heavyweight tuple lock and is waiting for our
                               4431                 :                :                          * transaction to finish.
                               4432                 :                :                          *
                               4433                 :                :                          * Note that in this case we still need to wait for
                               4434                 :                :                          * the multixact if required, to avoid acquiring
                               4435                 :                :                          * conflicting locks.
                               4436                 :                :                          */
 1762 alvherre@alvh.no-ip.     4437                 :             35 :                         skip_tuple_lock = true;
                               4438                 :                :                     }
                               4439                 :                :                 }
                               4440                 :                : 
 3292                          4441         [ +  - ]:             70 :                 if (members)
                               4442                 :             70 :                     pfree(members);
                               4443                 :                :             }
                               4444         [ +  + ]:           6715 :             else if (TransactionIdIsCurrentTransactionId(xwait))
                               4445                 :                :             {
                               4446   [ +  +  +  +  :           5495 :                 switch (mode)
                                                 - ]
                               4447                 :                :                 {
                               4448                 :            138 :                     case LockTupleKeyShare:
                               4449   [ -  +  -  -  :            138 :                         Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
                                              -  - ]
                               4450                 :                :                                HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
                               4451                 :                :                                HEAP_XMAX_IS_EXCL_LOCKED(infomask));
 1849 andres@anarazel.de       4452                 :            138 :                         result = TM_Ok;
 2827                          4453                 :            138 :                         goto out_unlocked;
 3292 alvherre@alvh.no-ip.     4454                 :              6 :                     case LockTupleShare:
                               4455         [ +  - ]:              6 :                         if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
                               4456         [ -  + ]:              6 :                             HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4457                 :                :                         {
 1849 andres@anarazel.de       4458                 :LBC       (110) :                             result = TM_Ok;
 2827                          4459                 :          (110) :                             goto out_unlocked;
                               4460                 :                :                         }
 3292 alvherre@alvh.no-ip.     4461                 :CBC           6 :                         break;
                               4462                 :             61 :                     case LockTupleNoKeyExclusive:
                               4463         [ +  + ]:             61 :                         if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4464                 :                :                         {
 1849 andres@anarazel.de       4465                 :             50 :                             result = TM_Ok;
 2827                          4466                 :             50 :                             goto out_unlocked;
                               4467                 :                :                         }
 3292 alvherre@alvh.no-ip.     4468                 :             11 :                         break;
                               4469                 :           5290 :                     case LockTupleExclusive:
                               4470         [ +  + ]:           5290 :                         if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
                               4471         [ +  + ]:            251 :                             infomask2 & HEAP_KEYS_UPDATED)
                               4472                 :                :                         {
 1849 andres@anarazel.de       4473                 :            230 :                             result = TM_Ok;
 2827                          4474                 :            230 :                             goto out_unlocked;
                               4475                 :                :                         }
 3292 alvherre@alvh.no-ip.     4476                 :           5060 :                         break;
                               4477                 :                :                 }
                               4478                 :                :             }
                               4479                 :                :         }
                               4480                 :                : 
                               4481                 :                :         /*
                               4482                 :                :          * Initially assume that we will have to wait for the locking
                               4483                 :                :          * transaction(s) to finish.  We check various cases below in which
                               4484                 :                :          * this can be turned off.
                               4485                 :                :          */
 4099                          4486                 :           6376 :         require_sleep = true;
                               4487         [ +  + ]:           6376 :         if (mode == LockTupleKeyShare)
                               4488                 :                :         {
                               4489                 :                :             /*
                               4490                 :                :              * If we're requesting KeyShare, and there's no update present, we
                               4491                 :                :              * don't need to wait.  Even if there is an update, we can still
                               4492                 :                :              * continue if the key hasn't been modified.
                               4493                 :                :              *
                               4494                 :                :              * However, if there are updates, we need to walk the update chain
                               4495                 :                :              * to mark future versions of the row as locked, too.  That way,
                               4496                 :                :              * if somebody deletes that future version, we're protected
                               4497                 :                :              * against the key going away.  This locking of future versions
                               4498                 :                :              * could block momentarily, if a concurrent transaction is
                               4499                 :                :              * deleting a key; or it could return a value to the effect that
                               4500                 :                :              * the transaction deleting the key has already committed.  So we
                               4501                 :                :              * do this before re-locking the buffer; otherwise this would be
                               4502                 :                :              * prone to deadlocks.
                               4503                 :                :              *
                               4504                 :                :              * Note that the TID we're locking was grabbed before we unlocked
                               4505                 :                :              * the buffer.  For it to change while we're not looking, the
                               4506                 :                :              * other properties we're testing for below after re-locking the
                               4507                 :                :              * buffer would also change, in which case we would restart this
                               4508                 :                :              * loop above.
                               4509                 :                :              */
                               4510         [ +  + ]:            578 :             if (!(infomask2 & HEAP_KEYS_UPDATED))
                               4511                 :                :             {
                               4512                 :                :                 bool        updated;
                               4513                 :                : 
                               4514   [ +  +  +  - ]:            547 :                 updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
                               4515                 :                : 
                               4516                 :                :                 /*
                               4517                 :                :                  * If there are updates, follow the update chain; bail out if
                               4518                 :                :                  * that cannot be done.
                               4519                 :                :                  */
                               4520   [ +  -  +  + ]:            547 :                 if (follow_updates && updated)
                               4521                 :                :                 {
                               4522                 :                :                     TM_Result   res;
                               4523                 :                : 
                               4524                 :             50 :                     res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
                               4525                 :                :                                                   GetCurrentTransactionId(),
                               4526                 :                :                                                   mode);
 1849 andres@anarazel.de       4527         [ +  + ]:             50 :                     if (res != TM_Ok)
                               4528                 :                :                     {
 4099 alvherre@alvh.no-ip.     4529                 :              6 :                         result = res;
                               4530                 :                :                         /* recovery code expects to have buffer lock held */
    3 akorotkov@postgresql     4531                 :              6 :                         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 4099 alvherre@alvh.no-ip.     4532                 :            182 :                         goto failed;
                               4533                 :                :                     }
                               4534                 :                :                 }
                               4535                 :                : 
    3 akorotkov@postgresql     4536                 :            541 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4537                 :                : 
                               4538                 :                :                 /*
                               4539                 :                :                  * Make sure it's still an appropriate lock, else start over.
                               4540                 :                :                  * Also, if it wasn't updated before we released the lock, but
                               4541                 :                :                  * is updated now, we start over too; the reason is that we
                               4542                 :                :                  * now need to follow the update chain to lock the new
                               4543                 :                :                  * versions.
                               4544                 :                :                  */
 4099 alvherre@alvh.no-ip.     4545         [ +  + ]:            541 :                 if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
                               4546         [ +  - ]:             43 :                     ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
                               4547         [ -  + ]:             43 :                      !updated))
 4099 alvherre@alvh.no-ip.     4548                 :UBC           0 :                     goto l3;
                               4549                 :                : 
                               4550                 :                :                 /* Things look okay, so we can skip sleeping */
 4099 alvherre@alvh.no-ip.     4551                 :CBC         541 :                 require_sleep = false;
                               4552                 :                : 
                               4553                 :                :                 /*
                               4554                 :                :                  * Note we allow Xmax to change here; other updaters/lockers
                               4555                 :                :                  * could have modified it before we grabbed the buffer lock.
                               4556                 :                :                  * However, this is not a problem, because with the recheck we
                               4557                 :                :                  * just did we ensure that they still don't conflict with the
                               4558                 :                :                  * lock we want.
                               4559                 :                :                  */
                               4560                 :                :             }
                               4561                 :                :         }
                               4562         [ +  + ]:           5798 :         else if (mode == LockTupleShare)
                               4563                 :                :         {
                               4564                 :                :             /*
                               4565                 :                :              * If we're requesting Share, we can similarly avoid sleeping if
                               4566                 :                :              * there's no update and no exclusive lock present.
                               4567                 :                :              */
                               4568   [ -  +  -  - ]:            441 :             if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
                               4569         [ +  + ]:            441 :                 !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
                               4570                 :                :             {
    3 akorotkov@postgresql     4571                 :            435 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4572                 :                : 
                               4573                 :                :                 /*
                               4574                 :                :                  * Make sure it's still an appropriate lock, else start over.
                               4575                 :                :                  * See above about allowing xmax to change.
                               4576                 :                :                  */
 4099 alvherre@alvh.no-ip.     4577   [ -  +  -  - ]:            435 :                 if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
                               4578         [ -  + ]:            435 :                     HEAP_XMAX_IS_EXCL_LOCKED(tuple->t_data->t_infomask))
 4099 alvherre@alvh.no-ip.     4579                 :UBC           0 :                     goto l3;
 4099 alvherre@alvh.no-ip.     4580                 :CBC         435 :                 require_sleep = false;
                               4581                 :                :             }
                               4582                 :                :         }
                               4583         [ +  + ]:           5357 :         else if (mode == LockTupleNoKeyExclusive)
                               4584                 :                :         {
                               4585                 :                :             /*
                               4586                 :                :              * If we're requesting NoKeyExclusive, we might also be able to
                               4587                 :                :              * avoid sleeping; just ensure that there no conflicting lock
                               4588                 :                :              * already acquired.
                               4589                 :                :              */
                               4590         [ +  + ]:            155 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               4591                 :                :             {
 3397                          4592         [ +  + ]:             26 :                 if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
                               4593                 :                :                                              mode, NULL))
                               4594                 :                :                 {
                               4595                 :                :                     /*
                               4596                 :                :                      * No conflict, but if the xmax changed under us in the
                               4597                 :                :                      * meantime, start over.
                               4598                 :                :                      */
    3 akorotkov@postgresql     4599                 :             13 :                     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3397 alvherre@alvh.no-ip.     4600         [ +  - ]:             13 :                     if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               4601         [ -  + ]:             13 :                         !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               4602                 :                :                                              xwait))
 3397 alvherre@alvh.no-ip.     4603                 :UBC           0 :                         goto l3;
                               4604                 :                : 
                               4605                 :                :                     /* otherwise, we're good */
 3397 alvherre@alvh.no-ip.     4606                 :CBC          13 :                     require_sleep = false;
                               4607                 :                :                 }
                               4608                 :                :             }
 4099                          4609         [ +  + ]:            129 :             else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
                               4610                 :                :             {
    3 akorotkov@postgresql     4611                 :             15 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4612                 :                : 
                               4613                 :                :                 /* if the xmax changed in the meantime, start over */
 3643 alvherre@alvh.no-ip.     4614         [ +  - ]:             15 :                 if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
 1536                          4615         [ -  + ]:             15 :                     !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               4616                 :                :                                          xwait))
 4099 alvherre@alvh.no-ip.     4617                 :UBC           0 :                     goto l3;
                               4618                 :                :                 /* otherwise, we're good */
 4099 alvherre@alvh.no-ip.     4619                 :CBC          15 :                 require_sleep = false;
                               4620                 :                :             }
                               4621                 :                :         }
                               4622                 :                : 
                               4623                 :                :         /*
                               4624                 :                :          * As a check independent from those above, we can also avoid sleeping
                               4625                 :                :          * if the current transaction is the sole locker of the tuple.  Note
                               4626                 :                :          * that the strength of the lock already held is irrelevant; this is
                               4627                 :                :          * not about recording the lock in Xmax (which will be done regardless
                               4628                 :                :          * of this optimization, below).  Also, note that the cases where we
                               4629                 :                :          * hold a lock stronger than we are requesting are already handled
                               4630                 :                :          * above by not doing anything.
                               4631                 :                :          *
                               4632                 :                :          * Note we only deal with the non-multixact case here; MultiXactIdWait
                               4633                 :                :          * is well equipped to deal with this situation on its own.
                               4634                 :                :          */
 3292                          4635   [ +  +  +  +  :          11695 :         if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
                                              +  + ]
                               4636                 :           5325 :             TransactionIdIsCurrentTransactionId(xwait))
                               4637                 :                :         {
                               4638                 :                :             /* ... but if the xmax changed in the meantime, start over */
    3 akorotkov@postgresql     4639                 :           5060 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3292 alvherre@alvh.no-ip.     4640         [ +  - ]:           5060 :             if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               4641         [ -  + ]:           5060 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               4642                 :                :                                      xwait))
 3292 alvherre@alvh.no-ip.     4643                 :UBC           0 :                 goto l3;
 3292 alvherre@alvh.no-ip.     4644   [ -  +  -  - ]:CBC        5060 :             Assert(HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask));
                               4645                 :           5060 :             require_sleep = false;
                               4646                 :                :         }
                               4647                 :                : 
                               4648                 :                :         /*
                               4649                 :                :          * Time to sleep on the other transaction/multixact, if necessary.
                               4650                 :                :          *
                               4651                 :                :          * If the other transaction is an update/delete that's already
                               4652                 :                :          * committed, then sleeping cannot possibly do any good: if we're
                               4653                 :                :          * required to sleep, get out to raise an error instead.
                               4654                 :                :          *
                               4655                 :                :          * By here, we either have already acquired the buffer exclusive lock,
                               4656                 :                :          * or we must wait for the locking transaction or multixact; so below
                               4657                 :                :          * we ensure that we grab buffer lock after the sleep.
                               4658                 :                :          */
 1849 andres@anarazel.de       4659   [ +  +  +  +  :           6370 :         if (require_sleep && (result == TM_Updated || result == TM_Deleted))
                                              +  + ]
                               4660                 :                :         {
    3 akorotkov@postgresql     4661                 :            138 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 2830 alvherre@alvh.no-ip.     4662                 :            138 :             goto failed;
                               4663                 :                :         }
                               4664         [ +  + ]:           6232 :         else if (require_sleep)
                               4665                 :                :         {
                               4666                 :                :             /*
                               4667                 :                :              * Acquire tuple lock to establish our priority for the tuple, or
                               4668                 :                :              * die trying.  LockTuple will release us when we are next-in-line
                               4669                 :                :              * for the tuple.  We must do this even if we are share-locking,
                               4670                 :                :              * but not if we already have a weaker lock on the tuple.
                               4671                 :                :              *
                               4672                 :                :              * If we are forced to "start over" below, we keep the tuple lock;
                               4673                 :                :              * this arranges that we stay at the head of the line while
                               4674                 :                :              * rechecking tuple state.
                               4675                 :                :              */
 1762                          4676         [ +  + ]:            168 :             if (!skip_tuple_lock &&
                               4677         [ +  + ]:            152 :                 !heap_acquire_tuplock(relation, tid, mode, wait_policy,
                               4678                 :                :                                       &have_tuple_lock))
                               4679                 :                :             {
                               4680                 :                :                 /*
                               4681                 :                :                  * This can only happen if wait_policy is Skip and the lock
                               4682                 :                :                  * couldn't be obtained.
                               4683                 :                :                  */
 1849 andres@anarazel.de       4684                 :              1 :                 result = TM_WouldBlock;
                               4685                 :                :                 /* recovery code expects to have buffer lock held */
    3 akorotkov@postgresql     4686                 :              1 :                 LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3397 alvherre@alvh.no-ip.     4687                 :              1 :                 goto failed;
                               4688                 :                :             }
                               4689                 :                : 
 4099                          4690         [ +  + ]:            166 :             if (infomask & HEAP_XMAX_IS_MULTI)
                               4691                 :                :             {
                               4692                 :             40 :                 MultiXactStatus status = get_mxact_status_for_lock(mode, false);
                               4693                 :                : 
                               4694                 :                :                 /* We only ever lock tuples, never update them */
                               4695         [ -  + ]:             40 :                 if (status >= MultiXactStatusNoKeyUpdate)
 4099 alvherre@alvh.no-ip.     4696         [ #  # ]:UBC           0 :                     elog(ERROR, "invalid lock mode in heap_lock_tuple");
                               4697                 :                : 
                               4698                 :                :                 /* wait for multixact to end, or die trying  */
 3477 alvherre@alvh.no-ip.     4699   [ +  +  +  - ]:CBC          40 :                 switch (wait_policy)
                               4700                 :                :                 {
                               4701                 :             36 :                     case LockWaitBlock:
                               4702                 :             36 :                         MultiXactIdWait((MultiXactId) xwait, status, infomask,
                               4703                 :                :                                         relation, &tuple->t_self, XLTW_Lock, NULL);
                               4704                 :             36 :                         break;
                               4705                 :              2 :                     case LockWaitSkip:
                               4706         [ +  - ]:              2 :                         if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
                               4707                 :                :                                                         status, infomask, relation,
                               4708                 :                :                                                         NULL))
                               4709                 :                :                         {
 1849 andres@anarazel.de       4710                 :              2 :                             result = TM_WouldBlock;
                               4711                 :                :                             /* recovery code expects to have buffer lock held */
    3 akorotkov@postgresql     4712                 :              2 :                             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3477 alvherre@alvh.no-ip.     4713                 :              2 :                             goto failed;
                               4714                 :                :                         }
 3477 alvherre@alvh.no-ip.     4715                 :UBC           0 :                         break;
 3477 alvherre@alvh.no-ip.     4716                 :CBC           2 :                     case LockWaitError:
                               4717         [ +  - ]:              2 :                         if (!ConditionalMultiXactIdWait((MultiXactId) xwait,
                               4718                 :                :                                                         status, infomask, relation,
                               4719                 :                :                                                         NULL))
                               4720         [ +  - ]:              2 :                             ereport(ERROR,
                               4721                 :                :                                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               4722                 :                :                                      errmsg("could not obtain lock on row in relation \"%s\"",
                               4723                 :                :                                             RelationGetRelationName(relation))));
                               4724                 :                : 
 3477 alvherre@alvh.no-ip.     4725                 :UBC           0 :                         break;
                               4726                 :                :                 }
                               4727                 :                : 
                               4728                 :                :                 /*
                               4729                 :                :                  * Of course, the multixact might not be done here: if we're
                               4730                 :                :                  * requesting a light lock mode, other transactions with light
                               4731                 :                :                  * locks could still be alive, as well as locks owned by our
                               4732                 :                :                  * own xact or other subxacts of this backend.  We need to
                               4733                 :                :                  * preserve the surviving MultiXact members.  Note that it
                               4734                 :                :                  * isn't absolutely necessary in the latter case, but doing so
                               4735                 :                :                  * is simpler.
                               4736                 :                :                  */
                               4737                 :                :             }
                               4738                 :                :             else
                               4739                 :                :             {
                               4740                 :                :                 /* wait for regular transaction to end, or die trying */
 3477 alvherre@alvh.no-ip.     4741   [ +  +  +  - ]:CBC         126 :                 switch (wait_policy)
                               4742                 :                :                 {
                               4743                 :             87 :                     case LockWaitBlock:
 3357 heikki.linnakangas@i     4744                 :             87 :                         XactLockTableWait(xwait, relation, &tuple->t_self,
                               4745                 :                :                                           XLTW_Lock);
 3477 alvherre@alvh.no-ip.     4746                 :             87 :                         break;
                               4747                 :             33 :                     case LockWaitSkip:
                               4748         [ +  - ]:             33 :                         if (!ConditionalXactLockTableWait(xwait))
                               4749                 :                :                         {
 1849 andres@anarazel.de       4750                 :             33 :                             result = TM_WouldBlock;
                               4751                 :                :                             /* recovery code expects to have buffer lock held */
    3 akorotkov@postgresql     4752                 :             33 :                             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3477 alvherre@alvh.no-ip.     4753                 :             33 :                             goto failed;
                               4754                 :                :                         }
 3477 alvherre@alvh.no-ip.     4755                 :UBC           0 :                         break;
 3477 alvherre@alvh.no-ip.     4756                 :CBC           6 :                     case LockWaitError:
                               4757         [ +  - ]:              6 :                         if (!ConditionalXactLockTableWait(xwait))
                               4758         [ +  - ]:              6 :                             ereport(ERROR,
                               4759                 :                :                                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               4760                 :                :                                      errmsg("could not obtain lock on row in relation \"%s\"",
                               4761                 :                :                                             RelationGetRelationName(relation))));
 3477 alvherre@alvh.no-ip.     4762                 :UBC           0 :                         break;
                               4763                 :                :                 }
                               4764                 :                :             }
                               4765                 :                : 
                               4766                 :                :             /* if there are updates, follow the update chain */
 3292 alvherre@alvh.no-ip.     4767   [ +  +  +  +  :CBC         123 :             if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
                                              +  - ]
                               4768                 :                :             {
                               4769                 :                :                 TM_Result   res;
                               4770                 :                : 
                               4771                 :             39 :                 res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
                               4772                 :                :                                               GetCurrentTransactionId(),
                               4773                 :                :                                               mode);
 1849 andres@anarazel.de       4774         [ +  + ]:             39 :                 if (res != TM_Ok)
                               4775                 :                :                 {
 3292 alvherre@alvh.no-ip.     4776                 :              2 :                     result = res;
                               4777                 :                :                     /* recovery code expects to have buffer lock held */
    3 akorotkov@postgresql     4778                 :              2 :                     LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 3292 alvherre@alvh.no-ip.     4779                 :              2 :                     goto failed;
                               4780                 :                :                 }
                               4781                 :                :             }
                               4782                 :                : 
    3 akorotkov@postgresql     4783                 :            121 :             LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
                               4784                 :                : 
                               4785                 :                :             /*
                               4786                 :                :              * xwait is done, but if xwait had just locked the tuple then some
                               4787                 :                :              * other xact could update this tuple before we get to this point.
                               4788                 :                :              * Check for xmax change, and start over if so.
                               4789                 :                :              */
 3292 alvherre@alvh.no-ip.     4790         [ +  + ]:            121 :             if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
                               4791         [ +  + ]:            110 :                 !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data),
                               4792                 :                :                                      xwait))
                               4793                 :             13 :                 goto l3;
                               4794                 :                : 
                               4795         [ +  + ]:            108 :             if (!(infomask & HEAP_XMAX_IS_MULTI))
                               4796                 :                :             {
                               4797                 :                :                 /*
                               4798                 :                :                  * Otherwise check if it committed or aborted.  Note we cannot
                               4799                 :                :                  * be here if the tuple was only locked by somebody who didn't
                               4800                 :                :                  * conflict with us; that would have been handled above.  So
                               4801                 :                :                  * that transaction must necessarily be gone by now.  But
                               4802                 :                :                  * don't check for this in the multixact case, because some
                               4803                 :                :                  * locker transactions might still be running.
                               4804                 :                :                  */
    3 akorotkov@postgresql     4805                 :             76 :                 UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
                               4806                 :                :             }
                               4807                 :                :         }
                               4808                 :                : 
                               4809                 :                :         /* By here, we're certain that we hold buffer exclusive lock again */
                               4810                 :                : 
                               4811                 :                :         /*
                               4812                 :                :          * We may lock if previous xmax aborted, or if it committed but only
                               4813                 :                :          * locked the tuple without updating it; or if we didn't have to wait
                               4814                 :                :          * at all for whatever reason.
                               4815                 :                :          */
 4099 alvherre@alvh.no-ip.     4816         [ +  + ]:           6172 :         if (!require_sleep ||
                               4817         [ +  + ]:            108 :             (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
                               4818   [ +  +  +  -  :            141 :             HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
                                              +  + ]
                               4819                 :             63 :             HeapTupleHeaderIsOnlyLocked(tuple->t_data))
 1849 andres@anarazel.de       4820                 :           6116 :             result = TM_Ok;
 1147 alvherre@alvh.no-ip.     4821         [ +  + ]:             56 :         else if (!ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid))
 1849 andres@anarazel.de       4822                 :             45 :             result = TM_Updated;
                               4823                 :                :         else
                               4824                 :             11 :             result = TM_Deleted;
                               4825                 :                :     }
                               4826                 :                : 
 4099 alvherre@alvh.no-ip.     4827                 :          75902 : failed:
 1849 andres@anarazel.de       4828         [ +  + ]:          82256 :     if (result != TM_Ok)
                               4829                 :                :     {
                               4830   [ +  +  +  +  :            244 :         Assert(result == TM_SelfModified || result == TM_Updated ||
                                        +  +  -  + ]
                               4831                 :                :                result == TM_Deleted || result == TM_WouldBlock);
                               4832                 :                : 
                               4833                 :                :         /*
                               4834                 :                :          * When locking a tuple under LockWaitSkip semantics and we fail with
                               4835                 :                :          * TM_WouldBlock above, it's possible for concurrent transactions to
                               4836                 :                :          * release the lock and set HEAP_XMAX_INVALID in the meantime.  So
                               4837                 :                :          * this assert is slightly different from the equivalent one in
                               4838                 :                :          * heap_delete and heap_update.
                               4839                 :                :          */
  831 alvherre@alvh.no-ip.     4840   [ +  +  -  + ]:            244 :         Assert((result == TM_WouldBlock) ||
                               4841                 :                :                !(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
 1849 andres@anarazel.de       4842   [ +  +  -  + ]:            244 :         Assert(result != TM_Updated ||
                               4843                 :                :                !ItemPointerEquals(&tuple->t_self, &tuple->t_data->t_ctid));
                               4844                 :            244 :         tmfd->ctid = tuple->t_data->t_ctid;
                               4845   [ +  -  +  +  :            244 :         tmfd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                                              +  + ]
                               4846         [ +  + ]:            244 :         if (result == TM_SelfModified)
                               4847                 :              6 :             tmfd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
                               4848                 :                :         else
                               4849                 :            238 :             tmfd->cmax = InvalidCommandId;
 2827                          4850                 :            244 :         goto out_locked;
                               4851                 :                :     }
                               4852                 :                : 
                               4853                 :                :     /*
                               4854                 :                :      * If we didn't pin the visibility map page and the page has become all
                               4855                 :                :      * visible while we were busy locking the buffer, or during some
                               4856                 :                :      * subsequent window during which we had it unlocked, we'll have to unlock
                               4857                 :                :      * and re-lock, to avoid holding the buffer lock across I/O.  That's a bit
                               4858                 :                :      * unfortunate, especially since we'll now have to recheck whether the
                               4859                 :                :      * tuple has been locked or updated under us, but hopefully it won't
                               4860                 :                :      * happen very often.
                               4861                 :                :      */
 2810                          4862   [ +  +  -  + ]:          82012 :     if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
                               4863                 :                :     {
    3 akorotkov@postgresql     4864                 :UBC           0 :         LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
 2810 andres@anarazel.de       4865                 :              0 :         visibilitymap_pin(relation, block, &vmbuffer);
    3 akorotkov@postgresql     4866                 :              0 :         LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE);
 2810 andres@anarazel.de       4867                 :              0 :         goto l3;
                               4868                 :                :     }
                               4869                 :                : 
 4099 alvherre@alvh.no-ip.     4870                 :CBC       82012 :     xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
                               4871                 :          82012 :     old_infomask = tuple->t_data->t_infomask;
                               4872                 :                : 
                               4873                 :                :     /*
                               4874                 :                :      * If this is the first possibly-multixact-able operation in the current
                               4875                 :                :      * transaction, set my per-backend OldestMemberMXactId setting. We can be
                               4876                 :                :      * certain that the transaction will never become a member of any older
                               4877                 :                :      * MultiXactIds than that.  (We have to do this even if we end up just
                               4878                 :                :      * using our own TransactionId below, since some other backend could
                               4879                 :                :      * incorporate our XID into a MultiXact immediately afterwards.)
                               4880                 :                :      */
                               4881                 :          82012 :     MultiXactIdSetOldestMember();
                               4882                 :                : 
                               4883                 :                :     /*
                               4884                 :                :      * Compute the new xmax and infomask to store into the tuple.  Note we do
                               4885                 :                :      * not modify the tuple just yet, because that would leave it in the wrong
                               4886                 :                :      * state if multixact.c elogs.
                               4887                 :                :      */
                               4888                 :          82012 :     compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
                               4889                 :                :                               GetCurrentTransactionId(), mode, false,
                               4890                 :                :                               &xid, &new_infomask, &new_infomask2);
                               4891                 :                : 
 6926 tgl@sss.pgh.pa.us        4892                 :          82012 :     START_CRIT_SECTION();
                               4893                 :                : 
                               4894                 :                :     /*
                               4895                 :                :      * Store transaction information of xact locking the tuple.
                               4896                 :                :      *
                               4897                 :                :      * Note: Cmax is meaningless in this context, so don't set it; this avoids
                               4898                 :                :      * possibly generating a useless combo CID.  Moreover, if we're locking a
                               4899                 :                :      * previously updated tuple, it's important to preserve the Cmax.
                               4900                 :                :      *
                               4901                 :                :      * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
                               4902                 :                :      * we would break the HOT chain.
                               4903                 :                :      */
 4099 alvherre@alvh.no-ip.     4904                 :          82012 :     tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
                               4905                 :          82012 :     tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               4906                 :          82012 :     tuple->t_data->t_infomask |= new_infomask;
                               4907                 :          82012 :     tuple->t_data->t_infomask2 |= new_infomask2;
                               4908   [ +  +  -  + ]:          82012 :     if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
                               4909                 :          81973 :         HeapTupleHeaderClearHotUpdated(tuple->t_data);
 7150 tgl@sss.pgh.pa.us        4910                 :          82012 :     HeapTupleHeaderSetXmax(tuple->t_data, xid);
                               4911                 :                : 
                               4912                 :                :     /*
                               4913                 :                :      * Make sure there is no forward chain link in t_ctid.  Note that in the
                               4914                 :                :      * cases where the tuple has been updated, we must not overwrite t_ctid,
                               4915                 :                :      * because it was set by the updater.  Moreover, if the tuple has been
                               4916                 :                :      * updated, we need to follow the update chain to lock the new versions of
                               4917                 :                :      * the tuple as well.
                               4918                 :                :      */
 4099 alvherre@alvh.no-ip.     4919   [ +  +  -  + ]:          82012 :     if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
                               4920                 :          81973 :         tuple->t_data->t_ctid = *tid;
                               4921                 :                : 
                               4922                 :                :     /* Clear only the all-frozen bit on visibility map if needed */
 2827 andres@anarazel.de       4923   [ +  +  +  + ]:          83670 :     if (PageIsAllVisible(page) &&
                               4924                 :           1658 :         visibilitymap_clear(relation, block, vmbuffer,
                               4925                 :                :                             VISIBILITYMAP_ALL_FROZEN))
                               4926                 :             14 :         cleared_all_frozen = true;
                               4927                 :                : 
                               4928                 :                : 
    3 akorotkov@postgresql     4929                 :          82012 :     MarkBufferDirty(*buffer);
                               4930                 :                : 
                               4931                 :                :     /*
                               4932                 :                :      * XLOG stuff.  You might think that we don't need an XLOG record because
                               4933                 :                :      * there is no state change worth restoring after a crash.  You would be
                               4934                 :                :      * wrong however: we have just written either a TransactionId or a
                               4935                 :                :      * MultiXactId that may never have been seen on disk before, and we need
                               4936                 :                :      * to make sure that there are XLOG entries covering those ID numbers.
                               4937                 :                :      * Else the same IDs might be re-used after a crash, which would be
                               4938                 :                :      * disastrous if this page made it to disk before the crash.  Essentially
                               4939                 :                :      * we have to enforce the WAL log-before-data rule even in this case.
                               4940                 :                :      * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
                               4941                 :                :      * entries for everything anyway.)
                               4942                 :                :      */
 4871 rhaas@postgresql.org     4943   [ +  +  +  +  :          82012 :     if (RelationNeedsWAL(relation))
                                        +  -  +  - ]
                               4944                 :                :     {
                               4945                 :                :         xl_heap_lock xlrec;
                               4946                 :                :         XLogRecPtr  recptr;
                               4947                 :                : 
 3433 heikki.linnakangas@i     4948                 :          81451 :         XLogBeginInsert();
    3 akorotkov@postgresql     4949                 :          81451 :         XLogRegisterBuffer(0, *buffer, REGBUF_STANDARD);
                               4950                 :                : 
 3433 heikki.linnakangas@i     4951                 :          81451 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
  369 pg@bowt.ie               4952                 :          81451 :         xlrec.xmax = xid;
 4099 alvherre@alvh.no-ip.     4953                 :         162902 :         xlrec.infobits_set = compute_infobits(new_infomask,
                               4954                 :          81451 :                                               tuple->t_data->t_infomask2);
 2827 andres@anarazel.de       4955                 :          81451 :         xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
 3433 heikki.linnakangas@i     4956                 :          81451 :         XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
                               4957                 :                : 
                               4958                 :                :         /* we don't decode row locks atm, so no need to log the origin */
                               4959                 :                : 
                               4960                 :          81451 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
                               4961                 :                : 
 5754 tgl@sss.pgh.pa.us        4962                 :          81451 :         PageSetLSN(page, recptr);
                               4963                 :                :     }
                               4964                 :                : 
 6926                          4965         [ -  + ]:          82012 :     END_CRIT_SECTION();
                               4966                 :                : 
 1849 andres@anarazel.de       4967                 :          82012 :     result = TM_Ok;
                               4968                 :                : 
 2827                          4969                 :          82268 : out_locked:
    3 akorotkov@postgresql     4970                 :          82268 :     LockBuffer(*buffer, BUFFER_LOCK_UNLOCK);
                               4971                 :                : 
 2827 andres@anarazel.de       4972                 :          82700 : out_unlocked:
                               4973         [ +  + ]:          82700 :     if (BufferIsValid(vmbuffer))
                               4974                 :           1658 :         ReleaseBuffer(vmbuffer);
                               4975                 :                : 
                               4976                 :                :     /*
                               4977                 :                :      * Don't update the visibility map here. Locking a tuple doesn't change
                               4978                 :                :      * visibility info.
                               4979                 :                :      */
                               4980                 :                : 
                               4981                 :                :     /*
                               4982                 :                :      * Now that we have successfully marked the tuple as locked, we can
                               4983                 :                :      * release the lmgr tuple lock, if we had it.
                               4984                 :                :      */
 6924 tgl@sss.pgh.pa.us        4985         [ +  + ]:          82700 :     if (have_tuple_lock)
 4099 alvherre@alvh.no-ip.     4986                 :            137 :         UnlockTupleTuplock(relation, tid, mode);
                               4987                 :                : 
 2827 andres@anarazel.de       4988                 :          82700 :     return result;
                               4989                 :                : }
                               4990                 :                : 
                               4991                 :                : /*
                               4992                 :                :  * Acquire heavyweight lock on the given tuple, in preparation for acquiring
                               4993                 :                :  * its normal, Xmax-based tuple lock.
                               4994                 :                :  *
                               4995                 :                :  * have_tuple_lock is an input and output parameter: on input, it indicates
                               4996                 :                :  * whether the lock has previously been acquired (and this function does
                               4997                 :                :  * nothing in that case).  If this function returns success, have_tuple_lock
                               4998                 :                :  * has been flipped to true.
                               4999                 :                :  *
                               5000                 :                :  * Returns false if it was unable to obtain the lock; this can only happen if
                               5001                 :                :  * wait_policy is Skip.
                               5002                 :                :  */
                               5003                 :                : static bool
 3397 alvherre@alvh.no-ip.     5004                 :            260 : heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode,
                               5005                 :                :                      LockWaitPolicy wait_policy, bool *have_tuple_lock)
                               5006                 :                : {
                               5007         [ +  + ]:            260 :     if (*have_tuple_lock)
                               5008                 :              9 :         return true;
                               5009                 :                : 
                               5010   [ +  +  +  - ]:            251 :     switch (wait_policy)
                               5011                 :                :     {
                               5012                 :            210 :         case LockWaitBlock:
                               5013                 :            210 :             LockTupleTuplock(relation, tid, mode);
                               5014                 :            210 :             break;
                               5015                 :                : 
                               5016                 :             34 :         case LockWaitSkip:
                               5017         [ +  + ]:             34 :             if (!ConditionalLockTupleTuplock(relation, tid, mode))
                               5018                 :              1 :                 return false;
                               5019                 :             33 :             break;
                               5020                 :                : 
                               5021                 :              7 :         case LockWaitError:
                               5022         [ +  + ]:              7 :             if (!ConditionalLockTupleTuplock(relation, tid, mode))
                               5023         [ +  - ]:              1 :                 ereport(ERROR,
                               5024                 :                :                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
                               5025                 :                :                          errmsg("could not obtain lock on row in relation \"%s\"",
                               5026                 :                :                                 RelationGetRelationName(relation))));
                               5027                 :              6 :             break;
                               5028                 :                :     }
                               5029                 :            249 :     *have_tuple_lock = true;
                               5030                 :                : 
                               5031                 :            249 :     return true;
                               5032                 :                : }
                               5033                 :                : 
                               5034                 :                : /*
                               5035                 :                :  * Given an original set of Xmax and infomask, and a transaction (identified by
                               5036                 :                :  * add_to_xmax) acquiring a new lock of some mode, compute the new Xmax and
                               5037                 :                :  * corresponding infomasks to use on the tuple.
                               5038                 :                :  *
                               5039                 :                :  * Note that this might have side effects such as creating a new MultiXactId.
                               5040                 :                :  *
                               5041                 :                :  * Most callers will have called HeapTupleSatisfiesUpdate before this function;
                               5042                 :                :  * that will have set the HEAP_XMAX_INVALID bit if the xmax was a MultiXactId
                               5043                 :                :  * but it was not running anymore. There is a race condition, which is that the
                               5044                 :                :  * MultiXactId may have finished since then, but that uncommon case is handled
                               5045                 :                :  * either here, or within MultiXactIdExpand.
                               5046                 :                :  *
                               5047                 :                :  * There is a similar race condition possible when the old xmax was a regular
                               5048                 :                :  * TransactionId.  We test TransactionIdIsInProgress again just to narrow the
                               5049                 :                :  * window, but it's still possible to end up creating an unnecessary
                               5050                 :                :  * MultiXactId.  Fortunately this is harmless.
                               5051                 :                :  */
                               5052                 :                : static void
 4099                          5053                 :        1932106 : compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask,
                               5054                 :                :                           uint16 old_infomask2, TransactionId add_to_xmax,
                               5055                 :                :                           LockTupleMode mode, bool is_update,
                               5056                 :                :                           TransactionId *result_xmax, uint16 *result_infomask,
                               5057                 :                :                           uint16 *result_infomask2)
                               5058                 :                : {
                               5059                 :                :     TransactionId new_xmax;
                               5060                 :                :     uint16      new_infomask,
                               5061                 :                :                 new_infomask2;
                               5062                 :                : 
 3769                          5063         [ +  - ]:        1932106 :     Assert(TransactionIdIsCurrentTransactionId(add_to_xmax));
                               5064                 :                : 
 4099                          5065                 :        2036120 : l5:
                               5066                 :        2036120 :     new_infomask = 0;
                               5067                 :        2036120 :     new_infomask2 = 0;
                               5068         [ +  + ]:        2036120 :     if (old_infomask & HEAP_XMAX_INVALID)
                               5069                 :                :     {
                               5070                 :                :         /*
                               5071                 :                :          * No previous locker; we just insert our own TransactionId.
                               5072                 :                :          *
                               5073                 :                :          * Note that it's critical that this case be the first one checked,
                               5074                 :                :          * because there are several blocks below that come back to this one
                               5075                 :                :          * to implement certain optimizations; old_infomask might contain
                               5076                 :                :          * other dirty bits in those cases, but we don't really care.
                               5077                 :                :          */
                               5078         [ +  + ]:        1930982 :         if (is_update)
                               5079                 :                :         {
                               5080                 :        1709479 :             new_xmax = add_to_xmax;
                               5081         [ +  + ]:        1709479 :             if (mode == LockTupleExclusive)
                               5082                 :        1468351 :                 new_infomask2 |= HEAP_KEYS_UPDATED;
                               5083                 :                :         }
                               5084                 :                :         else
                               5085                 :                :         {
                               5086                 :         221503 :             new_infomask |= HEAP_XMAX_LOCK_ONLY;
                               5087   [ +  +  +  +  :         221503 :             switch (mode)
                                                 - ]
                               5088                 :                :             {
                               5089                 :           2471 :                 case LockTupleKeyShare:
                               5090                 :           2471 :                     new_xmax = add_to_xmax;
                               5091                 :           2471 :                     new_infomask |= HEAP_XMAX_KEYSHR_LOCK;
                               5092                 :           2471 :                     break;
                               5093                 :            708 :                 case LockTupleShare:
                               5094                 :            708 :                     new_xmax = add_to_xmax;
                               5095                 :            708 :                     new_infomask |= HEAP_XMAX_SHR_LOCK;
                               5096                 :            708 :                     break;
                               5097                 :         123687 :                 case LockTupleNoKeyExclusive:
                               5098                 :         123687 :                     new_xmax = add_to_xmax;
                               5099                 :         123687 :                     new_infomask |= HEAP_XMAX_EXCL_LOCK;
                               5100                 :         123687 :                     break;
                               5101                 :          94637 :                 case LockTupleExclusive:
                               5102                 :          94637 :                     new_xmax = add_to_xmax;
                               5103                 :          94637 :                     new_infomask |= HEAP_XMAX_EXCL_LOCK;
                               5104                 :          94637 :                     new_infomask2 |= HEAP_KEYS_UPDATED;
                               5105                 :          94637 :                     break;
 4099 alvherre@alvh.no-ip.     5106                 :UBC           0 :                 default:
                               5107                 :              0 :                     new_xmax = InvalidTransactionId;    /* silence compiler */
                               5108         [ #  # ]:              0 :                     elog(ERROR, "invalid lock mode");
                               5109                 :                :             }
                               5110                 :                :         }
                               5111                 :                :     }
 4099 alvherre@alvh.no-ip.     5112         [ +  + ]:CBC      105138 :     else if (old_infomask & HEAP_XMAX_IS_MULTI)
                               5113                 :                :     {
                               5114                 :                :         MultiXactStatus new_status;
                               5115                 :                : 
                               5116                 :                :         /*
                               5117                 :                :          * Currently we don't allow XMAX_COMMITTED to be set for multis, so
                               5118                 :                :          * cross-check.
                               5119                 :                :          */
                               5120         [ -  + ]:            121 :         Assert(!(old_infomask & HEAP_XMAX_COMMITTED));
                               5121                 :                : 
                               5122                 :                :         /*
                               5123                 :                :          * A multixact together with LOCK_ONLY set but neither lock bit set
                               5124                 :                :          * (i.e. a pg_upgraded share locked tuple) cannot possibly be running
                               5125                 :                :          * anymore.  This check is critical for databases upgraded by
                               5126                 :                :          * pg_upgrade; both MultiXactIdIsRunning and MultiXactIdExpand assume
                               5127                 :                :          * that such multis are never passed.
                               5128                 :                :          */
 2851                          5129   [ +  -  +  +  :            121 :         if (HEAP_LOCKED_UPGRADED(old_infomask))
                                              -  + ]
                               5130                 :                :         {
 4099 alvherre@alvh.no-ip.     5131                 :UBC           0 :             old_infomask &= ~HEAP_XMAX_IS_MULTI;
                               5132                 :              0 :             old_infomask |= HEAP_XMAX_INVALID;
                               5133                 :              0 :             goto l5;
                               5134                 :                :         }
                               5135                 :                : 
                               5136                 :                :         /*
                               5137                 :                :          * If the XMAX is already a MultiXactId, then we need to expand it to
                               5138                 :                :          * include add_to_xmax; but if all the members were lockers and are
                               5139                 :                :          * all gone, we can do away with the IS_MULTI bit and just set
                               5140                 :                :          * add_to_xmax as the only locker/updater.  If all lockers are gone
                               5141                 :                :          * and we have an updater that aborted, we can also do without a
                               5142                 :                :          * multi.
                               5143                 :                :          *
                               5144                 :                :          * The cost of doing GetMultiXactIdMembers would be paid by
                               5145                 :                :          * MultiXactIdExpand if we weren't to do this, so this check is not
                               5146                 :                :          * incurring extra work anyhow.
                               5147                 :                :          */
 3547 alvherre@alvh.no-ip.     5148   [ +  +  -  +  :CBC         121 :         if (!MultiXactIdIsRunning(xmax, HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)))
                                              +  + ]
                               5149                 :                :         {
 4099                          5150   [ +  +  +  - ]:             24 :             if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) ||
 3292                          5151         [ +  - ]:              9 :                 !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax,
                               5152                 :                :                                                                 old_infomask)))
                               5153                 :                :             {
                               5154                 :                :                 /*
                               5155                 :                :                  * Reset these bits and restart; otherwise fall through to
                               5156                 :                :                  * create a new multi below.
                               5157                 :                :                  */
 4099                          5158                 :             24 :                 old_infomask &= ~HEAP_XMAX_IS_MULTI;
                               5159                 :             24 :                 old_infomask |= HEAP_XMAX_INVALID;
                               5160                 :             24 :                 goto l5;
                               5161                 :                :             }
                               5162                 :                :         }
                               5163                 :                : 
                               5164                 :             97 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5165                 :                : 
                               5166                 :             97 :         new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax,
                               5167                 :                :                                      new_status);
                               5168                 :             97 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5169                 :                :     }
                               5170         [ +  + ]:         105017 :     else if (old_infomask & HEAP_XMAX_COMMITTED)
                               5171                 :                :     {
                               5172                 :                :         /*
                               5173                 :                :          * It's a committed update, so we need to preserve him as updater of
                               5174                 :                :          * the tuple.
                               5175                 :                :          */
                               5176                 :                :         MultiXactStatus status;
                               5177                 :                :         MultiXactStatus new_status;
                               5178                 :                : 
                               5179         [ -  + ]:             13 :         if (old_infomask2 & HEAP_KEYS_UPDATED)
 4099 alvherre@alvh.no-ip.     5180                 :UBC           0 :             status = MultiXactStatusUpdate;
                               5181                 :                :         else
 4099 alvherre@alvh.no-ip.     5182                 :CBC          13 :             status = MultiXactStatusNoKeyUpdate;
                               5183                 :                : 
                               5184                 :             13 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5185                 :                : 
                               5186                 :                :         /*
                               5187                 :                :          * since it's not running, it's obviously impossible for the old
                               5188                 :                :          * updater to be identical to the current one, so we need not check
                               5189                 :                :          * for that case as we do in the block above.
                               5190                 :                :          */
                               5191                 :             13 :         new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
                               5192                 :             13 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5193                 :                :     }
                               5194         [ +  + ]:         105004 :     else if (TransactionIdIsInProgress(xmax))
                               5195                 :                :     {
                               5196                 :                :         /*
                               5197                 :                :          * If the XMAX is a valid, in-progress TransactionId, then we need to
                               5198                 :                :          * create a new MultiXactId that includes both the old locker or
                               5199                 :                :          * updater and our own TransactionId.
                               5200                 :                :          */
                               5201                 :                :         MultiXactStatus new_status;
                               5202                 :                :         MultiXactStatus old_status;
                               5203                 :                :         LockTupleMode old_mode;
                               5204                 :                : 
                               5205   [ +  +  -  + ]:         104995 :         if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
                               5206                 :                :         {
                               5207         [ +  + ]:         104969 :             if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
 3769                          5208                 :           5615 :                 old_status = MultiXactStatusForKeyShare;
 4099                          5209         [ +  + ]:          99354 :             else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
 3769                          5210                 :            431 :                 old_status = MultiXactStatusForShare;
 4099                          5211         [ +  - ]:          98923 :             else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
                               5212                 :                :             {
                               5213         [ +  + ]:          98923 :                 if (old_infomask2 & HEAP_KEYS_UPDATED)
 3769                          5214                 :          92817 :                     old_status = MultiXactStatusForUpdate;
                               5215                 :                :                 else
                               5216                 :           6106 :                     old_status = MultiXactStatusForNoKeyUpdate;
                               5217                 :                :             }
                               5218                 :                :             else
                               5219                 :                :             {
                               5220                 :                :                 /*
                               5221                 :                :                  * LOCK_ONLY can be present alone only when a page has been
                               5222                 :                :                  * upgraded by pg_upgrade.  But in that case,
                               5223                 :                :                  * TransactionIdIsInProgress() should have returned false.  We
                               5224                 :                :                  * assume it's no longer locked in this case.
                               5225                 :                :                  */
 4099 alvherre@alvh.no-ip.     5226         [ #  # ]:UBC           0 :                 elog(WARNING, "LOCK_ONLY found for Xid in progress %u", xmax);
                               5227                 :              0 :                 old_infomask |= HEAP_XMAX_INVALID;
                               5228                 :              0 :                 old_infomask &= ~HEAP_XMAX_LOCK_ONLY;
                               5229                 :              0 :                 goto l5;
                               5230                 :                :             }
                               5231                 :                :         }
                               5232                 :                :         else
                               5233                 :                :         {
                               5234                 :                :             /* it's an update, but which kind? */
 4099 alvherre@alvh.no-ip.     5235         [ -  + ]:CBC          26 :             if (old_infomask2 & HEAP_KEYS_UPDATED)
 3769 alvherre@alvh.no-ip.     5236                 :UBC           0 :                 old_status = MultiXactStatusUpdate;
                               5237                 :                :             else
 3769 alvherre@alvh.no-ip.     5238                 :CBC          26 :                 old_status = MultiXactStatusNoKeyUpdate;
                               5239                 :                :         }
                               5240                 :                : 
                               5241                 :         104995 :         old_mode = TUPLOCK_from_mxstatus(old_status);
                               5242                 :                : 
                               5243                 :                :         /*
                               5244                 :                :          * If the lock to be acquired is for the same TransactionId as the
                               5245                 :                :          * existing lock, there's an optimization possible: consider only the
                               5246                 :                :          * strongest of both locks as the only one present, and restart.
                               5247                 :                :          */
 4099                          5248         [ +  + ]:         104995 :         if (xmax == add_to_xmax)
                               5249                 :                :         {
                               5250                 :                :             /*
                               5251                 :                :              * Note that it's not possible for the original tuple to be
                               5252                 :                :              * updated: we wouldn't be here because the tuple would have been
                               5253                 :                :              * invisible and we wouldn't try to update it.  As a subtlety,
                               5254                 :                :              * this code can also run when traversing an update chain to lock
                               5255                 :                :              * future versions of a tuple.  But we wouldn't be here either,
                               5256                 :                :              * because the add_to_xmax would be different from the original
                               5257                 :                :              * updater.
                               5258                 :                :              */
 3769                          5259   [ -  +  -  - ]:         103982 :             Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
                               5260                 :                : 
                               5261                 :                :             /* acquire the strongest of both */
                               5262         [ +  + ]:         103982 :             if (mode < old_mode)
                               5263                 :          52257 :                 mode = old_mode;
                               5264                 :                :             /* mustn't touch is_update */
                               5265                 :                : 
                               5266                 :         103982 :             old_infomask |= HEAP_XMAX_INVALID;
                               5267                 :         103982 :             goto l5;
                               5268                 :                :         }
                               5269                 :                : 
                               5270                 :                :         /* otherwise, just fall back to creating a new multixact */
                               5271                 :           1013 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5272                 :           1013 :         new_xmax = MultiXactIdCreate(xmax, old_status,
                               5273                 :                :                                      add_to_xmax, new_status);
 4099                          5274                 :           1013 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5275                 :                :     }
                               5276   [ +  +  +  -  :             14 :     else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
                                              +  + ]
                               5277                 :              5 :              TransactionIdDidCommit(xmax))
                               5278                 :              1 :     {
                               5279                 :                :         /*
                               5280                 :                :          * It's a committed update, so we gotta preserve him as updater of the
                               5281                 :                :          * tuple.
                               5282                 :                :          */
                               5283                 :                :         MultiXactStatus status;
                               5284                 :                :         MultiXactStatus new_status;
                               5285                 :                : 
                               5286         [ -  + ]:              1 :         if (old_infomask2 & HEAP_KEYS_UPDATED)
 4099 alvherre@alvh.no-ip.     5287                 :UBC           0 :             status = MultiXactStatusUpdate;
                               5288                 :                :         else
 4099 alvherre@alvh.no-ip.     5289                 :CBC           1 :             status = MultiXactStatusNoKeyUpdate;
                               5290                 :                : 
                               5291                 :              1 :         new_status = get_mxact_status_for_lock(mode, is_update);
                               5292                 :                : 
                               5293                 :                :         /*
                               5294                 :                :          * since it's not running, it's obviously impossible for the old
                               5295                 :                :          * updater to be identical to the current one, so we need not check
                               5296                 :                :          * for that case as we do in the block above.
                               5297                 :                :          */
                               5298                 :              1 :         new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status);
                               5299                 :              1 :         GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2);
                               5300                 :                :     }
                               5301                 :                :     else
                               5302                 :                :     {
                               5303                 :                :         /*
                               5304                 :                :          * Can get here iff the locking/updating transaction was running when
                               5305                 :                :          * the infomask was extracted from the tuple, but finished before
                               5306                 :                :          * TransactionIdIsInProgress got to run.  Deal with it as if there was
                               5307                 :                :          * no locker at all in the first place.
                               5308                 :                :          */
                               5309                 :              8 :         old_infomask |= HEAP_XMAX_INVALID;
                               5310                 :              8 :         goto l5;
                               5311                 :                :     }
                               5312                 :                : 
                               5313                 :        1932106 :     *result_infomask = new_infomask;
                               5314                 :        1932106 :     *result_infomask2 = new_infomask2;
                               5315                 :        1932106 :     *result_xmax = new_xmax;
                               5316                 :        1932106 : }
                               5317                 :                : 
                               5318                 :                : /*
                               5319                 :                :  * Subroutine for heap_lock_updated_tuple_rec.
                               5320                 :                :  *
                               5321                 :                :  * Given a hypothetical multixact status held by the transaction identified
                               5322                 :                :  * with the given xid, does the current transaction need to wait, fail, or can
                               5323                 :                :  * it continue if it wanted to acquire a lock of the given mode?  "needwait"
                               5324                 :                :  * is set to true if waiting is necessary; if it can continue, then TM_Ok is
                               5325                 :                :  * returned.  If the lock is already held by the current transaction, return
                               5326                 :                :  * TM_SelfModified.  In case of a conflict with another transaction, a
                               5327                 :                :  * different HeapTupleSatisfiesUpdate return code is returned.
                               5328                 :                :  *
                               5329                 :                :  * The held status is said to be hypothetical because it might correspond to a
                               5330                 :                :  * lock held by a single Xid, i.e. not a real MultiXactId; we express it this
                               5331                 :                :  * way for simplicity of API.
                               5332                 :                :  */
                               5333                 :                : static TM_Result
 3791                          5334                 :             32 : test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid,
                               5335                 :                :                            LockTupleMode mode, HeapTuple tup,
                               5336                 :                :                            bool *needwait)
                               5337                 :                : {
                               5338                 :                :     MultiXactStatus wantedstatus;
                               5339                 :                : 
                               5340                 :             32 :     *needwait = false;
                               5341                 :             32 :     wantedstatus = get_mxact_status_for_lock(mode, false);
                               5342                 :                : 
                               5343                 :                :     /*
                               5344                 :                :      * Note: we *must* check TransactionIdIsInProgress before
                               5345                 :                :      * TransactionIdDidAbort/Commit; see comment at top of heapam_visibility.c
                               5346                 :                :      * for an explanation.
                               5347                 :                :      */
                               5348         [ -  + ]:             32 :     if (TransactionIdIsCurrentTransactionId(xid))
                               5349                 :                :     {
                               5350                 :                :         /*
                               5351                 :                :          * The tuple has already been locked by our own transaction.  This is
                               5352                 :                :          * very rare but can happen if multiple transactions are trying to
                               5353                 :                :          * lock an ancient version of the same tuple.
                               5354                 :                :          */
 1849 andres@anarazel.de       5355                 :UBC           0 :         return TM_SelfModified;
                               5356                 :                :     }
 3791 alvherre@alvh.no-ip.     5357         [ +  + ]:CBC          32 :     else if (TransactionIdIsInProgress(xid))
                               5358                 :                :     {
                               5359                 :                :         /*
                               5360                 :                :          * If the locking transaction is running, what we do depends on
                               5361                 :                :          * whether the lock modes conflict: if they do, then we must wait for
                               5362                 :                :          * it to finish; otherwise we can fall through to lock this tuple
                               5363                 :                :          * version without waiting.
                               5364                 :                :          */
                               5365         [ +  + ]:             16 :         if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
                               5366                 :             16 :                                 LOCKMODE_from_mxstatus(wantedstatus)))
                               5367                 :                :         {
                               5368                 :              8 :             *needwait = true;
                               5369                 :                :         }
                               5370                 :                : 
                               5371                 :                :         /*
                               5372                 :                :          * If we set needwait above, then this value doesn't matter;
                               5373                 :                :          * otherwise, this value signals to caller that it's okay to proceed.
                               5374                 :                :          */
 1849 andres@anarazel.de       5375                 :             16 :         return TM_Ok;
                               5376                 :                :     }
 3791 alvherre@alvh.no-ip.     5377         [ +  + ]:             16 :     else if (TransactionIdDidAbort(xid))
 1849 andres@anarazel.de       5378                 :              3 :         return TM_Ok;
 3791 alvherre@alvh.no-ip.     5379         [ +  - ]:             13 :     else if (TransactionIdDidCommit(xid))
                               5380                 :                :     {
                               5381                 :                :         /*
                               5382                 :                :          * The other transaction committed.  If it was only a locker, then the
                               5383                 :                :          * lock is completely gone now and we can return success; but if it
                               5384                 :                :          * was an update, then what we do depends on whether the two lock
                               5385                 :                :          * modes conflict.  If they conflict, then we must report error to
                               5386                 :                :          * caller. But if they don't, we can fall through to allow the current
                               5387                 :                :          * transaction to lock the tuple.
                               5388                 :                :          *
                               5389                 :                :          * Note: the reason we worry about ISUPDATE here is because as soon as
                               5390                 :                :          * a transaction ends, all its locks are gone and meaningless, and
                               5391                 :                :          * thus we can ignore them; whereas its updates persist.  In the
                               5392                 :                :          * TransactionIdIsInProgress case, above, we don't need to check
                               5393                 :                :          * because we know the lock is still "alive" and thus a conflict needs
                               5394                 :                :          * always be checked.
                               5395                 :                :          */
 3783                          5396         [ +  + ]:             13 :         if (!ISUPDATE_from_mxstatus(status))
 1849 andres@anarazel.de       5397                 :              4 :             return TM_Ok;
                               5398                 :                : 
 3791 alvherre@alvh.no-ip.     5399         [ +  + ]:              9 :         if (DoLockModesConflict(LOCKMODE_from_mxstatus(status),
                               5400                 :              9 :                                 LOCKMODE_from_mxstatus(wantedstatus)))
                               5401                 :                :         {
                               5402                 :                :             /* bummer */
 1147                          5403         [ +  + ]:              8 :             if (!ItemPointerEquals(&tup->t_self, &tup->t_data->t_ctid))
 1849 andres@anarazel.de       5404                 :              6 :                 return TM_Updated;
                               5405                 :                :             else
                               5406                 :              2 :                 return TM_Deleted;
                               5407                 :                :         }
                               5408                 :                : 
                               5409                 :              1 :         return TM_Ok;
                               5410                 :                :     }
                               5411                 :                : 
                               5412                 :                :     /* Not in progress, not aborted, not committed -- must have crashed */
 1849 andres@anarazel.de       5413                 :UBC           0 :     return TM_Ok;
                               5414                 :                : }
                               5415                 :                : 
                               5416                 :                : 
                               5417                 :                : /*
                               5418                 :                :  * Recursive part of heap_lock_updated_tuple
                               5419                 :                :  *
                               5420                 :                :  * Fetch the tuple pointed to by tid in rel, and mark it as locked by the given
                               5421                 :                :  * xid with the given mode; if this tuple is updated, recurse to lock the new
                               5422                 :                :  * version as well.
                               5423                 :                :  */
                               5424                 :                : static TM_Result
 4099 alvherre@alvh.no-ip.     5425                 :CBC          80 : heap_lock_updated_tuple_rec(Relation rel, ItemPointer tid, TransactionId xid,
                               5426                 :                :                             LockTupleMode mode)
                               5427                 :                : {
                               5428                 :                :     TM_Result   result;
                               5429                 :                :     ItemPointerData tupid;
                               5430                 :                :     HeapTupleData mytup;
                               5431                 :                :     Buffer      buf;
                               5432                 :                :     uint16      new_infomask,
                               5433                 :                :                 new_infomask2,
                               5434                 :                :                 old_infomask,
                               5435                 :                :                 old_infomask2;
                               5436                 :                :     TransactionId xmax,
                               5437                 :                :                 new_xmax;
 3791                          5438                 :             80 :     TransactionId priorXmax = InvalidTransactionId;
 2827 andres@anarazel.de       5439                 :             80 :     bool        cleared_all_frozen = false;
                               5440                 :                :     bool        pinned_desired_page;
                               5441                 :             80 :     Buffer      vmbuffer = InvalidBuffer;
                               5442                 :                :     BlockNumber block;
                               5443                 :                : 
 4099 alvherre@alvh.no-ip.     5444                 :             80 :     ItemPointerCopy(tid, &tupid);
                               5445                 :                : 
                               5446                 :                :     for (;;)
                               5447                 :                :     {
                               5448                 :             83 :         new_infomask = 0;
                               5449                 :             83 :         new_xmax = InvalidTransactionId;
 2827 andres@anarazel.de       5450                 :             83 :         block = ItemPointerGetBlockNumber(&tupid);
 4099 alvherre@alvh.no-ip.     5451                 :             83 :         ItemPointerCopy(&tupid, &(mytup.t_self));
                               5452                 :                : 
  732 tgl@sss.pgh.pa.us        5453         [ +  - ]:             83 :         if (!heap_fetch(rel, SnapshotAny, &mytup, &buf, false))
                               5454                 :                :         {
                               5455                 :                :             /*
                               5456                 :                :              * if we fail to find the updated version of the tuple, it's
                               5457                 :                :              * because it was vacuumed/pruned away after its creator
                               5458                 :                :              * transaction aborted.  So behave as if we got to the end of the
                               5459                 :                :              * chain, and there's no further tuple to lock: return success to
                               5460                 :                :              * caller.
                               5461                 :                :              */
 1849 andres@anarazel.de       5462                 :UBC           0 :             result = TM_Ok;
 2235 tgl@sss.pgh.pa.us        5463                 :              0 :             goto out_unlocked;
                               5464                 :                :         }
                               5465                 :                : 
 4099 alvherre@alvh.no-ip.     5466                 :CBC          83 : l4:
                               5467         [ -  + ]:             91 :         CHECK_FOR_INTERRUPTS();
                               5468                 :                : 
                               5469                 :                :         /*
                               5470                 :                :          * Before locking the buffer, pin the visibility map page if it
                               5471                 :                :          * appears to be necessary.  Since we haven't got the lock yet,
                               5472                 :                :          * someone else might be in the middle of changing this, so we'll need
                               5473                 :                :          * to recheck after we have the lock.
                               5474                 :                :          */
 2827 andres@anarazel.de       5475         [ -  + ]:             91 :         if (PageIsAllVisible(BufferGetPage(buf)))
                               5476                 :                :         {
 2827 andres@anarazel.de       5477                 :UBC           0 :             visibilitymap_pin(rel, block, &vmbuffer);
 2235 tgl@sss.pgh.pa.us        5478                 :              0 :             pinned_desired_page = true;
                               5479                 :                :         }
                               5480                 :                :         else
 2235 tgl@sss.pgh.pa.us        5481                 :CBC          91 :             pinned_desired_page = false;
                               5482                 :                : 
 4099 alvherre@alvh.no-ip.     5483                 :             91 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
                               5484                 :                : 
                               5485                 :                :         /*
                               5486                 :                :          * If we didn't pin the visibility map page and the page has become
                               5487                 :                :          * all visible while we were busy locking the buffer, we'll have to
                               5488                 :                :          * unlock and re-lock, to avoid holding the buffer lock across I/O.
                               5489                 :                :          * That's a bit unfortunate, but hopefully shouldn't happen often.
                               5490                 :                :          *
                               5491                 :                :          * Note: in some paths through this function, we will reach here
                               5492                 :                :          * holding a pin on a vm page that may or may not be the one matching
                               5493                 :                :          * this page.  If this page isn't all-visible, we won't use the vm
                               5494                 :                :          * page, but we hold onto such a pin till the end of the function.
                               5495                 :                :          */
 2235 tgl@sss.pgh.pa.us        5496   [ +  -  -  + ]:             91 :         if (!pinned_desired_page && PageIsAllVisible(BufferGetPage(buf)))
                               5497                 :                :         {
 2810 andres@anarazel.de       5498                 :UBC           0 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
                               5499                 :              0 :             visibilitymap_pin(rel, block, &vmbuffer);
                               5500                 :              0 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
                               5501                 :                :         }
                               5502                 :                : 
                               5503                 :                :         /*
                               5504                 :                :          * Check the tuple XMIN against prior XMAX, if any.  If we reached the
                               5505                 :                :          * end of the chain, we're done, so return success.
                               5506                 :                :          */
 3791 alvherre@alvh.no-ip.     5507   [ +  +  -  + ]:CBC          94 :         if (TransactionIdIsValid(priorXmax) &&
 2355                          5508         [ +  - ]:              3 :             !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data),
                               5509                 :                :                                  priorXmax))
                               5510                 :                :         {
 1849 andres@anarazel.de       5511                 :UBC           0 :             result = TM_Ok;
 2827                          5512                 :              0 :             goto out_locked;
                               5513                 :                :         }
                               5514                 :                : 
                               5515                 :                :         /*
                               5516                 :                :          * Also check Xmin: if this tuple was created by an aborted
                               5517                 :                :          * (sub)transaction, then we already locked the last live one in the
                               5518                 :                :          * chain, thus we're done, so return success.
                               5519                 :                :          */
 2774 alvherre@alvh.no-ip.     5520   [ +  -  +  + ]:CBC          91 :         if (TransactionIdDidAbort(HeapTupleHeaderGetXmin(mytup.t_data)))
                               5521                 :                :         {
 1849 andres@anarazel.de       5522                 :             13 :             result = TM_Ok;
 2235 tgl@sss.pgh.pa.us        5523                 :             13 :             goto out_locked;
                               5524                 :                :         }
                               5525                 :                : 
 4099 alvherre@alvh.no-ip.     5526                 :             78 :         old_infomask = mytup.t_data->t_infomask;
 3791                          5527                 :             78 :         old_infomask2 = mytup.t_data->t_infomask2;
 4099                          5528                 :             78 :         xmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
                               5529                 :                : 
                               5530                 :                :         /*
                               5531                 :                :          * If this tuple version has been updated or locked by some concurrent
                               5532                 :                :          * transaction(s), what we do depends on whether our lock mode
                               5533                 :                :          * conflicts with what those other transactions hold, and also on the
                               5534                 :                :          * status of them.
                               5535                 :                :          */
 3791                          5536         [ +  + ]:             78 :         if (!(old_infomask & HEAP_XMAX_INVALID))
                               5537                 :                :         {
                               5538                 :                :             TransactionId rawxmax;
                               5539                 :                :             bool        needwait;
                               5540                 :                : 
                               5541                 :             30 :             rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data);
                               5542         [ +  + ]:             30 :             if (old_infomask & HEAP_XMAX_IS_MULTI)
                               5543                 :                :             {
                               5544                 :                :                 int         nmembers;
                               5545                 :                :                 int         i;
                               5546                 :                :                 MultiXactMember *members;
                               5547                 :                : 
                               5548                 :                :                 /*
                               5549                 :                :                  * We don't need a test for pg_upgrade'd tuples: this is only
                               5550                 :                :                  * applied to tuples after the first in an update chain.  Said
                               5551                 :                :                  * first tuple in the chain may well be locked-in-9.2-and-
                               5552                 :                :                  * pg_upgraded, but that one was already locked by our caller,
                               5553                 :                :                  * not us; and any subsequent ones cannot be because our
                               5554                 :                :                  * caller must necessarily have obtained a snapshot later than
                               5555                 :                :                  * the pg_upgrade itself.
                               5556                 :                :                  */
 2851                          5557   [ +  -  -  +  :              1 :                 Assert(!HEAP_LOCKED_UPGRADED(mytup.t_data->t_infomask));
                                              -  - ]
                               5558                 :                : 
 3547                          5559                 :              1 :                 nmembers = GetMultiXactIdMembers(rawxmax, &members, false,
 2489 tgl@sss.pgh.pa.us        5560   [ +  -  -  + ]:              1 :                                                  HEAP_XMAX_IS_LOCKED_ONLY(old_infomask));
 3791 alvherre@alvh.no-ip.     5561         [ +  + ]:              4 :                 for (i = 0; i < nmembers; i++)
                               5562                 :                :                 {
 2827 andres@anarazel.de       5563                 :              3 :                     result = test_lockmode_for_conflict(members[i].status,
                               5564                 :              3 :                                                         members[i].xid,
                               5565                 :                :                                                         mode,
                               5566                 :                :                                                         &mytup,
                               5567                 :                :                                                         &needwait);
                               5568                 :                : 
                               5569                 :                :                     /*
                               5570                 :                :                      * If the tuple was already locked by ourselves in a
                               5571                 :                :                      * previous iteration of this (say heap_lock_tuple was
                               5572                 :                :                      * forced to restart the locking loop because of a change
                               5573                 :                :                      * in xmax), then we hold the lock already on this tuple
                               5574                 :                :                      * version and we don't need to do anything; and this is
                               5575                 :                :                      * not an error condition either.  We just need to skip
                               5576                 :                :                      * this tuple and continue locking the next version in the
                               5577                 :                :                      * update chain.
                               5578                 :                :                      */
 1849                          5579         [ -  + ]:              3 :                     if (result == TM_SelfModified)
                               5580                 :                :                     {
 2454 alvherre@alvh.no-ip.     5581                 :UBC           0 :                         pfree(members);
                               5582                 :              0 :                         goto next;
                               5583                 :                :                     }
                               5584                 :                : 
 3791 alvherre@alvh.no-ip.     5585         [ -  + ]:CBC           3 :                     if (needwait)
                               5586                 :                :                     {
 3791 alvherre@alvh.no-ip.     5587                 :UBC           0 :                         LockBuffer(buf, BUFFER_LOCK_UNLOCK);
 3679                          5588                 :              0 :                         XactLockTableWait(members[i].xid, rel,
                               5589                 :                :                                           &mytup.t_self,
                               5590                 :                :                                           XLTW_LockUpdated);
 3791                          5591                 :              0 :                         pfree(members);
                               5592                 :              0 :                         goto l4;
                               5593                 :                :                     }
 1849 andres@anarazel.de       5594         [ -  + ]:CBC           3 :                     if (result != TM_Ok)
                               5595                 :                :                     {
 3791 alvherre@alvh.no-ip.     5596                 :UBC           0 :                         pfree(members);
 2827 andres@anarazel.de       5597                 :              0 :                         goto out_locked;
                               5598                 :                :                     }
                               5599                 :                :                 }
 3791 alvherre@alvh.no-ip.     5600         [ +  - ]:CBC           1 :                 if (members)
                               5601                 :              1 :                     pfree(members);
                               5602                 :                :             }
                               5603                 :                :             else
                               5604                 :                :             {
                               5605                 :                :                 MultiXactStatus status;
                               5606                 :                : 
                               5607                 :                :                 /*
                               5608                 :                :                  * For a non-multi Xmax, we first need to compute the
                               5609                 :                :                  * corresponding MultiXactStatus by using the infomask bits.
                               5610                 :                :                  */
                               5611   [ +  +  -  + ]:             29 :                 if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask))
                               5612                 :                :                 {
                               5613         [ +  - ]:             10 :                     if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask))
                               5614                 :             10 :                         status = MultiXactStatusForKeyShare;
 3791 alvherre@alvh.no-ip.     5615         [ #  # ]:UBC           0 :                     else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask))
                               5616                 :              0 :                         status = MultiXactStatusForShare;
                               5617         [ #  # ]:              0 :                     else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))
                               5618                 :                :                     {
                               5619         [ #  # ]:              0 :                         if (old_infomask2 & HEAP_KEYS_UPDATED)
                               5620                 :              0 :                             status = MultiXactStatusForUpdate;
                               5621                 :                :                         else
                               5622                 :              0 :                             status = MultiXactStatusForNoKeyUpdate;
                               5623                 :                :                     }
                               5624                 :                :                     else
                               5625                 :                :                     {
                               5626                 :                :                         /*
                               5627                 :                :                          * LOCK_ONLY present alone (a pg_upgraded tuple marked
                               5628                 :                :                          * as share-locked in the old cluster) shouldn't be
                               5629                 :                :                          * seen in the middle of an update chain.
                               5630                 :                :                          */
                               5631         [ #  # ]:              0 :                         elog(ERROR, "invalid lock status in tuple");
                               5632                 :                :                     }
                               5633                 :                :                 }
                               5634                 :                :                 else
                               5635                 :                :                 {
                               5636                 :                :                     /* it's an update, but which kind? */
 3791 alvherre@alvh.no-ip.     5637         [ +  + ]:CBC          19 :                     if (old_infomask2 & HEAP_KEYS_UPDATED)
                               5638                 :             14 :                         status = MultiXactStatusUpdate;
                               5639                 :                :                     else
                               5640                 :              5 :                         status = MultiXactStatusNoKeyUpdate;
                               5641                 :                :                 }
                               5642                 :                : 
 2827 andres@anarazel.de       5643                 :             29 :                 result = test_lockmode_for_conflict(status, rawxmax, mode,
                               5644                 :                :                                                     &mytup, &needwait);
                               5645                 :                : 
                               5646                 :                :                 /*
                               5647                 :                :                  * If the tuple was already locked by ourselves in a previous
                               5648                 :                :                  * iteration of this (say heap_lock_tuple was forced to
                               5649                 :                :                  * restart the locking loop because of a change in xmax), then
                               5650                 :                :                  * we hold the lock already on this tuple version and we don't
                               5651                 :                :                  * need to do anything; and this is not an error condition
                               5652                 :                :                  * either.  We just need to skip this tuple and continue
                               5653                 :                :                  * locking the next version in the update chain.
                               5654                 :                :                  */
 1849                          5655         [ -  + ]:             29 :                 if (result == TM_SelfModified)
 2454 alvherre@alvh.no-ip.     5656                 :UBC           0 :                     goto next;
                               5657                 :                : 
 3791 alvherre@alvh.no-ip.     5658         [ +  + ]:CBC          29 :                 if (needwait)
                               5659                 :                :                 {
                               5660                 :              8 :                     LockBuffer(buf, BUFFER_LOCK_UNLOCK);
 3357 heikki.linnakangas@i     5661                 :              8 :                     XactLockTableWait(rawxmax, rel, &mytup.t_self,
                               5662                 :                :                                       XLTW_LockUpdated);
 3791 alvherre@alvh.no-ip.     5663                 :              8 :                     goto l4;
                               5664                 :                :                 }
 1849 andres@anarazel.de       5665         [ +  + ]:             21 :                 if (result != TM_Ok)
                               5666                 :                :                 {
 2827                          5667                 :              8 :                     goto out_locked;
                               5668                 :                :                 }
                               5669                 :                :             }
                               5670                 :                :         }
                               5671                 :                : 
                               5672                 :                :         /* compute the new Xmax and infomask values for the tuple ... */
 4099 alvherre@alvh.no-ip.     5673                 :             62 :         compute_new_xmax_infomask(xmax, old_infomask, mytup.t_data->t_infomask2,
                               5674                 :                :                                   xid, mode, false,
                               5675                 :                :                                   &new_xmax, &new_infomask, &new_infomask2);
                               5676                 :                : 
 2827 andres@anarazel.de       5677   [ -  +  -  - ]:             62 :         if (PageIsAllVisible(BufferGetPage(buf)) &&
 2827 andres@anarazel.de       5678                 :UBC           0 :             visibilitymap_clear(rel, block, vmbuffer,
                               5679                 :                :                                 VISIBILITYMAP_ALL_FROZEN))
                               5680                 :              0 :             cleared_all_frozen = true;
                               5681                 :                : 
 4099 alvherre@alvh.no-ip.     5682                 :CBC          62 :         START_CRIT_SECTION();
                               5683                 :                : 
                               5684                 :                :         /* ... and set them */
                               5685                 :             62 :         HeapTupleHeaderSetXmax(mytup.t_data, new_xmax);
                               5686                 :             62 :         mytup.t_data->t_infomask &= ~HEAP_XMAX_BITS;
                               5687                 :             62 :         mytup.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               5688                 :             62 :         mytup.t_data->t_infomask |= new_infomask;
                               5689                 :             62 :         mytup.t_data->t_infomask2 |= new_infomask2;
                               5690                 :                : 
                               5691                 :             62 :         MarkBufferDirty(buf);
                               5692                 :                : 
                               5693                 :                :         /* XLOG stuff */
                               5694   [ +  -  -  +  :             62 :         if (RelationNeedsWAL(rel))
                                        -  -  -  - ]
                               5695                 :                :         {
                               5696                 :                :             xl_heap_lock_updated xlrec;
                               5697                 :                :             XLogRecPtr  recptr;
 2916 kgrittn@postgresql.o     5698                 :             62 :             Page        page = BufferGetPage(buf);
                               5699                 :                : 
 3433 heikki.linnakangas@i     5700                 :             62 :             XLogBeginInsert();
                               5701                 :             62 :             XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
                               5702                 :                : 
                               5703                 :             62 :             xlrec.offnum = ItemPointerGetOffsetNumber(&mytup.t_self);
 4099 alvherre@alvh.no-ip.     5704                 :             62 :             xlrec.xmax = new_xmax;
                               5705                 :             62 :             xlrec.infobits_set = compute_infobits(new_infomask, new_infomask2);
 2827 andres@anarazel.de       5706                 :             62 :             xlrec.flags =
                               5707                 :             62 :                 cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
                               5708                 :                : 
 3433 heikki.linnakangas@i     5709                 :             62 :             XLogRegisterData((char *) &xlrec, SizeOfHeapLockUpdated);
                               5710                 :                : 
                               5711                 :             62 :             recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_LOCK_UPDATED);
                               5712                 :                : 
 4099 alvherre@alvh.no-ip.     5713                 :             62 :             PageSetLSN(page, recptr);
                               5714                 :                :         }
                               5715                 :                : 
                               5716         [ -  + ]:             62 :         END_CRIT_SECTION();
                               5717                 :                : 
 2454                          5718                 :             62 : next:
                               5719                 :                :         /* if we find the end of update chain, we're done. */
 4099                          5720   [ +  -  +  - ]:            124 :         if (mytup.t_data->t_infomask & HEAP_XMAX_INVALID ||
 2199 andres@anarazel.de       5721         [ +  + ]:            124 :             HeapTupleHeaderIndicatesMovedPartitions(mytup.t_data) ||
 3973 bruce@momjian.us         5722         [ +  + ]:             66 :             ItemPointerEquals(&mytup.t_self, &mytup.t_data->t_ctid) ||
 4099 alvherre@alvh.no-ip.     5723                 :              4 :             HeapTupleHeaderIsOnlyLocked(mytup.t_data))
                               5724                 :                :         {
 1849 andres@anarazel.de       5725                 :             59 :             result = TM_Ok;
 2827                          5726                 :             59 :             goto out_locked;
                               5727                 :                :         }
                               5728                 :                : 
                               5729                 :                :         /* tail recursion */
 3791 alvherre@alvh.no-ip.     5730   [ +  -  +  -  :              3 :         priorXmax = HeapTupleHeaderGetUpdateXid(mytup.t_data);
                                              +  - ]
 4099                          5731                 :              3 :         ItemPointerCopy(&(mytup.t_data->t_ctid), &tupid);
                               5732                 :              3 :         UnlockReleaseBuffer(buf);
                               5733                 :                :     }
                               5734                 :                : 
                               5735                 :                :     result = TM_Ok;
                               5736                 :                : 
 2827 andres@anarazel.de       5737                 :             80 : out_locked:
                               5738                 :             80 :     UnlockReleaseBuffer(buf);
                               5739                 :                : 
 2235 tgl@sss.pgh.pa.us        5740                 :             80 : out_unlocked:
 2827 andres@anarazel.de       5741         [ -  + ]:             80 :     if (vmbuffer != InvalidBuffer)
 2827 andres@anarazel.de       5742                 :UBC           0 :         ReleaseBuffer(vmbuffer);
                               5743                 :                : 
 2827 andres@anarazel.de       5744                 :CBC          80 :     return result;
                               5745                 :                : }
                               5746                 :                : 
                               5747                 :                : /*
                               5748                 :                :  * heap_lock_updated_tuple
                               5749                 :                :  *      Follow update chain when locking an updated tuple, acquiring locks (row
                               5750                 :                :  *      marks) on the updated versions.
                               5751                 :                :  *
                               5752                 :                :  * The initial tuple is assumed to be already locked.
                               5753                 :                :  *
                               5754                 :                :  * This function doesn't check visibility, it just unconditionally marks the
                               5755                 :                :  * tuple(s) as locked.  If any tuple in the updated chain is being deleted
                               5756                 :                :  * concurrently (or updated with the key being modified), sleep until the
                               5757                 :                :  * transaction doing it is finished.
                               5758                 :                :  *
                               5759                 :                :  * Note that we don't acquire heavyweight tuple locks on the tuples we walk
                               5760                 :                :  * when we have to wait for other transactions to release them, as opposed to
                               5761                 :                :  * what heap_lock_tuple does.  The reason is that having more than one
                               5762                 :                :  * transaction walking the chain is probably uncommon enough that risk of
                               5763                 :                :  * starvation is not likely: one of the preconditions for being here is that
                               5764                 :                :  * the snapshot in use predates the update that created this tuple (because we
                               5765                 :                :  * started at an earlier version of the tuple), but at the same time such a
                               5766                 :                :  * transaction cannot be using repeatable read or serializable isolation
                               5767                 :                :  * levels, because that would lead to a serializability failure.
                               5768                 :                :  */
                               5769                 :                : static TM_Result
 4099 alvherre@alvh.no-ip.     5770                 :             89 : heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid,
                               5771                 :                :                         TransactionId xid, LockTupleMode mode)
                               5772                 :                : {
                               5773                 :                :     /*
                               5774                 :                :      * If the tuple has not been updated, or has moved into another partition
                               5775                 :                :      * (effectively a delete) stop here.
                               5776                 :                :      */
 2199 andres@anarazel.de       5777         [ +  + ]:             89 :     if (!HeapTupleHeaderIndicatesMovedPartitions(tuple->t_data) &&
                               5778         [ +  + ]:             87 :         !ItemPointerEquals(&tuple->t_self, ctid))
                               5779                 :                :     {
                               5780                 :                :         /*
                               5781                 :                :          * If this is the first possibly-multixact-able operation in the
                               5782                 :                :          * current transaction, set my per-backend OldestMemberMXactId
                               5783                 :                :          * setting. We can be certain that the transaction will never become a
                               5784                 :                :          * member of any older MultiXactIds than that.  (We have to do this
                               5785                 :                :          * even if we end up just using our own TransactionId below, since
                               5786                 :                :          * some other backend could incorporate our XID into a MultiXact
                               5787                 :                :          * immediately afterwards.)
                               5788                 :                :          */
 4099 alvherre@alvh.no-ip.     5789                 :             80 :         MultiXactIdSetOldestMember();
                               5790                 :                : 
                               5791                 :             80 :         return heap_lock_updated_tuple_rec(rel, ctid, xid, mode);
                               5792                 :                :     }
                               5793                 :                : 
                               5794                 :                :     /* nothing to lock */
 1849 andres@anarazel.de       5795                 :              9 :     return TM_Ok;
                               5796                 :                : }
                               5797                 :                : 
                               5798                 :                : /*
                               5799                 :                :  *  heap_finish_speculative - mark speculative insertion as successful
                               5800                 :                :  *
                               5801                 :                :  * To successfully finish a speculative insertion we have to clear speculative
                               5802                 :                :  * token from tuple.  To do so the t_ctid field, which will contain a
                               5803                 :                :  * speculative token value, is modified in place to point to the tuple itself,
                               5804                 :                :  * which is characteristic of a newly inserted ordinary tuple.
                               5805                 :                :  *
                               5806                 :                :  * NB: It is not ok to commit without either finishing or aborting a
                               5807                 :                :  * speculative insertion.  We could treat speculative tuples of committed
                               5808                 :                :  * transactions implicitly as completed, but then we would have to be prepared
                               5809                 :                :  * to deal with speculative tokens on committed tuples.  That wouldn't be
                               5810                 :                :  * difficult - no-one looks at the ctid field of a tuple with invalid xmax -
                               5811                 :                :  * but clearing the token at completion isn't very expensive either.
                               5812                 :                :  * An explicit confirmation WAL record also makes logical decoding simpler.
                               5813                 :                :  */
                               5814                 :                : void
                               5815                 :           2005 : heap_finish_speculative(Relation relation, ItemPointer tid)
                               5816                 :                : {
                               5817                 :                :     Buffer      buffer;
                               5818                 :                :     Page        page;
                               5819                 :                :     OffsetNumber offnum;
 3264                          5820                 :           2005 :     ItemId      lp = NULL;
                               5821                 :                :     HeapTupleHeader htup;
                               5822                 :                : 
 1849                          5823                 :           2005 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
 3264                          5824                 :           2005 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
 2916 kgrittn@postgresql.o     5825                 :           2005 :     page = (Page) BufferGetPage(buffer);
                               5826                 :                : 
 1849 andres@anarazel.de       5827                 :           2005 :     offnum = ItemPointerGetOffsetNumber(tid);
 3264                          5828         [ +  - ]:           2005 :     if (PageGetMaxOffsetNumber(page) >= offnum)
                               5829                 :           2005 :         lp = PageGetItemId(page, offnum);
                               5830                 :                : 
                               5831   [ +  -  -  + ]:           2005 :     if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
 3069 andres@anarazel.de       5832         [ #  # ]:UBC           0 :         elog(ERROR, "invalid lp");
                               5833                 :                : 
 3264 andres@anarazel.de       5834                 :CBC        2005 :     htup = (HeapTupleHeader) PageGetItem(page, lp);
                               5835                 :                : 
                               5836                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
                               5837                 :           2005 :     START_CRIT_SECTION();
                               5838                 :                : 
 1849                          5839         [ -  + ]:           2005 :     Assert(HeapTupleHeaderIsSpeculative(htup));
                               5840                 :                : 
 3264                          5841                 :           2005 :     MarkBufferDirty(buffer);
                               5842                 :                : 
                               5843                 :                :     /*
                               5844                 :                :      * Replace the speculative insertion token with a real t_ctid, pointing to
                               5845                 :                :      * itself like it does on regular tuples.
                               5846                 :                :      */
 1849                          5847                 :           2005 :     htup->t_ctid = *tid;
                               5848                 :                : 
                               5849                 :                :     /* XLOG stuff */
 3264                          5850   [ +  +  +  +  :           2005 :     if (RelationNeedsWAL(relation))
                                        +  -  +  - ]
                               5851                 :                :     {
                               5852                 :                :         xl_heap_confirm xlrec;
                               5853                 :                :         XLogRecPtr  recptr;
                               5854                 :                : 
 1849                          5855                 :           1999 :         xlrec.offnum = ItemPointerGetOffsetNumber(tid);
                               5856                 :                : 
 3264                          5857                 :           1999 :         XLogBeginInsert();
                               5858                 :                : 
                               5859                 :                :         /* We want the same filtering on this as on a plain insert */
 2670                          5860                 :           1999 :         XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               5861                 :                : 
 3264                          5862                 :           1999 :         XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
                               5863                 :           1999 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               5864                 :                : 
                               5865                 :           1999 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
                               5866                 :                : 
                               5867                 :           1999 :         PageSetLSN(page, recptr);
                               5868                 :                :     }
                               5869                 :                : 
                               5870         [ -  + ]:           2005 :     END_CRIT_SECTION();
                               5871                 :                : 
                               5872                 :           2005 :     UnlockReleaseBuffer(buffer);
                               5873                 :           2005 : }
                               5874                 :                : 
                               5875                 :                : /*
                               5876                 :                :  *  heap_abort_speculative - kill a speculatively inserted tuple
                               5877                 :                :  *
                               5878                 :                :  * Marks a tuple that was speculatively inserted in the same command as dead,
                               5879                 :                :  * by setting its xmin as invalid.  That makes it immediately appear as dead
                               5880                 :                :  * to all transactions, including our own.  In particular, it makes
                               5881                 :                :  * HeapTupleSatisfiesDirty() regard the tuple as dead, so that another backend
                               5882                 :                :  * inserting a duplicate key value won't unnecessarily wait for our whole
                               5883                 :                :  * transaction to finish (it'll just wait for our speculative insertion to
                               5884                 :                :  * finish).
                               5885                 :                :  *
                               5886                 :                :  * Killing the tuple prevents "unprincipled deadlocks", which are deadlocks
                               5887                 :                :  * that arise due to a mutual dependency that is not user visible.  By
                               5888                 :                :  * definition, unprincipled deadlocks cannot be prevented by the user
                               5889                 :                :  * reordering lock acquisition in client code, because the implementation level
                               5890                 :                :  * lock acquisitions are not under the user's direct control.  If speculative
                               5891                 :                :  * inserters did not take this precaution, then under high concurrency they
                               5892                 :                :  * could deadlock with each other, which would not be acceptable.
                               5893                 :                :  *
                               5894                 :                :  * This is somewhat redundant with heap_delete, but we prefer to have a
                               5895                 :                :  * dedicated routine with stripped down requirements.  Note that this is also
                               5896                 :                :  * used to delete the TOAST tuples created during speculative insertion.
                               5897                 :                :  *
                               5898                 :                :  * This routine does not affect logical decoding as it only looks at
                               5899                 :                :  * confirmation records.
                               5900                 :                :  */
                               5901                 :                : void
 1849                          5902                 :             10 : heap_abort_speculative(Relation relation, ItemPointer tid)
                               5903                 :                : {
 3264                          5904                 :             10 :     TransactionId xid = GetCurrentTransactionId();
                               5905                 :                :     ItemId      lp;
                               5906                 :                :     HeapTupleData tp;
                               5907                 :                :     Page        page;
                               5908                 :                :     BlockNumber block;
                               5909                 :                :     Buffer      buffer;
                               5910                 :                :     TransactionId prune_xid;
                               5911                 :                : 
                               5912         [ -  + ]:             10 :     Assert(ItemPointerIsValid(tid));
                               5913                 :                : 
                               5914                 :             10 :     block = ItemPointerGetBlockNumber(tid);
                               5915                 :             10 :     buffer = ReadBuffer(relation, block);
 2916 kgrittn@postgresql.o     5916                 :             10 :     page = BufferGetPage(buffer);
                               5917                 :                : 
 3264 andres@anarazel.de       5918                 :             10 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
                               5919                 :                : 
                               5920                 :                :     /*
                               5921                 :                :      * Page can't be all visible, we just inserted into it, and are still
                               5922                 :                :      * running.
                               5923                 :                :      */
                               5924         [ -  + ]:             10 :     Assert(!PageIsAllVisible(page));
                               5925                 :                : 
                               5926                 :             10 :     lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
                               5927         [ -  + ]:             10 :     Assert(ItemIdIsNormal(lp));
                               5928                 :                : 
                               5929                 :             10 :     tp.t_tableOid = RelationGetRelid(relation);
                               5930                 :             10 :     tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
                               5931                 :             10 :     tp.t_len = ItemIdGetLength(lp);
                               5932                 :             10 :     tp.t_self = *tid;
                               5933                 :                : 
                               5934                 :                :     /*
                               5935                 :                :      * Sanity check that the tuple really is a speculatively inserted tuple,
                               5936                 :                :      * inserted by us.
                               5937                 :                :      */
                               5938         [ -  + ]:             10 :     if (tp.t_data->t_choice.t_heap.t_xmin != xid)
 3264 andres@anarazel.de       5939         [ #  # ]:UBC           0 :         elog(ERROR, "attempted to kill a tuple inserted by another transaction");
 2797 andres@anarazel.de       5940   [ +  +  -  + ]:CBC          10 :     if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
 3264 andres@anarazel.de       5941         [ #  # ]:UBC           0 :         elog(ERROR, "attempted to kill a non-speculative tuple");
 3264 andres@anarazel.de       5942         [ -  + ]:CBC          10 :     Assert(!HeapTupleHeaderIsHeapOnly(tp.t_data));
                               5943                 :                : 
                               5944                 :                :     /*
                               5945                 :                :      * No need to check for serializable conflicts here.  There is never a
                               5946                 :                :      * need for a combo CID, either.  No need to extract replica identity, or
                               5947                 :                :      * do anything special with infomask bits.
                               5948                 :                :      */
                               5949                 :                : 
                               5950                 :             10 :     START_CRIT_SECTION();
                               5951                 :                : 
                               5952                 :                :     /*
                               5953                 :                :      * The tuple will become DEAD immediately.  Flag that this page is a
                               5954                 :                :      * candidate for pruning by setting xmin to TransactionXmin. While not
                               5955                 :                :      * immediately prunable, it is the oldest xid we can cheaply determine
                               5956                 :                :      * that's safe against wraparound / being older than the table's
                               5957                 :                :      * relfrozenxid.  To defend against the unlikely case of a new relation
                               5958                 :                :      * having a newer relfrozenxid than our TransactionXmin, use relfrozenxid
                               5959                 :                :      * if so (vacuum can't subsequently move relfrozenxid to beyond
                               5960                 :                :      * TransactionXmin, so there's no race here).
                               5961                 :                :      */
 1470                          5962         [ -  + ]:             10 :     Assert(TransactionIdIsValid(TransactionXmin));
                               5963         [ -  + ]:             10 :     if (TransactionIdPrecedes(TransactionXmin, relation->rd_rel->relfrozenxid))
 1470 andres@anarazel.de       5964                 :UBC           0 :         prune_xid = relation->rd_rel->relfrozenxid;
                               5965                 :                :     else
 1470 andres@anarazel.de       5966                 :CBC          10 :         prune_xid = TransactionXmin;
                               5967   [ -  +  +  +  :             10 :     PageSetPrunable(page, prune_xid);
                                              -  + ]
                               5968                 :                : 
                               5969                 :                :     /* store transaction information of xact deleting the tuple */
 3264                          5970                 :             10 :     tp.t_data->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               5971                 :             10 :     tp.t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               5972                 :                : 
                               5973                 :                :     /*
                               5974                 :                :      * Set the tuple header xmin to InvalidTransactionId.  This makes the
                               5975                 :                :      * tuple immediately invisible everyone.  (In particular, to any
                               5976                 :                :      * transactions waiting on the speculative token, woken up later.)
                               5977                 :                :      */
                               5978                 :             10 :     HeapTupleHeaderSetXmin(tp.t_data, InvalidTransactionId);
                               5979                 :                : 
                               5980                 :                :     /* Clear the speculative insertion token too */
                               5981                 :             10 :     tp.t_data->t_ctid = tp.t_self;
                               5982                 :                : 
                               5983                 :             10 :     MarkBufferDirty(buffer);
                               5984                 :                : 
                               5985                 :                :     /*
                               5986                 :                :      * XLOG stuff
                               5987                 :                :      *
                               5988                 :                :      * The WAL records generated here match heap_delete().  The same recovery
                               5989                 :                :      * routines are used.
                               5990                 :                :      */
                               5991   [ +  -  -  +  :             10 :     if (RelationNeedsWAL(relation))
                                        -  -  -  - ]
                               5992                 :                :     {
                               5993                 :                :         xl_heap_delete xlrec;
                               5994                 :                :         XLogRecPtr  recptr;
                               5995                 :                : 
                               5996                 :             10 :         xlrec.flags = XLH_DELETE_IS_SUPER;
                               5997                 :             20 :         xlrec.infobits_set = compute_infobits(tp.t_data->t_infomask,
                               5998                 :             10 :                                               tp.t_data->t_infomask2);
                               5999                 :             10 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tp.t_self);
                               6000                 :             10 :         xlrec.xmax = xid;
                               6001                 :                : 
                               6002                 :             10 :         XLogBeginInsert();
                               6003                 :             10 :         XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
                               6004                 :             10 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               6005                 :                : 
                               6006                 :                :         /* No replica identity & replication origin logged */
                               6007                 :                : 
                               6008                 :             10 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
                               6009                 :                : 
                               6010                 :             10 :         PageSetLSN(page, recptr);
                               6011                 :                :     }
                               6012                 :                : 
                               6013         [ -  + ]:             10 :     END_CRIT_SECTION();
                               6014                 :                : 
                               6015                 :             10 :     LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
                               6016                 :                : 
                               6017         [ +  + ]:             10 :     if (HeapTupleHasExternal(&tp))
                               6018                 :                :     {
 2797                          6019         [ -  + ]:              1 :         Assert(!IsToastRelation(relation));
 1654 rhaas@postgresql.org     6020                 :              1 :         heap_toast_delete(relation, &tp, true);
                               6021                 :                :     }
                               6022                 :                : 
                               6023                 :                :     /*
                               6024                 :                :      * Never need to mark tuple for invalidation, since catalogs don't support
                               6025                 :                :      * speculative insertion
                               6026                 :                :      */
                               6027                 :                : 
                               6028                 :                :     /* Now we can release the buffer */
 3264 andres@anarazel.de       6029                 :             10 :     ReleaseBuffer(buffer);
                               6030                 :                : 
                               6031                 :                :     /* count deletion, as we counted the insertion too */
                               6032                 :             10 :     pgstat_count_heap_delete(relation);
                               6033                 :             10 : }
                               6034                 :                : 
                               6035                 :                : /*
                               6036                 :                :  * heap_inplace_update - update a tuple "in place" (ie, overwrite it)
                               6037                 :                :  *
                               6038                 :                :  * Overwriting violates both MVCC and transactional safety, so the uses
                               6039                 :                :  * of this function in Postgres are extremely limited.  Nonetheless we
                               6040                 :                :  * find some places to use it.
                               6041                 :                :  *
                               6042                 :                :  * The tuple cannot change size, and therefore it's reasonable to assume
                               6043                 :                :  * that its null bitmap (if any) doesn't change either.  So we just
                               6044                 :                :  * overwrite the data portion of the tuple without touching the null
                               6045                 :                :  * bitmap or any of the header fields.
                               6046                 :                :  *
                               6047                 :                :  * tuple is an in-memory tuple structure containing the data to be written
                               6048                 :                :  * over the target tuple.  Also, tuple->t_self identifies the target tuple.
                               6049                 :                :  *
                               6050                 :                :  * Note that the tuple updated here had better not come directly from the
                               6051                 :                :  * syscache if the relation has a toast relation as this tuple could
                               6052                 :                :  * include toast values that have been expanded, causing a failure here.
                               6053                 :                :  */
                               6054                 :                : void
 6549 tgl@sss.pgh.pa.us        6055                 :          71114 : heap_inplace_update(Relation relation, HeapTuple tuple)
                               6056                 :                : {
                               6057                 :                :     Buffer      buffer;
                               6058                 :                :     Page        page;
                               6059                 :                :     OffsetNumber offnum;
                               6060                 :          71114 :     ItemId      lp = NULL;
                               6061                 :                :     HeapTupleHeader htup;
                               6062                 :                :     uint32      oldlen;
                               6063                 :                :     uint32      newlen;
                               6064                 :                : 
                               6065                 :                :     /*
                               6066                 :                :      * For now, we don't allow parallel updates.  Unlike a regular update,
                               6067                 :                :      * this should never create a combo CID, so it might be possible to relax
                               6068                 :                :      * this restriction, but not without more thought and testing.  It's not
                               6069                 :                :      * clear that it would be useful, anyway.
                               6070                 :                :      */
 3272 rhaas@postgresql.org     6071         [ -  + ]:          71114 :     if (IsInParallelMode())
 3272 rhaas@postgresql.org     6072         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6073                 :                :                 (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
                               6074                 :                :                  errmsg("cannot update tuples during a parallel operation")));
                               6075                 :                : 
 6549 tgl@sss.pgh.pa.us        6076                 :CBC       71114 :     buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
                               6077                 :          71114 :     LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
 2916 kgrittn@postgresql.o     6078                 :          71114 :     page = (Page) BufferGetPage(buffer);
                               6079                 :                : 
 6549 tgl@sss.pgh.pa.us        6080                 :          71114 :     offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
                               6081         [ +  - ]:          71114 :     if (PageGetMaxOffsetNumber(page) >= offnum)
                               6082                 :          71114 :         lp = PageGetItemId(page, offnum);
                               6083                 :                : 
 6059                          6084   [ +  -  -  + ]:          71114 :     if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
 3069 andres@anarazel.de       6085         [ #  # ]:UBC           0 :         elog(ERROR, "invalid lp");
                               6086                 :                : 
 6549 tgl@sss.pgh.pa.us        6087                 :CBC       71114 :     htup = (HeapTupleHeader) PageGetItem(page, lp);
                               6088                 :                : 
                               6089                 :          71114 :     oldlen = ItemIdGetLength(lp) - htup->t_hoff;
                               6090                 :          71114 :     newlen = tuple->t_len - tuple->t_data->t_hoff;
                               6091   [ +  -  -  + ]:          71114 :     if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
 3069 andres@anarazel.de       6092         [ #  # ]:UBC           0 :         elog(ERROR, "wrong tuple length");
                               6093                 :                : 
                               6094                 :                :     /* NO EREPORT(ERROR) from here till changes are logged */
 6549 tgl@sss.pgh.pa.us        6095                 :CBC       71114 :     START_CRIT_SECTION();
                               6096                 :                : 
                               6097                 :          71114 :     memcpy((char *) htup + htup->t_hoff,
                               6098                 :          71114 :            (char *) tuple->t_data + tuple->t_data->t_hoff,
                               6099                 :                :            newlen);
                               6100                 :                : 
                               6101                 :          71114 :     MarkBufferDirty(buffer);
                               6102                 :                : 
                               6103                 :                :     /* XLOG stuff */
 4871 rhaas@postgresql.org     6104   [ +  -  +  +  :          71114 :     if (RelationNeedsWAL(relation))
                                        +  -  +  + ]
                               6105                 :                :     {
                               6106                 :                :         xl_heap_inplace xlrec;
                               6107                 :                :         XLogRecPtr  recptr;
                               6108                 :                : 
 3433 heikki.linnakangas@i     6109                 :          71106 :         xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
                               6110                 :                : 
                               6111                 :          71106 :         XLogBeginInsert();
                               6112                 :          71106 :         XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
                               6113                 :                : 
                               6114                 :          71106 :         XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
                               6115                 :          71106 :         XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
                               6116                 :                : 
                               6117                 :                :         /* inplace updates aren't decoded atm, don't log the origin */
                               6118                 :                : 
                               6119                 :          71106 :         recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
                               6120                 :                : 
 6549 tgl@sss.pgh.pa.us        6121                 :          71106 :         PageSetLSN(page, recptr);
                               6122                 :                :     }
                               6123                 :                : 
                               6124         [ -  + ]:          71114 :     END_CRIT_SECTION();
                               6125                 :                : 
                               6126                 :          71114 :     UnlockReleaseBuffer(buffer);
                               6127                 :                : 
                               6128                 :                :     /*
                               6129                 :                :      * Send out shared cache inval if necessary.  Note that because we only
                               6130                 :                :      * pass the new version of the tuple, this mustn't be used for any
                               6131                 :                :      * operations that could change catcache lookup keys.  But we aren't
                               6132                 :                :      * bothering with index updates either, so that's true a fortiori.
                               6133                 :                :      */
                               6134         [ +  + ]:          71114 :     if (!IsBootstrapProcessingMode())
 4625                          6135                 :          59570 :         CacheInvalidateHeapTuple(relation, tuple, NULL);
 6549                          6136                 :          71114 : }
                               6137                 :                : 
                               6138                 :                : #define     FRM_NOOP                0x0001
                               6139                 :                : #define     FRM_INVALIDATE_XMAX     0x0002
                               6140                 :                : #define     FRM_RETURN_IS_XID       0x0004
                               6141                 :                : #define     FRM_RETURN_IS_MULTI     0x0008
                               6142                 :                : #define     FRM_MARK_COMMITTED      0x0010
                               6143                 :                : 
                               6144                 :                : /*
                               6145                 :                :  * FreezeMultiXactId
                               6146                 :                :  *      Determine what to do during freezing when a tuple is marked by a
                               6147                 :                :  *      MultiXactId.
                               6148                 :                :  *
                               6149                 :                :  * "flags" is an output value; it's used to tell caller what to do on return.
                               6150                 :                :  * "pagefrz" is an input/output value, used to manage page level freezing.
                               6151                 :                :  *
                               6152                 :                :  * Possible values that we can set in "flags":
                               6153                 :                :  * FRM_NOOP
                               6154                 :                :  *      don't do anything -- keep existing Xmax
                               6155                 :                :  * FRM_INVALIDATE_XMAX
                               6156                 :                :  *      mark Xmax as InvalidTransactionId and set XMAX_INVALID flag.
                               6157                 :                :  * FRM_RETURN_IS_XID
                               6158                 :                :  *      The Xid return value is a single update Xid to set as xmax.
                               6159                 :                :  * FRM_MARK_COMMITTED
                               6160                 :                :  *      Xmax can be marked as HEAP_XMAX_COMMITTED
                               6161                 :                :  * FRM_RETURN_IS_MULTI
                               6162                 :                :  *      The return value is a new MultiXactId to set as new Xmax.
                               6163                 :                :  *      (caller must obtain proper infomask bits using GetMultiXactIdHintBits)
                               6164                 :                :  *
                               6165                 :                :  * Caller delegates control of page freezing to us.  In practice we always
                               6166                 :                :  * force freezing of caller's page unless FRM_NOOP processing is indicated.
                               6167                 :                :  * We help caller ensure that XIDs < FreezeLimit and MXIDs < MultiXactCutoff
                               6168                 :                :  * can never be left behind.  We freely choose when and how to process each
                               6169                 :                :  * Multi, without ever violating the cutoff postconditions for freezing.
                               6170                 :                :  *
                               6171                 :                :  * It's useful to remove Multis on a proactive timeline (relative to freezing
                               6172                 :                :  * XIDs) to keep MultiXact member SLRU buffer misses to a minimum.  It can also
                               6173                 :                :  * be cheaper in the short run, for us, since we too can avoid SLRU buffer
                               6174                 :                :  * misses through eager processing.
                               6175                 :                :  *
                               6176                 :                :  * NB: Creates a _new_ MultiXactId when FRM_RETURN_IS_MULTI is set, though only
                               6177                 :                :  * when FreezeLimit and/or MultiXactCutoff cutoffs leave us with no choice.
                               6178                 :                :  * This can usually be put off, which is usually enough to avoid it altogether.
                               6179                 :                :  * Allocating new multis during VACUUM should be avoided on general principle;
                               6180                 :                :  * only VACUUM can advance relminmxid, so allocating new Multis here comes with
                               6181                 :                :  * its own special risks.
                               6182                 :                :  *
                               6183                 :                :  * NB: Caller must maintain "no freeze" NewRelfrozenXid/NewRelminMxid trackers
                               6184                 :                :  * using heap_tuple_should_freeze when we haven't forced page-level freezing.
                               6185                 :                :  *
                               6186                 :                :  * NB: Caller should avoid needlessly calling heap_tuple_should_freeze when we
                               6187                 :                :  * have already forced page-level freezing, since that might incur the same
                               6188                 :                :  * SLRU buffer misses that we specifically intended to avoid by freezing.
                               6189                 :                :  */
                               6190                 :                : static TransactionId
 3772 alvherre@alvh.no-ip.     6191                 :              9 : FreezeMultiXactId(MultiXactId multi, uint16 t_infomask,
                               6192                 :                :                   const struct VacuumCutoffs *cutoffs, uint16 *flags,
                               6193                 :                :                   HeapPageFreeze *pagefrz)
                               6194                 :                : {
                               6195                 :                :     TransactionId newxmax;
                               6196                 :                :     MultiXactMember *members;
                               6197                 :                :     int         nmembers;
                               6198                 :                :     bool        need_replace;
                               6199                 :                :     int         nnewmembers;
                               6200                 :                :     MultiXactMember *newmembers;
                               6201                 :                :     bool        has_lockers;
                               6202                 :                :     TransactionId update_xid;
                               6203                 :                :     bool        update_committed;
                               6204                 :                :     TransactionId FreezePageRelfrozenXid;
                               6205                 :                : 
                               6206                 :              9 :     *flags = 0;
                               6207                 :                : 
                               6208                 :                :     /* We should only be called in Multis */
                               6209         [ -  + ]:              9 :     Assert(t_infomask & HEAP_XMAX_IS_MULTI);
                               6210                 :                : 
 2851                          6211         [ +  - ]:              9 :     if (!MultiXactIdIsValid(multi) ||
                               6212   [ +  -  +  -  :              9 :         HEAP_LOCKED_UPGRADED(t_infomask))
                                              -  + ]
                               6213                 :                :     {
 3772 alvherre@alvh.no-ip.     6214                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
  473 pg@bowt.ie               6215                 :              0 :         pagefrz->freeze_required = true;
 3772 alvherre@alvh.no-ip.     6216                 :              0 :         return InvalidTransactionId;
                               6217                 :                :     }
  479 pg@bowt.ie               6218         [ -  + ]:CBC           9 :     else if (MultiXactIdPrecedes(multi, cutoffs->relminmxid))
 2344 andres@anarazel.de       6219         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6220                 :                :                 (errcode(ERRCODE_DATA_CORRUPTED),
                               6221                 :                :                  errmsg_internal("found multixact %u from before relminmxid %u",
                               6222                 :                :                                  multi, cutoffs->relminmxid)));
  473 pg@bowt.ie               6223         [ +  + ]:CBC           9 :     else if (MultiXactIdPrecedes(multi, cutoffs->OldestMxact))
                               6224                 :                :     {
                               6225                 :                :         TransactionId update_xact;
                               6226                 :                : 
                               6227                 :                :         /*
                               6228                 :                :          * This old multi cannot possibly have members still running, but
                               6229                 :                :          * verify just in case.  If it was a locker only, it can be removed
                               6230                 :                :          * without any further consideration; but if it contained an update,
                               6231                 :                :          * we might need to preserve it.
                               6232                 :                :          */
 2344 andres@anarazel.de       6233         [ -  + ]:              7 :         if (MultiXactIdIsRunning(multi,
                               6234   [ -  +  -  - ]:              7 :                                  HEAP_XMAX_IS_LOCKED_ONLY(t_infomask)))
 2344 andres@anarazel.de       6235         [ #  # ]:UBC           0 :             ereport(ERROR,
                               6236                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6237                 :                :                      errmsg_internal("multixact %u from before multi freeze cutoff %u found to be still running",
                               6238                 :                :                                      multi, cutoffs->OldestMxact)));
                               6239                 :                : 
 3772 alvherre@alvh.no-ip.     6240   [ -  +  -  - ]:CBC           7 :         if (HEAP_XMAX_IS_LOCKED_ONLY(t_infomask))
                               6241                 :                :         {
                               6242                 :              7 :             *flags |= FRM_INVALIDATE_XMAX;
  473 pg@bowt.ie               6243                 :              7 :             pagefrz->freeze_required = true;
                               6244                 :              7 :             return InvalidTransactionId;
                               6245                 :                :         }
                               6246                 :                : 
                               6247                 :                :         /* replace multi with single XID for its updater? */
  473 pg@bowt.ie               6248                 :UBC           0 :         update_xact = MultiXactIdGetUpdateXid(multi, t_infomask);
                               6249         [ #  # ]:              0 :         if (TransactionIdPrecedes(update_xact, cutoffs->relfrozenxid))
                               6250         [ #  # ]:              0 :             ereport(ERROR,
                               6251                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6252                 :                :                      errmsg_internal("multixact %u contains update XID %u from before relfrozenxid %u",
                               6253                 :                :                                      multi, update_xact,
                               6254                 :                :                                      cutoffs->relfrozenxid)));
                               6255         [ #  # ]:              0 :         else if (TransactionIdPrecedes(update_xact, cutoffs->OldestXmin))
                               6256                 :                :         {
                               6257                 :                :             /*
                               6258                 :                :              * Updater XID has to have aborted (otherwise the tuple would have
                               6259                 :                :              * been pruned away instead, since updater XID is < OldestXmin).
                               6260                 :                :              * Just remove xmax.
                               6261                 :                :              */
  467                          6262         [ #  # ]:              0 :             if (TransactionIdDidCommit(update_xact))
  473                          6263         [ #  # ]:              0 :                 ereport(ERROR,
                               6264                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               6265                 :                :                          errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
                               6266                 :                :                                          multi, update_xact,
                               6267                 :                :                                          cutoffs->OldestXmin)));
                               6268                 :              0 :             *flags |= FRM_INVALIDATE_XMAX;
                               6269                 :              0 :             pagefrz->freeze_required = true;
                               6270                 :              0 :             return InvalidTransactionId;
                               6271                 :                :         }
                               6272                 :                : 
                               6273                 :                :         /* Have to keep updater XID as new xmax */
                               6274                 :              0 :         *flags |= FRM_RETURN_IS_XID;
                               6275                 :              0 :         pagefrz->freeze_required = true;
                               6276                 :              0 :         return update_xact;
                               6277                 :                :     }
                               6278                 :                : 
                               6279                 :                :     /*
                               6280                 :                :      * Some member(s) of this Multi may be below FreezeLimit xid cutoff, so we
                               6281                 :                :      * need to walk the whole members array to figure out what to do, if
                               6282                 :                :      * anything.
                               6283                 :                :      */
                               6284                 :                :     nmembers =
 2851 alvherre@alvh.no-ip.     6285                 :CBC           2 :         GetMultiXactIdMembers(multi, &members, false,
 3547                          6286   [ -  +  -  - ]:              2 :                               HEAP_XMAX_IS_LOCKED_ONLY(t_infomask));
 3772                          6287         [ -  + ]:              2 :     if (nmembers <= 0)
                               6288                 :                :     {
                               6289                 :                :         /* Nothing worth keeping */
 3772 alvherre@alvh.no-ip.     6290                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
  473 pg@bowt.ie               6291                 :              0 :         pagefrz->freeze_required = true;
 3772 alvherre@alvh.no-ip.     6292                 :              0 :         return InvalidTransactionId;
                               6293                 :                :     }
                               6294                 :                : 
                               6295                 :                :     /*
                               6296                 :                :      * The FRM_NOOP case is the only case where we might need to ratchet back
                               6297                 :                :      * FreezePageRelfrozenXid or FreezePageRelminMxid.  It is also the only
                               6298                 :                :      * case where our caller might ratchet back its NoFreezePageRelfrozenXid
                               6299                 :                :      * or NoFreezePageRelminMxid "no freeze" trackers to deal with a multi.
                               6300                 :                :      * FRM_NOOP handling should result in the NewRelfrozenXid/NewRelminMxid
                               6301                 :                :      * trackers managed by VACUUM being ratcheting back by xmax to the degree
                               6302                 :                :      * required to make it safe to leave xmax undisturbed, independent of
                               6303                 :                :      * whether or not page freezing is triggered somewhere else.
                               6304                 :                :      *
                               6305                 :                :      * Our policy is to force freezing in every case other than FRM_NOOP,
                               6306                 :                :      * which obviates the need to maintain either set of trackers, anywhere.
                               6307                 :                :      * Every other case will reliably execute a freeze plan for xmax that
                               6308                 :                :      * either replaces xmax with an XID/MXID >= OldestXmin/OldestMxact, or
                               6309                 :                :      * sets xmax to an InvalidTransactionId XID, rendering xmax fully frozen.
                               6310                 :                :      * (VACUUM's NewRelfrozenXid/NewRelminMxid trackers are initialized with
                               6311                 :                :      * OldestXmin/OldestMxact, so later values never need to be tracked here.)
                               6312                 :                :      */
 3772 alvherre@alvh.no-ip.     6313                 :CBC           2 :     need_replace = false;
  473 pg@bowt.ie               6314                 :              2 :     FreezePageRelfrozenXid = pagefrz->FreezePageRelfrozenXid;
  479                          6315         [ +  + ]:              4 :     for (int i = 0; i < nmembers; i++)
                               6316                 :                :     {
                               6317                 :              3 :         TransactionId xid = members[i].xid;
                               6318                 :                : 
                               6319         [ -  + ]:              3 :         Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
                               6320                 :                : 
                               6321         [ +  + ]:              3 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               6322                 :                :         {
                               6323                 :                :             /* Can't violate the FreezeLimit postcondition */
 3772 alvherre@alvh.no-ip.     6324                 :              1 :             need_replace = true;
                               6325                 :              1 :             break;
                               6326                 :                :         }
  473 pg@bowt.ie               6327         [ -  + ]:              2 :         if (TransactionIdPrecedes(xid, FreezePageRelfrozenXid))
  473 pg@bowt.ie               6328                 :UBC           0 :             FreezePageRelfrozenXid = xid;
                               6329                 :                :     }
                               6330                 :                : 
                               6331                 :                :     /* Can't violate the MultiXactCutoff postcondition, either */
  473 pg@bowt.ie               6332         [ +  + ]:CBC           2 :     if (!need_replace)
                               6333                 :              1 :         need_replace = MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff);
                               6334                 :                : 
 3772 alvherre@alvh.no-ip.     6335         [ +  + ]:              2 :     if (!need_replace)
                               6336                 :                :     {
                               6337                 :                :         /*
                               6338                 :                :          * vacuumlazy.c might ratchet back NewRelminMxid, NewRelfrozenXid, or
                               6339                 :                :          * both together to make it safe to retain this particular multi after
                               6340                 :                :          * freezing its page
                               6341                 :                :          */
                               6342                 :              1 :         *flags |= FRM_NOOP;
  473 pg@bowt.ie               6343                 :              1 :         pagefrz->FreezePageRelfrozenXid = FreezePageRelfrozenXid;
                               6344         [ -  + ]:              1 :         if (MultiXactIdPrecedes(multi, pagefrz->FreezePageRelminMxid))
  473 pg@bowt.ie               6345                 :UBC           0 :             pagefrz->FreezePageRelminMxid = multi;
 3772 alvherre@alvh.no-ip.     6346                 :CBC           1 :         pfree(members);
  742 pg@bowt.ie               6347                 :              1 :         return multi;
                               6348                 :                :     }
                               6349                 :                : 
                               6350                 :                :     /*
                               6351                 :                :      * Do a more thorough second pass over the multi to figure out which
                               6352                 :                :      * member XIDs actually need to be kept.  Checking the precise status of
                               6353                 :                :      * individual members might even show that we don't need to keep anything.
                               6354                 :                :      * That is quite possible even though the Multi must be >= OldestMxact,
                               6355                 :                :      * since our second pass only keeps member XIDs when it's truly necessary;
                               6356                 :                :      * even member XIDs >= OldestXmin often won't be kept by second pass.
                               6357                 :                :      */
 3772 alvherre@alvh.no-ip.     6358                 :              1 :     nnewmembers = 0;
                               6359                 :              1 :     newmembers = palloc(sizeof(MultiXactMember) * nmembers);
                               6360                 :              1 :     has_lockers = false;
                               6361                 :              1 :     update_xid = InvalidTransactionId;
                               6362                 :              1 :     update_committed = false;
                               6363                 :                : 
                               6364                 :                :     /*
                               6365                 :                :      * Determine whether to keep each member xid, or to ignore it instead
                               6366                 :                :      */
  479 pg@bowt.ie               6367         [ +  + ]:              3 :     for (int i = 0; i < nmembers; i++)
                               6368                 :                :     {
                               6369                 :              2 :         TransactionId xid = members[i].xid;
                               6370                 :              2 :         MultiXactStatus mstatus = members[i].status;
                               6371                 :                : 
                               6372         [ -  + ]:              2 :         Assert(!TransactionIdPrecedes(xid, cutoffs->relfrozenxid));
                               6373                 :                : 
                               6374         [ +  - ]:              2 :         if (!ISUPDATE_from_mxstatus(mstatus))
                               6375                 :                :         {
                               6376                 :                :             /*
                               6377                 :                :              * Locker XID (not updater XID).  We only keep lockers that are
                               6378                 :                :              * still running.
                               6379                 :                :              */
                               6380   [ +  -  +  + ]:              4 :             if (TransactionIdIsCurrentTransactionId(xid) ||
                               6381                 :              2 :                 TransactionIdIsInProgress(xid))
                               6382                 :                :             {
  473                          6383         [ -  + ]:              1 :                 if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
  473 pg@bowt.ie               6384         [ #  # ]:UBC           0 :                     ereport(ERROR,
                               6385                 :                :                             (errcode(ERRCODE_DATA_CORRUPTED),
                               6386                 :                :                              errmsg_internal("multixact %u contains running locker XID %u from before removable cutoff %u",
                               6387                 :                :                                              multi, xid,
                               6388                 :                :                                              cutoffs->OldestXmin)));
  479 pg@bowt.ie               6389                 :CBC           1 :                 newmembers[nnewmembers++] = members[i];
                               6390                 :              1 :                 has_lockers = true;
                               6391                 :                :             }
                               6392                 :                : 
                               6393                 :              2 :             continue;
                               6394                 :                :         }
                               6395                 :                : 
                               6396                 :                :         /*
                               6397                 :                :          * Updater XID (not locker XID).  Should we keep it?
                               6398                 :                :          *
                               6399                 :                :          * Since the tuple wasn't totally removed when vacuum pruned, the
                               6400                 :                :          * update Xid cannot possibly be older than OldestXmin cutoff unless
                               6401                 :                :          * the updater XID aborted.  If the updater transaction is known
                               6402                 :                :          * aborted or crashed then it's okay to ignore it, otherwise not.
                               6403                 :                :          *
                               6404                 :                :          * In any case the Multi should never contain two updaters, whatever
                               6405                 :                :          * their individual commit status.  Check for that first, in passing.
                               6406                 :                :          */
  479 pg@bowt.ie               6407         [ #  # ]:UBC           0 :         if (TransactionIdIsValid(update_xid))
                               6408         [ #  # ]:              0 :             ereport(ERROR,
                               6409                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6410                 :                :                      errmsg_internal("multixact %u has two or more updating members",
                               6411                 :                :                                      multi),
                               6412                 :                :                      errdetail_internal("First updater XID=%u second updater XID=%u.",
                               6413                 :                :                                         update_xid, xid)));
                               6414                 :                : 
                               6415                 :                :         /*
                               6416                 :                :          * As with all tuple visibility routines, it's critical to test
                               6417                 :                :          * TransactionIdIsInProgress before TransactionIdDidCommit, because of
                               6418                 :                :          * race conditions explained in detail in heapam_visibility.c.
                               6419                 :                :          */
                               6420   [ #  #  #  # ]:              0 :         if (TransactionIdIsCurrentTransactionId(xid) ||
                               6421                 :              0 :             TransactionIdIsInProgress(xid))
                               6422                 :              0 :             update_xid = xid;
                               6423         [ #  # ]:              0 :         else if (TransactionIdDidCommit(xid))
                               6424                 :                :         {
                               6425                 :                :             /*
                               6426                 :                :              * The transaction committed, so we can tell caller to set
                               6427                 :                :              * HEAP_XMAX_COMMITTED.  (We can only do this because we know the
                               6428                 :                :              * transaction is not running.)
                               6429                 :                :              */
                               6430                 :              0 :             update_committed = true;
                               6431                 :              0 :             update_xid = xid;
                               6432                 :                :         }
                               6433                 :                :         else
                               6434                 :                :         {
                               6435                 :                :             /*
                               6436                 :                :              * Not in progress, not committed -- must be aborted or crashed;
                               6437                 :                :              * we can ignore it.
                               6438                 :                :              */
                               6439                 :              0 :             continue;
                               6440                 :                :         }
                               6441                 :                : 
                               6442                 :                :         /*
                               6443                 :                :          * We determined that updater must be kept -- add it to pending new
                               6444                 :                :          * members list
                               6445                 :                :          */
  473                          6446         [ #  # ]:              0 :         if (TransactionIdPrecedes(xid, cutoffs->OldestXmin))
                               6447         [ #  # ]:              0 :             ereport(ERROR,
                               6448                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6449                 :                :                      errmsg_internal("multixact %u contains committed update XID %u from before removable cutoff %u",
                               6450                 :                :                                      multi, xid, cutoffs->OldestXmin)));
  479                          6451                 :              0 :         newmembers[nnewmembers++] = members[i];
                               6452                 :                :     }
                               6453                 :                : 
 3772 alvherre@alvh.no-ip.     6454                 :CBC           1 :     pfree(members);
                               6455                 :                : 
                               6456                 :                :     /*
                               6457                 :                :      * Determine what to do with caller's multi based on information gathered
                               6458                 :                :      * during our second pass
                               6459                 :                :      */
                               6460         [ -  + ]:              1 :     if (nnewmembers == 0)
                               6461                 :                :     {
                               6462                 :                :         /* Nothing worth keeping */
 3772 alvherre@alvh.no-ip.     6463                 :UBC           0 :         *flags |= FRM_INVALIDATE_XMAX;
  479 pg@bowt.ie               6464                 :              0 :         newxmax = InvalidTransactionId;
                               6465                 :                :     }
 3772 alvherre@alvh.no-ip.     6466   [ -  +  -  - ]:CBC           1 :     else if (TransactionIdIsValid(update_xid) && !has_lockers)
                               6467                 :                :     {
                               6468                 :                :         /*
                               6469                 :                :          * If there's a single member and it's an update, pass it back alone
                               6470                 :                :          * without creating a new Multi.  (XXX we could do this when there's a
                               6471                 :                :          * single remaining locker, too, but that would complicate the API too
                               6472                 :                :          * much; moreover, the case with the single updater is more
                               6473                 :                :          * interesting, because those are longer-lived.)
                               6474                 :                :          */
 3772 alvherre@alvh.no-ip.     6475         [ #  # ]:UBC           0 :         Assert(nnewmembers == 1);
                               6476                 :              0 :         *flags |= FRM_RETURN_IS_XID;
                               6477         [ #  # ]:              0 :         if (update_committed)
                               6478                 :              0 :             *flags |= FRM_MARK_COMMITTED;
  479 pg@bowt.ie               6479                 :              0 :         newxmax = update_xid;
                               6480                 :                :     }
                               6481                 :                :     else
                               6482                 :                :     {
                               6483                 :                :         /*
                               6484                 :                :          * Create a new multixact with the surviving members of the previous
                               6485                 :                :          * one, to set as new Xmax in the tuple
                               6486                 :                :          */
  479 pg@bowt.ie               6487                 :CBC           1 :         newxmax = MultiXactIdCreateFromMembers(nnewmembers, newmembers);
 3772 alvherre@alvh.no-ip.     6488                 :              1 :         *flags |= FRM_RETURN_IS_MULTI;
                               6489                 :                :     }
                               6490                 :                : 
                               6491                 :              1 :     pfree(newmembers);
                               6492                 :                : 
  473 pg@bowt.ie               6493                 :              1 :     pagefrz->freeze_required = true;
  479                          6494                 :              1 :     return newxmax;
                               6495                 :                : }
                               6496                 :                : 
                               6497                 :                : /*
                               6498                 :                :  * heap_prepare_freeze_tuple
                               6499                 :                :  *
                               6500                 :                :  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
                               6501                 :                :  * are older than the OldestXmin and/or OldestMxact freeze cutoffs.  If so,
                               6502                 :                :  * setup enough state (in the *frz output argument) to enable caller to
                               6503                 :                :  * process this tuple as part of freezing its page, and return true.  Return
                               6504                 :                :  * false if nothing can be changed about the tuple right now.
                               6505                 :                :  *
                               6506                 :                :  * Also sets *totally_frozen to true if the tuple will be totally frozen once
                               6507                 :                :  * caller executes returned freeze plan (or if the tuple was already totally
                               6508                 :                :  * frozen by an earlier VACUUM).  This indicates that there are no remaining
                               6509                 :                :  * XIDs or MultiXactIds that will need to be processed by a future VACUUM.
                               6510                 :                :  *
                               6511                 :                :  * VACUUM caller must assemble HeapTupleFreeze freeze plan entries for every
                               6512                 :                :  * tuple that we returned true for, and then execute freezing.  Caller must
                               6513                 :                :  * initialize pagefrz fields for page as a whole before first call here for
                               6514                 :                :  * each heap page.
                               6515                 :                :  *
                               6516                 :                :  * VACUUM caller decides on whether or not to freeze the page as a whole.
                               6517                 :                :  * We'll often prepare freeze plans for a page that caller just discards.
                               6518                 :                :  * However, VACUUM doesn't always get to make a choice; it must freeze when
                               6519                 :                :  * pagefrz.freeze_required is set, to ensure that any XIDs < FreezeLimit (and
                               6520                 :                :  * MXIDs < MultiXactCutoff) can never be left behind.  We help to make sure
                               6521                 :                :  * that VACUUM always follows that rule.
                               6522                 :                :  *
                               6523                 :                :  * We sometimes force freezing of xmax MultiXactId values long before it is
                               6524                 :                :  * strictly necessary to do so just to ensure the FreezeLimit postcondition.
                               6525                 :                :  * It's worth processing MultiXactIds proactively when it is cheap to do so,
                               6526                 :                :  * and it's convenient to make that happen by piggy-backing it on the "force
                               6527                 :                :  * freezing" mechanism.  Conversely, we sometimes delay freezing MultiXactIds
                               6528                 :                :  * because it is expensive right now (though only when it's still possible to
                               6529                 :                :  * do so without violating the FreezeLimit/MultiXactCutoff postcondition).
                               6530                 :                :  *
                               6531                 :                :  * It is assumed that the caller has checked the tuple with
                               6532                 :                :  * HeapTupleSatisfiesVacuum() and determined that it is not HEAPTUPLE_DEAD
                               6533                 :                :  * (else we should be removing the tuple, not freezing it).
                               6534                 :                :  *
                               6535                 :                :  * NB: This function has side effects: it might allocate a new MultiXactId.
                               6536                 :                :  * It will be set as tuple's new xmax when our *frz output is processed within
                               6537                 :                :  * heap_execute_freeze_tuple later on.  If the tuple is in a shared buffer
                               6538                 :                :  * then caller had better have an exclusive lock on it already.
                               6539                 :                :  */
                               6540                 :                : bool
 2344 andres@anarazel.de       6541                 :       15681373 : heap_prepare_freeze_tuple(HeapTupleHeader tuple,
                               6542                 :                :                           const struct VacuumCutoffs *cutoffs,
                               6543                 :                :                           HeapPageFreeze *pagefrz,
                               6544                 :                :                           HeapTupleFreeze *frz, bool *totally_frozen)
                               6545                 :                : {
  479 pg@bowt.ie               6546                 :       15681373 :     bool        xmin_already_frozen = false,
                               6547                 :       15681373 :                 xmax_already_frozen = false;
                               6548                 :       15681373 :     bool        freeze_xmin = false,
                               6549                 :       15681373 :                 replace_xvac = false,
                               6550                 :       15681373 :                 replace_xmax = false,
                               6551                 :       15681373 :                 freeze_xmax = false;
                               6552                 :                :     TransactionId xid;
                               6553                 :                : 
  467                          6554                 :       15681373 :     frz->xmax = HeapTupleHeaderGetRawXmax(tuple);
 3772 alvherre@alvh.no-ip.     6555                 :       15681373 :     frz->t_infomask2 = tuple->t_infomask2;
                               6556                 :       15681373 :     frz->t_infomask = tuple->t_infomask;
  467 pg@bowt.ie               6557                 :       15681373 :     frz->frzflags = 0;
                               6558                 :       15681373 :     frz->checkflags = 0;
                               6559                 :                : 
                               6560                 :                :     /*
                               6561                 :                :      * Process xmin, while keeping track of whether it's already frozen, or
                               6562                 :                :      * will become frozen iff our freeze plan is executed by caller (could be
                               6563                 :                :      * neither).
                               6564                 :                :      */
 6370 tgl@sss.pgh.pa.us        6565         [ +  + ]:       15681373 :     xid = HeapTupleHeaderGetXmin(tuple);
 1809 alvherre@alvh.no-ip.     6566         [ +  + ]:       15681373 :     if (!TransactionIdIsNormal(xid))
  479 pg@bowt.ie               6567                 :       12902131 :         xmin_already_frozen = true;
                               6568                 :                :     else
                               6569                 :                :     {
                               6570         [ -  + ]:        2779242 :         if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
 2344 andres@anarazel.de       6571         [ #  # ]:UBC           0 :             ereport(ERROR,
                               6572                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6573                 :                :                      errmsg_internal("found xmin %u from before relfrozenxid %u",
                               6574                 :                :                                      xid, cutoffs->relfrozenxid)));
                               6575                 :                : 
                               6576                 :                :         /* Will set freeze_xmin flags in freeze plan below */
  473 pg@bowt.ie               6577                 :CBC     2779242 :         freeze_xmin = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
                               6578                 :                : 
                               6579                 :                :         /* Verify that xmin committed if and when freeze plan is executed */
  467                          6580         [ +  + ]:        2779242 :         if (freeze_xmin)
                               6581                 :        2157917 :             frz->checkflags |= HEAP_FREEZE_CHECK_XMIN_COMMITTED;
                               6582                 :                :     }
                               6583                 :                : 
                               6584                 :                :     /*
                               6585                 :                :      * Old-style VACUUM FULL is gone, but we have to process xvac for as long
                               6586                 :                :      * as we support having MOVED_OFF/MOVED_IN tuples in the database
                               6587                 :                :      */
  479                          6588         [ -  + ]:       15681373 :     xid = HeapTupleHeaderGetXvac(tuple);
                               6589         [ -  + ]:       15681373 :     if (TransactionIdIsNormal(xid))
                               6590                 :                :     {
  479 pg@bowt.ie               6591         [ #  # ]:UBC           0 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
                               6592         [ #  # ]:              0 :         Assert(TransactionIdPrecedes(xid, cutoffs->OldestXmin));
                               6593                 :                : 
                               6594                 :                :         /*
                               6595                 :                :          * For Xvac, we always freeze proactively.  This allows totally_frozen
                               6596                 :                :          * tracking to ignore xvac.
                               6597                 :                :          */
  473                          6598                 :              0 :         replace_xvac = pagefrz->freeze_required = true;
                               6599                 :                : 
                               6600                 :                :         /* Will set replace_xvac flags in freeze plan below */
                               6601                 :                :     }
                               6602                 :                : 
                               6603                 :                :     /* Now process xmax */
  467 pg@bowt.ie               6604                 :CBC    15681373 :     xid = frz->xmax;
 3790 alvherre@alvh.no-ip.     6605         [ +  + ]:       15681373 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
                               6606                 :                :     {
                               6607                 :                :         /* Raw xmax is a MultiXactId */
                               6608                 :                :         TransactionId newxmax;
                               6609                 :                :         uint16      flags;
                               6610                 :                : 
                               6611                 :                :         /*
                               6612                 :                :          * We will either remove xmax completely (in the "freeze_xmax" path),
                               6613                 :                :          * process xmax by replacing it (in the "replace_xmax" path), or
                               6614                 :                :          * perform no-op xmax processing.  The only constraint is that the
                               6615                 :                :          * FreezeLimit/MultiXactCutoff postcondition must never be violated.
                               6616                 :                :          */
  479 pg@bowt.ie               6617                 :              9 :         newxmax = FreezeMultiXactId(xid, tuple->t_infomask, cutoffs,
                               6618                 :                :                                     &flags, pagefrz);
                               6619                 :                : 
  473                          6620         [ +  + ]:              9 :         if (flags & FRM_NOOP)
                               6621                 :                :         {
                               6622                 :                :             /*
                               6623                 :                :              * xmax is a MultiXactId, and nothing about it changes for now.
                               6624                 :                :              * This is the only case where 'freeze_required' won't have been
                               6625                 :                :              * set for us by FreezeMultiXactId, as well as the only case where
                               6626                 :                :              * neither freeze_xmax nor replace_xmax are set (given a multi).
                               6627                 :                :              *
                               6628                 :                :              * This is a no-op, but the call to FreezeMultiXactId might have
                               6629                 :                :              * ratcheted back NewRelfrozenXid and/or NewRelminMxid trackers
                               6630                 :                :              * for us (the "freeze page" variants, specifically).  That'll
                               6631                 :                :              * make it safe for our caller to freeze the page later on, while
                               6632                 :                :              * leaving this particular xmax undisturbed.
                               6633                 :                :              *
                               6634                 :                :              * FreezeMultiXactId is _not_ responsible for the "no freeze"
                               6635                 :                :              * NewRelfrozenXid/NewRelminMxid trackers, though -- that's our
                               6636                 :                :              * job.  A call to heap_tuple_should_freeze for this same tuple
                               6637                 :                :              * will take place below if 'freeze_required' isn't set already.
                               6638                 :                :              * (This repeats work from FreezeMultiXactId, but allows "no
                               6639                 :                :              * freeze" tracker maintenance to happen in only one place.)
                               6640                 :                :              */
                               6641         [ -  + ]:              1 :             Assert(!MultiXactIdPrecedes(newxmax, cutoffs->MultiXactCutoff));
                               6642   [ +  -  -  + ]:              1 :             Assert(MultiXactIdIsValid(newxmax) && xid == newxmax);
                               6643                 :                :         }
                               6644         [ -  + ]:              8 :         else if (flags & FRM_RETURN_IS_XID)
                               6645                 :                :         {
                               6646                 :                :             /*
                               6647                 :                :              * xmax will become an updater Xid (original MultiXact's updater
                               6648                 :                :              * member Xid will be carried forward as a simple Xid in Xmax).
                               6649                 :                :              */
  479 pg@bowt.ie               6650         [ #  # ]:UBC           0 :             Assert(!TransactionIdPrecedes(newxmax, cutoffs->OldestXmin));
                               6651                 :                : 
                               6652                 :                :             /*
                               6653                 :                :              * NB -- some of these transformations are only valid because we
                               6654                 :                :              * know the return Xid is a tuple updater (i.e. not merely a
                               6655                 :                :              * locker.) Also note that the only reason we don't explicitly
                               6656                 :                :              * worry about HEAP_KEYS_UPDATED is because it lives in
                               6657                 :                :              * t_infomask2 rather than t_infomask.
                               6658                 :                :              */
 3772 alvherre@alvh.no-ip.     6659                 :              0 :             frz->t_infomask &= ~HEAP_XMAX_BITS;
                               6660                 :              0 :             frz->xmax = newxmax;
                               6661         [ #  # ]:              0 :             if (flags & FRM_MARK_COMMITTED)
 2474 teodor@sigaev.ru         6662                 :              0 :                 frz->t_infomask |= HEAP_XMAX_COMMITTED;
  479 pg@bowt.ie               6663                 :              0 :             replace_xmax = true;
                               6664                 :                :         }
 3772 alvherre@alvh.no-ip.     6665         [ +  + ]:CBC           8 :         else if (flags & FRM_RETURN_IS_MULTI)
                               6666                 :                :         {
                               6667                 :                :             uint16      newbits;
                               6668                 :                :             uint16      newbits2;
                               6669                 :                : 
                               6670                 :                :             /*
                               6671                 :                :              * xmax is an old MultiXactId that we have to replace with a new
                               6672                 :                :              * MultiXactId, to carry forward two or more original member XIDs.
                               6673                 :                :              */
  479 pg@bowt.ie               6674         [ -  + ]:              1 :             Assert(!MultiXactIdPrecedes(newxmax, cutoffs->OldestMxact));
                               6675                 :                : 
                               6676                 :                :             /*
                               6677                 :                :              * We can't use GetMultiXactIdHintBits directly on the new multi
                               6678                 :                :              * here; that routine initializes the masks to all zeroes, which
                               6679                 :                :              * would lose other bits we need.  Doing it this way ensures all
                               6680                 :                :              * unrelated bits remain untouched.
                               6681                 :                :              */
 3772 alvherre@alvh.no-ip.     6682                 :              1 :             frz->t_infomask &= ~HEAP_XMAX_BITS;
                               6683                 :              1 :             frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               6684                 :              1 :             GetMultiXactIdHintBits(newxmax, &newbits, &newbits2);
                               6685                 :              1 :             frz->t_infomask |= newbits;
                               6686                 :              1 :             frz->t_infomask2 |= newbits2;
                               6687                 :              1 :             frz->xmax = newxmax;
  479 pg@bowt.ie               6688                 :              1 :             replace_xmax = true;
                               6689                 :                :         }
                               6690                 :                :         else
                               6691                 :                :         {
                               6692                 :                :             /*
                               6693                 :                :              * Freeze plan for tuple "freezes xmax" in the strictest sense:
                               6694                 :                :              * it'll leave nothing in xmax (neither an Xid nor a MultiXactId).
                               6695                 :                :              */
                               6696         [ -  + ]:              7 :             Assert(flags & FRM_INVALIDATE_XMAX);
  742                          6697         [ -  + ]:              7 :             Assert(!TransactionIdIsValid(newxmax));
                               6698                 :                : 
                               6699                 :                :             /* Will set freeze_xmax flags in freeze plan below */
  479                          6700                 :              7 :             freeze_xmax = true;
                               6701                 :                :         }
                               6702                 :                : 
                               6703                 :                :         /* MultiXactId processing forces freezing (barring FRM_NOOP case) */
  473                          6704   [ -  +  -  -  :              9 :         Assert(pagefrz->freeze_required || (!freeze_xmax && !replace_xmax));
                                              -  - ]
                               6705                 :                :     }
 2860 rhaas@postgresql.org     6706         [ +  + ]:       15681364 :     else if (TransactionIdIsNormal(xid))
                               6707                 :                :     {
                               6708                 :                :         /* Raw xmax is normal XID */
  479 pg@bowt.ie               6709         [ -  + ]:        3929888 :         if (TransactionIdPrecedes(xid, cutoffs->relfrozenxid))
 2344 andres@anarazel.de       6710         [ #  # ]:UBC           0 :             ereport(ERROR,
                               6711                 :                :                     (errcode(ERRCODE_DATA_CORRUPTED),
                               6712                 :                :                      errmsg_internal("found xmax %u from before relfrozenxid %u",
                               6713                 :                :                                      xid, cutoffs->relfrozenxid)));
                               6714                 :                : 
                               6715                 :                :         /* Will set freeze_xmax flags in freeze plan below */
  467 pg@bowt.ie               6716                 :CBC     3929888 :         freeze_xmax = TransactionIdPrecedes(xid, cutoffs->OldestXmin);
                               6717                 :                : 
                               6718                 :                :         /*
                               6719                 :                :          * Verify that xmax aborted if and when freeze plan is executed,
                               6720                 :                :          * provided it's from an update. (A lock-only xmax can be removed
                               6721                 :                :          * independent of this, since the lock is released at xact end.)
                               6722                 :                :          */
                               6723   [ +  +  +  +  :        3929888 :         if (freeze_xmax && !HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask))
                                              +  - ]
                               6724                 :           1402 :             frz->checkflags |= HEAP_FREEZE_CHECK_XMAX_ABORTED;
                               6725                 :                :     }
  508                          6726         [ +  - ]:       11751476 :     else if (!TransactionIdIsValid(xid))
                               6727                 :                :     {
                               6728                 :                :         /* Raw xmax is InvalidTransactionId XID */
                               6729         [ -  + ]:       11751476 :         Assert((tuple->t_infomask & HEAP_XMAX_IS_MULTI) == 0);
 2172 alvherre@alvh.no-ip.     6730                 :       11751476 :         xmax_already_frozen = true;
                               6731                 :                :     }
                               6732                 :                :     else
 2172 alvherre@alvh.no-ip.     6733         [ #  # ]:UBC           0 :         ereport(ERROR,
                               6734                 :                :                 (errcode(ERRCODE_DATA_CORRUPTED),
                               6735                 :                :                  errmsg_internal("found raw xmax %u (infomask 0x%04x) not invalid and not multi",
                               6736                 :                :                                  xid, tuple->t_infomask)));
                               6737                 :                : 
  479 pg@bowt.ie               6738         [ +  + ]:CBC    15681373 :     if (freeze_xmin)
                               6739                 :                :     {
                               6740         [ -  + ]:        2157917 :         Assert(!xmin_already_frozen);
                               6741                 :                : 
                               6742                 :        2157917 :         frz->t_infomask |= HEAP_XMIN_FROZEN;
                               6743                 :                :     }
                               6744         [ -  + ]:       15681373 :     if (replace_xvac)
                               6745                 :                :     {
                               6746                 :                :         /*
                               6747                 :                :          * If a MOVED_OFF tuple is not dead, the xvac transaction must have
                               6748                 :                :          * failed; whereas a non-dead MOVED_IN tuple must mean the xvac
                               6749                 :                :          * transaction succeeded.
                               6750                 :                :          */
  473 pg@bowt.ie               6751         [ #  # ]:UBC           0 :         Assert(pagefrz->freeze_required);
  479                          6752         [ #  # ]:              0 :         if (tuple->t_infomask & HEAP_MOVED_OFF)
                               6753                 :              0 :             frz->frzflags |= XLH_INVALID_XVAC;
                               6754                 :                :         else
                               6755                 :              0 :             frz->frzflags |= XLH_FREEZE_XVAC;
                               6756                 :                :     }
  479 pg@bowt.ie               6757         [ +  + ]:CBC    15681373 :     if (replace_xmax)
                               6758                 :                :     {
                               6759   [ +  -  -  + ]:              1 :         Assert(!xmax_already_frozen && !freeze_xmax);
  473                          6760         [ -  + ]:              1 :         Assert(pagefrz->freeze_required);
                               6761                 :                : 
                               6762                 :                :         /* Already set replace_xmax flags in freeze plan earlier */
                               6763                 :                :     }
 3790 alvherre@alvh.no-ip.     6764         [ +  + ]:       15681373 :     if (freeze_xmax)
                               6765                 :                :     {
  479 pg@bowt.ie               6766   [ +  -  -  + ]:           2165 :         Assert(!xmax_already_frozen && !replace_xmax);
                               6767                 :                : 
 3772 alvherre@alvh.no-ip.     6768                 :           2165 :         frz->xmax = InvalidTransactionId;
                               6769                 :                : 
                               6770                 :                :         /*
                               6771                 :                :          * The tuple might be marked either XMAX_INVALID or XMAX_COMMITTED +
                               6772                 :                :          * LOCKED.  Normalize to INVALID just to be sure no one gets confused.
                               6773                 :                :          * Also get rid of the HEAP_KEYS_UPDATED bit.
                               6774                 :                :          */
                               6775                 :           2165 :         frz->t_infomask &= ~HEAP_XMAX_BITS;
                               6776                 :           2165 :         frz->t_infomask |= HEAP_XMAX_INVALID;
                               6777                 :           2165 :         frz->t_infomask2 &= ~HEAP_HOT_UPDATED;
                               6778                 :           2165 :         frz->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               6779                 :                :     }
                               6780                 :                : 
                               6781                 :                :     /*
                               6782                 :                :      * Determine if this tuple is already totally frozen, or will become
                               6783                 :                :      * totally frozen (provided caller executes freeze plans for the page)
                               6784                 :                :      */
  479 pg@bowt.ie               6785   [ +  +  +  +  :       30739256 :     *totally_frozen = ((freeze_xmin || xmin_already_frozen) &&
                                              +  + ]
                               6786         [ +  + ]:       15057883 :                        (freeze_xmax || xmax_already_frozen));
                               6787                 :                : 
  473                          6788   [ +  +  +  +  :       15681373 :     if (!pagefrz->freeze_required && !(xmin_already_frozen &&
                                              +  + ]
                               6789                 :                :                                        xmax_already_frozen))
                               6790                 :                :     {
                               6791                 :                :         /*
                               6792                 :                :          * So far no previous tuple from the page made freezing mandatory.
                               6793                 :                :          * Does this tuple force caller to freeze the entire page?
                               6794                 :                :          */
                               6795                 :        5483586 :         pagefrz->freeze_required =
                               6796                 :        5483586 :             heap_tuple_should_freeze(tuple, cutoffs,
                               6797                 :                :                                      &pagefrz->NoFreezePageRelfrozenXid,
                               6798                 :                :                                      &pagefrz->NoFreezePageRelminMxid);
                               6799                 :                :     }
                               6800                 :                : 
                               6801                 :                :     /* Tell caller if this tuple has a usable freeze plan set in *frz */
  479                          6802   [ +  +  +  -  :       15681373 :     return freeze_xmin || replace_xvac || replace_xmax || freeze_xmax;
                                        +  -  +  + ]
                               6803                 :                : }
                               6804                 :                : 
                               6805                 :                : /*
                               6806                 :                :  * heap_execute_freeze_tuple
                               6807                 :                :  *      Execute the prepared freezing of a tuple with caller's freeze plan.
                               6808                 :                :  *
                               6809                 :                :  * Caller is responsible for ensuring that no other backend can access the
                               6810                 :                :  * storage underlying this tuple, either by holding an exclusive lock on the
                               6811                 :                :  * buffer containing it (which is what lazy VACUUM does), or by having it be
                               6812                 :                :  * in private storage (which is what CLUSTER and friends do).
                               6813                 :                :  */
                               6814                 :                : static inline void
  516                          6815                 :         894218 : heap_execute_freeze_tuple(HeapTupleHeader tuple, HeapTupleFreeze *frz)
                               6816                 :                : {
 3772 alvherre@alvh.no-ip.     6817                 :         894218 :     HeapTupleHeaderSetXmax(tuple, frz->xmax);
                               6818                 :                : 
                               6819         [ -  + ]:         894218 :     if (frz->frzflags & XLH_FREEZE_XVAC)
 3772 alvherre@alvh.no-ip.     6820         [ #  # ]:UBC           0 :         HeapTupleHeaderSetXvac(tuple, FrozenTransactionId);
                               6821                 :                : 
 3772 alvherre@alvh.no-ip.     6822         [ -  + ]:CBC      894218 :     if (frz->frzflags & XLH_INVALID_XVAC)
 3772 alvherre@alvh.no-ip.     6823         [ #  # ]:UBC           0 :         HeapTupleHeaderSetXvac(tuple, InvalidTransactionId);
                               6824                 :                : 
 3772 alvherre@alvh.no-ip.     6825                 :CBC      894218 :     tuple->t_infomask = frz->t_infomask;
                               6826                 :         894218 :     tuple->t_infomask2 = frz->t_infomask2;
                               6827                 :         894218 : }
                               6828                 :                : 
                               6829                 :                : /*
                               6830                 :                :  * Perform xmin/xmax XID status sanity checks before actually executing freeze
                               6831                 :                :  * plans.
                               6832                 :                :  *
                               6833                 :                :  * heap_prepare_freeze_tuple doesn't perform these checks directly because
                               6834                 :                :  * pg_xact lookups are relatively expensive.  They shouldn't be repeated by
                               6835                 :                :  * successive VACUUMs that each decide against freezing the same page.
                               6836                 :                :  */
                               6837                 :                : void
   11 heikki.linnakangas@i     6838                 :GNC       14927 : heap_pre_freeze_checks(Buffer buffer,
                               6839                 :                :                        HeapTupleFreeze *tuples, int ntuples)
                               6840                 :                : {
  516 pg@bowt.ie               6841                 :CBC       14927 :     Page        page = BufferGetPage(buffer);
                               6842                 :                : 
  467                          6843         [ +  + ]:         637991 :     for (int i = 0; i < ntuples; i++)
                               6844                 :                :     {
                               6845                 :         623064 :         HeapTupleFreeze *frz = tuples + i;
                               6846                 :         623064 :         ItemId      itemid = PageGetItemId(page, frz->offset);
                               6847                 :                :         HeapTupleHeader htup;
                               6848                 :                : 
                               6849                 :         623064 :         htup = (HeapTupleHeader) PageGetItem(page, itemid);
                               6850                 :                : 
                               6851                 :                :         /* Deliberately avoid relying on tuple hint bits here */
                               6852         [ +  + ]:         623064 :         if (frz->checkflags & HEAP_FREEZE_CHECK_XMIN_COMMITTED)
                               6853                 :                :         {
                               6854                 :         623063 :             TransactionId xmin = HeapTupleHeaderGetRawXmin(htup);
                               6855                 :                : 
                               6856         [ -  + ]:         623063 :             Assert(!HeapTupleHeaderXminFrozen(htup));
                               6857         [ -  + ]:         623063 :             if (unlikely(!TransactionIdDidCommit(xmin)))
  467 pg@bowt.ie               6858         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               6859                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               6860                 :                :                          errmsg_internal("uncommitted xmin %u needs to be frozen",
                               6861                 :                :                                          xmin)));
                               6862                 :                :         }
                               6863                 :                : 
                               6864                 :                :         /*
                               6865                 :                :          * TransactionIdDidAbort won't work reliably in the presence of XIDs
                               6866                 :                :          * left behind by transactions that were in progress during a crash,
                               6867                 :                :          * so we can only check that xmax didn't commit
                               6868                 :                :          */
  467 pg@bowt.ie               6869         [ +  + ]:CBC      623064 :         if (frz->checkflags & HEAP_FREEZE_CHECK_XMAX_ABORTED)
                               6870                 :                :         {
                               6871                 :            513 :             TransactionId xmax = HeapTupleHeaderGetRawXmax(htup);
                               6872                 :                : 
                               6873         [ -  + ]:            513 :             Assert(TransactionIdIsNormal(xmax));
                               6874         [ -  + ]:            513 :             if (unlikely(TransactionIdDidCommit(xmax)))
  467 pg@bowt.ie               6875         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               6876                 :                :                         (errcode(ERRCODE_DATA_CORRUPTED),
                               6877                 :                :                          errmsg_internal("cannot freeze committed xmax %u",
                               6878                 :                :                                          xmax)));
                               6879                 :                :         }
                               6880                 :                :     }
   11 heikki.linnakangas@i     6881                 :GNC       14927 : }
                               6882                 :                : 
                               6883                 :                : /*
                               6884                 :                :  * Helper which executes freezing of one or more heap tuples on a page on
                               6885                 :                :  * behalf of caller.  Caller passes an array of tuple plans from
                               6886                 :                :  * heap_prepare_freeze_tuple.  Caller must set 'offset' in each plan for us.
                               6887                 :                :  * Must be called in a critical section that also marks the buffer dirty and,
                               6888                 :                :  * if needed, emits WAL.
                               6889                 :                :  */
                               6890                 :                : void
                               6891                 :          14927 : heap_freeze_prepared_tuples(Buffer buffer, HeapTupleFreeze *tuples, int ntuples)
                               6892                 :                : {
                               6893                 :          14927 :     Page        page = BufferGetPage(buffer);
                               6894                 :                : 
  516 pg@bowt.ie               6895         [ +  + ]:CBC      637991 :     for (int i = 0; i < ntuples; i++)
                               6896                 :                :     {
  467                          6897                 :         623064 :         HeapTupleFreeze *frz = tuples + i;
                               6898                 :         623064 :         ItemId      itemid = PageGetItemId(page, frz->offset);
                               6899                 :                :         HeapTupleHeader htup;
                               6900                 :                : 
  516                          6901                 :         623064 :         htup = (HeapTupleHeader) PageGetItem(page, itemid);
  467                          6902                 :         623064 :         heap_execute_freeze_tuple(htup, frz);
                               6903                 :                :     }
  516 pg@bowt.ie               6904                 :GIC       14927 : }
                               6905                 :                : 
                               6906                 :                : /*
                               6907                 :                :  * heap_freeze_tuple
                               6908                 :                :  *      Freeze tuple in place, without WAL logging.
                               6909                 :                :  *
                               6910                 :                :  * Useful for callers like CLUSTER that perform their own WAL logging.
                               6911                 :                :  */
                               6912                 :                : bool
 2344 andres@anarazel.de       6913                 :CBC      375258 : heap_freeze_tuple(HeapTupleHeader tuple,
                               6914                 :                :                   TransactionId relfrozenxid, TransactionId relminmxid,
                               6915                 :                :                   TransactionId FreezeLimit, TransactionId MultiXactCutoff)
                               6916                 :                : {
                               6917                 :                :     HeapTupleFreeze frz;
                               6918                 :                :     bool        do_freeze;
                               6919                 :                :     bool        totally_frozen;
                               6920                 :                :     struct VacuumCutoffs cutoffs;
                               6921                 :                :     HeapPageFreeze pagefrz;
                               6922                 :                : 
  479 pg@bowt.ie               6923                 :         375258 :     cutoffs.relfrozenxid = relfrozenxid;
                               6924                 :         375258 :     cutoffs.relminmxid = relminmxid;
                               6925                 :         375258 :     cutoffs.OldestXmin = FreezeLimit;
                               6926                 :         375258 :     cutoffs.OldestMxact = MultiXactCutoff;
                               6927                 :         375258 :     cutoffs.FreezeLimit = FreezeLimit;
                               6928                 :         375258 :     cutoffs.MultiXactCutoff = MultiXactCutoff;
                               6929                 :                : 
  473                          6930                 :         375258 :     pagefrz.freeze_required = true;
                               6931                 :         375258 :     pagefrz.FreezePageRelfrozenXid = FreezeLimit;
                               6932                 :         375258 :     pagefrz.FreezePageRelminMxid = MultiXactCutoff;
                               6933                 :         375258 :     pagefrz.NoFreezePageRelfrozenXid = FreezeLimit;
                               6934                 :         375258 :     pagefrz.NoFreezePageRelminMxid = MultiXactCutoff;
                               6935                 :                : 
  479                          6936                 :         375258 :     do_freeze = heap_prepare_freeze_tuple(tuple, &cutoffs,
                               6937                 :                :                                           &pagefrz, &frz, &totally_frozen);
                               6938                 :                : 
                               6939                 :                :     /*
                               6940                 :                :      * Note that because this is not a WAL-logged operation, we don't need to
                               6941                 :                :      * fill in the offset in the freeze record.
                               6942                 :                :      */
                               6943                 :                : 
 3772 alvherre@alvh.no-ip.     6944         [ +  + ]:         375258 :     if (do_freeze)
                               6945                 :         251087 :         heap_execute_freeze_tuple(tuple, &frz);
                               6946                 :         375258 :     return do_freeze;
                               6947                 :                : }
                               6948                 :                : 
                               6949                 :                : /*
                               6950                 :                :  * For a given MultiXactId, return the hint bits that should be set in the
                               6951                 :                :  * tuple's infomask.
                               6952                 :                :  *
                               6953                 :                :  * Normally this should be called for a multixact that was just created, and
                               6954                 :                :  * so is on our local cache, so the GetMembers call is fast.
                               6955                 :                :  */
                               6956                 :                : static void
 4099                          6957                 :           1178 : GetMultiXactIdHintBits(MultiXactId multi, uint16 *new_infomask,
                               6958                 :                :                        uint16 *new_infomask2)
                               6959                 :                : {
                               6960                 :                :     int         nmembers;
                               6961                 :                :     MultiXactMember *members;
                               6962                 :                :     int         i;
 3973 bruce@momjian.us         6963                 :           1178 :     uint16      bits = HEAP_XMAX_IS_MULTI;
                               6964                 :           1178 :     uint16      bits2 = 0;
                               6965                 :           1178 :     bool        has_update = false;
                               6966                 :           1178 :     LockTupleMode strongest = LockTupleKeyShare;
                               6967                 :                : 
                               6968                 :                :     /*
                               6969                 :                :      * We only use this in multis we just created, so they cannot be values
                               6970                 :                :      * pre-pg_upgrade.
                               6971                 :                :      */
 3547 alvherre@alvh.no-ip.     6972                 :           1178 :     nmembers = GetMultiXactIdMembers(multi, &members, false, false);
                               6973                 :                : 
 4099                          6974         [ +  + ]:           3600 :     for (i = 0; i < nmembers; i++)
                               6975                 :                :     {
                               6976                 :                :         LockTupleMode mode;
                               6977                 :                : 
                               6978                 :                :         /*
                               6979                 :                :          * Remember the strongest lock mode held by any member of the
                               6980                 :                :          * multixact.
                               6981                 :                :          */
 4091                          6982                 :           2422 :         mode = TUPLOCK_from_mxstatus(members[i].status);
                               6983         [ +  + ]:           2422 :         if (mode > strongest)
                               6984                 :            656 :             strongest = mode;
                               6985                 :                : 
                               6986                 :                :         /* See what other bits we need */
 4099                          6987   [ +  +  +  +  :           2422 :         switch (members[i].status)
                                                 - ]
                               6988                 :                :         {
                               6989                 :           2231 :             case MultiXactStatusForKeyShare:
                               6990                 :                :             case MultiXactStatusForShare:
                               6991                 :                :             case MultiXactStatusForNoKeyUpdate:
                               6992                 :           2231 :                 break;
                               6993                 :                : 
                               6994                 :             52 :             case MultiXactStatusForUpdate:
                               6995                 :             52 :                 bits2 |= HEAP_KEYS_UPDATED;
                               6996                 :             52 :                 break;
                               6997                 :                : 
                               6998                 :            129 :             case MultiXactStatusNoKeyUpdate:
                               6999                 :            129 :                 has_update = true;
                               7000                 :            129 :                 break;
                               7001                 :                : 
                               7002                 :             10 :             case MultiXactStatusUpdate:
                               7003                 :             10 :                 bits2 |= HEAP_KEYS_UPDATED;
                               7004                 :             10 :                 has_update = true;
                               7005                 :             10 :                 break;
                               7006                 :                :         }
                               7007                 :                :     }
                               7008                 :                : 
 4091                          7009   [ +  +  +  + ]:           1178 :     if (strongest == LockTupleExclusive ||
                               7010                 :                :         strongest == LockTupleNoKeyExclusive)
                               7011                 :            216 :         bits |= HEAP_XMAX_EXCL_LOCK;
                               7012         [ +  + ]:            962 :     else if (strongest == LockTupleShare)
                               7013                 :            437 :         bits |= HEAP_XMAX_SHR_LOCK;
                               7014         [ +  - ]:            525 :     else if (strongest == LockTupleKeyShare)
                               7015                 :            525 :         bits |= HEAP_XMAX_KEYSHR_LOCK;
                               7016                 :                : 
 4099                          7017         [ +  + ]:           1178 :     if (!has_update)
                               7018                 :           1039 :         bits |= HEAP_XMAX_LOCK_ONLY;
                               7019                 :                : 
                               7020         [ +  - ]:           1178 :     if (nmembers > 0)
                               7021                 :           1178 :         pfree(members);
                               7022                 :                : 
                               7023                 :           1178 :     *new_infomask = bits;
                               7024                 :           1178 :     *new_infomask2 = bits2;
                               7025                 :           1178 : }
                               7026                 :                : 
                               7027                 :                : /*
                               7028                 :                :  * MultiXactIdGetUpdateXid
                               7029                 :                :  *
                               7030                 :                :  * Given a multixact Xmax and corresponding infomask, which does not have the
                               7031                 :                :  * HEAP_XMAX_LOCK_ONLY bit set, obtain and return the Xid of the updating
                               7032                 :                :  * transaction.
                               7033                 :                :  *
                               7034                 :                :  * Caller is expected to check the status of the updating transaction, if
                               7035                 :                :  * necessary.
                               7036                 :                :  */
                               7037                 :                : static TransactionId
                               7038                 :            553 : MultiXactIdGetUpdateXid(TransactionId xmax, uint16 t_infomask)
                               7039                 :                : {
 3973 bruce@momjian.us         7040                 :            553 :     TransactionId update_xact = InvalidTransactionId;
                               7041                 :                :     MultiXactMember *members;
                               7042                 :                :     int         nmembers;
                               7043                 :                : 
 4099 alvherre@alvh.no-ip.     7044         [ -  + ]:            553 :     Assert(!(t_infomask & HEAP_XMAX_LOCK_ONLY));
                               7045         [ -  + ]:            553 :     Assert(t_infomask & HEAP_XMAX_IS_MULTI);
                               7046                 :                : 
                               7047                 :                :     /*
                               7048                 :                :      * Since we know the LOCK_ONLY bit is not set, this cannot be a multi from
                               7049                 :                :      * pre-pg_upgrade.
                               7050                 :                :      */
 3547                          7051                 :            553 :     nmembers = GetMultiXactIdMembers(xmax, &members, false, false);
                               7052                 :                : 
 4099                          7053         [ +  - ]:            553 :     if (nmembers > 0)
                               7054                 :                :     {
                               7055                 :                :         int         i;
                               7056                 :                : 
                               7057         [ +  + ]:           2084 :         for (i = 0; i < nmembers; i++)
                               7058                 :                :         {
                               7059                 :                :             /* Ignore lockers */
 3789                          7060         [ +  + ]:           1531 :             if (!ISUPDATE_from_mxstatus(members[i].status))
 4099                          7061                 :            978 :                 continue;
                               7062                 :                : 
                               7063                 :                :             /* there can be at most one updater */
                               7064         [ -  + ]:            553 :             Assert(update_xact == InvalidTransactionId);
                               7065                 :            553 :             update_xact = members[i].xid;
                               7066                 :                : #ifndef USE_ASSERT_CHECKING
                               7067                 :                : 
                               7068                 :                :             /*
                               7069                 :                :              * in an assert-enabled build, walk the whole array to ensure
                               7070                 :                :              * there's no other updater.
                               7071                 :                :              */
                               7072                 :                :             break;
                               7073                 :                : #endif
                               7074                 :                :         }
                               7075                 :                : 
                               7076                 :            553 :         pfree(members);
                               7077                 :                :     }
                               7078                 :                : 
                               7079                 :            553 :     return update_xact;
                               7080                 :                : }
                               7081                 :                : 
                               7082                 :                : /*
                               7083                 :                :  * HeapTupleGetUpdateXid
                               7084                 :                :  *      As above, but use a HeapTupleHeader
                               7085                 :                :  *
                               7086                 :                :  * See also HeapTupleHeaderGetUpdateXid, which can be used without previously
                               7087                 :                :  * checking the hint bits.
                               7088                 :                :  */
                               7089                 :                : TransactionId
                               7090                 :            544 : HeapTupleGetUpdateXid(HeapTupleHeader tuple)
                               7091                 :                : {
                               7092                 :           1088 :     return MultiXactIdGetUpdateXid(HeapTupleHeaderGetRawXmax(tuple),
                               7093                 :            544 :                                    tuple->t_infomask);
                               7094                 :                : }
                               7095                 :                : 
                               7096                 :                : /*
                               7097                 :                :  * Does the given multixact conflict with the current transaction grabbing a
                               7098                 :                :  * tuple lock of the given strength?
                               7099                 :                :  *
                               7100                 :                :  * The passed infomask pairs up with the given multixact in the tuple header.
                               7101                 :                :  *
                               7102                 :                :  * If current_is_member is not NULL, it is set to 'true' if the current
                               7103                 :                :  * transaction is a member of the given multixact.
                               7104                 :                :  */
                               7105                 :                : static bool
 3397                          7106                 :             94 : DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask,
                               7107                 :                :                         LockTupleMode lockmode, bool *current_is_member)
                               7108                 :                : {
                               7109                 :                :     int         nmembers;
                               7110                 :                :     MultiXactMember *members;
 3249 bruce@momjian.us         7111                 :             94 :     bool        result = false;
                               7112                 :             94 :     LOCKMODE    wanted = tupleLockExtraInfo[lockmode].hwlock;
                               7113                 :                : 
 2851 alvherre@alvh.no-ip.     7114   [ +  -  +  +  :             94 :     if (HEAP_LOCKED_UPGRADED(infomask))
                                              -  + ]
 2851 alvherre@alvh.no-ip.     7115                 :UBC           0 :         return false;
                               7116                 :                : 
 2851 alvherre@alvh.no-ip.     7117                 :CBC          94 :     nmembers = GetMultiXactIdMembers(multi, &members, false,
 3397                          7118   [ +  +  -  + ]:             94 :                                      HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               7119         [ +  - ]:             94 :     if (nmembers >= 0)
                               7120                 :                :     {
                               7121                 :                :         int         i;
                               7122                 :                : 
                               7123         [ +  + ]:            295 :         for (i = 0; i < nmembers; i++)
                               7124                 :                :         {
                               7125                 :                :             TransactionId memxid;
                               7126                 :                :             LOCKMODE    memlockmode;
                               7127                 :                : 
 1762                          7128   [ +  +  +  +  :            207 :             if (result && (current_is_member == NULL || *current_is_member))
                                              +  - ]
                               7129                 :                :                 break;
                               7130                 :                : 
                               7131                 :            201 :             memlockmode = LOCKMODE_from_mxstatus(members[i].status);
                               7132                 :                : 
                               7133                 :                :             /* ignore members from current xact (but track their presence) */
 1764                          7134                 :            201 :             memxid = members[i].xid;
                               7135         [ +  + ]:            201 :             if (TransactionIdIsCurrentTransactionId(memxid))
                               7136                 :                :             {
 1762                          7137         [ +  + ]:             91 :                 if (current_is_member != NULL)
                               7138                 :             78 :                     *current_is_member = true;
                               7139                 :             91 :                 continue;
                               7140                 :                :             }
                               7141         [ +  + ]:            110 :             else if (result)
                               7142                 :              8 :                 continue;
                               7143                 :                : 
                               7144                 :                :             /* ignore members that don't conflict with the lock we want */
                               7145         [ +  + ]:            102 :             if (!DoLockModesConflict(memlockmode, wanted))
 1764                          7146                 :             67 :                 continue;
                               7147                 :                : 
 3397                          7148         [ +  + ]:             35 :             if (ISUPDATE_from_mxstatus(members[i].status))
                               7149                 :                :             {
                               7150                 :                :                 /* ignore aborted updaters */
                               7151         [ +  + ]:             17 :                 if (TransactionIdDidAbort(memxid))
                               7152                 :              1 :                     continue;
                               7153                 :                :             }
                               7154                 :                :             else
                               7155                 :                :             {
                               7156                 :                :                 /* ignore lockers-only that are no longer in progress */
                               7157         [ +  + ]:             18 :                 if (!TransactionIdIsInProgress(memxid))
                               7158                 :              5 :                     continue;
                               7159                 :                :             }
                               7160                 :                : 
                               7161                 :                :             /*
                               7162                 :                :              * Whatever remains are either live lockers that conflict with our
                               7163                 :                :              * wanted lock, and updaters that are not aborted.  Those conflict
                               7164                 :                :              * with what we want.  Set up to return true, but keep going to
                               7165                 :                :              * look for the current transaction among the multixact members,
                               7166                 :                :              * if needed.
                               7167                 :                :              */
                               7168                 :             29 :             result = true;
                               7169                 :                :         }
                               7170                 :             94 :         pfree(members);
                               7171                 :                :     }
                               7172                 :                : 
                               7173                 :             94 :     return result;
                               7174                 :                : }
                               7175                 :                : 
                               7176                 :                : /*
                               7177                 :                :  * Do_MultiXactIdWait
                               7178                 :                :  *      Actual implementation for the two functions below.
                               7179                 :                :  *
                               7180                 :                :  * 'multi', 'status' and 'infomask' indicate what to sleep on (the status is
                               7181                 :                :  * needed to ensure we only sleep on conflicting members, and the infomask is
                               7182                 :                :  * used to optimize multixact access in case it's a lock-only multi); 'nowait'
                               7183                 :                :  * indicates whether to use conditional lock acquisition, to allow callers to
                               7184                 :                :  * fail if lock is unavailable.  'rel', 'ctid' and 'oper' are used to set up
                               7185                 :                :  * context information for error messages.  'remaining', if not NULL, receives
                               7186                 :                :  * the number of members that are still running, including any (non-aborted)
                               7187                 :                :  * subtransactions of our own transaction.
                               7188                 :                :  *
                               7189                 :                :  * We do this by sleeping on each member using XactLockTableWait.  Any
                               7190                 :                :  * members that belong to the current backend are *not* waited for, however;
                               7191                 :                :  * this would not merely be useless but would lead to Assert failure inside
                               7192                 :                :  * XactLockTableWait.  By the time this returns, it is certain that all
                               7193                 :                :  * transactions *of other backends* that were members of the MultiXactId
                               7194                 :                :  * that conflict with the requested status are dead (and no new ones can have
                               7195                 :                :  * been added, since it is not legal to add members to an existing
                               7196                 :                :  * MultiXactId).
                               7197                 :                :  *
                               7198                 :                :  * But by the time we finish sleeping, someone else may have changed the Xmax
                               7199                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               7200                 :                :  *
                               7201                 :                :  * Note that in case we return false, the number of remaining members is
                               7202                 :                :  * not to be trusted.
                               7203                 :                :  */
                               7204                 :                : static bool
 4099                          7205                 :             56 : Do_MultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                               7206                 :                :                    uint16 infomask, bool nowait,
                               7207                 :                :                    Relation rel, ItemPointer ctid, XLTW_Oper oper,
                               7208                 :                :                    int *remaining)
                               7209                 :                : {
                               7210                 :             56 :     bool        result = true;
                               7211                 :                :     MultiXactMember *members;
                               7212                 :                :     int         nmembers;
                               7213                 :             56 :     int         remain = 0;
                               7214                 :                : 
                               7215                 :                :     /* for pre-pg_upgrade tuples, no need to sleep at all */
 2851                          7216   [ +  -  +  +  :             56 :     nmembers = HEAP_LOCKED_UPGRADED(infomask) ? -1 :
                                              +  - ]
                               7217                 :             56 :         GetMultiXactIdMembers(multi, &members, false,
                               7218   [ +  +  -  + ]:             56 :                               HEAP_XMAX_IS_LOCKED_ONLY(infomask));
                               7219                 :                : 
 4099                          7220         [ +  - ]:             56 :     if (nmembers >= 0)
                               7221                 :                :     {
                               7222                 :                :         int         i;
                               7223                 :                : 
                               7224         [ +  + ]:            181 :         for (i = 0; i < nmembers; i++)
                               7225                 :                :         {
                               7226                 :            129 :             TransactionId memxid = members[i].xid;
                               7227                 :            129 :             MultiXactStatus memstatus = members[i].status;
                               7228                 :                : 
                               7229         [ +  + ]:            129 :             if (TransactionIdIsCurrentTransactionId(memxid))
                               7230                 :                :             {
                               7231                 :             24 :                 remain++;
                               7232                 :             24 :                 continue;
                               7233                 :                :             }
                               7234                 :                : 
                               7235         [ +  + ]:            105 :             if (!DoLockModesConflict(LOCKMODE_from_mxstatus(memstatus),
                               7236                 :            105 :                                      LOCKMODE_from_mxstatus(status)))
                               7237                 :                :             {
                               7238   [ +  +  +  - ]:             20 :                 if (remaining && TransactionIdIsInProgress(memxid))
                               7239                 :              6 :                     remain++;
                               7240                 :             20 :                 continue;
                               7241                 :                :             }
                               7242                 :                : 
                               7243                 :                :             /*
                               7244                 :                :              * This member conflicts with our multi, so we have to sleep (or
                               7245                 :                :              * return failure, if asked to avoid waiting.)
                               7246                 :                :              *
                               7247                 :                :              * Note that we don't set up an error context callback ourselves,
                               7248                 :                :              * but instead we pass the info down to XactLockTableWait.  This
                               7249                 :                :              * might seem a bit wasteful because the context is set up and
                               7250                 :                :              * tore down for each member of the multixact, but in reality it
                               7251                 :                :              * should be barely noticeable, and it avoids duplicate code.
                               7252                 :                :              */
                               7253         [ +  + ]:             85 :             if (nowait)
                               7254                 :                :             {
                               7255                 :              4 :                 result = ConditionalXactLockTableWait(memxid);
                               7256         [ +  - ]:              4 :                 if (!result)
                               7257                 :              4 :                     break;
                               7258                 :                :             }
                               7259                 :                :             else
 3679                          7260                 :             81 :                 XactLockTableWait(memxid, rel, ctid, oper);
                               7261                 :                :         }
                               7262                 :                : 
 4099                          7263                 :             56 :         pfree(members);
                               7264                 :                :     }
                               7265                 :                : 
                               7266         [ +  + ]:             56 :     if (remaining)
                               7267                 :              8 :         *remaining = remain;
                               7268                 :                : 
                               7269                 :             56 :     return result;
                               7270                 :                : }
                               7271                 :                : 
                               7272                 :                : /*
                               7273                 :                :  * MultiXactIdWait
                               7274                 :                :  *      Sleep on a MultiXactId.
                               7275                 :                :  *
                               7276                 :                :  * By the time we finish sleeping, someone else may have changed the Xmax
                               7277                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               7278                 :                :  *
                               7279                 :                :  * We return (in *remaining, if not NULL) the number of members that are still
                               7280                 :                :  * running, including any (non-aborted) subtransactions of our own transaction.
                               7281                 :                :  */
                               7282                 :                : static void
 3679                          7283                 :             52 : MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask,
                               7284                 :                :                 Relation rel, ItemPointer ctid, XLTW_Oper oper,
                               7285                 :                :                 int *remaining)
                               7286                 :                : {
                               7287                 :             52 :     (void) Do_MultiXactIdWait(multi, status, infomask, false,
                               7288                 :                :                               rel, ctid, oper, remaining);
 4099                          7289                 :             52 : }
                               7290                 :                : 
                               7291                 :                : /*
                               7292                 :                :  * ConditionalMultiXactIdWait
                               7293                 :                :  *      As above, but only lock if we can get the lock without blocking.
                               7294                 :                :  *
                               7295                 :                :  * By the time we finish sleeping, someone else may have changed the Xmax
                               7296                 :                :  * of the containing tuple, so the caller needs to iterate on us somehow.
                               7297                 :                :  *
                               7298                 :                :  * If the multixact is now all gone, return true.  Returns false if some
                               7299                 :                :  * transactions might still be running.
                               7300                 :                :  *
                               7301                 :                :  * We return (in *remaining, if not NULL) the number of members that are still
                               7302                 :                :  * running, including any (non-aborted) subtransactions of our own transaction.
                               7303                 :                :  */
                               7304                 :                : static bool
                               7305                 :              4 : ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status,
                               7306                 :                :                            uint16 infomask, Relation rel, int *remaining)
                               7307                 :                : {
 3679                          7308                 :              4 :     return Do_MultiXactIdWait(multi, status, infomask, true,
                               7309                 :                :                               rel, NULL, XLTW_None, remaining);
                               7310                 :                : }
                               7311                 :                : 
                               7312                 :                : /*
                               7313                 :                :  * heap_tuple_needs_eventual_freeze
                               7314                 :                :  *
                               7315                 :                :  * Check to see whether any of the XID fields of a tuple (xmin, xmax, xvac)
                               7316                 :                :  * will eventually require freezing (if tuple isn't removed by pruning first).
                               7317                 :                :  */
                               7318                 :                : bool
 2966 rhaas@postgresql.org     7319                 :        8329478 : heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
                               7320                 :                : {
                               7321                 :                :     TransactionId xid;
                               7322                 :                : 
                               7323                 :                :     /*
                               7324                 :                :      * If xmin is a normal transaction ID, this tuple is definitely not
                               7325                 :                :      * frozen.
                               7326                 :                :      */
                               7327         [ +  + ]:        8329478 :     xid = HeapTupleHeaderGetXmin(tuple);
                               7328         [ +  + ]:        8329478 :     if (TransactionIdIsNormal(xid))
                               7329                 :          13340 :         return true;
                               7330                 :                : 
                               7331                 :                :     /*
                               7332                 :                :      * If xmax is a valid xact or multixact, this tuple is also not frozen.
                               7333                 :                :      */
                               7334         [ +  + ]:        8316138 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
                               7335                 :                :     {
                               7336                 :                :         MultiXactId multi;
                               7337                 :                : 
                               7338                 :              2 :         multi = HeapTupleHeaderGetRawXmax(tuple);
                               7339         [ +  - ]:              2 :         if (MultiXactIdIsValid(multi))
                               7340                 :              2 :             return true;
                               7341                 :                :     }
                               7342                 :                :     else
                               7343                 :                :     {
                               7344                 :        8316136 :         xid = HeapTupleHeaderGetRawXmax(tuple);
                               7345         [ +  + ]:        8316136 :         if (TransactionIdIsNormal(xid))
                               7346                 :              8 :             return true;
                               7347                 :                :     }
                               7348                 :                : 
                               7349         [ -  + ]:        8316128 :     if (tuple->t_infomask & HEAP_MOVED)
                               7350                 :                :     {
 2966 rhaas@postgresql.org     7351         [ #  # ]:UBC           0 :         xid = HeapTupleHeaderGetXvac(tuple);
                               7352         [ #  # ]:              0 :         if (TransactionIdIsNormal(xid))
                               7353                 :              0 :             return true;
                               7354                 :                :     }
                               7355                 :                : 
 2966 rhaas@postgresql.org     7356                 :CBC     8316128 :     return false;
                               7357                 :                : }
                               7358                 :                : 
                               7359                 :                : /*
                               7360                 :                :  * heap_tuple_should_freeze
                               7361                 :                :  *
                               7362                 :                :  * Return value indicates if heap_prepare_freeze_tuple sibling function would
                               7363                 :                :  * (or should) force freezing of the heap page that contains caller's tuple.
                               7364                 :                :  * Tuple header XIDs/MXIDs < FreezeLimit/MultiXactCutoff trigger freezing.
                               7365                 :                :  * This includes (xmin, xmax, xvac) fields, as well as MultiXact member XIDs.
                               7366                 :                :  *
                               7367                 :                :  * The *NoFreezePageRelfrozenXid and *NoFreezePageRelminMxid input/output
                               7368                 :                :  * arguments help VACUUM track the oldest extant XID/MXID remaining in rel.
                               7369                 :                :  * Our working assumption is that caller won't decide to freeze this tuple.
                               7370                 :                :  * It's up to caller to only ratchet back its own top-level trackers after the
                               7371                 :                :  * point that it fully commits to not freezing the tuple/page in question.
                               7372                 :                :  */
                               7373                 :                : bool
  473 pg@bowt.ie               7374                 :        5484392 : heap_tuple_should_freeze(HeapTupleHeader tuple,
                               7375                 :                :                          const struct VacuumCutoffs *cutoffs,
                               7376                 :                :                          TransactionId *NoFreezePageRelfrozenXid,
                               7377                 :                :                          MultiXactId *NoFreezePageRelminMxid)
                               7378                 :                : {
                               7379                 :                :     TransactionId xid;
                               7380                 :                :     MultiXactId multi;
  479                          7381                 :        5484392 :     bool        freeze = false;
                               7382                 :                : 
                               7383                 :                :     /* First deal with xmin */
 4542 rhaas@postgresql.org     7384         [ +  + ]:        5484392 :     xid = HeapTupleHeaderGetXmin(tuple);
  742 pg@bowt.ie               7385         [ +  + ]:        5484392 :     if (TransactionIdIsNormal(xid))
                               7386                 :                :     {
  479                          7387         [ -  + ]:        1892490 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
  473                          7388         [ +  + ]:        1892490 :         if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               7389                 :          15257 :             *NoFreezePageRelfrozenXid = xid;
  479                          7390         [ +  + ]:        1892490 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               7391                 :          13788 :             freeze = true;
                               7392                 :                :     }
                               7393                 :                : 
                               7394                 :                :     /* Now deal with xmax */
  742                          7395                 :        5484392 :     xid = InvalidTransactionId;
                               7396                 :        5484392 :     multi = InvalidMultiXactId;
                               7397         [ +  + ]:        5484392 :     if (tuple->t_infomask & HEAP_XMAX_IS_MULTI)
 3790 alvherre@alvh.no-ip.     7398                 :              2 :         multi = HeapTupleHeaderGetRawXmax(tuple);
                               7399                 :                :     else
  742 pg@bowt.ie               7400                 :        5484390 :         xid = HeapTupleHeaderGetRawXmax(tuple);
                               7401                 :                : 
                               7402         [ +  + ]:        5484392 :     if (TransactionIdIsNormal(xid))
                               7403                 :                :     {
  479                          7404         [ -  + ]:        3841035 :         Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
                               7405                 :                :         /* xmax is a non-permanent XID */
  473                          7406         [ +  + ]:        3841035 :         if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               7407                 :              3 :             *NoFreezePageRelfrozenXid = xid;
  479                          7408         [ +  + ]:        3841035 :         if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
                               7409                 :              4 :             freeze = true;
                               7410                 :                :     }
  742                          7411         [ +  + ]:        1643357 :     else if (!MultiXactIdIsValid(multi))
                               7412                 :                :     {
                               7413                 :                :         /* xmax is a permanent XID or invalid MultiXactId/XID */
                               7414                 :                :     }
                               7415   [ +  -  +  +  :              2 :     else if (HEAP_LOCKED_UPGRADED(tuple->t_infomask))
                                              -  + ]
                               7416                 :                :     {
                               7417                 :                :         /* xmax is a pg_upgrade'd MultiXact, which can't have updater XID */
  473 pg@bowt.ie               7418         [ #  # ]:UBC           0 :         if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
                               7419                 :              0 :             *NoFreezePageRelminMxid = multi;
                               7420                 :                :         /* heap_prepare_freeze_tuple always freezes pg_upgrade'd xmax */
  479                          7421                 :              0 :         freeze = true;
                               7422                 :                :     }
                               7423                 :                :     else
                               7424                 :                :     {
                               7425                 :                :         /* xmax is a MultiXactId that may have an updater XID */
                               7426                 :                :         MultiXactMember *members;
                               7427                 :                :         int         nmembers;
                               7428                 :                : 
  479 pg@bowt.ie               7429         [ -  + ]:CBC           2 :         Assert(MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, multi));
  473                          7430         [ +  - ]:              2 :         if (MultiXactIdPrecedes(multi, *NoFreezePageRelminMxid))
                               7431                 :              2 :             *NoFreezePageRelminMxid = multi;
  479                          7432         [ +  - ]:              2 :         if (MultiXactIdPrecedes(multi, cutoffs->MultiXactCutoff))
                               7433                 :              2 :             freeze = true;
                               7434                 :                : 
                               7435                 :                :         /* need to check whether any member of the mxact is old */
  742                          7436                 :              2 :         nmembers = GetMultiXactIdMembers(multi, &members, false,
                               7437   [ +  +  -  + ]:              2 :                                          HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask));
                               7438                 :                : 
                               7439         [ +  + ]:              5 :         for (int i = 0; i < nmembers; i++)
                               7440                 :                :         {
                               7441                 :              3 :             xid = members[i].xid;
  479                          7442         [ -  + ]:              3 :             Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
  473                          7443         [ -  + ]:              3 :             if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
  473 pg@bowt.ie               7444                 :UBC           0 :                 *NoFreezePageRelfrozenXid = xid;
  479 pg@bowt.ie               7445         [ -  + ]:CBC           3 :             if (TransactionIdPrecedes(xid, cutoffs->FreezeLimit))
  479 pg@bowt.ie               7446                 :UBC           0 :                 freeze = true;
                               7447                 :                :         }
  742 pg@bowt.ie               7448         [ +  + ]:CBC           2 :         if (nmembers > 0)
                               7449                 :              1 :             pfree(members);
                               7450                 :                :     }
                               7451                 :                : 
 4542 rhaas@postgresql.org     7452         [ -  + ]:        5484392 :     if (tuple->t_infomask & HEAP_MOVED)
                               7453                 :                :     {
 4542 rhaas@postgresql.org     7454         [ #  # ]:UBC           0 :         xid = HeapTupleHeaderGetXvac(tuple);
  742 pg@bowt.ie               7455         [ #  # ]:              0 :         if (TransactionIdIsNormal(xid))
                               7456                 :                :         {
  479                          7457         [ #  # ]:              0 :             Assert(TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, xid));
  473                          7458         [ #  # ]:              0 :             if (TransactionIdPrecedes(xid, *NoFreezePageRelfrozenXid))
                               7459                 :              0 :                 *NoFreezePageRelfrozenXid = xid;
                               7460                 :                :             /* heap_prepare_freeze_tuple forces xvac freezing */
  479                          7461                 :              0 :             freeze = true;
                               7462                 :                :         }
                               7463                 :                :     }
                               7464                 :                : 
  479 pg@bowt.ie               7465                 :CBC     5484392 :     return freeze;
                               7466                 :                : }
                               7467                 :                : 
                               7468                 :                : /*
                               7469                 :                :  * Maintain snapshotConflictHorizon for caller by ratcheting forward its value
                               7470                 :                :  * using any committed XIDs contained in 'tuple', an obsolescent heap tuple
                               7471                 :                :  * that caller is in the process of physically removing, e.g. via HOT pruning
                               7472                 :                :  * or index deletion.
                               7473                 :                :  *
                               7474                 :                :  * Caller must initialize its value to InvalidTransactionId, which is
                               7475                 :                :  * generally interpreted as "definitely no need for a recovery conflict".
                               7476                 :                :  * Final value must reflect all heap tuples that caller will physically remove
                               7477                 :                :  * (or remove TID references to) via its ongoing pruning/deletion operation.
                               7478                 :                :  * ResolveRecoveryConflictWithSnapshot() is passed the final value (taken from
                               7479                 :                :  * caller's WAL record) by REDO routine when it replays caller's operation.
                               7480                 :                :  */
                               7481                 :                : void
  514                          7482                 :        1515750 : HeapTupleHeaderAdvanceConflictHorizon(HeapTupleHeader tuple,
                               7483                 :                :                                       TransactionId *snapshotConflictHorizon)
                               7484                 :                : {
 5230 simon@2ndQuadrant.co     7485         [ +  + ]:        1515750 :     TransactionId xmin = HeapTupleHeaderGetXmin(tuple);
 4099 alvherre@alvh.no-ip.     7486   [ +  +  +  +  :        1515750 :     TransactionId xmax = HeapTupleHeaderGetUpdateXid(tuple);
                                              +  - ]
 5230 simon@2ndQuadrant.co     7487         [ -  + ]:        1515750 :     TransactionId xvac = HeapTupleHeaderGetXvac(tuple);
                               7488                 :                : 
 5179 tgl@sss.pgh.pa.us        7489         [ -  + ]:        1515750 :     if (tuple->t_infomask & HEAP_MOVED)
                               7490                 :                :     {
  514 pg@bowt.ie               7491         [ #  # ]:UBC           0 :         if (TransactionIdPrecedes(*snapshotConflictHorizon, xvac))
                               7492                 :              0 :             *snapshotConflictHorizon = xvac;
                               7493                 :                :     }
                               7494                 :                : 
                               7495                 :                :     /*
                               7496                 :                :      * Ignore tuples inserted by an aborted transaction or if the tuple was
                               7497                 :                :      * updated/deleted by the inserting transaction.
                               7498                 :                :      *
                               7499                 :                :      * Look for a committed hint bit, or if no xmin bit is set, check clog.
                               7500                 :                :      */
 3766 rhaas@postgresql.org     7501         [ +  + ]:CBC     1515750 :     if (HeapTupleHeaderXminCommitted(tuple) ||
                               7502   [ +  +  +  - ]:          89351 :         (!HeapTupleHeaderXminInvalid(tuple) && TransactionIdDidCommit(xmin)))
                               7503                 :                :     {
 4875 simon@2ndQuadrant.co     7504   [ +  +  +  + ]:        2730052 :         if (xmax != xmin &&
  514 pg@bowt.ie               7505                 :        1283827 :             TransactionIdFollows(xmax, *snapshotConflictHorizon))
                               7506                 :          86824 :             *snapshotConflictHorizon = xmax;
                               7507                 :                :     }
 5230 simon@2ndQuadrant.co     7508                 :        1515750 : }
                               7509                 :                : 
                               7510                 :                : #ifdef USE_PREFETCH
                               7511                 :                : /*
                               7512                 :                :  * Helper function for heap_index_delete_tuples.  Issues prefetch requests for
                               7513                 :                :  * prefetch_count buffers.  The prefetch_state keeps track of all the buffers
                               7514                 :                :  * we can prefetch, and which have already been prefetched; each call to this
                               7515                 :                :  * function picks up where the previous call left off.
                               7516                 :                :  *
                               7517                 :                :  * Note: we expect the deltids array to be sorted in an order that groups TIDs
                               7518                 :                :  * by heap block, with all TIDs for each block appearing together in exactly
                               7519                 :                :  * one group.
                               7520                 :                :  */
                               7521                 :                : static void
 1187 pg@bowt.ie               7522                 :          16517 : index_delete_prefetch_buffer(Relation rel,
                               7523                 :                :                              IndexDeletePrefetchState *prefetch_state,
                               7524                 :                :                              int prefetch_count)
                               7525                 :                : {
 1846 andres@anarazel.de       7526                 :          16517 :     BlockNumber cur_hblkno = prefetch_state->cur_hblkno;
                               7527                 :          16517 :     int         count = 0;
                               7528                 :                :     int         i;
 1187 pg@bowt.ie               7529                 :          16517 :     int         ndeltids = prefetch_state->ndeltids;
                               7530                 :          16517 :     TM_IndexDelete *deltids = prefetch_state->deltids;
                               7531                 :                : 
 1846 andres@anarazel.de       7532                 :          16517 :     for (i = prefetch_state->next_item;
 1187 pg@bowt.ie               7533   [ +  +  +  + ]:         598265 :          i < ndeltids && count < prefetch_count;
 1846 andres@anarazel.de       7534                 :         581748 :          i++)
                               7535                 :                :     {
 1187 pg@bowt.ie               7536                 :         581748 :         ItemPointer htid = &deltids[i].tid;
                               7537                 :                : 
 1846 andres@anarazel.de       7538   [ +  +  +  + ]:        1158511 :         if (cur_hblkno == InvalidBlockNumber ||
                               7539                 :         576763 :             ItemPointerGetBlockNumber(htid) != cur_hblkno)
                               7540                 :                :         {
                               7541                 :          14973 :             cur_hblkno = ItemPointerGetBlockNumber(htid);
                               7542                 :          14973 :             PrefetchBuffer(rel, MAIN_FORKNUM, cur_hblkno);
                               7543                 :          14973 :             count++;
                               7544                 :                :         }
                               7545                 :                :     }
                               7546                 :                : 
                               7547                 :                :     /*
                               7548                 :                :      * Save the prefetch position so that next time we can continue from that
                               7549                 :                :      * position.
                               7550                 :                :      */
                               7551                 :          16517 :     prefetch_state->next_item = i;
                               7552                 :          16517 :     prefetch_state->cur_hblkno = cur_hblkno;
                               7553                 :          16517 : }
                               7554                 :                : #endif
                               7555                 :                : 
                               7556                 :                : /*
                               7557                 :                :  * Helper function for heap_index_delete_tuples.  Checks for index corruption
                               7558                 :                :  * involving an invalid TID in index AM caller's index page.
                               7559                 :                :  *
                               7560                 :                :  * This is an ideal place for these checks.  The index AM must hold a buffer
                               7561                 :                :  * lock on the index page containing the TIDs we examine here, so we don't
                               7562                 :                :  * have to worry about concurrent VACUUMs at all.  We can be sure that the
                               7563                 :                :  * index is corrupt when htid points directly to an LP_UNUSED item or
                               7564                 :                :  * heap-only tuple, which is not the case during standard index scans.
                               7565                 :                :  */
                               7566                 :                : static inline void
  892 pg@bowt.ie               7567                 :         485124 : index_delete_check_htid(TM_IndexDeleteOp *delstate,
                               7568                 :                :                         Page page, OffsetNumber maxoff,
                               7569                 :                :                         ItemPointer htid, TM_IndexStatus *istatus)
                               7570                 :                : {
                               7571                 :         485124 :     OffsetNumber indexpagehoffnum = ItemPointerGetOffsetNumber(htid);
                               7572                 :                :     ItemId      iid;
                               7573                 :                : 
                               7574   [ +  -  +  -  :         485124 :     Assert(OffsetNumberIsValid(istatus->idxoffnum));
                                              -  + ]
                               7575                 :                : 
                               7576         [ -  + ]:         485124 :     if (unlikely(indexpagehoffnum > maxoff))
  892 pg@bowt.ie               7577         [ #  # ]:UBC           0 :         ereport(ERROR,
                               7578                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               7579                 :                :                  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\"",
                               7580                 :                :                                  ItemPointerGetBlockNumber(htid),
                               7581                 :                :                                  indexpagehoffnum,
                               7582                 :                :                                  istatus->idxoffnum, delstate->iblknum,
                               7583                 :                :                                  RelationGetRelationName(delstate->irel))));
                               7584                 :                : 
  892 pg@bowt.ie               7585                 :CBC      485124 :     iid = PageGetItemId(page, indexpagehoffnum);
                               7586         [ -  + ]:         485124 :     if (unlikely(!ItemIdIsUsed(iid)))
  892 pg@bowt.ie               7587         [ #  # ]:UBC           0 :         ereport(ERROR,
                               7588                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               7589                 :                :                  errmsg_internal("heap tid from index tuple (%u,%u) points to unused heap page item at offset %u of block %u in index \"%s\"",
                               7590                 :                :                                  ItemPointerGetBlockNumber(htid),
                               7591                 :                :                                  indexpagehoffnum,
                               7592                 :                :                                  istatus->idxoffnum, delstate->iblknum,
                               7593                 :                :                                  RelationGetRelationName(delstate->irel))));
                               7594                 :                : 
  892 pg@bowt.ie               7595         [ +  + ]:CBC      485124 :     if (ItemIdHasStorage(iid))
                               7596                 :                :     {
                               7597                 :                :         HeapTupleHeader htup;
                               7598                 :                : 
                               7599         [ -  + ]:         282856 :         Assert(ItemIdIsNormal(iid));
                               7600                 :         282856 :         htup = (HeapTupleHeader) PageGetItem(page, iid);
                               7601                 :                : 
                               7602         [ -  + ]:         282856 :         if (unlikely(HeapTupleHeaderIsHeapOnly(htup)))
  892 pg@bowt.ie               7603         [ #  # ]:UBC           0 :             ereport(ERROR,
                               7604                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               7605                 :                :                      errmsg_internal("heap tid from index tuple (%u,%u) points to heap-only tuple at offset %u of block %u in index \"%s\"",
                               7606                 :                :                                      ItemPointerGetBlockNumber(htid),
                               7607                 :                :                                      indexpagehoffnum,
                               7608                 :                :                                      istatus->idxoffnum, delstate->iblknum,
                               7609                 :                :                                      RelationGetRelationName(delstate->irel))));
                               7610                 :                :     }
  892 pg@bowt.ie               7611                 :CBC      485124 : }
                               7612                 :                : 
                               7613                 :                : /*
                               7614                 :                :  * heapam implementation of tableam's index_delete_tuples interface.
                               7615                 :                :  *
                               7616                 :                :  * This helper function is called by index AMs during index tuple deletion.
                               7617                 :                :  * See tableam header comments for an explanation of the interface implemented
                               7618                 :                :  * here and a general theory of operation.  Note that each call here is either
                               7619                 :                :  * a simple index deletion call, or a bottom-up index deletion call.
                               7620                 :                :  *
                               7621                 :                :  * It's possible for this to generate a fair amount of I/O, since we may be
                               7622                 :                :  * deleting hundreds of tuples from a single index block.  To amortize that
                               7623                 :                :  * cost to some degree, this uses prefetching and combines repeat accesses to
                               7624                 :                :  * the same heap block.
                               7625                 :                :  */
                               7626                 :                : TransactionId
 1187                          7627                 :           4985 : heap_index_delete_tuples(Relation rel, TM_IndexDeleteOp *delstate)
                               7628                 :                : {
                               7629                 :                :     /* Initial assumption is that earlier pruning took care of conflict */
  514                          7630                 :           4985 :     TransactionId snapshotConflictHorizon = InvalidTransactionId;
 1201                          7631                 :           4985 :     BlockNumber blkno = InvalidBlockNumber;
 1846 andres@anarazel.de       7632                 :           4985 :     Buffer      buf = InvalidBuffer;
 1201 pg@bowt.ie               7633                 :           4985 :     Page        page = NULL;
                               7634                 :           4985 :     OffsetNumber maxoff = InvalidOffsetNumber;
                               7635                 :                :     TransactionId priorXmax;
                               7636                 :                : #ifdef USE_PREFETCH
                               7637                 :                :     IndexDeletePrefetchState prefetch_state;
                               7638                 :                :     int         prefetch_distance;
                               7639                 :                : #endif
                               7640                 :                :     SnapshotData SnapshotNonVacuumable;
 1187                          7641                 :           4985 :     int         finalndeltids = 0,
                               7642                 :           4985 :                 nblocksaccessed = 0;
                               7643                 :                : 
                               7644                 :                :     /* State that's only used in bottom-up index deletion case */
                               7645                 :           4985 :     int         nblocksfavorable = 0;
                               7646                 :           4985 :     int         curtargetfreespace = delstate->bottomupfreespace,
                               7647                 :           4985 :                 lastfreespace = 0,
                               7648                 :           4985 :                 actualfreespace = 0;
                               7649                 :           4985 :     bool        bottomup_final_block = false;
                               7650                 :                : 
                               7651                 :           4985 :     InitNonVacuumableSnapshot(SnapshotNonVacuumable, GlobalVisTestFor(rel));
                               7652                 :                : 
                               7653                 :                :     /* Sort caller's deltids array by TID for further processing */
                               7654                 :           4985 :     index_delete_sort(delstate);
                               7655                 :                : 
                               7656                 :                :     /*
                               7657                 :                :      * Bottom-up case: resort deltids array in an order attuned to where the
                               7658                 :                :      * greatest number of promising TIDs are to be found, and determine how
                               7659                 :                :      * many blocks from the start of sorted array should be considered
                               7660                 :                :      * favorable.  This will also shrink the deltids array in order to
                               7661                 :                :      * eliminate completely unfavorable blocks up front.
                               7662                 :                :      */
                               7663         [ +  + ]:           4985 :     if (delstate->bottomup)
                               7664                 :           1729 :         nblocksfavorable = bottomup_sort_and_shrink(delstate);
                               7665                 :                : 
                               7666                 :                : #ifdef USE_PREFETCH
                               7667                 :                :     /* Initialize prefetch state. */
 1846 andres@anarazel.de       7668                 :           4985 :     prefetch_state.cur_hblkno = InvalidBlockNumber;
                               7669                 :           4985 :     prefetch_state.next_item = 0;
 1187 pg@bowt.ie               7670                 :           4985 :     prefetch_state.ndeltids = delstate->ndeltids;
                               7671                 :           4985 :     prefetch_state.deltids = delstate->deltids;
                               7672                 :                : 
                               7673                 :                :     /*
                               7674                 :                :      * Determine the prefetch distance that we will attempt to maintain.
                               7675                 :                :      *
                               7676                 :                :      * Since the caller holds a buffer lock somewhere in rel, we'd better make
                               7677                 :                :      * sure that isn't a catalog relation before we call code that does
                               7678                 :                :      * syscache lookups, to avoid risk of deadlock.
                               7679                 :                :      */
 1839 tmunro@postgresql.or     7680         [ +  + ]:           4985 :     if (IsCatalogRelation(rel))
 1490                          7681                 :           3346 :         prefetch_distance = maintenance_io_concurrency;
                               7682                 :                :     else
                               7683                 :                :         prefetch_distance =
                               7684                 :           1639 :             get_tablespace_maintenance_io_concurrency(rel->rd_rel->reltablespace);
                               7685                 :                : 
                               7686                 :                :     /* Cap initial prefetch distance for bottom-up deletion caller */
 1187 pg@bowt.ie               7687         [ +  + ]:           4985 :     if (delstate->bottomup)
                               7688                 :                :     {
                               7689         [ -  + ]:           1729 :         Assert(nblocksfavorable >= 1);
                               7690         [ -  + ]:           1729 :         Assert(nblocksfavorable <= BOTTOMUP_MAX_NBLOCKS);
                               7691                 :           1729 :         prefetch_distance = Min(prefetch_distance, nblocksfavorable);
                               7692                 :                :     }
                               7693                 :                : 
                               7694                 :                :     /* Start prefetching. */
                               7695                 :           4985 :     index_delete_prefetch_buffer(rel, &prefetch_state, prefetch_distance);
                               7696                 :                : #endif
                               7697                 :                : 
                               7698                 :                :     /* Iterate over deltids, determine which to delete, check their horizon */
                               7699         [ -  + ]:           4985 :     Assert(delstate->ndeltids > 0);
                               7700         [ +  + ]:         490109 :     for (int i = 0; i < delstate->ndeltids; i++)
                               7701                 :                :     {
                               7702                 :         486853 :         TM_IndexDelete *ideltid = &delstate->deltids[i];
                               7703                 :         486853 :         TM_IndexStatus *istatus = delstate->status + ideltid->id;
                               7704                 :         486853 :         ItemPointer htid = &ideltid->tid;
                               7705                 :                :         OffsetNumber offnum;
                               7706                 :                : 
                               7707                 :                :         /*
                               7708                 :                :          * Read buffer, and perform required extra steps each time a new block
                               7709                 :                :          * is encountered.  Avoid refetching if it's the same block as the one
                               7710                 :                :          * from the last htid.
                               7711                 :                :          */
 1201                          7712   [ +  +  +  + ]:         968721 :         if (blkno == InvalidBlockNumber ||
                               7713                 :         481868 :             ItemPointerGetBlockNumber(htid) != blkno)
                               7714                 :                :         {
                               7715                 :                :             /*
                               7716                 :                :              * Consider giving up early for bottom-up index deletion caller
                               7717                 :                :              * first. (Only prefetch next-next block afterwards, when it
                               7718                 :                :              * becomes clear that we're at least going to access the next
                               7719                 :                :              * block in line.)
                               7720                 :                :              *
                               7721                 :                :              * Sometimes the first block frees so much space for bottom-up
                               7722                 :                :              * caller that the deletion process can end without accessing any
                               7723                 :                :              * more blocks.  It is usually necessary to access 2 or 3 blocks
                               7724                 :                :              * per bottom-up deletion operation, though.
                               7725                 :                :              */
 1187                          7726         [ +  + ]:          13261 :             if (delstate->bottomup)
                               7727                 :                :             {
                               7728                 :                :                 /*
                               7729                 :                :                  * We often allow caller to delete a few additional items
                               7730                 :                :                  * whose entries we reached after the point that space target
                               7731                 :                :                  * from caller was satisfied.  The cost of accessing the page
                               7732                 :                :                  * was already paid at that point, so it made sense to finish
                               7733                 :                :                  * it off.  When that happened, we finalize everything here
                               7734                 :                :                  * (by finishing off the whole bottom-up deletion operation
                               7735                 :                :                  * without needlessly paying the cost of accessing any more
                               7736                 :                :                  * blocks).
                               7737                 :                :                  */
                               7738         [ +  + ]:           3705 :                 if (bottomup_final_block)
                               7739                 :            147 :                     break;
                               7740                 :                : 
                               7741                 :                :                 /*
                               7742                 :                :                  * Give up when we didn't enable our caller to free any
                               7743                 :                :                  * additional space as a result of processing the page that we
                               7744                 :                :                  * just finished up with.  This rule is the main way in which
                               7745                 :                :                  * we keep the cost of bottom-up deletion under control.
                               7746                 :                :                  */
                               7747   [ +  +  +  + ]:           3558 :                 if (nblocksaccessed >= 1 && actualfreespace == lastfreespace)
                               7748                 :           1582 :                     break;
                               7749                 :           1976 :                 lastfreespace = actualfreespace;    /* for next time */
                               7750                 :                : 
                               7751                 :                :                 /*
                               7752                 :                :                  * Deletion operation (which is bottom-up) will definitely
                               7753                 :                :                  * access the next block in line.  Prepare for that now.
                               7754                 :                :                  *
                               7755                 :                :                  * Decay target free space so that we don't hang on for too
                               7756                 :                :                  * long with a marginal case. (Space target is only truly
                               7757                 :                :                  * helpful when it allows us to recognize that we don't need
                               7758                 :                :                  * to access more than 1 or 2 blocks to satisfy caller due to
                               7759                 :                :                  * agreeable workload characteristics.)
                               7760                 :                :                  *
                               7761                 :                :                  * We are a bit more patient when we encounter contiguous
                               7762                 :                :                  * blocks, though: these are treated as favorable blocks.  The
                               7763                 :                :                  * decay process is only applied when the next block in line
                               7764                 :                :                  * is not a favorable/contiguous block.  This is not an
                               7765                 :                :                  * exception to the general rule; we still insist on finding
                               7766                 :                :                  * at least one deletable item per block accessed.  See
                               7767                 :                :                  * bottomup_nblocksfavorable() for full details of the theory
                               7768                 :                :                  * behind favorable blocks and heap block locality in general.
                               7769                 :                :                  *
                               7770                 :                :                  * Note: The first block in line is always treated as a
                               7771                 :                :                  * favorable block, so the earliest possible point that the
                               7772                 :                :                  * decay can be applied is just before we access the second
                               7773                 :                :                  * block in line.  The Assert() verifies this for us.
                               7774                 :                :                  */
                               7775   [ +  +  -  + ]:           1976 :                 Assert(nblocksaccessed > 0 || nblocksfavorable > 0);
                               7776         [ +  + ]:           1976 :                 if (nblocksfavorable > 0)
                               7777                 :           1874 :                     nblocksfavorable--;
                               7778                 :                :                 else
                               7779                 :            102 :                     curtargetfreespace /= 2;
                               7780                 :                :             }
                               7781                 :                : 
                               7782                 :                :             /* release old buffer */
                               7783         [ +  + ]:          11532 :             if (BufferIsValid(buf))
                               7784                 :           6547 :                 UnlockReleaseBuffer(buf);
                               7785                 :                : 
                               7786                 :          11532 :             blkno = ItemPointerGetBlockNumber(htid);
 1201                          7787                 :          11532 :             buf = ReadBuffer(rel, blkno);
 1187                          7788                 :          11532 :             nblocksaccessed++;
                               7789   [ +  +  -  + ]:          11532 :             Assert(!delstate->bottomup ||
                               7790                 :                :                    nblocksaccessed <= BOTTOMUP_MAX_NBLOCKS);
                               7791                 :                : 
                               7792                 :                : #ifdef USE_PREFETCH
                               7793                 :                : 
                               7794                 :                :             /*
                               7795                 :                :              * To maintain the prefetch distance, prefetch one more page for
                               7796                 :                :              * each page we read.
                               7797                 :                :              */
                               7798                 :          11532 :             index_delete_prefetch_buffer(rel, &prefetch_state, 1);
                               7799                 :                : #endif
                               7800                 :                : 
 1201                          7801                 :          11532 :             LockBuffer(buf, BUFFER_LOCK_SHARE);
                               7802                 :                : 
                               7803                 :          11532 :             page = BufferGetPage(buf);
                               7804                 :          11532 :             maxoff = PageGetMaxOffsetNumber(page);
                               7805                 :                :         }
                               7806                 :                : 
                               7807                 :                :         /*
                               7808                 :                :          * In passing, detect index corruption involving an index page with a
                               7809                 :                :          * TID that points to a location in the heap that couldn't possibly be
                               7810                 :                :          * correct.  We only do this with actual TIDs from caller's index page
                               7811                 :                :          * (not items reached by traversing through a HOT chain).
                               7812                 :                :          */
  892                          7813                 :         485124 :         index_delete_check_htid(delstate, page, maxoff, htid, istatus);
                               7814                 :                : 
 1187                          7815         [ +  + ]:         485124 :         if (istatus->knowndeletable)
                               7816   [ +  -  -  + ]:         126610 :             Assert(!delstate->bottomup && !istatus->promising);
                               7817                 :                :         else
                               7818                 :                :         {
                               7819                 :         358514 :             ItemPointerData tmp = *htid;
                               7820                 :                :             HeapTupleData heapTuple;
                               7821                 :                : 
                               7822                 :                :             /* Are any tuples from this HOT chain non-vacuumable? */
                               7823         [ +  + ]:         358514 :             if (heap_hot_search_buffer(&tmp, rel, buf, &SnapshotNonVacuumable,
                               7824                 :                :                                        &heapTuple, NULL, true))
                               7825                 :         215371 :                 continue;       /* can't delete entry */
                               7826                 :                : 
                               7827                 :                :             /* Caller will delete, since whole HOT chain is vacuumable */
                               7828                 :         143143 :             istatus->knowndeletable = true;
                               7829                 :                : 
                               7830                 :                :             /* Maintain index free space info for bottom-up deletion case */
                               7831         [ +  + ]:         143143 :             if (delstate->bottomup)
                               7832                 :                :             {
                               7833         [ -  + ]:           7552 :                 Assert(istatus->freespace > 0);
                               7834                 :           7552 :                 actualfreespace += istatus->freespace;
                               7835         [ +  + ]:           7552 :                 if (actualfreespace >= curtargetfreespace)
                               7836                 :           2358 :                     bottomup_final_block = true;
                               7837                 :                :             }
                               7838                 :                :         }
                               7839                 :                : 
                               7840                 :                :         /*
                               7841                 :                :          * Maintain snapshotConflictHorizon value for deletion operation as a
                               7842                 :                :          * whole by advancing current value using heap tuple headers.  This is
                               7843                 :                :          * loosely based on the logic for pruning a HOT chain.
                               7844                 :                :          */
 1201                          7845                 :         269753 :         offnum = ItemPointerGetOffsetNumber(htid);
                               7846                 :         269753 :         priorXmax = InvalidTransactionId;   /* cannot check first XMIN */
                               7847                 :                :         for (;;)
 1846 andres@anarazel.de       7848                 :          19355 :         {
                               7849                 :                :             ItemId      lp;
                               7850                 :                :             HeapTupleHeader htup;
                               7851                 :                : 
                               7852                 :                :             /* Sanity check (pure paranoia) */
  935 pg@bowt.ie               7853         [ -  + ]:         289108 :             if (offnum < FirstOffsetNumber)
  935 pg@bowt.ie               7854                 :UBC           0 :                 break;
                               7855                 :                : 
                               7856                 :                :             /*
                               7857                 :                :              * An offset past the end of page's line pointer array is possible
                               7858                 :                :              * when the array was truncated
                               7859                 :                :              */
  935 pg@bowt.ie               7860         [ -  + ]:CBC      289108 :             if (offnum > maxoff)
 1201 pg@bowt.ie               7861                 :UBC           0 :                 break;
                               7862                 :                : 
 1201 pg@bowt.ie               7863                 :CBC      289108 :             lp = PageGetItemId(page, offnum);
                               7864         [ +  + ]:         289108 :             if (ItemIdIsRedirected(lp))
                               7865                 :                :             {
                               7866                 :           8741 :                 offnum = ItemIdGetRedirect(lp);
                               7867                 :           8741 :                 continue;
                               7868                 :                :             }
                               7869                 :                : 
                               7870                 :                :             /*
                               7871                 :                :              * We'll often encounter LP_DEAD line pointers (especially with an
                               7872                 :                :              * entry marked knowndeletable by our caller up front).  No heap
                               7873                 :                :              * tuple headers get examined for an htid that leads us to an
                               7874                 :                :              * LP_DEAD item.  This is okay because the earlier pruning
                               7875                 :                :              * operation that made the line pointer LP_DEAD in the first place
                               7876                 :                :              * must have considered the original tuple header as part of
                               7877                 :                :              * generating its own snapshotConflictHorizon value.
                               7878                 :                :              *
                               7879                 :                :              * Relying on XLOG_HEAP2_PRUNE_VACUUM_SCAN records like this is
                               7880                 :                :              * the same strategy that index vacuuming uses in all cases. Index
                               7881                 :                :              * VACUUM WAL records don't even have a snapshotConflictHorizon
                               7882                 :                :              * field of their own for this reason.
                               7883                 :                :              */
                               7884         [ +  + ]:         280367 :             if (!ItemIdIsNormal(lp))
                               7885                 :         181211 :                 break;
                               7886                 :                : 
                               7887                 :          99156 :             htup = (HeapTupleHeader) PageGetItem(page, lp);
                               7888                 :                : 
                               7889                 :                :             /*
                               7890                 :                :              * Check the tuple XMIN against prior XMAX, if any
                               7891                 :                :              */
                               7892   [ +  +  -  + ]:         109770 :             if (TransactionIdIsValid(priorXmax) &&
                               7893         [ +  - ]:          10614 :                 !TransactionIdEquals(HeapTupleHeaderGetXmin(htup), priorXmax))
 1201 pg@bowt.ie               7894                 :UBC           0 :                 break;
                               7895                 :                : 
  514 pg@bowt.ie               7896                 :CBC       99156 :             HeapTupleHeaderAdvanceConflictHorizon(htup,
                               7897                 :                :                                                   &snapshotConflictHorizon);
                               7898                 :                : 
                               7899                 :                :             /*
                               7900                 :                :              * If the tuple is not HOT-updated, then we are at the end of this
                               7901                 :                :              * HOT-chain.  No need to visit later tuples from the same update
                               7902                 :                :              * chain (they get their own index entries) -- just move on to
                               7903                 :                :              * next htid from index AM caller.
                               7904                 :                :              */
 1201                          7905   [ +  +  +  -  :          99156 :             if (!HeapTupleHeaderIsHotUpdated(htup))
                                              +  + ]
                               7906                 :                :                 break;
                               7907                 :                : 
                               7908                 :                :             /* Advance to next HOT chain member */
                               7909         [ -  + ]:          10614 :             Assert(ItemPointerGetBlockNumber(&htup->t_ctid) == blkno);
                               7910                 :          10614 :             offnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
                               7911   [ +  -  -  +  :          10614 :             priorXmax = HeapTupleHeaderGetUpdateXid(htup);
                                              -  - ]
                               7912                 :                :         }
                               7913                 :                : 
                               7914                 :                :         /* Enable further/final shrinking of deltids for caller */
 1187                          7915                 :         269753 :         finalndeltids = i + 1;
                               7916                 :                :     }
                               7917                 :                : 
                               7918                 :           4985 :     UnlockReleaseBuffer(buf);
                               7919                 :                : 
                               7920                 :                :     /*
                               7921                 :                :      * Shrink deltids array to exclude non-deletable entries at the end.  This
                               7922                 :                :      * is not just a minor optimization.  Final deltids array size might be
                               7923                 :                :      * zero for a bottom-up caller.  Index AM is explicitly allowed to rely on
                               7924                 :                :      * ndeltids being zero in all cases with zero total deletable entries.
                               7925                 :                :      */
                               7926   [ +  +  -  + ]:           4985 :     Assert(finalndeltids > 0 || delstate->bottomup);
                               7927                 :           4985 :     delstate->ndeltids = finalndeltids;
                               7928                 :                : 
  514                          7929                 :           4985 :     return snapshotConflictHorizon;
                               7930                 :                : }
                               7931                 :                : 
                               7932                 :                : /*
                               7933                 :                :  * Specialized inlineable comparison function for index_delete_sort()
                               7934                 :                :  */
                               7935                 :                : static inline int
 1187                          7936                 :       11736116 : index_delete_sort_cmp(TM_IndexDelete *deltid1, TM_IndexDelete *deltid2)
                               7937                 :                : {
                               7938                 :       11736116 :     ItemPointer tid1 = &deltid1->tid;
                               7939                 :       11736116 :     ItemPointer tid2 = &deltid2->tid;
                               7940                 :                : 
                               7941                 :                :     {
                               7942                 :       11736116 :         BlockNumber blk1 = ItemPointerGetBlockNumber(tid1);
                               7943                 :       11736116 :         BlockNumber blk2 = ItemPointerGetBlockNumber(tid2);
                               7944                 :                : 
                               7945         [ +  + ]:       11736116 :         if (blk1 != blk2)
                               7946         [ +  + ]:        4818212 :             return (blk1 < blk2) ? -1 : 1;
                               7947                 :                :     }
                               7948                 :                :     {
                               7949                 :        6917904 :         OffsetNumber pos1 = ItemPointerGetOffsetNumber(tid1);
                               7950                 :        6917904 :         OffsetNumber pos2 = ItemPointerGetOffsetNumber(tid2);
                               7951                 :                : 
                               7952         [ +  - ]:        6917904 :         if (pos1 != pos2)
                               7953         [ +  + ]:        6917904 :             return (pos1 < pos2) ? -1 : 1;
                               7954                 :                :     }
                               7955                 :                : 
  898 pg@bowt.ie               7956                 :UBC           0 :     Assert(false);
                               7957                 :                : 
                               7958                 :                :     return 0;
                               7959                 :                : }
                               7960                 :                : 
                               7961                 :                : /*
                               7962                 :                :  * Sort deltids array from delstate by TID.  This prepares it for further
                               7963                 :                :  * processing by heap_index_delete_tuples().
                               7964                 :                :  *
                               7965                 :                :  * This operation becomes a noticeable consumer of CPU cycles with some
                               7966                 :                :  * workloads, so we go to the trouble of specialization/micro optimization.
                               7967                 :                :  * We use shellsort for this because it's easy to specialize, compiles to
                               7968                 :                :  * relatively few instructions, and is adaptive to presorted inputs/subsets
                               7969                 :                :  * (which are typical here).
                               7970                 :                :  */
                               7971                 :                : static void
 1187 pg@bowt.ie               7972                 :CBC        4985 : index_delete_sort(TM_IndexDeleteOp *delstate)
                               7973                 :                : {
                               7974                 :           4985 :     TM_IndexDelete *deltids = delstate->deltids;
                               7975                 :           4985 :     int         ndeltids = delstate->ndeltids;
                               7976                 :           4985 :     int         low = 0;
                               7977                 :                : 
                               7978                 :                :     /*
                               7979                 :                :      * Shellsort gap sequence (taken from Sedgewick-Incerpi paper).
                               7980                 :                :      *
                               7981                 :                :      * This implementation is fast with array sizes up to ~4500.  This covers
                               7982                 :                :      * all supported BLCKSZ values.
                               7983                 :                :      */
                               7984                 :           4985 :     const int   gaps[9] = {1968, 861, 336, 112, 48, 21, 7, 3, 1};
                               7985                 :                : 
                               7986                 :                :     /* Think carefully before changing anything here -- keep swaps cheap */
                               7987                 :                :     StaticAssertDecl(sizeof(TM_IndexDelete) <= 8,
                               7988                 :                :                      "element size exceeds 8 bytes");
                               7989                 :                : 
                               7990         [ +  + ]:          49850 :     for (int g = 0; g < lengthof(gaps); g++)
                               7991                 :                :     {
                               7992         [ +  + ]:        7011693 :         for (int hi = gaps[g], i = low + hi; i < ndeltids; i++)
                               7993                 :                :         {
                               7994                 :        6966828 :             TM_IndexDelete d = deltids[i];
                               7995                 :        6966828 :             int         j = i;
                               7996                 :                : 
                               7997   [ +  +  +  + ]:       12061452 :             while (j >= hi && index_delete_sort_cmp(&deltids[j - hi], &d) >= 0)
                               7998                 :                :             {
                               7999                 :        5094624 :                 deltids[j] = deltids[j - hi];
                               8000                 :        5094624 :                 j -= hi;
                               8001                 :                :             }
                               8002                 :        6966828 :             deltids[j] = d;
                               8003                 :                :         }
                               8004                 :                :     }
                               8005                 :           4985 : }
                               8006                 :                : 
                               8007                 :                : /*
                               8008                 :                :  * Returns how many blocks should be considered favorable/contiguous for a
                               8009                 :                :  * bottom-up index deletion pass.  This is a number of heap blocks that starts
                               8010                 :                :  * from and includes the first block in line.
                               8011                 :                :  *
                               8012                 :                :  * There is always at least one favorable block during bottom-up index
                               8013                 :                :  * deletion.  In the worst case (i.e. with totally random heap blocks) the
                               8014                 :                :  * first block in line (the only favorable block) can be thought of as a
                               8015                 :                :  * degenerate array of contiguous blocks that consists of a single block.
                               8016                 :                :  * heap_index_delete_tuples() will expect this.
                               8017                 :                :  *
                               8018                 :                :  * Caller passes blockgroups, a description of the final order that deltids
                               8019                 :                :  * will be sorted in for heap_index_delete_tuples() bottom-up index deletion
                               8020                 :                :  * processing.  Note that deltids need not actually be sorted just yet (caller
                               8021                 :                :  * only passes deltids to us so that we can interpret blockgroups).
                               8022                 :                :  *
                               8023                 :                :  * You might guess that the existence of contiguous blocks cannot matter much,
                               8024                 :                :  * since in general the main factor that determines which blocks we visit is
                               8025                 :                :  * the number of promising TIDs, which is a fixed hint from the index AM.
                               8026                 :                :  * We're not really targeting the general case, though -- the actual goal is
                               8027                 :                :  * to adapt our behavior to a wide variety of naturally occurring conditions.
                               8028                 :                :  * The effects of most of the heuristics we apply are only noticeable in the
                               8029                 :                :  * aggregate, over time and across many _related_ bottom-up index deletion
                               8030                 :                :  * passes.
                               8031                 :                :  *
                               8032                 :                :  * Deeming certain blocks favorable allows heapam to recognize and adapt to
                               8033                 :                :  * workloads where heap blocks visited during bottom-up index deletion can be
                               8034                 :                :  * accessed contiguously, in the sense that each newly visited block is the
                               8035                 :                :  * neighbor of the block that bottom-up deletion just finished processing (or
                               8036                 :                :  * close enough to it).  It will likely be cheaper to access more favorable
                               8037                 :                :  * blocks sooner rather than later (e.g. in this pass, not across a series of
                               8038                 :                :  * related bottom-up passes).  Either way it is probably only a matter of time
                               8039                 :                :  * (or a matter of further correlated version churn) before all blocks that
                               8040                 :                :  * appear together as a single large batch of favorable blocks get accessed by
                               8041                 :                :  * _some_ bottom-up pass.  Large batches of favorable blocks tend to either
                               8042                 :                :  * appear almost constantly or not even once (it all depends on per-index
                               8043                 :                :  * workload characteristics).
                               8044                 :                :  *
                               8045                 :                :  * Note that the blockgroups sort order applies a power-of-two bucketing
                               8046                 :                :  * scheme that creates opportunities for contiguous groups of blocks to get
                               8047                 :                :  * batched together, at least with workloads that are naturally amenable to
                               8048                 :                :  * being driven by heap block locality.  This doesn't just enhance the spatial
                               8049                 :                :  * locality of bottom-up heap block processing in the obvious way.  It also
                               8050                 :                :  * enables temporal locality of access, since sorting by heap block number
                               8051                 :                :  * naturally tends to make the bottom-up processing order deterministic.
                               8052                 :                :  *
                               8053                 :                :  * Consider the following example to get a sense of how temporal locality
                               8054                 :                :  * might matter: There is a heap relation with several indexes, each of which
                               8055                 :                :  * is low to medium cardinality.  It is subject to constant non-HOT updates.
                               8056                 :                :  * The updates are skewed (in one part of the primary key, perhaps).  None of
                               8057                 :                :  * the indexes are logically modified by the UPDATE statements (if they were
                               8058                 :                :  * then bottom-up index deletion would not be triggered in the first place).
                               8059                 :                :  * Naturally, each new round of index tuples (for each heap tuple that gets a
                               8060                 :                :  * heap_update() call) will have the same heap TID in each and every index.
                               8061                 :                :  * Since these indexes are low cardinality and never get logically modified,
                               8062                 :                :  * heapam processing during bottom-up deletion passes will access heap blocks
                               8063                 :                :  * in approximately sequential order.  Temporal locality of access occurs due
                               8064                 :                :  * to bottom-up deletion passes behaving very similarly across each of the
                               8065                 :                :  * indexes at any given moment.  This keeps the number of buffer misses needed
                               8066                 :                :  * to visit heap blocks to a minimum.
                               8067                 :                :  */
                               8068                 :                : static int
                               8069                 :           1729 : bottomup_nblocksfavorable(IndexDeleteCounts *blockgroups, int nblockgroups,
                               8070                 :                :                           TM_IndexDelete *deltids)
                               8071                 :                : {
                               8072                 :           1729 :     int64       lastblock = -1;
                               8073                 :           1729 :     int         nblocksfavorable = 0;
                               8074                 :                : 
                               8075         [ -  + ]:           1729 :     Assert(nblockgroups >= 1);
                               8076         [ -  + ]:           1729 :     Assert(nblockgroups <= BOTTOMUP_MAX_NBLOCKS);
                               8077                 :                : 
                               8078                 :                :     /*
                               8079                 :                :      * We tolerate heap blocks that will be accessed only slightly out of
                               8080                 :                :      * physical order.  Small blips occur when a pair of almost-contiguous
                               8081                 :                :      * blocks happen to fall into different buckets (perhaps due only to a
                               8082                 :                :      * small difference in npromisingtids that the bucketing scheme didn't
                               8083                 :                :      * quite manage to ignore).  We effectively ignore these blips by applying
                               8084                 :                :      * a small tolerance.  The precise tolerance we use is a little arbitrary,
                               8085                 :                :      * but it works well enough in practice.
                               8086                 :                :      */
                               8087         [ +  + ]:           5478 :     for (int b = 0; b < nblockgroups; b++)
                               8088                 :                :     {
                               8089                 :           5256 :         IndexDeleteCounts *group = blockgroups + b;
                               8090                 :           5256 :         TM_IndexDelete *firstdtid = deltids + group->ifirsttid;
                               8091                 :           5256 :         BlockNumber block = ItemPointerGetBlockNumber(&firstdtid->tid);
                               8092                 :                : 
                               8093         [ +  + ]:           5256 :         if (lastblock != -1 &&
                               8094         [ +  + ]:           3527 :             ((int64) block < lastblock - BOTTOMUP_TOLERANCE_NBLOCKS ||
                               8095         [ +  + ]:           2997 :              (int64) block > lastblock + BOTTOMUP_TOLERANCE_NBLOCKS))
                               8096                 :                :             break;
                               8097                 :                : 
                               8098                 :           3749 :         nblocksfavorable++;
                               8099                 :           3749 :         lastblock = block;
                               8100                 :                :     }
                               8101                 :                : 
                               8102                 :                :     /* Always indicate that there is at least 1 favorable block */
                               8103         [ -  + ]:           1729 :     Assert(nblocksfavorable >= 1);
                               8104                 :                : 
                               8105                 :           1729 :     return nblocksfavorable;
                               8106                 :                : }
                               8107                 :                : 
                               8108                 :                : /*
                               8109                 :                :  * qsort comparison function for bottomup_sort_and_shrink()
                               8110                 :                :  */
                               8111                 :                : static int
                               8112                 :         181444 : bottomup_sort_and_shrink_cmp(const void *arg1, const void *arg2)
                               8113                 :                : {
                               8114                 :         181444 :     const IndexDeleteCounts *group1 = (const IndexDeleteCounts *) arg1;
                               8115                 :         181444 :     const IndexDeleteCounts *group2 = (const IndexDeleteCounts *) arg2;
                               8116                 :                : 
                               8117                 :                :     /*
                               8118                 :                :      * Most significant field is npromisingtids (which we invert the order of
                               8119                 :                :      * so as to sort in desc order).
                               8120                 :                :      *
                               8121                 :                :      * Caller should have already normalized npromisingtids fields into
                               8122                 :                :      * power-of-two values (buckets).
                               8123                 :                :      */
                               8124         [ +  + ]:         181444 :     if (group1->npromisingtids > group2->npromisingtids)
                               8125                 :           7233 :         return -1;
                               8126         [ +  + ]:         174211 :     if (group1->npromisingtids < group2->npromisingtids)
                               8127                 :           9060 :         return 1;
                               8128                 :                : 
                               8129                 :                :     /*
                               8130                 :                :      * Tiebreak: desc ntids sort order.
                               8131                 :                :      *
                               8132                 :                :      * We cannot expect power-of-two values for ntids fields.  We should
                               8133                 :                :      * behave as if they were already rounded up for us instead.
                               8134                 :                :      */
                               8135         [ +  + ]:         165151 :     if (group1->ntids != group2->ntids)
                               8136                 :                :     {
                               8137                 :         117883 :         uint32      ntids1 = pg_nextpower2_32((uint32) group1->ntids);
                               8138                 :         117883 :         uint32      ntids2 = pg_nextpower2_32((uint32) group2->ntids);
                               8139                 :                : 
                               8140         [ +  + ]:         117883 :         if (ntids1 > ntids2)
                               8141                 :          16017 :             return -1;
                               8142         [ +  + ]:         101866 :         if (ntids1 < ntids2)
                               8143                 :          20295 :             return 1;
                               8144                 :                :     }
                               8145                 :                : 
                               8146                 :                :     /*
                               8147                 :                :      * Tiebreak: asc offset-into-deltids-for-block (offset to first TID for
                               8148                 :                :      * block in deltids array) order.
                               8149                 :                :      *
                               8150                 :                :      * This is equivalent to sorting in ascending heap block number order
                               8151                 :                :      * (among otherwise equal subsets of the array).  This approach allows us
                               8152                 :                :      * to avoid accessing the out-of-line TID.  (We rely on the assumption
                               8153                 :                :      * that the deltids array was sorted in ascending heap TID order when
                               8154                 :                :      * these offsets to the first TID from each heap block group were formed.)
                               8155                 :                :      */
                               8156         [ +  + ]:         128839 :     if (group1->ifirsttid > group2->ifirsttid)
                               8157                 :          63435 :         return 1;
                               8158         [ +  - ]:          65404 :     if (group1->ifirsttid < group2->ifirsttid)
                               8159                 :          65404 :         return -1;
                               8160                 :                : 
 1187 pg@bowt.ie               8161                 :UBC           0 :     pg_unreachable();
                               8162                 :                : 
                               8163                 :                :     return 0;
                               8164                 :                : }
                               8165                 :                : 
                               8166                 :                : /*
                               8167                 :                :  * heap_index_delete_tuples() helper function for bottom-up deletion callers.
                               8168                 :                :  *
                               8169                 :                :  * Sorts deltids array in the order needed for useful processing by bottom-up
                               8170                 :                :  * deletion.  The array should already be sorted in TID order when we're
                               8171                 :                :  * called.  The sort process groups heap TIDs from deltids into heap block
                               8172                 :                :  * groupings.  Earlier/more-promising groups/blocks are usually those that are
                               8173                 :                :  * known to have the most "promising" TIDs.
                               8174                 :                :  *
                               8175                 :                :  * Sets new size of deltids array (ndeltids) in state.  deltids will only have
                               8176                 :                :  * TIDs from the BOTTOMUP_MAX_NBLOCKS most promising heap blocks when we
                               8177                 :                :  * return.  This often means that deltids will be shrunk to a small fraction
                               8178                 :                :  * of its original size (we eliminate many heap blocks from consideration for
                               8179                 :                :  * caller up front).
                               8180                 :                :  *
                               8181                 :                :  * Returns the number of "favorable" blocks.  See bottomup_nblocksfavorable()
                               8182                 :                :  * for a definition and full details.
                               8183                 :                :  */
                               8184                 :                : static int
 1187 pg@bowt.ie               8185                 :CBC        1729 : bottomup_sort_and_shrink(TM_IndexDeleteOp *delstate)
                               8186                 :                : {
                               8187                 :                :     IndexDeleteCounts *blockgroups;
                               8188                 :                :     TM_IndexDelete *reordereddeltids;
                               8189                 :           1729 :     BlockNumber curblock = InvalidBlockNumber;
                               8190                 :           1729 :     int         nblockgroups = 0;
                               8191                 :           1729 :     int         ncopied = 0;
                               8192                 :           1729 :     int         nblocksfavorable = 0;
                               8193                 :                : 
                               8194         [ -  + ]:           1729 :     Assert(delstate->bottomup);
                               8195         [ -  + ]:           1729 :     Assert(delstate->ndeltids > 0);
                               8196                 :                : 
                               8197                 :                :     /* Calculate per-heap-block count of TIDs */
                               8198                 :           1729 :     blockgroups = palloc(sizeof(IndexDeleteCounts) * delstate->ndeltids);
                               8199         [ +  + ]:         869044 :     for (int i = 0; i < delstate->ndeltids; i++)
                               8200                 :                :     {
                               8201                 :         867315 :         TM_IndexDelete *ideltid = &delstate->deltids[i];
                               8202                 :         867315 :         TM_IndexStatus *istatus = delstate->status + ideltid->id;
                               8203                 :         867315 :         ItemPointer htid = &ideltid->tid;
                               8204                 :         867315 :         bool        promising = istatus->promising;
                               8205                 :                : 
                               8206         [ +  + ]:         867315 :         if (curblock != ItemPointerGetBlockNumber(htid))
                               8207                 :                :         {
                               8208                 :                :             /* New block group */
                               8209                 :          34141 :             nblockgroups++;
                               8210                 :                : 
                               8211   [ +  +  -  + ]:          34141 :             Assert(curblock < ItemPointerGetBlockNumber(htid) ||
                               8212                 :                :                    !BlockNumberIsValid(curblock));
                               8213                 :                : 
                               8214                 :          34141 :             curblock = ItemPointerGetBlockNumber(htid);
                               8215                 :          34141 :             blockgroups[nblockgroups - 1].ifirsttid = i;
                               8216                 :          34141 :             blockgroups[nblockgroups - 1].ntids = 1;
                               8217                 :          34141 :             blockgroups[nblockgroups - 1].npromisingtids = 0;
                               8218                 :                :         }
                               8219                 :                :         else
                               8220                 :                :         {
                               8221                 :         833174 :             blockgroups[nblockgroups - 1].ntids++;
                               8222                 :                :         }
                               8223                 :                : 
                               8224         [ +  + ]:         867315 :         if (promising)
                               8225                 :         106062 :             blockgroups[nblockgroups - 1].npromisingtids++;
                               8226                 :                :     }
                               8227                 :                : 
                               8228                 :                :     /*
                               8229                 :                :      * We're about ready to sort block groups to determine the optimal order
                               8230                 :                :      * for visiting heap blocks.  But before we do, round the number of
                               8231                 :                :      * promising tuples for each block group up to the next power-of-two,
                               8232                 :                :      * unless it is very low (less than 4), in which case we round up to 4.
                               8233                 :                :      * npromisingtids is far too noisy to trust when choosing between a pair
                               8234                 :                :      * of block groups that both have very low values.
                               8235                 :                :      *
                               8236                 :                :      * This scheme divides heap blocks/block groups into buckets.  Each bucket
                               8237                 :                :      * contains blocks that have _approximately_ the same number of promising
                               8238                 :                :      * TIDs as each other.  The goal is to ignore relatively small differences
                               8239                 :                :      * in the total number of promising entries, so that the whole process can
                               8240                 :                :      * give a little weight to heapam factors (like heap block locality)
                               8241                 :                :      * instead.  This isn't a trade-off, really -- we have nothing to lose. It
                               8242                 :                :      * would be foolish to interpret small differences in npromisingtids
                               8243                 :                :      * values as anything more than noise.
                               8244                 :                :      *
                               8245                 :                :      * We tiebreak on nhtids when sorting block group subsets that have the
                               8246                 :                :      * same npromisingtids, but this has the same issues as npromisingtids,
                               8247                 :                :      * and so nhtids is subject to the same power-of-two bucketing scheme. The
                               8248                 :                :      * only reason that we don't fix nhtids in the same way here too is that
                               8249                 :                :      * we'll need accurate nhtids values after the sort.  We handle nhtids
                               8250                 :                :      * bucketization dynamically instead (in the sort comparator).
                               8251                 :                :      *
                               8252                 :                :      * See bottomup_nblocksfavorable() for a full explanation of when and how
                               8253                 :                :      * heap locality/favorable blocks can significantly influence when and how
                               8254                 :                :      * heap blocks are accessed.
                               8255                 :                :      */
                               8256         [ +  + ]:          35870 :     for (int b = 0; b < nblockgroups; b++)
                               8257                 :                :     {
                               8258                 :          34141 :         IndexDeleteCounts *group = blockgroups + b;
                               8259                 :                : 
                               8260                 :                :         /* Better off falling back on nhtids with low npromisingtids */
                               8261         [ +  + ]:          34141 :         if (group->npromisingtids <= 4)
                               8262                 :          29291 :             group->npromisingtids = 4;
                               8263                 :                :         else
                               8264                 :           4850 :             group->npromisingtids =
                               8265                 :           4850 :                 pg_nextpower2_32((uint32) group->npromisingtids);
                               8266                 :                :     }
                               8267                 :                : 
                               8268                 :                :     /* Sort groups and rearrange caller's deltids array */
                               8269                 :           1729 :     qsort(blockgroups, nblockgroups, sizeof(IndexDeleteCounts),
                               8270                 :                :           bottomup_sort_and_shrink_cmp);
                               8271                 :           1729 :     reordereddeltids = palloc(delstate->ndeltids * sizeof(TM_IndexDelete));
                               8272                 :                : 
                               8273                 :           1729 :     nblockgroups = Min(BOTTOMUP_MAX_NBLOCKS, nblockgroups);
                               8274                 :                :     /* Determine number of favorable blocks at the start of final deltids */
                               8275                 :           1729 :     nblocksfavorable = bottomup_nblocksfavorable(blockgroups, nblockgroups,
                               8276                 :                :                                                  delstate->deltids);
                               8277                 :                : 
                               8278         [ +  + ]:          11493 :     for (int b = 0; b < nblockgroups; b++)
                               8279                 :                :     {
                               8280                 :           9764 :         IndexDeleteCounts *group = blockgroups + b;
                               8281                 :           9764 :         TM_IndexDelete *firstdtid = delstate->deltids + group->ifirsttid;
                               8282                 :                : 
                               8283                 :           9764 :         memcpy(reordereddeltids + ncopied, firstdtid,
                               8284                 :           9764 :                sizeof(TM_IndexDelete) * group->ntids);
                               8285                 :           9764 :         ncopied += group->ntids;
                               8286                 :                :     }
                               8287                 :                : 
                               8288                 :                :     /* Copy final grouped and sorted TIDs back into start of caller's array */
                               8289                 :           1729 :     memcpy(delstate->deltids, reordereddeltids,
                               8290                 :                :            sizeof(TM_IndexDelete) * ncopied);
                               8291                 :           1729 :     delstate->ndeltids = ncopied;
                               8292                 :                : 
                               8293                 :           1729 :     pfree(reordereddeltids);
                               8294                 :           1729 :     pfree(blockgroups);
                               8295                 :                : 
                               8296                 :           1729 :     return nblocksfavorable;
                               8297                 :                : }
                               8298                 :                : 
                               8299                 :                : /*
                               8300                 :                :  * Perform XLogInsert for a heap-visible operation.  'block' is the block
                               8301                 :                :  * being marked all-visible, and vm_buffer is the buffer containing the
                               8302                 :                :  * corresponding visibility map block.  Both should have already been modified
                               8303                 :                :  * and dirtied.
                               8304                 :                :  *
                               8305                 :                :  * snapshotConflictHorizon comes from the largest xmin on the page being
                               8306                 :                :  * marked all-visible.  REDO routine uses it to generate recovery conflicts.
                               8307                 :                :  *
                               8308                 :                :  * If checksums or wal_log_hints are enabled, we may also generate a full-page
                               8309                 :                :  * image of heap_buffer. Otherwise, we optimize away the FPI (by specifying
                               8310                 :                :  * REGBUF_NO_IMAGE for the heap buffer), in which case the caller should *not*
                               8311                 :                :  * update the heap page's LSN.
                               8312                 :                :  */
                               8313                 :                : XLogRecPtr
  379 andres@anarazel.de       8314                 :          39281 : log_heap_visible(Relation rel, Buffer heap_buffer, Buffer vm_buffer,
                               8315                 :                :                  TransactionId snapshotConflictHorizon, uint8 vmflags)
                               8316                 :                : {
                               8317                 :                :     xl_heap_visible xlrec;
                               8318                 :                :     XLogRecPtr  recptr;
                               8319                 :                :     uint8       flags;
                               8320                 :                : 
 4041 simon@2ndQuadrant.co     8321         [ -  + ]:          39281 :     Assert(BufferIsValid(heap_buffer));
                               8322         [ -  + ]:          39281 :     Assert(BufferIsValid(vm_buffer));
                               8323                 :                : 
  514 pg@bowt.ie               8324                 :          39281 :     xlrec.snapshotConflictHorizon = snapshotConflictHorizon;
 2966 rhaas@postgresql.org     8325                 :          39281 :     xlrec.flags = vmflags;
  378 andres@anarazel.de       8326   [ +  +  +  -  :          39281 :     if (RelationIsAccessibleInLogicalDecoding(rel))
                                     -  +  -  -  -  
                                     -  +  +  -  +  
                                     -  -  -  -  -  
                                                 - ]
                               8327                 :            139 :         xlrec.flags |= VISIBILITYMAP_XLOG_CATALOG_REL;
 3433 heikki.linnakangas@i     8328                 :          39281 :     XLogBeginInsert();
                               8329                 :          39281 :     XLogRegisterData((char *) &xlrec, SizeOfHeapVisible);
                               8330                 :                : 
                               8331                 :          39281 :     XLogRegisterBuffer(0, vm_buffer, 0);
                               8332                 :                : 
                               8333                 :          39281 :     flags = REGBUF_STANDARD;
                               8334   [ +  +  +  + ]:          39281 :     if (!XLogHintBitIsNeeded())
                               8335                 :          31134 :         flags |= REGBUF_NO_IMAGE;
                               8336                 :          39281 :     XLogRegisterBuffer(1, heap_buffer, flags);
                               8337                 :                : 
                               8338                 :          39281 :     recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);
                               8339                 :                : 
 4681 rhaas@postgresql.org     8340                 :          39281 :     return recptr;
                               8341                 :                : }
                               8342                 :                : 
                               8343                 :                : /*
                               8344                 :                :  * Perform XLogInsert for a heap-update operation.  Caller must already
                               8345                 :                :  * have modified the buffer(s) and marked them dirty.
                               8346                 :                :  */
                               8347                 :                : static XLogRecPtr
 4099 alvherre@alvh.no-ip.     8348                 :         265654 : log_heap_update(Relation reln, Buffer oldbuf,
                               8349                 :                :                 Buffer newbuf, HeapTuple oldtup, HeapTuple newtup,
                               8350                 :                :                 HeapTuple old_key_tuple,
                               8351                 :                :                 bool all_visible_cleared, bool new_all_visible_cleared)
                               8352                 :                : {
                               8353                 :                :     xl_heap_update xlrec;
                               8354                 :                :     xl_heap_header xlhdr;
                               8355                 :                :     xl_heap_header xlhdr_idx;
                               8356                 :                :     uint8       info;
                               8357                 :                :     uint16      prefix_suffix[2];
 3686 heikki.linnakangas@i     8358                 :         265654 :     uint16      prefixlen = 0,
                               8359                 :         265654 :                 suffixlen = 0;
                               8360                 :                :     XLogRecPtr  recptr;
 2916 kgrittn@postgresql.o     8361                 :         265654 :     Page        page = BufferGetPage(newbuf);
 3778 rhaas@postgresql.org     8362   [ +  +  +  -  :         265654 :     bool        need_tuple_data = RelationIsLogicallyLogged(reln);
                                     -  +  -  -  -  
                                        -  +  -  +  
                                                 + ]
                               8363                 :                :     bool        init;
                               8364                 :                :     int         bufflags;
                               8365                 :                : 
                               8366                 :                :     /* Caller should not call me on a non-WAL-logged relation */
 4871                          8367   [ +  -  +  +  :         265654 :     Assert(RelationNeedsWAL(reln));
                                        +  -  -  + ]
                               8368                 :                : 
 3433 heikki.linnakangas@i     8369                 :         265654 :     XLogBeginInsert();
                               8370                 :                : 
 5179 tgl@sss.pgh.pa.us        8371         [ +  + ]:         265654 :     if (HeapTupleIsHeapOnly(newtup))
 6051                          8372                 :         124964 :         info = XLOG_HEAP_HOT_UPDATE;
                               8373                 :                :     else
                               8374                 :         140690 :         info = XLOG_HEAP_UPDATE;
                               8375                 :                : 
                               8376                 :                :     /*
                               8377                 :                :      * If the old and new tuple are on the same page, we only need to log the
                               8378                 :                :      * parts of the new tuple that were changed.  That saves on the amount of
                               8379                 :                :      * WAL we need to write.  Currently, we just count any unchanged bytes in
                               8380                 :                :      * the beginning and end of the tuple.  That's quick to check, and
                               8381                 :                :      * perfectly covers the common case that only one field is updated.
                               8382                 :                :      *
                               8383                 :                :      * We could do this even if the old and new tuple are on different pages,
                               8384                 :                :      * but only if we don't make a full-page image of the old page, which is
                               8385                 :                :      * difficult to know in advance.  Also, if the old tuple is corrupt for
                               8386                 :                :      * some reason, it would allow the corruption to propagate the new page,
                               8387                 :                :      * so it seems best to avoid.  Under the general assumption that most
                               8388                 :                :      * updates tend to create the new tuple version on the same page, there
                               8389                 :                :      * isn't much to be gained by doing this across pages anyway.
                               8390                 :                :      *
                               8391                 :                :      * Skip this if we're taking a full-page image of the new page, as we
                               8392                 :                :      * don't include the new tuple in the WAL record in that case.  Also
                               8393                 :                :      * disable if wal_level='logical', as logical decoding needs to be able to
                               8394                 :                :      * read the new tuple in whole from the WAL record alone.
                               8395                 :                :      */
 3686 heikki.linnakangas@i     8396   [ +  +  +  + ]:         265654 :     if (oldbuf == newbuf && !need_tuple_data &&
                               8397         [ +  + ]:         123702 :         !XLogCheckBufferNeedsBackup(newbuf))
                               8398                 :                :     {
                               8399                 :         123320 :         char       *oldp = (char *) oldtup->t_data + oldtup->t_data->t_hoff;
                               8400                 :         123320 :         char       *newp = (char *) newtup->t_data + newtup->t_data->t_hoff;
                               8401                 :         123320 :         int         oldlen = oldtup->t_len - oldtup->t_data->t_hoff;
                               8402                 :         123320 :         int         newlen = newtup->t_len - newtup->t_data->t_hoff;
                               8403                 :                : 
                               8404                 :                :         /* Check for common prefix between old and new tuple */
                               8405         [ +  + ]:        9182180 :         for (prefixlen = 0; prefixlen < Min(oldlen, newlen); prefixlen++)
                               8406                 :                :         {
                               8407         [ +  + ]:        9161273 :             if (newp[prefixlen] != oldp[prefixlen])
                               8408                 :         102413 :                 break;
                               8409                 :                :         }
                               8410                 :                : 
                               8411                 :                :         /*
                               8412                 :                :          * Storing the length of the prefix takes 2 bytes, so we need to save
                               8413                 :                :          * at least 3 bytes or there's no point.
                               8414                 :                :          */
                               8415         [ +  + ]:         123320 :         if (prefixlen < 3)
                               8416                 :          22042 :             prefixlen = 0;
                               8417                 :                : 
                               8418                 :                :         /* Same for suffix */
                               8419         [ +  + ]:        4144937 :         for (suffixlen = 0; suffixlen < Min(oldlen, newlen) - prefixlen; suffixlen++)
                               8420                 :                :         {
                               8421         [ +  + ]:        4123816 :             if (newp[newlen - suffixlen - 1] != oldp[oldlen - suffixlen - 1])
                               8422                 :         102199 :                 break;
                               8423                 :                :         }
                               8424         [ +  + ]:         123320 :         if (suffixlen < 3)
                               8425                 :          30252 :             suffixlen = 0;
                               8426                 :                :     }
                               8427                 :                : 
                               8428                 :                :     /* Prepare main WAL data chain */
 3778 rhaas@postgresql.org     8429                 :         265654 :     xlrec.flags = 0;
                               8430         [ +  + ]:         265654 :     if (all_visible_cleared)
 3264 andres@anarazel.de       8431                 :           1175 :         xlrec.flags |= XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED;
 3778 rhaas@postgresql.org     8432         [ +  + ]:         265654 :     if (new_all_visible_cleared)
 3264 andres@anarazel.de       8433                 :            815 :         xlrec.flags |= XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED;
 3686 heikki.linnakangas@i     8434         [ +  + ]:         265654 :     if (prefixlen > 0)
 3264 andres@anarazel.de       8435                 :         101278 :         xlrec.flags |= XLH_UPDATE_PREFIX_FROM_OLD;
 3686 heikki.linnakangas@i     8436         [ +  + ]:         265654 :     if (suffixlen > 0)
 3264 andres@anarazel.de       8437                 :          93068 :         xlrec.flags |= XLH_UPDATE_SUFFIX_FROM_OLD;
 3433 heikki.linnakangas@i     8438         [ +  + ]:         265654 :     if (need_tuple_data)
                               8439                 :                :     {
 3264 andres@anarazel.de       8440                 :          47008 :         xlrec.flags |= XLH_UPDATE_CONTAINS_NEW_TUPLE;
 3433 heikki.linnakangas@i     8441         [ +  + ]:          47008 :         if (old_key_tuple)
                               8442                 :                :         {
                               8443         [ +  + ]:            133 :             if (reln->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
 3264 andres@anarazel.de       8444                 :             56 :                 xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_TUPLE;
                               8445                 :                :             else
                               8446                 :             77 :                 xlrec.flags |= XLH_UPDATE_CONTAINS_OLD_KEY;
                               8447                 :                :         }
                               8448                 :                :     }
                               8449                 :                : 
                               8450                 :                :     /* If new tuple is the single and first tuple on page... */
 3686 heikki.linnakangas@i     8451   [ +  +  +  + ]:         268589 :     if (ItemPointerGetOffsetNumber(&(newtup->t_self)) == FirstOffsetNumber &&
                               8452                 :           2935 :         PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
                               8453                 :                :     {
                               8454                 :           2753 :         info |= XLOG_HEAP_INIT_PAGE;
 3433                          8455                 :           2753 :         init = true;
                               8456                 :                :     }
                               8457                 :                :     else
                               8458                 :         262901 :         init = false;
                               8459                 :                : 
                               8460                 :                :     /* Prepare WAL data for the old page */
                               8461                 :         265654 :     xlrec.old_offnum = ItemPointerGetOffsetNumber(&oldtup->t_self);
                               8462                 :         265654 :     xlrec.old_xmax = HeapTupleHeaderGetRawXmax(oldtup->t_data);
                               8463                 :         531308 :     xlrec.old_infobits_set = compute_infobits(oldtup->t_data->t_infomask,
                               8464                 :         265654 :                                               oldtup->t_data->t_infomask2);
                               8465                 :                : 
                               8466                 :                :     /* Prepare WAL data for the new page */
                               8467                 :         265654 :     xlrec.new_offnum = ItemPointerGetOffsetNumber(&newtup->t_self);
                               8468                 :         265654 :     xlrec.new_xmax = HeapTupleHeaderGetRawXmax(newtup->t_data);
                               8469                 :                : 
                               8470                 :         265654 :     bufflags = REGBUF_STANDARD;
                               8471         [ +  + ]:         265654 :     if (init)
                               8472                 :           2753 :         bufflags |= REGBUF_WILL_INIT;
                               8473         [ +  + ]:         265654 :     if (need_tuple_data)
                               8474                 :          47008 :         bufflags |= REGBUF_KEEP_DATA;
                               8475                 :                : 
                               8476                 :         265654 :     XLogRegisterBuffer(0, newbuf, bufflags);
                               8477         [ +  + ]:         265654 :     if (oldbuf != newbuf)
                               8478                 :         130024 :         XLogRegisterBuffer(1, oldbuf, REGBUF_STANDARD);
                               8479                 :                : 
                               8480                 :         265654 :     XLogRegisterData((char *) &xlrec, SizeOfHeapUpdate);
                               8481                 :                : 
                               8482                 :                :     /*
                               8483                 :                :      * Prepare WAL data for the new tuple.
                               8484                 :                :      */
 3686                          8485   [ +  +  +  + ]:         265654 :     if (prefixlen > 0 || suffixlen > 0)
                               8486                 :                :     {
                               8487   [ +  +  +  + ]:         122889 :         if (prefixlen > 0 && suffixlen > 0)
                               8488                 :                :         {
                               8489                 :          71457 :             prefix_suffix[0] = prefixlen;
                               8490                 :          71457 :             prefix_suffix[1] = suffixlen;
 3433                          8491                 :          71457 :             XLogRegisterBufData(0, (char *) &prefix_suffix, sizeof(uint16) * 2);
                               8492                 :                :         }
 3686                          8493         [ +  + ]:          51432 :         else if (prefixlen > 0)
                               8494                 :                :         {
 3433                          8495                 :          29821 :             XLogRegisterBufData(0, (char *) &prefixlen, sizeof(uint16));
                               8496                 :                :         }
                               8497                 :                :         else
                               8498                 :                :         {
                               8499                 :          21611 :             XLogRegisterBufData(0, (char *) &suffixlen, sizeof(uint16));
                               8500                 :                :         }
                               8501                 :                :     }
                               8502                 :                : 
                               8503                 :         265654 :     xlhdr.t_infomask2 = newtup->t_data->t_infomask2;
                               8504                 :         265654 :     xlhdr.t_infomask = newtup->t_data->t_infomask;
                               8505                 :         265654 :     xlhdr.t_hoff = newtup->t_data->t_hoff;
 3340 tgl@sss.pgh.pa.us        8506         [ -  + ]:         265654 :     Assert(SizeofHeapTupleHeader + prefixlen + suffixlen <= newtup->t_len);
                               8507                 :                : 
                               8508                 :                :     /*
                               8509                 :                :      * PG73FORMAT: write bitmap [+ padding] [+ oid] + data
                               8510                 :                :      *
                               8511                 :                :      * The 'data' doesn't include the common prefix or suffix.
                               8512                 :                :      */
 3433 heikki.linnakangas@i     8513                 :         265654 :     XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
 3686                          8514         [ +  + ]:         265654 :     if (prefixlen == 0)
                               8515                 :                :     {
 3433                          8516                 :         164376 :         XLogRegisterBufData(0,
 3340 tgl@sss.pgh.pa.us        8517                 :         164376 :                             ((char *) newtup->t_data) + SizeofHeapTupleHeader,
 2489                          8518                 :         164376 :                             newtup->t_len - SizeofHeapTupleHeader - suffixlen);
                               8519                 :                :     }
                               8520                 :                :     else
                               8521                 :                :     {
                               8522                 :                :         /*
                               8523                 :                :          * Have to write the null bitmap and data after the common prefix as
                               8524                 :                :          * two separate rdata entries.
                               8525                 :                :          */
                               8526                 :                :         /* bitmap [+ padding] [+ oid] */
 3340                          8527         [ +  - ]:         101278 :         if (newtup->t_data->t_hoff - SizeofHeapTupleHeader > 0)
                               8528                 :                :         {
 3433 heikki.linnakangas@i     8529                 :         101278 :             XLogRegisterBufData(0,
 2489 tgl@sss.pgh.pa.us        8530                 :         101278 :                                 ((char *) newtup->t_data) + SizeofHeapTupleHeader,
                               8531                 :         101278 :                                 newtup->t_data->t_hoff - SizeofHeapTupleHeader);
                               8532                 :                :         }
                               8533                 :                : 
                               8534                 :                :         /* data after common prefix */
 3433 heikki.linnakangas@i     8535                 :         101278 :         XLogRegisterBufData(0,
 2489 tgl@sss.pgh.pa.us        8536                 :         101278 :                             ((char *) newtup->t_data) + newtup->t_data->t_hoff + prefixlen,
                               8537                 :         101278 :                             newtup->t_len - newtup->t_data->t_hoff - prefixlen - suffixlen);
                               8538                 :                :     }
                               8539                 :                : 
                               8540                 :                :     /* We need to log a tuple identity */
 3433 heikki.linnakangas@i     8541   [ +  +  +  + ]:         265654 :     if (need_tuple_data && old_key_tuple)
                               8542                 :                :     {
                               8543                 :                :         /* don't really need this, but its more comfy to decode */
                               8544                 :            133 :         xlhdr_idx.t_infomask2 = old_key_tuple->t_data->t_infomask2;
                               8545                 :            133 :         xlhdr_idx.t_infomask = old_key_tuple->t_data->t_infomask;
                               8546                 :            133 :         xlhdr_idx.t_hoff = old_key_tuple->t_data->t_hoff;
                               8547                 :                : 
                               8548                 :            133 :         XLogRegisterData((char *) &xlhdr_idx, SizeOfHeapHeader);
                               8549                 :                : 
                               8550                 :                :         /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
 3340 tgl@sss.pgh.pa.us        8551                 :            133 :         XLogRegisterData((char *) old_key_tuple->t_data + SizeofHeapTupleHeader,
                               8552                 :            133 :                          old_key_tuple->t_len - SizeofHeapTupleHeader);
                               8553                 :                :     }
                               8554                 :                : 
                               8555                 :                :     /* filtering by origin on a row level is much more efficient */
 2670 andres@anarazel.de       8556                 :         265654 :     XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
                               8557                 :                : 
 3433 heikki.linnakangas@i     8558                 :         265654 :     recptr = XLogInsert(RM_HEAP_ID, info);
                               8559                 :                : 
 6668 neilc@samurai.com        8560                 :         265654 :     return recptr;
                               8561                 :                : }
                               8562                 :                : 
                               8563                 :                : /*
                               8564                 :                :  * Perform XLogInsert of an XLOG_HEAP2_NEW_CID record
                               8565                 :                :  *
                               8566                 :                :  * This is only used in wal_level >= WAL_LEVEL_LOGICAL, and only for catalog
                               8567                 :                :  * tuples.
                               8568                 :                :  */
                               8569                 :                : static XLogRecPtr
 3778 rhaas@postgresql.org     8570                 :          21457 : log_heap_new_cid(Relation relation, HeapTuple tup)
                               8571                 :                : {
                               8572                 :                :     xl_heap_new_cid xlrec;
                               8573                 :                : 
                               8574                 :                :     XLogRecPtr  recptr;
                               8575                 :          21457 :     HeapTupleHeader hdr = tup->t_data;
                               8576                 :                : 
                               8577         [ -  + ]:          21457 :     Assert(ItemPointerIsValid(&tup->t_self));
                               8578         [ -  + ]:          21457 :     Assert(tup->t_tableOid != InvalidOid);
                               8579                 :                : 
                               8580                 :          21457 :     xlrec.top_xid = GetTopTransactionId();
  648                          8581                 :          21457 :     xlrec.target_locator = relation->rd_locator;
 3433 heikki.linnakangas@i     8582                 :          21457 :     xlrec.target_tid = tup->t_self;
                               8583                 :                : 
                               8584                 :                :     /*
                               8585                 :                :      * If the tuple got inserted & deleted in the same TX we definitely have a
                               8586                 :                :      * combo CID, set cmin and cmax.
                               8587                 :                :      */
 3778 rhaas@postgresql.org     8588         [ +  + ]:          21457 :     if (hdr->t_infomask & HEAP_COMBOCID)
                               8589                 :                :     {
                               8590         [ -  + ]:           1928 :         Assert(!(hdr->t_infomask & HEAP_XMAX_INVALID));
 3766                          8591         [ -  + ]:           1928 :         Assert(!HeapTupleHeaderXminInvalid(hdr));
 3778                          8592                 :           1928 :         xlrec.cmin = HeapTupleHeaderGetCmin(hdr);
                               8593                 :           1928 :         xlrec.cmax = HeapTupleHeaderGetCmax(hdr);
                               8594                 :           1928 :         xlrec.combocid = HeapTupleHeaderGetRawCommandId(hdr);
                               8595                 :                :     }
                               8596                 :                :     /* No combo CID, so only cmin or cmax can be set by this TX */
                               8597                 :                :     else
                               8598                 :                :     {
                               8599                 :                :         /*
                               8600                 :                :          * Tuple inserted.
                               8601                 :                :          *
                               8602                 :                :          * We need to check for LOCK ONLY because multixacts might be
                               8603                 :                :          * transferred to the new tuple in case of FOR KEY SHARE updates in
                               8604                 :                :          * which case there will be an xmax, although the tuple just got
                               8605                 :                :          * inserted.
                               8606                 :                :          */
                               8607         [ +  + ]:          19529 :         if (hdr->t_infomask & HEAP_XMAX_INVALID ||
                               8608   [ +  +  -  + ]:           5782 :             HEAP_XMAX_IS_LOCKED_ONLY(hdr->t_infomask))
                               8609                 :                :         {
                               8610                 :          13748 :             xlrec.cmin = HeapTupleHeaderGetRawCommandId(hdr);
                               8611                 :          13748 :             xlrec.cmax = InvalidCommandId;
                               8612                 :                :         }
                               8613                 :                :         /* Tuple from a different tx updated or deleted. */
                               8614                 :                :         else
                               8615                 :                :         {
                               8616                 :           5781 :             xlrec.cmin = InvalidCommandId;
                               8617                 :           5781 :             xlrec.cmax = HeapTupleHeaderGetRawCommandId(hdr);
                               8618                 :                :         }
                               8619                 :          19529 :         xlrec.combocid = InvalidCommandId;
                               8620                 :                :     }
                               8621                 :                : 
                               8622                 :                :     /*
                               8623                 :                :      * Note that we don't need to register the buffer here, because this
                               8624                 :                :      * operation does not modify the page. The insert/update/delete that
                               8625                 :                :      * called us certainly did, but that's WAL-logged separately.
                               8626                 :                :      */
 3433 heikki.linnakangas@i     8627                 :          21457 :     XLogBeginInsert();
                               8628                 :          21457 :     XLogRegisterData((char *) &xlrec, SizeOfHeapNewCid);
                               8629                 :                : 
                               8630                 :                :     /* will be looked at irrespective of origin */
                               8631                 :                : 
                               8632                 :          21457 :     recptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_NEW_CID);
                               8633                 :                : 
 3778 rhaas@postgresql.org     8634                 :          21457 :     return recptr;
                               8635                 :                : }
                               8636                 :                : 
                               8637                 :                : /*
                               8638                 :                :  * Build a heap tuple representing the configured REPLICA IDENTITY to represent
                               8639                 :                :  * the old tuple in an UPDATE or DELETE.
                               8640                 :                :  *
                               8641                 :                :  * Returns NULL if there's no need to log an identity or if there's no suitable
                               8642                 :                :  * key defined.
                               8643                 :                :  *
                               8644                 :                :  * Pass key_required true if any replica identity columns changed value, or if
                               8645                 :                :  * any of them have any external data.  Delete must always pass true.
                               8646                 :                :  *
                               8647                 :                :  * *copy is set to true if the returned tuple is a modified copy rather than
                               8648                 :                :  * the same tuple that was passed in.
                               8649                 :                :  */
                               8650                 :                : static HeapTuple
  790 akapila@postgresql.o     8651                 :        1709563 : ExtractReplicaIdentity(Relation relation, HeapTuple tp, bool key_required,
                               8652                 :                :                        bool *copy)
                               8653                 :                : {
 3778 rhaas@postgresql.org     8654                 :        1709563 :     TupleDesc   desc = RelationGetDescr(relation);
                               8655                 :        1709563 :     char        replident = relation->rd_rel->relreplident;
                               8656                 :                :     Bitmapset  *idattrs;
                               8657                 :                :     HeapTuple   key_tuple;
                               8658                 :                :     bool        nulls[MaxHeapAttributeNumber];
                               8659                 :                :     Datum       values[MaxHeapAttributeNumber];
                               8660                 :                : 
                               8661                 :        1709563 :     *copy = false;
                               8662                 :                : 
                               8663   [ +  +  +  +  :        1709563 :     if (!RelationIsLogicallyLogged(relation))
                                     -  +  -  -  -  
                                        -  +  -  +  
                                                 + ]
                               8664                 :        1609303 :         return NULL;
                               8665                 :                : 
                               8666         [ +  + ]:         100260 :     if (replident == REPLICA_IDENTITY_NOTHING)
                               8667                 :            231 :         return NULL;
                               8668                 :                : 
                               8669         [ +  + ]:         100029 :     if (replident == REPLICA_IDENTITY_FULL)
                               8670                 :                :     {
                               8671                 :                :         /*
                               8672                 :                :          * When logging the entire old tuple, it very well could contain
                               8673                 :                :          * toasted columns. If so, force them to be inlined.
                               8674                 :                :          */
                               8675         [ +  + ]:            177 :         if (HeapTupleHasExternal(tp))
                               8676                 :                :         {
                               8677                 :              4 :             *copy = true;
 1686 tgl@sss.pgh.pa.us        8678                 :              4 :             tp = toast_flatten_tuple(tp, desc);
                               8679                 :                :         }
 3778 rhaas@postgresql.org     8680                 :            177 :         return tp;
                               8681                 :                :     }
                               8682                 :                : 
                               8683                 :                :     /* if the key isn't required and we're only logging the key, we're done */
  790 akapila@postgresql.o     8684         [ +  + ]:          99852 :     if (!key_required)
 3778 rhaas@postgresql.org     8685                 :          46875 :         return NULL;
                               8686                 :                : 
                               8687                 :                :     /* find out the replica identity columns */
 1686 tgl@sss.pgh.pa.us        8688                 :          52977 :     idattrs = RelationGetIndexAttrBitmap(relation,
                               8689                 :                :                                          INDEX_ATTR_BITMAP_IDENTITY_KEY);
                               8690                 :                : 
                               8691                 :                :     /*
                               8692                 :                :      * If there's no defined replica identity columns, treat as !key_required.
                               8693                 :                :      * (This case should not be reachable from heap_update, since that should
                               8694                 :                :      * calculate key_required accurately.  But heap_delete just passes
                               8695                 :                :      * constant true for key_required, so we can hit this case in deletes.)
                               8696                 :                :      */
                               8697         [ +  + ]:          52977 :     if (bms_is_empty(idattrs))
                               8698                 :           6021 :         return NULL;
                               8699                 :                : 
                               8700                 :                :     /*
                               8701                 :                :      * Construct a new tuple containing only the replica identity columns,
                               8702                 :                :      * with nulls elsewhere.  While we're at it, assert that the replica
                               8703                 :                :      * identity columns aren't null.
                               8704                 :                :      */
                               8705                 :          46956 :     heap_deform_tuple(tp, desc, values, nulls);
                               8706                 :                : 
                               8707         [ +  + ]:         150861 :     for (int i = 0; i < desc->natts; i++)
                               8708                 :                :     {
                               8709         [ +  + ]:         103905 :         if (bms_is_member(i + 1 - FirstLowInvalidHeapAttributeNumber,
                               8710                 :                :                           idattrs))
                               8711         [ -  + ]:          46965 :             Assert(!nulls[i]);
                               8712                 :                :         else
                               8713                 :          56940 :             nulls[i] = true;
                               8714                 :                :     }
                               8715                 :                : 
 3778 rhaas@postgresql.org     8716                 :          46956 :     key_tuple = heap_form_tuple(desc, values, nulls);
                               8717                 :          46956 :     *copy = true;
                               8718                 :                : 
 1686 tgl@sss.pgh.pa.us        8719                 :          46956 :     bms_free(idattrs);
                               8720                 :                : 
                               8721                 :                :     /*
                               8722                 :                :      * If the tuple, which by here only contains indexed columns, still has
                               8723                 :                :      * toasted columns, force them to be inlined. This is somewhat unlikely
                               8724                 :                :      * since there's limits on the size of indexed columns, so we don't
                               8725                 :                :      * duplicate toast_flatten_tuple()s functionality in the above loop over
                               8726                 :                :      * the indexed columns, even if it would be more efficient.
                               8727                 :                :      */
 3778 rhaas@postgresql.org     8728         [ +  + ]:          46956 :     if (HeapTupleHasExternal(key_tuple))
                               8729                 :                :     {
 3631 bruce@momjian.us         8730                 :              4 :         HeapTuple   oldtup = key_tuple;
                               8731                 :                : 
 1686 tgl@sss.pgh.pa.us        8732                 :              4 :         key_tuple = toast_flatten_tuple(oldtup, desc);
 3778 rhaas@postgresql.org     8733                 :              4 :         heap_freetuple(oldtup);
                               8734                 :                :     }
                               8735                 :                : 
                               8736                 :          46956 :     return key_tuple;
                               8737                 :                : }
                               8738                 :                : 
                               8739                 :                : /*
                               8740                 :                :  * Replay XLOG_HEAP2_PRUNE_* records.
                               8741                 :                :  */
                               8742                 :                : static void
   20 heikki.linnakangas@i     8743                 :GNC       13170 : heap_xlog_prune_freeze(XLogReaderState *record)
                               8744                 :                : {
 3433 heikki.linnakangas@i     8745                 :CBC       13170 :     XLogRecPtr  lsn = record->EndRecPtr;
   20 heikki.linnakangas@i     8746                 :GNC       13170 :     char       *maindataptr = XLogRecGetData(record);
                               8747                 :                :     xl_heap_prune xlrec;
                               8748                 :                :     Buffer      buffer;
                               8749                 :                :     RelFileLocator rlocator;
                               8750                 :                :     BlockNumber blkno;
                               8751                 :                :     XLogRedoAction action;
                               8752                 :                : 
  648 rhaas@postgresql.org     8753                 :CBC       13170 :     XLogRecGetBlockTag(record, 0, &rlocator, NULL, &blkno);
   20 heikki.linnakangas@i     8754                 :GNC       13170 :     memcpy(&xlrec, maindataptr, SizeOfHeapPrune);
                               8755                 :          13170 :     maindataptr += SizeOfHeapPrune;
                               8756                 :                : 
                               8757                 :                :     /*
                               8758                 :                :      * We will take an ordinary exclusive lock or a cleanup lock depending on
                               8759                 :                :      * whether the XLHP_CLEANUP_LOCK flag is set.  With an ordinary exclusive
                               8760                 :                :      * lock, we better not be doing anything that requires moving existing
                               8761                 :                :      * tuple data.
                               8762                 :                :      */
                               8763   [ +  +  -  + ]:          13170 :     Assert((xlrec.flags & XLHP_CLEANUP_LOCK) != 0 ||
                               8764                 :                :            (xlrec.flags & (XLHP_HAS_REDIRECTIONS | XLHP_HAS_DEAD_ITEMS)) == 0);
                               8765                 :                : 
                               8766                 :                :     /*
                               8767                 :                :      * We are about to remove and/or freeze tuples.  In Hot Standby mode,
                               8768                 :                :      * ensure that there are no queries running for which the removed tuples
                               8769                 :                :      * are still visible or which still consider the frozen xids as running.
                               8770                 :                :      * The conflict horizon XID comes after xl_heap_prune.
                               8771                 :                :      */
                               8772         [ +  + ]:          13170 :     if ((xlrec.flags & XLHP_HAS_CONFLICT_HORIZON) != 0)
                               8773                 :                :     {
                               8774                 :                :         TransactionId snapshot_conflict_horizon;
                               8775                 :                : 
                               8776                 :                :         /* memcpy() because snapshot_conflict_horizon is stored unaligned */
                               8777                 :           8826 :         memcpy(&snapshot_conflict_horizon, maindataptr, sizeof(TransactionId));
                               8778                 :           8826 :         maindataptr += sizeof(TransactionId);
                               8779                 :                : 
                               8780         [ +  + ]:           8826 :         if (InHotStandby)
                               8781                 :           8636 :             ResolveRecoveryConflictWithSnapshot(snapshot_conflict_horizon,
                               8782                 :           8636 :                                                 (xlrec.flags & XLHP_IS_CATALOG_REL) != 0,
                               8783                 :                :                                                 rlocator);
                               8784                 :                :     }
                               8785                 :                : 
                               8786                 :                :     /*
                               8787                 :                :      * If we have a full-page image, restore it and we're done.
                               8788                 :                :      */
                               8789                 :          13170 :     action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL,
                               8790                 :          13170 :                                            (xlrec.flags & XLHP_CLEANUP_LOCK) != 0,
                               8791                 :                :                                            &buffer);
 3532 heikki.linnakangas@i     8792         [ +  + ]:CBC       13170 :     if (action == BLK_NEEDS_REDO)
                               8793                 :                :     {
 2916 kgrittn@postgresql.o     8794                 :          11958 :         Page        page = (Page) BufferGetPage(buffer);
                               8795                 :                :         OffsetNumber *redirected;
                               8796                 :                :         OffsetNumber *nowdead;
                               8797                 :                :         OffsetNumber *nowunused;
                               8798                 :                :         int         nredirected;
                               8799                 :                :         int         ndead;
                               8800                 :                :         int         nunused;
                               8801                 :                :         int         nplans;
                               8802                 :                :         Size        datalen;
                               8803                 :                :         xlhp_freeze_plan *plans;
                               8804                 :                :         OffsetNumber *frz_offsets;
   20 heikki.linnakangas@i     8805                 :GNC       11958 :         char       *dataptr = XLogRecGetBlockData(record, 0, &datalen);
                               8806                 :                : 
                               8807                 :          11958 :         heap_xlog_deserialize_prune_and_freeze(dataptr, xlrec.flags,
                               8808                 :                :                                                &nplans, &plans, &frz_offsets,
                               8809                 :                :                                                &nredirected, &redirected,
                               8810                 :                :                                                &ndead, &nowdead,
                               8811                 :                :                                                &nunused, &nowunused);
                               8812                 :                : 
                               8813                 :                :         /*
                               8814                 :                :          * Update all line pointers per the record, and repair fragmentation
                               8815                 :                :          * if needed.
                               8816                 :                :          */
                               8817   [ +  +  +  +  :          11958 :         if (nredirected > 0 || ndead > 0 || nunused > 0)
                                              +  + ]
                               8818                 :          11721 :             heap_page_prune_execute(buffer,
                               8819                 :          11721 :                                     (xlrec.flags & XLHP_CLEANUP_LOCK) == 0,
                               8820                 :                :                                     redirected, nredirected,
                               8821                 :                :                                     nowdead, ndead,
                               8822                 :                :                                     nowunused, nunused);
                               8823                 :                : 
                               8824                 :                :         /* Freeze tuples */
                               8825         [ +  + ]:          12551 :         for (int p = 0; p < nplans; p++)
                               8826                 :                :         {
                               8827                 :                :             HeapTupleFreeze frz;
                               8828                 :                : 
                               8829                 :                :             /*
                               8830                 :                :              * Convert freeze plan representation from WAL record into
                               8831                 :                :              * per-tuple format used by heap_execute_freeze_tuple
                               8832                 :                :              */
                               8833                 :            593 :             frz.xmax = plans[p].xmax;
                               8834                 :            593 :             frz.t_infomask2 = plans[p].t_infomask2;
                               8835                 :            593 :             frz.t_infomask = plans[p].t_infomask;
                               8836                 :            593 :             frz.frzflags = plans[p].frzflags;
                               8837                 :            593 :             frz.offset = InvalidOffsetNumber;   /* unused, but be tidy */
                               8838                 :                : 
                               8839         [ +  + ]:          20660 :             for (int i = 0; i < plans[p].ntuples; i++)
                               8840                 :                :             {
                               8841                 :          20067 :                 OffsetNumber offset = *(frz_offsets++);
                               8842                 :                :                 ItemId      lp;
                               8843                 :                :                 HeapTupleHeader tuple;
                               8844                 :                : 
                               8845                 :          20067 :                 lp = PageGetItemId(page, offset);
                               8846                 :          20067 :                 tuple = (HeapTupleHeader) PageGetItem(page, lp);
                               8847                 :          20067 :                 heap_execute_freeze_tuple(tuple, &frz);
                               8848                 :                :             }
                               8849                 :                :         }
                               8850                 :                : 
                               8851                 :                :         /* There should be no more data */
                               8852         [ -  + ]:          11958 :         Assert((char *) frz_offsets == dataptr + datalen);
                               8853                 :                : 
                               8854                 :                :         /*
                               8855                 :                :          * Note: we don't worry about updating the page's prunability hints.
                               8856                 :                :          * At worst this will cause an extra prune cycle to occur soon.
                               8857                 :                :          */
                               8858                 :                : 
 1104 pg@bowt.ie               8859                 :CBC       11958 :         PageSetLSN(page, lsn);
                               8860                 :          11958 :         MarkBufferDirty(buffer);
                               8861                 :                :     }
                               8862                 :                : 
                               8863                 :                :     /*
                               8864                 :                :      * If we released any space or line pointers, update the free space map.
                               8865                 :                :      *
                               8866                 :                :      * Do this regardless of a full-page image being applied, since the FSM
                               8867                 :                :      * data is not in the page anyway.
                               8868                 :                :      */
                               8869         [ +  - ]:          13170 :     if (BufferIsValid(buffer))
                               8870                 :                :     {
   20 heikki.linnakangas@i     8871         [ +  + ]:GNC       13170 :         if (xlrec.flags & (XLHP_HAS_REDIRECTIONS |
                               8872                 :                :                            XLHP_HAS_DEAD_ITEMS |
                               8873                 :                :                            XLHP_HAS_NOW_UNUSED_ITEMS))
                               8874                 :                :         {
                               8875                 :          12932 :             Size        freespace = PageGetHeapFreeSpace(BufferGetPage(buffer));
                               8876                 :                : 
                               8877                 :          12932 :             UnlockReleaseBuffer(buffer);
                               8878                 :                : 
                               8879                 :          12932 :             XLogRecordPageWithFreeSpace(rlocator, blkno, freespace);
                               8880                 :                :         }
                               8881                 :                :         else
                               8882                 :            238 :             UnlockReleaseBuffer(buffer);
                               8883                 :                :     }
 1104 pg@bowt.ie               8884                 :CBC       13170 : }
                               8885                 :                : 
                               8886                 :                : /*
                               8887                 :                :  * Replay XLOG_HEAP2_VISIBLE record.
                               8888                 :                :  *
                               8889                 :                :  * The critical integrity requirement here is that we must never end up with
                               8890                 :                :  * a situation where the visibility map bit is set, and the page-level
                               8891                 :                :  * PD_ALL_VISIBLE bit is clear.  If that were to occur, then a subsequent
                               8892                 :                :  * page modification would fail to clear the visibility map bit.
                               8893                 :                :  */
                               8894                 :                : static void
 3433 heikki.linnakangas@i     8895                 :           7594 : heap_xlog_visible(XLogReaderState *record)
                               8896                 :                : {
                               8897                 :           7594 :     XLogRecPtr  lsn = record->EndRecPtr;
 4681 rhaas@postgresql.org     8898                 :           7594 :     xl_heap_visible *xlrec = (xl_heap_visible *) XLogRecGetData(record);
 3433 heikki.linnakangas@i     8899                 :           7594 :     Buffer      vmbuffer = InvalidBuffer;
                               8900                 :                :     Buffer      buffer;
                               8901                 :                :     Page        page;
                               8902                 :                :     RelFileLocator rlocator;
                               8903                 :                :     BlockNumber blkno;
                               8904                 :                :     XLogRedoAction action;
                               8905                 :                : 
  378 andres@anarazel.de       8906         [ -  + ]:           7594 :     Assert((xlrec->flags & VISIBILITYMAP_XLOG_VALID_BITS) == xlrec->flags);
                               8907                 :                : 
  648 rhaas@postgresql.org     8908                 :           7594 :     XLogRecGetBlockTag(record, 1, &rlocator, NULL, &blkno);
                               8909                 :                : 
                               8910                 :                :     /*
                               8911                 :                :      * If there are any Hot Standby transactions running that have an xmin
                               8912                 :                :      * horizon old enough that this page isn't all-visible for them, they
                               8913                 :                :      * might incorrectly decide that an index-only scan can skip a heap fetch.
                               8914                 :                :      *
                               8915                 :                :      * NB: It might be better to throw some kind of "soft" conflict here that
                               8916                 :                :      * forces any index-only scan that is in flight to perform heap fetches,
                               8917                 :                :      * rather than killing the transaction outright.
                               8918                 :                :      */
 4336 simon@2ndQuadrant.co     8919         [ +  + ]:           7594 :     if (InHotStandby)
  514 pg@bowt.ie               8920                 :           7420 :         ResolveRecoveryConflictWithSnapshot(xlrec->snapshotConflictHorizon,
  373 andres@anarazel.de       8921                 :           7420 :                                             xlrec->flags & VISIBILITYMAP_XLOG_CATALOG_REL,
                               8922                 :                :                                             rlocator);
                               8923                 :                : 
                               8924                 :                :     /*
                               8925                 :                :      * Read the heap page, if it still exists. If the heap file has dropped or
                               8926                 :                :      * truncated later in recovery, we don't need to update the page, but we'd
                               8927                 :                :      * better still update the visibility map.
                               8928                 :                :      */
 3433 heikki.linnakangas@i     8929                 :           7594 :     action = XLogReadBufferForRedo(record, 1, &buffer);
 3532                          8930         [ +  + ]:           7594 :     if (action == BLK_NEEDS_REDO)
                               8931                 :                :     {
                               8932                 :                :         /*
                               8933                 :                :          * We don't bump the LSN of the heap page when setting the visibility
                               8934                 :                :          * map bit (unless checksums or wal_hint_bits is enabled, in which
                               8935                 :                :          * case we must). This exposes us to torn page hazards, but since
                               8936                 :                :          * we're not inspecting the existing page contents in any way, we
                               8937                 :                :          * don't care.
                               8938                 :                :          */
 2916 kgrittn@postgresql.o     8939                 :           5744 :         page = BufferGetPage(buffer);
                               8940                 :                : 
 2959 rhaas@postgresql.org     8941                 :           5744 :         PageSetAllVisible(page);
                               8942                 :                : 
  521 jdavis@postgresql.or     8943   [ +  -  +  + ]:           5744 :         if (XLogHintBitIsNeeded())
                               8944                 :           5654 :             PageSetLSN(page, lsn);
                               8945                 :                : 
 3532 heikki.linnakangas@i     8946                 :           5744 :         MarkBufferDirty(buffer);
                               8947                 :                :     }
                               8948                 :                :     else if (action == BLK_RESTORED)
                               8949                 :                :     {
                               8950                 :                :         /*
                               8951                 :                :          * If heap block was backed up, we already restored it and there's
                               8952                 :                :          * nothing more to do. (This can only happen with checksums or
                               8953                 :                :          * wal_log_hints enabled.)
                               8954                 :                :          */
                               8955                 :                :     }
                               8956                 :                : 
                               8957         [ +  + ]:           7594 :     if (BufferIsValid(buffer))
                               8958                 :                :     {
 2069 alvherre@alvh.no-ip.     8959                 :           7549 :         Size        space = PageGetFreeSpace(BufferGetPage(buffer));
                               8960                 :                : 
 3532 heikki.linnakangas@i     8961                 :           7549 :         UnlockReleaseBuffer(buffer);
                               8962                 :                : 
                               8963                 :                :         /*
                               8964                 :                :          * Since FSM is not WAL-logged and only updated heuristically, it
                               8965                 :                :          * easily becomes stale in standbys.  If the standby is later promoted
                               8966                 :                :          * and runs VACUUM, it will skip updating individual free space
                               8967                 :                :          * figures for pages that became all-visible (or all-frozen, depending
                               8968                 :                :          * on the vacuum mode,) which is troublesome when FreeSpaceMapVacuum
                               8969                 :                :          * propagates too optimistic free space values to upper FSM layers;
                               8970                 :                :          * later inserters try to use such pages only to find out that they
                               8971                 :                :          * are unusable.  This can cause long stalls when there are many such
                               8972                 :                :          * pages.
                               8973                 :                :          *
                               8974                 :                :          * Forestall those problems by updating FSM's idea about a page that
                               8975                 :                :          * is becoming all-visible or all-frozen.
                               8976                 :                :          *
                               8977                 :                :          * Do this regardless of a full-page image being applied, since the
                               8978                 :                :          * FSM data is not in the page anyway.
                               8979                 :                :          */
 2069 alvherre@alvh.no-ip.     8980         [ +  - ]:           7549 :         if (xlrec->flags & VISIBILITYMAP_VALID_BITS)
  648 rhaas@postgresql.org     8981                 :           7549 :             XLogRecordPageWithFreeSpace(rlocator, blkno, space);
                               8982                 :                :     }
                               8983                 :                : 
                               8984                 :                :     /*
                               8985                 :                :      * Even if we skipped the heap page update due to the LSN interlock, it's
                               8986                 :                :      * still safe to update the visibility map.  Any WAL record that clears
                               8987                 :                :      * the visibility map bit does so before checking the page LSN, so any
                               8988                 :                :      * bits that need to be cleared will still be cleared.
                               8989                 :                :      */
 3433 heikki.linnakangas@i     8990         [ +  + ]:           7594 :     if (XLogReadBufferForRedoExtended(record, 0, RBM_ZERO_ON_ERROR, false,
                               8991                 :                :                                       &vmbuffer) == BLK_NEEDS_REDO)
                               8992                 :                :     {
 2916 kgrittn@postgresql.o     8993                 :           7325 :         Page        vmpage = BufferGetPage(vmbuffer);
                               8994                 :                :         Relation    reln;
                               8995                 :                :         uint8       vmbits;
                               8996                 :                : 
                               8997                 :                :         /* initialize the page if it was read as zeros */
 3433 heikki.linnakangas@i     8998         [ -  + ]:           7325 :         if (PageIsNew(vmpage))
 3433 heikki.linnakangas@i     8999                 :UBC           0 :             PageInit(vmpage, BLCKSZ, 0);
                               9000                 :                : 
                               9001                 :                :         /* remove VISIBILITYMAP_XLOG_* */
  378 andres@anarazel.de       9002                 :CBC        7325 :         vmbits = xlrec->flags & VISIBILITYMAP_VALID_BITS;
                               9003                 :                : 
                               9004                 :                :         /*
                               9005                 :                :          * XLogReadBufferForRedoExtended locked the buffer. But
                               9006                 :                :          * visibilitymap_set will handle locking itself.
                               9007                 :                :          */
 3433 heikki.linnakangas@i     9008                 :           7325 :         LockBuffer(vmbuffer, BUFFER_LOCK_UNLOCK);
                               9009                 :                : 
  648 rhaas@postgresql.org     9010                 :           7325 :         reln = CreateFakeRelcacheEntry(rlocator);
 3532 heikki.linnakangas@i     9011                 :           7325 :         visibilitymap_pin(reln, blkno, &vmbuffer);
                               9012                 :                : 
  520 jdavis@postgresql.or     9013                 :           7325 :         visibilitymap_set(reln, blkno, InvalidBuffer, lsn, vmbuffer,
                               9014                 :                :                           xlrec->snapshotConflictHorizon, vmbits);
                               9015                 :                : 
 4681 rhaas@postgresql.org     9016                 :           7325 :         ReleaseBuffer(vmbuffer);
                               9017                 :           7325 :         FreeFakeRelcacheEntry(reln);
                               9018                 :                :     }
 3433 heikki.linnakangas@i     9019         [ +  - ]:            269 :     else if (BufferIsValid(vmbuffer))
                               9020                 :            269 :         UnlockReleaseBuffer(vmbuffer);
 4681 rhaas@postgresql.org     9021                 :           7594 : }
                               9022                 :                : 
                               9023                 :                : /*
                               9024                 :                :  * Given an "infobits" field from an XLog record, set the correct bits in the
                               9025                 :                :  * given infomask and infomask2 for the tuple touched by the record.
                               9026                 :                :  *
                               9027                 :                :  * (This is the reverse of compute_infobits).
                               9028                 :                :  */
                               9029                 :                : static void
 4099 alvherre@alvh.no-ip.     9030                 :         481432 : fix_infomask_from_infobits(uint8 infobits, uint16 *infomask, uint16 *infomask2)
                               9031                 :                : {
                               9032                 :         481432 :     *infomask &= ~(HEAP_XMAX_IS_MULTI | HEAP_XMAX_LOCK_ONLY |
                               9033                 :                :                    HEAP_XMAX_KEYSHR_LOCK | HEAP_XMAX_EXCL_LOCK);
                               9034                 :         481432 :     *infomask2 &= ~HEAP_KEYS_UPDATED;
                               9035                 :                : 
                               9036         [ +  + ]:         481432 :     if (infobits & XLHL_XMAX_IS_MULTI)
                               9037                 :              2 :         *infomask |= HEAP_XMAX_IS_MULTI;
                               9038         [ +  + ]:         481432 :     if (infobits & XLHL_XMAX_LOCK_ONLY)
                               9039                 :          54763 :         *infomask |= HEAP_XMAX_LOCK_ONLY;
                               9040         [ +  + ]:         481432 :     if (infobits & XLHL_XMAX_EXCL_LOCK)
                               9041                 :          54381 :         *infomask |= HEAP_XMAX_EXCL_LOCK;
                               9042                 :                :     /* note HEAP_XMAX_SHR_LOCK isn't considered here */
                               9043         [ +  + ]:         481432 :     if (infobits & XLHL_XMAX_KEYSHR_LOCK)
                               9044                 :            393 :         *infomask |= HEAP_XMAX_KEYSHR_LOCK;
                               9045                 :                : 
                               9046         [ +  + ]:         481432 :     if (infobits & XLHL_KEYS_UPDATED)
                               9047                 :         336013 :         *infomask2 |= HEAP_KEYS_UPDATED;
                               9048                 :         481432 : }
                               9049                 :                : 
                               9050                 :                : static void
 3433 heikki.linnakangas@i     9051                 :         334896 : heap_xlog_delete(XLogReaderState *record)
                               9052                 :                : {
                               9053                 :         334896 :     XLogRecPtr  lsn = record->EndRecPtr;
 8424 bruce@momjian.us         9054                 :         334896 :     xl_heap_delete *xlrec = (xl_heap_delete *) XLogRecGetData(record);
                               9055                 :                :     Buffer      buffer;
                               9056                 :                :     Page        page;
                               9057                 :         334896 :     ItemId      lp = NULL;
                               9058                 :                :     HeapTupleHeader htup;
                               9059                 :                :     BlockNumber blkno;
                               9060                 :                :     RelFileLocator target_locator;
                               9061                 :                :     ItemPointerData target_tid;
                               9062                 :                : 
  648 rhaas@postgresql.org     9063                 :         334896 :     XLogRecGetBlockTag(record, 0, &target_locator, NULL, &blkno);
 3433 heikki.linnakangas@i     9064                 :         334896 :     ItemPointerSetBlockNumber(&target_tid, blkno);
                               9065                 :         334896 :     ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
                               9066                 :                : 
                               9067                 :                :     /*
                               9068                 :                :      * The visibility map may need to be fixed even if the heap page is
                               9069                 :                :      * already up-to-date.
                               9070                 :                :      */
 3264 andres@anarazel.de       9071         [ +  + ]:         334896 :     if (xlrec->flags & XLH_DELETE_ALL_VISIBLE_CLEARED)
                               9072                 :                :     {
  648 rhaas@postgresql.org     9073                 :             21 :         Relation    reln = CreateFakeRelcacheEntry(target_locator);
 4681                          9074                 :             21 :         Buffer      vmbuffer = InvalidBuffer;
                               9075                 :                : 
                               9076                 :             21 :         visibilitymap_pin(reln, blkno, &vmbuffer);
 2827 andres@anarazel.de       9077                 :             21 :         visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
 4681 rhaas@postgresql.org     9078                 :             21 :         ReleaseBuffer(vmbuffer);
 5611 heikki.linnakangas@i     9079                 :             21 :         FreeFakeRelcacheEntry(reln);
                               9080                 :                :     }
                               9081                 :                : 
 3433                          9082         [ +  + ]:         334896 :     if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
                               9083                 :                :     {
 2916 kgrittn@postgresql.o     9084                 :         334751 :         page = BufferGetPage(buffer);
                               9085                 :                : 
 3433 heikki.linnakangas@i     9086         [ +  - ]:         334751 :         if (PageGetMaxOffsetNumber(page) >= xlrec->offnum)
                               9087                 :         334751 :             lp = PageGetItemId(page, xlrec->offnum);
                               9088                 :                : 
                               9089   [ +  -  -  + ]:         334751 :         if (PageGetMaxOffsetNumber(page) < xlrec->offnum || !ItemIdIsNormal(lp))
 3069 andres@anarazel.de       9090         [ #  # ]:UBC           0 :             elog(PANIC, "invalid lp");
                               9091                 :                : 
 3532 heikki.linnakangas@i     9092                 :CBC      334751 :         htup = (HeapTupleHeader) PageGetItem(page, lp);
                               9093                 :                : 
                               9094                 :         334751 :         htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               9095                 :         334751 :         htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               9096                 :         334751 :         HeapTupleHeaderClearHotUpdated(htup);
                               9097                 :         334751 :         fix_infomask_from_infobits(xlrec->infobits_set,
                               9098                 :                :                                    &htup->t_infomask, &htup->t_infomask2);
 3264 andres@anarazel.de       9099         [ +  - ]:         334751 :         if (!(xlrec->flags & XLH_DELETE_IS_SUPER))
                               9100                 :         334751 :             HeapTupleHeaderSetXmax(htup, xlrec->xmax);
                               9101                 :                :         else
 3264 andres@anarazel.de       9102                 :UBC           0 :             HeapTupleHeaderSetXmin(htup, InvalidTransactionId);
 3532 heikki.linnakangas@i     9103         [ -  + ]:CBC      334751 :         HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
                               9104                 :                : 
                               9105                 :                :         /* Mark the page as a candidate for pruning */
 3433                          9106   [ -  +  +  +  :         334751 :         PageSetPrunable(page, XLogRecGetXid(record));
                                              +  + ]
                               9107                 :                : 
 3264 andres@anarazel.de       9108         [ +  + ]:         334751 :         if (xlrec->flags & XLH_DELETE_ALL_VISIBLE_CLEARED)
 3532 heikki.linnakangas@i     9109                 :             17 :             PageClearAllVisible(page);
                               9110                 :                : 
                               9111                 :                :         /* Make sure t_ctid is set correctly */
 2199 andres@anarazel.de       9112         [ +  + ]:         334751 :         if (xlrec->flags & XLH_DELETE_IS_PARTITION_MOVE)
                               9113                 :            132 :             HeapTupleHeaderSetMovedPartitions(htup);
                               9114                 :                :         else
                               9115                 :         334619 :             htup->t_ctid = target_tid;
 3532 heikki.linnakangas@i     9116                 :         334751 :         PageSetLSN(page, lsn);
                               9117                 :         334751 :         MarkBufferDirty(buffer);
                               9118                 :                :     }
                               9119         [ +  - ]:         334896 :     if (BufferIsValid(buffer))
                               9120                 :         334896 :         UnlockReleaseBuffer(buffer);
 8685 vadim4o@yahoo.com        9121                 :         334896 : }
                               9122                 :                : 
                               9123                 :                : static void
 3433 heikki.linnakangas@i     9124                 :        1423598 : heap_xlog_insert(XLogReaderState *record)
                               9125                 :                : {
                               9126                 :        1423598 :     XLogRecPtr  lsn = record->EndRecPtr;
 8424 bruce@momjian.us         9127                 :        1423598 :     xl_heap_insert *xlrec = (xl_heap_insert *) XLogRecGetData(record);
                               9128                 :                :     Buffer      buffer;
                               9129                 :                :     Page        page;
                               9130                 :                :     union
                               9131                 :                :     {
                               9132                 :                :         HeapTupleHeaderData hdr;
                               9133                 :                :         char        data[MaxHeapTupleSize];
                               9134                 :                :     }           tbuf;
                               9135                 :                :     HeapTupleHeader htup;
                               9136                 :                :     xl_heap_header xlhdr;
                               9137                 :                :     uint32      newlen;
 3532 heikki.linnakangas@i     9138                 :        1423598 :     Size        freespace = 0;
                               9139                 :                :     RelFileLocator target_locator;
                               9140                 :                :     BlockNumber blkno;
                               9141                 :                :     ItemPointerData target_tid;
                               9142                 :                :     XLogRedoAction action;
                               9143                 :                : 
  648 rhaas@postgresql.org     9144                 :        1423598 :     XLogRecGetBlockTag(record, 0, &target_locator, NULL, &blkno);
 3433 heikki.linnakangas@i     9145                 :        1423598 :     ItemPointerSetBlockNumber(&target_tid, blkno);
                               9146                 :        1423598 :     ItemPointerSetOffsetNumber(&target_tid, xlrec->offnum);
                               9147                 :                : 
                               9148                 :                :     /*
                               9149                 :                :      * The visibility map may need to be fixed even if the heap page is
                               9150                 :                :      * already up-to-date.
                               9151                 :                :      */
 3264 andres@anarazel.de       9152         [ +  + ]:        1423598 :     if (xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED)
                               9153                 :                :     {
  648 rhaas@postgresql.org     9154                 :           2307 :         Relation    reln = CreateFakeRelcacheEntry(target_locator);
 4681                          9155                 :           2307 :         Buffer      vmbuffer = InvalidBuffer;
                               9156                 :                : 
                               9157                 :           2307 :         visibilitymap_pin(reln, blkno, &vmbuffer);
 2827 andres@anarazel.de       9158                 :           2307 :         visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
 4681 rhaas@postgresql.org     9159                 :           2307 :         ReleaseBuffer(vmbuffer);
 5611 heikki.linnakangas@i     9160                 :           2307 :         FreeFakeRelcacheEntry(reln);
                               9161                 :                :     }
                               9162                 :                : 
                               9163                 :                :     /*
                               9164                 :                :      * If we inserted the first and only tuple on the page, re-initialize the
                               9165                 :                :      * page from scratch.
                               9166                 :                :      */
 3433                          9167         [ +  + ]:        1423598 :     if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
                               9168                 :                :     {
                               9169                 :          18114 :         buffer = XLogInitBufferForRedo(record, 0);
 2916 kgrittn@postgresql.o     9170                 :          18114 :         page = BufferGetPage(buffer);
 6591 tgl@sss.pgh.pa.us        9171                 :          18114 :         PageInit(page, BufferGetPageSize(buffer), 0);
 3532 heikki.linnakangas@i     9172                 :          18114 :         action = BLK_NEEDS_REDO;
                               9173                 :                :     }
                               9174                 :                :     else
 3433                          9175                 :        1405484 :         action = XLogReadBufferForRedo(record, 0, &buffer);
 3532                          9176         [ +  + ]:        1423598 :     if (action == BLK_NEEDS_REDO)
                               9177                 :                :     {
                               9178                 :                :         Size        datalen;
                               9179                 :                :         char       *data;
                               9180                 :                : 
 2916 kgrittn@postgresql.o     9181                 :        1422816 :         page = BufferGetPage(buffer);
                               9182                 :                : 
 3433 heikki.linnakangas@i     9183         [ -  + ]:        1422816 :         if (PageGetMaxOffsetNumber(page) + 1 < xlrec->offnum)
 3069 andres@anarazel.de       9184         [ #  # ]:UBC           0 :             elog(PANIC, "invalid max offset number");
                               9185                 :                : 
 3433 heikki.linnakangas@i     9186                 :CBC     1422816 :         data = XLogRecGetBlockData(record, 0, &datalen);
                               9187                 :                : 
                               9188                 :        1422816 :         newlen = datalen - SizeOfHeapHeader;
                               9189   [ +  -  -  + ]:        1422816 :         Assert(datalen > SizeOfHeapHeader && newlen <= MaxHeapTupleSize);
                               9190                 :        1422816 :         memcpy((char *) &xlhdr, data, SizeOfHeapHeader);
                               9191                 :        1422816 :         data += SizeOfHeapHeader;
                               9192                 :                : 
 3532                          9193                 :        1422816 :         htup = &tbuf.hdr;
 3340 tgl@sss.pgh.pa.us        9194   [ +  -  -  +  :        1422816 :         MemSet((char *) htup, 0, SizeofHeapTupleHeader);
                                     -  -  -  -  -  
                                                 - ]
                               9195                 :                :         /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
                               9196                 :        1422816 :         memcpy((char *) htup + SizeofHeapTupleHeader,
                               9197                 :                :                data,
                               9198                 :                :                newlen);
                               9199                 :        1422816 :         newlen += SizeofHeapTupleHeader;
 3532 heikki.linnakangas@i     9200                 :        1422816 :         htup->t_infomask2 = xlhdr.t_infomask2;
                               9201                 :        1422816 :         htup->t_infomask = xlhdr.t_infomask;
                               9202                 :        1422816 :         htup->t_hoff = xlhdr.t_hoff;
 3433                          9203                 :        1422816 :         HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
 3532                          9204         [ -  + ]:        1422816 :         HeapTupleHeaderSetCmin(htup, FirstCommandId);
 3433                          9205                 :        1422816 :         htup->t_ctid = target_tid;
                               9206                 :                : 
                               9207         [ -  + ]:        1422816 :         if (PageAddItem(page, (Item) htup, newlen, xlrec->offnum,
                               9208                 :                :                         true, true) == InvalidOffsetNumber)
 3069 andres@anarazel.de       9209         [ #  # ]:UBC           0 :             elog(PANIC, "failed to add tuple");
                               9210                 :                : 
 3532 heikki.linnakangas@i     9211                 :CBC     1422816 :         freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
                               9212                 :                : 
                               9213                 :        1422816 :         PageSetLSN(page, lsn);
                               9214                 :                : 
 3264 andres@anarazel.de       9215         [ +  + ]:        1422816 :         if (xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED)
 3532 heikki.linnakangas@i     9216                 :           1992 :             PageClearAllVisible(page);
                               9217                 :                : 
                               9218                 :                :         /* XLH_INSERT_ALL_FROZEN_SET implies that all tuples are visible */
 1183 tomas.vondra@postgre     9219         [ -  + ]:        1422816 :         if (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)
 1183 tomas.vondra@postgre     9220                 :UBC           0 :             PageSetAllVisible(page);
                               9221                 :                : 
 3532 heikki.linnakangas@i     9222                 :CBC     1422816 :         MarkBufferDirty(buffer);
                               9223                 :                :     }
                               9224         [ +  - ]:        1423598 :     if (BufferIsValid(buffer))
                               9225                 :        1423598 :         UnlockReleaseBuffer(buffer);
                               9226                 :                : 
                               9227                 :                :     /*
                               9228                 :                :      * If the page is running low on free space, update the FSM as well.
                               9229                 :                :      * Arbitrarily, our definition of "low" is less than 20%. We can't do much
                               9230                 :                :      * better than that without knowing the fill-factor for the table.
                               9231                 :                :      *
                               9232                 :                :      * XXX: Don't do this if the page was restored from full page image. We
                               9233                 :                :      * don't bother to update the FSM in that case, it doesn't need to be
                               9234                 :                :      * totally accurate anyway.
                               9235                 :                :      */
                               9236   [ +  +  +  + ]:        1423598 :     if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
  648 rhaas@postgresql.org     9237                 :         311033 :         XLogRecordPageWithFreeSpace(target_locator, blkno, freespace);
 8620 vadim4o@yahoo.com        9238                 :        1423598 : }
                               9239                 :                : 
                               9240                 :                : /*
                               9241                 :                :  * Handles MULTI_INSERT record type.
                               9242                 :                :  */
                               9243                 :                : static void
 3433 heikki.linnakangas@i     9244                 :          52736 : heap_xlog_multi_insert(XLogReaderState *record)
                               9245                 :                : {
                               9246                 :          52736 :     XLogRecPtr  lsn = record->EndRecPtr;
                               9247                 :                :     xl_heap_multi_insert *xlrec;
                               9248                 :                :     RelFileLocator rlocator;
                               9249                 :                :     BlockNumber blkno;
                               9250                 :                :     Buffer      buffer;
                               9251                 :                :     Page        page;
                               9252                 :                :     union
                               9253                 :                :     {
                               9254                 :                :         HeapTupleHeaderData hdr;
                               9255                 :                :         char        data[MaxHeapTupleSize];
                               9256                 :                :     }           tbuf;
                               9257                 :                :     HeapTupleHeader htup;
                               9258                 :                :     uint32      newlen;
 3532                          9259                 :          52736 :     Size        freespace = 0;
                               9260                 :                :     int         i;
 3433                          9261                 :          52736 :     bool        isinit = (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE) != 0;
                               9262                 :                :     XLogRedoAction action;
                               9263                 :                : 
                               9264                 :                :     /*
                               9265                 :                :      * Insertion doesn't overwrite MVCC data, so no conflict processing is
                               9266                 :                :      * required.
                               9267                 :                :      */
                               9268                 :          52736 :     xlrec = (xl_heap_multi_insert *) XLogRecGetData(record);
                               9269                 :                : 
  648 rhaas@postgresql.org     9270                 :          52736 :     XLogRecGetBlockTag(record, 0, &rlocator, NULL, &blkno);
                               9271                 :                : 
                               9272                 :                :     /* check that the mutually exclusive flags are not both set */
 1068 tgl@sss.pgh.pa.us        9273   [ +  +  -  + ]:          52736 :     Assert(!((xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED) &&
                               9274                 :                :              (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)));
                               9275                 :                : 
                               9276                 :                :     /*
                               9277                 :                :      * The visibility map may need to be fixed even if the heap page is
                               9278                 :                :      * already up-to-date.
                               9279                 :                :      */
 3264 andres@anarazel.de       9280         [ +  + ]:          52736 :     if (xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED)
                               9281                 :                :     {
  648 rhaas@postgresql.org     9282                 :            964 :         Relation    reln = CreateFakeRelcacheEntry(rlocator);
 4540 heikki.linnakangas@i     9283                 :            964 :         Buffer      vmbuffer = InvalidBuffer;
                               9284                 :                : 
                               9285                 :            964 :         visibilitymap_pin(reln, blkno, &vmbuffer);
 2827 andres@anarazel.de       9286                 :            964 :         visibilitymap_clear(reln, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS);
 4540 heikki.linnakangas@i     9287                 :            964 :         ReleaseBuffer(vmbuffer);
                               9288                 :            964 :         FreeFakeRelcacheEntry(reln);
                               9289                 :                :     }
                               9290                 :                : 
                               9291         [ +  + ]:          52736 :     if (isinit)
                               9292                 :                :     {
 3433                          9293                 :           1727 :         buffer = XLogInitBufferForRedo(record, 0);
 2916 kgrittn@postgresql.o     9294                 :           1727 :         page = BufferGetPage(buffer);
 4540 heikki.linnakangas@i     9295                 :           1727 :         PageInit(page, BufferGetPageSize(buffer), 0);
 3532                          9296                 :           1727 :         action = BLK_NEEDS_REDO;
                               9297                 :                :     }
                               9298                 :                :     else
 3433                          9299                 :          51009 :         action = XLogReadBufferForRedo(record, 0, &buffer);
 3532                          9300         [ +  + ]:          52736 :     if (action == BLK_NEEDS_REDO)
                               9301                 :                :     {
                               9302                 :                :         char       *tupdata;
                               9303                 :                :         char       *endptr;
                               9304                 :                :         Size        len;
                               9305                 :                : 
                               9306                 :                :         /* Tuples are stored as block data */
 3433                          9307                 :          52130 :         tupdata = XLogRecGetBlockData(record, 0, &len);
                               9308                 :          52130 :         endptr = tupdata + len;
                               9309                 :                : 
 2916 kgrittn@postgresql.o     9310                 :          52130 :         page = (Page) BufferGetPage(buffer);
                               9311                 :                : 
 3532 heikki.linnakangas@i     9312         [ +  + ]:         252665 :         for (i = 0; i < xlrec->ntuples; i++)
                               9313                 :                :         {
                               9314                 :                :             OffsetNumber offnum;
                               9315                 :                :             xl_multi_insert_tuple *xlhdr;
                               9316                 :                : 
                               9317                 :                :             /*
                               9318                 :                :              * If we're reinitializing the page, the tuples are stored in
                               9319                 :                :              * order from FirstOffsetNumber. Otherwise there's an array of
                               9320                 :                :              * offsets in the WAL record, and the tuples come after that.
                               9321                 :                :              */
                               9322         [ +  + ]:         200535 :             if (isinit)
                               9323                 :          99123 :                 offnum = FirstOffsetNumber + i;
                               9324                 :                :             else
                               9325                 :         101412 :                 offnum = xlrec->offsets[i];
                               9326         [ -  + ]:         200535 :             if (PageGetMaxOffsetNumber(page) + 1 < offnum)
 3069 andres@anarazel.de       9327         [ #  # ]:UBC           0 :                 elog(PANIC, "invalid max offset number");
                               9328                 :                : 
 3433 heikki.linnakangas@i     9329                 :CBC      200535 :             xlhdr = (xl_multi_insert_tuple *) SHORTALIGN(tupdata);
                               9330                 :         200535 :             tupdata = ((char *) xlhdr) + SizeOfMultiInsertTuple;
                               9331                 :                : 
 3532                          9332                 :         200535 :             newlen = xlhdr->datalen;
                               9333         [ -  + ]:         200535 :             Assert(newlen <= MaxHeapTupleSize);
                               9334                 :         200535 :             htup = &tbuf.hdr;
 3340 tgl@sss.pgh.pa.us        9335   [ +  -  -  +  :         200535 :             MemSet((char *) htup, 0, SizeofHeapTupleHeader);
                                     -  -  -  -  -  
                                                 - ]
                               9336                 :                :             /* PG73FORMAT: get bitmap [+ padding] [+ oid] + data */
                               9337                 :         200535 :             memcpy((char *) htup + SizeofHeapTupleHeader,
                               9338                 :                :                    (char *) tupdata,
                               9339                 :                :                    newlen);
 3433 heikki.linnakangas@i     9340                 :         200535 :             tupdata += newlen;
                               9341                 :                : 
 3340 tgl@sss.pgh.pa.us        9342                 :         200535 :             newlen += SizeofHeapTupleHeader;
 3532 heikki.linnakangas@i     9343                 :         200535 :             htup->t_infomask2 = xlhdr->t_infomask2;
                               9344                 :         200535 :             htup->t_infomask = xlhdr->t_infomask;
                               9345                 :         200535 :             htup->t_hoff = xlhdr->t_hoff;
 3433                          9346                 :         200535 :             HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
 3532                          9347         [ -  + ]:         200535 :             HeapTupleHeaderSetCmin(htup, FirstCommandId);
                               9348                 :         200535 :             ItemPointerSetBlockNumber(&htup->t_ctid, blkno);
                               9349                 :         200535 :             ItemPointerSetOffsetNumber(&htup->t_ctid, offnum);
                               9350                 :                : 
                               9351                 :         200535 :             offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
                               9352         [ -  + ]:         200535 :             if (offnum == InvalidOffsetNumber)
 3069 andres@anarazel.de       9353         [ #  # ]:UBC           0 :                 elog(PANIC, "failed to add tuple");
                               9354                 :                :         }
 3433 heikki.linnakangas@i     9355         [ -  + ]:CBC       52130 :         if (tupdata != endptr)
 3069 andres@anarazel.de       9356         [ #  # ]:UBC           0 :             elog(PANIC, "total tuple length mismatch");
                               9357                 :                : 
 3532 heikki.linnakangas@i     9358                 :CBC       52130 :         freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
                               9359                 :                : 
                               9360                 :          52130 :         PageSetLSN(page, lsn);
                               9361                 :                : 
 3264 andres@anarazel.de       9362         [ +  + ]:          52130 :         if (xlrec->flags & XLH_INSERT_ALL_VISIBLE_CLEARED)
 3532 heikki.linnakangas@i     9363                 :            537 :             PageClearAllVisible(page);
                               9364                 :                : 
                               9365                 :                :         /* XLH_INSERT_ALL_FROZEN_SET implies that all tuples are visible */
 1176 tomas.vondra@postgre     9366         [ +  + ]:          52130 :         if (xlrec->flags & XLH_INSERT_ALL_FROZEN_SET)
                               9367                 :              4 :             PageSetAllVisible(page);
                               9368                 :                : 
 3532 heikki.linnakangas@i     9369                 :          52130 :         MarkBufferDirty(buffer);
                               9370                 :                :     }
                               9371         [ +  - ]:          52736 :     if (BufferIsValid(buffer))
                               9372                 :          52736 :         UnlockReleaseBuffer(buffer);
                               9373                 :                : 
                               9374                 :                :     /*
                               9375                 :                :      * If the page is running low on free space, update the FSM as well.
                               9376                 :                :      * Arbitrarily, our definition of "low" is less than 20%. We can't do much
                               9377                 :                :      * better than that without knowing the fill-factor for the table.
                               9378                 :                :      *
                               9379                 :                :      * XXX: Don't do this if the page was restored from full page image. We
                               9380                 :                :      * don't bother to update the FSM in that case, it doesn't need to be
                               9381                 :                :      * totally accurate anyway.
                               9382                 :                :      */
                               9383   [ +  +  +  + ]:          52736 :     if (action == BLK_NEEDS_REDO && freespace < BLCKSZ / 5)
  648 rhaas@postgresql.org     9384                 :          14847 :         XLogRecordPageWithFreeSpace(rlocator, blkno, freespace);
 4540 heikki.linnakangas@i     9385                 :          52736 : }
                               9386                 :                : 
                               9387                 :                : /*
                               9388                 :                :  * Handles UPDATE and HOT_UPDATE
                               9389                 :                :  */
                               9390                 :                : static void
 3433                          9391                 :          91961 : heap_xlog_update(XLogReaderState *record, bool hot_update)
                               9392                 :                : {
                               9393                 :          91961 :     XLogRecPtr  lsn = record->EndRecPtr;
 8424 bruce@momjian.us         9394                 :          91961 :     xl_heap_update *xlrec = (xl_heap_update *) XLogRecGetData(record);
                               9395                 :                :     RelFileLocator rlocator;
                               9396                 :                :     BlockNumber oldblk;
                               9397                 :                :     BlockNumber newblk;
                               9398                 :                :     ItemPointerData newtid;
                               9399                 :                :     Buffer      obuffer,
                               9400                 :                :                 nbuffer;
                               9401                 :                :     Page        page;
                               9402                 :                :     OffsetNumber offnum;
                               9403                 :          91961 :     ItemId      lp = NULL;
                               9404                 :                :     HeapTupleData oldtup;
                               9405                 :                :     HeapTupleHeader htup;
 3686 heikki.linnakangas@i     9406                 :          91961 :     uint16      prefixlen = 0,
                               9407                 :          91961 :                 suffixlen = 0;
                               9408                 :                :     char       *newp;
                               9409                 :                :     union
                               9410                 :                :     {
                               9411                 :                :         HeapTupleHeaderData hdr;
                               9412                 :                :         char        data[MaxHeapTupleSize];
                               9413                 :                :     }           tbuf;
                               9414                 :                :     xl_heap_header xlhdr;
                               9415                 :                :     uint32      newlen;
 3532                          9416                 :          91961 :     Size        freespace = 0;
                               9417                 :                :     XLogRedoAction oldaction;
                               9418                 :                :     XLogRedoAction newaction;
                               9419                 :                : 
                               9420                 :                :     /* initialize to keep the compiler quiet */
 3686                          9421                 :          91961 :     oldtup.t_data = NULL;
                               9422                 :          91961 :     oldtup.t_len = 0;
                               9423                 :                : 
  648 rhaas@postgresql.org     9424                 :          91961 :     XLogRecGetBlockTag(record, 0, &rlocator, NULL, &newblk);
  734 tgl@sss.pgh.pa.us        9425         [ +  + ]:          91961 :     if (XLogRecGetBlockTagExtended(record, 1, NULL, NULL, &oldblk, NULL))
                               9426                 :                :     {
                               9427                 :                :         /* HOT updates are never done across pages */
 3433 heikki.linnakangas@i     9428         [ -  + ]:          53974 :         Assert(!hot_update);
                               9429                 :                :     }
                               9430                 :                :     else
                               9431                 :          37987 :         oldblk = newblk;
                               9432                 :                : 
                               9433                 :          91961 :     ItemPointerSet(&newtid, newblk, xlrec->new_offnum);
                               9434                 :                : 
                               9435                 :                :     /*
                               9436                 :                :      * The visibility map may need to be fixed even if the heap page is
                               9437                 :                :      * already up-to-date.
                               9438                 :                :      */
 3264 andres@anarazel.de       9439         [ +  + ]:          91961 :     if (xlrec->flags & XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED)
                               9440                 :                :     {
  648 rhaas@postgresql.org     9441                 :            175 :         Relation    reln = CreateFakeRelcacheEntry(rlocator);
 4681                          9442                 :            175 :         Buffer      vmbuffer = InvalidBuffer;
                               9443                 :                : 
 3532 heikki.linnakangas@i     9444                 :            175 :         visibilitymap_pin(reln, oldblk, &vmbuffer);
 2827 andres@anarazel.de       9445                 :            175 :         visibilitymap_clear(reln, oldblk, vmbuffer, VISIBILITYMAP_VALID_BITS);
 4681 rhaas@postgresql.org     9446                 :            175 :         ReleaseBuffer(vmbuffer);
 5611 heikki.linnakangas@i     9447                 :            175 :         FreeFakeRelcacheEntry(reln);
                               9448                 :                :     }
                               9449                 :                : 
                               9450                 :                :     /*
                               9451                 :                :      * In normal operation, it is important to lock the two pages in
                               9452                 :                :      * page-number order, to avoid possible deadlocks against other update
                               9453                 :                :      * operations going the other way.  However, during WAL replay there can
                               9454                 :                :      * be no other update happening, so we don't need to worry about that. But
                               9455                 :                :      * we *do* need to worry that we don't expose an inconsistent state to Hot
                               9456                 :                :      * Standby queries --- so the original page can't be unlocked before we've
                               9457                 :                :      * added the new tuple to the new page.
                               9458                 :                :      */
                               9459                 :                : 
                               9460                 :                :     /* Deal with old tuple version */
 3433                          9461                 :          91961 :     oldaction = XLogReadBufferForRedo(record, (oldblk == newblk) ? 0 : 1,
                               9462                 :                :                                       &obuffer);
 3532                          9463         [ +  + ]:          91961 :     if (oldaction == BLK_NEEDS_REDO)
                               9464                 :                :     {
 2916 kgrittn@postgresql.o     9465                 :          91918 :         page = BufferGetPage(obuffer);
 3433 heikki.linnakangas@i     9466                 :          91918 :         offnum = xlrec->old_offnum;
 3532                          9467         [ +  - ]:          91918 :         if (PageGetMaxOffsetNumber(page) >= offnum)
                               9468                 :          91918 :             lp = PageGetItemId(page, offnum);
                               9469                 :                : 
                               9470   [ +  -  -  + ]:          91918 :         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
 3069 andres@anarazel.de       9471         [ #  # ]:UBC           0 :             elog(PANIC, "invalid lp");
                               9472                 :                : 
 3532 heikki.linnakangas@i     9473                 :CBC       91918 :         htup = (HeapTupleHeader) PageGetItem(page, lp);
                               9474                 :                : 
                               9475                 :          91918 :         oldtup.t_data = htup;
                               9476                 :          91918 :         oldtup.t_len = ItemIdGetLength(lp);
                               9477                 :                : 
                               9478                 :          91918 :         htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               9479                 :          91918 :         htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
                               9480         [ +  + ]:          91918 :         if (hot_update)
                               9481                 :          35355 :             HeapTupleHeaderSetHotUpdated(htup);
                               9482                 :                :         else
                               9483                 :          56563 :             HeapTupleHeaderClearHotUpdated(htup);
                               9484                 :          91918 :         fix_infomask_from_infobits(xlrec->old_infobits_set, &htup->t_infomask,
                               9485                 :                :                                    &htup->t_infomask2);
                               9486                 :          91918 :         HeapTupleHeaderSetXmax(htup, xlrec->old_xmax);
                               9487         [ -  + ]:          91918 :         HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
                               9488                 :                :         /* Set forward chain link in t_ctid */
 3433                          9489                 :          91918 :         htup->t_ctid = newtid;
                               9490                 :                : 
                               9491                 :                :         /* Mark the page as a candidate for pruning */
                               9492   [ -  +  +  +  :          91918 :         PageSetPrunable(page, XLogRecGetXid(record));
                                              +  + ]
                               9493                 :                : 
 3264 andres@anarazel.de       9494         [ +  + ]:          91918 :         if (xlrec->flags & XLH_UPDATE_OLD_ALL_VISIBLE_CLEARED)
 3532 heikki.linnakangas@i     9495                 :            173 :             PageClearAllVisible(page);
                               9496                 :                : 
                               9497                 :          91918 :         PageSetLSN(page, lsn);
                               9498                 :          91918 :         MarkBufferDirty(obuffer);
                               9499                 :                :     }
                               9500                 :                : 
                               9501                 :                :     /*
                               9502                 :                :      * Read the page the new tuple goes into, if different from old.
                               9503                 :                :      */
                               9504         [ +  + ]:          91961 :     if (oldblk == newblk)
                               9505                 :                :     {
 4171 tgl@sss.pgh.pa.us        9506                 :          37987 :         nbuffer = obuffer;
 3532 heikki.linnakangas@i     9507                 :          37987 :         newaction = oldaction;
                               9508                 :                :     }
 3433                          9509         [ +  + ]:          53974 :     else if (XLogRecGetInfo(record) & XLOG_HEAP_INIT_PAGE)
                               9510                 :                :     {
                               9511                 :            572 :         nbuffer = XLogInitBufferForRedo(record, 0);
 2916 kgrittn@postgresql.o     9512                 :            572 :         page = (Page) BufferGetPage(nbuffer);
 3532 heikki.linnakangas@i     9513                 :            572 :         PageInit(page, BufferGetPageSize(nbuffer), 0);
                               9514                 :            572 :         newaction = BLK_NEEDS_REDO;
                               9515                 :                :     }
                               9516                 :                :     else
 3433                          9517                 :          53402 :         newaction = XLogReadBufferForRedo(record, 0, &nbuffer);
                               9518                 :                : 
                               9519                 :                :     /*
                               9520                 :                :      * The visibility map may need to be fixed even if the heap page is
                               9521                 :                :      * already up-to-date.
                               9522                 :                :      */
 3264 andres@anarazel.de       9523         [ +  + ]:          91961 :     if (xlrec->flags & XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED)
                               9524                 :                :     {
  648 rhaas@postgresql.org     9525                 :            147 :         Relation    reln = CreateFakeRelcacheEntry(rlocator);
 4681                          9526                 :            147 :         Buffer      vmbuffer = InvalidBuffer;
                               9527                 :                : 
 3532 heikki.linnakangas@i     9528                 :            147 :         visibilitymap_pin(reln, newblk, &vmbuffer);
 2827 andres@anarazel.de       9529                 :            147 :         visibilitymap_clear(reln, newblk, vmbuffer, VISIBILITYMAP_VALID_BITS);
 4681 rhaas@postgresql.org     9530                 :            147 :         ReleaseBuffer(vmbuffer);
 5611 heikki.linnakangas@i     9531                 :            147 :         FreeFakeRelcacheEntry(reln);
                               9532                 :                :     }
                               9533                 :                : 
                               9534                 :                :     /* Deal with new tuple */
 3532                          9535         [ +  + ]:          91961 :     if (newaction == BLK_NEEDS_REDO)
                               9536                 :                :     {
                               9537                 :                :         char       *recdata;
                               9538                 :                :         char       *recdata_end;
                               9539                 :                :         Size        datalen;
                               9540                 :                :         Size        tuplen;
                               9541                 :                : 
 3433                          9542                 :          91852 :         recdata = XLogRecGetBlockData(record, 0, &datalen);
                               9543                 :          91852 :         recdata_end = recdata + datalen;
                               9544                 :                : 
 2916 kgrittn@postgresql.o     9545                 :          91852 :         page = BufferGetPage(nbuffer);
                               9546                 :                : 
 3433 heikki.linnakangas@i     9547                 :          91852 :         offnum = xlrec->new_offnum;
 3532                          9548         [ -  + ]:          91852 :         if (PageGetMaxOffsetNumber(page) + 1 < offnum)
 3069 andres@anarazel.de       9549         [ #  # ]:UBC           0 :             elog(PANIC, "invalid max offset number");
                               9550                 :                : 
 3264 andres@anarazel.de       9551         [ +  + ]:CBC       91852 :         if (xlrec->flags & XLH_UPDATE_PREFIX_FROM_OLD)
                               9552                 :                :         {
 3532 heikki.linnakangas@i     9553         [ -  + ]:          14373 :             Assert(newblk == oldblk);
                               9554                 :          14373 :             memcpy(&prefixlen, recdata, sizeof(uint16));
                               9555                 :          14373 :             recdata += sizeof(uint16);
                               9556                 :                :         }
 3264 andres@anarazel.de       9557         [ +  + ]:          91852 :         if (xlrec->flags & XLH_UPDATE_SUFFIX_FROM_OLD)
                               9558                 :                :         {
 3532 heikki.linnakangas@i     9559         [ -  + ]:          32853 :             Assert(newblk == oldblk);
                               9560                 :          32853 :             memcpy(&suffixlen, recdata, sizeof(uint16));
                               9561                 :          32853 :             recdata += sizeof(uint16);
                               9562                 :                :         }
                               9563                 :                : 
 3433                          9564                 :          91852 :         memcpy((char *) &xlhdr, recdata, SizeOfHeapHeader);
                               9565                 :          91852 :         recdata += SizeOfHeapHeader;
                               9566                 :                : 
                               9567                 :          91852 :         tuplen = recdata_end - recdata;
                               9568         [ -  + ]:          91852 :         Assert(tuplen <= MaxHeapTupleSize);
                               9569                 :                : 
 3532                          9570                 :          91852 :         htup = &tbuf.hdr;
 3340 tgl@sss.pgh.pa.us        9571   [ +  -  -  +  :          91852 :         MemSet((char *) htup, 0, SizeofHeapTupleHeader);
                                     -  -  -  -  -  
                                                 - ]
                               9572                 :                : 
                               9573                 :                :         /*
                               9574                 :                :          * Reconstruct the new tuple using the prefix and/or suffix from the
                               9575                 :                :          * old tuple, and the data stored in the WAL record.
                               9576                 :                :          */
                               9577                 :          91852 :         newp = (char *) htup + SizeofHeapTupleHeader;
 3532 heikki.linnakangas@i     9578         [ +  + ]:          91852 :         if (prefixlen > 0)
                               9579                 :                :         {
                               9580                 :                :             int         len;
                               9581                 :                : 
                               9582                 :                :             /* copy bitmap [+ padding] [+ oid] from WAL record */
 3340 tgl@sss.pgh.pa.us        9583                 :          14373 :             len = xlhdr.t_hoff - SizeofHeapTupleHeader;
 3532 heikki.linnakangas@i     9584                 :          14373 :             memcpy(newp, recdata, len);
                               9585                 :          14373 :             recdata += len;
                               9586                 :          14373 :             newp += len;
                               9587                 :                : 
                               9588                 :                :             /* copy prefix from old tuple */
                               9589                 :          14373 :             memcpy(newp, (char *) oldtup.t_data + oldtup.t_data->t_hoff, prefixlen);
                               9590                 :          14373 :             newp += prefixlen;
                               9591                 :                : 
                               9592                 :                :             /* copy new tuple data from WAL record */
 3340 tgl@sss.pgh.pa.us        9593                 :          14373 :             len = tuplen - (xlhdr.t_hoff - SizeofHeapTupleHeader);
 3532 heikki.linnakangas@i     9594                 :          14373 :             memcpy(newp, recdata, len);
                               9595                 :          14373 :             recdata += len;
                               9596                 :          14373 :             newp += len;
                               9597                 :                :         }
                               9598                 :                :         else
                               9599                 :                :         {
                               9600                 :                :             /*
                               9601                 :                :              * copy bitmap [+ padding] [+ oid] + data from record, all in one
                               9602                 :                :              * go
                               9603                 :                :              */
 3433                          9604                 :          77479 :             memcpy(newp, recdata, tuplen);
                               9605                 :          77479 :             recdata += tuplen;
                               9606                 :          77479 :             newp += tuplen;
                               9607                 :                :         }
                               9608         [ -  + ]:          91852 :         Assert(recdata == recdata_end);
                               9609                 :                : 
                               9610                 :                :         /* copy suffix from old tuple */
 3532                          9611         [ +  + ]:          91852 :         if (suffixlen > 0)
                               9612                 :          32853 :             memcpy(newp, (char *) oldtup.t_data + oldtup.t_len - suffixlen, suffixlen);
                               9613                 :                : 
 3340 tgl@sss.pgh.pa.us        9614                 :          91852 :         newlen = SizeofHeapTupleHeader + tuplen + prefixlen + suffixlen;
 3433 heikki.linnakangas@i     9615                 :          91852 :         htup->t_infomask2 = xlhdr.t_infomask2;
                               9616                 :          91852 :         htup->t_infomask = xlhdr.t_infomask;
                               9617                 :          91852 :         htup->t_hoff = xlhdr.t_hoff;
                               9618                 :                : 
                               9619                 :          91852 :         HeapTupleHeaderSetXmin(htup, XLogRecGetXid(record));
 3532                          9620         [ -  + ]:          91852 :         HeapTupleHeaderSetCmin(htup, FirstCommandId);
                               9621                 :          91852 :         HeapTupleHeaderSetXmax(htup, xlrec->new_xmax);
                               9622                 :                :         /* Make sure there is no forward chain link in t_ctid */
 3433                          9623                 :          91852 :         htup->t_ctid = newtid;
                               9624                 :                : 
 3532                          9625                 :          91852 :         offnum = PageAddItem(page, (Item) htup, newlen, offnum, true, true);
                               9626         [ -  + ]:          91852 :         if (offnum == InvalidOffsetNumber)
 3069 andres@anarazel.de       9627         [ #  # ]:UBC           0 :             elog(PANIC, "failed to add tuple");
                               9628                 :                : 
 3264 andres@anarazel.de       9629         [ +  + ]:CBC       91852 :         if (xlrec->flags & XLH_UPDATE_NEW_ALL_VISIBLE_CLEARED)
 3532 heikki.linnakangas@i     9630                 :            113 :             PageClearAllVisible(page);
                               9631                 :                : 
                               9632                 :          91852 :         freespace = PageGetHeapFreeSpace(page); /* needed to update FSM below */
                               9633                 :                : 
                               9634                 :          91852 :         PageSetLSN(page, lsn);
                               9635                 :          91852 :         MarkBufferDirty(nbuffer);
                               9636                 :                :     }
                               9637                 :                : 
                               9638   [ +  -  +  + ]:          91961 :     if (BufferIsValid(nbuffer) && nbuffer != obuffer)
                               9639                 :          53974 :         UnlockReleaseBuffer(nbuffer);
                               9640         [ +  - ]:          91961 :     if (BufferIsValid(obuffer))
 4171 tgl@sss.pgh.pa.us        9641                 :          91961 :         UnlockReleaseBuffer(obuffer);
                               9642                 :                : 
                               9643                 :                :     /*
                               9644                 :                :      * If the new page is running low on free space, update the FSM as well.
                               9645                 :                :      * Arbitrarily, our definition of "low" is less than 20%. We can't do much
                               9646                 :                :      * better than that without knowing the fill-factor for the table.
                               9647                 :                :      *
                               9648                 :                :      * However, don't update the FSM on HOT updates, because after crash
                               9649                 :                :      * recovery, either the old or the new tuple will certainly be dead and
                               9650                 :                :      * prunable. After pruning, the page will have roughly as much free space
                               9651                 :                :      * as it did before the update, assuming the new tuple is about the same
                               9652                 :                :      * size as the old one.
                               9653                 :                :      *
                               9654                 :                :      * XXX: Don't do this if the page was restored from full page image. We
                               9655                 :                :      * don't bother to update the FSM in that case, it doesn't need to be
                               9656                 :                :      * totally accurate anyway.
                               9657                 :                :      */
 3532 heikki.linnakangas@i     9658   [ +  +  +  +  :          91961 :     if (newaction == BLK_NEEDS_REDO && !hot_update && freespace < BLCKSZ / 5)
                                              +  + ]
  648 rhaas@postgresql.org     9659                 :          11497 :         XLogRecordPageWithFreeSpace(rlocator, newblk, freespace);
 8577 vadim4o@yahoo.com        9660                 :          91961 : }
                               9661                 :                : 
                               9662                 :                : static void
 3264 andres@anarazel.de       9663                 :             61 : heap_xlog_confirm(XLogReaderState *record)
                               9664                 :                : {
                               9665                 :             61 :     XLogRecPtr  lsn = record->EndRecPtr;
                               9666                 :             61 :     xl_heap_confirm *xlrec = (xl_heap_confirm *) XLogRecGetData(record);
                               9667                 :                :     Buffer      buffer;
                               9668                 :                :     Page        page;
                               9669                 :                :     OffsetNumber offnum;
                               9670                 :             61 :     ItemId      lp = NULL;
                               9671                 :                :     HeapTupleHeader htup;
                               9672                 :                : 
                               9673         [ +  - ]:             61 :     if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
                               9674                 :                :     {
 2916 kgrittn@postgresql.o     9675                 :             61 :         page = BufferGetPage(buffer);
                               9676                 :                : 
 3264 andres@anarazel.de       9677                 :             61 :         offnum = xlrec->offnum;
                               9678         [ +  - ]:             61 :         if (PageGetMaxOffsetNumber(page) >= offnum)
                               9679                 :             61 :             lp = PageGetItemId(page, offnum);
                               9680                 :                : 
                               9681   [ +  -  -  + ]:             61 :         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
 3069 andres@anarazel.de       9682         [ #  # ]:UBC           0 :             elog(PANIC, "invalid lp");
                               9683                 :                : 
 3264 andres@anarazel.de       9684                 :CBC          61 :         htup = (HeapTupleHeader) PageGetItem(page, lp);
                               9685                 :                : 
                               9686                 :                :         /*
                               9687                 :                :          * Confirm tuple as actually inserted
                               9688                 :                :          */
                               9689                 :             61 :         ItemPointerSet(&htup->t_ctid, BufferGetBlockNumber(buffer), offnum);
                               9690                 :                : 
                               9691                 :             61 :         PageSetLSN(page, lsn);
                               9692                 :             61 :         MarkBufferDirty(buffer);
                               9693                 :                :     }
                               9694         [ +  - ]:             61 :     if (BufferIsValid(buffer))
                               9695                 :             61 :         UnlockReleaseBuffer(buffer);
                               9696                 :             61 : }
                               9697                 :                : 
                               9698                 :                : static void
 3433 heikki.linnakangas@i     9699                 :          54845 : heap_xlog_lock(XLogReaderState *record)
                               9700                 :                : {
                               9701                 :          54845 :     XLogRecPtr  lsn = record->EndRecPtr;
 6926 tgl@sss.pgh.pa.us        9702                 :          54845 :     xl_heap_lock *xlrec = (xl_heap_lock *) XLogRecGetData(record);
                               9703                 :                :     Buffer      buffer;
                               9704                 :                :     Page        page;
                               9705                 :                :     OffsetNumber offnum;
                               9706                 :          54845 :     ItemId      lp = NULL;
                               9707                 :                :     HeapTupleHeader htup;
                               9708                 :                : 
                               9709                 :                :     /*
                               9710                 :                :      * The visibility map may need to be fixed even if the heap page is
                               9711                 :                :      * already up-to-date.
                               9712                 :                :      */
 2827 andres@anarazel.de       9713         [ +  + ]:          54845 :     if (xlrec->flags & XLH_LOCK_ALL_FROZEN_CLEARED)
                               9714                 :                :     {
                               9715                 :                :         RelFileLocator rlocator;
                               9716                 :             34 :         Buffer      vmbuffer = InvalidBuffer;
                               9717                 :                :         BlockNumber block;
                               9718                 :                :         Relation    reln;
                               9719                 :                : 
  648 rhaas@postgresql.org     9720                 :             34 :         XLogRecGetBlockTag(record, 0, &rlocator, NULL, &block);
                               9721                 :             34 :         reln = CreateFakeRelcacheEntry(rlocator);
                               9722                 :                : 
 2827 andres@anarazel.de       9723                 :             34 :         visibilitymap_pin(reln, block, &vmbuffer);
                               9724                 :             34 :         visibilitymap_clear(reln, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN);
                               9725                 :                : 
                               9726                 :             34 :         ReleaseBuffer(vmbuffer);
                               9727                 :             34 :         FreeFakeRelcacheEntry(reln);
                               9728                 :                :     }
                               9729                 :                : 
 3433 heikki.linnakangas@i     9730         [ +  + ]:          54845 :     if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
                               9731                 :                :     {
 2916 kgrittn@postgresql.o     9732                 :          54763 :         page = (Page) BufferGetPage(buffer);
                               9733                 :                : 
 3433 heikki.linnakangas@i     9734                 :          54763 :         offnum = xlrec->offnum;
 3532                          9735         [ +  - ]:          54763 :         if (PageGetMaxOffsetNumber(page) >= offnum)
                               9736                 :          54763 :             lp = PageGetItemId(page, offnum);
                               9737                 :                : 
                               9738   [ +  -  -  + ]:          54763 :         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
 3069 andres@anarazel.de       9739         [ #  # ]:UBC           0 :             elog(PANIC, "invalid lp");
                               9740                 :                : 
 3532 heikki.linnakangas@i     9741                 :CBC       54763 :         htup = (HeapTupleHeader) PageGetItem(page, lp);
                               9742                 :                : 
 2830 andres@anarazel.de       9743                 :          54763 :         htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               9744                 :          54763 :         htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 3532 heikki.linnakangas@i     9745                 :          54763 :         fix_infomask_from_infobits(xlrec->infobits_set, &htup->t_infomask,
                               9746                 :                :                                    &htup->t_infomask2);
                               9747                 :                : 
                               9748                 :                :         /*
                               9749                 :                :          * Clear relevant update flags, but only if the modified infomask says
                               9750                 :                :          * there's no update.
                               9751                 :                :          */
                               9752   [ -  +  -  - ]:          54763 :         if (HEAP_XMAX_IS_LOCKED_ONLY(htup->t_infomask))
                               9753                 :                :         {
                               9754                 :          54763 :             HeapTupleHeaderClearHotUpdated(htup);
                               9755                 :                :             /* Make sure there is no forward chain link in t_ctid */
 3433                          9756                 :          54763 :             ItemPointerSet(&htup->t_ctid,
                               9757                 :                :                            BufferGetBlockNumber(buffer),
                               9758                 :                :                            offnum);
                               9759                 :                :         }
  369 pg@bowt.ie               9760                 :          54763 :         HeapTupleHeaderSetXmax(htup, xlrec->xmax);
 3532 heikki.linnakangas@i     9761         [ -  + ]:          54763 :         HeapTupleHeaderSetCmax(htup, FirstCommandId, false);
                               9762                 :          54763 :         PageSetLSN(page, lsn);
                               9763                 :          54763 :         MarkBufferDirty(buffer);
                               9764                 :                :     }
                               9765         [ +  - ]:          54845 :     if (BufferIsValid(buffer))
                               9766                 :          54845 :         UnlockReleaseBuffer(buffer);
 6926 tgl@sss.pgh.pa.us        9767                 :          54845 : }
                               9768                 :                : 
                               9769                 :                : static void
 3433 heikki.linnakangas@i     9770                 :UBC           0 : heap_xlog_lock_updated(XLogReaderState *record)
                               9771                 :                : {
                               9772                 :              0 :     XLogRecPtr  lsn = record->EndRecPtr;
                               9773                 :                :     xl_heap_lock_updated *xlrec;
                               9774                 :                :     Buffer      buffer;
                               9775                 :                :     Page        page;
                               9776                 :                :     OffsetNumber offnum;
 4099 alvherre@alvh.no-ip.     9777                 :              0 :     ItemId      lp = NULL;
                               9778                 :                :     HeapTupleHeader htup;
                               9779                 :                : 
 3433 heikki.linnakangas@i     9780                 :              0 :     xlrec = (xl_heap_lock_updated *) XLogRecGetData(record);
                               9781                 :                : 
                               9782                 :                :     /*
                               9783                 :                :      * The visibility map may need to be fixed even if the heap page is
                               9784                 :                :      * already up-to-date.
                               9785                 :                :      */
 2827 andres@anarazel.de       9786         [ #  # ]:              0 :     if (xlrec->flags & XLH_LOCK_ALL_FROZEN_CLEARED)
                               9787                 :                :     {
                               9788                 :                :         RelFileLocator rlocator;
                               9789                 :              0 :         Buffer      vmbuffer = InvalidBuffer;
                               9790                 :                :         BlockNumber block;
                               9791                 :                :         Relation    reln;
                               9792                 :                : 
  648 rhaas@postgresql.org     9793                 :              0 :         XLogRecGetBlockTag(record, 0, &rlocator, NULL, &block);
                               9794                 :              0 :         reln = CreateFakeRelcacheEntry(rlocator);
                               9795                 :                : 
 2827 andres@anarazel.de       9796                 :              0 :         visibilitymap_pin(reln, block, &vmbuffer);
                               9797                 :              0 :         visibilitymap_clear(reln, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN);
                               9798                 :                : 
                               9799                 :              0 :         ReleaseBuffer(vmbuffer);
                               9800                 :              0 :         FreeFakeRelcacheEntry(reln);
                               9801                 :                :     }
                               9802                 :                : 
 3433 heikki.linnakangas@i     9803         [ #  # ]:              0 :     if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
                               9804                 :                :     {
 2916 kgrittn@postgresql.o     9805                 :              0 :         page = BufferGetPage(buffer);
                               9806                 :                : 
 3433 heikki.linnakangas@i     9807                 :              0 :         offnum = xlrec->offnum;
 3532                          9808         [ #  # ]:              0 :         if (PageGetMaxOffsetNumber(page) >= offnum)
                               9809                 :              0 :             lp = PageGetItemId(page, offnum);
                               9810                 :                : 
                               9811   [ #  #  #  # ]:              0 :         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
 3069 andres@anarazel.de       9812         [ #  # ]:              0 :             elog(PANIC, "invalid lp");
                               9813                 :                : 
 3532 heikki.linnakangas@i     9814                 :              0 :         htup = (HeapTupleHeader) PageGetItem(page, lp);
                               9815                 :                : 
 2830 andres@anarazel.de       9816                 :              0 :         htup->t_infomask &= ~(HEAP_XMAX_BITS | HEAP_MOVED);
                               9817                 :              0 :         htup->t_infomask2 &= ~HEAP_KEYS_UPDATED;
 3532 heikki.linnakangas@i     9818                 :              0 :         fix_infomask_from_infobits(xlrec->infobits_set, &htup->t_infomask,
                               9819                 :                :                                    &htup->t_infomask2);
                               9820                 :              0 :         HeapTupleHeaderSetXmax(htup, xlrec->xmax);
                               9821                 :                : 
                               9822                 :              0 :         PageSetLSN(page, lsn);
                               9823                 :              0 :         MarkBufferDirty(buffer);
                               9824                 :                :     }
                               9825         [ #  # ]:              0 :     if (BufferIsValid(buffer))
                               9826                 :              0 :         UnlockReleaseBuffer(buffer);
 4099 alvherre@alvh.no-ip.     9827                 :              0 : }
                               9828                 :                : 
                               9829                 :                : static void
 3433 heikki.linnakangas@i     9830                 :CBC        7205 : heap_xlog_inplace(XLogReaderState *record)
                               9831                 :                : {
                               9832                 :           7205 :     XLogRecPtr  lsn = record->EndRecPtr;
 6549 tgl@sss.pgh.pa.us        9833                 :           7205 :     xl_heap_inplace *xlrec = (xl_heap_inplace *) XLogRecGetData(record);
                               9834                 :                :     Buffer      buffer;
                               9835                 :                :     Page        page;
                               9836                 :                :     OffsetNumber offnum;
                               9837                 :           7205 :     ItemId      lp = NULL;
                               9838                 :                :     HeapTupleHeader htup;
                               9839                 :                :     uint32      oldlen;
                               9840                 :                :     Size        newlen;
                               9841                 :                : 
 3433 heikki.linnakangas@i     9842         [ +  + ]:           7205 :     if (XLogReadBufferForRedo(record, 0, &buffer) == BLK_NEEDS_REDO)
                               9843                 :                :     {
                               9844                 :           7144 :         char       *newtup = XLogRecGetBlockData(record, 0, &newlen);
                               9845                 :                : 
 2916 kgrittn@postgresql.o     9846                 :           7144 :         page = BufferGetPage(buffer);
                               9847                 :                : 
 3433 heikki.linnakangas@i     9848                 :           7144 :         offnum = xlrec->offnum;
 3532                          9849         [ +  - ]:           7144 :         if (PageGetMaxOffsetNumber(page) >= offnum)
                               9850                 :           7144 :             lp = PageGetItemId(page, offnum);
                               9851                 :                : 
                               9852   [ +  -  -  + ]:           7144 :         if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
 3069 andres@anarazel.de       9853         [ #  # ]:UBC           0 :             elog(PANIC, "invalid lp");
                               9854                 :                : 
 3532 heikki.linnakangas@i     9855                 :CBC        7144 :         htup = (HeapTupleHeader) PageGetItem(page, lp);
                               9856                 :                : 
                               9857                 :           7144 :         oldlen = ItemIdGetLength(lp) - htup->t_hoff;
                               9858         [ -  + ]:           7144 :         if (oldlen != newlen)
 3069 andres@anarazel.de       9859         [ #  # ]:UBC           0 :             elog(PANIC, "wrong tuple length");
                               9860                 :                : 
 3433 heikki.linnakangas@i     9861                 :CBC        7144 :         memcpy((char *) htup + htup->t_hoff, newtup, newlen);
                               9862                 :                : 
 3532                          9863                 :           7144 :         PageSetLSN(page, lsn);
                               9864                 :           7144 :         MarkBufferDirty(buffer);
                               9865                 :                :     }
                               9866         [ +  - ]:           7205 :     if (BufferIsValid(buffer))
                               9867                 :           7205 :         UnlockReleaseBuffer(buffer);
 6549 tgl@sss.pgh.pa.us        9868                 :           7205 : }
                               9869                 :                : 
                               9870                 :                : void
 3433 heikki.linnakangas@i     9871                 :        1912569 : heap_redo(XLogReaderState *record)
                               9872                 :                : {
                               9873                 :        1912569 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
                               9874                 :                : 
                               9875                 :                :     /*
                               9876                 :                :      * These operations don't overwrite MVCC data so no conflict processing is
                               9877                 :                :      * required. The ones in heap2 rmgr do.
                               9878                 :                :      */
                               9879                 :                : 
 6051 tgl@sss.pgh.pa.us        9880   [ +  +  +  +  :        1912569 :     switch (info & XLOG_HEAP_OPMASK)
                                        +  +  +  +  
                                                 - ]
                               9881                 :                :     {
                               9882                 :        1423598 :         case XLOG_HEAP_INSERT:
 3433 heikki.linnakangas@i     9883                 :        1423598 :             heap_xlog_insert(record);
 6051 tgl@sss.pgh.pa.us        9884                 :        1423598 :             break;
                               9885                 :         334896 :         case XLOG_HEAP_DELETE:
 3433 heikki.linnakangas@i     9886                 :         334896 :             heap_xlog_delete(record);
 6051 tgl@sss.pgh.pa.us        9887                 :         334896 :             break;
                               9888                 :          56572 :         case XLOG_HEAP_UPDATE:
 3433 heikki.linnakangas@i     9889                 :          56572 :             heap_xlog_update(record, false);
 6051 tgl@sss.pgh.pa.us        9890                 :          56572 :             break;
 2199 peter_e@gmx.net          9891                 :GBC           3 :         case XLOG_HEAP_TRUNCATE:
                               9892                 :                : 
                               9893                 :                :             /*
                               9894                 :                :              * TRUNCATE is a no-op because the actions are already logged as
                               9895                 :                :              * SMGR WAL records.  TRUNCATE WAL record only exists for logical
                               9896                 :                :              * decoding.
                               9897                 :                :              */
                               9898                 :              3 :             break;
 6051 tgl@sss.pgh.pa.us        9899                 :CBC       35389 :         case XLOG_HEAP_HOT_UPDATE:
 3433 heikki.linnakangas@i     9900                 :          35389 :             heap_xlog_update(record, true);
 6051 tgl@sss.pgh.pa.us        9901                 :          35389 :             break;
 3264 andres@anarazel.de       9902                 :             61 :         case XLOG_HEAP_CONFIRM:
                               9903                 :             61 :             heap_xlog_confirm(record);
                               9904                 :             61 :             break;
 6051 tgl@sss.pgh.pa.us        9905                 :          54845 :         case XLOG_HEAP_LOCK:
 3433 heikki.linnakangas@i     9906                 :          54845 :             heap_xlog_lock(record);
 6051 tgl@sss.pgh.pa.us        9907                 :          54845 :             break;
                               9908                 :           7205 :         case XLOG_HEAP_INPLACE:
 3433 heikki.linnakangas@i     9909                 :           7205 :             heap_xlog_inplace(record);
 6051 tgl@sss.pgh.pa.us        9910                 :           7205 :             break;
 6051 tgl@sss.pgh.pa.us        9911                 :UBC           0 :         default:
                               9912         [ #  # ]:              0 :             elog(PANIC, "heap_redo: unknown op code %u", info);
                               9913                 :                :     }
 8577 vadim4o@yahoo.com        9914                 :CBC     1912569 : }
                               9915                 :                : 
                               9916                 :                : void
 3433 heikki.linnakangas@i     9917                 :          74388 : heap2_redo(XLogReaderState *record)
                               9918                 :                : {
                               9919                 :          74388 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
                               9920                 :                : 
 6051 tgl@sss.pgh.pa.us        9921   [ +  +  +  -  :          74388 :     switch (info & XLOG_HEAP_OPMASK)
                                        +  -  -  -  
                                                 - ]
                               9922                 :                :     {
   20 heikki.linnakangas@i     9923                 :GNC       13170 :         case XLOG_HEAP2_PRUNE_ON_ACCESS:
                               9924                 :                :         case XLOG_HEAP2_PRUNE_VACUUM_SCAN:
                               9925                 :                :         case XLOG_HEAP2_PRUNE_VACUUM_CLEANUP:
                               9926                 :          13170 :             heap_xlog_prune_freeze(record);
 3772 alvherre@alvh.no-ip.     9927                 :CBC       13170 :             break;
 4681 rhaas@postgresql.org     9928                 :           7594 :         case XLOG_HEAP2_VISIBLE:
 3433 heikki.linnakangas@i     9929                 :           7594 :             heap_xlog_visible(record);
 4681 rhaas@postgresql.org     9930                 :           7594 :             break;
 4540 heikki.linnakangas@i     9931                 :          52736 :         case XLOG_HEAP2_MULTI_INSERT:
 3433                          9932                 :          52736 :             heap_xlog_multi_insert(record);
 4540                          9933                 :          52736 :             break;
 4099 alvherre@alvh.no-ip.     9934                 :UBC           0 :         case XLOG_HEAP2_LOCK_UPDATED:
 3433 heikki.linnakangas@i     9935                 :              0 :             heap_xlog_lock_updated(record);
 4099 alvherre@alvh.no-ip.     9936                 :              0 :             break;
 3778 rhaas@postgresql.org     9937                 :CBC         888 :         case XLOG_HEAP2_NEW_CID:
                               9938                 :                : 
                               9939                 :                :             /*
                               9940                 :                :              * Nothing to do on a real replay, only used during logical
                               9941                 :                :              * decoding.
                               9942                 :                :              */
                               9943                 :            888 :             break;
 3695 rhaas@postgresql.org     9944                 :UBC           0 :         case XLOG_HEAP2_REWRITE:
 3433 heikki.linnakangas@i     9945                 :              0 :             heap_xlog_logical_rewrite(record);
 3695 rhaas@postgresql.org     9946                 :              0 :             break;
 6051 tgl@sss.pgh.pa.us        9947                 :              0 :         default:
                               9948         [ #  # ]:              0 :             elog(PANIC, "heap2_redo: unknown op code %u", info);
                               9949                 :                :     }
 6370 tgl@sss.pgh.pa.us        9950                 :CBC       74388 : }
                               9951                 :                : 
                               9952                 :                : /*
                               9953                 :                :  * Mask a heap page before performing consistency checks on it.
                               9954                 :                :  */
                               9955                 :                : void
 2622 rhaas@postgresql.org     9956                 :UBC           0 : heap_mask(char *pagedata, BlockNumber blkno)
                               9957                 :                : {
                               9958                 :              0 :     Page        page = (Page) pagedata;
                               9959                 :                :     OffsetNumber off;
                               9960                 :                : 
 2396                          9961                 :              0 :     mask_page_lsn_and_checksum(page);
                               9962                 :                : 
 2622                          9963                 :              0 :     mask_page_hint_bits(page);
                               9964                 :              0 :     mask_unused_space(page);
                               9965                 :                : 
                               9966         [ #  # ]:              0 :     for (off = 1; off <= PageGetMaxOffsetNumber(page); off++)
                               9967                 :                :     {
                               9968                 :              0 :         ItemId      iid = PageGetItemId(page, off);
                               9969                 :                :         char       *page_item;
                               9970                 :                : 
                               9971                 :              0 :         page_item = (char *) (page + ItemIdGetOffset(iid));
                               9972                 :                : 
                               9973         [ #  # ]:              0 :         if (ItemIdIsNormal(iid))
                               9974                 :                :         {
                               9975                 :              0 :             HeapTupleHeader page_htup = (HeapTupleHeader) page_item;
                               9976                 :                : 
                               9977                 :                :             /*
                               9978                 :                :              * If xmin of a tuple is not yet frozen, we should ignore
                               9979                 :                :              * differences in hint bits, since they can be set without
                               9980                 :                :              * emitting WAL.
                               9981                 :                :              */
                               9982         [ #  # ]:              0 :             if (!HeapTupleHeaderXminFrozen(page_htup))
                               9983                 :              0 :                 page_htup->t_infomask &= ~HEAP_XACT_MASK;
                               9984                 :                :             else
                               9985                 :                :             {
                               9986                 :                :                 /* Still we need to mask xmax hint bits. */
                               9987                 :              0 :                 page_htup->t_infomask &= ~HEAP_XMAX_INVALID;
                               9988                 :              0 :                 page_htup->t_infomask &= ~HEAP_XMAX_COMMITTED;
                               9989                 :                :             }
                               9990                 :                : 
                               9991                 :                :             /*
                               9992                 :                :              * During replay, we set Command Id to FirstCommandId. Hence, mask
                               9993                 :                :              * it. See heap_xlog_insert() for details.
                               9994                 :                :              */
                               9995                 :              0 :             page_htup->t_choice.t_heap.t_field3.t_cid = MASK_MARKER;
                               9996                 :                : 
                               9997                 :                :             /*
                               9998                 :                :              * For a speculative tuple, heap_insert() does not set ctid in the
                               9999                 :                :              * caller-passed heap tuple itself, leaving the ctid field to
                              10000                 :                :              * contain a speculative token value - a per-backend monotonically
                              10001                 :                :              * increasing identifier. Besides, it does not WAL-log ctid under
                              10002                 :                :              * any circumstances.
                              10003                 :                :              *
                              10004                 :                :              * During redo, heap_xlog_insert() sets t_ctid to current block
                              10005                 :                :              * number and self offset number. It doesn't care about any
                              10006                 :                :              * speculative insertions on the primary. Hence, we set t_ctid to
                              10007                 :                :              * current block number and self offset number to ignore any
                              10008                 :                :              * inconsistency.
                              10009                 :                :              */
                              10010         [ #  # ]:              0 :             if (HeapTupleHeaderIsSpeculative(page_htup))
                              10011                 :              0 :                 ItemPointerSet(&page_htup->t_ctid, blkno, off);
                              10012                 :                : 
                              10013                 :                :             /*
                              10014                 :                :              * NB: Not ignoring ctid changes due to the tuple having moved
                              10015                 :                :              * (i.e. HeapTupleHeaderIndicatesMovedPartitions), because that's
                              10016                 :                :              * important information that needs to be in-sync between primary
                              10017                 :                :              * and standby, and thus is WAL logged.
                              10018                 :                :              */
                              10019                 :                :         }
                              10020                 :                : 
                              10021                 :                :         /*
                              10022                 :                :          * Ignore any padding bytes after the tuple, when the length of the
                              10023                 :                :          * item is not MAXALIGNed.
                              10024                 :                :          */
                              10025         [ #  # ]:              0 :         if (ItemIdHasStorage(iid))
                              10026                 :                :         {
                              10027                 :              0 :             int         len = ItemIdGetLength(iid);
                              10028                 :              0 :             int         padlen = MAXALIGN(len) - len;
                              10029                 :                : 
                              10030         [ #  # ]:              0 :             if (padlen > 0)
                              10031                 :              0 :                 memset(page_item + len, MASK_MARKER, padlen);
                              10032                 :                :         }
                              10033                 :                :     }
                              10034                 :              0 : }
                              10035                 :                : 
                              10036                 :                : /*
                              10037                 :                :  * HeapCheckForSerializableConflictOut
                              10038                 :                :  *      We are reading a tuple.  If it's not visible, there may be a
                              10039                 :                :  *      rw-conflict out with the inserter.  Otherwise, if it is visible to us
                              10040                 :                :  *      but has been deleted, there may be a rw-conflict out with the deleter.
                              10041                 :                :  *
                              10042                 :                :  * We will determine the top level xid of the writing transaction with which
                              10043                 :                :  * we may be in conflict, and ask CheckForSerializableConflictOut() to check
                              10044                 :                :  * for overlap with our own transaction.
                              10045                 :                :  *
                              10046                 :                :  * This function should be called just about anywhere in heapam.c where a
                              10047                 :                :  * tuple has been read. The caller must hold at least a shared lock on the
                              10048                 :                :  * buffer, because this function might set hint bits on the tuple. There is
                              10049                 :                :  * currently no known reason to call this function from an index AM.
                              10050                 :                :  */
                              10051                 :                : void
 1538 tmunro@postgresql.or    10052                 :CBC    28152682 : HeapCheckForSerializableConflictOut(bool visible, Relation relation,
                              10053                 :                :                                     HeapTuple tuple, Buffer buffer,
                              10054                 :                :                                     Snapshot snapshot)
                              10055                 :                : {
                              10056                 :                :     TransactionId xid;
                              10057                 :                :     HTSV_Result htsvResult;
                              10058                 :                : 
                              10059         [ +  + ]:       28152682 :     if (!CheckForSerializableConflictOutNeeded(relation, snapshot))
                              10060                 :       28127335 :         return;
                              10061                 :                : 
                              10062                 :                :     /*
                              10063                 :                :      * Check to see whether the tuple has been written to by a concurrent
                              10064                 :                :      * transaction, either to create it not visible to us, or to delete it
                              10065                 :                :      * while it is visible to us.  The "visible" bool indicates whether the
                              10066                 :                :      * tuple is visible to us, while HeapTupleSatisfiesVacuum checks what else
                              10067                 :                :      * is going on with it.
                              10068                 :                :      *
                              10069                 :                :      * In the event of a concurrently inserted tuple that also happens to have
                              10070                 :                :      * been concurrently updated (by a separate transaction), the xmin of the
                              10071                 :                :      * tuple will be used -- not the updater's xid.
                              10072                 :                :      */
                              10073                 :          25347 :     htsvResult = HeapTupleSatisfiesVacuum(tuple, TransactionXmin, buffer);
                              10074   [ +  +  +  +  :          25347 :     switch (htsvResult)
                                                 - ]
                              10075                 :                :     {
                              10076                 :          24545 :         case HEAPTUPLE_LIVE:
                              10077         [ +  + ]:          24545 :             if (visible)
                              10078                 :          24532 :                 return;
                              10079         [ +  - ]:             13 :             xid = HeapTupleHeaderGetXmin(tuple->t_data);
                              10080                 :             13 :             break;
                              10081                 :            352 :         case HEAPTUPLE_RECENTLY_DEAD:
                              10082                 :                :         case HEAPTUPLE_DELETE_IN_PROGRESS:
 1403 pg@bowt.ie              10083         [ +  + ]:            352 :             if (visible)
                              10084   [ +  -  -  +  :            281 :                 xid = HeapTupleHeaderGetUpdateXid(tuple->t_data);
                                              -  - ]
                              10085                 :                :             else
                              10086         [ +  - ]:             71 :                 xid = HeapTupleHeaderGetXmin(tuple->t_data);
                              10087                 :                : 
                              10088         [ +  + ]:            352 :             if (TransactionIdPrecedes(xid, TransactionXmin))
                              10089                 :                :             {
                              10090                 :                :                 /* This is like the HEAPTUPLE_DEAD case */
                              10091         [ -  + ]:             62 :                 Assert(!visible);
                              10092                 :             62 :                 return;
                              10093                 :                :             }
 1538 tmunro@postgresql.or    10094                 :            290 :             break;
                              10095                 :            326 :         case HEAPTUPLE_INSERT_IN_PROGRESS:
                              10096         [ +  - ]:            326 :             xid = HeapTupleHeaderGetXmin(tuple->t_data);
                              10097                 :            326 :             break;
                              10098                 :            124 :         case HEAPTUPLE_DEAD:
 1403 pg@bowt.ie              10099         [ -  + ]:            124 :             Assert(!visible);
 1538 tmunro@postgresql.or    10100                 :            124 :             return;
 1538 tmunro@postgresql.or    10101                 :UBC           0 :         default:
                              10102                 :                : 
                              10103                 :                :             /*
                              10104                 :                :              * The only way to get to this default clause is if a new value is
                              10105                 :                :              * added to the enum type without adding it to this switch
                              10106                 :                :              * statement.  That's a bug, so elog.
                              10107                 :                :              */
                              10108         [ #  # ]:              0 :             elog(ERROR, "unrecognized return value from HeapTupleSatisfiesVacuum: %u", htsvResult);
                              10109                 :                : 
                              10110                 :                :             /*
                              10111                 :                :              * In spite of having all enum values covered and calling elog on
                              10112                 :                :              * this default, some compilers think this is a code path which
                              10113                 :                :              * allows xid to be used below without initialization. Silence
                              10114                 :                :              * that warning.
                              10115                 :                :              */
                              10116                 :                :             xid = InvalidTransactionId;
                              10117                 :                :     }
                              10118                 :                : 
 1538 tmunro@postgresql.or    10119         [ -  + ]:CBC         629 :     Assert(TransactionIdIsValid(xid));
                              10120         [ -  + ]:            629 :     Assert(TransactionIdFollowsOrEquals(xid, TransactionXmin));
                              10121                 :                : 
                              10122                 :                :     /*
                              10123                 :                :      * Find top level xid.  Bail out if xid is too early to be a conflict, or
                              10124                 :                :      * if it's our own xid.
                              10125                 :                :      */
                              10126         [ +  + ]:            629 :     if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
                              10127                 :             62 :         return;
                              10128                 :            567 :     xid = SubTransGetTopmostTransaction(xid);
                              10129         [ -  + ]:            567 :     if (TransactionIdPrecedes(xid, TransactionXmin))
 1538 tmunro@postgresql.or    10130                 :UBC           0 :         return;
                              10131                 :                : 
 1538 tmunro@postgresql.or    10132                 :CBC         567 :     CheckForSerializableConflictOut(relation, xid, snapshot);
                              10133                 :                : }
        

Generated by: LCOV version 2.1-beta2-3-g6141622