LCOV - differential code coverage report
Current view: top level - contrib/amcheck - verify_nbtree.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 73.1 % 799 584 27 188 17 91 476 13
Current Date: 2024-04-14 14:21:10 Functions: 94.3 % 35 33 2 1 15 17 1
Baseline: 16@8cea358b128 Branches: 49.9 % 864 431 43 390 8 77 346
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: 100.0 % 17 17 1 16
(120,180] days: 80.1 % 141 113 27 1 89 24
(180,240] days: 20.0 % 5 1 4 1
(240..) days: 71.2 % 636 453 183 17 436
Function coverage date bins:
(120,180] days: 100.0 % 5 5 4 1
(240..) days: 93.3 % 30 28 2 1 11 16
Branch coverage date bins:
[..60] days: 92.9 % 14 13 1 13
(120,180] days: 62.3 % 154 96 43 15 77 19
(180,240] days: 0.0 % 4 0 4
(240..) days: 46.5 % 692 322 370 8 314

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * verify_nbtree.c
                                  4                 :                :  *      Verifies the integrity of nbtree indexes based on invariants.
                                  5                 :                :  *
                                  6                 :                :  * For B-Tree indexes, verification includes checking that each page in the
                                  7                 :                :  * target index has items in logical order as reported by an insertion scankey
                                  8                 :                :  * (the insertion scankey sort-wise NULL semantics are needed for
                                  9                 :                :  * verification).
                                 10                 :                :  *
                                 11                 :                :  * When index-to-heap verification is requested, a Bloom filter is used to
                                 12                 :                :  * fingerprint all tuples in the target index, as the index is traversed to
                                 13                 :                :  * verify its structure.  A heap scan later uses Bloom filter probes to verify
                                 14                 :                :  * that every visible heap tuple has a matching index tuple.
                                 15                 :                :  *
                                 16                 :                :  *
                                 17                 :                :  * Copyright (c) 2017-2024, PostgreSQL Global Development Group
                                 18                 :                :  *
                                 19                 :                :  * IDENTIFICATION
                                 20                 :                :  *    contrib/amcheck/verify_nbtree.c
                                 21                 :                :  *
                                 22                 :                :  *-------------------------------------------------------------------------
                                 23                 :                :  */
                                 24                 :                : #include "postgres.h"
                                 25                 :                : 
                                 26                 :                : #include "access/heaptoast.h"
                                 27                 :                : #include "access/htup_details.h"
                                 28                 :                : #include "access/nbtree.h"
                                 29                 :                : #include "access/table.h"
                                 30                 :                : #include "access/tableam.h"
                                 31                 :                : #include "access/transam.h"
                                 32                 :                : #include "access/xact.h"
                                 33                 :                : #include "catalog/index.h"
                                 34                 :                : #include "catalog/pg_am.h"
                                 35                 :                : #include "catalog/pg_opfamily_d.h"
                                 36                 :                : #include "commands/tablecmds.h"
                                 37                 :                : #include "common/pg_prng.h"
                                 38                 :                : #include "lib/bloomfilter.h"
                                 39                 :                : #include "miscadmin.h"
                                 40                 :                : #include "storage/lmgr.h"
                                 41                 :                : #include "storage/smgr.h"
                                 42                 :                : #include "utils/guc.h"
                                 43                 :                : #include "utils/memutils.h"
                                 44                 :                : #include "utils/snapmgr.h"
                                 45                 :                : 
                                 46                 :                : 
 2593 andres@anarazel.de         47                 :CBC         317 : PG_MODULE_MAGIC;
                                 48                 :                : 
                                 49                 :                : /*
                                 50                 :                :  * A B-Tree cannot possibly have this many levels, since there must be one
                                 51                 :                :  * block per level, which is bound by the range of BlockNumber:
                                 52                 :                :  */
                                 53                 :                : #define InvalidBtreeLevel   ((uint32) InvalidBlockNumber)
                                 54                 :                : #define BTreeTupleGetNKeyAtts(itup, rel)   \
                                 55                 :                :     Min(IndexRelationGetNumberOfKeyAttributes(rel), BTreeTupleGetNAtts(itup, rel))
                                 56                 :                : 
                                 57                 :                : /*
                                 58                 :                :  * State associated with verifying a B-Tree index
                                 59                 :                :  *
                                 60                 :                :  * target is the point of reference for a verification operation.
                                 61                 :                :  *
                                 62                 :                :  * Other B-Tree pages may be allocated, but those are always auxiliary (e.g.,
                                 63                 :                :  * they are current target's child pages).  Conceptually, problems are only
                                 64                 :                :  * ever found in the current target page (or for a particular heap tuple during
                                 65                 :                :  * heapallindexed verification).  Each page found by verification's left/right,
                                 66                 :                :  * top/bottom scan becomes the target exactly once.
                                 67                 :                :  */
                                 68                 :                : typedef struct BtreeCheckState
                                 69                 :                : {
                                 70                 :                :     /*
                                 71                 :                :      * Unchanging state, established at start of verification:
                                 72                 :                :      */
                                 73                 :                : 
                                 74                 :                :     /* B-Tree Index Relation and associated heap relation */
                                 75                 :                :     Relation    rel;
                                 76                 :                :     Relation    heaprel;
                                 77                 :                :     /* rel is heapkeyspace index? */
                                 78                 :                :     bool        heapkeyspace;
                                 79                 :                :     /* ShareLock held on heap/index, rather than AccessShareLock? */
                                 80                 :                :     bool        readonly;
                                 81                 :                :     /* Also verifying heap has no unindexed tuples? */
                                 82                 :                :     bool        heapallindexed;
                                 83                 :                :     /* Also making sure non-pivot tuples can be found by new search? */
                                 84                 :                :     bool        rootdescend;
                                 85                 :                :     /* Also check uniqueness constraint if index is unique */
                                 86                 :                :     bool        checkunique;
                                 87                 :                :     /* Per-page context */
                                 88                 :                :     MemoryContext targetcontext;
                                 89                 :                :     /* Buffer access strategy */
                                 90                 :                :     BufferAccessStrategy checkstrategy;
                                 91                 :                : 
                                 92                 :                :     /*
                                 93                 :                :      * Info for uniqueness checking. Fill these fields once per index check.
                                 94                 :                :      */
                                 95                 :                :     IndexInfo  *indexinfo;
                                 96                 :                :     Snapshot    snapshot;
                                 97                 :                : 
                                 98                 :                :     /*
                                 99                 :                :      * Mutable state, for verification of particular page:
                                100                 :                :      */
                                101                 :                : 
                                102                 :                :     /* Current target page */
                                103                 :                :     Page        target;
                                104                 :                :     /* Target block number */
                                105                 :                :     BlockNumber targetblock;
                                106                 :                :     /* Target page's LSN */
                                107                 :                :     XLogRecPtr  targetlsn;
                                108                 :                : 
                                109                 :                :     /*
                                110                 :                :      * Low key: high key of left sibling of target page.  Used only for child
                                111                 :                :      * verification.  So, 'lowkey' is kept only when 'readonly' is set.
                                112                 :                :      */
                                113                 :                :     IndexTuple  lowkey;
                                114                 :                : 
                                115                 :                :     /*
                                116                 :                :      * The rightlink and incomplete split flag of block one level down to the
                                117                 :                :      * target page, which was visited last time via downlink from target page.
                                118                 :                :      * We use it to check for missing downlinks.
                                119                 :                :      */
                                120                 :                :     BlockNumber prevrightlink;
                                121                 :                :     bool        previncompletesplit;
                                122                 :                : 
                                123                 :                :     /*
                                124                 :                :      * Mutable state, for optional heapallindexed verification:
                                125                 :                :      */
                                126                 :                : 
                                127                 :                :     /* Bloom filter fingerprints B-Tree index */
                                128                 :                :     bloom_filter *filter;
                                129                 :                :     /* Debug counter */
                                130                 :                :     int64       heaptuplespresent;
                                131                 :                : } BtreeCheckState;
                                132                 :                : 
                                133                 :                : /*
                                134                 :                :  * Starting point for verifying an entire B-Tree index level
                                135                 :                :  */
                                136                 :                : typedef struct BtreeLevel
                                137                 :                : {
                                138                 :                :     /* Level number (0 is leaf page level). */
                                139                 :                :     uint32      level;
                                140                 :                : 
                                141                 :                :     /* Left most block on level.  Scan of level begins here. */
                                142                 :                :     BlockNumber leftmost;
                                143                 :                : 
                                144                 :                :     /* Is this level reported as "true" root level by meta page? */
                                145                 :                :     bool        istruerootlevel;
                                146                 :                : } BtreeLevel;
                                147                 :                : 
                                148                 :             88 : PG_FUNCTION_INFO_V1(bt_index_check);
                                149                 :             60 : PG_FUNCTION_INFO_V1(bt_index_parent_check);
                                150                 :                : 
                                151                 :                : static void bt_index_check_internal(Oid indrelid, bool parentcheck,
                                152                 :                :                                     bool heapallindexed, bool rootdescend,
                                153                 :                :                                     bool checkunique);
                                154                 :                : static inline void btree_index_checkable(Relation rel);
                                155                 :                : static inline bool btree_index_mainfork_expected(Relation rel);
                                156                 :                : static void bt_check_every_level(Relation rel, Relation heaprel,
                                157                 :                :                                  bool heapkeyspace, bool readonly, bool heapallindexed,
                                158                 :                :                                  bool rootdescend, bool checkunique);
                                159                 :                : static BtreeLevel bt_check_level_from_leftmost(BtreeCheckState *state,
                                160                 :                :                                                BtreeLevel level);
                                161                 :                : static bool bt_leftmost_ignoring_half_dead(BtreeCheckState *state,
                                162                 :                :                                            BlockNumber start,
                                163                 :                :                                            BTPageOpaque start_opaque);
                                164                 :                : static void bt_recheck_sibling_links(BtreeCheckState *state,
                                165                 :                :                                      BlockNumber btpo_prev_from_target,
                                166                 :                :                                      BlockNumber leftcurrent);
                                167                 :                : static bool heap_entry_is_visible(BtreeCheckState *state, ItemPointer tid);
                                168                 :                : static void bt_report_duplicate(BtreeCheckState *state, ItemPointer tid,
                                169                 :                :                                 BlockNumber block, OffsetNumber offset,
                                170                 :                :                                 int posting, ItemPointer nexttid,
                                171                 :                :                                 BlockNumber nblock, OffsetNumber noffset,
                                172                 :                :                                 int nposting);
                                173                 :                : static void bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup,
                                174                 :                :                                   BlockNumber targetblock,
                                175                 :                :                                   OffsetNumber offset, int *lVis_i,
                                176                 :                :                                   ItemPointer *lVis_tid,
                                177                 :                :                                   OffsetNumber *lVis_offset,
                                178                 :                :                                   BlockNumber *lVis_block);
                                179                 :                : static void bt_target_page_check(BtreeCheckState *state);
                                180                 :                : static BTScanInsert bt_right_page_check_scankey(BtreeCheckState *state,
                                181                 :                :                                                 OffsetNumber *rightfirstoffset);
                                182                 :                : static void bt_child_check(BtreeCheckState *state, BTScanInsert targetkey,
                                183                 :                :                            OffsetNumber downlinkoffnum);
                                184                 :                : static void bt_child_highkey_check(BtreeCheckState *state,
                                185                 :                :                                    OffsetNumber target_downlinkoffnum,
                                186                 :                :                                    Page loaded_child,
                                187                 :                :                                    uint32 target_level);
                                188                 :                : static void bt_downlink_missing_check(BtreeCheckState *state, bool rightsplit,
                                189                 :                :                                       BlockNumber blkno, Page page);
                                190                 :                : static void bt_tuple_present_callback(Relation index, ItemPointer tid,
                                191                 :                :                                       Datum *values, bool *isnull,
                                192                 :                :                                       bool tupleIsAlive, void *checkstate);
                                193                 :                : static IndexTuple bt_normalize_tuple(BtreeCheckState *state,
                                194                 :                :                                      IndexTuple itup);
                                195                 :                : static inline IndexTuple bt_posting_plain_tuple(IndexTuple itup, int n);
                                196                 :                : static bool bt_rootdescend(BtreeCheckState *state, IndexTuple itup);
                                197                 :                : static inline bool offset_is_negative_infinity(BTPageOpaque opaque,
                                198                 :                :                                                OffsetNumber offset);
                                199                 :                : static inline bool invariant_l_offset(BtreeCheckState *state, BTScanInsert key,
                                200                 :                :                                       OffsetNumber upperbound);
                                201                 :                : static inline bool invariant_leq_offset(BtreeCheckState *state,
                                202                 :                :                                         BTScanInsert key,
                                203                 :                :                                         OffsetNumber upperbound);
                                204                 :                : static inline bool invariant_g_offset(BtreeCheckState *state, BTScanInsert key,
                                205                 :                :                                       OffsetNumber lowerbound);
                                206                 :                : static inline bool invariant_l_nontarget_offset(BtreeCheckState *state,
                                207                 :                :                                                 BTScanInsert key,
                                208                 :                :                                                 BlockNumber nontargetblock,
                                209                 :                :                                                 Page nontarget,
                                210                 :                :                                                 OffsetNumber upperbound);
                                211                 :                : static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum);
                                212                 :                : static inline BTScanInsert bt_mkscankey_pivotsearch(Relation rel,
                                213                 :                :                                                     IndexTuple itup);
                                214                 :                : static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block,
                                215                 :                :                                    Page page, OffsetNumber offset);
                                216                 :                : static inline ItemPointer BTreeTupleGetHeapTIDCareful(BtreeCheckState *state,
                                217                 :                :                                                       IndexTuple itup, bool nonpivot);
                                218                 :                : static inline ItemPointer BTreeTupleGetPointsToTID(IndexTuple itup);
                                219                 :                : 
                                220                 :                : /*
                                221                 :                :  * bt_index_check(index regclass, heapallindexed boolean, checkunique boolean)
                                222                 :                :  *
                                223                 :                :  * Verify integrity of B-Tree index.
                                224                 :                :  *
                                225                 :                :  * Acquires AccessShareLock on heap & index relations.  Does not consider
                                226                 :                :  * invariants that exist between parent/child pages.  Optionally verifies
                                227                 :                :  * that heap does not contain any unindexed or incorrectly indexed tuples.
                                228                 :                :  */
                                229                 :                : Datum
                                230                 :           3968 : bt_index_check(PG_FUNCTION_ARGS)
                                231                 :                : {
                                232                 :           3968 :     Oid         indrelid = PG_GETARG_OID(0);
 2206                           233                 :           3968 :     bool        heapallindexed = false;
  169 akorotkov@postgresql      234                 :GNC        3968 :     bool        checkunique = false;
                                235                 :                : 
                                236         [ +  + ]:           3968 :     if (PG_NARGS() >= 2)
 2206 andres@anarazel.de        237                 :CBC        3962 :         heapallindexed = PG_GETARG_BOOL(1);
  169 akorotkov@postgresql      238         [ +  + ]:GNC        3968 :     if (PG_NARGS() == 3)
                                239                 :            686 :         checkunique = PG_GETARG_BOOL(2);
                                240                 :                : 
                                241                 :           3968 :     bt_index_check_internal(indrelid, false, heapallindexed, false, checkunique);
                                242                 :                : 
 2593 andres@anarazel.de        243                 :CBC        3942 :     PG_RETURN_VOID();
                                244                 :                : }
                                245                 :                : 
                                246                 :                : /*
                                247                 :                :  * bt_index_parent_check(index regclass, heapallindexed boolean, rootdescend boolean, checkunique boolean)
                                248                 :                :  *
                                249                 :                :  * Verify integrity of B-Tree index.
                                250                 :                :  *
                                251                 :                :  * Acquires ShareLock on heap & index relations.  Verifies that downlinks in
                                252                 :                :  * parent pages are valid lower bounds on child pages.  Optionally verifies
                                253                 :                :  * that heap does not contain any unindexed or incorrectly indexed tuples.
                                254                 :                :  */
                                255                 :                : Datum
                                256                 :             60 : bt_index_parent_check(PG_FUNCTION_ARGS)
                                257                 :                : {
                                258                 :             60 :     Oid         indrelid = PG_GETARG_OID(0);
 2206                           259                 :             60 :     bool        heapallindexed = false;
 1852 pg@bowt.ie                260                 :             60 :     bool        rootdescend = false;
  169 akorotkov@postgresql      261                 :GNC          60 :     bool        checkunique = false;
                                262                 :                : 
 1852 pg@bowt.ie                263         [ +  + ]:CBC          60 :     if (PG_NARGS() >= 2)
 2206 andres@anarazel.de        264                 :             55 :         heapallindexed = PG_GETARG_BOOL(1);
  169 akorotkov@postgresql      265         [ +  + ]:GNC          60 :     if (PG_NARGS() >= 3)
 1852 pg@bowt.ie                266                 :CBC          52 :         rootdescend = PG_GETARG_BOOL(2);
  169 akorotkov@postgresql      267         [ +  + ]:GNC          60 :     if (PG_NARGS() == 4)
                                268                 :             26 :         checkunique = PG_GETARG_BOOL(3);
                                269                 :                : 
                                270                 :             60 :     bt_index_check_internal(indrelid, true, heapallindexed, rootdescend, checkunique);
                                271                 :                : 
 2593 andres@anarazel.de        272                 :CBC          43 :     PG_RETURN_VOID();
                                273                 :                : }
                                274                 :                : 
                                275                 :                : /*
                                276                 :                :  * Helper for bt_index_[parent_]check, coordinating the bulk of the work.
                                277                 :                :  */
                                278                 :                : static void
 1852 pg@bowt.ie                279                 :           4028 : bt_index_check_internal(Oid indrelid, bool parentcheck, bool heapallindexed,
                                280                 :                :                         bool rootdescend, bool checkunique)
                                281                 :                : {
                                282                 :                :     Oid         heapid;
                                283                 :                :     Relation    indrel;
                                284                 :                :     Relation    heaprel;
                                285                 :                :     LOCKMODE    lockmode;
                                286                 :                :     Oid         save_userid;
                                287                 :                :     int         save_sec_context;
                                288                 :                :     int         save_nestlevel;
                                289                 :                : 
 2593 andres@anarazel.de        290         [ +  + ]:           4028 :     if (parentcheck)
                                291                 :             60 :         lockmode = ShareLock;
                                292                 :                :     else
                                293                 :           3968 :         lockmode = AccessShareLock;
                                294                 :                : 
                                295                 :                :     /*
                                296                 :                :      * We must lock table before index to avoid deadlocks.  However, if the
                                297                 :                :      * passed indrelid isn't an index then IndexGetRelation() will fail.
                                298                 :                :      * Rather than emitting a not-very-helpful error message, postpone
                                299                 :                :      * complaining, expecting that the is-it-an-index test below will fail.
                                300                 :                :      *
                                301                 :                :      * In hot standby mode this will raise an error when parentcheck is true.
                                302                 :                :      */
                                303                 :           4028 :     heapid = IndexGetRelation(indrelid, true);
                                304         [ +  + ]:           4028 :     if (OidIsValid(heapid))
                                305                 :                :     {
 1910                           306                 :           4024 :         heaprel = table_open(heapid, lockmode);
                                307                 :                : 
                                308                 :                :         /*
                                309                 :                :          * Switch to the table owner's userid, so that any index functions are
                                310                 :                :          * run as that user.  Also lock down security-restricted operations
                                311                 :                :          * and arrange to make GUC variable changes local to this command.
                                312                 :                :          */
  706 noah@leadboat.com         313                 :           4024 :         GetUserIdAndSecContext(&save_userid, &save_sec_context);
                                314                 :           4024 :         SetUserIdAndSecContext(heaprel->rd_rel->relowner,
                                315                 :                :                                save_sec_context | SECURITY_RESTRICTED_OPERATION);
                                316                 :           4024 :         save_nestlevel = NewGUCNestLevel();
   41 jdavis@postgresql.or      317                 :GNC        4024 :         RestrictSearchPath();
                                318                 :                :     }
                                319                 :                :     else
                                320                 :                :     {
 2593 andres@anarazel.de        321                 :CBC           4 :         heaprel = NULL;
                                322                 :                :         /* Set these just to suppress "uninitialized variable" warnings */
  706 noah@leadboat.com         323                 :              4 :         save_userid = InvalidOid;
                                324                 :              4 :         save_sec_context = -1;
                                325                 :              4 :         save_nestlevel = -1;
                                326                 :                :     }
                                327                 :                : 
                                328                 :                :     /*
                                329                 :                :      * Open the target index relations separately (like relation_openrv(), but
                                330                 :                :      * with heap relation locked first to prevent deadlocking).  In hot
                                331                 :                :      * standby mode this will raise an error when parentcheck is true.
                                332                 :                :      *
                                333                 :                :      * There is no need for the usual indcheckxmin usability horizon test
                                334                 :                :      * here, even in the heapallindexed case, because index undergoing
                                335                 :                :      * verification only needs to have entries for a new transaction snapshot.
                                336                 :                :      * (If this is a parentcheck verification, there is no question about
                                337                 :                :      * committed or recently dead heap tuples lacking index entries due to
                                338                 :                :      * concurrent activity.)
                                339                 :                :      */
 2593 andres@anarazel.de        340                 :           4028 :     indrel = index_open(indrelid, lockmode);
                                341                 :                : 
                                342                 :                :     /*
                                343                 :                :      * Since we did the IndexGetRelation call above without any lock, it's
                                344                 :                :      * barely possible that a race against an index drop/recreation could have
                                345                 :                :      * netted us the wrong table.
                                346                 :                :      */
                                347   [ +  -  -  + ]:           4024 :     if (heaprel == NULL || heapid != IndexGetRelation(indrelid, false))
 2593 andres@anarazel.de        348         [ #  # ]:UBC           0 :         ereport(ERROR,
                                349                 :                :                 (errcode(ERRCODE_UNDEFINED_TABLE),
                                350                 :                :                  errmsg("could not open parent table of index \"%s\"",
                                351                 :                :                         RelationGetRelationName(indrel))));
                                352                 :                : 
                                353                 :                :     /* Relation suitable for checking as B-Tree? */
 2593 andres@anarazel.de        354                 :CBC        4024 :     btree_index_checkable(indrel);
                                355                 :                : 
 1707 pg@bowt.ie                356         [ +  - ]:           4023 :     if (btree_index_mainfork_expected(indrel))
                                357                 :                :     {
                                358                 :                :         bool        heapkeyspace,
                                359                 :                :                     allequalimage;
                                360                 :                : 
 1007 tgl@sss.pgh.pa.us         361         [ +  + ]:           4023 :         if (!smgrexists(RelationGetSmgr(indrel), MAIN_FORKNUM))
 1707 pg@bowt.ie                362         [ +  - ]:             18 :             ereport(ERROR,
                                363                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                                364                 :                :                      errmsg("index \"%s\" lacks a main relation fork",
                                365                 :                :                             RelationGetRelationName(indrel))));
                                366                 :                : 
                                367                 :                :         /* Extract metadata from metapage, and sanitize it in passing */
  309                           368                 :           4005 :         _bt_metaversion(indrel, &heapkeyspace, &allequalimage);
 1347                           369   [ +  +  -  + ]:           4005 :         if (allequalimage && !heapkeyspace)
 1347 pg@bowt.ie                370         [ #  # ]:UBC           0 :             ereport(ERROR,
                                371                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                                372                 :                :                      errmsg("index \"%s\" metapage has equalimage field set on unsupported nbtree version",
                                373                 :                :                             RelationGetRelationName(indrel))));
 1347 pg@bowt.ie                374   [ +  +  -  + ]:CBC        4005 :         if (allequalimage && !_bt_allequalimage(indrel, false))
                                375                 :                :         {
  183 noah@leadboat.com         376                 :UBC           0 :             bool        has_interval_ops = false;
                                377                 :                : 
                                378         [ #  # ]:              0 :             for (int i = 0; i < IndexRelationGetNumberOfKeyAttributes(indrel); i++)
                                379         [ #  # ]:              0 :                 if (indrel->rd_opfamily[i] == INTERVAL_BTREE_FAM_OID)
                                380                 :              0 :                     has_interval_ops = true;
 1347 pg@bowt.ie                381   [ #  #  #  # ]:              0 :             ereport(ERROR,
                                382                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                                383                 :                :                      errmsg("index \"%s\" metapage incorrectly indicates that deduplication is safe",
                                384                 :                :                             RelationGetRelationName(indrel)),
                                385                 :                :                      has_interval_ops
                                386                 :                :                      ? errhint("This is known of \"interval\" indexes last built on a version predating 2023-11.")
                                387                 :                :                      : 0));
                                388                 :                :         }
                                389                 :                : 
                                390                 :                :         /* Check index, possibly against table it is an index on */
 1707 pg@bowt.ie                391                 :CBC        4005 :         bt_check_every_level(indrel, heaprel, heapkeyspace, parentcheck,
                                392                 :                :                              heapallindexed, rootdescend, checkunique);
                                393                 :                :     }
                                394                 :                : 
                                395                 :                :     /* Roll back any GUC changes executed by index functions */
  706 noah@leadboat.com         396                 :           3985 :     AtEOXact_GUC(false, save_nestlevel);
                                397                 :                : 
                                398                 :                :     /* Restore userid and security context */
                                399                 :           3985 :     SetUserIdAndSecContext(save_userid, save_sec_context);
                                400                 :                : 
                                401                 :                :     /*
                                402                 :                :      * Release locks early. That's ok here because nothing in the called
                                403                 :                :      * routines will trigger shared cache invalidations to be sent, so we can
                                404                 :                :      * relax the usual pattern of only releasing locks after commit.
                                405                 :                :      */
 2593 andres@anarazel.de        406                 :           3985 :     index_close(indrel, lockmode);
                                407         [ +  - ]:           3985 :     if (heaprel)
 1910                           408                 :           3985 :         table_close(heaprel, lockmode);
 2593                           409                 :           3985 : }
                                410                 :                : 
                                411                 :                : /*
                                412                 :                :  * Basic checks about the suitability of a relation for checking as a B-Tree
                                413                 :                :  * index.
                                414                 :                :  *
                                415                 :                :  * NB: Intentionally not checking permissions, the function is normally not
                                416                 :                :  * callable by non-superusers. If granted, it's useful to be able to check a
                                417                 :                :  * whole cluster.
                                418                 :                :  */
                                419                 :                : static inline void
                                420                 :           4024 : btree_index_checkable(Relation rel)
                                421                 :                : {
                                422         [ +  - ]:           4024 :     if (rel->rd_rel->relkind != RELKIND_INDEX ||
                                423         [ +  + ]:           4024 :         rel->rd_rel->relam != BTREE_AM_OID)
                                424         [ +  - ]:              1 :         ereport(ERROR,
                                425                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                426                 :                :                  errmsg("only B-Tree indexes are supported as targets for verification"),
                                427                 :                :                  errdetail("Relation \"%s\" is not a B-Tree index.",
                                428                 :                :                            RelationGetRelationName(rel))));
                                429                 :                : 
                                430   [ -  +  -  - ]:           4023 :     if (RELATION_IS_OTHER_TEMP(rel))
 2593 andres@anarazel.de        431         [ #  # ]:UBC           0 :         ereport(ERROR,
                                432                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                433                 :                :                  errmsg("cannot access temporary tables of other sessions"),
                                434                 :                :                  errdetail("Index \"%s\" is associated with temporary relation.",
                                435                 :                :                            RelationGetRelationName(rel))));
                                436                 :                : 
 1935 peter_e@gmx.net           437         [ -  + ]:CBC        4023 :     if (!rel->rd_index->indisvalid)
 2593 andres@anarazel.de        438         [ #  # ]:UBC           0 :         ereport(ERROR,
                                439                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                440                 :                :                  errmsg("cannot check index \"%s\"",
                                441                 :                :                         RelationGetRelationName(rel)),
                                442                 :                :                  errdetail("Index is not valid.")));
 2593 andres@anarazel.de        443                 :CBC        4023 : }
                                444                 :                : 
                                445                 :                : /*
                                446                 :                :  * Check if B-Tree index relation should have a file for its main relation
                                447                 :                :  * fork.  Verification uses this to skip unlogged indexes when in hot standby
                                448                 :                :  * mode, where there is simply nothing to verify.  We behave as if the
                                449                 :                :  * relation is empty.
                                450                 :                :  *
                                451                 :                :  * NB: Caller should call btree_index_checkable() before calling here.
                                452                 :                :  */
                                453                 :                : static inline bool
 1707 pg@bowt.ie                454                 :           4023 : btree_index_mainfork_expected(Relation rel)
                                455                 :                : {
                                456         [ -  + ]:           4023 :     if (rel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED ||
 1707 pg@bowt.ie                457         [ #  # ]:UBC           0 :         !RecoveryInProgress())
 1707 pg@bowt.ie                458                 :CBC        4023 :         return true;
                                459                 :                : 
  916 pg@bowt.ie                460         [ #  # ]:UBC           0 :     ereport(DEBUG1,
                                461                 :                :             (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
                                462                 :                :              errmsg("cannot verify unlogged index \"%s\" during recovery, skipping",
                                463                 :                :                     RelationGetRelationName(rel))));
                                464                 :                : 
 1707                           465                 :              0 :     return false;
                                466                 :                : }
                                467                 :                : 
                                468                 :                : /*
                                469                 :                :  * Main entry point for B-Tree SQL-callable functions. Walks the B-Tree in
                                470                 :                :  * logical order, verifying invariants as it goes.  Optionally, verification
                                471                 :                :  * checks if the heap relation contains any tuples that are not represented in
                                472                 :                :  * the index but should be.
                                473                 :                :  *
                                474                 :                :  * It is the caller's responsibility to acquire appropriate heavyweight lock on
                                475                 :                :  * the index relation, and advise us if extra checks are safe when a ShareLock
                                476                 :                :  * is held.  (A lock of the same type must also have been acquired on the heap
                                477                 :                :  * relation.)
                                478                 :                :  *
                                479                 :                :  * A ShareLock is generally assumed to prevent any kind of physical
                                480                 :                :  * modification to the index structure, including modifications that VACUUM may
                                481                 :                :  * make.  This does not include setting of the LP_DEAD bit by concurrent index
                                482                 :                :  * scans, although that is just metadata that is not able to directly affect
                                483                 :                :  * any check performed here.  Any concurrent process that might act on the
                                484                 :                :  * LP_DEAD bit being set (recycle space) requires a heavyweight lock that
                                485                 :                :  * cannot be held while we hold a ShareLock.  (Besides, even if that could
                                486                 :                :  * happen, the ad-hoc recycling when a page might otherwise split is performed
                                487                 :                :  * per-page, and requires an exclusive buffer lock, which wouldn't cause us
                                488                 :                :  * trouble.  _bt_delitems_vacuum() may only delete leaf items, and so the extra
                                489                 :                :  * parent/child check cannot be affected.)
                                490                 :                :  */
                                491                 :                : static void
 1852 pg@bowt.ie                492                 :CBC        4005 : bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
                                493                 :                :                      bool readonly, bool heapallindexed, bool rootdescend,
                                494                 :                :                      bool checkunique)
                                495                 :                : {
                                496                 :                :     BtreeCheckState *state;
                                497                 :                :     Page        metapage;
                                498                 :                :     BTMetaPageData *metad;
                                499                 :                :     uint32      previouslevel;
                                500                 :                :     BtreeLevel  current;
 2206 andres@anarazel.de        501                 :           4005 :     Snapshot    snapshot = SnapshotAny;
                                502                 :                : 
 1465 pg@bowt.ie                503         [ +  + ]:           4005 :     if (!readonly)
                                504         [ +  + ]:           3956 :         elog(DEBUG1, "verifying consistency of tree structure for index \"%s\"",
                                505                 :                :              RelationGetRelationName(rel));
                                506                 :                :     else
                                507         [ +  + ]:             49 :         elog(DEBUG1, "verifying consistency of tree structure for index \"%s\" with cross-level checks",
                                508                 :                :              RelationGetRelationName(rel));
                                509                 :                : 
                                510                 :                :     /*
                                511                 :                :      * This assertion matches the one in index_getnext_tid().  See page
                                512                 :                :      * recycling/"visible to everyone" notes in nbtree README.
                                513                 :                :      */
 1341 andres@anarazel.de        514         [ -  + ]:           4005 :     Assert(TransactionIdIsValid(RecentXmin));
                                515                 :                : 
                                516                 :                :     /*
                                517                 :                :      * Initialize state for entire verification operation
                                518                 :                :      */
 2181 teodor@sigaev.ru          519                 :           4005 :     state = palloc0(sizeof(BtreeCheckState));
 2593 andres@anarazel.de        520                 :           4005 :     state->rel = rel;
 2206                           521                 :           4005 :     state->heaprel = heaprel;
 1852 pg@bowt.ie                522                 :           4005 :     state->heapkeyspace = heapkeyspace;
 2593 andres@anarazel.de        523                 :           4005 :     state->readonly = readonly;
 2206                           524                 :           4005 :     state->heapallindexed = heapallindexed;
 1852 pg@bowt.ie                525                 :           4005 :     state->rootdescend = rootdescend;
  169 akorotkov@postgresql      526                 :GNC        4005 :     state->checkunique = checkunique;
                                527                 :           4005 :     state->snapshot = InvalidSnapshot;
                                528                 :                : 
 2206 andres@anarazel.de        529         [ +  + ]:CBC        4005 :     if (state->heapallindexed)
                                530                 :                :     {
                                531                 :                :         int64       total_pages;
                                532                 :                :         int64       total_elems;
                                533                 :                :         uint64      seed;
                                534                 :                : 
                                535                 :                :         /*
                                536                 :                :          * Size Bloom filter based on estimated number of tuples in index,
                                537                 :                :          * while conservatively assuming that each block must contain at least
                                538                 :                :          * MaxTIDsPerBTreePage / 3 "plain" tuples -- see
                                539                 :                :          * bt_posting_plain_tuple() for definition, and details of how posting
                                540                 :                :          * list tuples are handled.
                                541                 :                :          */
 1730 pg@bowt.ie                542                 :             83 :         total_pages = RelationGetNumberOfBlocks(rel);
 1509                           543                 :             83 :         total_elems = Max(total_pages * (MaxTIDsPerBTreePage / 3),
                                544                 :                :                           (int64) state->rel->rd_rel->reltuples);
                                545                 :                :         /* Generate a random seed to avoid repetition */
  868 tgl@sss.pgh.pa.us         546                 :             83 :         seed = pg_prng_uint64(&pg_global_prng_state);
                                547                 :                :         /* Create Bloom filter to fingerprint index */
 2206 andres@anarazel.de        548                 :             83 :         state->filter = bloom_create(total_elems, maintenance_work_mem, seed);
                                549                 :             83 :         state->heaptuplespresent = 0;
                                550                 :                : 
                                551                 :                :         /*
                                552                 :                :          * Register our own snapshot in !readonly case, rather than asking
                                553                 :                :          * table_index_build_scan() to do this for us later.  This needs to
                                554                 :                :          * happen before index fingerprinting begins, so we can later be
                                555                 :                :          * certain that index fingerprinting should have reached all tuples
                                556                 :                :          * returned by table_index_build_scan().
                                557                 :                :          */
                                558         [ +  + ]:             83 :         if (!state->readonly)
                                559                 :                :         {
                                560                 :             56 :             snapshot = RegisterSnapshot(GetTransactionSnapshot());
                                561                 :                : 
                                562                 :                :             /*
                                563                 :                :              * GetTransactionSnapshot() always acquires a new MVCC snapshot in
                                564                 :                :              * READ COMMITTED mode.  A new snapshot is guaranteed to have all
                                565                 :                :              * the entries it requires in the index.
                                566                 :                :              *
                                567                 :                :              * We must defend against the possibility that an old xact
                                568                 :                :              * snapshot was returned at higher isolation levels when that
                                569                 :                :              * snapshot is not safe for index scans of the target index.  This
                                570                 :                :              * is possible when the snapshot sees tuples that are before the
                                571                 :                :              * index's indcheckxmin horizon.  Throwing an error here should be
                                572                 :                :              * very rare.  It doesn't seem worth using a secondary snapshot to
                                573                 :                :              * avoid this.
                                574                 :                :              */
                                575   [ -  +  -  - ]:             56 :             if (IsolationUsesXactSnapshot() && rel->rd_index->indcheckxmin &&
 2206 andres@anarazel.de        576   [ #  #  #  # ]:UBC           0 :                 !TransactionIdPrecedes(HeapTupleHeaderGetXmin(rel->rd_indextuple->t_data),
                                577                 :                :                                        snapshot->xmin))
                                578         [ #  # ]:              0 :                 ereport(ERROR,
                                579                 :                :                         (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
                                580                 :                :                          errmsg("index \"%s\" cannot be verified using transaction snapshot",
                                581                 :                :                                 RelationGetRelationName(rel))));
                                582                 :                :         }
                                583                 :                :     }
                                584                 :                : 
                                585                 :                :     /*
                                586                 :                :      * We need a snapshot to check the uniqueness of the index. For better
                                587                 :                :      * performance take it once per index check. If snapshot already taken
                                588                 :                :      * reuse it.
                                589                 :                :      */
  169 akorotkov@postgresql      590         [ +  + ]:GNC        4005 :     if (state->checkunique)
                                591                 :                :     {
                                592                 :            708 :         state->indexinfo = BuildIndexInfo(state->rel);
                                593         [ +  + ]:            708 :         if (state->indexinfo->ii_Unique)
                                594                 :                :         {
                                595         [ +  + ]:            638 :             if (snapshot != SnapshotAny)
                                596                 :              7 :                 state->snapshot = snapshot;
                                597                 :                :             else
                                598                 :            631 :                 state->snapshot = RegisterSnapshot(GetTransactionSnapshot());
                                599                 :                :         }
                                600                 :                :     }
                                601                 :                : 
 1852 pg@bowt.ie                602   [ +  +  -  + ]:CBC        4005 :     Assert(!state->rootdescend || state->readonly);
                                603   [ +  +  -  + ]:           4005 :     if (state->rootdescend && !state->heapkeyspace)
 1852 pg@bowt.ie                604         [ #  # ]:UBC           0 :         ereport(ERROR,
                                605                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                606                 :                :                  errmsg("cannot verify that tuples from index \"%s\" can each be found by an independent index search",
                                607                 :                :                         RelationGetRelationName(rel)),
                                608                 :                :                  errhint("Only B-Tree version 4 indexes support rootdescend verification.")));
                                609                 :                : 
                                610                 :                :     /* Create context for page */
 2593 andres@anarazel.de        611                 :CBC        4005 :     state->targetcontext = AllocSetContextCreate(CurrentMemoryContext,
                                612                 :                :                                                  "amcheck context",
                                613                 :                :                                                  ALLOCSET_DEFAULT_SIZES);
                                614                 :           4005 :     state->checkstrategy = GetAccessStrategy(BAS_BULKREAD);
                                615                 :                : 
                                616                 :                :     /* Get true root block from meta-page */
                                617                 :           4005 :     metapage = palloc_btree_page(state, BTREE_METAPAGE);
                                618                 :           4005 :     metad = BTPageGetMeta(metapage);
                                619                 :                : 
                                620                 :                :     /*
                                621                 :                :      * Certain deletion patterns can result in "skinny" B-Tree indexes, where
                                622                 :                :      * the fast root and true root differ.
                                623                 :                :      *
                                624                 :                :      * Start from the true root, not the fast root, unlike conventional index
                                625                 :                :      * scans.  This approach is more thorough, and removes the risk of
                                626                 :                :      * following a stale fast root from the meta page.
                                627                 :                :      */
                                628         [ +  + ]:           4005 :     if (metad->btm_fastroot != metad->btm_root)
                                629         [ -  + ]:             13 :         ereport(DEBUG1,
                                630                 :                :                 (errcode(ERRCODE_NO_DATA),
                                631                 :                :                  errmsg_internal("harmless fast root mismatch in index \"%s\"",
                                632                 :                :                                  RelationGetRelationName(rel)),
                                633                 :                :                  errdetail_internal("Fast root block %u (level %u) differs from true root block %u (level %u).",
                                634                 :                :                                     metad->btm_fastroot, metad->btm_fastlevel,
                                635                 :                :                                     metad->btm_root, metad->btm_level)));
                                636                 :                : 
                                637                 :                :     /*
                                638                 :                :      * Starting at the root, verify every level.  Move left to right, top to
                                639                 :                :      * bottom.  Note that there may be no pages other than the meta page (meta
                                640                 :                :      * page can indicate that root is P_NONE when the index is totally empty).
                                641                 :                :      */
                                642                 :           4005 :     previouslevel = InvalidBtreeLevel;
                                643                 :           4005 :     current.level = metad->btm_level;
                                644                 :           4005 :     current.leftmost = metad->btm_root;
                                645                 :           4005 :     current.istruerootlevel = true;
                                646         [ +  + ]:           6464 :     while (current.leftmost != P_NONE)
                                647                 :                :     {
                                648                 :                :         /*
                                649                 :                :          * Verify this level, and get left most page for next level down, if
                                650                 :                :          * not at leaf level
                                651                 :                :          */
                                652                 :           2477 :         current = bt_check_level_from_leftmost(state, current);
                                653                 :                : 
                                654         [ -  + ]:           2459 :         if (current.leftmost == InvalidBlockNumber)
 2593 andres@anarazel.de        655         [ #  # ]:UBC           0 :             ereport(ERROR,
                                656                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                                657                 :                :                      errmsg("index \"%s\" has no valid pages on level below %u or first level",
                                658                 :                :                             RelationGetRelationName(rel), previouslevel)));
                                659                 :                : 
 2593 andres@anarazel.de        660                 :CBC        2459 :         previouslevel = current.level;
                                661                 :                :     }
                                662                 :                : 
                                663                 :                :     /*
                                664                 :                :      * * Check whether heap contains unindexed/malformed tuples *
                                665                 :                :      */
 2206                           666         [ +  + ]:           3987 :     if (state->heapallindexed)
                                667                 :                :     {
                                668                 :             76 :         IndexInfo  *indexinfo = BuildIndexInfo(state->rel);
                                669                 :                :         TableScanDesc scan;
                                670                 :                : 
                                671                 :                :         /*
                                672                 :                :          * Create our own scan for table_index_build_scan(), rather than
                                673                 :                :          * getting it to do so for us.  This is required so that we can
                                674                 :                :          * actually use the MVCC snapshot registered earlier in !readonly
                                675                 :                :          * case.
                                676                 :                :          *
                                677                 :                :          * Note that table_index_build_scan() calls heap_endscan() for us.
                                678                 :                :          */
 1845                           679                 :             76 :         scan = table_beginscan_strat(state->heaprel, /* relation */
                                680                 :                :                                      snapshot,  /* snapshot */
                                681                 :                :                                      0, /* number of keys */
                                682                 :                :                                      NULL,  /* scan key */
                                683                 :                :                                      true,  /* buffer access strategy OK */
                                684                 :                :                                      true); /* syncscan OK? */
                                685                 :                : 
                                686                 :                :         /*
                                687                 :                :          * Scan will behave as the first scan of a CREATE INDEX CONCURRENTLY
                                688                 :                :          * behaves in !readonly case.
                                689                 :                :          *
                                690                 :                :          * It's okay that we don't actually use the same lock strength for the
                                691                 :                :          * heap relation as any other ii_Concurrent caller would in !readonly
                                692                 :                :          * case.  We have no reason to care about a concurrent VACUUM
                                693                 :                :          * operation, since there isn't going to be a second scan of the heap
                                694                 :                :          * that needs to be sure that there was no concurrent recycling of
                                695                 :                :          * TIDs.
                                696                 :                :          */
 2206                           697                 :             74 :         indexinfo->ii_Concurrent = !state->readonly;
                                698                 :                : 
                                699                 :                :         /*
                                700                 :                :          * Don't wait for uncommitted tuple xact commit/abort when index is a
                                701                 :                :          * unique index on a catalog (or an index used by an exclusion
                                702                 :                :          * constraint).  This could otherwise happen in the readonly case.
                                703                 :                :          */
                                704                 :             74 :         indexinfo->ii_Unique = false;
                                705                 :             74 :         indexinfo->ii_ExclusionOps = NULL;
                                706                 :             74 :         indexinfo->ii_ExclusionProcs = NULL;
                                707                 :             74 :         indexinfo->ii_ExclusionStrats = NULL;
                                708                 :                : 
                                709         [ +  + ]:             74 :         elog(DEBUG1, "verifying that tuples from index \"%s\" are present in \"%s\"",
                                710                 :                :              RelationGetRelationName(state->rel),
                                711                 :                :              RelationGetRelationName(state->heaprel));
                                712                 :                : 
 1839 alvherre@alvh.no-ip.      713                 :             74 :         table_index_build_scan(state->heaprel, state->rel, indexinfo, true, false,
                                714                 :                :                                bt_tuple_present_callback, (void *) state, scan);
                                715                 :                : 
 2206 andres@anarazel.de        716         [ +  + ]:             74 :         ereport(DEBUG1,
                                717                 :                :                 (errmsg_internal("finished verifying presence of " INT64_FORMAT " tuples from table \"%s\" with bitset %.2f%% set",
                                718                 :                :                                  state->heaptuplespresent, RelationGetRelationName(heaprel),
                                719                 :                :                                  100.0 * bloom_prop_bits_set(state->filter))));
                                720                 :                : 
                                721         [ +  + ]:             74 :         if (snapshot != SnapshotAny)
                                722                 :             51 :             UnregisterSnapshot(snapshot);
                                723                 :                : 
                                724                 :             74 :         bloom_free(state->filter);
                                725                 :                :     }
                                726                 :                : 
                                727                 :                :     /* Be tidy: */
  169 akorotkov@postgresql      728   [ +  +  +  + ]:GNC        3985 :     if (snapshot == SnapshotAny && state->snapshot != InvalidSnapshot)
                                729                 :            631 :         UnregisterSnapshot(state->snapshot);
 2593 andres@anarazel.de        730                 :CBC        3985 :     MemoryContextDelete(state->targetcontext);
                                731                 :           3985 : }
                                732                 :                : 
                                733                 :                : /*
                                734                 :                :  * Given a left-most block at some level, move right, verifying each page
                                735                 :                :  * individually (with more verification across pages for "readonly"
                                736                 :                :  * callers).  Caller should pass the true root page as the leftmost initially,
                                737                 :                :  * working their way down by passing what is returned for the last call here
                                738                 :                :  * until level 0 (leaf page level) was reached.
                                739                 :                :  *
                                740                 :                :  * Returns state for next call, if any.  This includes left-most block number
                                741                 :                :  * one level lower that should be passed on next level/call, which is set to
                                742                 :                :  * P_NONE on last call here (when leaf level is verified).  Level numbers
                                743                 :                :  * follow the nbtree convention: higher levels have higher numbers, because new
                                744                 :                :  * levels are added only due to a root page split.  Note that prior to the
                                745                 :                :  * first root page split, the root is also a leaf page, so there is always a
                                746                 :                :  * level 0 (leaf level), and it's always the last level processed.
                                747                 :                :  *
                                748                 :                :  * Note on memory management:  State's per-page context is reset here, between
                                749                 :                :  * each call to bt_target_page_check().
                                750                 :                :  */
                                751                 :                : static BtreeLevel
                                752                 :           2477 : bt_check_level_from_leftmost(BtreeCheckState *state, BtreeLevel level)
                                753                 :                : {
                                754                 :                :     /* State to establish early, concerning entire level */
                                755                 :                :     BTPageOpaque opaque;
                                756                 :                :     MemoryContext oldcontext;
                                757                 :                :     BtreeLevel  nextleveldown;
                                758                 :                : 
                                759                 :                :     /* Variables for iterating across level using right links */
                                760                 :           2477 :     BlockNumber leftcurrent = P_NONE;
                                761                 :           2477 :     BlockNumber current = level.leftmost;
                                762                 :                : 
                                763                 :                :     /* Initialize return state */
                                764                 :           2477 :     nextleveldown.leftmost = InvalidBlockNumber;
                                765                 :           2477 :     nextleveldown.level = InvalidBtreeLevel;
                                766                 :           2477 :     nextleveldown.istruerootlevel = false;
                                767                 :                : 
                                768                 :                :     /* Use page-level context for duration of this call */
                                769                 :           2477 :     oldcontext = MemoryContextSwitchTo(state->targetcontext);
                                770                 :                : 
 1465 pg@bowt.ie                771   [ +  +  +  +  :           2477 :     elog(DEBUG1, "verifying level %u%s", level.level,
                                              +  - ]
                                772                 :                :          level.istruerootlevel ?
                                773                 :                :          " (true root level)" : level.level == 0 ? " (leaf level)" : "");
                                774                 :                : 
 1495 akorotkov@postgresql      775                 :           2477 :     state->prevrightlink = InvalidBlockNumber;
                                776                 :           2477 :     state->previncompletesplit = false;
                                777                 :                : 
                                778                 :                :     do
                                779                 :                :     {
                                780                 :                :         /* Don't rely on CHECK_FOR_INTERRUPTS() calls at lower level */
 2593 andres@anarazel.de        781         [ -  + ]:           9092 :         CHECK_FOR_INTERRUPTS();
                                782                 :                : 
                                783                 :                :         /* Initialize state for this iteration */
                                784                 :           9092 :         state->targetblock = current;
                                785                 :           9092 :         state->target = palloc_btree_page(state, state->targetblock);
                                786                 :           9080 :         state->targetlsn = PageGetLSN(state->target);
                                787                 :                : 
  744 michael@paquier.xyz       788                 :           9080 :         opaque = BTPageGetOpaque(state->target);
                                789                 :                : 
 2593 andres@anarazel.de        790         [ -  + ]:           9080 :         if (P_IGNORE(opaque))
                                791                 :                :         {
                                792                 :                :             /*
                                793                 :                :              * Since there cannot be a concurrent VACUUM operation in readonly
                                794                 :                :              * mode, and since a page has no links within other pages
                                795                 :                :              * (siblings and parent) once it is marked fully deleted, it
                                796                 :                :              * should be impossible to land on a fully deleted page in
                                797                 :                :              * readonly mode. See bt_child_check() for further details.
                                798                 :                :              *
                                799                 :                :              * The bt_child_check() P_ISDELETED() check is repeated here so
                                800                 :                :              * that pages that are only reachable through sibling links get
                                801                 :                :              * checked.
                                802                 :                :              */
 2181 teodor@sigaev.ru          803   [ #  #  #  # ]:UBC           0 :             if (state->readonly && P_ISDELETED(opaque))
                                804         [ #  # ]:              0 :                 ereport(ERROR,
                                805                 :                :                         (errcode(ERRCODE_INDEX_CORRUPTED),
                                806                 :                :                          errmsg("downlink or sibling link points to deleted block in index \"%s\"",
                                807                 :                :                                 RelationGetRelationName(state->rel)),
                                808                 :                :                          errdetail_internal("Block=%u left block=%u left link from block=%u.",
                                809                 :                :                                             current, leftcurrent, opaque->btpo_prev)));
                                810                 :                : 
 2593 andres@anarazel.de        811         [ #  # ]:              0 :             if (P_RIGHTMOST(opaque))
                                812         [ #  # ]:              0 :                 ereport(ERROR,
                                813                 :                :                         (errcode(ERRCODE_INDEX_CORRUPTED),
                                814                 :                :                          errmsg("block %u fell off the end of index \"%s\"",
                                815                 :                :                                 current, RelationGetRelationName(state->rel))));
                                816                 :                :             else
                                817         [ #  # ]:              0 :                 ereport(DEBUG1,
                                818                 :                :                         (errcode(ERRCODE_NO_DATA),
                                819                 :                :                          errmsg_internal("block %u of index \"%s\" concurrently deleted",
                                820                 :                :                                          current, RelationGetRelationName(state->rel))));
                                821                 :              0 :             goto nextpage;
                                822                 :                :         }
 2593 andres@anarazel.de        823         [ +  + ]:CBC        9080 :         else if (nextleveldown.leftmost == InvalidBlockNumber)
                                824                 :                :         {
                                825                 :                :             /*
                                826                 :                :              * A concurrent page split could make the caller supplied leftmost
                                827                 :                :              * block no longer contain the leftmost page, or no longer be the
                                828                 :                :              * true root, but where that isn't possible due to heavyweight
                                829                 :                :              * locking, check that the first valid page meets caller's
                                830                 :                :              * expectations.
                                831                 :                :              */
                                832         [ +  + ]:           2465 :             if (state->readonly)
                                833                 :                :             {
  167 noah@leadboat.com         834         [ -  + ]:             44 :                 if (!bt_leftmost_ignoring_half_dead(state, current, opaque))
 2593 andres@anarazel.de        835         [ #  # ]:UBC           0 :                     ereport(ERROR,
                                836                 :                :                             (errcode(ERRCODE_INDEX_CORRUPTED),
                                837                 :                :                              errmsg("block %u is not leftmost in index \"%s\"",
                                838                 :                :                                     current, RelationGetRelationName(state->rel))));
                                839                 :                : 
 2593 andres@anarazel.de        840   [ +  +  -  + ]:CBC          44 :                 if (level.istruerootlevel && !P_ISROOT(opaque))
 2593 andres@anarazel.de        841         [ #  # ]:UBC           0 :                     ereport(ERROR,
                                842                 :                :                             (errcode(ERRCODE_INDEX_CORRUPTED),
                                843                 :                :                              errmsg("block %u is not true root in index \"%s\"",
                                844                 :                :                                     current, RelationGetRelationName(state->rel))));
                                845                 :                :             }
                                846                 :                : 
                                847                 :                :             /*
                                848                 :                :              * Before beginning any non-trivial examination of level, prepare
                                849                 :                :              * state for next bt_check_level_from_leftmost() invocation for
                                850                 :                :              * the next level for the next level down (if any).
                                851                 :                :              *
                                852                 :                :              * There should be at least one non-ignorable page per level,
                                853                 :                :              * unless this is the leaf level, which is assumed by caller to be
                                854                 :                :              * final level.
                                855                 :                :              */
 2593 andres@anarazel.de        856         [ +  + ]:CBC        2465 :             if (!P_ISLEAF(opaque))
                                857                 :                :             {
                                858                 :                :                 IndexTuple  itup;
                                859                 :                :                 ItemId      itemid;
                                860                 :                : 
                                861                 :                :                 /* Internal page -- downlink gets leftmost on next level */
 1816 pg@bowt.ie                862                 :            513 :                 itemid = PageGetItemIdCareful(state, state->targetblock,
                                863                 :                :                                               state->target,
                                864         [ +  + ]:            513 :                                               P_FIRSTDATAKEY(opaque));
 2593 andres@anarazel.de        865                 :            513 :                 itup = (IndexTuple) PageGetItem(state->target, itemid);
 1581 pg@bowt.ie                866                 :            513 :                 nextleveldown.leftmost = BTreeTupleGetDownLink(itup);
 1145                           867                 :            513 :                 nextleveldown.level = opaque->btpo_level - 1;
                                868                 :                :             }
                                869                 :                :             else
                                870                 :                :             {
                                871                 :                :                 /*
                                872                 :                :                  * Leaf page -- final level caller must process.
                                873                 :                :                  *
                                874                 :                :                  * Note that this could also be the root page, if there has
                                875                 :                :                  * been no root page split yet.
                                876                 :                :                  */
 2593 andres@anarazel.de        877                 :           1952 :                 nextleveldown.leftmost = P_NONE;
                                878                 :           1952 :                 nextleveldown.level = InvalidBtreeLevel;
                                879                 :                :             }
                                880                 :                : 
                                881                 :                :             /*
                                882                 :                :              * Finished setting up state for this call/level.  Control will
                                883                 :                :              * never end up back here in any future loop iteration for this
                                884                 :                :              * level.
                                885                 :                :              */
                                886                 :                :         }
                                887                 :                : 
                                888                 :                :         /*
                                889                 :                :          * Sibling links should be in mutual agreement.  There arises
                                890                 :                :          * leftcurrent == P_NONE && btpo_prev != P_NONE when the left sibling
                                891                 :                :          * of the parent's low-key downlink is half-dead.  (A half-dead page
                                892                 :                :          * has no downlink from its parent.)  Under heavyweight locking, the
                                893                 :                :          * last bt_leftmost_ignoring_half_dead() validated this btpo_prev.
                                894                 :                :          * Without heavyweight locking, validation of the P_NONE case remains
                                895                 :                :          * unimplemented.
                                896                 :                :          */
  167 noah@leadboat.com         897   [ +  +  -  + ]:           9080 :         if (opaque->btpo_prev != leftcurrent && leftcurrent != P_NONE)
 1345 pg@bowt.ie                898                 :UBC           0 :             bt_recheck_sibling_links(state, opaque->btpo_prev, leftcurrent);
                                899                 :                : 
                                900                 :                :         /* Check level */
 1145 pg@bowt.ie                901         [ -  + ]:CBC        9080 :         if (level.level != opaque->btpo_level)
 2593 andres@anarazel.de        902         [ #  # ]:UBC           0 :             ereport(ERROR,
                                903                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                                904                 :                :                      errmsg("leftmost down link for level points to block in index \"%s\" whose level is not one level down",
                                905                 :                :                             RelationGetRelationName(state->rel)),
                                906                 :                :                      errdetail_internal("Block pointed to=%u expected level=%u level in pointed to block=%u.",
                                907                 :                :                                         current, level.level, opaque->btpo_level)));
                                908                 :                : 
                                909                 :                :         /* Verify invariants for page */
 2593 andres@anarazel.de        910                 :CBC        9080 :         bt_target_page_check(state);
                                911                 :                : 
                                912                 :           9074 : nextpage:
                                913                 :                : 
                                914                 :                :         /* Try to detect circular links */
                                915   [ +  -  -  + ]:           9074 :         if (current == leftcurrent || current == opaque->btpo_prev)
 2593 andres@anarazel.de        916         [ #  # ]:UBC           0 :             ereport(ERROR,
                                917                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                                918                 :                :                      errmsg("circular link chain found in block %u of index \"%s\"",
                                919                 :                :                             current, RelationGetRelationName(state->rel))));
                                920                 :                : 
 1495 akorotkov@postgresql      921                 :CBC        9074 :         leftcurrent = current;
                                922                 :           9074 :         current = opaque->btpo_next;
                                923                 :                : 
                                924         [ +  + ]:           9074 :         if (state->lowkey)
                                925                 :                :         {
                                926         [ -  + ]:           1862 :             Assert(state->readonly);
                                927                 :           1862 :             pfree(state->lowkey);
                                928                 :           1862 :             state->lowkey = NULL;
                                929                 :                :         }
                                930                 :                : 
                                931                 :                :         /*
                                932                 :                :          * Copy current target high key as the low key of right sibling.
                                933                 :                :          * Allocate memory in upper level context, so it would be cleared
                                934                 :                :          * after reset of target context.
                                935                 :                :          *
                                936                 :                :          * We only need the low key in corner cases of checking child high
                                937                 :                :          * keys. We use high key only when incomplete split on the child level
                                938                 :                :          * falls to the boundary of pages on the target level.  See
                                939                 :                :          * bt_child_highkey_check() for details.  So, typically we won't end
                                940                 :                :          * up doing anything with low key, but it's simpler for general case
                                941                 :                :          * high key verification to always have it available.
                                942                 :                :          *
                                943                 :                :          * The correctness of managing low key in the case of concurrent
                                944                 :                :          * splits wasn't investigated yet.  Thankfully we only need low key
                                945                 :                :          * for readonly verification and concurrent splits won't happen.
                                946                 :                :          */
                                947   [ +  +  +  + ]:           9074 :         if (state->readonly && !P_RIGHTMOST(opaque))
                                948                 :                :         {
                                949                 :                :             IndexTuple  itup;
                                950                 :                :             ItemId      itemid;
                                951                 :                : 
                                952                 :           1862 :             itemid = PageGetItemIdCareful(state, state->targetblock,
                                953                 :                :                                           state->target, P_HIKEY);
                                954                 :           1862 :             itup = (IndexTuple) PageGetItem(state->target, itemid);
                                955                 :                : 
                                956                 :           1862 :             state->lowkey = MemoryContextAlloc(oldcontext, IndexTupleSize(itup));
                                957                 :           1862 :             memcpy(state->lowkey, itup, IndexTupleSize(itup));
                                958                 :                :         }
                                959                 :                : 
                                960                 :                :         /* Free page and associated memory for this iteration */
 2593 andres@anarazel.de        961                 :           9074 :         MemoryContextReset(state->targetcontext);
                                962                 :                :     }
                                963         [ +  + ]:           9074 :     while (current != P_NONE);
                                964                 :                : 
 1495 akorotkov@postgresql      965         [ -  + ]:           2459 :     if (state->lowkey)
                                966                 :                :     {
 1495 akorotkov@postgresql      967         [ #  # ]:UBC           0 :         Assert(state->readonly);
                                968                 :              0 :         pfree(state->lowkey);
                                969                 :              0 :         state->lowkey = NULL;
                                970                 :                :     }
                                971                 :                : 
                                972                 :                :     /* Don't change context for caller */
 2593 andres@anarazel.de        973                 :CBC        2459 :     MemoryContextSwitchTo(oldcontext);
                                974                 :                : 
                                975                 :           2459 :     return nextleveldown;
                                976                 :                : }
                                977                 :                : 
                                978                 :                : /* Check visibility of the table entry referenced by nbtree index */
                                979                 :                : static bool
  169 akorotkov@postgresql      980                 :GNC      144902 : heap_entry_is_visible(BtreeCheckState *state, ItemPointer tid)
                                981                 :                : {
                                982                 :                :     bool        tid_visible;
                                983                 :                : 
                                984                 :         144902 :     TupleTableSlot *slot = table_slot_create(state->heaprel, NULL);
                                985                 :                : 
                                986                 :         144902 :     tid_visible = table_tuple_fetch_row_version(state->heaprel,
                                987                 :                :                                                 tid, state->snapshot, slot);
                                988         [ +  - ]:         144902 :     if (slot != NULL)
                                989                 :         144902 :         ExecDropSingleTupleTableSlot(slot);
                                990                 :                : 
                                991                 :         144902 :     return tid_visible;
                                992                 :                : }
                                993                 :                : 
                                994                 :                : /*
                                995                 :                :  * Prepare an error message for unique constrain violation in
                                996                 :                :  * a btree index and report ERROR.
                                997                 :                :  */
                                998                 :                : static void
                                999                 :              3 : bt_report_duplicate(BtreeCheckState *state,
                               1000                 :                :                     ItemPointer tid, BlockNumber block, OffsetNumber offset,
                               1001                 :                :                     int posting,
                               1002                 :                :                     ItemPointer nexttid, BlockNumber nblock, OffsetNumber noffset,
                               1003                 :                :                     int nposting)
                               1004                 :                : {
                               1005                 :                :     char       *htid,
                               1006                 :                :                *nhtid,
                               1007                 :                :                *itid,
                               1008                 :              3 :                *nitid = "",
                               1009                 :              3 :                *pposting = "",
                               1010                 :              3 :                *pnposting = "";
                               1011                 :                : 
                               1012                 :              3 :     htid = psprintf("tid=(%u,%u)",
                               1013                 :                :                     ItemPointerGetBlockNumberNoCheck(tid),
                               1014                 :              3 :                     ItemPointerGetOffsetNumberNoCheck(tid));
                               1015                 :              3 :     nhtid = psprintf("tid=(%u,%u)",
                               1016                 :                :                      ItemPointerGetBlockNumberNoCheck(nexttid),
                               1017                 :              3 :                      ItemPointerGetOffsetNumberNoCheck(nexttid));
                               1018                 :              3 :     itid = psprintf("tid=(%u,%u)", block, offset);
                               1019                 :                : 
                               1020   [ +  -  +  - ]:              3 :     if (nblock != block || noffset != offset)
                               1021                 :              3 :         nitid = psprintf(" tid=(%u,%u)", nblock, noffset);
                               1022                 :                : 
                               1023         [ -  + ]:              3 :     if (posting >= 0)
  169 akorotkov@postgresql     1024                 :UNC           0 :         pposting = psprintf(" posting %u", posting);
                               1025                 :                : 
  169 akorotkov@postgresql     1026         [ -  + ]:GNC           3 :     if (nposting >= 0)
  169 akorotkov@postgresql     1027                 :UNC           0 :         pnposting = psprintf(" posting %u", nposting);
                               1028                 :                : 
  169 akorotkov@postgresql     1029         [ +  - ]:GNC           3 :     ereport(ERROR,
                               1030                 :                :             (errcode(ERRCODE_INDEX_CORRUPTED),
                               1031                 :                :              errmsg("index uniqueness is violated for index \"%s\"",
                               1032                 :                :                     RelationGetRelationName(state->rel)),
                               1033                 :                :              errdetail("Index %s%s and%s%s (point to heap %s and %s) page lsn=%X/%X.",
                               1034                 :                :                        itid, pposting, nitid, pnposting, htid, nhtid,
                               1035                 :                :                        LSN_FORMAT_ARGS(state->targetlsn))));
                               1036                 :                : }
                               1037                 :                : 
                               1038                 :                : /* Check if current nbtree leaf entry complies with UNIQUE constraint */
                               1039                 :                : static void
                               1040                 :         144902 : bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup,
                               1041                 :                :                       BlockNumber targetblock, OffsetNumber offset, int *lVis_i,
                               1042                 :                :                       ItemPointer *lVis_tid, OffsetNumber *lVis_offset,
                               1043                 :                :                       BlockNumber *lVis_block)
                               1044                 :                : {
                               1045                 :                :     ItemPointer tid;
                               1046                 :         144902 :     bool        has_visible_entry = false;
                               1047                 :                : 
                               1048         [ -  + ]:         144902 :     Assert(targetblock != P_NONE);
                               1049                 :                : 
                               1050                 :                :     /*
                               1051                 :                :      * Current tuple has posting list. Report duplicate if TID of any posting
                               1052                 :                :      * list entry is visible and lVis_tid is valid.
                               1053                 :                :      */
                               1054         [ -  + ]:         144902 :     if (BTreeTupleIsPosting(itup))
                               1055                 :                :     {
  169 akorotkov@postgresql     1056         [ #  # ]:UNC           0 :         for (int i = 0; i < BTreeTupleGetNPosting(itup); i++)
                               1057                 :                :         {
                               1058                 :              0 :             tid = BTreeTupleGetPostingN(itup, i);
                               1059         [ #  # ]:              0 :             if (heap_entry_is_visible(state, tid))
                               1060                 :                :             {
                               1061                 :              0 :                 has_visible_entry = true;
                               1062         [ #  # ]:              0 :                 if (ItemPointerIsValid(*lVis_tid))
                               1063                 :                :                 {
                               1064                 :              0 :                     bt_report_duplicate(state,
                               1065                 :                :                                         *lVis_tid, *lVis_block,
                               1066                 :              0 :                                         *lVis_offset, *lVis_i,
                               1067                 :                :                                         tid, targetblock,
                               1068                 :                :                                         offset, i);
                               1069                 :                :                 }
                               1070                 :                : 
                               1071                 :                :                 /*
                               1072                 :                :                  * Prevent double reporting unique constraint violation
                               1073                 :                :                  * between the posting list entries of the first tuple on the
                               1074                 :                :                  * page after cross-page check.
                               1075                 :                :                  */
                               1076   [ #  #  #  # ]:              0 :                 if (*lVis_block != targetblock && ItemPointerIsValid(*lVis_tid))
                               1077                 :              0 :                     return;
                               1078                 :                : 
                               1079                 :              0 :                 *lVis_i = i;
                               1080                 :              0 :                 *lVis_tid = tid;
                               1081                 :              0 :                 *lVis_offset = offset;
                               1082                 :              0 :                 *lVis_block = targetblock;
                               1083                 :                :             }
                               1084                 :                :         }
                               1085                 :                :     }
                               1086                 :                : 
                               1087                 :                :     /*
                               1088                 :                :      * Current tuple has no posting list. If TID is visible save info about it
                               1089                 :                :      * for the next comparisons in the loop in bt_page_check(). Report
                               1090                 :                :      * duplicate if lVis_tid is already valid.
                               1091                 :                :      */
                               1092                 :                :     else
                               1093                 :                :     {
  169 akorotkov@postgresql     1094                 :GNC      144902 :         tid = BTreeTupleGetHeapTID(itup);
                               1095         [ +  + ]:         144902 :         if (heap_entry_is_visible(state, tid))
                               1096                 :                :         {
                               1097                 :         143031 :             has_visible_entry = true;
                               1098         [ +  + ]:         143031 :             if (ItemPointerIsValid(*lVis_tid))
                               1099                 :                :             {
                               1100                 :              3 :                 bt_report_duplicate(state,
                               1101                 :                :                                     *lVis_tid, *lVis_block,
                               1102                 :              3 :                                     *lVis_offset, *lVis_i,
                               1103                 :                :                                     tid, targetblock,
                               1104                 :                :                                     offset, -1);
                               1105                 :                :             }
                               1106                 :         143028 :             *lVis_i = -1;
                               1107                 :         143028 :             *lVis_tid = tid;
                               1108                 :         143028 :             *lVis_offset = offset;
                               1109                 :         143028 :             *lVis_block = targetblock;
                               1110                 :                :         }
                               1111                 :                :     }
                               1112                 :                : 
                               1113   [ +  +  -  + ]:         144899 :     if (!has_visible_entry && *lVis_block != InvalidBlockNumber &&
  169 akorotkov@postgresql     1114         [ #  # ]:UNC           0 :         *lVis_block != targetblock)
                               1115                 :                :     {
                               1116                 :              0 :         char       *posting = "";
                               1117                 :                : 
                               1118         [ #  # ]:              0 :         if (*lVis_i >= 0)
                               1119                 :              0 :             posting = psprintf(" posting %u", *lVis_i);
                               1120         [ #  # ]:              0 :         ereport(DEBUG1,
                               1121                 :                :                 (errcode(ERRCODE_NO_DATA),
                               1122                 :                :                  errmsg("index uniqueness can not be checked for index tid=(%u,%u) in index \"%s\"",
                               1123                 :                :                         targetblock, offset,
                               1124                 :                :                         RelationGetRelationName(state->rel)),
                               1125                 :                :                  errdetail("It doesn't have visible heap tids and key is equal to the tid=(%u,%u)%s (points to heap tid=(%u,%u)).",
                               1126                 :                :                            *lVis_block, *lVis_offset, posting,
                               1127                 :                :                            ItemPointerGetBlockNumberNoCheck(*lVis_tid),
                               1128                 :                :                            ItemPointerGetOffsetNumberNoCheck(*lVis_tid)),
                               1129                 :                :                  errhint("VACUUM the table and repeat the check.")));
                               1130                 :                :     }
                               1131                 :                : }
                               1132                 :                : 
                               1133                 :                : /*
                               1134                 :                :  * Like P_LEFTMOST(start_opaque), but accept an arbitrarily-long chain of
                               1135                 :                :  * half-dead, sibling-linked pages to the left.  If a half-dead page appears
                               1136                 :                :  * under state->readonly, the database exited recovery between the first-stage
                               1137                 :                :  * and second-stage WAL records of a deletion.
                               1138                 :                :  */
                               1139                 :                : static bool
  167 noah@leadboat.com        1140                 :CBC          55 : bt_leftmost_ignoring_half_dead(BtreeCheckState *state,
                               1141                 :                :                                BlockNumber start,
                               1142                 :                :                                BTPageOpaque start_opaque)
                               1143                 :                : {
                               1144                 :             55 :     BlockNumber reached = start_opaque->btpo_prev,
                               1145                 :             55 :                 reached_from = start;
                               1146                 :             55 :     bool        all_half_dead = true;
                               1147                 :                : 
                               1148                 :                :     /*
                               1149                 :                :      * To handle the !readonly case, we'd need to accept BTP_DELETED pages and
                               1150                 :                :      * potentially observe nbtree/README "Page deletion and backwards scans".
                               1151                 :                :      */
                               1152         [ -  + ]:             55 :     Assert(state->readonly);
                               1153                 :                : 
                               1154   [ +  +  +  - ]:             57 :     while (reached != P_NONE && all_half_dead)
                               1155                 :                :     {
                               1156                 :              2 :         Page        page = palloc_btree_page(state, reached);
                               1157                 :              2 :         BTPageOpaque reached_opaque = BTPageGetOpaque(page);
                               1158                 :                : 
                               1159         [ -  + ]:              2 :         CHECK_FOR_INTERRUPTS();
                               1160                 :                : 
                               1161                 :                :         /*
                               1162                 :                :          * Try to detect btpo_prev circular links.  _bt_unlink_halfdead_page()
                               1163                 :                :          * writes that side-links will continue to point to the siblings.
                               1164                 :                :          * Check btpo_next for that property.
                               1165                 :                :          */
                               1166         [ +  - ]:              2 :         all_half_dead = P_ISHALFDEAD(reached_opaque) &&
                               1167         [ +  - ]:              2 :             reached != start &&
                               1168         [ +  - ]:              4 :             reached != reached_from &&
                               1169         [ +  - ]:              2 :             reached_opaque->btpo_next == reached_from;
                               1170         [ +  - ]:              2 :         if (all_half_dead)
                               1171                 :                :         {
                               1172                 :              2 :             XLogRecPtr  pagelsn = PageGetLSN(page);
                               1173                 :                : 
                               1174                 :                :             /* pagelsn should point to an XLOG_BTREE_MARK_PAGE_HALFDEAD */
                               1175         [ +  - ]:              2 :             ereport(DEBUG1,
                               1176                 :                :                     (errcode(ERRCODE_NO_DATA),
                               1177                 :                :                      errmsg_internal("harmless interrupted page deletion detected in index \"%s\"",
                               1178                 :                :                                      RelationGetRelationName(state->rel)),
                               1179                 :                :                      errdetail_internal("Block=%u right block=%u page lsn=%X/%X.",
                               1180                 :                :                                         reached, reached_from,
                               1181                 :                :                                         LSN_FORMAT_ARGS(pagelsn))));
                               1182                 :                : 
                               1183                 :              2 :             reached_from = reached;
                               1184                 :              2 :             reached = reached_opaque->btpo_prev;
                               1185                 :                :         }
                               1186                 :                : 
                               1187                 :              2 :         pfree(page);
                               1188                 :                :     }
                               1189                 :                : 
                               1190                 :             55 :     return all_half_dead;
                               1191                 :                : }
                               1192                 :                : 
                               1193                 :                : /*
                               1194                 :                :  * Raise an error when target page's left link does not point back to the
                               1195                 :                :  * previous target page, called leftcurrent here.  The leftcurrent page's
                               1196                 :                :  * right link was followed to get to the current target page, and we expect
                               1197                 :                :  * mutual agreement among leftcurrent and the current target page.  Make sure
                               1198                 :                :  * that this condition has definitely been violated in the !readonly case,
                               1199                 :                :  * where concurrent page splits are something that we need to deal with.
                               1200                 :                :  *
                               1201                 :                :  * Cross-page inconsistencies involving pages that don't agree about being
                               1202                 :                :  * siblings are known to be a particularly good indicator of corruption
                               1203                 :                :  * involving partial writes/lost updates.  The bt_right_page_check_scankey
                               1204                 :                :  * check also provides a way of detecting cross-page inconsistencies for
                               1205                 :                :  * !readonly callers, but it can only detect sibling pages that have an
                               1206                 :                :  * out-of-order keyspace, which can't catch many of the problems that we
                               1207                 :                :  * expect to catch here.
                               1208                 :                :  *
                               1209                 :                :  * The classic example of the kind of inconsistency that we can only catch
                               1210                 :                :  * with this check (when in !readonly mode) involves three sibling pages that
                               1211                 :                :  * were affected by a faulty page split at some point in the past.  The
                               1212                 :                :  * effects of the split are reflected in the original page and its new right
                               1213                 :                :  * sibling page, with a lack of any accompanying changes for the _original_
                               1214                 :                :  * right sibling page.  The original right sibling page's left link fails to
                               1215                 :                :  * point to the new right sibling page (its left link still points to the
                               1216                 :                :  * original page), even though the first phase of a page split is supposed to
                               1217                 :                :  * work as a single atomic action.  This subtle inconsistency will probably
                               1218                 :                :  * only break backwards scans in practice.
                               1219                 :                :  *
                               1220                 :                :  * Note that this is the only place where amcheck will "couple" buffer locks
                               1221                 :                :  * (and only for !readonly callers).  In general we prefer to avoid more
                               1222                 :                :  * thorough cross-page checks in !readonly mode, but it seems worth the
                               1223                 :                :  * complexity here.  Also, the performance overhead of performing lock
                               1224                 :                :  * coupling here is negligible in practice.  Control only reaches here with a
                               1225                 :                :  * non-corrupt index when there is a concurrent page split at the instant
                               1226                 :                :  * caller crossed over to target page from leftcurrent page.
                               1227                 :                :  */
                               1228                 :                : static void
 1345 pg@bowt.ie               1229                 :UBC           0 : bt_recheck_sibling_links(BtreeCheckState *state,
                               1230                 :                :                          BlockNumber btpo_prev_from_target,
                               1231                 :                :                          BlockNumber leftcurrent)
                               1232                 :                : {
                               1233                 :                :     /* passing metapage to BTPageGetOpaque() would give irrelevant findings */
  167 noah@leadboat.com        1234         [ #  # ]:              0 :     Assert(leftcurrent != P_NONE);
                               1235                 :                : 
 1345 pg@bowt.ie               1236         [ #  # ]:              0 :     if (!state->readonly)
                               1237                 :                :     {
                               1238                 :                :         Buffer      lbuf;
                               1239                 :                :         Buffer      newtargetbuf;
                               1240                 :                :         Page        page;
                               1241                 :                :         BTPageOpaque opaque;
                               1242                 :                :         BlockNumber newtargetblock;
                               1243                 :                : 
                               1244                 :                :         /* Couple locks in the usual order for nbtree:  Left to right */
                               1245                 :              0 :         lbuf = ReadBufferExtended(state->rel, MAIN_FORKNUM, leftcurrent,
                               1246                 :                :                                   RBM_NORMAL, state->checkstrategy);
                               1247                 :              0 :         LockBuffer(lbuf, BT_READ);
                               1248                 :              0 :         _bt_checkpage(state->rel, lbuf);
                               1249                 :              0 :         page = BufferGetPage(lbuf);
  744 michael@paquier.xyz      1250                 :              0 :         opaque = BTPageGetOpaque(page);
 1345 pg@bowt.ie               1251         [ #  # ]:              0 :         if (P_ISDELETED(opaque))
                               1252                 :                :         {
                               1253                 :                :             /*
                               1254                 :                :              * Cannot reason about concurrently deleted page -- the left link
                               1255                 :                :              * in the page to the right is expected to point to some other
                               1256                 :                :              * page to the left (not leftcurrent page).
                               1257                 :                :              *
                               1258                 :                :              * Note that we deliberately don't give up with a half-dead page.
                               1259                 :                :              */
                               1260                 :              0 :             UnlockReleaseBuffer(lbuf);
                               1261                 :              0 :             return;
                               1262                 :                :         }
                               1263                 :                : 
                               1264                 :              0 :         newtargetblock = opaque->btpo_next;
                               1265                 :                :         /* Avoid self-deadlock when newtargetblock == leftcurrent */
                               1266         [ #  # ]:              0 :         if (newtargetblock != leftcurrent)
                               1267                 :                :         {
                               1268                 :              0 :             newtargetbuf = ReadBufferExtended(state->rel, MAIN_FORKNUM,
                               1269                 :                :                                               newtargetblock, RBM_NORMAL,
                               1270                 :                :                                               state->checkstrategy);
                               1271                 :              0 :             LockBuffer(newtargetbuf, BT_READ);
                               1272                 :              0 :             _bt_checkpage(state->rel, newtargetbuf);
                               1273                 :              0 :             page = BufferGetPage(newtargetbuf);
  744 michael@paquier.xyz      1274                 :              0 :             opaque = BTPageGetOpaque(page);
                               1275                 :                :             /* btpo_prev_from_target may have changed; update it */
 1345 pg@bowt.ie               1276                 :              0 :             btpo_prev_from_target = opaque->btpo_prev;
                               1277                 :                :         }
                               1278                 :                :         else
                               1279                 :                :         {
                               1280                 :                :             /*
                               1281                 :                :              * leftcurrent right sibling points back to leftcurrent block.
                               1282                 :                :              * Index is corrupt.  Easiest way to handle this is to pretend
                               1283                 :                :              * that we actually read from a distinct page that has an invalid
                               1284                 :                :              * block number in its btpo_prev.
                               1285                 :                :              */
                               1286                 :              0 :             newtargetbuf = InvalidBuffer;
                               1287                 :              0 :             btpo_prev_from_target = InvalidBlockNumber;
                               1288                 :                :         }
                               1289                 :                : 
                               1290                 :                :         /*
                               1291                 :                :          * No need to check P_ISDELETED here, since new target block cannot be
                               1292                 :                :          * marked deleted as long as we hold a lock on lbuf
                               1293                 :                :          */
                               1294         [ #  # ]:              0 :         if (BufferIsValid(newtargetbuf))
                               1295                 :              0 :             UnlockReleaseBuffer(newtargetbuf);
                               1296                 :              0 :         UnlockReleaseBuffer(lbuf);
                               1297                 :                : 
                               1298         [ #  # ]:              0 :         if (btpo_prev_from_target == leftcurrent)
                               1299                 :                :         {
                               1300                 :                :             /* Report split in left sibling, not target (or new target) */
                               1301         [ #  # ]:              0 :             ereport(DEBUG1,
                               1302                 :                :                     (errcode(ERRCODE_INTERNAL_ERROR),
                               1303                 :                :                      errmsg_internal("harmless concurrent page split detected in index \"%s\"",
                               1304                 :                :                                      RelationGetRelationName(state->rel)),
                               1305                 :                :                      errdetail_internal("Block=%u new right sibling=%u original right sibling=%u.",
                               1306                 :                :                                         leftcurrent, newtargetblock,
                               1307                 :                :                                         state->targetblock)));
                               1308                 :              0 :             return;
                               1309                 :                :         }
                               1310                 :                : 
                               1311                 :                :         /*
                               1312                 :                :          * Index is corrupt.  Make sure that we report correct target page.
                               1313                 :                :          *
                               1314                 :                :          * This could have changed in cases where there was a concurrent page
                               1315                 :                :          * split, as well as index corruption (at least in theory).  Note that
                               1316                 :                :          * btpo_prev_from_target was already updated above.
                               1317                 :                :          */
                               1318                 :              0 :         state->targetblock = newtargetblock;
                               1319                 :                :     }
                               1320                 :                : 
                               1321         [ #  # ]:              0 :     ereport(ERROR,
                               1322                 :                :             (errcode(ERRCODE_INDEX_CORRUPTED),
                               1323                 :                :              errmsg("left link/right link pair in index \"%s\" not in agreement",
                               1324                 :                :                     RelationGetRelationName(state->rel)),
                               1325                 :                :              errdetail_internal("Block=%u left block=%u left link from block=%u.",
                               1326                 :                :                                 state->targetblock, leftcurrent,
                               1327                 :                :                                 btpo_prev_from_target)));
                               1328                 :                : }
                               1329                 :                : 
                               1330                 :                : /*
                               1331                 :                :  * Function performs the following checks on target page, or pages ancillary to
                               1332                 :                :  * target page:
                               1333                 :                :  *
                               1334                 :                :  * - That every "real" data item is less than or equal to the high key, which
                               1335                 :                :  *   is an upper bound on the items on the page.  Data items should be
                               1336                 :                :  *   strictly less than the high key when the page is an internal page.
                               1337                 :                :  *
                               1338                 :                :  * - That within the page, every data item is strictly less than the item
                               1339                 :                :  *   immediately to its right, if any (i.e., that the items are in order
                               1340                 :                :  *   within the page, so that the binary searches performed by index scans are
                               1341                 :                :  *   sane).
                               1342                 :                :  *
                               1343                 :                :  * - That the last data item stored on the page is strictly less than the
                               1344                 :                :  *   first data item on the page to the right (when such a first item is
                               1345                 :                :  *   available).
                               1346                 :                :  *
                               1347                 :                :  * - Various checks on the structure of tuples themselves.  For example, check
                               1348                 :                :  *   that non-pivot tuples have no truncated attributes.
                               1349                 :                :  *
                               1350                 :                :  * - For index with unique constraint make sure that only one of table entries
                               1351                 :                :  *   for equal keys is visible.
                               1352                 :                :  *
                               1353                 :                :  * Furthermore, when state passed shows ShareLock held, function also checks:
                               1354                 :                :  *
                               1355                 :                :  * - That all child pages respect strict lower bound from parent's pivot
                               1356                 :                :  *   tuple.
                               1357                 :                :  *
                               1358                 :                :  * - That downlink to block was encountered in parent where that's expected.
                               1359                 :                :  *
                               1360                 :                :  * - That high keys of child pages matches corresponding pivot keys in parent.
                               1361                 :                :  *
                               1362                 :                :  * This is also where heapallindexed callers use their Bloom filter to
                               1363                 :                :  * fingerprint IndexTuples for later table_index_build_scan() verification.
                               1364                 :                :  *
                               1365                 :                :  * Note:  Memory allocated in this routine is expected to be released by caller
                               1366                 :                :  * resetting state->targetcontext.
                               1367                 :                :  */
                               1368                 :                : static void
 2593 andres@anarazel.de       1369                 :CBC        9080 : bt_target_page_check(BtreeCheckState *state)
                               1370                 :                : {
                               1371                 :                :     OffsetNumber offset;
                               1372                 :                :     OffsetNumber max;
                               1373                 :                :     BTPageOpaque topaque;
                               1374                 :                : 
                               1375                 :                :     /* last visible entry info for checking indexes with unique constraint */
  169 akorotkov@postgresql     1376                 :GNC        9080 :     int         lVis_i = -1;    /* the position of last visible item for
                               1377                 :                :                                  * posting tuple. for non-posting tuple (-1) */
                               1378                 :           9080 :     ItemPointer lVis_tid = NULL;
                               1379                 :           9080 :     BlockNumber lVis_block = InvalidBlockNumber;
                               1380                 :           9080 :     OffsetNumber lVis_offset = InvalidOffsetNumber;
                               1381                 :                : 
  744 michael@paquier.xyz      1382                 :CBC        9080 :     topaque = BTPageGetOpaque(state->target);
 2593 andres@anarazel.de       1383                 :           9080 :     max = PageGetMaxOffsetNumber(state->target);
                               1384                 :                : 
                               1385   [ -  +  -  - ]:           9080 :     elog(DEBUG2, "verifying %u items on %s block %u", max,
                               1386                 :                :          P_ISLEAF(topaque) ? "leaf" : "internal", state->targetblock);
                               1387                 :                : 
                               1388                 :                :     /*
                               1389                 :                :      * Check the number of attributes in high key. Note, rightmost page
                               1390                 :                :      * doesn't contain a high key, so nothing to check
                               1391                 :                :      */
 1816 pg@bowt.ie               1392         [ +  + ]:           9080 :     if (!P_RIGHTMOST(topaque))
                               1393                 :                :     {
                               1394                 :                :         ItemId      itemid;
                               1395                 :                :         IndexTuple  itup;
                               1396                 :                : 
                               1397                 :                :         /* Verify line pointer before checking tuple */
                               1398                 :           6619 :         itemid = PageGetItemIdCareful(state, state->targetblock,
                               1399                 :                :                                       state->target, P_HIKEY);
                               1400         [ -  + ]:           6619 :         if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target,
                               1401                 :                :                              P_HIKEY))
                               1402                 :                :         {
 1816 pg@bowt.ie               1403                 :UBC           0 :             itup = (IndexTuple) PageGetItem(state->target, itemid);
                               1404   [ #  #  #  #  :              0 :             ereport(ERROR,
                                              #  # ]
                               1405                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               1406                 :                :                      errmsg("wrong number of high key index tuple attributes in index \"%s\"",
                               1407                 :                :                             RelationGetRelationName(state->rel)),
                               1408                 :                :                      errdetail_internal("Index block=%u natts=%u block type=%s page lsn=%X/%X.",
                               1409                 :                :                                         state->targetblock,
                               1410                 :                :                                         BTreeTupleGetNAtts(itup, state->rel),
                               1411                 :                :                                         P_ISLEAF(topaque) ? "heap" : "index",
                               1412                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn))));
                               1413                 :                :         }
                               1414                 :                :     }
                               1415                 :                : 
                               1416                 :                :     /*
                               1417                 :                :      * Loop over page items, starting from first non-highkey item, not high
                               1418                 :                :      * key (if any).  Most tests are not performed for the "negative infinity"
                               1419                 :                :      * real item (if any).
                               1420                 :                :      */
 2593 andres@anarazel.de       1421         [ +  + ]:CBC        9080 :     for (offset = P_FIRSTDATAKEY(topaque);
                               1422         [ +  + ]:        2028138 :          offset <= max;
                               1423                 :        2019058 :          offset = OffsetNumberNext(offset))
                               1424                 :                :     {
                               1425                 :                :         ItemId      itemid;
                               1426                 :                :         IndexTuple  itup;
                               1427                 :                :         size_t      tupsize;
                               1428                 :                :         BTScanInsert skey;
                               1429                 :                :         bool        lowersizelimit;
                               1430                 :                :         ItemPointer scantid;
                               1431                 :                : 
                               1432         [ -  + ]:        2019064 :         CHECK_FOR_INTERRUPTS();
                               1433                 :                : 
 1816 pg@bowt.ie               1434                 :        2019064 :         itemid = PageGetItemIdCareful(state, state->targetblock,
                               1435                 :                :                                       state->target, offset);
 2206 andres@anarazel.de       1436                 :        2019064 :         itup = (IndexTuple) PageGetItem(state->target, itemid);
                               1437                 :        2019064 :         tupsize = IndexTupleSize(itup);
                               1438                 :                : 
                               1439                 :                :         /*
                               1440                 :                :          * lp_len should match the IndexTuple reported length exactly, since
                               1441                 :                :          * lp_len is completely redundant in indexes, and both sources of
                               1442                 :                :          * tuple length are MAXALIGN()'d.  nbtree does not use lp_len all that
                               1443                 :                :          * frequently, and is surprisingly tolerant of corrupt lp_len fields.
                               1444                 :                :          */
                               1445         [ -  + ]:        2019064 :         if (tupsize != ItemIdGetLength(itemid))
 2206 andres@anarazel.de       1446         [ #  # ]:UBC           0 :             ereport(ERROR,
                               1447                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               1448                 :                :                      errmsg("index tuple size does not equal lp_len in index \"%s\"",
                               1449                 :                :                             RelationGetRelationName(state->rel)),
                               1450                 :                :                      errdetail_internal("Index tid=(%u,%u) tuple size=%zu lp_len=%u page lsn=%X/%X.",
                               1451                 :                :                                         state->targetblock, offset,
                               1452                 :                :                                         tupsize, ItemIdGetLength(itemid),
                               1453                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn)),
                               1454                 :                :                      errhint("This could be a torn page problem.")));
                               1455                 :                : 
                               1456                 :                :         /* Check the number of index tuple attributes */
 1852 pg@bowt.ie               1457         [ -  + ]:CBC     2019064 :         if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target,
                               1458                 :                :                              offset))
                               1459                 :                :         {
                               1460                 :                :             ItemPointer tid;
                               1461                 :                :             char       *itid,
                               1462                 :                :                        *htid;
                               1463                 :                : 
 2199 teodor@sigaev.ru         1464                 :UBC           0 :             itid = psprintf("(%u,%u)", state->targetblock, offset);
 1509 pg@bowt.ie               1465                 :              0 :             tid = BTreeTupleGetPointsToTID(itup);
 2199 teodor@sigaev.ru         1466                 :              0 :             htid = psprintf("(%u,%u)",
                               1467                 :                :                             ItemPointerGetBlockNumberNoCheck(tid),
 1509 pg@bowt.ie               1468                 :              0 :                             ItemPointerGetOffsetNumberNoCheck(tid));
                               1469                 :                : 
 2199 teodor@sigaev.ru         1470   [ #  #  #  #  :              0 :             ereport(ERROR,
                                              #  # ]
                               1471                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               1472                 :                :                      errmsg("wrong number of index tuple attributes in index \"%s\"",
                               1473                 :                :                             RelationGetRelationName(state->rel)),
                               1474                 :                :                      errdetail_internal("Index tid=%s natts=%u points to %s tid=%s page lsn=%X/%X.",
                               1475                 :                :                                         itid,
                               1476                 :                :                                         BTreeTupleGetNAtts(itup, state->rel),
                               1477                 :                :                                         P_ISLEAF(topaque) ? "heap" : "index",
                               1478                 :                :                                         htid,
                               1479                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn))));
                               1480                 :                :         }
                               1481                 :                : 
                               1482                 :                :         /*
                               1483                 :                :          * Don't try to generate scankey using "negative infinity" item on
                               1484                 :                :          * internal pages. They are always truncated to zero attributes.
                               1485                 :                :          */
 2593 andres@anarazel.de       1486         [ +  + ]:CBC     2019064 :         if (offset_is_negative_infinity(topaque, offset))
                               1487                 :                :         {
                               1488                 :                :             /*
                               1489                 :                :              * We don't call bt_child_check() for "negative infinity" items.
                               1490                 :                :              * But if we're performing downlink connectivity check, we do it
                               1491                 :                :              * for every item including "negative infinity" one.
                               1492                 :                :              */
 1495 akorotkov@postgresql     1493   [ +  -  +  + ]:            515 :             if (!P_ISLEAF(topaque) && state->readonly)
                               1494                 :                :             {
                               1495                 :             12 :                 bt_child_highkey_check(state,
                               1496                 :                :                                        offset,
                               1497                 :                :                                        NULL,
                               1498                 :                :                                        topaque->btpo_level);
                               1499                 :                :             }
 2593 andres@anarazel.de       1500                 :            515 :             continue;
                               1501                 :                :         }
                               1502                 :                : 
                               1503                 :                :         /*
                               1504                 :                :          * Readonly callers may optionally verify that non-pivot tuples can
                               1505                 :                :          * each be found by an independent search that starts from the root.
                               1506                 :                :          * Note that we deliberately don't do individual searches for each
                               1507                 :                :          * TID, since the posting list itself is validated by other checks.
                               1508                 :                :          */
 1852 pg@bowt.ie               1509   [ +  +  +  + ]:        2018549 :         if (state->rootdescend && P_ISLEAF(topaque) &&
                               1510         [ -  + ]:         201098 :             !bt_rootdescend(state, itup))
                               1511                 :                :         {
 1509 pg@bowt.ie               1512                 :UBC           0 :             ItemPointer tid = BTreeTupleGetPointsToTID(itup);
                               1513                 :                :             char       *itid,
                               1514                 :                :                        *htid;
                               1515                 :                : 
 1852                          1516                 :              0 :             itid = psprintf("(%u,%u)", state->targetblock, offset);
 1509                          1517                 :              0 :             htid = psprintf("(%u,%u)", ItemPointerGetBlockNumber(tid),
                               1518                 :              0 :                             ItemPointerGetOffsetNumber(tid));
                               1519                 :                : 
 1852                          1520         [ #  # ]:              0 :             ereport(ERROR,
                               1521                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               1522                 :                :                      errmsg("could not find tuple using search from root page in index \"%s\"",
                               1523                 :                :                             RelationGetRelationName(state->rel)),
                               1524                 :                :                      errdetail_internal("Index tid=%s points to heap tid=%s page lsn=%X/%X.",
                               1525                 :                :                                         itid, htid,
                               1526                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn))));
                               1527                 :                :         }
                               1528                 :                : 
                               1529                 :                :         /*
                               1530                 :                :          * If tuple is a posting list tuple, make sure posting list TIDs are
                               1531                 :                :          * in order
                               1532                 :                :          */
 1509 pg@bowt.ie               1533         [ +  + ]:CBC     2018549 :         if (BTreeTupleIsPosting(itup))
                               1534                 :                :         {
                               1535                 :                :             ItemPointerData last;
                               1536                 :                :             ItemPointer current;
                               1537                 :                : 
                               1538                 :          10287 :             ItemPointerCopy(BTreeTupleGetHeapTID(itup), &last);
                               1539                 :                : 
                               1540         [ +  + ]:          82219 :             for (int i = 1; i < BTreeTupleGetNPosting(itup); i++)
                               1541                 :                :             {
                               1542                 :                : 
                               1543                 :          71932 :                 current = BTreeTupleGetPostingN(itup, i);
                               1544                 :                : 
                               1545         [ -  + ]:          71932 :                 if (ItemPointerCompare(current, &last) <= 0)
                               1546                 :                :                 {
 1509 pg@bowt.ie               1547                 :UBC           0 :                     char       *itid = psprintf("(%u,%u)", state->targetblock, offset);
                               1548                 :                : 
                               1549         [ #  # ]:              0 :                     ereport(ERROR,
                               1550                 :                :                             (errcode(ERRCODE_INDEX_CORRUPTED),
                               1551                 :                :                              errmsg_internal("posting list contains misplaced TID in index \"%s\"",
                               1552                 :                :                                              RelationGetRelationName(state->rel)),
                               1553                 :                :                              errdetail_internal("Index tid=%s posting list offset=%d page lsn=%X/%X.",
                               1554                 :                :                                                 itid, i,
                               1555                 :                :                                                 LSN_FORMAT_ARGS(state->targetlsn))));
                               1556                 :                :                 }
                               1557                 :                : 
 1509 pg@bowt.ie               1558                 :CBC       71932 :                 ItemPointerCopy(current, &last);
                               1559                 :                :             }
                               1560                 :                :         }
                               1561                 :                : 
                               1562                 :                :         /* Build insertion scankey for current page offset */
  309                          1563                 :        2018549 :         skey = bt_mkscankey_pivotsearch(state->rel, itup);
                               1564                 :                : 
                               1565                 :                :         /*
                               1566                 :                :          * Make sure tuple size does not exceed the relevant BTREE_VERSION
                               1567                 :                :          * specific limit.
                               1568                 :                :          *
                               1569                 :                :          * BTREE_VERSION 4 (which introduced heapkeyspace rules) requisitioned
                               1570                 :                :          * a small amount of space from BTMaxItemSize() in order to ensure
                               1571                 :                :          * that suffix truncation always has enough space to add an explicit
                               1572                 :                :          * heap TID back to a tuple -- we pessimistically assume that every
                               1573                 :                :          * newly inserted tuple will eventually need to have a heap TID
                               1574                 :                :          * appended during a future leaf page split, when the tuple becomes
                               1575                 :                :          * the basis of the new high key (pivot tuple) for the leaf page.
                               1576                 :                :          *
                               1577                 :                :          * Since the reclaimed space is reserved for that purpose, we must not
                               1578                 :                :          * enforce the slightly lower limit when the extra space has been used
                               1579                 :                :          * as intended.  In other words, there is only a cross-version
                               1580                 :                :          * difference in the limit on tuple size within leaf pages.
                               1581                 :                :          *
                               1582                 :                :          * Still, we're particular about the details within BTREE_VERSION 4
                               1583                 :                :          * internal pages.  Pivot tuples may only use the extra space for its
                               1584                 :                :          * designated purpose.  Enforce the lower limit for pivot tuples when
                               1585                 :                :          * an explicit heap TID isn't actually present. (In all other cases
                               1586                 :                :          * suffix truncation is guaranteed to generate a pivot tuple that's no
                               1587                 :                :          * larger than the firstright tuple provided to it by its caller.)
                               1588                 :                :          */
 1852                          1589         [ +  - ]:        4037098 :         lowersizelimit = skey->heapkeyspace &&
                               1590   [ +  +  +  + ]:        2018549 :             (P_ISLEAF(topaque) || BTreeTupleGetHeapTID(itup) == NULL);
                               1591   [ +  +  -  + ]:        2018565 :         if (tupsize > (lowersizelimit ? BTMaxItemSize(state->target) :
                               1592                 :             16 :                        BTMaxItemSizeNoHeapTid(state->target)))
                               1593                 :                :         {
 1509 pg@bowt.ie               1594                 :UBC           0 :             ItemPointer tid = BTreeTupleGetPointsToTID(itup);
                               1595                 :                :             char       *itid,
                               1596                 :                :                        *htid;
                               1597                 :                : 
 1852                          1598                 :              0 :             itid = psprintf("(%u,%u)", state->targetblock, offset);
                               1599                 :              0 :             htid = psprintf("(%u,%u)",
                               1600                 :                :                             ItemPointerGetBlockNumberNoCheck(tid),
 1509                          1601                 :              0 :                             ItemPointerGetOffsetNumberNoCheck(tid));
                               1602                 :                : 
 1852                          1603   [ #  #  #  # ]:              0 :             ereport(ERROR,
                               1604                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               1605                 :                :                      errmsg("index row size %zu exceeds maximum for index \"%s\"",
                               1606                 :                :                             tupsize, RelationGetRelationName(state->rel)),
                               1607                 :                :                      errdetail_internal("Index tid=%s points to %s tid=%s page lsn=%X/%X.",
                               1608                 :                :                                         itid,
                               1609                 :                :                                         P_ISLEAF(topaque) ? "heap" : "index",
                               1610                 :                :                                         htid,
                               1611                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn))));
                               1612                 :                :         }
                               1613                 :                : 
                               1614                 :                :         /* Fingerprint leaf page tuples (those that point to the heap) */
 2206 andres@anarazel.de       1615   [ +  +  +  +  :CBC     2018549 :         if (state->heapallindexed && P_ISLEAF(topaque) && !ItemIdIsDead(itemid))
                                              +  - ]
                               1616                 :                :         {
                               1617                 :                :             IndexTuple  norm;
                               1618                 :                : 
 1509 pg@bowt.ie               1619         [ +  + ]:         506946 :             if (BTreeTupleIsPosting(itup))
                               1620                 :                :             {
                               1621                 :                :                 /* Fingerprint all elements as distinct "plain" tuples */
                               1622         [ +  + ]:          30765 :                 for (int i = 0; i < BTreeTupleGetNPosting(itup); i++)
                               1623                 :                :                 {
                               1624                 :                :                     IndexTuple  logtuple;
                               1625                 :                : 
                               1626                 :          30546 :                     logtuple = bt_posting_plain_tuple(itup, i);
                               1627                 :          30546 :                     norm = bt_normalize_tuple(state, logtuple);
                               1628                 :          30546 :                     bloom_add_element(state->filter, (unsigned char *) norm,
                               1629                 :          30546 :                                       IndexTupleSize(norm));
                               1630                 :                :                     /* Be tidy */
                               1631         [ +  + ]:          30546 :                     if (norm != logtuple)
                               1632                 :              2 :                         pfree(norm);
                               1633                 :          30546 :                     pfree(logtuple);
                               1634                 :                :                 }
                               1635                 :                :             }
                               1636                 :                :             else
                               1637                 :                :             {
                               1638                 :         506727 :                 norm = bt_normalize_tuple(state, itup);
                               1639                 :         506727 :                 bloom_add_element(state->filter, (unsigned char *) norm,
                               1640                 :         506727 :                                   IndexTupleSize(norm));
                               1641                 :                :                 /* Be tidy */
                               1642         [ +  + ]:         506727 :                 if (norm != itup)
                               1643                 :              1 :                     pfree(norm);
                               1644                 :                :             }
                               1645                 :                :         }
                               1646                 :                : 
                               1647                 :                :         /*
                               1648                 :                :          * * High key check *
                               1649                 :                :          *
                               1650                 :                :          * If there is a high key (if this is not the rightmost page on its
                               1651                 :                :          * entire level), check that high key actually is upper bound on all
                               1652                 :                :          * page items.  If this is a posting list tuple, we'll need to set
                               1653                 :                :          * scantid to be highest TID in posting list.
                               1654                 :                :          *
                               1655                 :                :          * We prefer to check all items against high key rather than checking
                               1656                 :                :          * just the last and trusting that the operator class obeys the
                               1657                 :                :          * transitive law (which implies that all previous items also
                               1658                 :                :          * respected the high key invariant if they pass the item order
                               1659                 :                :          * check).
                               1660                 :                :          *
                               1661                 :                :          * Ideally, we'd compare every item in the index against every other
                               1662                 :                :          * item in the index, and not trust opclass obedience of the
                               1663                 :                :          * transitive law to bridge the gap between children and their
                               1664                 :                :          * grandparents (as well as great-grandparents, and so on).  We don't
                               1665                 :                :          * go to those lengths because that would be prohibitively expensive,
                               1666                 :                :          * and probably not markedly more effective in practice.
                               1667                 :                :          *
                               1668                 :                :          * On the leaf level, we check that the key is <= the highkey.
                               1669                 :                :          * However, on non-leaf levels we check that the key is < the highkey,
                               1670                 :                :          * because the high key is "just another separator" rather than a copy
                               1671                 :                :          * of some existing key item; we expect it to be unique among all keys
                               1672                 :                :          * on the same level.  (Suffix truncation will sometimes produce a
                               1673                 :                :          * leaf highkey that is an untruncated copy of the lastleft item, but
                               1674                 :                :          * never any other item, which necessitates weakening the leaf level
                               1675                 :                :          * check to <=.)
                               1676                 :                :          *
                               1677                 :                :          * Full explanation for why a highkey is never truly a copy of another
                               1678                 :                :          * item from the same level on internal levels:
                               1679                 :                :          *
                               1680                 :                :          * While the new left page's high key is copied from the first offset
                               1681                 :                :          * on the right page during an internal page split, that's not the
                               1682                 :                :          * full story.  In effect, internal pages are split in the middle of
                               1683                 :                :          * the firstright tuple, not between the would-be lastleft and
                               1684                 :                :          * firstright tuples: the firstright key ends up on the left side as
                               1685                 :                :          * left's new highkey, and the firstright downlink ends up on the
                               1686                 :                :          * right side as right's new "negative infinity" item.  The negative
                               1687                 :                :          * infinity tuple is truncated to zero attributes, so we're only left
                               1688                 :                :          * with the downlink.  In other words, the copying is just an
                               1689                 :                :          * implementation detail of splitting in the middle of a (pivot)
                               1690                 :                :          * tuple. (See also: "Notes About Data Representation" in the nbtree
                               1691                 :                :          * README.)
                               1692                 :                :          */
                               1693                 :        2018549 :         scantid = skey->scantid;
                               1694   [ +  -  +  + ]:        2018549 :         if (state->heapkeyspace && BTreeTupleIsPosting(itup))
                               1695                 :          10287 :             skey->scantid = BTreeTupleGetMaxHeapTID(itup);
                               1696                 :                : 
 2593 andres@anarazel.de       1697   [ +  +  -  + ]:        3869398 :         if (!P_RIGHTMOST(topaque) &&
 1852 pg@bowt.ie               1698         [ +  + ]:        1850849 :             !(P_ISLEAF(topaque) ? invariant_leq_offset(state, skey, P_HIKEY) :
                               1699                 :            566 :               invariant_l_offset(state, skey, P_HIKEY)))
                               1700                 :                :         {
 1509 pg@bowt.ie               1701                 :UBC           0 :             ItemPointer tid = BTreeTupleGetPointsToTID(itup);
                               1702                 :                :             char       *itid,
                               1703                 :                :                        *htid;
                               1704                 :                : 
 2593 andres@anarazel.de       1705                 :              0 :             itid = psprintf("(%u,%u)", state->targetblock, offset);
                               1706                 :              0 :             htid = psprintf("(%u,%u)",
                               1707                 :                :                             ItemPointerGetBlockNumberNoCheck(tid),
 1509 pg@bowt.ie               1708                 :              0 :                             ItemPointerGetOffsetNumberNoCheck(tid));
                               1709                 :                : 
 2593 andres@anarazel.de       1710   [ #  #  #  # ]:              0 :             ereport(ERROR,
                               1711                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               1712                 :                :                      errmsg("high key invariant violated for index \"%s\"",
                               1713                 :                :                             RelationGetRelationName(state->rel)),
                               1714                 :                :                      errdetail_internal("Index tid=%s points to %s tid=%s page lsn=%X/%X.",
                               1715                 :                :                                         itid,
                               1716                 :                :                                         P_ISLEAF(topaque) ? "heap" : "index",
                               1717                 :                :                                         htid,
                               1718                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn))));
                               1719                 :                :         }
                               1720                 :                :         /* Reset, in case scantid was set to (itup) posting tuple's max TID */
 1509 pg@bowt.ie               1721                 :CBC     2018549 :         skey->scantid = scantid;
                               1722                 :                : 
                               1723                 :                :         /*
                               1724                 :                :          * * Item order check *
                               1725                 :                :          *
                               1726                 :                :          * Check that items are stored on page in logical order, by checking
                               1727                 :                :          * current item is strictly less than next item (if any).
                               1728                 :                :          */
 2593 andres@anarazel.de       1729         [ +  + ]:        2018549 :         if (OffsetNumberNext(offset) <= max &&
 1852 pg@bowt.ie               1730         [ +  + ]:        2009477 :             !invariant_l_offset(state, skey, OffsetNumberNext(offset)))
                               1731                 :                :         {
                               1732                 :                :             ItemPointer tid;
                               1733                 :                :             char       *itid,
                               1734                 :                :                        *htid,
                               1735                 :                :                        *nitid,
                               1736                 :                :                        *nhtid;
                               1737                 :                : 
 2593 andres@anarazel.de       1738                 :GBC           3 :             itid = psprintf("(%u,%u)", state->targetblock, offset);
 1509 pg@bowt.ie               1739                 :              3 :             tid = BTreeTupleGetPointsToTID(itup);
 2593 andres@anarazel.de       1740                 :              3 :             htid = psprintf("(%u,%u)",
                               1741                 :                :                             ItemPointerGetBlockNumberNoCheck(tid),
 1509 pg@bowt.ie               1742                 :              3 :                             ItemPointerGetOffsetNumberNoCheck(tid));
 2593 andres@anarazel.de       1743                 :              3 :             nitid = psprintf("(%u,%u)", state->targetblock,
                               1744                 :              3 :                              OffsetNumberNext(offset));
                               1745                 :                : 
                               1746                 :                :             /* Reuse itup to get pointed-to heap location of second item */
 1816 pg@bowt.ie               1747                 :              3 :             itemid = PageGetItemIdCareful(state, state->targetblock,
                               1748                 :                :                                           state->target,
                               1749                 :              3 :                                           OffsetNumberNext(offset));
 2593 andres@anarazel.de       1750                 :              3 :             itup = (IndexTuple) PageGetItem(state->target, itemid);
 1509 pg@bowt.ie               1751                 :              3 :             tid = BTreeTupleGetPointsToTID(itup);
 2593 andres@anarazel.de       1752                 :              3 :             nhtid = psprintf("(%u,%u)",
                               1753                 :                :                              ItemPointerGetBlockNumberNoCheck(tid),
 1509 pg@bowt.ie               1754                 :              3 :                              ItemPointerGetOffsetNumberNoCheck(tid));
                               1755                 :                : 
 2593 andres@anarazel.de       1756   [ +  -  +  +  :              3 :             ereport(ERROR,
                                              +  + ]
                               1757                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               1758                 :                :                      errmsg("item order invariant violated for index \"%s\"",
                               1759                 :                :                             RelationGetRelationName(state->rel)),
                               1760                 :                :                      errdetail_internal("Lower index tid=%s (points to %s tid=%s) "
                               1761                 :                :                                         "higher index tid=%s (points to %s tid=%s) "
                               1762                 :                :                                         "page lsn=%X/%X.",
                               1763                 :                :                                         itid,
                               1764                 :                :                                         P_ISLEAF(topaque) ? "heap" : "index",
                               1765                 :                :                                         htid,
                               1766                 :                :                                         nitid,
                               1767                 :                :                                         P_ISLEAF(topaque) ? "heap" : "index",
                               1768                 :                :                                         nhtid,
                               1769                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn))));
                               1770                 :                :         }
                               1771                 :                : 
                               1772                 :                :         /*
                               1773                 :                :          * If the index is unique verify entries uniqueness by checking the
                               1774                 :                :          * heap tuples visibility.
                               1775                 :                :          */
  169 akorotkov@postgresql     1776   [ +  +  +  + ]:GNC     2018546 :         if (state->checkunique && state->indexinfo->ii_Unique &&
                               1777   [ +  +  +  + ]:         145510 :             P_ISLEAF(topaque) && !skey->anynullkeys)
                               1778                 :         144902 :             bt_entry_unique_check(state, itup, state->targetblock, offset,
                               1779                 :                :                                   &lVis_i, &lVis_tid, &lVis_offset,
                               1780                 :                :                                   &lVis_block);
                               1781                 :                : 
                               1782   [ +  +  +  + ]:        2018543 :         if (state->checkunique && state->indexinfo->ii_Unique &&
                               1783   [ +  +  +  + ]:         145507 :             P_ISLEAF(topaque) && OffsetNumberNext(offset) <= max)
                               1784                 :                :         {
                               1785                 :                :             /* Save current scankey tid */
                               1786                 :         144165 :             scantid = skey->scantid;
                               1787                 :                : 
                               1788                 :                :             /*
                               1789                 :                :              * Invalidate scankey tid to make _bt_compare compare only keys in
                               1790                 :                :              * the item to report equality even if heap TIDs are different
                               1791                 :                :              */
                               1792                 :         144165 :             skey->scantid = NULL;
                               1793                 :                : 
                               1794                 :                :             /*
                               1795                 :                :              * If next key tuple is different, invalidate last visible entry
                               1796                 :                :              * data (whole index tuple or last posting in index tuple). Key
                               1797                 :                :              * containing null value does not violate unique constraint and
                               1798                 :                :              * treated as different to any other key.
                               1799                 :                :              */
                               1800         [ +  + ]:         144165 :             if (_bt_compare(state->rel, skey, state->target,
                               1801         [ +  + ]:         144323 :                             OffsetNumberNext(offset)) != 0 || skey->anynullkeys)
                               1802                 :                :             {
                               1803                 :         144077 :                 lVis_i = -1;
                               1804                 :         144077 :                 lVis_tid = NULL;
                               1805                 :         144077 :                 lVis_block = InvalidBlockNumber;
                               1806                 :         144077 :                 lVis_offset = InvalidOffsetNumber;
                               1807                 :                :             }
                               1808                 :         144165 :             skey->scantid = scantid; /* Restore saved scan key state */
                               1809                 :                :         }
                               1810                 :                : 
                               1811                 :                :         /*
                               1812                 :                :          * * Last item check *
                               1813                 :                :          *
                               1814                 :                :          * Check last item against next/right page's first data item's when
                               1815                 :                :          * last item on page is reached.  This additional check will detect
                               1816                 :                :          * transposed pages iff the supposed right sibling page happens to
                               1817                 :                :          * belong before target in the key space.  (Otherwise, a subsequent
                               1818                 :                :          * heap verification will probably detect the problem.)
                               1819                 :                :          *
                               1820                 :                :          * This check is similar to the item order check that will have
                               1821                 :                :          * already been performed for every other "real" item on target page
                               1822                 :                :          * when last item is checked.  The difference is that the next item
                               1823                 :                :          * (the item that is compared to target's last item) needs to come
                               1824                 :                :          * from the next/sibling page.  There may not be such an item
                               1825                 :                :          * available from sibling for various reasons, though (e.g., target is
                               1826                 :                :          * the rightmost page on level).
                               1827                 :                :          */
                               1828         [ +  + ]:        2018543 :         if (offset == max)
                               1829                 :                :         {
                               1830                 :                :             BTScanInsert rightkey;
                               1831                 :                :             BlockNumber rightblock_number;
                               1832                 :                : 
                               1833                 :                :             /* first offset on a right index page (log only) */
                               1834                 :           9072 :             OffsetNumber rightfirstoffset = InvalidOffsetNumber;
                               1835                 :                : 
                               1836                 :                :             /* Get item in next/right page */
                               1837                 :           9072 :             rightkey = bt_right_page_check_scankey(state, &rightfirstoffset);
                               1838                 :                : 
 2593 andres@anarazel.de       1839         [ +  + ]:CBC        9072 :             if (rightkey &&
 1852 pg@bowt.ie               1840         [ -  + ]:           6615 :                 !invariant_g_offset(state, rightkey, max))
                               1841                 :                :             {
                               1842                 :                :                 /*
                               1843                 :                :                  * As explained at length in bt_right_page_check_scankey(),
                               1844                 :                :                  * there is a known !readonly race that could account for
                               1845                 :                :                  * apparent violation of invariant, which we must check for
                               1846                 :                :                  * before actually proceeding with raising error.  Our canary
                               1847                 :                :                  * condition is that target page was deleted.
                               1848                 :                :                  */
 2593 andres@anarazel.de       1849         [ #  # ]:UBC           0 :                 if (!state->readonly)
                               1850                 :                :                 {
                               1851                 :                :                     /* Get fresh copy of target page */
                               1852                 :              0 :                     state->target = palloc_btree_page(state, state->targetblock);
                               1853                 :                :                     /* Note that we deliberately do not update target LSN */
  744 michael@paquier.xyz      1854                 :              0 :                     topaque = BTPageGetOpaque(state->target);
                               1855                 :                : 
                               1856                 :                :                     /*
                               1857                 :                :                      * All !readonly checks now performed; just return
                               1858                 :                :                      */
 2593 andres@anarazel.de       1859         [ #  # ]:              0 :                     if (P_IGNORE(topaque))
                               1860                 :              0 :                         return;
                               1861                 :                :                 }
                               1862                 :                : 
                               1863         [ #  # ]:              0 :                 ereport(ERROR,
                               1864                 :                :                         (errcode(ERRCODE_INDEX_CORRUPTED),
                               1865                 :                :                          errmsg("cross page item order invariant violated for index \"%s\"",
                               1866                 :                :                                 RelationGetRelationName(state->rel)),
                               1867                 :                :                          errdetail_internal("Last item on page tid=(%u,%u) page lsn=%X/%X.",
                               1868                 :                :                                             state->targetblock, offset,
                               1869                 :                :                                             LSN_FORMAT_ARGS(state->targetlsn))));
                               1870                 :                :             }
                               1871                 :                : 
                               1872                 :                :             /*
                               1873                 :                :              * If index has unique constraint make sure that no more than one
                               1874                 :                :              * found equal items is visible.
                               1875                 :                :              */
  169 akorotkov@postgresql     1876                 :GNC        9072 :             rightblock_number = topaque->btpo_next;
                               1877   [ +  +  +  +  :           9072 :             if (state->checkunique && state->indexinfo->ii_Unique &&
                                              +  + ]
                               1878   [ +  -  +  - ]:            526 :                 rightkey && P_ISLEAF(topaque) && rightblock_number != P_NONE)
                               1879                 :                :             {
                               1880         [ -  + ]:            526 :                 elog(DEBUG2, "check cross page unique condition");
                               1881                 :                : 
                               1882                 :                :                 /*
                               1883                 :                :                  * Make _bt_compare compare only index keys without heap TIDs.
                               1884                 :                :                  * rightkey->scantid is modified destructively but it is ok
                               1885                 :                :                  * for it is not used later.
                               1886                 :                :                  */
                               1887                 :            526 :                 rightkey->scantid = NULL;
                               1888                 :                : 
                               1889                 :                :                 /* The first key on the next page is the same */
                               1890   [ +  +  -  + ]:            526 :                 if (_bt_compare(state->rel, rightkey, state->target, max) == 0 && !rightkey->anynullkeys)
                               1891                 :                :                 {
  169 akorotkov@postgresql     1892         [ #  # ]:UNC           0 :                     elog(DEBUG2, "cross page equal keys");
                               1893                 :              0 :                     state->target = palloc_btree_page(state,
                               1894                 :                :                                                       rightblock_number);
                               1895                 :              0 :                     topaque = BTPageGetOpaque(state->target);
                               1896                 :                : 
                               1897   [ #  #  #  # ]:              0 :                     if (P_IGNORE(topaque) || !P_ISLEAF(topaque))
                               1898                 :                :                         break;
                               1899                 :                : 
                               1900                 :              0 :                     itemid = PageGetItemIdCareful(state, rightblock_number,
                               1901                 :                :                                                   state->target,
                               1902                 :                :                                                   rightfirstoffset);
                               1903                 :              0 :                     itup = (IndexTuple) PageGetItem(state->target, itemid);
                               1904                 :                : 
                               1905                 :              0 :                     bt_entry_unique_check(state, itup, rightblock_number, rightfirstoffset,
                               1906                 :                :                                           &lVis_i, &lVis_tid, &lVis_offset,
                               1907                 :                :                                           &lVis_block);
                               1908                 :                :                 }
                               1909                 :                :             }
                               1910                 :                :         }
                               1911                 :                : 
                               1912                 :                :         /*
                               1913                 :                :          * * Downlink check *
                               1914                 :                :          *
                               1915                 :                :          * Additional check of child items iff this is an internal page and
                               1916                 :                :          * caller holds a ShareLock.  This happens for every downlink (item)
                               1917                 :                :          * in target excluding the negative-infinity downlink (again, this is
                               1918                 :                :          * because it has no useful value to compare).
                               1919                 :                :          */
 2593 andres@anarazel.de       1920   [ +  +  +  + ]:CBC     2018543 :         if (!P_ISLEAF(topaque) && state->readonly)
 1495 akorotkov@postgresql     1921                 :           1861 :             bt_child_check(state, skey, offset);
                               1922                 :                :     }
                               1923                 :                : 
                               1924                 :                :     /*
                               1925                 :                :      * Special case bt_child_highkey_check() call
                               1926                 :                :      *
                               1927                 :                :      * We don't pass a real downlink, but we've to finish the level
                               1928                 :                :      * processing. If condition is satisfied, we've already processed all the
                               1929                 :                :      * downlinks from the target level.  But there still might be pages to the
                               1930                 :                :      * right of the child page pointer to by our rightmost downlink.  And they
                               1931                 :                :      * might have missing downlinks.  This final call checks for them.
                               1932                 :                :      */
                               1933   [ +  +  +  +  :           9074 :     if (!P_ISLEAF(topaque) && P_RIGHTMOST(topaque) && state->readonly)
                                              +  + ]
                               1934                 :                :     {
                               1935                 :             11 :         bt_child_highkey_check(state, InvalidOffsetNumber,
                               1936                 :                :                                NULL, topaque->btpo_level);
                               1937                 :                :     }
                               1938                 :                : }
                               1939                 :                : 
                               1940                 :                : /*
                               1941                 :                :  * Return a scankey for an item on page to right of current target (or the
                               1942                 :                :  * first non-ignorable page), sufficient to check ordering invariant on last
                               1943                 :                :  * item in current target page.  Returned scankey relies on local memory
                               1944                 :                :  * allocated for the child page, which caller cannot pfree().  Caller's memory
                               1945                 :                :  * context should be reset between calls here.
                               1946                 :                :  *
                               1947                 :                :  * This is the first data item, and so all adjacent items are checked against
                               1948                 :                :  * their immediate sibling item (which may be on a sibling page, or even a
                               1949                 :                :  * "cousin" page at parent boundaries where target's rightlink points to page
                               1950                 :                :  * with different parent page).  If no such valid item is available, return
                               1951                 :                :  * NULL instead.
                               1952                 :                :  *
                               1953                 :                :  * Note that !readonly callers must reverify that target page has not
                               1954                 :                :  * been concurrently deleted.
                               1955                 :                :  *
                               1956                 :                :  * Save rightfirstdataoffset for detailed error message.
                               1957                 :                :  */
                               1958                 :                : static BTScanInsert
  169 akorotkov@postgresql     1959                 :GNC        9072 : bt_right_page_check_scankey(BtreeCheckState *state, OffsetNumber *rightfirstoffset)
                               1960                 :                : {
                               1961                 :                :     BTPageOpaque opaque;
                               1962                 :                :     ItemId      rightitem;
                               1963                 :                :     IndexTuple  firstitup;
                               1964                 :                :     BlockNumber targetnext;
                               1965                 :                :     Page        rightpage;
                               1966                 :                :     OffsetNumber nline;
                               1967                 :                : 
                               1968                 :                :     /* Determine target's next block number */
  744 michael@paquier.xyz      1969                 :CBC        9072 :     opaque = BTPageGetOpaque(state->target);
                               1970                 :                : 
                               1971                 :                :     /* If target is already rightmost, no right sibling; nothing to do here */
 2593 andres@anarazel.de       1972         [ +  + ]:           9072 :     if (P_RIGHTMOST(opaque))
                               1973                 :           2457 :         return NULL;
                               1974                 :                : 
                               1975                 :                :     /*
                               1976                 :                :      * General notes on concurrent page splits and page deletion:
                               1977                 :                :      *
                               1978                 :                :      * Routines like _bt_search() don't require *any* page split interlock
                               1979                 :                :      * when descending the tree, including something very light like a buffer
                               1980                 :                :      * pin. That's why it's okay that we don't either.  This avoidance of any
                               1981                 :                :      * need to "couple" buffer locks is the raison d' etre of the Lehman & Yao
                               1982                 :                :      * algorithm, in fact.
                               1983                 :                :      *
                               1984                 :                :      * That leaves deletion.  A deleted page won't actually be recycled by
                               1985                 :                :      * VACUUM early enough for us to fail to at least follow its right link
                               1986                 :                :      * (or left link, or downlink) and find its sibling, because recycling
                               1987                 :                :      * does not occur until no possible index scan could land on the page.
                               1988                 :                :      * Index scans can follow links with nothing more than their snapshot as
                               1989                 :                :      * an interlock and be sure of at least that much.  (See page
                               1990                 :                :      * recycling/"visible to everyone" notes in nbtree README.)
                               1991                 :                :      *
                               1992                 :                :      * Furthermore, it's okay if we follow a rightlink and find a half-dead or
                               1993                 :                :      * dead (ignorable) page one or more times.  There will either be a
                               1994                 :                :      * further right link to follow that leads to a live page before too long
                               1995                 :                :      * (before passing by parent's rightmost child), or we will find the end
                               1996                 :                :      * of the entire level instead (possible when parent page is itself the
                               1997                 :                :      * rightmost on its level).
                               1998                 :                :      */
                               1999                 :           6615 :     targetnext = opaque->btpo_next;
                               2000                 :                :     for (;;)
                               2001                 :                :     {
                               2002         [ -  + ]:           6615 :         CHECK_FOR_INTERRUPTS();
                               2003                 :                : 
                               2004                 :           6615 :         rightpage = palloc_btree_page(state, targetnext);
  744 michael@paquier.xyz      2005                 :           6615 :         opaque = BTPageGetOpaque(rightpage);
                               2006                 :                : 
 2593 andres@anarazel.de       2007   [ -  +  -  - ]:           6615 :         if (!P_IGNORE(opaque) || P_RIGHTMOST(opaque))
                               2008                 :                :             break;
                               2009                 :                : 
                               2010                 :                :         /*
                               2011                 :                :          * We landed on a deleted or half-dead sibling page.  Step right until
                               2012                 :                :          * we locate a live sibling page.
                               2013                 :                :          */
 1125 pg@bowt.ie               2014         [ #  # ]:UBC           0 :         ereport(DEBUG2,
                               2015                 :                :                 (errcode(ERRCODE_NO_DATA),
                               2016                 :                :                  errmsg_internal("level %u sibling page in block %u of index \"%s\" was found deleted or half dead",
                               2017                 :                :                                  opaque->btpo_level, targetnext, RelationGetRelationName(state->rel)),
                               2018                 :                :                  errdetail_internal("Deleted page found when building scankey from right sibling.")));
                               2019                 :                : 
                               2020                 :              0 :         targetnext = opaque->btpo_next;
                               2021                 :                : 
                               2022                 :                :         /* Be slightly more pro-active in freeing this memory, just in case */
 2593 andres@anarazel.de       2023                 :              0 :         pfree(rightpage);
                               2024                 :                :     }
                               2025                 :                : 
                               2026                 :                :     /*
                               2027                 :                :      * No ShareLock held case -- why it's safe to proceed.
                               2028                 :                :      *
                               2029                 :                :      * Problem:
                               2030                 :                :      *
                               2031                 :                :      * We must avoid false positive reports of corruption when caller treats
                               2032                 :                :      * item returned here as an upper bound on target's last item.  In
                               2033                 :                :      * general, false positives are disallowed.  Avoiding them here when
                               2034                 :                :      * caller is !readonly is subtle.
                               2035                 :                :      *
                               2036                 :                :      * A concurrent page deletion by VACUUM of the target page can result in
                               2037                 :                :      * the insertion of items on to this right sibling page that would
                               2038                 :                :      * previously have been inserted on our target page.  There might have
                               2039                 :                :      * been insertions that followed the target's downlink after it was made
                               2040                 :                :      * to point to right sibling instead of target by page deletion's first
                               2041                 :                :      * phase. The inserters insert items that would belong on target page.
                               2042                 :                :      * This race is very tight, but it's possible.  This is our only problem.
                               2043                 :                :      *
                               2044                 :                :      * Non-problems:
                               2045                 :                :      *
                               2046                 :                :      * We are not hindered by a concurrent page split of the target; we'll
                               2047                 :                :      * never land on the second half of the page anyway.  A concurrent split
                               2048                 :                :      * of the right page will also not matter, because the first data item
                               2049                 :                :      * remains the same within the left half, which we'll reliably land on. If
                               2050                 :                :      * we had to skip over ignorable/deleted pages, it cannot matter because
                               2051                 :                :      * their key space has already been atomically merged with the first
                               2052                 :                :      * non-ignorable page we eventually find (doesn't matter whether the page
                               2053                 :                :      * we eventually find is a true sibling or a cousin of target, which we go
                               2054                 :                :      * into below).
                               2055                 :                :      *
                               2056                 :                :      * Solution:
                               2057                 :                :      *
                               2058                 :                :      * Caller knows that it should reverify that target is not ignorable
                               2059                 :                :      * (half-dead or deleted) when cross-page sibling item comparison appears
                               2060                 :                :      * to indicate corruption (invariant fails).  This detects the single race
                               2061                 :                :      * condition that exists for caller.  This is correct because the
                               2062                 :                :      * continued existence of target block as non-ignorable (not half-dead or
                               2063                 :                :      * deleted) implies that target page was not merged into from the right by
                               2064                 :                :      * deletion; the key space at or after target never moved left.  Target's
                               2065                 :                :      * parent either has the same downlink to target as before, or a <
                               2066                 :                :      * downlink due to deletion at the left of target.  Target either has the
                               2067                 :                :      * same highkey as before, or a highkey < before when there is a page
                               2068                 :                :      * split. (The rightmost concurrently-split-from-target-page page will
                               2069                 :                :      * still have the same highkey as target was originally found to have,
                               2070                 :                :      * which for our purposes is equivalent to target's highkey itself never
                               2071                 :                :      * changing, since we reliably skip over
                               2072                 :                :      * concurrently-split-from-target-page pages.)
                               2073                 :                :      *
                               2074                 :                :      * In simpler terms, we allow that the key space of the target may expand
                               2075                 :                :      * left (the key space can move left on the left side of target only), but
                               2076                 :                :      * the target key space cannot expand right and get ahead of us without
                               2077                 :                :      * our detecting it.  The key space of the target cannot shrink, unless it
                               2078                 :                :      * shrinks to zero due to the deletion of the original page, our canary
                               2079                 :                :      * condition.  (To be very precise, we're a bit stricter than that because
                               2080                 :                :      * it might just have been that the target page split and only the
                               2081                 :                :      * original target page was deleted.  We can be more strict, just not more
                               2082                 :                :      * lax.)
                               2083                 :                :      *
                               2084                 :                :      * Top level tree walk caller moves on to next page (makes it the new
                               2085                 :                :      * target) following recovery from this race.  (cf.  The rationale for
                               2086                 :                :      * child/downlink verification needing a ShareLock within
                               2087                 :                :      * bt_child_check(), where page deletion is also the main source of
                               2088                 :                :      * trouble.)
                               2089                 :                :      *
                               2090                 :                :      * Note that it doesn't matter if right sibling page here is actually a
                               2091                 :                :      * cousin page, because in order for the key space to be readjusted in a
                               2092                 :                :      * way that causes us issues in next level up (guiding problematic
                               2093                 :                :      * concurrent insertions to the cousin from the grandparent rather than to
                               2094                 :                :      * the sibling from the parent), there'd have to be page deletion of
                               2095                 :                :      * target's parent page (affecting target's parent's downlink in target's
                               2096                 :                :      * grandparent page).  Internal page deletion only occurs when there are
                               2097                 :                :      * no child pages (they were all fully deleted), and caller is checking
                               2098                 :                :      * that the target's parent has at least one non-deleted (so
                               2099                 :                :      * non-ignorable) child: the target page.  (Note that the first phase of
                               2100                 :                :      * deletion atomically marks the page to be deleted half-dead/ignorable at
                               2101                 :                :      * the same time downlink in its parent is removed, so caller will
                               2102                 :                :      * definitely not fail to detect that this happened.)
                               2103                 :                :      *
                               2104                 :                :      * This trick is inspired by the method backward scans use for dealing
                               2105                 :                :      * with concurrent page splits; concurrent page deletion is a problem that
                               2106                 :                :      * similarly receives special consideration sometimes (it's possible that
                               2107                 :                :      * the backwards scan will re-read its "original" block after failing to
                               2108                 :                :      * find a right-link to it, having already moved in the opposite direction
                               2109                 :                :      * (right/"forwards") a few times to try to locate one).  Just like us,
                               2110                 :                :      * that happens only to determine if there was a concurrent page deletion
                               2111                 :                :      * of a reference page, and just like us if there was a page deletion of
                               2112                 :                :      * that reference page it means we can move on from caring about the
                               2113                 :                :      * reference page.  See the nbtree README for a full description of how
                               2114                 :                :      * that works.
                               2115                 :                :      */
 2593 andres@anarazel.de       2116                 :CBC        6615 :     nline = PageGetMaxOffsetNumber(rightpage);
                               2117                 :                : 
                               2118                 :                :     /*
                               2119                 :                :      * Get first data item, if any
                               2120                 :                :      */
                               2121   [ +  +  +  +  :           6615 :     if (P_ISLEAF(opaque) && nline >= P_FIRSTDATAKEY(opaque))
                                              +  - ]
                               2122                 :                :     {
                               2123                 :                :         /* Return first data item (if any) */
 1816 pg@bowt.ie               2124                 :           6613 :         rightitem = PageGetItemIdCareful(state, targetnext, rightpage,
                               2125         [ +  + ]:           6613 :                                          P_FIRSTDATAKEY(opaque));
  169 akorotkov@postgresql     2126         [ +  + ]:GNC        6613 :         *rightfirstoffset = P_FIRSTDATAKEY(opaque);
                               2127                 :                :     }
 2593 andres@anarazel.de       2128   [ +  -  +  - ]:CBC           4 :     else if (!P_ISLEAF(opaque) &&
                               2129         [ +  - ]:              2 :              nline >= OffsetNumberNext(P_FIRSTDATAKEY(opaque)))
                               2130                 :                :     {
                               2131                 :                :         /*
                               2132                 :                :          * Return first item after the internal page's "negative infinity"
                               2133                 :                :          * item
                               2134                 :                :          */
 1816 pg@bowt.ie               2135                 :UBC           0 :         rightitem = PageGetItemIdCareful(state, targetnext, rightpage,
 1816 pg@bowt.ie               2136         [ +  - ]:CBC           2 :                                          OffsetNumberNext(P_FIRSTDATAKEY(opaque)));
                               2137                 :                :     }
                               2138                 :                :     else
                               2139                 :                :     {
                               2140                 :                :         /*
                               2141                 :                :          * No first item.  Page is probably empty leaf page, but it's also
                               2142                 :                :          * possible that it's an internal page with only a negative infinity
                               2143                 :                :          * item.
                               2144                 :                :          */
 1125 pg@bowt.ie               2145   [ #  #  #  # ]:UBC           0 :         ereport(DEBUG2,
                               2146                 :                :                 (errcode(ERRCODE_NO_DATA),
                               2147                 :                :                  errmsg_internal("%s block %u of index \"%s\" has no first data item",
                               2148                 :                :                                  P_ISLEAF(opaque) ? "leaf" : "internal", targetnext,
                               2149                 :                :                                  RelationGetRelationName(state->rel))));
 2593 andres@anarazel.de       2150                 :              0 :         return NULL;
                               2151                 :                :     }
                               2152                 :                : 
                               2153                 :                :     /*
                               2154                 :                :      * Return first real item scankey.  Note that this relies on right page
                               2155                 :                :      * memory remaining allocated.
                               2156                 :                :      */
 1852 pg@bowt.ie               2157                 :CBC        6615 :     firstitup = (IndexTuple) PageGetItem(rightpage, rightitem);
  309                          2158                 :           6615 :     return bt_mkscankey_pivotsearch(state->rel, firstitup);
                               2159                 :                : }
                               2160                 :                : 
                               2161                 :                : /*
                               2162                 :                :  * Check if two tuples are binary identical except the block number.  So,
                               2163                 :                :  * this function is capable to compare pivot keys on different levels.
                               2164                 :                :  */
                               2165                 :                : static bool
 1306                          2166                 :           1862 : bt_pivot_tuple_identical(bool heapkeyspace, IndexTuple itup1, IndexTuple itup2)
                               2167                 :                : {
 1495 akorotkov@postgresql     2168         [ -  + ]:           1862 :     if (IndexTupleSize(itup1) != IndexTupleSize(itup2))
 1495 akorotkov@postgresql     2169                 :UBC           0 :         return false;
                               2170                 :                : 
 1306 pg@bowt.ie               2171         [ +  - ]:CBC        1862 :     if (heapkeyspace)
                               2172                 :                :     {
                               2173                 :                :         /*
                               2174                 :                :          * Offset number will contain important information in heapkeyspace
                               2175                 :                :          * indexes: the number of attributes left in the pivot tuple following
                               2176                 :                :          * suffix truncation.  Don't skip over it (compare it too).
                               2177                 :                :          */
                               2178                 :           1862 :         if (memcmp(&itup1->t_tid.ip_posid, &itup2->t_tid.ip_posid,
                               2179         [ -  + ]:           1862 :                    IndexTupleSize(itup1) -
                               2180                 :                :                    offsetof(ItemPointerData, ip_posid)) != 0)
 1306 pg@bowt.ie               2181                 :UBC           0 :             return false;
                               2182                 :                :     }
                               2183                 :                :     else
                               2184                 :                :     {
                               2185                 :                :         /*
                               2186                 :                :          * Cannot rely on offset number field having consistent value across
                               2187                 :                :          * levels on pg_upgrade'd !heapkeyspace indexes.  Compare contents of
                               2188                 :                :          * tuple starting from just after item pointer (i.e. after block
                               2189                 :                :          * number and offset number).
                               2190                 :                :          */
                               2191                 :              0 :         if (memcmp(&itup1->t_info, &itup2->t_info,
                               2192         [ #  # ]:              0 :                    IndexTupleSize(itup1) -
                               2193                 :                :                    offsetof(IndexTupleData, t_info)) != 0)
                               2194                 :              0 :             return false;
                               2195                 :                :     }
                               2196                 :                : 
 1495 akorotkov@postgresql     2197                 :CBC        1862 :     return true;
                               2198                 :                : }
                               2199                 :                : 
                               2200                 :                : /*---
                               2201                 :                :  * Check high keys on the child level.  Traverse rightlinks from previous
                               2202                 :                :  * downlink to the current one.  Check that there are no intermediate pages
                               2203                 :                :  * with missing downlinks.
                               2204                 :                :  *
                               2205                 :                :  * If 'loaded_child' is given, it's assumed to be the page pointed to by the
                               2206                 :                :  * downlink referenced by 'downlinkoffnum' of the target page.
                               2207                 :                :  *
                               2208                 :                :  * Basically this function is called for each target downlink and checks two
                               2209                 :                :  * invariants:
                               2210                 :                :  *
                               2211                 :                :  * 1) You can reach the next child from previous one via rightlinks;
                               2212                 :                :  * 2) Each child high key have matching pivot key on target level.
                               2213                 :                :  *
                               2214                 :                :  * Consider the sample tree picture.
                               2215                 :                :  *
                               2216                 :                :  *               1
                               2217                 :                :  *           /       \
                               2218                 :                :  *        2     <->     3
                               2219                 :                :  *      /   \        /     \
                               2220                 :                :  *    4  <>  5  <> 6 <> 7 <> 8
                               2221                 :                :  *
                               2222                 :                :  * This function will be called for blocks 4, 5, 6 and 8.  Consider what is
                               2223                 :                :  * happening for each function call.
                               2224                 :                :  *
                               2225                 :                :  * - The function call for block 4 initializes data structure and matches high
                               2226                 :                :  *   key of block 4 to downlink's pivot key of block 2.
                               2227                 :                :  * - The high key of block 5 is matched to the high key of block 2.
                               2228                 :                :  * - The block 6 has an incomplete split flag set, so its high key isn't
                               2229                 :                :  *   matched to anything.
                               2230                 :                :  * - The function call for block 8 checks that block 8 can be found while
                               2231                 :                :  *   following rightlinks from block 6.  The high key of block 7 will be
                               2232                 :                :  *   matched to downlink's pivot key in block 3.
                               2233                 :                :  *
                               2234                 :                :  * There is also final call of this function, which checks that there is no
                               2235                 :                :  * missing downlinks for children to the right of the child referenced by
                               2236                 :                :  * rightmost downlink in target level.
                               2237                 :                :  */
                               2238                 :                : static void
                               2239                 :           1884 : bt_child_highkey_check(BtreeCheckState *state,
                               2240                 :                :                        OffsetNumber target_downlinkoffnum,
                               2241                 :                :                        Page loaded_child,
                               2242                 :                :                        uint32 target_level)
                               2243                 :                : {
                               2244                 :           1884 :     BlockNumber blkno = state->prevrightlink;
                               2245                 :                :     Page        page;
                               2246                 :                :     BTPageOpaque opaque;
                               2247                 :           1884 :     bool        rightsplit = state->previncompletesplit;
                               2248                 :           1884 :     bool        first = true;
                               2249                 :                :     ItemId      itemid;
                               2250                 :                :     IndexTuple  itup;
                               2251                 :                :     BlockNumber downlink;
                               2252                 :                : 
                               2253   [ +  +  +  -  :           1884 :     if (OffsetNumberIsValid(target_downlinkoffnum))
                                              +  + ]
                               2254                 :                :     {
                               2255                 :           1873 :         itemid = PageGetItemIdCareful(state, state->targetblock,
                               2256                 :                :                                       state->target, target_downlinkoffnum);
                               2257                 :           1873 :         itup = (IndexTuple) PageGetItem(state->target, itemid);
                               2258                 :           1873 :         downlink = BTreeTupleGetDownLink(itup);
                               2259                 :                :     }
                               2260                 :                :     else
                               2261                 :                :     {
                               2262                 :             11 :         downlink = P_NONE;
                               2263                 :                :     }
                               2264                 :                : 
                               2265                 :                :     /*
                               2266                 :                :      * If no previous rightlink is memorized for current level just below
                               2267                 :                :      * target page's level, we are about to start from the leftmost page. We
                               2268                 :                :      * can't follow rightlinks from previous page, because there is no
                               2269                 :                :      * previous page.  But we still can match high key.
                               2270                 :                :      *
                               2271                 :                :      * So we initialize variables for the loop above like there is previous
                               2272                 :                :      * page referencing current child.  Also we imply previous page to not
                               2273                 :                :      * have incomplete split flag, that would make us require downlink for
                               2274                 :                :      * current child.  That's correct, because leftmost page on the level
                               2275                 :                :      * should always have parent downlink.
                               2276                 :                :      */
                               2277         [ +  + ]:           1884 :     if (!BlockNumberIsValid(blkno))
                               2278                 :                :     {
                               2279                 :             11 :         blkno = downlink;
                               2280                 :             11 :         rightsplit = false;
                               2281                 :                :     }
                               2282                 :                : 
                               2283                 :                :     /* Move to the right on the child level */
                               2284                 :                :     while (true)
                               2285                 :                :     {
                               2286                 :                :         /*
                               2287                 :                :          * Did we traverse the whole tree level and this is check for pages to
                               2288                 :                :          * the right of rightmost downlink?
                               2289                 :                :          */
                               2290   [ +  +  +  - ]:           1884 :         if (blkno == P_NONE && downlink == P_NONE)
                               2291                 :                :         {
                               2292                 :             11 :             state->prevrightlink = InvalidBlockNumber;
                               2293                 :             11 :             state->previncompletesplit = false;
                               2294                 :             11 :             return;
                               2295                 :                :         }
                               2296                 :                : 
                               2297                 :                :         /* Did we traverse the whole tree level and don't find next downlink? */
                               2298         [ -  + ]:           1873 :         if (blkno == P_NONE)
 1495 akorotkov@postgresql     2299         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2300                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               2301                 :                :                      errmsg("can't traverse from downlink %u to downlink %u of index \"%s\"",
                               2302                 :                :                             state->prevrightlink, downlink,
                               2303                 :                :                             RelationGetRelationName(state->rel))));
                               2304                 :                : 
                               2305                 :                :         /* Load page contents */
 1495 akorotkov@postgresql     2306   [ +  -  +  + ]:CBC        1873 :         if (blkno == downlink && loaded_child)
                               2307                 :           1861 :             page = loaded_child;
                               2308                 :                :         else
                               2309                 :             12 :             page = palloc_btree_page(state, blkno);
                               2310                 :                : 
  744 michael@paquier.xyz      2311                 :           1873 :         opaque = BTPageGetOpaque(page);
                               2312                 :                : 
                               2313                 :                :         /* The first page we visit at the level should be leftmost */
  167 noah@leadboat.com        2314   [ +  -  +  + ]:           1873 :         if (first && !BlockNumberIsValid(state->prevrightlink) &&
                               2315         [ -  + ]:             11 :             !bt_leftmost_ignoring_half_dead(state, blkno, opaque))
 1495 akorotkov@postgresql     2316         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2317                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               2318                 :                :                      errmsg("the first child of leftmost target page is not leftmost of its level in index \"%s\"",
                               2319                 :                :                             RelationGetRelationName(state->rel)),
                               2320                 :                :                      errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.",
                               2321                 :                :                                         state->targetblock, blkno,
                               2322                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn))));
                               2323                 :                : 
                               2324                 :                :         /* Do level sanity check */
 1145 pg@bowt.ie               2325   [ -  +  -  - ]:CBC        1873 :         if ((!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque)) &&
                               2326         [ -  + ]:           1873 :             opaque->btpo_level != target_level - 1)
 1495 akorotkov@postgresql     2327         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2328                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               2329                 :                :                      errmsg("block found while following rightlinks from child of index \"%s\" has invalid level",
                               2330                 :                :                             RelationGetRelationName(state->rel)),
                               2331                 :                :                      errdetail_internal("Block pointed to=%u expected level=%u level in pointed to block=%u.",
                               2332                 :                :                                         blkno, target_level - 1, opaque->btpo_level)));
                               2333                 :                : 
                               2334                 :                :         /* Try to detect circular links */
 1495 akorotkov@postgresql     2335   [ -  +  -  -  :CBC        1873 :         if ((!first && blkno == state->prevrightlink) || blkno == opaque->btpo_prev)
                                              -  + ]
 1495 akorotkov@postgresql     2336         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2337                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               2338                 :                :                      errmsg("circular link chain found in block %u of index \"%s\"",
                               2339                 :                :                             blkno, RelationGetRelationName(state->rel))));
                               2340                 :                : 
 1495 akorotkov@postgresql     2341   [ -  +  -  - ]:CBC        1873 :         if (blkno != downlink && !P_IGNORE(opaque))
                               2342                 :                :         {
                               2343                 :                :             /* blkno probably has missing parent downlink */
 1495 akorotkov@postgresql     2344                 :UBC           0 :             bt_downlink_missing_check(state, rightsplit, blkno, page);
                               2345                 :                :         }
                               2346                 :                : 
 1495 akorotkov@postgresql     2347                 :CBC        1873 :         rightsplit = P_INCOMPLETE_SPLIT(opaque);
                               2348                 :                : 
                               2349                 :                :         /*
                               2350                 :                :          * If we visit page with high key, check that it is equal to the
                               2351                 :                :          * target key next to corresponding downlink.
                               2352                 :                :          */
                               2353   [ +  -  +  + ]:           1873 :         if (!rightsplit && !P_RIGHTMOST(opaque))
                               2354                 :                :         {
                               2355                 :                :             BTPageOpaque topaque;
                               2356                 :                :             IndexTuple  highkey;
                               2357                 :                :             OffsetNumber pivotkey_offset;
                               2358                 :                : 
                               2359                 :                :             /* Get high key */
                               2360                 :           1862 :             itemid = PageGetItemIdCareful(state, blkno, page, P_HIKEY);
                               2361                 :           1862 :             highkey = (IndexTuple) PageGetItem(page, itemid);
                               2362                 :                : 
                               2363                 :                :             /*
                               2364                 :                :              * There might be two situations when we examine high key.  If
                               2365                 :                :              * current child page is referenced by given target downlink, we
                               2366                 :                :              * should look to the next offset number for matching key from
                               2367                 :                :              * target page.
                               2368                 :                :              *
                               2369                 :                :              * Alternatively, we're following rightlinks somewhere in the
                               2370                 :                :              * middle between page referenced by previous target's downlink
                               2371                 :                :              * and the page referenced by current target's downlink.  If
                               2372                 :                :              * current child page hasn't incomplete split flag set, then its
                               2373                 :                :              * high key should match to the target's key of current offset
                               2374                 :                :              * number. This happens when a previous call here (to
                               2375                 :                :              * bt_child_highkey_check()) found an incomplete split, and we
                               2376                 :                :              * reach a right sibling page without a downlink -- the right
                               2377                 :                :              * sibling page's high key still needs to be matched to a
                               2378                 :                :              * separator key on the parent/target level.
                               2379                 :                :              *
                               2380                 :                :              * Don't apply OffsetNumberNext() to target_downlinkoffnum when we
                               2381                 :                :              * already had to step right on the child level. Our traversal of
                               2382                 :                :              * the child level must try to move in perfect lockstep behind (to
                               2383                 :                :              * the left of) the target/parent level traversal.
                               2384                 :                :              */
                               2385         [ +  - ]:           1862 :             if (blkno == downlink)
                               2386                 :           1862 :                 pivotkey_offset = OffsetNumberNext(target_downlinkoffnum);
                               2387                 :                :             else
 1495 akorotkov@postgresql     2388                 :UBC           0 :                 pivotkey_offset = target_downlinkoffnum;
                               2389                 :                : 
  744 michael@paquier.xyz      2390                 :CBC        1862 :             topaque = BTPageGetOpaque(state->target);
                               2391                 :                : 
 1495 akorotkov@postgresql     2392         [ +  - ]:           1862 :             if (!offset_is_negative_infinity(topaque, pivotkey_offset))
                               2393                 :                :             {
                               2394                 :                :                 /*
                               2395                 :                :                  * If we're looking for the next pivot tuple in target page,
                               2396                 :                :                  * but there is no more pivot tuples, then we should match to
                               2397                 :                :                  * high key instead.
                               2398                 :                :                  */
                               2399         [ +  + ]:           1862 :                 if (pivotkey_offset > PageGetMaxOffsetNumber(state->target))
                               2400                 :                :                 {
                               2401         [ -  + ]:              1 :                     if (P_RIGHTMOST(topaque))
 1495 akorotkov@postgresql     2402         [ #  # ]:UBC           0 :                         ereport(ERROR,
                               2403                 :                :                                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               2404                 :                :                                  errmsg("child high key is greater than rightmost pivot key on target level in index \"%s\"",
                               2405                 :                :                                         RelationGetRelationName(state->rel)),
                               2406                 :                :                                  errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.",
                               2407                 :                :                                                     state->targetblock, blkno,
                               2408                 :                :                                                     LSN_FORMAT_ARGS(state->targetlsn))));
 1495 akorotkov@postgresql     2409                 :CBC           1 :                     pivotkey_offset = P_HIKEY;
                               2410                 :                :                 }
                               2411                 :           1862 :                 itemid = PageGetItemIdCareful(state, state->targetblock,
                               2412                 :                :                                               state->target, pivotkey_offset);
                               2413                 :           1862 :                 itup = (IndexTuple) PageGetItem(state->target, itemid);
                               2414                 :                :             }
                               2415                 :                :             else
                               2416                 :                :             {
                               2417                 :                :                 /*
                               2418                 :                :                  * We cannot try to match child's high key to a negative
                               2419                 :                :                  * infinity key in target, since there is nothing to compare.
                               2420                 :                :                  * However, it's still possible to match child's high key
                               2421                 :                :                  * outside of target page.  The reason why we're are is that
                               2422                 :                :                  * bt_child_highkey_check() was previously called for the
                               2423                 :                :                  * cousin page of 'loaded_child', which is incomplete split.
                               2424                 :                :                  * So, now we traverse to the right of that cousin page and
                               2425                 :                :                  * current child level page under consideration still belongs
                               2426                 :                :                  * to the subtree of target's left sibling.  Thus, we need to
                               2427                 :                :                  * match child's high key to it's left uncle page high key.
                               2428                 :                :                  * Thankfully we saved it, it's called a "low key" of target
                               2429                 :                :                  * page.
                               2430                 :                :                  */
 1495 akorotkov@postgresql     2431         [ #  # ]:UBC           0 :                 if (!state->lowkey)
                               2432         [ #  # ]:              0 :                     ereport(ERROR,
                               2433                 :                :                             (errcode(ERRCODE_INDEX_CORRUPTED),
                               2434                 :                :                              errmsg("can't find left sibling high key in index \"%s\"",
                               2435                 :                :                                     RelationGetRelationName(state->rel)),
                               2436                 :                :                              errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.",
                               2437                 :                :                                                 state->targetblock, blkno,
                               2438                 :                :                                                 LSN_FORMAT_ARGS(state->targetlsn))));
                               2439                 :              0 :                 itup = state->lowkey;
                               2440                 :                :             }
                               2441                 :                : 
 1306 pg@bowt.ie               2442         [ -  + ]:CBC        1862 :             if (!bt_pivot_tuple_identical(state->heapkeyspace, highkey, itup))
                               2443                 :                :             {
 1495 akorotkov@postgresql     2444         [ #  # ]:UBC           0 :                 ereport(ERROR,
                               2445                 :                :                         (errcode(ERRCODE_INDEX_CORRUPTED),
                               2446                 :                :                          errmsg("mismatch between parent key and child high key in index \"%s\"",
                               2447                 :                :                                 RelationGetRelationName(state->rel)),
                               2448                 :                :                          errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.",
                               2449                 :                :                                             state->targetblock, blkno,
                               2450                 :                :                                             LSN_FORMAT_ARGS(state->targetlsn))));
                               2451                 :                :             }
                               2452                 :                :         }
                               2453                 :                : 
                               2454                 :                :         /* Exit if we already found next downlink */
 1495 akorotkov@postgresql     2455         [ +  - ]:CBC        1873 :         if (blkno == downlink)
                               2456                 :                :         {
                               2457                 :           1873 :             state->prevrightlink = opaque->btpo_next;
                               2458                 :           1873 :             state->previncompletesplit = rightsplit;
                               2459                 :           1873 :             return;
                               2460                 :                :         }
                               2461                 :                : 
                               2462                 :                :         /* Traverse to the next page using rightlink */
 1495 akorotkov@postgresql     2463                 :UBC           0 :         blkno = opaque->btpo_next;
                               2464                 :                : 
                               2465                 :                :         /* Free page contents if it's allocated by us */
                               2466         [ #  # ]:              0 :         if (page != loaded_child)
                               2467                 :              0 :             pfree(page);
                               2468                 :              0 :         first = false;
                               2469                 :                :     }
                               2470                 :                : }
                               2471                 :                : 
                               2472                 :                : /*
                               2473                 :                :  * Checks one of target's downlink against its child page.
                               2474                 :                :  *
                               2475                 :                :  * Conceptually, the target page continues to be what is checked here.  The
                               2476                 :                :  * target block is still blamed in the event of finding an invariant violation.
                               2477                 :                :  * The downlink insertion into the target is probably where any problem raised
                               2478                 :                :  * here arises, and there is no such thing as a parent link, so doing the
                               2479                 :                :  * verification this way around is much more practical.
                               2480                 :                :  *
                               2481                 :                :  * This function visits child page and it's sequentially called for each
                               2482                 :                :  * downlink of target page.  Assuming this we also check downlink connectivity
                               2483                 :                :  * here in order to save child page visits.
                               2484                 :                :  */
                               2485                 :                : static void
 1495 akorotkov@postgresql     2486                 :CBC        1861 : bt_child_check(BtreeCheckState *state, BTScanInsert targetkey,
                               2487                 :                :                OffsetNumber downlinkoffnum)
                               2488                 :                : {
                               2489                 :                :     ItemId      itemid;
                               2490                 :                :     IndexTuple  itup;
                               2491                 :                :     BlockNumber childblock;
                               2492                 :                :     OffsetNumber offset;
                               2493                 :                :     OffsetNumber maxoffset;
                               2494                 :                :     Page        child;
                               2495                 :                :     BTPageOpaque copaque;
                               2496                 :                :     BTPageOpaque topaque;
                               2497                 :                : 
                               2498                 :           1861 :     itemid = PageGetItemIdCareful(state, state->targetblock,
                               2499                 :                :                                   state->target, downlinkoffnum);
                               2500                 :           1861 :     itup = (IndexTuple) PageGetItem(state->target, itemid);
                               2501                 :           1861 :     childblock = BTreeTupleGetDownLink(itup);
                               2502                 :                : 
                               2503                 :                :     /*
                               2504                 :                :      * Caller must have ShareLock on target relation, because of
                               2505                 :                :      * considerations around page deletion by VACUUM.
                               2506                 :                :      *
                               2507                 :                :      * NB: In general, page deletion deletes the right sibling's downlink, not
                               2508                 :                :      * the downlink of the page being deleted; the deleted page's downlink is
                               2509                 :                :      * reused for its sibling.  The key space is thereby consolidated between
                               2510                 :                :      * the deleted page and its right sibling.  (We cannot delete a parent
                               2511                 :                :      * page's rightmost child unless it is the last child page, and we intend
                               2512                 :                :      * to also delete the parent itself.)
                               2513                 :                :      *
                               2514                 :                :      * If this verification happened without a ShareLock, the following race
                               2515                 :                :      * condition could cause false positives:
                               2516                 :                :      *
                               2517                 :                :      * In general, concurrent page deletion might occur, including deletion of
                               2518                 :                :      * the left sibling of the child page that is examined here.  If such a
                               2519                 :                :      * page deletion were to occur, closely followed by an insertion into the
                               2520                 :                :      * newly expanded key space of the child, a window for the false positive
                               2521                 :                :      * opens up: the stale parent/target downlink originally followed to get
                               2522                 :                :      * to the child legitimately ceases to be a lower bound on all items in
                               2523                 :                :      * the page, since the key space was concurrently expanded "left".
                               2524                 :                :      * (Insertion followed the "new" downlink for the child, not our now-stale
                               2525                 :                :      * downlink, which was concurrently physically removed in target/parent as
                               2526                 :                :      * part of deletion's first phase.)
                               2527                 :                :      *
                               2528                 :                :      * While we use various techniques elsewhere to perform cross-page
                               2529                 :                :      * verification for !readonly callers, a similar trick seems difficult
                               2530                 :                :      * here.  The tricks used by bt_recheck_sibling_links and by
                               2531                 :                :      * bt_right_page_check_scankey both involve verification of a same-level,
                               2532                 :                :      * cross-sibling invariant.  Cross-level invariants are far more squishy,
                               2533                 :                :      * though.  The nbtree REDO routines do not actually couple buffer locks
                               2534                 :                :      * across levels during page splits, so making any cross-level check work
                               2535                 :                :      * reliably in !readonly mode may be impossible.
                               2536                 :                :      */
 2593 andres@anarazel.de       2537         [ -  + ]:           1861 :     Assert(state->readonly);
                               2538                 :                : 
                               2539                 :                :     /*
                               2540                 :                :      * Verify child page has the downlink key from target page (its parent) as
                               2541                 :                :      * a lower bound; downlink must be strictly less than all keys on the
                               2542                 :                :      * page.
                               2543                 :                :      *
                               2544                 :                :      * Check all items, rather than checking just the first and trusting that
                               2545                 :                :      * the operator class obeys the transitive law.
                               2546                 :                :      */
  744 michael@paquier.xyz      2547                 :           1861 :     topaque = BTPageGetOpaque(state->target);
 2593 andres@anarazel.de       2548                 :           1861 :     child = palloc_btree_page(state, childblock);
  744 michael@paquier.xyz      2549                 :           1861 :     copaque = BTPageGetOpaque(child);
 2593 andres@anarazel.de       2550                 :           1861 :     maxoffset = PageGetMaxOffsetNumber(child);
                               2551                 :                : 
                               2552                 :                :     /*
                               2553                 :                :      * Since we've already loaded the child block, combine this check with
                               2554                 :                :      * check for downlink connectivity.
                               2555                 :                :      */
 1495 akorotkov@postgresql     2556                 :           1861 :     bt_child_highkey_check(state, downlinkoffnum,
                               2557                 :                :                            child, topaque->btpo_level);
                               2558                 :                : 
                               2559                 :                :     /*
                               2560                 :                :      * Since there cannot be a concurrent VACUUM operation in readonly mode,
                               2561                 :                :      * and since a page has no links within other pages (siblings and parent)
                               2562                 :                :      * once it is marked fully deleted, it should be impossible to land on a
                               2563                 :                :      * fully deleted page.
                               2564                 :                :      *
                               2565                 :                :      * It does not quite make sense to enforce that the page cannot even be
                               2566                 :                :      * half-dead, despite the fact the downlink is modified at the same stage
                               2567                 :                :      * that the child leaf page is marked half-dead.  That's incorrect because
                               2568                 :                :      * there may occasionally be multiple downlinks from a chain of pages
                               2569                 :                :      * undergoing deletion, where multiple successive calls are made to
                               2570                 :                :      * _bt_unlink_halfdead_page() by VACUUM before it can finally safely mark
                               2571                 :                :      * the leaf page as fully dead.  While _bt_mark_page_halfdead() usually
                               2572                 :                :      * removes the downlink to the leaf page that is marked half-dead, that's
                               2573                 :                :      * not guaranteed, so it's possible we'll land on a half-dead page with a
                               2574                 :                :      * downlink due to an interrupted multi-level page deletion.
                               2575                 :                :      *
                               2576                 :                :      * We go ahead with our checks if the child page is half-dead.  It's safe
                               2577                 :                :      * to do so because we do not test the child's high key, so it does not
                               2578                 :                :      * matter that the original high key will have been replaced by a dummy
                               2579                 :                :      * truncated high key within _bt_mark_page_halfdead().  All other page
                               2580                 :                :      * items are left intact on a half-dead page, so there is still something
                               2581                 :                :      * to test.
                               2582                 :                :      */
 2181 teodor@sigaev.ru         2583         [ -  + ]:           1861 :     if (P_ISDELETED(copaque))
 2181 teodor@sigaev.ru         2584         [ #  # ]:UBC           0 :         ereport(ERROR,
                               2585                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               2586                 :                :                  errmsg("downlink to deleted page found in index \"%s\"",
                               2587                 :                :                         RelationGetRelationName(state->rel)),
                               2588                 :                :                  errdetail_internal("Parent block=%u child block=%u parent page lsn=%X/%X.",
                               2589                 :                :                                     state->targetblock, childblock,
                               2590                 :                :                                     LSN_FORMAT_ARGS(state->targetlsn))));
                               2591                 :                : 
 2593 andres@anarazel.de       2592         [ +  + ]:CBC        1861 :     for (offset = P_FIRSTDATAKEY(copaque);
                               2593         [ +  + ]:         600350 :          offset <= maxoffset;
                               2594                 :         598489 :          offset = OffsetNumberNext(offset))
                               2595                 :                :     {
                               2596                 :                :         /*
                               2597                 :                :          * Skip comparison of target page key against "negative infinity"
                               2598                 :                :          * item, if any.  Checking it would indicate that it's not a strict
                               2599                 :                :          * lower bound, but that's only because of the hard-coding for
                               2600                 :                :          * negative infinity items within _bt_compare().
                               2601                 :                :          *
                               2602                 :                :          * If nbtree didn't truncate negative infinity tuples during internal
                               2603                 :                :          * page splits then we'd expect child's negative infinity key to be
                               2604                 :                :          * equal to the scankey/downlink from target/parent (it would be a
                               2605                 :                :          * "low key" in this hypothetical scenario, and so it would still need
                               2606                 :                :          * to be treated as a special case here).
                               2607                 :                :          *
                               2608                 :                :          * Negative infinity items can be thought of as a strict lower bound
                               2609                 :                :          * that works transitively, with the last non-negative-infinity pivot
                               2610                 :                :          * followed during a descent from the root as its "true" strict lower
                               2611                 :                :          * bound.  Only a small number of negative infinity items are truly
                               2612                 :                :          * negative infinity; those that are the first items of leftmost
                               2613                 :                :          * internal pages.  In more general terms, a negative infinity item is
                               2614                 :                :          * only negative infinity with respect to the subtree that the page is
                               2615                 :                :          * at the root of.
                               2616                 :                :          *
                               2617                 :                :          * See also: bt_rootdescend(), which can even detect transitive
                               2618                 :                :          * inconsistencies on cousin leaf pages.
                               2619                 :                :          */
                               2620         [ +  + ]:         598489 :         if (offset_is_negative_infinity(copaque, offset))
                               2621                 :              1 :             continue;
                               2622                 :                : 
 1816 pg@bowt.ie               2623         [ -  + ]:         598488 :         if (!invariant_l_nontarget_offset(state, targetkey, childblock, child,
                               2624                 :                :                                           offset))
 2593 andres@anarazel.de       2625         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2626                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               2627                 :                :                      errmsg("down-link lower bound invariant violated for index \"%s\"",
                               2628                 :                :                             RelationGetRelationName(state->rel)),
                               2629                 :                :                      errdetail_internal("Parent block=%u child index tid=(%u,%u) parent page lsn=%X/%X.",
                               2630                 :                :                                         state->targetblock, childblock, offset,
                               2631                 :                :                                         LSN_FORMAT_ARGS(state->targetlsn))));
                               2632                 :                :     }
                               2633                 :                : 
 2593 andres@anarazel.de       2634                 :CBC        1861 :     pfree(child);
                               2635                 :           1861 : }
                               2636                 :                : 
                               2637                 :                : /*
                               2638                 :                :  * Checks if page is missing a downlink that it should have.
                               2639                 :                :  *
                               2640                 :                :  * A page that lacks a downlink/parent may indicate corruption.  However, we
                               2641                 :                :  * must account for the fact that a missing downlink can occasionally be
                               2642                 :                :  * encountered in a non-corrupt index.  This can be due to an interrupted page
                               2643                 :                :  * split, or an interrupted multi-level page deletion (i.e. there was a hard
                               2644                 :                :  * crash or an error during a page split, or while VACUUM was deleting a
                               2645                 :                :  * multi-level chain of pages).
                               2646                 :                :  *
                               2647                 :                :  * Note that this can only be called in readonly mode, so there is no need to
                               2648                 :                :  * be concerned about concurrent page splits or page deletions.
                               2649                 :                :  */
                               2650                 :                : static void
 1495 akorotkov@postgresql     2651                 :UBC           0 : bt_downlink_missing_check(BtreeCheckState *state, bool rightsplit,
                               2652                 :                :                           BlockNumber blkno, Page page)
                               2653                 :                : {
  744 michael@paquier.xyz      2654                 :              0 :     BTPageOpaque opaque = BTPageGetOpaque(page);
                               2655                 :                :     ItemId      itemid;
                               2656                 :                :     IndexTuple  itup;
                               2657                 :                :     Page        child;
                               2658                 :                :     BTPageOpaque copaque;
                               2659                 :                :     uint32      level;
                               2660                 :                :     BlockNumber childblk;
                               2661                 :                :     XLogRecPtr  pagelsn;
                               2662                 :                : 
 1495 akorotkov@postgresql     2663         [ #  # ]:              0 :     Assert(state->readonly);
                               2664         [ #  # ]:              0 :     Assert(!P_IGNORE(opaque));
                               2665                 :                : 
                               2666                 :                :     /* No next level up with downlinks to fingerprint from the true root */
                               2667         [ #  # ]:              0 :     if (P_ISROOT(opaque))
 2181 teodor@sigaev.ru         2668                 :              0 :         return;
                               2669                 :                : 
 1495 akorotkov@postgresql     2670                 :              0 :     pagelsn = PageGetLSN(page);
                               2671                 :                : 
                               2672                 :                :     /*
                               2673                 :                :      * Incomplete (interrupted) page splits can account for the lack of a
                               2674                 :                :      * downlink.  Some inserting transaction should eventually complete the
                               2675                 :                :      * page split in passing, when it notices that the left sibling page is
                               2676                 :                :      * P_INCOMPLETE_SPLIT().
                               2677                 :                :      *
                               2678                 :                :      * In general, VACUUM is not prepared for there to be no downlink to a
                               2679                 :                :      * page that it deletes.  This is the main reason why the lack of a
                               2680                 :                :      * downlink can be reported as corruption here.  It's not obvious that an
                               2681                 :                :      * invalid missing downlink can result in wrong answers to queries,
                               2682                 :                :      * though, since index scans that land on the child may end up
                               2683                 :                :      * consistently moving right. The handling of concurrent page splits (and
                               2684                 :                :      * page deletions) within _bt_moveright() cannot distinguish
                               2685                 :                :      * inconsistencies that last for a moment from inconsistencies that are
                               2686                 :                :      * permanent and irrecoverable.
                               2687                 :                :      *
                               2688                 :                :      * VACUUM isn't even prepared to delete pages that have no downlink due to
                               2689                 :                :      * an incomplete page split, but it can detect and reason about that case
                               2690                 :                :      * by design, so it shouldn't be taken to indicate corruption.  See
                               2691                 :                :      * _bt_pagedel() for full details.
                               2692                 :                :      */
                               2693         [ #  # ]:              0 :     if (rightsplit)
                               2694                 :                :     {
 2181 teodor@sigaev.ru         2695         [ #  # ]:              0 :         ereport(DEBUG1,
                               2696                 :                :                 (errcode(ERRCODE_NO_DATA),
                               2697                 :                :                  errmsg_internal("harmless interrupted page split detected in index \"%s\"",
                               2698                 :                :                                  RelationGetRelationName(state->rel)),
                               2699                 :                :                  errdetail_internal("Block=%u level=%u left sibling=%u page lsn=%X/%X.",
                               2700                 :                :                                     blkno, opaque->btpo_level,
                               2701                 :                :                                     opaque->btpo_prev,
                               2702                 :                :                                     LSN_FORMAT_ARGS(pagelsn))));
                               2703                 :              0 :         return;
                               2704                 :                :     }
                               2705                 :                : 
                               2706                 :                :     /*
                               2707                 :                :      * Page under check is probably the "top parent" of a multi-level page
                               2708                 :                :      * deletion.  We'll need to descend the subtree to make sure that
                               2709                 :                :      * descendant pages are consistent with that, though.
                               2710                 :                :      *
                               2711                 :                :      * If the page (which must be non-ignorable) is a leaf page, then clearly
                               2712                 :                :      * it can't be the top parent.  The lack of a downlink is probably a
                               2713                 :                :      * symptom of a broad problem that could just as easily cause
                               2714                 :                :      * inconsistencies anywhere else.
                               2715                 :                :      */
 1495 akorotkov@postgresql     2716         [ #  # ]:              0 :     if (P_ISLEAF(opaque))
 2181 teodor@sigaev.ru         2717         [ #  # ]:              0 :         ereport(ERROR,
                               2718                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               2719                 :                :                  errmsg("leaf index block lacks downlink in index \"%s\"",
                               2720                 :                :                         RelationGetRelationName(state->rel)),
                               2721                 :                :                  errdetail_internal("Block=%u page lsn=%X/%X.",
                               2722                 :                :                                     blkno,
                               2723                 :                :                                     LSN_FORMAT_ARGS(pagelsn))));
                               2724                 :                : 
                               2725                 :                :     /* Descend from the given page, which is an internal page */
                               2726         [ #  # ]:              0 :     elog(DEBUG1, "checking for interrupted multi-level deletion due to missing downlink in index \"%s\"",
                               2727                 :                :          RelationGetRelationName(state->rel));
                               2728                 :                : 
 1145 pg@bowt.ie               2729                 :              0 :     level = opaque->btpo_level;
 1495 akorotkov@postgresql     2730         [ #  # ]:              0 :     itemid = PageGetItemIdCareful(state, blkno, page, P_FIRSTDATAKEY(opaque));
                               2731                 :              0 :     itup = (IndexTuple) PageGetItem(page, itemid);
 1581 pg@bowt.ie               2732                 :              0 :     childblk = BTreeTupleGetDownLink(itup);
                               2733                 :                :     for (;;)
                               2734                 :                :     {
 2181 teodor@sigaev.ru         2735         [ #  # ]:              0 :         CHECK_FOR_INTERRUPTS();
                               2736                 :                : 
                               2737                 :              0 :         child = palloc_btree_page(state, childblk);
  744 michael@paquier.xyz      2738                 :              0 :         copaque = BTPageGetOpaque(child);
                               2739                 :                : 
 2181 teodor@sigaev.ru         2740         [ #  # ]:              0 :         if (P_ISLEAF(copaque))
                               2741                 :              0 :             break;
                               2742                 :                : 
                               2743                 :                :         /* Do an extra sanity check in passing on internal pages */
 1145 pg@bowt.ie               2744         [ #  # ]:              0 :         if (copaque->btpo_level != level - 1)
 2181 teodor@sigaev.ru         2745         [ #  # ]:              0 :             ereport(ERROR,
                               2746                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               2747                 :                :                      errmsg_internal("downlink points to block in index \"%s\" whose level is not one level down",
                               2748                 :                :                                      RelationGetRelationName(state->rel)),
                               2749                 :                :                      errdetail_internal("Top parent/under check block=%u block pointed to=%u expected level=%u level in pointed to block=%u.",
                               2750                 :                :                                         blkno, childblk,
                               2751                 :                :                                         level - 1, copaque->btpo_level)));
                               2752                 :                : 
 1145 pg@bowt.ie               2753                 :              0 :         level = copaque->btpo_level;
 1816                          2754                 :              0 :         itemid = PageGetItemIdCareful(state, childblk, child,
                               2755         [ #  # ]:              0 :                                       P_FIRSTDATAKEY(copaque));
 2181 teodor@sigaev.ru         2756                 :              0 :         itup = (IndexTuple) PageGetItem(child, itemid);
 1581 pg@bowt.ie               2757                 :              0 :         childblk = BTreeTupleGetDownLink(itup);
                               2758                 :                :         /* Be slightly more pro-active in freeing this memory, just in case */
 2181 teodor@sigaev.ru         2759                 :              0 :         pfree(child);
                               2760                 :                :     }
                               2761                 :                : 
                               2762                 :                :     /*
                               2763                 :                :      * Since there cannot be a concurrent VACUUM operation in readonly mode,
                               2764                 :                :      * and since a page has no links within other pages (siblings and parent)
                               2765                 :                :      * once it is marked fully deleted, it should be impossible to land on a
                               2766                 :                :      * fully deleted page.  See bt_child_check() for further details.
                               2767                 :                :      *
                               2768                 :                :      * The bt_child_check() P_ISDELETED() check is repeated here because
                               2769                 :                :      * bt_child_check() does not visit pages reachable through negative
                               2770                 :                :      * infinity items.  Besides, bt_child_check() is unwilling to descend
                               2771                 :                :      * multiple levels.  (The similar bt_child_check() P_ISDELETED() check
                               2772                 :                :      * within bt_check_level_from_leftmost() won't reach the page either,
                               2773                 :                :      * since the leaf's live siblings should have their sibling links updated
                               2774                 :                :      * to bypass the deletion target page when it is marked fully dead.)
                               2775                 :                :      *
                               2776                 :                :      * If this error is raised, it might be due to a previous multi-level page
                               2777                 :                :      * deletion that failed to realize that it wasn't yet safe to mark the
                               2778                 :                :      * leaf page as fully dead.  A "dangling downlink" will still remain when
                               2779                 :                :      * this happens.  The fact that the dangling downlink's page (the leaf's
                               2780                 :                :      * parent/ancestor page) lacked a downlink is incidental.
                               2781                 :                :      */
                               2782         [ #  # ]:              0 :     if (P_ISDELETED(copaque))
                               2783         [ #  # ]:              0 :         ereport(ERROR,
                               2784                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               2785                 :                :                  errmsg_internal("downlink to deleted leaf page found in index \"%s\"",
                               2786                 :                :                                  RelationGetRelationName(state->rel)),
                               2787                 :                :                  errdetail_internal("Top parent/target block=%u leaf block=%u top parent/under check lsn=%X/%X.",
                               2788                 :                :                                     blkno, childblk,
                               2789                 :                :                                     LSN_FORMAT_ARGS(pagelsn))));
                               2790                 :                : 
                               2791                 :                :     /*
                               2792                 :                :      * Iff leaf page is half-dead, its high key top parent link should point
                               2793                 :                :      * to what VACUUM considered to be the top parent page at the instant it
                               2794                 :                :      * was interrupted.  Provided the high key link actually points to the
                               2795                 :                :      * page under check, the missing downlink we detected is consistent with
                               2796                 :                :      * there having been an interrupted multi-level page deletion.  This means
                               2797                 :                :      * that the subtree with the page under check at its root (a page deletion
                               2798                 :                :      * chain) is in a consistent state, enabling VACUUM to resume deleting the
                               2799                 :                :      * entire chain the next time it encounters the half-dead leaf page.
                               2800                 :                :      */
                               2801   [ #  #  #  # ]:              0 :     if (P_ISHALFDEAD(copaque) && !P_RIGHTMOST(copaque))
                               2802                 :                :     {
 1816 pg@bowt.ie               2803                 :              0 :         itemid = PageGetItemIdCareful(state, childblk, child, P_HIKEY);
 2181 teodor@sigaev.ru         2804                 :              0 :         itup = (IndexTuple) PageGetItem(child, itemid);
 1495 akorotkov@postgresql     2805         [ #  # ]:              0 :         if (BTreeTupleGetTopParent(itup) == blkno)
 2181 teodor@sigaev.ru         2806                 :              0 :             return;
                               2807                 :                :     }
                               2808                 :                : 
                               2809         [ #  # ]:              0 :     ereport(ERROR,
                               2810                 :                :             (errcode(ERRCODE_INDEX_CORRUPTED),
                               2811                 :                :              errmsg("internal index block lacks downlink in index \"%s\"",
                               2812                 :                :                     RelationGetRelationName(state->rel)),
                               2813                 :                :              errdetail_internal("Block=%u level=%u page lsn=%X/%X.",
                               2814                 :                :                                 blkno, opaque->btpo_level,
                               2815                 :                :                                 LSN_FORMAT_ARGS(pagelsn))));
                               2816                 :                : }
                               2817                 :                : 
                               2818                 :                : /*
                               2819                 :                :  * Per-tuple callback from table_index_build_scan, used to determine if index has
                               2820                 :                :  * all the entries that definitely should have been observed in leaf pages of
                               2821                 :                :  * the target index (that is, all IndexTuples that were fingerprinted by our
                               2822                 :                :  * Bloom filter).  All heapallindexed checks occur here.
                               2823                 :                :  *
                               2824                 :                :  * The redundancy between an index and the table it indexes provides a good
                               2825                 :                :  * opportunity to detect corruption, especially corruption within the table.
                               2826                 :                :  * The high level principle behind the verification performed here is that any
                               2827                 :                :  * IndexTuple that should be in an index following a fresh CREATE INDEX (based
                               2828                 :                :  * on the same index definition) should also have been in the original,
                               2829                 :                :  * existing index, which should have used exactly the same representation
                               2830                 :                :  *
                               2831                 :                :  * Since the overall structure of the index has already been verified, the most
                               2832                 :                :  * likely explanation for error here is a corrupt heap page (could be logical
                               2833                 :                :  * or physical corruption).  Index corruption may still be detected here,
                               2834                 :                :  * though.  Only readonly callers will have verified that left links and right
                               2835                 :                :  * links are in agreement, and so it's possible that a leaf page transposition
                               2836                 :                :  * within index is actually the source of corruption detected here (for
                               2837                 :                :  * !readonly callers).  The checks performed only for readonly callers might
                               2838                 :                :  * more accurately frame the problem as a cross-page invariant issue (this
                               2839                 :                :  * could even be due to recovery not replaying all WAL records).  The !readonly
                               2840                 :                :  * ERROR message raised here includes a HINT about retrying with readonly
                               2841                 :                :  * verification, just in case it's a cross-page invariant issue, though that
                               2842                 :                :  * isn't particularly likely.
                               2843                 :                :  *
                               2844                 :                :  * table_index_build_scan() expects to be able to find the root tuple when a
                               2845                 :                :  * heap-only tuple (the live tuple at the end of some HOT chain) needs to be
                               2846                 :                :  * indexed, in order to replace the actual tuple's TID with the root tuple's
                               2847                 :                :  * TID (which is what we're actually passed back here).  The index build heap
                               2848                 :                :  * scan code will raise an error when a tuple that claims to be the root of the
                               2849                 :                :  * heap-only tuple's HOT chain cannot be located.  This catches cases where the
                               2850                 :                :  * original root item offset/root tuple for a HOT chain indicates (for whatever
                               2851                 :                :  * reason) that the entire HOT chain is dead, despite the fact that the latest
                               2852                 :                :  * heap-only tuple should be indexed.  When this happens, sequential scans may
                               2853                 :                :  * always give correct answers, and all indexes may be considered structurally
                               2854                 :                :  * consistent (i.e. the nbtree structural checks would not detect corruption).
                               2855                 :                :  * It may be the case that only index scans give wrong answers, and yet heap or
                               2856                 :                :  * SLRU corruption is the real culprit.  (While it's true that LP_DEAD bit
                               2857                 :                :  * setting will probably also leave the index in a corrupt state before too
                               2858                 :                :  * long, the problem is nonetheless that there is heap corruption.)
                               2859                 :                :  *
                               2860                 :                :  * Heap-only tuple handling within table_index_build_scan() works in a way that
                               2861                 :                :  * helps us to detect index tuples that contain the wrong values (values that
                               2862                 :                :  * don't match the latest tuple in the HOT chain).  This can happen when there
                               2863                 :                :  * is no superseding index tuple due to a faulty assessment of HOT safety,
                               2864                 :                :  * perhaps during the original CREATE INDEX.  Because the latest tuple's
                               2865                 :                :  * contents are used with the root TID, an error will be raised when a tuple
                               2866                 :                :  * with the same TID but non-matching attribute values is passed back to us.
                               2867                 :                :  * Faulty assessment of HOT-safety was behind at least two distinct CREATE
                               2868                 :                :  * INDEX CONCURRENTLY bugs that made it into stable releases, one of which was
                               2869                 :                :  * undetected for many years.  In short, the same principle that allows a
                               2870                 :                :  * REINDEX to repair corruption when there was an (undetected) broken HOT chain
                               2871                 :                :  * also allows us to detect the corruption in many cases.
                               2872                 :                :  */
                               2873                 :                : static void
 1619 andres@anarazel.de       2874                 :CBC      534868 : bt_tuple_present_callback(Relation index, ItemPointer tid, Datum *values,
                               2875                 :                :                           bool *isnull, bool tupleIsAlive, void *checkstate)
                               2876                 :                : {
 2206                          2877                 :         534868 :     BtreeCheckState *state = (BtreeCheckState *) checkstate;
                               2878                 :                :     IndexTuple  itup,
                               2879                 :                :                 norm;
                               2880                 :                : 
                               2881         [ -  + ]:         534868 :     Assert(state->heapallindexed);
                               2882                 :                : 
                               2883                 :                :     /* Generate a normalized index tuple for fingerprinting */
                               2884                 :         534868 :     itup = index_form_tuple(RelationGetDescr(index), values, isnull);
 1619                          2885                 :         534868 :     itup->t_tid = *tid;
 1894 pg@bowt.ie               2886                 :         534868 :     norm = bt_normalize_tuple(state, itup);
                               2887                 :                : 
                               2888                 :                :     /* Probe Bloom filter -- tuple should be present */
                               2889         [ -  + ]:         534868 :     if (bloom_lacks_element(state->filter, (unsigned char *) norm,
                               2890                 :         534868 :                             IndexTupleSize(norm)))
 2206 andres@anarazel.de       2891   [ #  #  #  # ]:UBC           0 :         ereport(ERROR,
                               2892                 :                :                 (errcode(ERRCODE_DATA_CORRUPTED),
                               2893                 :                :                  errmsg("heap tuple (%u,%u) from table \"%s\" lacks matching index tuple within index \"%s\"",
                               2894                 :                :                         ItemPointerGetBlockNumber(&(itup->t_tid)),
                               2895                 :                :                         ItemPointerGetOffsetNumber(&(itup->t_tid)),
                               2896                 :                :                         RelationGetRelationName(state->heaprel),
                               2897                 :                :                         RelationGetRelationName(state->rel)),
                               2898                 :                :                  !state->readonly
                               2899                 :                :                  ? errhint("Retrying verification using the function bt_index_parent_check() might provide a more specific error.")
                               2900                 :                :                  : 0));
                               2901                 :                : 
 2206 andres@anarazel.de       2902                 :CBC      534868 :     state->heaptuplespresent++;
                               2903                 :         534868 :     pfree(itup);
                               2904                 :                :     /* Cannot leak memory here */
 1894 pg@bowt.ie               2905         [ +  + ]:         534868 :     if (norm != itup)
                               2906                 :              5 :         pfree(norm);
                               2907                 :         534868 : }
                               2908                 :                : 
                               2909                 :                : /*
                               2910                 :                :  * Normalize an index tuple for fingerprinting.
                               2911                 :                :  *
                               2912                 :                :  * In general, index tuple formation is assumed to be deterministic by
                               2913                 :                :  * heapallindexed verification, and IndexTuples are assumed immutable.  While
                               2914                 :                :  * the LP_DEAD bit is mutable in leaf pages, that's ItemId metadata, which is
                               2915                 :                :  * not fingerprinted.  Normalization is required to compensate for corner
                               2916                 :                :  * cases where the determinism assumption doesn't quite work.
                               2917                 :                :  *
                               2918                 :                :  * There is currently one such case: index_form_tuple() does not try to hide
                               2919                 :                :  * the source TOAST state of input datums.  The executor applies TOAST
                               2920                 :                :  * compression for heap tuples based on different criteria to the compression
                               2921                 :                :  * applied within btinsert()'s call to index_form_tuple(): it sometimes
                               2922                 :                :  * compresses more aggressively, resulting in compressed heap tuple datums but
                               2923                 :                :  * uncompressed corresponding index tuple datums.  A subsequent heapallindexed
                               2924                 :                :  * verification will get a logically equivalent though bitwise unequal tuple
                               2925                 :                :  * from index_form_tuple().  False positive heapallindexed corruption reports
                               2926                 :                :  * could occur without normalizing away the inconsistency.
                               2927                 :                :  *
                               2928                 :                :  * Returned tuple is often caller's own original tuple.  Otherwise, it is a
                               2929                 :                :  * new representation of caller's original index tuple, palloc()'d in caller's
                               2930                 :                :  * memory context.
                               2931                 :                :  *
                               2932                 :                :  * Note: This routine is not concerned with distinctions about the
                               2933                 :                :  * representation of tuples beyond those that might break heapallindexed
                               2934                 :                :  * verification.  In particular, it won't try to normalize opclass-equal
                               2935                 :                :  * datums with potentially distinct representations (e.g., btree/numeric_ops
                               2936                 :                :  * index datums will not get their display scale normalized-away here).
                               2937                 :                :  * Caller does normalization for non-pivot tuples that have a posting list,
                               2938                 :                :  * since dummy CREATE INDEX callback code generates new tuples with the same
                               2939                 :                :  * normalized representation.
                               2940                 :                :  */
                               2941                 :                : static IndexTuple
                               2942                 :        1072141 : bt_normalize_tuple(BtreeCheckState *state, IndexTuple itup)
                               2943                 :                : {
                               2944                 :        1072141 :     TupleDesc   tupleDescriptor = RelationGetDescr(state->rel);
                               2945                 :                :     Datum       normalized[INDEX_MAX_KEYS];
                               2946                 :                :     bool        isnull[INDEX_MAX_KEYS];
                               2947                 :                :     bool        need_free[INDEX_MAX_KEYS];
                               2948                 :        1072141 :     bool        formnewtup = false;
                               2949                 :                :     IndexTuple  reformed;
                               2950                 :                :     int         i;
                               2951                 :                : 
                               2952                 :                :     /* Caller should only pass "logical" non-pivot tuples here */
 1509                          2953   [ +  -  -  + ]:        1072141 :     Assert(!BTreeTupleIsPosting(itup) && !BTreeTupleIsPivot(itup));
                               2954                 :                : 
                               2955                 :                :     /* Easy case: It's immediately clear that tuple has no varlena datums */
 1894                          2956         [ +  + ]:        1072141 :     if (!IndexTupleHasVarwidths(itup))
                               2957                 :        1072117 :         return itup;
                               2958                 :                : 
                               2959         [ +  + ]:             48 :     for (i = 0; i < tupleDescriptor->natts; i++)
                               2960                 :                :     {
                               2961                 :                :         Form_pg_attribute att;
                               2962                 :                : 
                               2963                 :             24 :         att = TupleDescAttr(tupleDescriptor, i);
                               2964                 :                : 
                               2965                 :                :         /* Assume untoasted/already normalized datum initially */
   22 akorotkov@postgresql     2966                 :             24 :         need_free[i] = false;
 1894 pg@bowt.ie               2967                 :             24 :         normalized[i] = index_getattr(itup, att->attnum,
                               2968                 :                :                                       tupleDescriptor,
                               2969                 :                :                                       &isnull[i]);
                               2970   [ +  -  +  -  :             24 :         if (att->attbyval || att->attlen != -1 || isnull[i])
                                              -  + ]
 1894 pg@bowt.ie               2971                 :UBC           0 :             continue;
                               2972                 :                : 
                               2973                 :                :         /*
                               2974                 :                :          * Callers always pass a tuple that could safely be inserted into the
                               2975                 :                :          * index without further processing, so an external varlena header
                               2976                 :                :          * should never be encountered here
                               2977                 :                :          */
 1894 pg@bowt.ie               2978         [ -  + ]:CBC          24 :         if (VARATT_IS_EXTERNAL(DatumGetPointer(normalized[i])))
 1894 pg@bowt.ie               2979         [ #  # ]:UBC           0 :             ereport(ERROR,
                               2980                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               2981                 :                :                      errmsg("external varlena datum in tuple that references heap row (%u,%u) in index \"%s\"",
                               2982                 :                :                             ItemPointerGetBlockNumber(&(itup->t_tid)),
                               2983                 :                :                             ItemPointerGetOffsetNumber(&(itup->t_tid)),
                               2984                 :                :                             RelationGetRelationName(state->rel))));
   22 akorotkov@postgresql     2985         [ +  + ]:CBC          24 :         else if (!VARATT_IS_COMPRESSED(DatumGetPointer(normalized[i])) &&
                               2986         [ +  + ]:             22 :                  VARSIZE(DatumGetPointer(normalized[i])) > TOAST_INDEX_TARGET &&
                               2987         [ +  + ]:             21 :                  (att->attstorage == TYPSTORAGE_EXTENDED ||
                               2988         [ -  + ]:             16 :                   att->attstorage == TYPSTORAGE_MAIN))
                               2989                 :                :         {
                               2990                 :                :             /*
                               2991                 :                :              * This value will be compressed by index_form_tuple() with the
                               2992                 :                :              * current storage settings.  We may be here because this tuple
                               2993                 :                :              * was formed with different storage settings.  So, force forming.
                               2994                 :                :              */
                               2995                 :              5 :             formnewtup = true;
                               2996                 :                :         }
 1894 pg@bowt.ie               2997         [ +  + ]:             19 :         else if (VARATT_IS_COMPRESSED(DatumGetPointer(normalized[i])))
                               2998                 :                :         {
                               2999                 :              2 :             formnewtup = true;
                               3000                 :              2 :             normalized[i] = PointerGetDatum(PG_DETOAST_DATUM(normalized[i]));
   22 akorotkov@postgresql     3001                 :              2 :             need_free[i] = true;
                               3002                 :                :         }
                               3003                 :                : 
                               3004                 :                :         /*
                               3005                 :                :          * Short tuples may have 1B or 4B header. Convert 4B header of short
                               3006                 :                :          * tuples to 1B
                               3007                 :                :          */
                               3008   [ +  +  +  + ]:             17 :         else if (VARATT_CAN_MAKE_SHORT(DatumGetPointer(normalized[i])))
                               3009                 :                :         {
                               3010                 :                :             /* convert to short varlena */
                               3011                 :              1 :             Size        len = VARATT_CONVERTED_SHORT_SIZE(DatumGetPointer(normalized[i]));
                               3012                 :              1 :             char       *data = palloc(len);
                               3013                 :                : 
                               3014                 :              1 :             SET_VARSIZE_SHORT(data, len);
                               3015                 :              1 :             memcpy(data + 1, VARDATA(DatumGetPointer(normalized[i])), len - 1);
                               3016                 :                : 
                               3017                 :              1 :             formnewtup = true;
                               3018                 :              1 :             normalized[i] = PointerGetDatum(data);
                               3019                 :              1 :             need_free[i] = true;
                               3020                 :                :         }
                               3021                 :                :     }
                               3022                 :                : 
                               3023                 :                :     /*
                               3024                 :                :      * Easier case: Tuple has varlena datums, none of which are compressed or
                               3025                 :                :      * short with 4B header
                               3026                 :                :      */
 1894 pg@bowt.ie               3027         [ +  + ]:             24 :     if (!formnewtup)
                               3028                 :             16 :         return itup;
                               3029                 :                : 
                               3030                 :                :     /*
                               3031                 :                :      * Hard case: Tuple had compressed varlena datums that necessitate
                               3032                 :                :      * creating normalized version of the tuple from uncompressed input datums
                               3033                 :                :      * (normalized input datums).  This is rather naive, but shouldn't be
                               3034                 :                :      * necessary too often.
                               3035                 :                :      *
                               3036                 :                :      * In the heap, tuples may contain short varlena datums with both 1B
                               3037                 :                :      * header and 4B headers.  But the corresponding index tuple should always
                               3038                 :                :      * have such varlena's with 1B headers.  So, if there is a short varlena
                               3039                 :                :      * with 4B header, we need to convert it for for fingerprinting.
                               3040                 :                :      *
                               3041                 :                :      * Note that we rely on deterministic index_form_tuple() TOAST compression
                               3042                 :                :      * of normalized input.
                               3043                 :                :      */
                               3044                 :              8 :     reformed = index_form_tuple(tupleDescriptor, normalized, isnull);
                               3045                 :              8 :     reformed->t_tid = itup->t_tid;
                               3046                 :                : 
                               3047                 :                :     /* Cannot leak memory here */
                               3048         [ +  + ]:             16 :     for (i = 0; i < tupleDescriptor->natts; i++)
   22 akorotkov@postgresql     3049         [ +  + ]:              8 :         if (need_free[i])
 1894 pg@bowt.ie               3050                 :              3 :             pfree(DatumGetPointer(normalized[i]));
                               3051                 :                : 
                               3052                 :              8 :     return reformed;
                               3053                 :                : }
                               3054                 :                : 
                               3055                 :                : /*
                               3056                 :                :  * Produce palloc()'d "plain" tuple for nth posting list entry/TID.
                               3057                 :                :  *
                               3058                 :                :  * In general, deduplication is not supposed to change the logical contents of
                               3059                 :                :  * an index.  Multiple index tuples are merged together into one equivalent
                               3060                 :                :  * posting list index tuple when convenient.
                               3061                 :                :  *
                               3062                 :                :  * heapallindexed verification must normalize-away this variation in
                               3063                 :                :  * representation by converting posting list tuples into two or more "plain"
                               3064                 :                :  * tuples.  Each tuple must be fingerprinted separately -- there must be one
                               3065                 :                :  * tuple for each corresponding Bloom filter probe during the heap scan.
                               3066                 :                :  *
                               3067                 :                :  * Note: Caller still needs to call bt_normalize_tuple() with returned tuple.
                               3068                 :                :  */
                               3069                 :                : static inline IndexTuple
 1509                          3070                 :          30546 : bt_posting_plain_tuple(IndexTuple itup, int n)
                               3071                 :                : {
                               3072         [ -  + ]:          30546 :     Assert(BTreeTupleIsPosting(itup));
                               3073                 :                : 
                               3074                 :                :     /* Returns non-posting-list tuple */
                               3075                 :          30546 :     return _bt_form_posting(itup, BTreeTupleGetPostingN(itup, n), 1);
                               3076                 :                : }
                               3077                 :                : 
                               3078                 :                : /*
                               3079                 :                :  * Search for itup in index, starting from fast root page.  itup must be a
                               3080                 :                :  * non-pivot tuple.  This is only supported with heapkeyspace indexes, since
                               3081                 :                :  * we rely on having fully unique keys to find a match with only a single
                               3082                 :                :  * visit to a leaf page, barring an interrupted page split, where we may have
                               3083                 :                :  * to move right.  (A concurrent page split is impossible because caller must
                               3084                 :                :  * be readonly caller.)
                               3085                 :                :  *
                               3086                 :                :  * This routine can detect very subtle transitive consistency issues across
                               3087                 :                :  * more than one level of the tree.  Leaf pages all have a high key (even the
                               3088                 :                :  * rightmost page has a conceptual positive infinity high key), but not a low
                               3089                 :                :  * key.  Their downlink in parent is a lower bound, which along with the high
                               3090                 :                :  * key is almost enough to detect every possible inconsistency.  A downlink
                               3091                 :                :  * separator key value won't always be available from parent, though, because
                               3092                 :                :  * the first items of internal pages are negative infinity items, truncated
                               3093                 :                :  * down to zero attributes during internal page splits.  While it's true that
                               3094                 :                :  * bt_child_check() and the high key check can detect most imaginable key
                               3095                 :                :  * space problems, there are remaining problems it won't detect with non-pivot
                               3096                 :                :  * tuples in cousin leaf pages.  Starting a search from the root for every
                               3097                 :                :  * existing leaf tuple detects small inconsistencies in upper levels of the
                               3098                 :                :  * tree that cannot be detected any other way.  (Besides all this, this is
                               3099                 :                :  * probably also useful as a direct test of the code used by index scans
                               3100                 :                :  * themselves.)
                               3101                 :                :  */
                               3102                 :                : static bool
 1852                          3103                 :         201098 : bt_rootdescend(BtreeCheckState *state, IndexTuple itup)
                               3104                 :                : {
                               3105                 :                :     BTScanInsert key;
                               3106                 :                :     BTStack     stack;
                               3107                 :                :     Buffer      lbuf;
                               3108                 :                :     bool        exists;
                               3109                 :                : 
  309                          3110                 :         201098 :     key = _bt_mkscankey(state->rel, itup);
 1852                          3111   [ +  -  -  + ]:         201098 :     Assert(key->heapkeyspace && key->scantid != NULL);
                               3112                 :                : 
                               3113                 :                :     /*
                               3114                 :                :      * Search from root.
                               3115                 :                :      *
                               3116                 :                :      * Ideally, we would arrange to only move right within _bt_search() when
                               3117                 :                :      * an interrupted page split is detected (i.e. when the incomplete split
                               3118                 :                :      * bit is found to be set), but for now we accept the possibility that
                               3119                 :                :      * that could conceal an inconsistency.
                               3120                 :                :      */
                               3121   [ +  -  -  + ]:         201098 :     Assert(state->readonly && state->rootdescend);
                               3122                 :         201098 :     exists = false;
  219 tmunro@postgresql.or     3123                 :GNC      201098 :     stack = _bt_search(state->rel, NULL, key, &lbuf, BT_READ);
                               3124                 :                : 
 1852 pg@bowt.ie               3125         [ +  - ]:CBC      201098 :     if (BufferIsValid(lbuf))
                               3126                 :                :     {
                               3127                 :                :         BTInsertStateData insertstate;
                               3128                 :                :         OffsetNumber offnum;
                               3129                 :                :         Page        page;
                               3130                 :                : 
                               3131                 :         201098 :         insertstate.itup = itup;
                               3132                 :         201098 :         insertstate.itemsz = MAXALIGN(IndexTupleSize(itup));
                               3133                 :         201098 :         insertstate.itup_key = key;
 1509                          3134                 :         201098 :         insertstate.postingoff = 0;
 1852                          3135                 :         201098 :         insertstate.bounds_valid = false;
                               3136                 :         201098 :         insertstate.buf = lbuf;
                               3137                 :                : 
                               3138                 :                :         /* Get matching tuple on leaf page */
                               3139                 :         201098 :         offnum = _bt_binsrch_insert(state->rel, &insertstate);
                               3140                 :                :         /* Compare first >= matching item on leaf page, if any */
                               3141                 :         201098 :         page = BufferGetPage(lbuf);
                               3142                 :                :         /* Should match on first heap TID when tuple has a posting list */
                               3143         [ +  - ]:         201098 :         if (offnum <= PageGetMaxOffsetNumber(page) &&
 1509                          3144   [ +  -  +  - ]:         402196 :             insertstate.postingoff <= 0 &&
 1852                          3145                 :         201098 :             _bt_compare(state->rel, key, page, offnum) == 0)
                               3146                 :         201098 :             exists = true;
                               3147                 :         201098 :         _bt_relbuf(state->rel, lbuf);
                               3148                 :                :     }
                               3149                 :                : 
                               3150                 :         201098 :     _bt_freestack(stack);
                               3151                 :         201098 :     pfree(key);
                               3152                 :                : 
                               3153                 :         201098 :     return exists;
                               3154                 :                : }
                               3155                 :                : 
                               3156                 :                : /*
                               3157                 :                :  * Is particular offset within page (whose special state is passed by caller)
                               3158                 :                :  * the page negative-infinity item?
                               3159                 :                :  *
                               3160                 :                :  * As noted in comments above _bt_compare(), there is special handling of the
                               3161                 :                :  * first data item as a "negative infinity" item.  The hard-coding within
                               3162                 :                :  * _bt_compare() makes comparing this item for the purposes of verification
                               3163                 :                :  * pointless at best, since the IndexTuple only contains a valid TID (a
                               3164                 :                :  * reference TID to child page).
                               3165                 :                :  */
                               3166                 :                : static inline bool
 2593 andres@anarazel.de       3167                 :        2619415 : offset_is_negative_infinity(BTPageOpaque opaque, OffsetNumber offset)
                               3168                 :                : {
                               3169                 :                :     /*
                               3170                 :                :      * For internal pages only, the first item after high key, if any, is
                               3171                 :                :      * negative infinity item.  Internal pages always have a negative infinity
                               3172                 :                :      * item, whereas leaf pages never have one.  This implies that negative
                               3173                 :                :      * infinity item is either first or second line item, or there is none
                               3174                 :                :      * within page.
                               3175                 :                :      *
                               3176                 :                :      * Negative infinity items are a special case among pivot tuples.  They
                               3177                 :                :      * always have zero attributes, while all other pivot tuples always have
                               3178                 :                :      * nkeyatts attributes.
                               3179                 :                :      *
                               3180                 :                :      * Right-most pages don't have a high key, but could be said to
                               3181                 :                :      * conceptually have a "positive infinity" high key.  Thus, there is a
                               3182                 :                :      * symmetry between down link items in parent pages, and high keys in
                               3183                 :                :      * children.  Together, they represent the part of the key space that
                               3184                 :                :      * belongs to each page in the index.  For example, all children of the
                               3185                 :                :      * root page will have negative infinity as a lower bound from root
                               3186                 :                :      * negative infinity downlink, and positive infinity as an upper bound
                               3187                 :                :      * (implicitly, from "imaginary" positive infinity high key in root).
                               3188                 :                :      */
                               3189   [ +  +  +  +  :        2619415 :     return !P_ISLEAF(opaque) && offset == P_FIRSTDATAKEY(opaque);
                                              +  + ]
                               3190                 :                : }
                               3191                 :                : 
                               3192                 :                : /*
                               3193                 :                :  * Does the invariant hold that the key is strictly less than a given upper
                               3194                 :                :  * bound offset item?
                               3195                 :                :  *
                               3196                 :                :  * Verifies line pointer on behalf of caller.
                               3197                 :                :  *
                               3198                 :                :  * If this function returns false, convention is that caller throws error due
                               3199                 :                :  * to corruption.
                               3200                 :                :  */
                               3201                 :                : static inline bool
 1852 pg@bowt.ie               3202                 :        2010043 : invariant_l_offset(BtreeCheckState *state, BTScanInsert key,
                               3203                 :                :                    OffsetNumber upperbound)
                               3204                 :                : {
                               3205                 :                :     ItemId      itemid;
                               3206                 :                :     int32       cmp;
                               3207                 :                : 
  128 pg@bowt.ie               3208   [ +  -  -  + ]:GNC     2010043 :     Assert(!key->nextkey && key->backward);
                               3209                 :                : 
                               3210                 :                :     /* Verify line pointer before checking tuple */
 1816 pg@bowt.ie               3211                 :CBC     2010043 :     itemid = PageGetItemIdCareful(state, state->targetblock, state->target,
                               3212                 :                :                                   upperbound);
                               3213                 :                :     /* pg_upgrade'd indexes may legally have equal sibling tuples */
 1852                          3214         [ -  + ]:        2010043 :     if (!key->heapkeyspace)
 1852 pg@bowt.ie               3215                 :UBC           0 :         return invariant_leq_offset(state, key, upperbound);
                               3216                 :                : 
 1852 pg@bowt.ie               3217                 :CBC     2010043 :     cmp = _bt_compare(state->rel, key, state->target, upperbound);
                               3218                 :                : 
                               3219                 :                :     /*
                               3220                 :                :      * _bt_compare() is capable of determining that a scankey with a
                               3221                 :                :      * filled-out attribute is greater than pivot tuples where the comparison
                               3222                 :                :      * is resolved at a truncated attribute (value of attribute in pivot is
                               3223                 :                :      * minus infinity).  However, it is not capable of determining that a
                               3224                 :                :      * scankey is _less than_ a tuple on the basis of a comparison resolved at
                               3225                 :                :      * _scankey_ minus infinity attribute.  Complete an extra step to simulate
                               3226                 :                :      * having minus infinity values for omitted scankey attribute(s).
                               3227                 :                :      */
                               3228         [ -  + ]:        2010043 :     if (cmp == 0)
                               3229                 :                :     {
                               3230                 :                :         BTPageOpaque topaque;
                               3231                 :                :         IndexTuple  ritup;
                               3232                 :                :         int         uppnkeyatts;
                               3233                 :                :         ItemPointer rheaptid;
                               3234                 :                :         bool        nonpivot;
                               3235                 :                : 
 1852 pg@bowt.ie               3236                 :UBC           0 :         ritup = (IndexTuple) PageGetItem(state->target, itemid);
  744 michael@paquier.xyz      3237                 :              0 :         topaque = BTPageGetOpaque(state->target);
 1852 pg@bowt.ie               3238   [ #  #  #  #  :              0 :         nonpivot = P_ISLEAF(topaque) && upperbound >= P_FIRSTDATAKEY(topaque);
                                              #  # ]
                               3239                 :                : 
                               3240                 :                :         /* Get number of keys + heap TID for item to the right */
                               3241   [ #  #  #  #  :              0 :         uppnkeyatts = BTreeTupleGetNKeyAtts(ritup, state->rel);
                                              #  # ]
                               3242                 :              0 :         rheaptid = BTreeTupleGetHeapTIDCareful(state, ritup, nonpivot);
                               3243                 :                : 
                               3244                 :                :         /* Heap TID is tiebreaker key attribute */
                               3245         [ #  # ]:              0 :         if (key->keysz == uppnkeyatts)
                               3246   [ #  #  #  # ]:              0 :             return key->scantid == NULL && rheaptid != NULL;
                               3247                 :                : 
                               3248                 :              0 :         return key->keysz < uppnkeyatts;
                               3249                 :                :     }
                               3250                 :                : 
 1852 pg@bowt.ie               3251                 :CBC     2010043 :     return cmp < 0;
                               3252                 :                : }
                               3253                 :                : 
                               3254                 :                : /*
                               3255                 :                :  * Does the invariant hold that the key is less than or equal to a given upper
                               3256                 :                :  * bound offset item?
                               3257                 :                :  *
                               3258                 :                :  * Caller should have verified that upperbound's line pointer is consistent
                               3259                 :                :  * using PageGetItemIdCareful() call.
                               3260                 :                :  *
                               3261                 :                :  * If this function returns false, convention is that caller throws error due
                               3262                 :                :  * to corruption.
                               3263                 :                :  */
                               3264                 :                : static inline bool
                               3265                 :        1850283 : invariant_leq_offset(BtreeCheckState *state, BTScanInsert key,
                               3266                 :                :                      OffsetNumber upperbound)
                               3267                 :                : {
                               3268                 :                :     int32       cmp;
                               3269                 :                : 
  128 pg@bowt.ie               3270   [ +  -  -  + ]:GNC     1850283 :     Assert(!key->nextkey && key->backward);
                               3271                 :                : 
 1852 pg@bowt.ie               3272                 :CBC     1850283 :     cmp = _bt_compare(state->rel, key, state->target, upperbound);
                               3273                 :                : 
 2593 andres@anarazel.de       3274                 :        1850283 :     return cmp <= 0;
                               3275                 :                : }
                               3276                 :                : 
                               3277                 :                : /*
                               3278                 :                :  * Does the invariant hold that the key is strictly greater than a given lower
                               3279                 :                :  * bound offset item?
                               3280                 :                :  *
                               3281                 :                :  * Caller should have verified that lowerbound's line pointer is consistent
                               3282                 :                :  * using PageGetItemIdCareful() call.
                               3283                 :                :  *
                               3284                 :                :  * If this function returns false, convention is that caller throws error due
                               3285                 :                :  * to corruption.
                               3286                 :                :  */
                               3287                 :                : static inline bool
 1852 pg@bowt.ie               3288                 :           6615 : invariant_g_offset(BtreeCheckState *state, BTScanInsert key,
                               3289                 :                :                    OffsetNumber lowerbound)
                               3290                 :                : {
                               3291                 :                :     int32       cmp;
                               3292                 :                : 
  128 pg@bowt.ie               3293   [ +  -  -  + ]:GNC        6615 :     Assert(!key->nextkey && key->backward);
                               3294                 :                : 
 1852 pg@bowt.ie               3295                 :CBC        6615 :     cmp = _bt_compare(state->rel, key, state->target, lowerbound);
                               3296                 :                : 
                               3297                 :                :     /* pg_upgrade'd indexes may legally have equal sibling tuples */
                               3298         [ -  + ]:           6615 :     if (!key->heapkeyspace)
 1852 pg@bowt.ie               3299                 :UBC           0 :         return cmp >= 0;
                               3300                 :                : 
                               3301                 :                :     /*
                               3302                 :                :      * No need to consider the possibility that scankey has attributes that we
                               3303                 :                :      * need to force to be interpreted as negative infinity.  _bt_compare() is
                               3304                 :                :      * able to determine that scankey is greater than negative infinity.  The
                               3305                 :                :      * distinction between "==" and "<" isn't interesting here, since
                               3306                 :                :      * corruption is indicated either way.
                               3307                 :                :      */
 1852 pg@bowt.ie               3308                 :CBC        6615 :     return cmp > 0;
                               3309                 :                : }
                               3310                 :                : 
                               3311                 :                : /*
                               3312                 :                :  * Does the invariant hold that the key is strictly less than a given upper
                               3313                 :                :  * bound offset item, with the offset relating to a caller-supplied page that
                               3314                 :                :  * is not the current target page?
                               3315                 :                :  *
                               3316                 :                :  * Caller's non-target page is a child page of the target, checked as part of
                               3317                 :                :  * checking a property of the target page (i.e. the key comes from the
                               3318                 :                :  * target).  Verifies line pointer on behalf of caller.
                               3319                 :                :  *
                               3320                 :                :  * If this function returns false, convention is that caller throws error due
                               3321                 :                :  * to corruption.
                               3322                 :                :  */
                               3323                 :                : static inline bool
                               3324                 :         598488 : invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key,
                               3325                 :                :                              BlockNumber nontargetblock, Page nontarget,
                               3326                 :                :                              OffsetNumber upperbound)
                               3327                 :                : {
                               3328                 :                :     ItemId      itemid;
                               3329                 :                :     int32       cmp;
                               3330                 :                : 
  128 pg@bowt.ie               3331   [ +  -  -  + ]:GNC      598488 :     Assert(!key->nextkey && key->backward);
                               3332                 :                : 
                               3333                 :                :     /* Verify line pointer before checking tuple */
 1816 pg@bowt.ie               3334                 :CBC      598488 :     itemid = PageGetItemIdCareful(state, nontargetblock, nontarget,
                               3335                 :                :                                   upperbound);
 1852                          3336                 :         598488 :     cmp = _bt_compare(state->rel, key, nontarget, upperbound);
                               3337                 :                : 
                               3338                 :                :     /* pg_upgrade'd indexes may legally have equal sibling tuples */
                               3339         [ -  + ]:         598488 :     if (!key->heapkeyspace)
 1852 pg@bowt.ie               3340                 :UBC           0 :         return cmp <= 0;
                               3341                 :                : 
                               3342                 :                :     /* See invariant_l_offset() for an explanation of this extra step */
 1852 pg@bowt.ie               3343         [ +  + ]:CBC      598488 :     if (cmp == 0)
                               3344                 :                :     {
                               3345                 :                :         IndexTuple  child;
                               3346                 :                :         int         uppnkeyatts;
                               3347                 :                :         ItemPointer childheaptid;
                               3348                 :                :         BTPageOpaque copaque;
                               3349                 :                :         bool        nonpivot;
                               3350                 :                : 
                               3351                 :           1860 :         child = (IndexTuple) PageGetItem(nontarget, itemid);
  744 michael@paquier.xyz      3352                 :           1860 :         copaque = BTPageGetOpaque(nontarget);
 1852 pg@bowt.ie               3353   [ +  -  +  +  :           1860 :         nonpivot = P_ISLEAF(copaque) && upperbound >= P_FIRSTDATAKEY(copaque);
                                              +  - ]
                               3354                 :                : 
                               3355                 :                :         /* Get number of keys + heap TID for child/non-target item */
                               3356   [ -  +  +  +  :           1860 :         uppnkeyatts = BTreeTupleGetNKeyAtts(child, state->rel);
                                              -  + ]
                               3357                 :           1860 :         childheaptid = BTreeTupleGetHeapTIDCareful(state, child, nonpivot);
                               3358                 :                : 
                               3359                 :                :         /* Heap TID is tiebreaker key attribute */
                               3360         [ +  - ]:           1860 :         if (key->keysz == uppnkeyatts)
                               3361   [ +  -  +  - ]:           1860 :             return key->scantid == NULL && childheaptid != NULL;
                               3362                 :                : 
 1852 pg@bowt.ie               3363                 :UBC           0 :         return key->keysz < uppnkeyatts;
                               3364                 :                :     }
                               3365                 :                : 
 1852 pg@bowt.ie               3366                 :CBC      596628 :     return cmp < 0;
                               3367                 :                : }
                               3368                 :                : 
                               3369                 :                : /*
                               3370                 :                :  * Given a block number of a B-Tree page, return page in palloc()'d memory.
                               3371                 :                :  * While at it, perform some basic checks of the page.
                               3372                 :                :  *
                               3373                 :                :  * There is never an attempt to get a consistent view of multiple pages using
                               3374                 :                :  * multiple concurrent buffer locks; in general, we only acquire a single pin
                               3375                 :                :  * and buffer lock at a time, which is often all that the nbtree code requires.
                               3376                 :                :  * (Actually, bt_recheck_sibling_links couples buffer locks, which is the only
                               3377                 :                :  * exception to this general rule.)
                               3378                 :                :  *
                               3379                 :                :  * Operating on a copy of the page is useful because it prevents control
                               3380                 :                :  * getting stuck in an uninterruptible state when an underlying operator class
                               3381                 :                :  * misbehaves.
                               3382                 :                :  */
                               3383                 :                : static Page
 2593 andres@anarazel.de       3384                 :          21587 : palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
                               3385                 :                : {
                               3386                 :                :     Buffer      buffer;
                               3387                 :                :     Page        page;
                               3388                 :                :     BTPageOpaque opaque;
                               3389                 :                :     OffsetNumber maxoffset;
                               3390                 :                : 
                               3391                 :          21587 :     page = palloc(BLCKSZ);
                               3392                 :                : 
                               3393                 :                :     /*
                               3394                 :                :      * We copy the page into local storage to avoid holding pin on the buffer
                               3395                 :                :      * longer than we must.
                               3396                 :                :      */
                               3397                 :          21587 :     buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum, RBM_NORMAL,
                               3398                 :                :                                 state->checkstrategy);
                               3399                 :          21575 :     LockBuffer(buffer, BT_READ);
                               3400                 :                : 
                               3401                 :                :     /*
                               3402                 :                :      * Perform the same basic sanity checking that nbtree itself performs for
                               3403                 :                :      * every page:
                               3404                 :                :      */
                               3405                 :          21575 :     _bt_checkpage(state->rel, buffer);
                               3406                 :                : 
                               3407                 :                :     /* Only use copy of page in palloc()'d memory */
                               3408                 :          21575 :     memcpy(page, BufferGetPage(buffer), BLCKSZ);
                               3409                 :          21575 :     UnlockReleaseBuffer(buffer);
                               3410                 :                : 
  744 michael@paquier.xyz      3411                 :          21575 :     opaque = BTPageGetOpaque(page);
                               3412                 :                : 
 2400 tgl@sss.pgh.pa.us        3413   [ +  +  -  + ]:          21575 :     if (P_ISMETA(opaque) && blocknum != BTREE_METAPAGE)
 2593 andres@anarazel.de       3414         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3415                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3416                 :                :                  errmsg("invalid meta page found at block %u in index \"%s\"",
                               3417                 :                :                         blocknum, RelationGetRelationName(state->rel))));
                               3418                 :                : 
                               3419                 :                :     /* Check page from block that ought to be meta page */
 2593 andres@anarazel.de       3420         [ +  + ]:CBC       21575 :     if (blocknum == BTREE_METAPAGE)
                               3421                 :                :     {
                               3422                 :           4005 :         BTMetaPageData *metad = BTPageGetMeta(page);
                               3423                 :                : 
 2400 tgl@sss.pgh.pa.us        3424         [ +  - ]:           4005 :         if (!P_ISMETA(opaque) ||
 2593 andres@anarazel.de       3425         [ -  + ]:           4005 :             metad->btm_magic != BTREE_MAGIC)
 2593 andres@anarazel.de       3426         [ #  # ]:UBC           0 :             ereport(ERROR,
                               3427                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               3428                 :                :                      errmsg("index \"%s\" meta page is corrupt",
                               3429                 :                :                             RelationGetRelationName(state->rel))));
                               3430                 :                : 
 2202 teodor@sigaev.ru         3431         [ +  - ]:CBC        4005 :         if (metad->btm_version < BTREE_MIN_VERSION ||
                               3432         [ -  + ]:           4005 :             metad->btm_version > BTREE_VERSION)
 2593 andres@anarazel.de       3433         [ #  # ]:UBC           0 :             ereport(ERROR,
                               3434                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               3435                 :                :                      errmsg("version mismatch in index \"%s\": file version %d, "
                               3436                 :                :                             "current version %d, minimum supported version %d",
                               3437                 :                :                             RelationGetRelationName(state->rel),
                               3438                 :                :                             metad->btm_version, BTREE_VERSION,
                               3439                 :                :                             BTREE_MIN_VERSION)));
                               3440                 :                : 
                               3441                 :                :         /* Finished with metapage checks */
 2181 teodor@sigaev.ru         3442                 :CBC        4005 :         return page;
                               3443                 :                :     }
                               3444                 :                : 
                               3445                 :                :     /*
                               3446                 :                :      * Deleted pages that still use the old 32-bit XID representation have no
                               3447                 :                :      * sane "level" field because they type pun the field, but all other pages
                               3448                 :                :      * (including pages deleted on Postgres 14+) have a valid value.
                               3449                 :                :      */
 1145 pg@bowt.ie               3450   [ -  +  -  - ]:          17570 :     if (!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque))
                               3451                 :                :     {
                               3452                 :                :         /* Okay, no reason not to trust btpo_level field from page */
                               3453                 :                : 
                               3454   [ +  +  -  + ]:          17570 :         if (P_ISLEAF(opaque) && opaque->btpo_level != 0)
 1145 pg@bowt.ie               3455         [ #  # ]:UBC           0 :             ereport(ERROR,
                               3456                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               3457                 :                :                      errmsg_internal("invalid leaf page level %u for block %u in index \"%s\"",
                               3458                 :                :                                      opaque->btpo_level, blocknum,
                               3459                 :                :                                      RelationGetRelationName(state->rel))));
                               3460                 :                : 
 1145 pg@bowt.ie               3461   [ +  +  -  + ]:CBC       17570 :         if (!P_ISLEAF(opaque) && opaque->btpo_level == 0)
 1145 pg@bowt.ie               3462         [ #  # ]:UBC           0 :             ereport(ERROR,
                               3463                 :                :                     (errcode(ERRCODE_INDEX_CORRUPTED),
                               3464                 :                :                      errmsg_internal("invalid internal page level 0 for block %u in index \"%s\"",
                               3465                 :                :                                      blocknum,
                               3466                 :                :                                      RelationGetRelationName(state->rel))));
                               3467                 :                :     }
                               3468                 :                : 
                               3469                 :                :     /*
                               3470                 :                :      * Sanity checks for number of items on page.
                               3471                 :                :      *
                               3472                 :                :      * As noted at the beginning of _bt_binsrch(), an internal page must have
                               3473                 :                :      * children, since there must always be a negative infinity downlink
                               3474                 :                :      * (there may also be a highkey).  In the case of non-rightmost leaf
                               3475                 :                :      * pages, there must be at least a highkey.  The exceptions are deleted
                               3476                 :                :      * pages, which contain no items.
                               3477                 :                :      *
                               3478                 :                :      * This is correct when pages are half-dead, since internal pages are
                               3479                 :                :      * never half-dead, and leaf pages must have a high key when half-dead
                               3480                 :                :      * (the rightmost page can never be deleted).  It's also correct with
                               3481                 :                :      * fully deleted pages: _bt_unlink_halfdead_page() doesn't change anything
                               3482                 :                :      * about the target page other than setting the page as fully dead, and
                               3483                 :                :      * setting its xact field.  In particular, it doesn't change the sibling
                               3484                 :                :      * links in the deletion target itself, since they're required when index
                               3485                 :                :      * scans land on the deletion target, and then need to move right (or need
                               3486                 :                :      * to move left, in the case of backward index scans).
                               3487                 :                :      */
 2181 teodor@sigaev.ru         3488                 :CBC       17570 :     maxoffset = PageGetMaxOffsetNumber(page);
                               3489         [ -  + ]:          17570 :     if (maxoffset > MaxIndexTuplesPerPage)
 2181 teodor@sigaev.ru         3490         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3491                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3492                 :                :                  errmsg("Number of items on block %u of index \"%s\" exceeds MaxIndexTuplesPerPage (%u)",
                               3493                 :                :                         blocknum, RelationGetRelationName(state->rel),
                               3494                 :                :                         MaxIndexTuplesPerPage)));
                               3495                 :                : 
 1431 akorotkov@postgresql     3496   [ +  +  +  -  :CBC       17570 :     if (!P_ISLEAF(opaque) && !P_ISDELETED(opaque) && maxoffset < P_FIRSTDATAKEY(opaque))
                                        +  +  -  + ]
 2181 teodor@sigaev.ru         3497         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3498                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3499                 :                :                  errmsg("internal block %u in index \"%s\" lacks high key and/or at least one downlink",
                               3500                 :                :                         blocknum, RelationGetRelationName(state->rel))));
                               3501                 :                : 
 1431 akorotkov@postgresql     3502   [ +  +  +  -  :CBC       17570 :     if (P_ISLEAF(opaque) && !P_ISDELETED(opaque) && !P_RIGHTMOST(opaque) && maxoffset < P_HIKEY)
                                        +  +  -  + ]
 2181 teodor@sigaev.ru         3503         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3504                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3505                 :                :                  errmsg("non-rightmost leaf block %u in index \"%s\" lacks high key item",
                               3506                 :                :                         blocknum, RelationGetRelationName(state->rel))));
                               3507                 :                : 
                               3508                 :                :     /*
                               3509                 :                :      * In general, internal pages are never marked half-dead, except on
                               3510                 :                :      * versions of Postgres prior to 9.4, where it can be valid transient
                               3511                 :                :      * state.  This state is nonetheless treated as corruption by VACUUM on
                               3512                 :                :      * from version 9.4 on, so do the same here.  See _bt_pagedel() for full
                               3513                 :                :      * details.
                               3514                 :                :      */
 2181 teodor@sigaev.ru         3515   [ +  +  -  + ]:CBC       17570 :     if (!P_ISLEAF(opaque) && P_ISHALFDEAD(opaque))
 2181 teodor@sigaev.ru         3516         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3517                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3518                 :                :                  errmsg("internal page block %u in index \"%s\" is half-dead",
                               3519                 :                :                         blocknum, RelationGetRelationName(state->rel)),
                               3520                 :                :                  errhint("This can be caused by an interrupted VACUUM in version 9.3 or older, before upgrade. Please REINDEX it.")));
                               3521                 :                : 
                               3522                 :                :     /*
                               3523                 :                :      * Check that internal pages have no garbage items, and that no page has
                               3524                 :                :      * an invalid combination of deletion-related page level flags
                               3525                 :                :      */
 2593 andres@anarazel.de       3526   [ +  +  -  + ]:CBC       17570 :     if (!P_ISLEAF(opaque) && P_HAS_GARBAGE(opaque))
 2593 andres@anarazel.de       3527         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3528                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3529                 :                :                  errmsg_internal("internal page block %u in index \"%s\" has garbage items",
                               3530                 :                :                                  blocknum, RelationGetRelationName(state->rel))));
                               3531                 :                : 
 1145 pg@bowt.ie               3532   [ -  +  -  - ]:CBC       17570 :     if (P_HAS_FULLXID(opaque) && !P_ISDELETED(opaque))
 1145 pg@bowt.ie               3533         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3534                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3535                 :                :                  errmsg_internal("full transaction id page flag appears in non-deleted block %u in index \"%s\"",
                               3536                 :                :                                  blocknum, RelationGetRelationName(state->rel))));
                               3537                 :                : 
 1145 pg@bowt.ie               3538   [ -  +  -  - ]:CBC       17570 :     if (P_ISDELETED(opaque) && P_ISHALFDEAD(opaque))
 1145 pg@bowt.ie               3539         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3540                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3541                 :                :                  errmsg_internal("deleted page block %u in index \"%s\" is half-dead",
                               3542                 :                :                                  blocknum, RelationGetRelationName(state->rel))));
                               3543                 :                : 
 2593 andres@anarazel.de       3544                 :CBC       17570 :     return page;
                               3545                 :                : }
                               3546                 :                : 
                               3547                 :                : /*
                               3548                 :                :  * _bt_mkscankey() wrapper that automatically prevents insertion scankey from
                               3549                 :                :  * being considered greater than the pivot tuple that its values originated
                               3550                 :                :  * from (or some other identical pivot tuple) in the common case where there
                               3551                 :                :  * are truncated/minus infinity attributes.  Without this extra step, there
                               3552                 :                :  * are forms of corruption that amcheck could theoretically fail to report.
                               3553                 :                :  *
                               3554                 :                :  * For example, invariant_g_offset() might miss a cross-page invariant failure
                               3555                 :                :  * on an internal level if the scankey built from the first item on the
                               3556                 :                :  * target's right sibling page happened to be equal to (not greater than) the
                               3557                 :                :  * last item on target page.  The !backward tiebreaker in _bt_compare() might
                               3558                 :                :  * otherwise cause amcheck to assume (rather than actually verify) that the
                               3559                 :                :  * scankey is greater.
                               3560                 :                :  */
                               3561                 :                : static inline BTScanInsert
  309 pg@bowt.ie               3562                 :        2025164 : bt_mkscankey_pivotsearch(Relation rel, IndexTuple itup)
                               3563                 :                : {
                               3564                 :                :     BTScanInsert skey;
                               3565                 :                : 
                               3566                 :        2025164 :     skey = _bt_mkscankey(rel, itup);
  128 pg@bowt.ie               3567                 :GNC     2025164 :     skey->backward = true;
                               3568                 :                : 
 1852 pg@bowt.ie               3569                 :CBC     2025164 :     return skey;
                               3570                 :                : }
                               3571                 :                : 
                               3572                 :                : /*
                               3573                 :                :  * PageGetItemId() wrapper that validates returned line pointer.
                               3574                 :                :  *
                               3575                 :                :  * Buffer page/page item access macros generally trust that line pointers are
                               3576                 :                :  * not corrupt, which might cause problems for verification itself.  For
                               3577                 :                :  * example, there is no bounds checking in PageGetItem().  Passing it a
                               3578                 :                :  * corrupt line pointer can cause it to return a tuple/pointer that is unsafe
                               3579                 :                :  * to dereference.
                               3580                 :                :  *
                               3581                 :                :  * Validating line pointers before tuples avoids undefined behavior and
                               3582                 :                :  * assertion failures with corrupt indexes, making the verification process
                               3583                 :                :  * more robust and predictable.
                               3584                 :                :  */
                               3585                 :                : static ItemId
 1816                          3586                 :        4650665 : PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page,
                               3587                 :                :                      OffsetNumber offset)
                               3588                 :                : {
                               3589                 :        4650665 :     ItemId      itemid = PageGetItemId(page, offset);
                               3590                 :                : 
                               3591         [ -  + ]:        4650665 :     if (ItemIdGetOffset(itemid) + ItemIdGetLength(itemid) >
                               3592                 :                :         BLCKSZ - MAXALIGN(sizeof(BTPageOpaqueData)))
 1816 pg@bowt.ie               3593         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3594                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3595                 :                :                  errmsg("line pointer points past end of tuple space in index \"%s\"",
                               3596                 :                :                         RelationGetRelationName(state->rel)),
                               3597                 :                :                  errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.",
                               3598                 :                :                                     block, offset, ItemIdGetOffset(itemid),
                               3599                 :                :                                     ItemIdGetLength(itemid),
                               3600                 :                :                                     ItemIdGetFlags(itemid))));
                               3601                 :                : 
                               3602                 :                :     /*
                               3603                 :                :      * Verify that line pointer isn't LP_REDIRECT or LP_UNUSED, since nbtree
                               3604                 :                :      * never uses either.  Verify that line pointer has storage, too, since
                               3605                 :                :      * even LP_DEAD items should within nbtree.
                               3606                 :                :      */
 1816 pg@bowt.ie               3607   [ +  -  +  - ]:CBC     4650665 :     if (ItemIdIsRedirected(itemid) || !ItemIdIsUsed(itemid) ||
                               3608         [ -  + ]:        4650665 :         ItemIdGetLength(itemid) == 0)
 1816 pg@bowt.ie               3609         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3610                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3611                 :                :                  errmsg("invalid line pointer storage in index \"%s\"",
                               3612                 :                :                         RelationGetRelationName(state->rel)),
                               3613                 :                :                  errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.",
                               3614                 :                :                                     block, offset, ItemIdGetOffset(itemid),
                               3615                 :                :                                     ItemIdGetLength(itemid),
                               3616                 :                :                                     ItemIdGetFlags(itemid))));
                               3617                 :                : 
 1816 pg@bowt.ie               3618                 :CBC     4650665 :     return itemid;
                               3619                 :                : }
                               3620                 :                : 
                               3621                 :                : /*
                               3622                 :                :  * BTreeTupleGetHeapTID() wrapper that enforces that a heap TID is present in
                               3623                 :                :  * cases where that is mandatory (i.e. for non-pivot tuples)
                               3624                 :                :  */
                               3625                 :                : static inline ItemPointer
 1852                          3626                 :           1860 : BTreeTupleGetHeapTIDCareful(BtreeCheckState *state, IndexTuple itup,
                               3627                 :                :                             bool nonpivot)
                               3628                 :                : {
                               3629                 :                :     ItemPointer htid;
                               3630                 :                : 
                               3631                 :                :     /*
                               3632                 :                :      * Caller determines whether this is supposed to be a pivot or non-pivot
                               3633                 :                :      * tuple using page type and item offset number.  Verify that tuple
                               3634                 :                :      * metadata agrees with this.
                               3635                 :                :      */
 1509                          3636         [ -  + ]:           1860 :     Assert(state->heapkeyspace);
                               3637   [ -  +  -  - ]:           1860 :     if (BTreeTupleIsPivot(itup) && nonpivot)
 1509 pg@bowt.ie               3638         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3639                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3640                 :                :                  errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected pivot tuple",
                               3641                 :                :                                  state->targetblock,
                               3642                 :                :                                  RelationGetRelationName(state->rel))));
                               3643                 :                : 
 1509 pg@bowt.ie               3644   [ +  -  -  + ]:CBC        1860 :     if (!BTreeTupleIsPivot(itup) && !nonpivot)
 1509 pg@bowt.ie               3645         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3646                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3647                 :                :                  errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected non-pivot tuple",
                               3648                 :                :                                  state->targetblock,
                               3649                 :                :                                  RelationGetRelationName(state->rel))));
                               3650                 :                : 
 1509 pg@bowt.ie               3651                 :CBC        1860 :     htid = BTreeTupleGetHeapTID(itup);
                               3652   [ -  +  -  - ]:           1860 :     if (!ItemPointerIsValid(htid) && nonpivot)
 1852 pg@bowt.ie               3653         [ #  # ]:UBC           0 :         ereport(ERROR,
                               3654                 :                :                 (errcode(ERRCODE_INDEX_CORRUPTED),
                               3655                 :                :                  errmsg("block %u or its right sibling block or child block in index \"%s\" contains non-pivot tuple that lacks a heap TID",
                               3656                 :                :                         state->targetblock,
                               3657                 :                :                         RelationGetRelationName(state->rel))));
                               3658                 :                : 
 1509 pg@bowt.ie               3659                 :CBC        1860 :     return htid;
                               3660                 :                : }
                               3661                 :                : 
                               3662                 :                : /*
                               3663                 :                :  * Return the "pointed to" TID for itup, which is used to generate a
                               3664                 :                :  * descriptive error message.  itup must be a "data item" tuple (it wouldn't
                               3665                 :                :  * make much sense to call here with a high key tuple, since there won't be a
                               3666                 :                :  * valid downlink/block number to display).
                               3667                 :                :  *
                               3668                 :                :  * Returns either a heap TID (which will be the first heap TID in posting list
                               3669                 :                :  * if itup is posting list tuple), or a TID that contains downlink block
                               3670                 :                :  * number, plus some encoded metadata (e.g., the number of attributes present
                               3671                 :                :  * in itup).
                               3672                 :                :  */
                               3673                 :                : static inline ItemPointer
 1509 pg@bowt.ie               3674                 :GBC           6 : BTreeTupleGetPointsToTID(IndexTuple itup)
                               3675                 :                : {
                               3676                 :                :     /*
                               3677                 :                :      * Rely on the assumption that !heapkeyspace internal page data items will
                               3678                 :                :      * correctly return TID with downlink here -- BTreeTupleGetHeapTID() won't
                               3679                 :                :      * recognize it as a pivot tuple, but everything still works out because
                               3680                 :                :      * the t_tid field is still returned
                               3681                 :                :      */
                               3682         [ +  + ]:              6 :     if (!BTreeTupleIsPivot(itup))
                               3683                 :              4 :         return BTreeTupleGetHeapTID(itup);
                               3684                 :                : 
                               3685                 :                :     /* Pivot tuple returns TID with downlink block (heapkeyspace variant) */
                               3686                 :              2 :     return &itup->t_tid;
                               3687                 :                : }
        

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