LCOV - code coverage report
Current view: top level - contrib/amcheck - verify_nbtree.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 74.9 % 742 556
Test Date: 2026-10-16 23:15:56 Functions: 97.0 % 33 32
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 54.0 % 772 417

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

Generated by: LCOV version 2.0-1