LCOV - code coverage report
Current view: top level - contrib/amcheck - verify_nbtree.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 572 787 72.7 %
Date: 2024-11-21 08:14:44 Functions: 33 35 94.3 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14