LCOV - differential code coverage report
Current view: top level - contrib/amcheck - verify_nbtree.c (source / functions) Coverage Total Hit LBC UIC UBC GBC GIC GNC CBC EUB ECB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 69.3 % 655 454 22 130 49 4 307 7 136 148 295 1
Current Date: 2023-04-08 17:13:01 Functions: 90.3 % 31 28 3 27 1 3 28
Baseline: 15 Line coverage date bins:
Baseline Date: 2023-04-08 15:09:40 [..60] days: 100.0 % 7 7 7
Legend: Lines: hit not hit (240..) days: 69.0 % 648 447 22 130 49 4 307 136 147 295
Function coverage date bins:
[..60] days: 100.0 % 1 1 1
(240..) days: 44.3 % 61 27 3 27 3 28

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

Generated by: LCOV version v1.16-55-g56c0a2a