PostgreSQL Source Code  git master
verify_nbtree.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/table.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "commands/tablecmds.h"
#include "lib/bloomfilter.h"
#include "miscadmin.h"
#include "storage/lmgr.h"
#include "storage/smgr.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
Include dependency graph for verify_nbtree.c:

Go to the source code of this file.

Data Structures

struct  BtreeCheckState
 
struct  BtreeLevel
 

Macros

#define InvalidBtreeLevel   ((uint32) InvalidBlockNumber)
 
#define BTreeTupleGetNKeyAtts(itup, rel)   Min(IndexRelationGetNumberOfKeyAttributes(rel), BTreeTupleGetNAtts(itup, rel))
 

Typedefs

typedef struct BtreeCheckState BtreeCheckState
 
typedef struct BtreeLevel BtreeLevel
 

Functions

 PG_FUNCTION_INFO_V1 (bt_index_check)
 
 PG_FUNCTION_INFO_V1 (bt_index_parent_check)
 
static void bt_index_check_internal (Oid indrelid, bool parentcheck, bool heapallindexed, bool rootdescend)
 
static void btree_index_checkable (Relation rel)
 
static bool btree_index_mainfork_expected (Relation rel)
 
static void bt_check_every_level (Relation rel, Relation heaprel, bool heapkeyspace, bool readonly, bool heapallindexed, bool rootdescend)
 
static BtreeLevel bt_check_level_from_leftmost (BtreeCheckState *state, BtreeLevel level)
 
static void bt_recheck_sibling_links (BtreeCheckState *state, BlockNumber btpo_prev_from_target, BlockNumber leftcurrent)
 
static void bt_target_page_check (BtreeCheckState *state)
 
static BTScanInsert bt_right_page_check_scankey (BtreeCheckState *state)
 
static void bt_child_check (BtreeCheckState *state, BTScanInsert targetkey, OffsetNumber downlinkoffnum)
 
static void bt_child_highkey_check (BtreeCheckState *state, OffsetNumber target_downlinkoffnum, Page loaded_child, uint32 target_level)
 
static void bt_downlink_missing_check (BtreeCheckState *state, bool rightsplit, BlockNumber targetblock, Page target)
 
static void bt_tuple_present_callback (Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *checkstate)
 
static IndexTuple bt_normalize_tuple (BtreeCheckState *state, IndexTuple itup)
 
static IndexTuple bt_posting_plain_tuple (IndexTuple itup, int n)
 
static bool bt_rootdescend (BtreeCheckState *state, IndexTuple itup)
 
static bool offset_is_negative_infinity (BTPageOpaque opaque, OffsetNumber offset)
 
static bool invariant_l_offset (BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound)
 
static bool invariant_leq_offset (BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound)
 
static bool invariant_g_offset (BtreeCheckState *state, BTScanInsert key, OffsetNumber lowerbound)
 
static bool invariant_l_nontarget_offset (BtreeCheckState *state, BTScanInsert key, BlockNumber nontargetblock, Page nontarget, OffsetNumber upperbound)
 
static Page palloc_btree_page (BtreeCheckState *state, BlockNumber blocknum)
 
static BTScanInsert bt_mkscankey_pivotsearch (Relation rel, IndexTuple itup)
 
static ItemId PageGetItemIdCareful (BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
 
static ItemPointer BTreeTupleGetHeapTIDCareful (BtreeCheckState *state, IndexTuple itup, bool nonpivot)
 
static ItemPointer BTreeTupleGetPointsToTID (IndexTuple itup)
 
Datum bt_index_check (PG_FUNCTION_ARGS)
 
Datum bt_index_parent_check (PG_FUNCTION_ARGS)
 
static bool bt_pivot_tuple_identical (bool heapkeyspace, IndexTuple itup1, IndexTuple itup2)
 

Variables

 PG_MODULE_MAGIC
 

Macro Definition Documentation

◆ BTreeTupleGetNKeyAtts

#define BTreeTupleGetNKeyAtts (   itup,
  rel 
)    Min(IndexRelationGetNumberOfKeyAttributes(rel), BTreeTupleGetNAtts(itup, rel))

Definition at line 50 of file verify_nbtree.c.

Referenced by invariant_l_nontarget_offset(), and invariant_l_offset().

◆ InvalidBtreeLevel

#define InvalidBtreeLevel   ((uint32) InvalidBlockNumber)

Definition at line 49 of file verify_nbtree.c.

Referenced by bt_check_every_level(), and bt_check_level_from_leftmost().

Typedef Documentation

◆ BtreeCheckState

◆ BtreeLevel

typedef struct BtreeLevel BtreeLevel

Function Documentation

◆ bt_check_every_level()

static void bt_check_every_level ( Relation  rel,
Relation  heaprel,
bool  heapkeyspace,
bool  readonly,
bool  heapallindexed,
bool  rootdescend 
)
static

Definition at line 419 of file verify_nbtree.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, BAS_BULKREAD, bloom_create(), bloom_free(), bloom_prop_bits_set(), bt_check_level_from_leftmost(), bt_tuple_present_callback(), BTMetaPageData::btm_fastlevel, BTMetaPageData::btm_fastroot, BTMetaPageData::btm_level, BTMetaPageData::btm_root, BTPageGetMeta, BTREE_METAPAGE, BuildIndexInfo(), BtreeCheckState::checkstrategy, CurrentMemoryContext, DEBUG1, elog, ereport, errcode(), errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, BtreeCheckState::filter, GetAccessStrategy(), GetTransactionSnapshot(), BtreeCheckState::heapallindexed, BtreeCheckState::heapkeyspace, BtreeCheckState::heaprel, HeapTupleHeaderGetXmin, BtreeCheckState::heaptuplespresent, IndexInfo::ii_Concurrent, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Unique, INT64_FORMAT, InvalidBlockNumber, InvalidBtreeLevel, IsolationUsesXactSnapshot, BtreeLevel::istruerootlevel, BtreeLevel::leftmost, BtreeLevel::level, maintenance_work_mem, Max, MaxTIDsPerBTreePage, MemoryContextDelete(), P_NONE, palloc0(), palloc_btree_page(), random(), RelationData::rd_index, RelationData::rd_indextuple, RelationData::rd_rel, BtreeCheckState::readonly, RecentXmin, RegisterSnapshot(), BtreeCheckState::rel, RelationGetNumberOfBlocks, RelationGetRelationName, BtreeCheckState::rootdescend, SnapshotAny, HeapTupleData::t_data, table_beginscan_strat(), table_index_build_scan(), BtreeCheckState::targetcontext, TransactionIdIsValid, TransactionIdPrecedes(), UnregisterSnapshot(), and SnapshotData::xmin.

Referenced by bt_index_check_internal().

421 {
423  Page metapage;
424  BTMetaPageData *metad;
425  uint32 previouslevel;
426  BtreeLevel current;
427  Snapshot snapshot = SnapshotAny;
428 
429  if (!readonly)
430  elog(DEBUG1, "verifying consistency of tree structure for index \"%s\"",
432  else
433  elog(DEBUG1, "verifying consistency of tree structure for index \"%s\" with cross-level checks",
435 
436  /*
437  * This assertion matches the one in index_getnext_tid(). See page
438  * recycling/"visible to everyone" notes in nbtree README.
439  */
441 
442  /*
443  * Initialize state for entire verification operation
444  */
445  state = palloc0(sizeof(BtreeCheckState));
446  state->rel = rel;
447  state->heaprel = heaprel;
448  state->heapkeyspace = heapkeyspace;
449  state->readonly = readonly;
450  state->heapallindexed = heapallindexed;
451  state->rootdescend = rootdescend;
452 
453  if (state->heapallindexed)
454  {
455  int64 total_pages;
456  int64 total_elems;
457  uint64 seed;
458 
459  /*
460  * Size Bloom filter based on estimated number of tuples in index,
461  * while conservatively assuming that each block must contain at least
462  * MaxTIDsPerBTreePage / 3 "plain" tuples -- see
463  * bt_posting_plain_tuple() for definition, and details of how posting
464  * list tuples are handled.
465  */
466  total_pages = RelationGetNumberOfBlocks(rel);
467  total_elems = Max(total_pages * (MaxTIDsPerBTreePage / 3),
468  (int64) state->rel->rd_rel->reltuples);
469  /* Random seed relies on backend srandom() call to avoid repetition */
470  seed = random();
471  /* Create Bloom filter to fingerprint index */
472  state->filter = bloom_create(total_elems, maintenance_work_mem, seed);
473  state->heaptuplespresent = 0;
474 
475  /*
476  * Register our own snapshot in !readonly case, rather than asking
477  * table_index_build_scan() to do this for us later. This needs to
478  * happen before index fingerprinting begins, so we can later be
479  * certain that index fingerprinting should have reached all tuples
480  * returned by table_index_build_scan().
481  */
482  if (!state->readonly)
483  {
485 
486  /*
487  * GetTransactionSnapshot() always acquires a new MVCC snapshot in
488  * READ COMMITTED mode. A new snapshot is guaranteed to have all
489  * the entries it requires in the index.
490  *
491  * We must defend against the possibility that an old xact
492  * snapshot was returned at higher isolation levels when that
493  * snapshot is not safe for index scans of the target index. This
494  * is possible when the snapshot sees tuples that are before the
495  * index's indcheckxmin horizon. Throwing an error here should be
496  * very rare. It doesn't seem worth using a secondary snapshot to
497  * avoid this.
498  */
499  if (IsolationUsesXactSnapshot() && rel->rd_index->indcheckxmin &&
501  snapshot->xmin))
502  ereport(ERROR,
503  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
504  errmsg("index \"%s\" cannot be verified using transaction snapshot",
505  RelationGetRelationName(rel))));
506  }
507  }
508 
509  Assert(!state->rootdescend || state->readonly);
510  if (state->rootdescend && !state->heapkeyspace)
511  ereport(ERROR,
512  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
513  errmsg("cannot verify that tuples from index \"%s\" can each be found by an independent index search",
515  errhint("Only B-Tree version 4 indexes support rootdescend verification.")));
516 
517  /* Create context for page */
519  "amcheck context",
522 
523  /* Get true root block from meta-page */
524  metapage = palloc_btree_page(state, BTREE_METAPAGE);
525  metad = BTPageGetMeta(metapage);
526 
527  /*
528  * Certain deletion patterns can result in "skinny" B-Tree indexes, where
529  * the fast root and true root differ.
530  *
531  * Start from the true root, not the fast root, unlike conventional index
532  * scans. This approach is more thorough, and removes the risk of
533  * following a stale fast root from the meta page.
534  */
535  if (metad->btm_fastroot != metad->btm_root)
536  ereport(DEBUG1,
537  (errcode(ERRCODE_NO_DATA),
538  errmsg_internal("harmless fast root mismatch in index %s",
540  errdetail_internal("Fast root block %u (level %u) differs from true root block %u (level %u).",
541  metad->btm_fastroot, metad->btm_fastlevel,
542  metad->btm_root, metad->btm_level)));
543 
544  /*
545  * Starting at the root, verify every level. Move left to right, top to
546  * bottom. Note that there may be no pages other than the meta page (meta
547  * page can indicate that root is P_NONE when the index is totally empty).
548  */
549  previouslevel = InvalidBtreeLevel;
550  current.level = metad->btm_level;
551  current.leftmost = metad->btm_root;
552  current.istruerootlevel = true;
553  while (current.leftmost != P_NONE)
554  {
555  /*
556  * Verify this level, and get left most page for next level down, if
557  * not at leaf level
558  */
559  current = bt_check_level_from_leftmost(state, current);
560 
561  if (current.leftmost == InvalidBlockNumber)
562  ereport(ERROR,
563  (errcode(ERRCODE_INDEX_CORRUPTED),
564  errmsg("index \"%s\" has no valid pages on level below %u or first level",
565  RelationGetRelationName(rel), previouslevel)));
566 
567  previouslevel = current.level;
568  }
569 
570  /*
571  * * Check whether heap contains unindexed/malformed tuples *
572  */
573  if (state->heapallindexed)
574  {
575  IndexInfo *indexinfo = BuildIndexInfo(state->rel);
576  TableScanDesc scan;
577 
578  /*
579  * Create our own scan for table_index_build_scan(), rather than
580  * getting it to do so for us. This is required so that we can
581  * actually use the MVCC snapshot registered earlier in !readonly
582  * case.
583  *
584  * Note that table_index_build_scan() calls heap_endscan() for us.
585  */
586  scan = table_beginscan_strat(state->heaprel, /* relation */
587  snapshot, /* snapshot */
588  0, /* number of keys */
589  NULL, /* scan key */
590  true, /* buffer access strategy OK */
591  true); /* syncscan OK? */
592 
593  /*
594  * Scan will behave as the first scan of a CREATE INDEX CONCURRENTLY
595  * behaves in !readonly case.
596  *
597  * It's okay that we don't actually use the same lock strength for the
598  * heap relation as any other ii_Concurrent caller would in !readonly
599  * case. We have no reason to care about a concurrent VACUUM
600  * operation, since there isn't going to be a second scan of the heap
601  * that needs to be sure that there was no concurrent recycling of
602  * TIDs.
603  */
604  indexinfo->ii_Concurrent = !state->readonly;
605 
606  /*
607  * Don't wait for uncommitted tuple xact commit/abort when index is a
608  * unique index on a catalog (or an index used by an exclusion
609  * constraint). This could otherwise happen in the readonly case.
610  */
611  indexinfo->ii_Unique = false;
612  indexinfo->ii_ExclusionOps = NULL;
613  indexinfo->ii_ExclusionProcs = NULL;
614  indexinfo->ii_ExclusionStrats = NULL;
615 
616  elog(DEBUG1, "verifying that tuples from index \"%s\" are present in \"%s\"",
619 
620  table_index_build_scan(state->heaprel, state->rel, indexinfo, true, false,
621  bt_tuple_present_callback, (void *) state, scan);
622 
623  ereport(DEBUG1,
624  (errmsg_internal("finished verifying presence of " INT64_FORMAT " tuples from table \"%s\" with bitset %.2f%% set",
626  100.0 * bloom_prop_bits_set(state->filter))));
627 
628  if (snapshot != SnapshotAny)
629  UnregisterSnapshot(snapshot);
630 
631  bloom_free(state->filter);
632  }
633 
634  /* Be tidy: */
636 }
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:542
bloom_filter * bloom_create(int64 total_elems, int bloom_work_mem, uint64 seed)
Definition: bloomfilter.c:88
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
#define AllocSetContextCreate
Definition: memutils.h:170
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1162
static BtreeLevel bt_check_level_from_leftmost(BtreeCheckState *state, BtreeLevel level)
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:810
static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
uint32 level
long random(void)
Definition: random.c:22
static void bt_tuple_present_callback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *checkstate)
#define IsolationUsesXactSnapshot()
Definition: xact.h:51
#define P_NONE
Definition: nbtree.h:211
Oid * ii_ExclusionProcs
Definition: execnodes.h:165
int errcode(int sqlerrcode)
Definition: elog.c:704
TransactionId RecentXmin
Definition: snapmgr.c:113
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2532
#define MaxTIDsPerBTreePage
Definition: nbtree.h:184
Form_pg_class rd_rel
Definition: rel.h:110
BufferAccessStrategy checkstrategy
Definition: verify_nbtree.c:84
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:878
bloom_filter * filter
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
struct HeapTupleData * rd_indextuple
Definition: rel.h:177
HeapTupleHeader t_data
Definition: htup.h:68
Form_pg_index rd_index
Definition: rel.h:175
BlockNumber btm_fastroot
Definition: nbtree.h:107
#define ERROR
Definition: elog.h:45
static double table_index_build_scan(Relation table_rel, Relation index_rel, struct IndexInfo *index_info, bool allow_sync, bool progress, IndexBuildCallback callback, void *callback_state, TableScanDesc scan)
Definition: tableam.h:1658
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define BTPageGetMeta(p)
Definition: nbtree.h:119
BlockNumber leftmost
#define RelationGetRelationName(relation)
Definition: rel.h:491
unsigned int uint32
Definition: c.h:441
TransactionId xmin
Definition: snapshot.h:157
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
#define BTREE_METAPAGE
Definition: nbtree.h:146
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:852
void bloom_free(bloom_filter *filter)
Definition: bloomfilter.c:127
Relation heaprel
Definition: verify_nbtree.c:72
uint32 btm_fastlevel
Definition: nbtree.h:108
void * palloc0(Size size)
Definition: mcxt.c:981
BlockNumber btm_root
Definition: nbtree.h:105
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define ereport(elevel,...)
Definition: elog.h:155
int maintenance_work_mem
Definition: globals.c:124
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
bool ii_Unique
Definition: execnodes.h:171
#define Max(x, y)
Definition: c.h:980
#define Assert(condition)
Definition: c.h:804
Definition: regguts.h:317
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
#define InvalidBlockNumber
Definition: block.h:33
bool ii_Concurrent
Definition: execnodes.h:173
#define INT64_FORMAT
Definition: c.h:483
#define SnapshotAny
Definition: snapmgr.h:68
double bloom_prop_bits_set(bloom_filter *filter)
Definition: bloomfilter.c:188
Oid * ii_ExclusionOps
Definition: execnodes.h:164
int errmsg(const char *fmt,...)
Definition: elog.c:915
uint32 btm_level
Definition: nbtree.h:106
#define elog(elevel,...)
Definition: elog.h:228
bool istruerootlevel
#define InvalidBtreeLevel
Definition: verify_nbtree.c:49
#define TransactionIdIsValid(xid)
Definition: transam.h:41
uint16 * ii_ExclusionStrats
Definition: execnodes.h:166
MemoryContext targetcontext
Definition: verify_nbtree.c:82
Pointer Page
Definition: bufpage.h:78

◆ bt_check_level_from_leftmost()

static BtreeLevel bt_check_level_from_leftmost ( BtreeCheckState state,
BtreeLevel  level 
)
static

Definition at line 657 of file verify_nbtree.c.

References Assert, bt_recheck_sibling_links(), bt_target_page_check(), BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_next, BTPageOpaqueData::btpo_prev, BTreeTupleGetDownLink(), CHECK_FOR_INTERRUPTS, DEBUG1, elog, ereport, errcode(), errdetail_internal(), errmsg(), errmsg_internal(), ERROR, IndexTupleSize, InvalidBlockNumber, InvalidBtreeLevel, BtreeLevel::istruerootlevel, BtreeLevel::leftmost, BtreeLevel::level, BtreeCheckState::lowkey, MemoryContextAlloc(), MemoryContextReset(), MemoryContextSwitchTo(), P_FIRSTDATAKEY, P_HIKEY, P_IGNORE, P_ISDELETED, P_ISLEAF, P_ISROOT, P_LEFTMOST, P_NONE, P_RIGHTMOST, PageGetItem, PageGetItemIdCareful(), PageGetLSN, PageGetSpecialPointer, palloc_btree_page(), pfree(), BtreeCheckState::previncompletesplit, BtreeCheckState::prevrightlink, BtreeCheckState::readonly, BtreeCheckState::rel, RelationGetRelationName, BtreeCheckState::target, BtreeCheckState::targetblock, BtreeCheckState::targetcontext, and BtreeCheckState::targetlsn.

Referenced by bt_check_every_level().

658 {
659  /* State to establish early, concerning entire level */
660  BTPageOpaque opaque;
661  MemoryContext oldcontext;
662  BtreeLevel nextleveldown;
663 
664  /* Variables for iterating across level using right links */
665  BlockNumber leftcurrent = P_NONE;
666  BlockNumber current = level.leftmost;
667 
668  /* Initialize return state */
669  nextleveldown.leftmost = InvalidBlockNumber;
670  nextleveldown.level = InvalidBtreeLevel;
671  nextleveldown.istruerootlevel = false;
672 
673  /* Use page-level context for duration of this call */
674  oldcontext = MemoryContextSwitchTo(state->targetcontext);
675 
676  elog(DEBUG1, "verifying level %u%s", level.level,
677  level.istruerootlevel ?
678  " (true root level)" : level.level == 0 ? " (leaf level)" : "");
679 
681  state->previncompletesplit = false;
682 
683  do
684  {
685  /* Don't rely on CHECK_FOR_INTERRUPTS() calls at lower level */
687 
688  /* Initialize state for this iteration */
689  state->targetblock = current;
690  state->target = palloc_btree_page(state, state->targetblock);
691  state->targetlsn = PageGetLSN(state->target);
692 
693  opaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
694 
695  if (P_IGNORE(opaque))
696  {
697  /*
698  * Since there cannot be a concurrent VACUUM operation in readonly
699  * mode, and since a page has no links within other pages
700  * (siblings and parent) once it is marked fully deleted, it
701  * should be impossible to land on a fully deleted page in
702  * readonly mode. See bt_child_check() for further details.
703  *
704  * The bt_child_check() P_ISDELETED() check is repeated here so
705  * that pages that are only reachable through sibling links get
706  * checked.
707  */
708  if (state->readonly && P_ISDELETED(opaque))
709  ereport(ERROR,
710  (errcode(ERRCODE_INDEX_CORRUPTED),
711  errmsg("downlink or sibling link points to deleted block in index \"%s\"",
712  RelationGetRelationName(state->rel)),
713  errdetail_internal("Block=%u left block=%u left link from block=%u.",
714  current, leftcurrent, opaque->btpo_prev)));
715 
716  if (P_RIGHTMOST(opaque))
717  ereport(ERROR,
718  (errcode(ERRCODE_INDEX_CORRUPTED),
719  errmsg("block %u fell off the end of index \"%s\"",
720  current, RelationGetRelationName(state->rel))));
721  else
722  ereport(DEBUG1,
723  (errcode(ERRCODE_NO_DATA),
724  errmsg_internal("block %u of index \"%s\" ignored",
725  current, RelationGetRelationName(state->rel))));
726  goto nextpage;
727  }
728  else if (nextleveldown.leftmost == InvalidBlockNumber)
729  {
730  /*
731  * A concurrent page split could make the caller supplied leftmost
732  * block no longer contain the leftmost page, or no longer be the
733  * true root, but where that isn't possible due to heavyweight
734  * locking, check that the first valid page meets caller's
735  * expectations.
736  */
737  if (state->readonly)
738  {
739  if (!P_LEFTMOST(opaque))
740  ereport(ERROR,
741  (errcode(ERRCODE_INDEX_CORRUPTED),
742  errmsg("block %u is not leftmost in index \"%s\"",
743  current, RelationGetRelationName(state->rel))));
744 
745  if (level.istruerootlevel && !P_ISROOT(opaque))
746  ereport(ERROR,
747  (errcode(ERRCODE_INDEX_CORRUPTED),
748  errmsg("block %u is not true root in index \"%s\"",
749  current, RelationGetRelationName(state->rel))));
750  }
751 
752  /*
753  * Before beginning any non-trivial examination of level, prepare
754  * state for next bt_check_level_from_leftmost() invocation for
755  * the next level for the next level down (if any).
756  *
757  * There should be at least one non-ignorable page per level,
758  * unless this is the leaf level, which is assumed by caller to be
759  * final level.
760  */
761  if (!P_ISLEAF(opaque))
762  {
763  IndexTuple itup;
764  ItemId itemid;
765 
766  /* Internal page -- downlink gets leftmost on next level */
767  itemid = PageGetItemIdCareful(state, state->targetblock,
768  state->target,
769  P_FIRSTDATAKEY(opaque));
770  itup = (IndexTuple) PageGetItem(state->target, itemid);
771  nextleveldown.leftmost = BTreeTupleGetDownLink(itup);
772  nextleveldown.level = opaque->btpo_level - 1;
773  }
774  else
775  {
776  /*
777  * Leaf page -- final level caller must process.
778  *
779  * Note that this could also be the root page, if there has
780  * been no root page split yet.
781  */
782  nextleveldown.leftmost = P_NONE;
783  nextleveldown.level = InvalidBtreeLevel;
784  }
785 
786  /*
787  * Finished setting up state for this call/level. Control will
788  * never end up back here in any future loop iteration for this
789  * level.
790  */
791  }
792 
793  /* Sibling links should be in mutual agreement */
794  if (opaque->btpo_prev != leftcurrent)
795  bt_recheck_sibling_links(state, opaque->btpo_prev, leftcurrent);
796 
797  /* Check level */
798  if (level.level != opaque->btpo_level)
799  ereport(ERROR,
800  (errcode(ERRCODE_INDEX_CORRUPTED),
801  errmsg("leftmost down link for level points to block in index \"%s\" whose level is not one level down",
802  RelationGetRelationName(state->rel)),
803  errdetail_internal("Block pointed to=%u expected level=%u level in pointed to block=%u.",
804  current, level.level, opaque->btpo_level)));
805 
806  /* Verify invariants for page */
807  bt_target_page_check(state);
808 
809 nextpage:
810 
811  /* Try to detect circular links */
812  if (current == leftcurrent || current == opaque->btpo_prev)
813  ereport(ERROR,
814  (errcode(ERRCODE_INDEX_CORRUPTED),
815  errmsg("circular link chain found in block %u of index \"%s\"",
816  current, RelationGetRelationName(state->rel))));
817 
818  leftcurrent = current;
819  current = opaque->btpo_next;
820 
821  if (state->lowkey)
822  {
823  Assert(state->readonly);
824  pfree(state->lowkey);
825  state->lowkey = NULL;
826  }
827 
828  /*
829  * Copy current target high key as the low key of right sibling.
830  * Allocate memory in upper level context, so it would be cleared
831  * after reset of target context.
832  *
833  * We only need the low key in corner cases of checking child high
834  * keys. We use high key only when incomplete split on the child level
835  * falls to the boundary of pages on the target level. See
836  * bt_child_highkey_check() for details. So, typically we won't end
837  * up doing anything with low key, but it's simpler for general case
838  * high key verification to always have it available.
839  *
840  * The correctness of managing low key in the case of concurrent
841  * splits wasn't investigated yet. Thankfully we only need low key
842  * for readonly verification and concurrent splits won't happen.
843  */
844  if (state->readonly && !P_RIGHTMOST(opaque))
845  {
846  IndexTuple itup;
847  ItemId itemid;
848 
849  itemid = PageGetItemIdCareful(state, state->targetblock,
850  state->target, P_HIKEY);
851  itup = (IndexTuple) PageGetItem(state->target, itemid);
852 
853  state->lowkey = MemoryContextAlloc(oldcontext, IndexTupleSize(itup));
854  memcpy(state->lowkey, itup, IndexTupleSize(itup));
855  }
856 
857  /* Free page and associated memory for this iteration */
859  }
860  while (current != P_NONE);
861 
862  if (state->lowkey)
863  {
864  Assert(state->readonly);
865  pfree(state->lowkey);
866  state->lowkey = NULL;
867  }
868 
869  /* Don't change context for caller */
870  MemoryContextSwitchTo(oldcontext);
871 
872  return nextleveldown;
873 }
BlockNumber targetblock
Definition: verify_nbtree.c:93
BlockNumber btpo_next
Definition: nbtree.h:65
#define DEBUG1
Definition: elog.h:25
#define P_IGNORE(opaque)
Definition: nbtree.h:224
static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
uint32 level
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define P_NONE
Definition: nbtree.h:211
static BlockNumber BTreeTupleGetDownLink(IndexTuple pivot)
Definition: nbtree.h:530
int errcode(int sqlerrcode)
Definition: elog.c:704
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
uint32 BlockNumber
Definition: block.h:31
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
XLogRecPtr targetlsn
Definition: verify_nbtree.c:95
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
static void bt_recheck_sibling_links(BtreeCheckState *state, BlockNumber btpo_prev_from_target, BlockNumber leftcurrent)
BlockNumber btpo_prev
Definition: nbtree.h:64
uint32 btpo_level
Definition: nbtree.h:66
BlockNumber leftmost
IndexTupleData * IndexTuple
Definition: itup.h:53
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define P_LEFTMOST(opaque)
Definition: nbtree.h:217
#define P_ISDELETED(opaque)
Definition: nbtree.h:221
#define P_ISROOT(opaque)
Definition: nbtree.h:220
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
#define Assert(condition)
Definition: c.h:804
static void bt_target_page_check(BtreeCheckState *state)
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
#define InvalidBlockNumber
Definition: block.h:33
#define PageGetLSN(page)
Definition: bufpage.h:366
IndexTuple lowkey
#define P_HIKEY
Definition: nbtree.h:348
int errmsg(const char *fmt,...)
Definition: elog.c:915
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:797
#define elog(elevel,...)
Definition: elog.h:228
bool istruerootlevel
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
#define InvalidBtreeLevel
Definition: verify_nbtree.c:49
MemoryContext targetcontext
Definition: verify_nbtree.c:82
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:218
BlockNumber prevrightlink
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
#define IndexTupleSize(itup)
Definition: itup.h:71
#define P_ISLEAF(opaque)
Definition: nbtree.h:219

◆ bt_child_check()

static void bt_child_check ( BtreeCheckState state,
BTScanInsert  targetkey,
OffsetNumber  downlinkoffnum 
)
static

Definition at line 2065 of file verify_nbtree.c.

References Assert, bt_child_highkey_check(), BTPageOpaqueData::btpo_level, BTreeTupleGetDownLink(), ereport, errcode(), errdetail_internal(), errmsg(), ERROR, invariant_l_nontarget_offset(), LSN_FORMAT_ARGS, offset_is_negative_infinity(), OffsetNumberNext, P_FIRSTDATAKEY, P_ISDELETED, PageGetItem, PageGetItemIdCareful(), PageGetMaxOffsetNumber, PageGetSpecialPointer, palloc_btree_page(), pfree(), BtreeCheckState::readonly, BtreeCheckState::rel, RelationGetRelationName, BtreeCheckState::target, BtreeCheckState::targetblock, and BtreeCheckState::targetlsn.

Referenced by bt_target_page_check().

2067 {
2068  ItemId itemid;
2069  IndexTuple itup;
2070  BlockNumber childblock;
2071  OffsetNumber offset;
2072  OffsetNumber maxoffset;
2073  Page child;
2074  BTPageOpaque copaque;
2075  BTPageOpaque topaque;
2076 
2077  itemid = PageGetItemIdCareful(state, state->targetblock,
2078  state->target, downlinkoffnum);
2079  itup = (IndexTuple) PageGetItem(state->target, itemid);
2080  childblock = BTreeTupleGetDownLink(itup);
2081 
2082  /*
2083  * Caller must have ShareLock on target relation, because of
2084  * considerations around page deletion by VACUUM.
2085  *
2086  * NB: In general, page deletion deletes the right sibling's downlink, not
2087  * the downlink of the page being deleted; the deleted page's downlink is
2088  * reused for its sibling. The key space is thereby consolidated between
2089  * the deleted page and its right sibling. (We cannot delete a parent
2090  * page's rightmost child unless it is the last child page, and we intend
2091  * to also delete the parent itself.)
2092  *
2093  * If this verification happened without a ShareLock, the following race
2094  * condition could cause false positives:
2095  *
2096  * In general, concurrent page deletion might occur, including deletion of
2097  * the left sibling of the child page that is examined here. If such a
2098  * page deletion were to occur, closely followed by an insertion into the
2099  * newly expanded key space of the child, a window for the false positive
2100  * opens up: the stale parent/target downlink originally followed to get
2101  * to the child legitimately ceases to be a lower bound on all items in
2102  * the page, since the key space was concurrently expanded "left".
2103  * (Insertion followed the "new" downlink for the child, not our now-stale
2104  * downlink, which was concurrently physically removed in target/parent as
2105  * part of deletion's first phase.)
2106  *
2107  * While we use various techniques elsewhere to perform cross-page
2108  * verification for !readonly callers, a similar trick seems difficult
2109  * here. The tricks used by bt_recheck_sibling_links and by
2110  * bt_right_page_check_scankey both involve verification of a same-level,
2111  * cross-sibling invariant. Cross-level invariants are far more squishy,
2112  * though. The nbtree REDO routines do not actually couple buffer locks
2113  * across levels during page splits, so making any cross-level check work
2114  * reliably in !readonly mode may be impossible.
2115  */
2116  Assert(state->readonly);
2117 
2118  /*
2119  * Verify child page has the downlink key from target page (its parent) as
2120  * a lower bound; downlink must be strictly less than all keys on the
2121  * page.
2122  *
2123  * Check all items, rather than checking just the first and trusting that
2124  * the operator class obeys the transitive law.
2125  */
2126  topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
2127  child = palloc_btree_page(state, childblock);
2128  copaque = (BTPageOpaque) PageGetSpecialPointer(child);
2129  maxoffset = PageGetMaxOffsetNumber(child);
2130 
2131  /*
2132  * Since we've already loaded the child block, combine this check with
2133  * check for downlink connectivity.
2134  */
2135  bt_child_highkey_check(state, downlinkoffnum,
2136  child, topaque->btpo_level);
2137 
2138  /*
2139  * Since there cannot be a concurrent VACUUM operation in readonly mode,
2140  * and since a page has no links within other pages (siblings and parent)
2141  * once it is marked fully deleted, it should be impossible to land on a
2142  * fully deleted page.
2143  *
2144  * It does not quite make sense to enforce that the page cannot even be
2145  * half-dead, despite the fact the downlink is modified at the same stage
2146  * that the child leaf page is marked half-dead. That's incorrect because
2147  * there may occasionally be multiple downlinks from a chain of pages
2148  * undergoing deletion, where multiple successive calls are made to
2149  * _bt_unlink_halfdead_page() by VACUUM before it can finally safely mark
2150  * the leaf page as fully dead. While _bt_mark_page_halfdead() usually
2151  * removes the downlink to the leaf page that is marked half-dead, that's
2152  * not guaranteed, so it's possible we'll land on a half-dead page with a
2153  * downlink due to an interrupted multi-level page deletion.
2154  *
2155  * We go ahead with our checks if the child page is half-dead. It's safe
2156  * to do so because we do not test the child's high key, so it does not
2157  * matter that the original high key will have been replaced by a dummy
2158  * truncated high key within _bt_mark_page_halfdead(). All other page
2159  * items are left intact on a half-dead page, so there is still something
2160  * to test.
2161  */
2162  if (P_ISDELETED(copaque))
2163  ereport(ERROR,
2164  (errcode(ERRCODE_INDEX_CORRUPTED),
2165  errmsg("downlink to deleted page found in index \"%s\"",
2166  RelationGetRelationName(state->rel)),
2167  errdetail_internal("Parent block=%u child block=%u parent page lsn=%X/%X.",
2168  state->targetblock, childblock,
2169  LSN_FORMAT_ARGS(state->targetlsn))));
2170 
2171  for (offset = P_FIRSTDATAKEY(copaque);
2172  offset <= maxoffset;
2173  offset = OffsetNumberNext(offset))
2174  {
2175  /*
2176  * Skip comparison of target page key against "negative infinity"
2177  * item, if any. Checking it would indicate that it's not a strict
2178  * lower bound, but that's only because of the hard-coding for
2179  * negative infinity items within _bt_compare().
2180  *
2181  * If nbtree didn't truncate negative infinity tuples during internal
2182  * page splits then we'd expect child's negative infinity key to be
2183  * equal to the scankey/downlink from target/parent (it would be a
2184  * "low key" in this hypothetical scenario, and so it would still need
2185  * to be treated as a special case here).
2186  *
2187  * Negative infinity items can be thought of as a strict lower bound
2188  * that works transitively, with the last non-negative-infinity pivot
2189  * followed during a descent from the root as its "true" strict lower
2190  * bound. Only a small number of negative infinity items are truly
2191  * negative infinity; those that are the first items of leftmost
2192  * internal pages. In more general terms, a negative infinity item is
2193  * only negative infinity with respect to the subtree that the page is
2194  * at the root of.
2195  *
2196  * See also: bt_rootdescend(), which can even detect transitive
2197  * inconsistencies on cousin leaf pages.
2198  */
2199  if (offset_is_negative_infinity(copaque, offset))
2200  continue;
2201 
2202  if (!invariant_l_nontarget_offset(state, targetkey, childblock, child,
2203  offset))
2204  ereport(ERROR,
2205  (errcode(ERRCODE_INDEX_CORRUPTED),
2206  errmsg("down-link lower bound invariant violated for index \"%s\"",
2207  RelationGetRelationName(state->rel)),
2208  errdetail_internal("Parent block=%u child index tid=(%u,%u) parent page lsn=%X/%X.",
2209  state->targetblock, childblock, offset,
2210  LSN_FORMAT_ARGS(state->targetlsn))));
2211  }
2212 
2213  pfree(child);
2214 }
BlockNumber targetblock
Definition: verify_nbtree.c:93
static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
static BlockNumber BTreeTupleGetDownLink(IndexTuple pivot)
Definition: nbtree.h:530
int errcode(int sqlerrcode)
Definition: elog.c:704
uint32 BlockNumber
Definition: block.h:31
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
uint16 OffsetNumber
Definition: off.h:24
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
XLogRecPtr targetlsn
Definition: verify_nbtree.c:95
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
uint32 btpo_level
Definition: nbtree.h:66
IndexTupleData * IndexTuple
Definition: itup.h:53
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define P_ISDELETED(opaque)
Definition: nbtree.h:221
static bool invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key, BlockNumber nontargetblock, Page nontarget, OffsetNumber upperbound)
#define ereport(elevel,...)
Definition: elog.h:155
static void bt_child_highkey_check(BtreeCheckState *state, OffsetNumber target_downlinkoffnum, Page loaded_child, uint32 target_level)
#define Assert(condition)
Definition: c.h:804
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
int errmsg(const char *fmt,...)
Definition: elog.c:915
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
static bool offset_is_negative_infinity(BTPageOpaque opaque, OffsetNumber offset)
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78

◆ bt_child_highkey_check()

static void bt_child_highkey_check ( BtreeCheckState state,
OffsetNumber  target_downlinkoffnum,
Page  loaded_child,
uint32  target_level 
)
static

Definition at line 1819 of file verify_nbtree.c.

References BlockNumberIsValid, bt_downlink_missing_check(), bt_pivot_tuple_identical(), BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_next, BTPageOpaqueData::btpo_prev, BTreeTupleGetDownLink(), ereport, errcode(), errdetail_internal(), errmsg(), ERROR, BtreeCheckState::heapkeyspace, InvalidBlockNumber, BtreeCheckState::lowkey, LSN_FORMAT_ARGS, offset_is_negative_infinity(), OffsetNumberIsValid, OffsetNumberNext, P_HAS_FULLXID, P_HIKEY, P_IGNORE, P_INCOMPLETE_SPLIT, P_ISDELETED, P_LEFTMOST, P_NONE, P_RIGHTMOST, PageGetItem, PageGetItemIdCareful(), PageGetMaxOffsetNumber, PageGetSpecialPointer, palloc_btree_page(), pfree(), BtreeCheckState::previncompletesplit, BtreeCheckState::prevrightlink, BtreeCheckState::rel, RelationGetRelationName, BtreeCheckState::target, BtreeCheckState::targetblock, and BtreeCheckState::targetlsn.

Referenced by bt_child_check(), and bt_target_page_check().

1823 {
1824  BlockNumber blkno = state->prevrightlink;
1825  Page page;
1826  BTPageOpaque opaque;
1827  bool rightsplit = state->previncompletesplit;
1828  bool first = true;
1829  ItemId itemid;
1830  IndexTuple itup;
1831  BlockNumber downlink;
1832 
1833  if (OffsetNumberIsValid(target_downlinkoffnum))
1834  {
1835  itemid = PageGetItemIdCareful(state, state->targetblock,
1836  state->target, target_downlinkoffnum);
1837  itup = (IndexTuple) PageGetItem(state->target, itemid);
1838  downlink = BTreeTupleGetDownLink(itup);
1839  }
1840  else
1841  {
1842  downlink = P_NONE;
1843  }
1844 
1845  /*
1846  * If no previous rightlink is memorized for current level just below
1847  * target page's level, we are about to start from the leftmost page. We
1848  * can't follow rightlinks from previous page, because there is no
1849  * previous page. But we still can match high key.
1850  *
1851  * So we initialize variables for the loop above like there is previous
1852  * page referencing current child. Also we imply previous page to not
1853  * have incomplete split flag, that would make us require downlink for
1854  * current child. That's correct, because leftmost page on the level
1855  * should always have parent downlink.
1856  */
1857  if (!BlockNumberIsValid(blkno))
1858  {
1859  blkno = downlink;
1860  rightsplit = false;
1861  }
1862 
1863  /* Move to the right on the child level */
1864  while (true)
1865  {
1866  /*
1867  * Did we traverse the whole tree level and this is check for pages to
1868  * the right of rightmost downlink?
1869  */
1870  if (blkno == P_NONE && downlink == P_NONE)
1871  {
1873  state->previncompletesplit = false;
1874  return;
1875  }
1876 
1877  /* Did we traverse the whole tree level and don't find next downlink? */
1878  if (blkno == P_NONE)
1879  ereport(ERROR,
1880  (errcode(ERRCODE_INDEX_CORRUPTED),
1881  errmsg("can't traverse from downlink %u to downlink %u of index \"%s\"",
1882  state->prevrightlink, downlink,
1883  RelationGetRelationName(state->rel))));
1884 
1885  /* Load page contents */
1886  if (blkno == downlink && loaded_child)
1887  page = loaded_child;
1888  else
1889  page = palloc_btree_page(state, blkno);
1890 
1891  opaque = (BTPageOpaque) PageGetSpecialPointer(page);
1892 
1893  /* The first page we visit at the level should be leftmost */
1894  if (first && !BlockNumberIsValid(state->prevrightlink) && !P_LEFTMOST(opaque))
1895  ereport(ERROR,
1896  (errcode(ERRCODE_INDEX_CORRUPTED),
1897  errmsg("the first child of leftmost target page is not leftmost of its level in index \"%s\"",
1898  RelationGetRelationName(state->rel)),
1899  errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.",
1900  state->targetblock, blkno,
1901  LSN_FORMAT_ARGS(state->targetlsn))));
1902 
1903  /* Do level sanity check */
1904  if ((!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque)) &&
1905  opaque->btpo_level != target_level - 1)
1906  ereport(ERROR,
1907  (errcode(ERRCODE_INDEX_CORRUPTED),
1908  errmsg("block found while following rightlinks from child of index \"%s\" has invalid level",
1909  RelationGetRelationName(state->rel)),
1910  errdetail_internal("Block pointed to=%u expected level=%u level in pointed to block=%u.",
1911  blkno, target_level - 1, opaque->btpo_level)));
1912 
1913  /* Try to detect circular links */
1914  if ((!first && blkno == state->prevrightlink) || blkno == opaque->btpo_prev)
1915  ereport(ERROR,
1916  (errcode(ERRCODE_INDEX_CORRUPTED),
1917  errmsg("circular link chain found in block %u of index \"%s\"",
1918  blkno, RelationGetRelationName(state->rel))));
1919 
1920  if (blkno != downlink && !P_IGNORE(opaque))
1921  {
1922  /* blkno probably has missing parent downlink */
1923  bt_downlink_missing_check(state, rightsplit, blkno, page);
1924  }
1925 
1926  rightsplit = P_INCOMPLETE_SPLIT(opaque);
1927 
1928  /*
1929  * If we visit page with high key, check that it is equal to the
1930  * target key next to corresponding downlink.
1931  */
1932  if (!rightsplit && !P_RIGHTMOST(opaque))
1933  {
1934  BTPageOpaque topaque;
1935  IndexTuple highkey;
1936  OffsetNumber pivotkey_offset;
1937 
1938  /* Get high key */
1939  itemid = PageGetItemIdCareful(state, blkno, page, P_HIKEY);
1940  highkey = (IndexTuple) PageGetItem(page, itemid);
1941 
1942  /*
1943  * There might be two situations when we examine high key. If
1944  * current child page is referenced by given target downlink, we
1945  * should look to the next offset number for matching key from
1946  * target page.
1947  *
1948  * Alternatively, we're following rightlinks somewhere in the
1949  * middle between page referenced by previous target's downlink
1950  * and the page referenced by current target's downlink. If
1951  * current child page hasn't incomplete split flag set, then its
1952  * high key should match to the target's key of current offset
1953  * number. This happens when a previous call here (to
1954  * bt_child_highkey_check()) found an incomplete split, and we
1955  * reach a right sibling page without a downlink -- the right
1956  * sibling page's high key still needs to be matched to a
1957  * separator key on the parent/target level.
1958  *
1959  * Don't apply OffsetNumberNext() to target_downlinkoffnum when we
1960  * already had to step right on the child level. Our traversal of
1961  * the child level must try to move in perfect lockstep behind (to
1962  * the left of) the target/parent level traversal.
1963  */
1964  if (blkno == downlink)
1965  pivotkey_offset = OffsetNumberNext(target_downlinkoffnum);
1966  else
1967  pivotkey_offset = target_downlinkoffnum;
1968 
1969  topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
1970 
1971  if (!offset_is_negative_infinity(topaque, pivotkey_offset))
1972  {
1973  /*
1974  * If we're looking for the next pivot tuple in target page,
1975  * but there is no more pivot tuples, then we should match to
1976  * high key instead.
1977  */
1978  if (pivotkey_offset > PageGetMaxOffsetNumber(state->target))
1979  {
1980  if (P_RIGHTMOST(topaque))
1981  ereport(ERROR,
1982  (errcode(ERRCODE_INDEX_CORRUPTED),
1983  errmsg("child high key is greater than rightmost pivot key on target level in index \"%s\"",
1984  RelationGetRelationName(state->rel)),
1985  errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.",
1986  state->targetblock, blkno,
1987  LSN_FORMAT_ARGS(state->targetlsn))));
1988  pivotkey_offset = P_HIKEY;
1989  }
1990  itemid = PageGetItemIdCareful(state, state->targetblock,
1991  state->target, pivotkey_offset);
1992  itup = (IndexTuple) PageGetItem(state->target, itemid);
1993  }
1994  else
1995  {
1996  /*
1997  * We cannot try to match child's high key to a negative
1998  * infinity key in target, since there is nothing to compare.
1999  * However, it's still possible to match child's high key
2000  * outside of target page. The reason why we're are is that
2001  * bt_child_highkey_check() was previously called for the
2002  * cousin page of 'loaded_child', which is incomplete split.
2003  * So, now we traverse to the right of that cousin page and
2004  * current child level page under consideration still belongs
2005  * to the subtree of target's left sibling. Thus, we need to
2006  * match child's high key to it's left uncle page high key.
2007  * Thankfully we saved it, it's called a "low key" of target
2008  * page.
2009  */
2010  if (!state->lowkey)
2011  ereport(ERROR,
2012  (errcode(ERRCODE_INDEX_CORRUPTED),
2013  errmsg("can't find left sibling high key in index \"%s\"",
2014  RelationGetRelationName(state->rel)),
2015  errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.",
2016  state->targetblock, blkno,
2017  LSN_FORMAT_ARGS(state->targetlsn))));
2018  itup = state->lowkey;
2019  }
2020 
2021  if (!bt_pivot_tuple_identical(state->heapkeyspace, highkey, itup))
2022  {
2023  ereport(ERROR,
2024  (errcode(ERRCODE_INDEX_CORRUPTED),
2025  errmsg("mismatch between parent key and child high key in index \"%s\"",
2026  RelationGetRelationName(state->rel)),
2027  errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.",
2028  state->targetblock, blkno,
2029  LSN_FORMAT_ARGS(state->targetlsn))));
2030  }
2031  }
2032 
2033  /* Exit if we already found next downlink */
2034  if (blkno == downlink)
2035  {
2036  state->prevrightlink = opaque->btpo_next;
2037  state->previncompletesplit = rightsplit;
2038  return;
2039  }
2040 
2041  /* Traverse to the next page using rightlink */
2042  blkno = opaque->btpo_next;
2043 
2044  /* Free page contents if it's allocated by us */
2045  if (page != loaded_child)
2046  pfree(page);
2047  first = false;
2048  }
2049 }
BlockNumber targetblock
Definition: verify_nbtree.c:93
BlockNumber btpo_next
Definition: nbtree.h:65
#define P_IGNORE(opaque)
Definition: nbtree.h:224
static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
static bool bt_pivot_tuple_identical(bool heapkeyspace, IndexTuple itup1, IndexTuple itup2)
#define P_NONE
Definition: nbtree.h:211
static BlockNumber BTreeTupleGetDownLink(IndexTuple pivot)
Definition: nbtree.h:530
int errcode(int sqlerrcode)
Definition: elog.c:704
uint32 BlockNumber
Definition: block.h:31
#define P_INCOMPLETE_SPLIT(opaque)
Definition: nbtree.h:226
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
static void bt_downlink_missing_check(BtreeCheckState *state, bool rightsplit, BlockNumber targetblock, Page target)
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
#define P_HAS_FULLXID(opaque)
Definition: nbtree.h:227
uint16 OffsetNumber
Definition: off.h:24
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
XLogRecPtr targetlsn
Definition: verify_nbtree.c:95
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
BlockNumber btpo_prev
Definition: nbtree.h:64
uint32 btpo_level
Definition: nbtree.h:66
IndexTupleData * IndexTuple
Definition: itup.h:53
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define P_LEFTMOST(opaque)
Definition: nbtree.h:217
#define P_ISDELETED(opaque)
Definition: nbtree.h:221
#define ereport(elevel,...)
Definition: elog.h:155
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
#define InvalidBlockNumber
Definition: block.h:33
IndexTuple lowkey
#define P_HIKEY
Definition: nbtree.h:348
int errmsg(const char *fmt,...)
Definition: elog.c:915
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
static bool offset_is_negative_infinity(BTPageOpaque opaque, OffsetNumber offset)
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:218
BlockNumber prevrightlink
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78

◆ bt_downlink_missing_check()

static void bt_downlink_missing_check ( BtreeCheckState state,
bool  rightsplit,
BlockNumber  targetblock,
Page  target 
)
static

Definition at line 2230 of file verify_nbtree.c.

References Assert, BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_prev, BTreeTupleGetDownLink(), BTreeTupleGetTopParent(), CHECK_FOR_INTERRUPTS, DEBUG1, elog, ereport, errcode(), errdetail_internal(), errmsg(), errmsg_internal(), ERROR, LSN_FORMAT_ARGS, P_FIRSTDATAKEY, P_HIKEY, P_IGNORE, P_ISDELETED, P_ISHALFDEAD, P_ISLEAF, P_ISROOT, P_RIGHTMOST, PageGetItem, PageGetItemIdCareful(), PageGetLSN, PageGetSpecialPointer, palloc_btree_page(), pfree(), BtreeCheckState::readonly, BtreeCheckState::rel, and RelationGetRelationName.

Referenced by bt_child_highkey_check().

2232 {
2234  ItemId itemid;
2235  IndexTuple itup;
2236  Page child;
2237  BTPageOpaque copaque;
2238  uint32 level;
2239  BlockNumber childblk;
2240  XLogRecPtr pagelsn;
2241 
2242  Assert(state->readonly);
2243  Assert(!P_IGNORE(opaque));
2244 
2245  /* No next level up with downlinks to fingerprint from the true root */
2246  if (P_ISROOT(opaque))
2247  return;
2248 
2249  pagelsn = PageGetLSN(page);
2250 
2251  /*
2252  * Incomplete (interrupted) page splits can account for the lack of a
2253  * downlink. Some inserting transaction should eventually complete the
2254  * page split in passing, when it notices that the left sibling page is
2255  * P_INCOMPLETE_SPLIT().
2256  *
2257  * In general, VACUUM is not prepared for there to be no downlink to a
2258  * page that it deletes. This is the main reason why the lack of a
2259  * downlink can be reported as corruption here. It's not obvious that an
2260  * invalid missing downlink can result in wrong answers to queries,
2261  * though, since index scans that land on the child may end up
2262  * consistently moving right. The handling of concurrent page splits (and
2263  * page deletions) within _bt_moveright() cannot distinguish
2264  * inconsistencies that last for a moment from inconsistencies that are
2265  * permanent and irrecoverable.
2266  *
2267  * VACUUM isn't even prepared to delete pages that have no downlink due to
2268  * an incomplete page split, but it can detect and reason about that case
2269  * by design, so it shouldn't be taken to indicate corruption. See
2270  * _bt_pagedel() for full details.
2271  */
2272  if (rightsplit)
2273  {
2274  ereport(DEBUG1,
2275  (errcode(ERRCODE_NO_DATA),
2276  errmsg_internal("harmless interrupted page split detected in index %s",
2277  RelationGetRelationName(state->rel)),
2278  errdetail_internal("Block=%u level=%u left sibling=%u page lsn=%X/%X.",
2279  blkno, opaque->btpo_level,
2280  opaque->btpo_prev,
2281  LSN_FORMAT_ARGS(pagelsn))));
2282  return;
2283  }
2284 
2285  /*
2286  * Page under check is probably the "top parent" of a multi-level page
2287  * deletion. We'll need to descend the subtree to make sure that
2288  * descendant pages are consistent with that, though.
2289  *
2290  * If the page (which must be non-ignorable) is a leaf page, then clearly
2291  * it can't be the top parent. The lack of a downlink is probably a
2292  * symptom of a broad problem that could just as easily cause
2293  * inconsistencies anywhere else.
2294  */
2295  if (P_ISLEAF(opaque))
2296  ereport(ERROR,
2297  (errcode(ERRCODE_INDEX_CORRUPTED),
2298  errmsg("leaf index block lacks downlink in index \"%s\"",
2299  RelationGetRelationName(state->rel)),
2300  errdetail_internal("Block=%u page lsn=%X/%X.",
2301  blkno,
2302  LSN_FORMAT_ARGS(pagelsn))));
2303 
2304  /* Descend from the given page, which is an internal page */
2305  elog(DEBUG1, "checking for interrupted multi-level deletion due to missing downlink in index \"%s\"",
2306  RelationGetRelationName(state->rel));
2307 
2308  level = opaque->btpo_level;
2309  itemid = PageGetItemIdCareful(state, blkno, page, P_FIRSTDATAKEY(opaque));
2310  itup = (IndexTuple) PageGetItem(page, itemid);
2311  childblk = BTreeTupleGetDownLink(itup);
2312  for (;;)
2313  {
2315 
2316  child = palloc_btree_page(state, childblk);
2317  copaque = (BTPageOpaque) PageGetSpecialPointer(child);
2318 
2319  if (P_ISLEAF(copaque))
2320  break;
2321 
2322  /* Do an extra sanity check in passing on internal pages */
2323  if (copaque->btpo_level != level - 1)
2324  ereport(ERROR,
2325  (errcode(ERRCODE_INDEX_CORRUPTED),
2326  errmsg_internal("downlink points to block in index \"%s\" whose level is not one level down",
2327  RelationGetRelationName(state->rel)),
2328  errdetail_internal("Top parent/under check block=%u block pointed to=%u expected level=%u level in pointed to block=%u.",
2329  blkno, childblk,
2330  level - 1, copaque->btpo_level)));
2331 
2332  level = copaque->btpo_level;
2333  itemid = PageGetItemIdCareful(state, childblk, child,
2334  P_FIRSTDATAKEY(copaque));
2335  itup = (IndexTuple) PageGetItem(child, itemid);
2336  childblk = BTreeTupleGetDownLink(itup);
2337  /* Be slightly more pro-active in freeing this memory, just in case */
2338  pfree(child);
2339  }
2340 
2341  /*
2342  * Since there cannot be a concurrent VACUUM operation in readonly mode,
2343  * and since a page has no links within other pages (siblings and parent)
2344  * once it is marked fully deleted, it should be impossible to land on a
2345  * fully deleted page. See bt_child_check() for further details.
2346  *
2347  * The bt_child_check() P_ISDELETED() check is repeated here because
2348  * bt_child_check() does not visit pages reachable through negative
2349  * infinity items. Besides, bt_child_check() is unwilling to descend
2350  * multiple levels. (The similar bt_child_check() P_ISDELETED() check
2351  * within bt_check_level_from_leftmost() won't reach the page either,
2352  * since the leaf's live siblings should have their sibling links updated
2353  * to bypass the deletion target page when it is marked fully dead.)
2354  *
2355  * If this error is raised, it might be due to a previous multi-level page
2356  * deletion that failed to realize that it wasn't yet safe to mark the
2357  * leaf page as fully dead. A "dangling downlink" will still remain when
2358  * this happens. The fact that the dangling downlink's page (the leaf's
2359  * parent/ancestor page) lacked a downlink is incidental.
2360  */
2361  if (P_ISDELETED(copaque))
2362  ereport(ERROR,
2363  (errcode(ERRCODE_INDEX_CORRUPTED),
2364  errmsg_internal("downlink to deleted leaf page found in index \"%s\"",
2365  RelationGetRelationName(state->rel)),
2366  errdetail_internal("Top parent/target block=%u leaf block=%u top parent/under check lsn=%X/%X.",
2367  blkno, childblk,
2368  LSN_FORMAT_ARGS(pagelsn))));
2369 
2370  /*
2371  * Iff leaf page is half-dead, its high key top parent link should point
2372  * to what VACUUM considered to be the top parent page at the instant it
2373  * was interrupted. Provided the high key link actually points to the
2374  * page under check, the missing downlink we detected is consistent with
2375  * there having been an interrupted multi-level page deletion. This means
2376  * that the subtree with the page under check at its root (a page deletion
2377  * chain) is in a consistent state, enabling VACUUM to resume deleting the
2378  * entire chain the next time it encounters the half-dead leaf page.
2379  */
2380  if (P_ISHALFDEAD(copaque) && !P_RIGHTMOST(copaque))
2381  {
2382  itemid = PageGetItemIdCareful(state, childblk, child, P_HIKEY);
2383  itup = (IndexTuple) PageGetItem(child, itemid);
2384  if (BTreeTupleGetTopParent(itup) == blkno)
2385  return;
2386  }
2387 
2388  ereport(ERROR,
2389  (errcode(ERRCODE_INDEX_CORRUPTED),
2390  errmsg("internal index block lacks downlink in index \"%s\"",
2391  RelationGetRelationName(state->rel)),
2392  errdetail_internal("Block=%u level=%u page lsn=%X/%X.",
2393  blkno, opaque->btpo_level,
2394  LSN_FORMAT_ARGS(pagelsn))));
2395 }
#define DEBUG1
Definition: elog.h:25
#define P_IGNORE(opaque)
Definition: nbtree.h:224
static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
static BlockNumber BTreeTupleGetDownLink(IndexTuple pivot)
Definition: nbtree.h:530
int errcode(int sqlerrcode)
Definition: elog.c:704
uint32 BlockNumber
Definition: block.h:31
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
void pfree(void *pointer)
Definition: mcxt.c:1057
#define P_ISHALFDEAD(opaque)
Definition: nbtree.h:223
#define ERROR
Definition: elog.h:45
BlockNumber btpo_prev
Definition: nbtree.h:64
uint32 btpo_level
Definition: nbtree.h:66
IndexTupleData * IndexTuple
Definition: itup.h:53
#define RelationGetRelationName(relation)
Definition: rel.h:491
unsigned int uint32
Definition: c.h:441
#define P_ISDELETED(opaque)
Definition: nbtree.h:221
#define P_ISROOT(opaque)
Definition: nbtree.h:220
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
#define PageGetLSN(page)
Definition: bufpage.h:366
#define P_HIKEY
Definition: nbtree.h:348
int errmsg(const char *fmt,...)
Definition: elog.c:915
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
#define elog(elevel,...)
Definition: elog.h:228
static BlockNumber BTreeTupleGetTopParent(IndexTuple leafhikey)
Definition: nbtree.h:594
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:218
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define P_ISLEAF(opaque)
Definition: nbtree.h:219

◆ bt_index_check()

Datum bt_index_check ( PG_FUNCTION_ARGS  )

Definition at line 201 of file verify_nbtree.c.

References bt_index_check_internal(), BtreeCheckState::heapallindexed, PG_GETARG_BOOL, PG_GETARG_OID, PG_NARGS, and PG_RETURN_VOID.

202 {
203  Oid indrelid = PG_GETARG_OID(0);
204  bool heapallindexed = false;
205 
206  if (PG_NARGS() == 2)
207  heapallindexed = PG_GETARG_BOOL(1);
208 
209  bt_index_check_internal(indrelid, false, heapallindexed, false);
210 
211  PG_RETURN_VOID();
212 }
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
unsigned int Oid
Definition: postgres_ext.h:31
static void bt_index_check_internal(Oid indrelid, bool parentcheck, bool heapallindexed, bool rootdescend)
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_NARGS()
Definition: fmgr.h:203

◆ bt_index_check_internal()

static void bt_index_check_internal ( Oid  indrelid,
bool  parentcheck,
bool  heapallindexed,
bool  rootdescend 
)
static

Definition at line 244 of file verify_nbtree.c.

References _bt_allequalimage(), _bt_metaversion(), AccessShareLock, bt_check_every_level(), btree_index_checkable(), btree_index_mainfork_expected(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg(), ERROR, BtreeCheckState::heapkeyspace, BtreeCheckState::heaprel, index_close(), index_open(), IndexGetRelation(), MAIN_FORKNUM, OidIsValid, RelationData::rd_smgr, RelationGetRelationName, RelationOpenSmgr, ShareLock, smgrexists(), table_close(), and table_open().

Referenced by bt_index_check(), and bt_index_parent_check().

246 {
247  Oid heapid;
248  Relation indrel;
249  Relation heaprel;
250  LOCKMODE lockmode;
251 
252  if (parentcheck)
253  lockmode = ShareLock;
254  else
255  lockmode = AccessShareLock;
256 
257  /*
258  * We must lock table before index to avoid deadlocks. However, if the
259  * passed indrelid isn't an index then IndexGetRelation() will fail.
260  * Rather than emitting a not-very-helpful error message, postpone
261  * complaining, expecting that the is-it-an-index test below will fail.
262  *
263  * In hot standby mode this will raise an error when parentcheck is true.
264  */
265  heapid = IndexGetRelation(indrelid, true);
266  if (OidIsValid(heapid))
267  heaprel = table_open(heapid, lockmode);
268  else
269  heaprel = NULL;
270 
271  /*
272  * Open the target index relations separately (like relation_openrv(), but
273  * with heap relation locked first to prevent deadlocking). In hot
274  * standby mode this will raise an error when parentcheck is true.
275  *
276  * There is no need for the usual indcheckxmin usability horizon test
277  * here, even in the heapallindexed case, because index undergoing
278  * verification only needs to have entries for a new transaction snapshot.
279  * (If this is a parentcheck verification, there is no question about
280  * committed or recently dead heap tuples lacking index entries due to
281  * concurrent activity.)
282  */
283  indrel = index_open(indrelid, lockmode);
284 
285  /*
286  * Since we did the IndexGetRelation call above without any lock, it's
287  * barely possible that a race against an index drop/recreation could have
288  * netted us the wrong table.
289  */
290  if (heaprel == NULL || heapid != IndexGetRelation(indrelid, false))
291  ereport(ERROR,
293  errmsg("could not open parent table of index %s",
294  RelationGetRelationName(indrel))));
295 
296  /* Relation suitable for checking as B-Tree? */
297  btree_index_checkable(indrel);
298 
299  if (btree_index_mainfork_expected(indrel))
300  {
301  bool heapkeyspace,
302  allequalimage;
303 
304  RelationOpenSmgr(indrel);
305  if (!smgrexists(indrel->rd_smgr, MAIN_FORKNUM))
306  ereport(ERROR,
307  (errcode(ERRCODE_INDEX_CORRUPTED),
308  errmsg("index \"%s\" lacks a main relation fork",
309  RelationGetRelationName(indrel))));
310 
311  /* Extract metadata from metapage, and sanitize it in passing */
312  _bt_metaversion(indrel, &heapkeyspace, &allequalimage);
313  if (allequalimage && !heapkeyspace)
314  ereport(ERROR,
315  (errcode(ERRCODE_INDEX_CORRUPTED),
316  errmsg("index \"%s\" metapage has equalimage field set on unsupported nbtree version",
317  RelationGetRelationName(indrel))));
318  if (allequalimage && !_bt_allequalimage(indrel, false))
319  ereport(ERROR,
320  (errcode(ERRCODE_INDEX_CORRUPTED),
321  errmsg("index \"%s\" metapage incorrectly indicates that deduplication is safe",
322  RelationGetRelationName(indrel))));
323 
324  /* Check index, possibly against table it is an index on */
325  bt_check_every_level(indrel, heaprel, heapkeyspace, parentcheck,
326  heapallindexed, rootdescend);
327  }
328 
329  /*
330  * Release locks early. That's ok here because nothing in the called
331  * routines will trigger shared cache invalidations to be sent, so we can
332  * relax the usual pattern of only releasing locks after commit.
333  */
334  index_close(indrel, lockmode);
335  if (heaprel)
336  table_close(heaprel, lockmode);
337 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3630
static bool btree_index_mainfork_expected(Relation rel)
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:74
static void btree_index_checkable(Relation rel)
int LOCKMODE
Definition: lockdefs.h:26
struct SMgrRelationData * rd_smgr
Definition: rel.h:57
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:704
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:247
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define RelationOpenSmgr(relation)
Definition: rel.h:514
#define ERROR
Definition: elog.h:45
static void bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace, bool readonly, bool heapallindexed, bool rootdescend)
#define RelationGetRelationName(relation)
Definition: rel.h:491
void _bt_metaversion(Relation rel, bool *heapkeyspace, bool *allequalimage)
Definition: nbtpage.c:697
#define ereport(elevel,...)
Definition: elog.h:155
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define ShareLock
Definition: lockdefs.h:41
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
bool _bt_allequalimage(Relation rel, bool debugmessage)
Definition: nbtutils.c:2692
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ bt_index_parent_check()

Datum bt_index_parent_check ( PG_FUNCTION_ARGS  )

Definition at line 224 of file verify_nbtree.c.

References bt_index_check_internal(), BtreeCheckState::heapallindexed, PG_GETARG_BOOL, PG_GETARG_OID, PG_NARGS, PG_RETURN_VOID, and BtreeCheckState::rootdescend.

225 {
226  Oid indrelid = PG_GETARG_OID(0);
227  bool heapallindexed = false;
228  bool rootdescend = false;
229 
230  if (PG_NARGS() >= 2)
231  heapallindexed = PG_GETARG_BOOL(1);
232  if (PG_NARGS() == 3)
233  rootdescend = PG_GETARG_BOOL(2);
234 
235  bt_index_check_internal(indrelid, true, heapallindexed, rootdescend);
236 
237  PG_RETURN_VOID();
238 }
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
unsigned int Oid
Definition: postgres_ext.h:31
static void bt_index_check_internal(Oid indrelid, bool parentcheck, bool heapallindexed, bool rootdescend)
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_NARGS()
Definition: fmgr.h:203

◆ bt_mkscankey_pivotsearch()

static BTScanInsert bt_mkscankey_pivotsearch ( Relation  rel,
IndexTuple  itup 
)
inlinestatic

Definition at line 3103 of file verify_nbtree.c.

References _bt_mkscankey(), and BTScanInsertData::pivotsearch.

Referenced by bt_right_page_check_scankey(), and bt_target_page_check().

3104 {
3105  BTScanInsert skey;
3106 
3107  skey = _bt_mkscankey(rel, itup);
3108  skey->pivotsearch = true;
3109 
3110  return skey;
3111 }
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:90
bool pivotsearch
Definition: nbtree.h:769

◆ bt_normalize_tuple()

static IndexTuple bt_normalize_tuple ( BtreeCheckState state,
IndexTuple  itup 
)
static

Definition at line 2521 of file verify_nbtree.c.

References Assert, BTreeTupleIsPivot(), BTreeTupleIsPosting(), DatumGetPointer, ereport, errcode(), errmsg(), ERROR, i, index_form_tuple(), index_getattr, INDEX_MAX_KEYS, IndexTupleHasVarwidths, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, TupleDescData::natts, pfree(), PG_DETOAST_DATUM, PointerGetDatum, BtreeCheckState::rel, RelationGetDescr, RelationGetRelationName, IndexTupleData::t_tid, TupleDescAttr, VARATT_IS_COMPRESSED, and VARATT_IS_EXTERNAL.

Referenced by bt_target_page_check(), and bt_tuple_present_callback().

2522 {
2523  TupleDesc tupleDescriptor = RelationGetDescr(state->rel);
2524  Datum normalized[INDEX_MAX_KEYS];
2525  bool isnull[INDEX_MAX_KEYS];
2526  bool toast_free[INDEX_MAX_KEYS];
2527  bool formnewtup = false;
2528  IndexTuple reformed;
2529  int i;
2530 
2531  /* Caller should only pass "logical" non-pivot tuples here */
2532  Assert(!BTreeTupleIsPosting(itup) && !BTreeTupleIsPivot(itup));
2533 
2534  /* Easy case: It's immediately clear that tuple has no varlena datums */
2535  if (!IndexTupleHasVarwidths(itup))
2536  return itup;
2537 
2538  for (i = 0; i < tupleDescriptor->natts; i++)
2539  {
2540  Form_pg_attribute att;
2541 
2542  att = TupleDescAttr(tupleDescriptor, i);
2543 
2544  /* Assume untoasted/already normalized datum initially */
2545  toast_free[i] = false;
2546  normalized[i] = index_getattr(itup, att->attnum,
2547  tupleDescriptor,
2548  &isnull[i]);
2549  if (att->attbyval || att->attlen != -1 || isnull[i])
2550  continue;
2551 
2552  /*
2553  * Callers always pass a tuple that could safely be inserted into the
2554  * index without further processing, so an external varlena header
2555  * should never be encountered here
2556  */
2557  if (VARATT_IS_EXTERNAL(DatumGetPointer(normalized[i])))
2558  ereport(ERROR,
2559  (errcode(ERRCODE_INDEX_CORRUPTED),
2560  errmsg("external varlena datum in tuple that references heap row (%u,%u) in index \"%s\"",
2561  ItemPointerGetBlockNumber(&(itup->t_tid)),
2563  RelationGetRelationName(state->rel))));
2564  else if (VARATT_IS_COMPRESSED(DatumGetPointer(normalized[i])))
2565  {
2566  formnewtup = true;
2567  normalized[i] = PointerGetDatum(PG_DETOAST_DATUM(normalized[i]));
2568  toast_free[i] = true;
2569  }
2570  }
2571 
2572  /* Easier case: Tuple has varlena datums, none of which are compressed */
2573  if (!formnewtup)
2574  return itup;
2575 
2576  /*
2577  * Hard case: Tuple had compressed varlena datums that necessitate
2578  * creating normalized version of the tuple from uncompressed input datums
2579  * (normalized input datums). This is rather naive, but shouldn't be
2580  * necessary too often.
2581  *
2582  * Note that we rely on deterministic index_form_tuple() TOAST compression
2583  * of normalized input.
2584  */
2585  reformed = index_form_tuple(tupleDescriptor, normalized, isnull);
2586  reformed->t_tid = itup->t_tid;
2587 
2588  /* Cannot leak memory here */
2589  for (i = 0; i < tupleDescriptor->natts; i++)
2590  if (toast_free[i])
2591  pfree(DatumGetPointer(normalized[i]));
2592 
2593  return reformed;
2594 }
#define VARATT_IS_COMPRESSED(PTR)
Definition: postgres.h:312
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:454
#define RelationGetDescr(relation)
Definition: rel.h:483
#define PointerGetDatum(X)
Definition: postgres.h:556
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
ItemPointerData t_tid
Definition: itup.h:37
int errcode(int sqlerrcode)
Definition: elog.c:704
#define VARATT_IS_EXTERNAL(PTR)
Definition: postgres.h:313
IndexTuple index_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:47
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
#define RelationGetRelationName(relation)
Definition: rel.h:491
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:155
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:466
#define Assert(condition)
Definition: c.h:804
#define INDEX_MAX_KEYS
#define index_getattr(tup, attnum, tupleDesc, isnull)
Definition: itup.h:100
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define IndexTupleHasVarwidths(itup)
Definition: itup.h:73
#define DatumGetPointer(X)
Definition: postgres.h:549
int errmsg(const char *fmt,...)
Definition: elog.c:915
int i
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ bt_pivot_tuple_identical()

static bool bt_pivot_tuple_identical ( bool  heapkeyspace,
IndexTuple  itup1,
IndexTuple  itup2 
)
static

Definition at line 1746 of file verify_nbtree.c.

References IndexTupleSize, ItemPointerData::ip_posid, offsetof, IndexTupleData::t_info, and IndexTupleData::t_tid.

Referenced by bt_child_highkey_check().

1747 {
1748  if (IndexTupleSize(itup1) != IndexTupleSize(itup2))
1749  return false;
1750 
1751  if (heapkeyspace)
1752  {
1753  /*
1754  * Offset number will contain important information in heapkeyspace
1755  * indexes: the number of attributes left in the pivot tuple following
1756  * suffix truncation. Don't skip over it (compare it too).
1757  */
1758  if (memcmp(&itup1->t_tid.ip_posid, &itup2->t_tid.ip_posid,
1759  IndexTupleSize(itup1) -
1760  offsetof(ItemPointerData, ip_posid)) != 0)
1761  return false;
1762  }
1763  else
1764  {
1765  /*
1766  * Cannot rely on offset number field having consistent value across
1767  * levels on pg_upgrade'd !heapkeyspace indexes. Compare contents of
1768  * tuple starting from just after item pointer (i.e. after block
1769  * number and offset number).
1770  */
1771  if (memcmp(&itup1->t_info, &itup2->t_info,
1772  IndexTupleSize(itup1) -
1773  offsetof(IndexTupleData, t_info)) != 0)
1774  return false;
1775  }
1776 
1777  return true;
1778 }
ItemPointerData t_tid
Definition: itup.h:37
unsigned short t_info
Definition: itup.h:49
OffsetNumber ip_posid
Definition: itemptr.h:39
#define offsetof(type, field)
Definition: c.h:727
#define IndexTupleSize(itup)
Definition: itup.h:71

◆ bt_posting_plain_tuple()

static IndexTuple bt_posting_plain_tuple ( IndexTuple  itup,
int  n 
)
inlinestatic

Definition at line 2611 of file verify_nbtree.c.

References _bt_form_posting(), Assert, BTreeTupleGetPostingN(), and BTreeTupleIsPosting().

Referenced by bt_target_page_check().

2612 {
2613  Assert(BTreeTupleIsPosting(itup));
2614 
2615  /* Returns non-posting-list tuple */
2616  return _bt_form_posting(itup, BTreeTupleGetPostingN(itup, n), 1);
2617 }
IndexTuple _bt_form_posting(IndexTuple base, ItemPointer htids, int nhtids)
Definition: nbtdedup.c:859
static ItemPointer BTreeTupleGetPostingN(IndexTuple posting, int n)
Definition: nbtree.h:518
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:466
#define Assert(condition)
Definition: c.h:804

◆ bt_recheck_sibling_links()

static void bt_recheck_sibling_links ( BtreeCheckState state,
BlockNumber  btpo_prev_from_target,
BlockNumber  leftcurrent 
)
static

Definition at line 911 of file verify_nbtree.c.

References _bt_checkpage(), BT_READ, BTPageOpaqueData::btpo_next, BTPageOpaqueData::btpo_prev, BufferGetPage, BufferIsValid, BtreeCheckState::checkstrategy, DEBUG1, ereport, errcode(), errdetail_internal(), errmsg(), errmsg_internal(), ERROR, InvalidBlockNumber, InvalidBuffer, LockBuffer(), MAIN_FORKNUM, P_ISDELETED, PageGetSpecialPointer, RBM_NORMAL, ReadBufferExtended(), BtreeCheckState::readonly, BtreeCheckState::rel, RelationGetRelationName, BtreeCheckState::targetblock, and UnlockReleaseBuffer().

Referenced by bt_check_level_from_leftmost().

914 {
915  if (!state->readonly)
916  {
917  Buffer lbuf;
918  Buffer newtargetbuf;
919  Page page;
920  BTPageOpaque opaque;
921  BlockNumber newtargetblock;
922 
923  /* Couple locks in the usual order for nbtree: Left to right */
924  lbuf = ReadBufferExtended(state->rel, MAIN_FORKNUM, leftcurrent,
925  RBM_NORMAL, state->checkstrategy);
926  LockBuffer(lbuf, BT_READ);
927  _bt_checkpage(state->rel, lbuf);
928  page = BufferGetPage(lbuf);
929  opaque = (BTPageOpaque) PageGetSpecialPointer(page);
930  if (P_ISDELETED(opaque))
931  {
932  /*
933  * Cannot reason about concurrently deleted page -- the left link
934  * in the page to the right is expected to point to some other
935  * page to the left (not leftcurrent page).
936  *
937  * Note that we deliberately don't give up with a half-dead page.
938  */
939  UnlockReleaseBuffer(lbuf);
940  return;
941  }
942 
943  newtargetblock = opaque->btpo_next;
944  /* Avoid self-deadlock when newtargetblock == leftcurrent */
945  if (newtargetblock != leftcurrent)
946  {
947  newtargetbuf = ReadBufferExtended(state->rel, MAIN_FORKNUM,
948  newtargetblock, RBM_NORMAL,
949  state->checkstrategy);
950  LockBuffer(newtargetbuf, BT_READ);
951  _bt_checkpage(state->rel, newtargetbuf);
952  page = BufferGetPage(newtargetbuf);
953  opaque = (BTPageOpaque) PageGetSpecialPointer(page);
954  /* btpo_prev_from_target may have changed; update it */
955  btpo_prev_from_target = opaque->btpo_prev;
956  }
957  else
958  {
959  /*
960  * leftcurrent right sibling points back to leftcurrent block.
961  * Index is corrupt. Easiest way to handle this is to pretend
962  * that we actually read from a distinct page that has an invalid
963  * block number in its btpo_prev.
964  */
965  newtargetbuf = InvalidBuffer;
966  btpo_prev_from_target = InvalidBlockNumber;
967  }
968 
969  /*
970  * No need to check P_ISDELETED here, since new target block cannot be
971  * marked deleted as long as we hold a lock on lbuf
972  */
973  if (BufferIsValid(newtargetbuf))
974  UnlockReleaseBuffer(newtargetbuf);
975  UnlockReleaseBuffer(lbuf);
976 
977  if (btpo_prev_from_target == leftcurrent)
978  {
979  /* Report split in left sibling, not target (or new target) */
980  ereport(DEBUG1,
981  (errcode(ERRCODE_INTERNAL_ERROR),
982  errmsg_internal("harmless concurrent page split detected in index \"%s\"",
983  RelationGetRelationName(state->rel)),
984  errdetail_internal("Block=%u new right sibling=%u original right sibling=%u.",
985  leftcurrent, newtargetblock,
986  state->targetblock)));
987  return;
988  }
989 
990  /*
991  * Index is corrupt. Make sure that we report correct target page.
992  *
993  * This could have changed in cases where there was a concurrent page
994  * split, as well as index corruption (at least in theory). Note that
995  * btpo_prev_from_target was already updated above.
996  */
997  state->targetblock = newtargetblock;
998  }
999 
1000  ereport(ERROR,
1001  (errcode(ERRCODE_INDEX_CORRUPTED),
1002  errmsg("left link/right link pair in index \"%s\" not in agreement",
1003  RelationGetRelationName(state->rel)),
1004  errdetail_internal("Block=%u left block=%u left link from block=%u.",
1005  state->targetblock, leftcurrent,
1006  btpo_prev_from_target)));
1007 }
BlockNumber targetblock
Definition: verify_nbtree.c:93
BlockNumber btpo_next
Definition: nbtree.h:65
#define DEBUG1
Definition: elog.h:25
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:666
#define InvalidBuffer
Definition: buf.h:25
int errcode(int sqlerrcode)
Definition: elog.c:704
uint32 BlockNumber
Definition: block.h:31
BufferAccessStrategy checkstrategy
Definition: verify_nbtree.c:84
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
#define BT_READ
Definition: nbtree.h:693
void _bt_checkpage(Relation rel, Buffer buf)
Definition: nbtpage.c:755
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3723
#define ERROR
Definition: elog.h:45
BlockNumber btpo_prev
Definition: nbtree.h:64
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
#define P_ISDELETED(opaque)
Definition: nbtree.h:221
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3939
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
#define InvalidBlockNumber
Definition: block.h:33
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
int errmsg(const char *fmt,...)
Definition: elog.c:915
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:78

◆ bt_right_page_check_scankey()

static BTScanInsert bt_right_page_check_scankey ( BtreeCheckState state)
static

Definition at line 1544 of file verify_nbtree.c.

References bt_mkscankey_pivotsearch(), BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_next, CHECK_FOR_INTERRUPTS, DEBUG1, ereport, errcode(), errdetail_internal(), errmsg_internal(), OffsetNumberNext, P_FIRSTDATAKEY, P_IGNORE, P_ISLEAF, P_RIGHTMOST, PageGetItem, PageGetItemIdCareful(), PageGetMaxOffsetNumber, PageGetSpecialPointer, palloc_btree_page(), pfree(), BtreeCheckState::rel, RelationGetRelationName, and BtreeCheckState::target.

Referenced by bt_target_page_check().

1545 {
1546  BTPageOpaque opaque;
1547  ItemId rightitem;
1548  IndexTuple firstitup;
1549  BlockNumber targetnext;
1550  Page rightpage;
1551  OffsetNumber nline;
1552 
1553  /* Determine target's next block number */
1554  opaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
1555 
1556  /* If target is already rightmost, no right sibling; nothing to do here */
1557  if (P_RIGHTMOST(opaque))
1558  return NULL;
1559 
1560  /*
1561  * General notes on concurrent page splits and page deletion:
1562  *
1563  * Routines like _bt_search() don't require *any* page split interlock
1564  * when descending the tree, including something very light like a buffer
1565  * pin. That's why it's okay that we don't either. This avoidance of any
1566  * need to "couple" buffer locks is the raison d' etre of the Lehman & Yao
1567  * algorithm, in fact.
1568  *
1569  * That leaves deletion. A deleted page won't actually be recycled by
1570  * VACUUM early enough for us to fail to at least follow its right link
1571  * (or left link, or downlink) and find its sibling, because recycling
1572  * does not occur until no possible index scan could land on the page.
1573  * Index scans can follow links with nothing more than their snapshot as
1574  * an interlock and be sure of at least that much. (See page
1575  * recycling/"visible to everyone" notes in nbtree README.)
1576  *
1577  * Furthermore, it's okay if we follow a rightlink and find a half-dead or
1578  * dead (ignorable) page one or more times. There will either be a
1579  * further right link to follow that leads to a live page before too long
1580  * (before passing by parent's rightmost child), or we will find the end
1581  * of the entire level instead (possible when parent page is itself the
1582  * rightmost on its level).
1583  */
1584  targetnext = opaque->btpo_next;
1585  for (;;)
1586  {
1588 
1589  rightpage = palloc_btree_page(state, targetnext);
1590  opaque = (BTPageOpaque) PageGetSpecialPointer(rightpage);
1591 
1592  if (!P_IGNORE(opaque) || P_RIGHTMOST(opaque))
1593  break;
1594 
1595  /* We landed on a deleted page, so step right to find a live page */
1596  targetnext = opaque->btpo_next;
1597  ereport(DEBUG1,
1598  (errcode(ERRCODE_NO_DATA),
1599  errmsg_internal("level %u leftmost page of index \"%s\" was found deleted or half dead",
1600  opaque->btpo_level, RelationGetRelationName(state->rel)),
1601  errdetail_internal("Deleted page found when building scankey from right sibling.")));
1602 
1603  /* Be slightly more pro-active in freeing this memory, just in case */
1604  pfree(rightpage);
1605  }
1606 
1607  /*
1608  * No ShareLock held case -- why it's safe to proceed.
1609  *
1610  * Problem:
1611  *
1612  * We must avoid false positive reports of corruption when caller treats
1613  * item returned here as an upper bound on target's last item. In
1614  * general, false positives are disallowed. Avoiding them here when
1615  * caller is !readonly is subtle.
1616  *
1617  * A concurrent page deletion by VACUUM of the target page can result in
1618  * the insertion of items on to this right sibling page that would
1619  * previously have been inserted on our target page. There might have
1620  * been insertions that followed the target's downlink after it was made
1621  * to point to right sibling instead of target by page deletion's first
1622  * phase. The inserters insert items that would belong on target page.
1623  * This race is very tight, but it's possible. This is our only problem.
1624  *
1625  * Non-problems:
1626  *
1627  * We are not hindered by a concurrent page split of the target; we'll
1628  * never land on the second half of the page anyway. A concurrent split
1629  * of the right page will also not matter, because the first data item
1630  * remains the same within the left half, which we'll reliably land on. If
1631  * we had to skip over ignorable/deleted pages, it cannot matter because
1632  * their key space has already been atomically merged with the first
1633  * non-ignorable page we eventually find (doesn't matter whether the page
1634  * we eventually find is a true sibling or a cousin of target, which we go
1635  * into below).
1636  *
1637  * Solution:
1638  *
1639  * Caller knows that it should reverify that target is not ignorable
1640  * (half-dead or deleted) when cross-page sibling item comparison appears
1641  * to indicate corruption (invariant fails). This detects the single race
1642  * condition that exists for caller. This is correct because the
1643  * continued existence of target block as non-ignorable (not half-dead or
1644  * deleted) implies that target page was not merged into from the right by
1645  * deletion; the key space at or after target never moved left. Target's
1646  * parent either has the same downlink to target as before, or a <
1647  * downlink due to deletion at the left of target. Target either has the
1648  * same highkey as before, or a highkey < before when there is a page
1649  * split. (The rightmost concurrently-split-from-target-page page will
1650  * still have the same highkey as target was originally found to have,
1651  * which for our purposes is equivalent to target's highkey itself never
1652  * changing, since we reliably skip over
1653  * concurrently-split-from-target-page pages.)
1654  *
1655  * In simpler terms, we allow that the key space of the target may expand
1656  * left (the key space can move left on the left side of target only), but
1657  * the target key space cannot expand right and get ahead of us without
1658  * our detecting it. The key space of the target cannot shrink, unless it
1659  * shrinks to zero due to the deletion of the original page, our canary
1660  * condition. (To be very precise, we're a bit stricter than that because
1661  * it might just have been that the target page split and only the
1662  * original target page was deleted. We can be more strict, just not more
1663  * lax.)
1664  *
1665  * Top level tree walk caller moves on to next page (makes it the new
1666  * target) following recovery from this race. (cf. The rationale for
1667  * child/downlink verification needing a ShareLock within
1668  * bt_child_check(), where page deletion is also the main source of
1669  * trouble.)
1670  *
1671  * Note that it doesn't matter if right sibling page here is actually a
1672  * cousin page, because in order for the key space to be readjusted in a
1673  * way that causes us issues in next level up (guiding problematic
1674  * concurrent insertions to the cousin from the grandparent rather than to
1675  * the sibling from the parent), there'd have to be page deletion of
1676  * target's parent page (affecting target's parent's downlink in target's
1677  * grandparent page). Internal page deletion only occurs when there are
1678  * no child pages (they were all fully deleted), and caller is checking
1679  * that the target's parent has at least one non-deleted (so
1680  * non-ignorable) child: the target page. (Note that the first phase of
1681  * deletion atomically marks the page to be deleted half-dead/ignorable at
1682  * the same time downlink in its parent is removed, so caller will
1683  * definitely not fail to detect that this happened.)
1684  *
1685  * This trick is inspired by the method backward scans use for dealing
1686  * with concurrent page splits; concurrent page deletion is a problem that
1687  * similarly receives special consideration sometimes (it's possible that
1688  * the backwards scan will re-read its "original" block after failing to
1689  * find a right-link to it, having already moved in the opposite direction
1690  * (right/"forwards") a few times to try to locate one). Just like us,
1691  * that happens only to determine if there was a concurrent page deletion
1692  * of a reference page, and just like us if there was a page deletion of
1693  * that reference page it means we can move on from caring about the
1694  * reference page. See the nbtree README for a full description of how
1695  * that works.
1696  */
1697  nline = PageGetMaxOffsetNumber(rightpage);
1698 
1699  /*
1700  * Get first data item, if any
1701  */
1702  if (P_ISLEAF(opaque) && nline >= P_FIRSTDATAKEY(opaque))
1703  {
1704  /* Return first data item (if any) */
1705  rightitem = PageGetItemIdCareful(state, targetnext, rightpage,
1706  P_FIRSTDATAKEY(opaque));
1707  }
1708  else if (!P_ISLEAF(opaque) &&
1709  nline >= OffsetNumberNext(P_FIRSTDATAKEY(opaque)))
1710  {
1711  /*
1712  * Return first item after the internal page's "negative infinity"
1713  * item
1714  */
1715  rightitem = PageGetItemIdCareful(state, targetnext, rightpage,
1716  OffsetNumberNext(P_FIRSTDATAKEY(opaque)));
1717  }
1718  else
1719  {
1720  /*
1721  * No first item. Page is probably empty leaf page, but it's also
1722  * possible that it's an internal page with only a negative infinity
1723  * item.
1724  */
1725  ereport(DEBUG1,
1726  (errcode(ERRCODE_NO_DATA),
1727  errmsg_internal("%s block %u of index \"%s\" has no first data item",
1728  P_ISLEAF(opaque) ? "leaf" : "internal", targetnext,
1729  RelationGetRelationName(state->rel))));
1730  return NULL;
1731  }
1732 
1733  /*
1734  * Return first real item scankey. Note that this relies on right page
1735  * memory remaining allocated.
1736  */
1737  firstitup = (IndexTuple) PageGetItem(rightpage, rightitem);
1738  return bt_mkscankey_pivotsearch(state->rel, firstitup);
1739 }
BlockNumber btpo_next
Definition: nbtree.h:65
#define DEBUG1
Definition: elog.h:25
#define P_IGNORE(opaque)
Definition: nbtree.h:224
static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
int errcode(int sqlerrcode)
Definition: elog.c:704
uint32 BlockNumber
Definition: block.h:31
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
uint16 OffsetNumber
Definition: off.h:24
void pfree(void *pointer)
Definition: mcxt.c:1057
uint32 btpo_level
Definition: nbtree.h:66
IndexTupleData * IndexTuple
Definition: itup.h:53
#define RelationGetRelationName(relation)
Definition: rel.h:491
static BTScanInsert bt_mkscankey_pivotsearch(Relation rel, IndexTuple itup)
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:218
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define P_ISLEAF(opaque)
Definition: nbtree.h:219

◆ bt_rootdescend()

static bool bt_rootdescend ( BtreeCheckState state,
IndexTuple  itup 
)
static

Definition at line 2644 of file verify_nbtree.c.

References _bt_binsrch_insert(), _bt_compare(), _bt_freestack(), _bt_mkscankey(), _bt_relbuf(), _bt_search(), Assert, BTInsertStateData::bounds_valid, BT_READ, BTInsertStateData::buf, BufferGetPage, BufferIsValid, BTScanInsertData::heapkeyspace, IndexTupleSize, BTInsertStateData::itemsz, BTInsertStateData::itup, BTInsertStateData::itup_key, sort-test::key, MAXALIGN, PageGetMaxOffsetNumber, pfree(), BTInsertStateData::postingoff, BtreeCheckState::readonly, BtreeCheckState::rel, BtreeCheckState::rootdescend, and BTScanInsertData::scantid.

Referenced by bt_target_page_check().

2645 {
2646  BTScanInsert key;
2647  BTStack stack;
2648  Buffer lbuf;
2649  bool exists;
2650 
2651  key = _bt_mkscankey(state->rel, itup);
2652  Assert(key->heapkeyspace && key->scantid != NULL);
2653 
2654  /*
2655  * Search from root.
2656  *
2657  * Ideally, we would arrange to only move right within _bt_search() when
2658  * an interrupted page split is detected (i.e. when the incomplete split
2659  * bit is found to be set), but for now we accept the possibility that
2660  * that could conceal an inconsistency.
2661  */
2662  Assert(state->readonly && state->rootdescend);
2663  exists = false;
2664  stack = _bt_search(state->rel, key, &lbuf, BT_READ, NULL);
2665 
2666  if (BufferIsValid(lbuf))
2667  {
2668  BTInsertStateData insertstate;
2669  OffsetNumber offnum;
2670  Page page;
2671 
2672  insertstate.itup = itup;
2673  insertstate.itemsz = MAXALIGN(IndexTupleSize(itup));
2674  insertstate.itup_key = key;
2675  insertstate.postingoff = 0;
2676  insertstate.bounds_valid = false;
2677  insertstate.buf = lbuf;
2678 
2679  /* Get matching tuple on leaf page */
2680  offnum = _bt_binsrch_insert(state->rel, &insertstate);
2681  /* Compare first >= matching item on leaf page, if any */
2682  page = BufferGetPage(lbuf);
2683  /* Should match on first heap TID when tuple has a posting list */
2684  if (offnum <= PageGetMaxOffsetNumber(page) &&
2685  insertstate.postingoff <= 0 &&
2686  _bt_compare(state->rel, key, page, offnum) == 0)
2687  exists = true;
2688  _bt_relbuf(state->rel, lbuf);
2689  }
2690 
2691  _bt_freestack(stack);
2692  pfree(key);
2693 
2694  return exists;
2695 }
void _bt_freestack(BTStack stack)
Definition: nbtutils.c:175
bool bounds_valid
Definition: nbtree.h:802
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:90
ItemPointer scantid
Definition: nbtree.h:770
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
uint16 OffsetNumber
Definition: off.h:24
#define BT_READ
Definition: nbtree.h:693
void pfree(void *pointer)
Definition: mcxt.c:1057
OffsetNumber _bt_binsrch_insert(Relation rel, BTInsertState insertstate)
Definition: nbtsearch.c:447
IndexTuple itup
Definition: nbtree.h:790
int32 _bt_compare(Relation rel, BTScanInsert key, Page page, OffsetNumber offnum)
Definition: nbtsearch.c:644
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
void _bt_relbuf(Relation rel, Buffer buf)
Definition: nbtpage.c:996
BTScanInsert itup_key
Definition: nbtree.h:792
#define Assert(condition)
Definition: c.h:804
bool heapkeyspace
Definition: nbtree.h:765
#define MAXALIGN(LEN)
Definition: c.h:757
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
int Buffer
Definition: buf.h:23
BTStack _bt_search(Relation rel, BTScanInsert key, Buffer *bufP, int access, Snapshot snapshot)
Definition: nbtsearch.c:101
Pointer Page
Definition: bufpage.h:78
#define IndexTupleSize(itup)
Definition: itup.h:71

◆ bt_target_page_check()

static void bt_target_page_check ( BtreeCheckState state)
static

Definition at line 1045 of file verify_nbtree.c.

References _bt_check_natts(), bloom_add_element(), bt_child_check(), bt_child_highkey_check(), bt_mkscankey_pivotsearch(), bt_normalize_tuple(), bt_posting_plain_tuple(), bt_right_page_check_scankey(), bt_rootdescend(), BTMaxItemSize, BTMaxItemSizeNoHeapTid, BTPageOpaqueData::btpo_level, BTreeTupleGetHeapTID(), BTreeTupleGetMaxHeapTID(), BTreeTupleGetNAtts, BTreeTupleGetNPosting(), BTreeTupleGetPointsToTID(), BTreeTupleGetPostingN(), BTreeTupleIsPosting(), CHECK_FOR_INTERRUPTS, DEBUG2, elog, ereport, errcode(), errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, BtreeCheckState::filter, BtreeCheckState::heapallindexed, BtreeCheckState::heapkeyspace, BTScanInsertData::heapkeyspace, i, IndexTupleSize, InvalidOffsetNumber, invariant_g_offset(), invariant_l_offset(), invariant_leq_offset(), ItemIdGetLength, ItemIdIsDead, ItemPointerCompare(), ItemPointerCopy, ItemPointerGetBlockNumber, ItemPointerGetBlockNumberNoCheck, ItemPointerGetOffsetNumber, ItemPointerGetOffsetNumberNoCheck, LSN_FORMAT_ARGS, offset_is_negative_infinity(), OffsetNumberNext, P_FIRSTDATAKEY, P_HIKEY, P_IGNORE, P_ISLEAF, P_RIGHTMOST, PageGetItem, PageGetItemIdCareful(), PageGetMaxOffsetNumber, PageGetSpecialPointer, palloc_btree_page(), pfree(), psprintf(), BtreeCheckState::readonly, BtreeCheckState::rel, RelationGetRelationName, BtreeCheckState::rootdescend, BTScanInsertData::scantid, BtreeCheckState::target, BtreeCheckState::targetblock, and BtreeCheckState::targetlsn.

Referenced by bt_check_level_from_leftmost().

1046 {
1047  OffsetNumber offset;
1048  OffsetNumber max;
1049  BTPageOpaque topaque;
1050 
1051  topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
1052  max = PageGetMaxOffsetNumber(state->target);
1053 
1054  elog(DEBUG2, "verifying %u items on %s block %u", max,
1055  P_ISLEAF(topaque) ? "leaf" : "internal", state->targetblock);
1056 
1057  /*
1058  * Check the number of attributes in high key. Note, rightmost page
1059  * doesn't contain a high key, so nothing to check
1060  */
1061  if (!P_RIGHTMOST(topaque))
1062  {
1063  ItemId itemid;
1064  IndexTuple itup;
1065 
1066  /* Verify line pointer before checking tuple */
1067  itemid = PageGetItemIdCareful(state, state->targetblock,
1068  state->target, P_HIKEY);
1069  if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target,
1070  P_HIKEY))
1071  {
1072  itup = (IndexTuple) PageGetItem(state->target, itemid);
1073  ereport(ERROR,
1074  (errcode(ERRCODE_INDEX_CORRUPTED),
1075  errmsg("wrong number of high key index tuple attributes in index \"%s\"",
1076  RelationGetRelationName(state->rel)),
1077  errdetail_internal("Index block=%u natts=%u block type=%s page lsn=%X/%X.",
1078  state->targetblock,
1079  BTreeTupleGetNAtts(itup, state->rel),
1080  P_ISLEAF(topaque) ? "heap" : "index",
1081  LSN_FORMAT_ARGS(state->targetlsn))));
1082  }
1083  }
1084 
1085  /*
1086  * Loop over page items, starting from first non-highkey item, not high
1087  * key (if any). Most tests are not performed for the "negative infinity"
1088  * real item (if any).
1089  */
1090  for (offset = P_FIRSTDATAKEY(topaque);
1091  offset <= max;
1092  offset = OffsetNumberNext(offset))
1093  {
1094  ItemId itemid;
1095  IndexTuple itup;
1096  size_t tupsize;
1097  BTScanInsert skey;
1098  bool lowersizelimit;
1099  ItemPointer scantid;
1100 
1102 
1103  itemid = PageGetItemIdCareful(state, state->targetblock,
1104  state->target, offset);
1105  itup = (IndexTuple) PageGetItem(state->target, itemid);
1106  tupsize = IndexTupleSize(itup);
1107 
1108  /*
1109  * lp_len should match the IndexTuple reported length exactly, since
1110  * lp_len is completely redundant in indexes, and both sources of
1111  * tuple length are MAXALIGN()'d. nbtree does not use lp_len all that
1112  * frequently, and is surprisingly tolerant of corrupt lp_len fields.
1113  */
1114  if (tupsize != ItemIdGetLength(itemid))
1115  ereport(ERROR,
1116  (errcode(ERRCODE_INDEX_CORRUPTED),
1117  errmsg("index tuple size does not equal lp_len in index \"%s\"",
1118  RelationGetRelationName(state->rel)),
1119  errdetail_internal("Index tid=(%u,%u) tuple size=%zu lp_len=%u page lsn=%X/%X.",
1120  state->targetblock, offset,
1121  tupsize, ItemIdGetLength(itemid),
1122  LSN_FORMAT_ARGS(state->targetlsn)),
1123  errhint("This could be a torn page problem.")));
1124 
1125  /* Check the number of index tuple attributes */
1126  if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target,
1127  offset))
1128  {
1129  ItemPointer tid;
1130  char *itid,
1131  *htid;
1132 
1133  itid = psprintf("(%u,%u)", state->targetblock, offset);
1134  tid = BTreeTupleGetPointsToTID(itup);
1135  htid = psprintf("(%u,%u)",
1138 
1139  ereport(ERROR,
1140  (errcode(ERRCODE_INDEX_CORRUPTED),
1141  errmsg("wrong number of index tuple attributes in index \"%s\"",
1142  RelationGetRelationName(state->rel)),
1143  errdetail_internal("Index tid=%s natts=%u points to %s tid=%s page lsn=%X/%X.",
1144  itid,
1145  BTreeTupleGetNAtts(itup, state->rel),
1146  P_ISLEAF(topaque) ? "heap" : "index",
1147  htid,
1148  LSN_FORMAT_ARGS(state->targetlsn))));
1149  }
1150 
1151  /*
1152  * Don't try to generate scankey using "negative infinity" item on
1153  * internal pages. They are always truncated to zero attributes.
1154  */
1155  if (offset_is_negative_infinity(topaque, offset))
1156  {
1157  /*
1158  * We don't call bt_child_check() for "negative infinity" items.
1159  * But if we're performing downlink connectivity check, we do it
1160  * for every item including "negative infinity" one.
1161  */
1162  if (!P_ISLEAF(topaque) && state->readonly)
1163  {
1164  bt_child_highkey_check(state,
1165  offset,
1166  NULL,
1167  topaque->btpo_level);
1168  }
1169  continue;
1170  }
1171 
1172  /*
1173  * Readonly callers may optionally verify that non-pivot tuples can
1174  * each be found by an independent search that starts from the root.
1175  * Note that we deliberately don't do individual searches for each
1176  * TID, since the posting list itself is validated by other checks.
1177  */
1178  if (state->rootdescend && P_ISLEAF(topaque) &&
1179  !bt_rootdescend(state, itup))
1180  {
1182  char *itid,
1183  *htid;
1184 
1185  itid = psprintf("(%u,%u)", state->targetblock, offset);
1186  htid = psprintf("(%u,%u)", ItemPointerGetBlockNumber(tid),
1188 
1189  ereport(ERROR,
1190  (errcode(ERRCODE_INDEX_CORRUPTED),
1191  errmsg("could not find tuple using search from root page in index \"%s\"",
1192  RelationGetRelationName(state->rel)),
1193  errdetail_internal("Index tid=%s points to heap tid=%s page lsn=%X/%X.",
1194  itid, htid,
1195  LSN_FORMAT_ARGS(state->targetlsn))));
1196  }
1197 
1198  /*
1199  * If tuple is a posting list tuple, make sure posting list TIDs are
1200  * in order
1201  */
1202  if (BTreeTupleIsPosting(itup))
1203  {
1204  ItemPointerData last;
1205  ItemPointer current;
1206 
1207  ItemPointerCopy(BTreeTupleGetHeapTID(itup), &last);
1208 
1209  for (int i = 1; i < BTreeTupleGetNPosting(itup); i++)
1210  {
1211 
1212  current = BTreeTupleGetPostingN(itup, i);
1213 
1214  if (ItemPointerCompare(current, &last) <= 0)
1215  {
1216  char *itid = psprintf("(%u,%u)", state->targetblock, offset);
1217 
1218  ereport(ERROR,
1219  (errcode(ERRCODE_INDEX_CORRUPTED),
1220  errmsg_internal("posting list contains misplaced TID in index \"%s\"",
1221  RelationGetRelationName(state->rel)),
1222  errdetail_internal("Index tid=%s posting list offset=%d page lsn=%X/%X.",
1223  itid, i,
1224  LSN_FORMAT_ARGS(state->targetlsn))));
1225  }
1226 
1227  ItemPointerCopy(current, &last);
1228  }
1229  }
1230 
1231  /* Build insertion scankey for current page offset */
1232  skey = bt_mkscankey_pivotsearch(state->rel, itup);
1233 
1234  /*
1235  * Make sure tuple size does not exceed the relevant BTREE_VERSION
1236  * specific limit.
1237  *
1238  * BTREE_VERSION 4 (which introduced heapkeyspace rules) requisitioned
1239  * a small amount of space from BTMaxItemSize() in order to ensure
1240  * that suffix truncation always has enough space to add an explicit
1241  * heap TID back to a tuple -- we pessimistically assume that every
1242  * newly inserted tuple will eventually need to have a heap TID
1243  * appended during a future leaf page split, when the tuple becomes
1244  * the basis of the new high key (pivot tuple) for the leaf page.
1245  *
1246  * Since the reclaimed space is reserved for that purpose, we must not
1247  * enforce the slightly lower limit when the extra space has been used
1248  * as intended. In other words, there is only a cross-version
1249  * difference in the limit on tuple size within leaf pages.
1250  *
1251  * Still, we're particular about the details within BTREE_VERSION 4
1252  * internal pages. Pivot tuples may only use the extra space for its
1253  * designated purpose. Enforce the lower limit for pivot tuples when
1254  * an explicit heap TID isn't actually present. (In all other cases
1255  * suffix truncation is guaranteed to generate a pivot tuple that's no
1256  * larger than the firstright tuple provided to it by its caller.)
1257  */
1258  lowersizelimit = skey->heapkeyspace &&
1259  (P_ISLEAF(topaque) || BTreeTupleGetHeapTID(itup) == NULL);
1260  if (tupsize > (lowersizelimit ? BTMaxItemSize(state->target) :
1261  BTMaxItemSizeNoHeapTid(state->target)))
1262  {
1264  char *itid,
1265  *htid;
1266 
1267  itid = psprintf("(%u,%u)", state->targetblock, offset);
1268  htid = psprintf("(%u,%u)",
1271 
1272  ereport(ERROR,
1273  (errcode(ERRCODE_INDEX_CORRUPTED),
1274  errmsg("index row size %zu exceeds maximum for index \"%s\"",
1275  tupsize, RelationGetRelationName(state->rel)),
1276  errdetail_internal("Index tid=%s points to %s tid=%s page lsn=%X/%X.",
1277  itid,
1278  P_ISLEAF(topaque) ? "heap" : "index",
1279  htid,
1280  LSN_FORMAT_ARGS(state->targetlsn))));
1281  }
1282 
1283  /* Fingerprint leaf page tuples (those that point to the heap) */
1284  if (state->heapallindexed && P_ISLEAF(topaque) && !ItemIdIsDead(itemid))
1285  {
1286  IndexTuple norm;
1287 
1288  if (BTreeTupleIsPosting(itup))
1289  {
1290  /* Fingerprint all elements as distinct "plain" tuples */
1291  for (int i = 0; i < BTreeTupleGetNPosting(itup); i++)
1292  {
1293  IndexTuple logtuple;
1294 
1295  logtuple = bt_posting_plain_tuple(itup, i);
1296  norm = bt_normalize_tuple(state, logtuple);
1297  bloom_add_element(state->filter, (unsigned char *) norm,
1298  IndexTupleSize(norm));
1299  /* Be tidy */
1300  if (norm != logtuple)
1301  pfree(norm);
1302  pfree(logtuple);
1303  }
1304  }
1305  else
1306  {
1307  norm = bt_normalize_tuple(state, itup);
1308  bloom_add_element(state->filter, (unsigned char *) norm,
1309  IndexTupleSize(norm));
1310  /* Be tidy */
1311  if (norm != itup)
1312  pfree(norm);
1313  }
1314  }
1315 
1316  /*
1317  * * High key check *
1318  *
1319  * If there is a high key (if this is not the rightmost page on its
1320  * entire level), check that high key actually is upper bound on all
1321  * page items. If this is a posting list tuple, we'll need to set
1322  * scantid to be highest TID in posting list.
1323  *
1324  * We prefer to check all items against high key rather than checking
1325  * just the last and trusting that the operator class obeys the
1326  * transitive law (which implies that all previous items also
1327  * respected the high key invariant if they pass the item order
1328  * check).
1329  *
1330  * Ideally, we'd compare every item in the index against every other
1331  * item in the index, and not trust opclass obedience of the
1332  * transitive law to bridge the gap between children and their
1333  * grandparents (as well as great-grandparents, and so on). We don't
1334  * go to those lengths because that would be prohibitively expensive,
1335  * and probably not markedly more effective in practice.
1336  *
1337  * On the leaf level, we check that the key is <= the highkey.
1338  * However, on non-leaf levels we check that the key is < the highkey,
1339  * because the high key is "just another separator" rather than a copy
1340  * of some existing key item; we expect it to be unique among all keys
1341  * on the same level. (Suffix truncation will sometimes produce a
1342  * leaf highkey that is an untruncated copy of the lastleft item, but
1343  * never any other item, which necessitates weakening the leaf level
1344  * check to <=.)
1345  *
1346  * Full explanation for why a highkey is never truly a copy of another
1347  * item from the same level on internal levels:
1348  *
1349  * While the new left page's high key is copied from the first offset
1350  * on the right page during an internal page split, that's not the
1351  * full story. In effect, internal pages are split in the middle of
1352  * the firstright tuple, not between the would-be lastleft and
1353  * firstright tuples: the firstright key ends up on the left side as
1354  * left's new highkey, and the firstright downlink ends up on the
1355  * right side as right's new "negative infinity" item. The negative
1356  * infinity tuple is truncated to zero attributes, so we're only left
1357  * with the downlink. In other words, the copying is just an
1358  * implementation detail of splitting in the middle of a (pivot)
1359  * tuple. (See also: "Notes About Data Representation" in the nbtree
1360  * README.)
1361  */
1362  scantid = skey->scantid;
1363  if (state->heapkeyspace && BTreeTupleIsPosting(itup))
1364  skey->scantid = BTreeTupleGetMaxHeapTID(itup);
1365 
1366  if (!P_RIGHTMOST(topaque) &&
1367  !(P_ISLEAF(topaque) ? invariant_leq_offset(state, skey, P_HIKEY) :
1368  invariant_l_offset(state, skey, P_HIKEY)))
1369  {
1371  char *itid,
1372  *htid;
1373 
1374  itid = psprintf("(%u,%u)", state->targetblock, offset);
1375  htid = psprintf("(%u,%u)",
1378 
1379  ereport(ERROR,
1380  (errcode(ERRCODE_INDEX_CORRUPTED),
1381  errmsg("high key invariant violated for index \"%s\"",
1382  RelationGetRelationName(state->rel)),
1383  errdetail_internal("Index tid=%s points to %s tid=%s page lsn=%X/%X.",
1384  itid,
1385  P_ISLEAF(topaque) ? "heap" : "index",
1386  htid,
1387  LSN_FORMAT_ARGS(state->targetlsn))));
1388  }
1389  /* Reset, in case scantid was set to (itup) posting tuple's max TID */
1390  skey->scantid = scantid;
1391 
1392  /*
1393  * * Item order check *
1394  *
1395  * Check that items are stored on page in logical order, by checking
1396  * current item is strictly less than next item (if any).
1397  */
1398  if (OffsetNumberNext(offset) <= max &&
1399  !invariant_l_offset(state, skey, OffsetNumberNext(offset)))
1400  {
1401  ItemPointer tid;
1402  char *itid,
1403  *htid,
1404  *nitid,
1405  *nhtid;
1406 
1407  itid = psprintf("(%u,%u)", state->targetblock, offset);
1408  tid = BTreeTupleGetPointsToTID(itup);
1409  htid = psprintf("(%u,%u)",
1412  nitid = psprintf("(%u,%u)", state->targetblock,
1413  OffsetNumberNext(offset));
1414 
1415  /* Reuse itup to get pointed-to heap location of second item */
1416  itemid = PageGetItemIdCareful(state, state->targetblock,
1417  state->target,
1418  OffsetNumberNext(offset));
1419  itup = (IndexTuple) PageGetItem(state->target, itemid);
1420  tid = BTreeTupleGetPointsToTID(itup);
1421  nhtid = psprintf("(%u,%u)",
1424 
1425  ereport(ERROR,
1426  (errcode(ERRCODE_INDEX_CORRUPTED),
1427  errmsg("item order invariant violated for index \"%s\"",
1428  RelationGetRelationName(state->rel)),
1429  errdetail_internal("Lower index tid=%s (points to %s tid=%s) "
1430  "higher index tid=%s (points to %s tid=%s) "
1431  "page lsn=%X/%X.",
1432  itid,
1433  P_ISLEAF(topaque) ? "heap" : "index",
1434  htid,
1435  nitid,
1436  P_ISLEAF(topaque) ? "heap" : "index",
1437  nhtid,
1438  LSN_FORMAT_ARGS(state->targetlsn))));
1439  }
1440 
1441  /*
1442  * * Last item check *
1443  *
1444  * Check last item against next/right page's first data item's when
1445  * last item on page is reached. This additional check will detect
1446  * transposed pages iff the supposed right sibling page happens to
1447  * belong before target in the key space. (Otherwise, a subsequent
1448  * heap verification will probably detect the problem.)
1449  *
1450  * This check is similar to the item order check that will have
1451  * already been performed for every other "real" item on target page
1452  * when last item is checked. The difference is that the next item
1453  * (the item that is compared to target's last item) needs to come
1454  * from the next/sibling page. There may not be such an item
1455  * available from sibling for various reasons, though (e.g., target is
1456  * the rightmost page on level).
1457  */
1458  else if (offset == max)
1459  {
1460  BTScanInsert rightkey;
1461 
1462  /* Get item in next/right page */
1463  rightkey = bt_right_page_check_scankey(state);
1464 
1465  if (rightkey &&
1466  !invariant_g_offset(state, rightkey, max))
1467  {
1468  /*
1469  * As explained at length in bt_right_page_check_scankey(),
1470  * there is a known !readonly race that could account for
1471  * apparent violation of invariant, which we must check for
1472  * before actually proceeding with raising error. Our canary
1473  * condition is that target page was deleted.
1474  */
1475  if (!state->readonly)
1476  {
1477  /* Get fresh copy of target page */
1478  state->target = palloc_btree_page(state, state->targetblock);
1479  /* Note that we deliberately do not update target LSN */
1480  topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
1481 
1482  /*
1483  * All !readonly checks now performed; just return
1484  */
1485  if (P_IGNORE(topaque))
1486  return;
1487  }
1488 
1489  ereport(ERROR,
1490  (errcode(ERRCODE_INDEX_CORRUPTED),
1491  errmsg("cross page item order invariant violated for index \"%s\"",
1492  RelationGetRelationName(state->rel)),
1493  errdetail_internal("Last item on page tid=(%u,%u) page lsn=%X/%X.",
1494  state->targetblock, offset,
1495  LSN_FORMAT_ARGS(state->targetlsn))));
1496  }
1497  }
1498 
1499  /*
1500  * * Downlink check *
1501  *
1502  * Additional check of child items iff this is an internal page and
1503  * caller holds a ShareLock. This happens for every downlink (item)
1504  * in target excluding the negative-infinity downlink (again, this is
1505  * because it has no useful value to compare).
1506  */
1507  if (!P_ISLEAF(topaque) && state->readonly)
1508  bt_child_check(state, skey, offset);
1509  }
1510 
1511  /*
1512  * Special case bt_child_highkey_check() call
1513  *
1514  * We don't pass an real downlink, but we've to finish the level
1515  * processing. If condition is satisfied, we've already processed all the
1516  * downlinks from the target level. But there still might be pages to the
1517  * right of the child page pointer to by our rightmost downlink. And they
1518  * might have missing downlinks. This final call checks for them.
1519  */
1520  if (!P_ISLEAF(topaque) && P_RIGHTMOST(topaque) && state->readonly)
1521  {
1523  NULL, topaque->btpo_level);
1524  }
1525 }
int32 ItemPointerCompare(ItemPointer arg1, ItemPointer arg2)
Definition: itemptr.c:52
#define ItemPointerGetOffsetNumberNoCheck(pointer)
Definition: itemptr.h:108
static bool invariant_leq_offset(BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound)
static ItemPointer BTreeTupleGetPointsToTID(IndexTuple itup)
BlockNumber targetblock
Definition: verify_nbtree.c:93
int errhint(const char *fmt,...)
Definition: elog.c:1162
#define P_IGNORE(opaque)
Definition: nbtree.h:224
static ItemPointer BTreeTupleGetHeapTID(IndexTuple itup)
Definition: nbtree.h:612
ItemPointer scantid
Definition: nbtree.h:770
static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
void bloom_add_element(bloom_filter *filter, unsigned char *elem, size_t len)
Definition: bloomfilter.c:136
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
static IndexTuple bt_normalize_tuple(BtreeCheckState *state, IndexTuple itup)
#define BTMaxItemSizeNoHeapTid(page)
Definition: nbtree.h:168
int errcode(int sqlerrcode)
Definition: elog.c:704
static BTScanInsert bt_right_page_check_scankey(BtreeCheckState *state)
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define BTreeTupleGetNAtts(itup, rel)
Definition: nbtree.h:551
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
bloom_filter * filter
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
uint16 OffsetNumber
Definition: off.h:24
static bool invariant_l_offset(BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound)
static bool invariant_g_offset(BtreeCheckState *state, BTScanInsert key, OffsetNumber lowerbound)
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
XLogRecPtr targetlsn
Definition: verify_nbtree.c:95
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ERROR
Definition: elog.h:45
#define DEBUG2
Definition: elog.h:24
uint32 btpo_level
Definition: nbtree.h:66
IndexTupleData * IndexTuple
Definition: itup.h:53
#define RelationGetRelationName(relation)
Definition: rel.h:491
static ItemPointer BTreeTupleGetMaxHeapTID(IndexTuple itup)
Definition: nbtree.h:638
static BTScanInsert bt_mkscankey_pivotsearch(Relation rel, IndexTuple itup)
#define InvalidOffsetNumber
Definition: off.h:26
#define ereport(elevel,...)
Definition: elog.h:155
static ItemPointer BTreeTupleGetPostingN(IndexTuple posting, int n)
Definition: nbtree.h:518
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:466
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
bool _bt_check_natts(Relation rel, bool heapkeyspace, Page page, OffsetNumber offnum)
Definition: nbtutils.c:2466
static void bt_child_highkey_check(BtreeCheckState *state, OffsetNumber target_downlinkoffnum, Page loaded_child, uint32 target_level)
bool heapkeyspace
Definition: nbtree.h:765
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
static void bt_child_check(BtreeCheckState *state, BTScanInsert targetkey, OffsetNumber downlinkoffnum)
#define BTMaxItemSize(page)
Definition: nbtree.h:162
#define P_HIKEY
Definition: nbtree.h:348
static bool bt_rootdescend(BtreeCheckState *state, IndexTuple itup)
int errmsg(const char *fmt,...)
Definition: elog.c:915
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
#define ItemPointerGetBlockNumberNoCheck(pointer)
Definition: itemptr.h:89
#define elog(elevel,...)
Definition: elog.h:228
int i
static uint16 BTreeTupleGetNPosting(IndexTuple posting)
Definition: nbtree.h:492
static bool offset_is_negative_infinity(BTPageOpaque opaque, OffsetNumber offset)
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:218
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
#define IndexTupleSize(itup)
Definition: itup.h:71
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:161
static IndexTuple bt_posting_plain_tuple(IndexTuple itup, int n)
#define P_ISLEAF(opaque)
Definition: nbtree.h:219

◆ bt_tuple_present_callback()

static void bt_tuple_present_callback ( Relation  index,
ItemPointer  tid,
Datum values,
bool isnull,
bool  tupleIsAlive,
void *  checkstate 
)
static

Definition at line 2453 of file verify_nbtree.c.

References Assert, bloom_lacks_element(), bt_normalize_tuple(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errhint(), errmsg(), ERROR, BtreeCheckState::filter, BtreeCheckState::heapallindexed, BtreeCheckState::heaprel, BtreeCheckState::heaptuplespresent, index_form_tuple(), IndexTupleSize, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, pfree(), BtreeCheckState::readonly, BtreeCheckState::rel, RelationGetDescr, RelationGetRelationName, and IndexTupleData::t_tid.

Referenced by bt_check_every_level().

2455 {
2456  BtreeCheckState *state = (BtreeCheckState *) checkstate;
2457  IndexTuple itup,
2458  norm;
2459 
2460  Assert(state->heapallindexed);
2461 
2462  /* Generate a normalized index tuple for fingerprinting */
2463  itup = index_form_tuple(RelationGetDescr(index), values, isnull);
2464  itup->t_tid = *tid;
2465  norm = bt_normalize_tuple(state, itup);
2466 
2467  /* Probe Bloom filter -- tuple should be present */
2468  if (bloom_lacks_element(state->filter, (unsigned char *) norm,
2469  IndexTupleSize(norm)))
2470  ereport(ERROR,
2472  errmsg("heap tuple (%u,%u) from table \"%s\" lacks matching index tuple within index \"%s\"",
2473  ItemPointerGetBlockNumber(&(itup->t_tid)),
2476  RelationGetRelationName(state->rel)),
2477  !state->readonly
2478  ? errhint("Retrying verification using the function bt_index_parent_check() might provide a more specific error.")
2479  : 0));
2480 
2481  state->heaptuplespresent++;
2482  pfree(itup);
2483  /* Cannot leak memory here */
2484  if (norm != itup)
2485  pfree(norm);
2486 }
int errhint(const char *fmt,...)
Definition: elog.c:1162
#define RelationGetDescr(relation)
Definition: rel.h:483
static IndexTuple bt_normalize_tuple(BtreeCheckState *state, IndexTuple itup)
ItemPointerData t_tid
Definition: itup.h:37
int errcode(int sqlerrcode)
Definition: elog.c:704
bloom_filter * filter
IndexTuple index_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:47
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:45
Relation heaprel
Definition: verify_nbtree.c:72
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:804
Definition: regguts.h:317
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
bool bloom_lacks_element(bloom_filter *filter, unsigned char *elem, size_t len)
Definition: bloomfilter.c:158
#define IndexTupleSize(itup)
Definition: itup.h:71

◆ btree_index_checkable()

static void btree_index_checkable ( Relation  rel)
inlinestatic

Definition at line 348 of file verify_nbtree.c.

References ereport, errcode(), errdetail(), errmsg(), ERROR, RelationData::rd_index, RelationData::rd_rel, RELATION_IS_OTHER_TEMP, and RelationGetRelationName.

Referenced by bt_index_check_internal().

349 {
350  if (rel->rd_rel->relkind != RELKIND_INDEX ||
351  rel->rd_rel->relam != BTREE_AM_OID)
352  ereport(ERROR,
353  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
354  errmsg("only B-Tree indexes are supported as targets for verification"),
355  errdetail("Relation \"%s\" is not a B-Tree index.",
356  RelationGetRelationName(rel))));
357 
358  if (RELATION_IS_OTHER_TEMP(rel))
359  ereport(ERROR,
360  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
361  errmsg("cannot access temporary tables of other sessions"),
362  errdetail("Index \"%s\" is associated with temporary relation.",
363  RelationGetRelationName(rel))));
364 
365  if (!rel->rd_index->indisvalid)
366  ereport(ERROR,
367  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
368  errmsg("cannot check index \"%s\"",
370  errdetail("Index is not valid.")));
371 }
int errcode(int sqlerrcode)
Definition: elog.c:704
Form_pg_class rd_rel
Definition: rel.h:110
Form_pg_index rd_index
Definition: rel.h:175
#define ERROR
Definition: elog.h:45
int errdetail(const char *fmt,...)
Definition: elog.c:1048
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define ereport(elevel,...)
Definition: elog.h:155
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:594
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ btree_index_mainfork_expected()

static bool btree_index_mainfork_expected ( Relation  rel)
inlinestatic

Definition at line 381 of file verify_nbtree.c.

References ereport, errcode(), errmsg(), NOTICE, RelationData::rd_rel, RecoveryInProgress(), and RelationGetRelationName.

Referenced by bt_index_check_internal().

382 {
383  if (rel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED ||
385  return true;
386 
387  ereport(NOTICE,
388  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
389  errmsg("cannot verify unlogged index \"%s\" during recovery, skipping",
390  RelationGetRelationName(rel))));
391 
392  return false;
393 }
int errcode(int sqlerrcode)
Definition: elog.c:704
Form_pg_class rd_rel
Definition: rel.h:110
bool RecoveryInProgress(void)
Definition: xlog.c:8132
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define ereport(elevel,...)
Definition: elog.h:155
#define NOTICE
Definition: elog.h:37
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ BTreeTupleGetHeapTIDCareful()

static ItemPointer BTreeTupleGetHeapTIDCareful ( BtreeCheckState state,
IndexTuple  itup,
bool  nonpivot 
)
inlinestatic

Definition at line 3167 of file verify_nbtree.c.

References Assert, BTreeTupleGetHeapTID(), BTreeTupleIsPivot(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, BtreeCheckState::heapkeyspace, ItemPointerIsValid, BtreeCheckState::rel, RelationGetRelationName, and BtreeCheckState::targetblock.

Referenced by invariant_l_nontarget_offset(), and invariant_l_offset().

3169 {
3170  ItemPointer htid;
3171 
3172  /*
3173  * Caller determines whether this is supposed to be a pivot or non-pivot
3174  * tuple using page type and item offset number. Verify that tuple
3175  * metadata agrees with this.
3176  */
3177  Assert(state->heapkeyspace);
3178  if (BTreeTupleIsPivot(itup) && nonpivot)
3179  ereport(ERROR,
3180  (errcode(ERRCODE_INDEX_CORRUPTED),
3181  errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected pivot tuple",
3182  state->targetblock,
3183  RelationGetRelationName(state->rel))));
3184 
3185  if (!BTreeTupleIsPivot(itup) && !nonpivot)
3186  ereport(ERROR,
3187  (errcode(ERRCODE_INDEX_CORRUPTED),
3188  errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected non-pivot tuple",
3189  state->targetblock,
3190  RelationGetRelationName(state->rel))));
3191 
3192  htid = BTreeTupleGetHeapTID(itup);
3193  if (!ItemPointerIsValid(htid) && nonpivot)
3194  ereport(ERROR,
3195  (errcode(ERRCODE_INDEX_CORRUPTED),
3196  errmsg("block %u or its right sibling block or child block in index \"%s\" contains non-pivot tuple that lacks a heap TID",
3197  state->targetblock,
3198  RelationGetRelationName(state->rel))));
3199 
3200  return htid;
3201 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:82
BlockNumber targetblock
Definition: verify_nbtree.c:93
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:454
static ItemPointer BTreeTupleGetHeapTID(IndexTuple itup)
Definition: nbtree.h:612
int errcode(int sqlerrcode)
Definition: elog.c:704
#define ERROR
Definition: elog.h:45
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
#define Assert(condition)
Definition: c.h:804
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ BTreeTupleGetPointsToTID()

static ItemPointer BTreeTupleGetPointsToTID ( IndexTuple  itup)
inlinestatic

Definition at line 3215 of file verify_nbtree.c.

References BTreeTupleGetHeapTID(), BTreeTupleIsPivot(), and IndexTupleData::t_tid.

Referenced by bt_target_page_check().

3216 {
3217  /*
3218  * Rely on the assumption that !heapkeyspace internal page data items will
3219  * correctly return TID with downlink here -- BTreeTupleGetHeapTID() won't
3220  * recognize it as a pivot tuple, but everything still works out because
3221  * the t_tid field is still returned
3222  */
3223  if (!BTreeTupleIsPivot(itup))
3224  return BTreeTupleGetHeapTID(itup);
3225 
3226  /* Pivot tuple returns TID with downlink block (heapkeyspace variant) */
3227  return &itup->t_tid;
3228 }
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:454
static ItemPointer BTreeTupleGetHeapTID(IndexTuple itup)
Definition: nbtree.h:612
ItemPointerData t_tid
Definition: itup.h:37

◆ invariant_g_offset()

static bool invariant_g_offset ( BtreeCheckState state,
BTScanInsert  key,
OffsetNumber  lowerbound 
)
inlinestatic

Definition at line 2829 of file verify_nbtree.c.

References _bt_compare(), Assert, cmp(), BTScanInsertData::heapkeyspace, BTScanInsertData::pivotsearch, BtreeCheckState::rel, and BtreeCheckState::target.

Referenced by bt_target_page_check().

2831 {
2832  int32 cmp;
2833 
2834  Assert(key->pivotsearch);
2835 
2836  cmp = _bt_compare(state->rel, key, state->target, lowerbound);
2837 
2838  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2839  if (!key->heapkeyspace)
2840  return cmp >= 0;
2841 
2842  /*
2843  * No need to consider the possibility that scankey has attributes that we
2844  * need to force to be interpreted as negative infinity. _bt_compare() is
2845  * able to determine that scankey is greater than negative infinity. The
2846  * distinction between "==" and "<" isn't interesting here, since
2847  * corruption is indicated either way.
2848  */
2849  return cmp > 0;
2850 }
signed int int32
Definition: c.h:429
int32 _bt_compare(Relation rel, BTScanInsert key, Page page, OffsetNumber offnum)
Definition: nbtsearch.c:644
bool pivotsearch
Definition: nbtree.h:769
#define Assert(condition)
Definition: c.h:804
bool heapkeyspace
Definition: nbtree.h:765
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:747

◆ invariant_l_nontarget_offset()

static bool invariant_l_nontarget_offset ( BtreeCheckState state,
BTScanInsert  key,
BlockNumber  nontargetblock,
Page  nontarget,
OffsetNumber  upperbound 
)
inlinestatic

Definition at line 2865 of file verify_nbtree.c.

References _bt_compare(), Assert, BTreeTupleGetHeapTIDCareful(), BTreeTupleGetNKeyAtts, cmp(), BTScanInsertData::heapkeyspace, BTScanInsertData::keysz, P_FIRSTDATAKEY, P_ISLEAF, PageGetItem, PageGetItemIdCareful(), PageGetSpecialPointer, BTScanInsertData::pivotsearch, BtreeCheckState::rel, and BTScanInsertData::scantid.

Referenced by bt_child_check().

2868 {
2869  ItemId itemid;
2870  int32 cmp;
2871 
2872  Assert(key->pivotsearch);
2873 
2874  /* Verify line pointer before checking tuple */
2875  itemid = PageGetItemIdCareful(state, nontargetblock, nontarget,
2876  upperbound);
2877  cmp = _bt_compare(state->rel, key, nontarget, upperbound);
2878 
2879  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2880  if (!key->heapkeyspace)
2881  return cmp <= 0;
2882 
2883  /* See invariant_l_offset() for an explanation of this extra step */
2884  if (cmp == 0)
2885  {
2886  IndexTuple child;
2887  int uppnkeyatts;
2888  ItemPointer childheaptid;
2889  BTPageOpaque copaque;
2890  bool nonpivot;
2891 
2892  child = (IndexTuple) PageGetItem(nontarget, itemid);
2893  copaque = (BTPageOpaque) PageGetSpecialPointer(nontarget);
2894  nonpivot = P_ISLEAF(copaque) && upperbound >= P_FIRSTDATAKEY(copaque);
2895 
2896  /* Get number of keys + heap TID for child/non-target item */
2897  uppnkeyatts = BTreeTupleGetNKeyAtts(child, state->rel);
2898  childheaptid = BTreeTupleGetHeapTIDCareful(state, child, nonpivot);
2899 
2900  /* Heap TID is tiebreaker key attribute */
2901  if (key->keysz == uppnkeyatts)
2902  return key->scantid == NULL && childheaptid != NULL;
2903 
2904  return key->keysz < uppnkeyatts;
2905  }
2906 
2907  return cmp < 0;
2908 }
ItemPointer scantid
Definition: nbtree.h:770
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
signed int int32
Definition: c.h:429
IndexTupleData * IndexTuple
Definition: itup.h:53
int32 _bt_compare(Relation rel, BTScanInsert key, Page page, OffsetNumber offnum)
Definition: nbtsearch.c:644
static ItemPointer BTreeTupleGetHeapTIDCareful(BtreeCheckState *state, IndexTuple itup, bool nonpivot)
bool pivotsearch
Definition: nbtree.h:769
#define Assert(condition)
Definition: c.h:804
#define BTreeTupleGetNKeyAtts(itup, rel)
Definition: verify_nbtree.c:50
bool heapkeyspace
Definition: nbtree.h:765
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:747
#define P_ISLEAF(opaque)
Definition: nbtree.h:219

◆ invariant_l_offset()

static bool invariant_l_offset ( BtreeCheckState state,
BTScanInsert  key,
OffsetNumber  upperbound 
)
inlinestatic

Definition at line 2743 of file verify_nbtree.c.

References _bt_compare(), Assert, BTreeTupleGetHeapTIDCareful(), BTreeTupleGetNKeyAtts, cmp(), BTScanInsertData::heapkeyspace, invariant_leq_offset(), BTScanInsertData::keysz, P_FIRSTDATAKEY, P_ISLEAF, PageGetItem, PageGetItemIdCareful(), PageGetSpecialPointer, BTScanInsertData::pivotsearch, BtreeCheckState::rel, BTScanInsertData::scantid, BtreeCheckState::target, and BtreeCheckState::targetblock.

Referenced by bt_target_page_check().

2745 {
2746  ItemId itemid;
2747  int32 cmp;
2748 
2749  Assert(key->pivotsearch);
2750 
2751  /* Verify line pointer before checking tuple */
2752  itemid = PageGetItemIdCareful(state, state->targetblock, state->target,
2753  upperbound);
2754  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2755  if (!key->heapkeyspace)
2756  return invariant_leq_offset(state, key, upperbound);
2757 
2758  cmp = _bt_compare(state->rel, key, state->target, upperbound);
2759 
2760  /*
2761  * _bt_compare() is capable of determining that a scankey with a
2762  * filled-out attribute is greater than pivot tuples where the comparison
2763  * is resolved at a truncated attribute (value of attribute in pivot is
2764  * minus infinity). However, it is not capable of determining that a
2765  * scankey is _less than_ a tuple on the basis of a comparison resolved at
2766  * _scankey_ minus infinity attribute. Complete an extra step to simulate
2767  * having minus infinity values for omitted scankey attribute(s).
2768  */
2769  if (cmp == 0)
2770  {
2771  BTPageOpaque topaque;
2772  IndexTuple ritup;
2773  int uppnkeyatts;
2774  ItemPointer rheaptid;
2775  bool nonpivot;
2776 
2777  ritup = (IndexTuple) PageGetItem(state->target, itemid);
2778  topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
2779  nonpivot = P_ISLEAF(topaque) && upperbound >= P_FIRSTDATAKEY(topaque);
2780 
2781  /* Get number of keys + heap TID for item to the right */
2782  uppnkeyatts = BTreeTupleGetNKeyAtts(ritup, state->rel);
2783  rheaptid = BTreeTupleGetHeapTIDCareful(state, ritup, nonpivot);
2784 
2785  /* Heap TID is tiebreaker key attribute */
2786  if (key->keysz == uppnkeyatts)
2787  return key->scantid == NULL && rheaptid != NULL;
2788 
2789  return key->keysz < uppnkeyatts;
2790  }
2791 
2792  return cmp < 0;
2793 }
static bool invariant_leq_offset(BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound)
BlockNumber targetblock
Definition: verify_nbtree.c:93
ItemPointer scantid
Definition: nbtree.h:770
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
signed int int32
Definition: c.h:429
IndexTupleData * IndexTuple
Definition: itup.h:53
int32 _bt_compare(Relation rel, BTScanInsert key, Page page, OffsetNumber offnum)
Definition: nbtsearch.c:644
static ItemPointer BTreeTupleGetHeapTIDCareful(BtreeCheckState *state, IndexTuple itup, bool nonpivot)
bool pivotsearch
Definition: nbtree.h:769
#define Assert(condition)
Definition: c.h:804
#define BTreeTupleGetNKeyAtts(itup, rel)
Definition: verify_nbtree.c:50
bool heapkeyspace
Definition: nbtree.h:765
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:747
#define P_ISLEAF(opaque)
Definition: nbtree.h:219

◆ invariant_leq_offset()

static bool invariant_leq_offset ( BtreeCheckState state,
BTScanInsert  key,
OffsetNumber  upperbound 
)
inlinestatic

Definition at line 2806 of file verify_nbtree.c.

References _bt_compare(), Assert, cmp(), BTScanInsertData::pivotsearch, BtreeCheckState::rel, and BtreeCheckState::target.

Referenced by bt_target_page_check(), and invariant_l_offset().

2808 {
2809  int32 cmp;
2810 
2811  Assert(key->pivotsearch);
2812 
2813  cmp = _bt_compare(state->rel, key, state->target, upperbound);
2814 
2815  return cmp <= 0;
2816 }
signed int int32
Definition: c.h:429
int32 _bt_compare(Relation rel, BTScanInsert key, Page page, OffsetNumber offnum)
Definition: nbtsearch.c:644
bool pivotsearch
Definition: nbtree.h:769
#define Assert(condition)
Definition: c.h:804
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:747

◆ offset_is_negative_infinity()

static bool offset_is_negative_infinity ( BTPageOpaque  opaque,
OffsetNumber  offset 
)
inlinestatic

Definition at line 2708 of file verify_nbtree.c.

References P_FIRSTDATAKEY, and P_ISLEAF.

Referenced by bt_child_check(), bt_child_highkey_check(), and bt_target_page_check().

2709 {
2710  /*
2711  * For internal pages only, the first item after high key, if any, is
2712  * negative infinity item. Internal pages always have a negative infinity
2713  * item, whereas leaf pages never have one. This implies that negative
2714  * infinity item is either first or second line item, or there is none
2715  * within page.
2716  *
2717  * Negative infinity items are a special case among pivot tuples. They
2718  * always have zero attributes, while all other pivot tuples always have
2719  * nkeyatts attributes.
2720  *
2721  * Right-most pages don't have a high key, but could be said to
2722  * conceptually have a "positive infinity" high key. Thus, there is a
2723  * symmetry between down link items in parent pages, and high keys in
2724  * children. Together, they represent the part of the key space that
2725  * belongs to each page in the index. For example, all children of the
2726  * root page will have negative infinity as a lower bound from root
2727  * negative infinity downlink, and positive infinity as an upper bound
2728  * (implicitly, from "imaginary" positive infinity high key in root).
2729  */
2730  return !P_ISLEAF(opaque) && offset == P_FIRSTDATAKEY(opaque);
2731 }
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
#define P_ISLEAF(opaque)
Definition: nbtree.h:219

◆ PageGetItemIdCareful()

static ItemId PageGetItemIdCareful ( BtreeCheckState state,
BlockNumber  block,
Page  page,
OffsetNumber  offset 
)
static

Definition at line 3127 of file verify_nbtree.c.

References ereport, errcode(), errdetail_internal(), errmsg(), ERROR, ItemIdGetFlags, ItemIdGetLength, ItemIdGetOffset, ItemIdIsRedirected, ItemIdIsUsed, PageGetItemId, BtreeCheckState::rel, and RelationGetRelationName.

Referenced by bt_check_level_from_leftmost(), bt_child_check(), bt_child_highkey_check(), bt_downlink_missing_check(), bt_right_page_check_scankey(), bt_target_page_check(), invariant_l_nontarget_offset(), and invariant_l_offset().

3129 {
3130  ItemId itemid = PageGetItemId(page, offset);
3131 
3132  if (ItemIdGetOffset(itemid) + ItemIdGetLength(itemid) >
3133  BLCKSZ - sizeof(BTPageOpaqueData))
3134  ereport(ERROR,
3135  (errcode(ERRCODE_INDEX_CORRUPTED),
3136  errmsg("line pointer points past end of tuple space in index \"%s\"",
3137  RelationGetRelationName(state->rel)),
3138  errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.",
3139  block, offset, ItemIdGetOffset(itemid),
3140  ItemIdGetLength(itemid),
3141  ItemIdGetFlags(itemid))));
3142 
3143  /*
3144  * Verify that line pointer isn't LP_REDIRECT or LP_UNUSED, since nbtree
3145  * never uses either. Verify that line pointer has storage, too, since
3146  * even LP_DEAD items should within nbtree.
3147  */
3148  if (ItemIdIsRedirected(itemid) || !ItemIdIsUsed(itemid) ||
3149  ItemIdGetLength(itemid) == 0)
3150  ereport(ERROR,
3151  (errcode(ERRCODE_INDEX_CORRUPTED),
3152  errmsg("invalid line pointer storage in index \"%s\"",
3153  RelationGetRelationName(state->rel)),
3154  errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.",
3155  block, offset, ItemIdGetOffset(itemid),
3156  ItemIdGetLength(itemid),
3157  ItemIdGetFlags(itemid))));
3158 
3159  return itemid;
3160 }
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
int errcode(int sqlerrcode)
Definition: elog.c:704
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1075
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ERROR
Definition: elog.h:45
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define ItemIdGetOffset(itemId)
Definition: itemid.h:65
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
#define ItemIdGetFlags(itemId)
Definition: itemid.h:71
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ palloc_btree_page()

static Page palloc_btree_page ( BtreeCheckState state,
BlockNumber  blocknum 
)
static

Definition at line 2925 of file verify_nbtree.c.

References _bt_checkpage(), BT_READ, BTMetaPageData::btm_magic, BTMetaPageData::btm_version, BTPageGetMeta, BTPageOpaqueData::btpo_level, BTREE_MAGIC, BTREE_METAPAGE, BTREE_MIN_VERSION, BTREE_VERSION, BufferGetPage, BtreeCheckState::checkstrategy, ereport, errcode(), errhint(), errmsg(), errmsg_internal(), ERROR, LockBuffer(), MAIN_FORKNUM, MaxIndexTuplesPerPage, P_FIRSTDATAKEY, P_HAS_FULLXID, P_HAS_GARBAGE, P_HIKEY, P_ISDELETED, P_ISHALFDEAD, P_ISLEAF, P_ISMETA, P_RIGHTMOST, PageGetMaxOffsetNumber, PageGetSpecialPointer, palloc(), RBM_NORMAL, ReadBufferExtended(), BtreeCheckState::rel, RelationGetRelationName, and UnlockReleaseBuffer().

Referenced by bt_check_every_level(), bt_check_level_from_leftmost(), bt_child_check(), bt_child_highkey_check(), bt_downlink_missing_check(), bt_right_page_check_scankey(), and bt_target_page_check().

2926 {
2927  Buffer buffer;
2928  Page page;
2929  BTPageOpaque opaque;
2930  OffsetNumber maxoffset;
2931 
2932  page = palloc(BLCKSZ);
2933 
2934  /*
2935  * We copy the page into local storage to avoid holding pin on the buffer
2936  * longer than we must.
2937  */
2938  buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum, RBM_NORMAL,
2939  state->checkstrategy);
2940  LockBuffer(buffer, BT_READ);
2941 
2942  /*
2943  * Perform the same basic sanity checking that nbtree itself performs for
2944  * every page:
2945  */
2946  _bt_checkpage(state->rel, buffer);
2947 
2948  /* Only use copy of page in palloc()'d memory */
2949  memcpy(page, BufferGetPage(buffer), BLCKSZ);
2950  UnlockReleaseBuffer(buffer);
2951 
2952  opaque = (BTPageOpaque) PageGetSpecialPointer(page);
2953 
2954  if (P_ISMETA(opaque) && blocknum != BTREE_METAPAGE)
2955  ereport(ERROR,
2956  (errcode(ERRCODE_INDEX_CORRUPTED),
2957  errmsg("invalid meta page found at block %u in index \"%s\"",
2958  blocknum, RelationGetRelationName(state->rel))));
2959 
2960  /* Check page from block that ought to be meta page */
2961  if (blocknum == BTREE_METAPAGE)
2962  {
2963  BTMetaPageData *metad = BTPageGetMeta(page);
2964 
2965  if (!P_ISMETA(opaque) ||
2966  metad->btm_magic != BTREE_MAGIC)
2967  ereport(ERROR,
2968  (errcode(ERRCODE_INDEX_CORRUPTED),
2969  errmsg("index \"%s\" meta page is corrupt",
2970  RelationGetRelationName(state->rel))));
2971 
2972  if (metad->btm_version < BTREE_MIN_VERSION ||
2973  metad->btm_version > BTREE_VERSION)
2974  ereport(ERROR,
2975  (errcode(ERRCODE_INDEX_CORRUPTED),
2976  errmsg("version mismatch in index \"%s\": file version %d, "
2977  "current version %d, minimum supported version %d",
2978  RelationGetRelationName(state->rel),
2979  metad->btm_version, BTREE_VERSION,
2980  BTREE_MIN_VERSION)));
2981 
2982  /* Finished with metapage checks */
2983  return page;
2984  }
2985 
2986  /*
2987  * Deleted pages that still use the old 32-bit XID representation have no
2988  * sane "level" field because they type pun the field, but all other pages
2989  * (including pages deleted on Postgres 14+) have a valid value.
2990  */
2991  if (!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque))
2992  {
2993  /* Okay, no reason not to trust btpo_level field from page */
2994 
2995  if (P_ISLEAF(opaque) && opaque->btpo_level != 0)
2996  ereport(ERROR,
2997  (errcode(ERRCODE_INDEX_CORRUPTED),
2998  errmsg_internal("invalid leaf page level %u for block %u in index \"%s\"",
2999  opaque->btpo_level, blocknum,
3000  RelationGetRelationName(state->rel))));
3001 
3002  if (!P_ISLEAF(opaque) && opaque->btpo_level == 0)
3003  ereport(ERROR,
3004  (errcode(ERRCODE_INDEX_CORRUPTED),
3005  errmsg_internal("invalid internal page level 0 for block %u in index \"%s\"",
3006  blocknum,
3007  RelationGetRelationName(state->rel))));
3008  }
3009 
3010  /*
3011  * Sanity checks for number of items on page.
3012  *
3013  * As noted at the beginning of _bt_binsrch(), an internal page must have
3014  * children, since there must always be a negative infinity downlink
3015  * (there may also be a highkey). In the case of non-rightmost leaf
3016  * pages, there must be at least a highkey. The exceptions are deleted
3017  * pages, which contain no items.
3018  *
3019  * This is correct when pages are half-dead, since internal pages are
3020  * never half-dead, and leaf pages must have a high key when half-dead
3021  * (the rightmost page can never be deleted). It's also correct with
3022  * fully deleted pages: _bt_unlink_halfdead_page() doesn't change anything
3023  * about the target page other than setting the page as fully dead, and
3024  * setting its xact field. In particular, it doesn't change the sibling
3025  * links in the deletion target itself, since they're required when index
3026  * scans land on the deletion target, and then need to move right (or need
3027  * to move left, in the case of backward index scans).
3028  */
3029  maxoffset = PageGetMaxOffsetNumber(page);
3030  if (maxoffset > MaxIndexTuplesPerPage)
3031  ereport(ERROR,
3032  (errcode(ERRCODE_INDEX_CORRUPTED),
3033  errmsg("Number of items on block %u of index \"%s\" exceeds MaxIndexTuplesPerPage (%u)",
3034  blocknum, RelationGetRelationName(state->rel),
3036 
3037  if (!P_ISLEAF(opaque) && !P_ISDELETED(opaque) && maxoffset < P_FIRSTDATAKEY(opaque))
3038  ereport(ERROR,
3039  (errcode(ERRCODE_INDEX_CORRUPTED),
3040  errmsg("internal block %u in index \"%s\" lacks high key and/or at least one downlink",
3041  blocknum, RelationGetRelationName(state->rel))));
3042 
3043  if (P_ISLEAF(opaque) && !P_ISDELETED(opaque) && !P_RIGHTMOST(opaque) && maxoffset < P_HIKEY)
3044  ereport(ERROR,
3045  (errcode(ERRCODE_INDEX_CORRUPTED),
3046  errmsg("non-rightmost leaf block %u in index \"%s\" lacks high key item",
3047  blocknum, RelationGetRelationName(state->rel))));
3048 
3049  /*
3050  * In general, internal pages are never marked half-dead, except on
3051  * versions of Postgres prior to 9.4, where it can be valid transient
3052  * state. This state is nonetheless treated as corruption by VACUUM on
3053  * from version 9.4 on, so do the same here. See _bt_pagedel() for full
3054  * details.
3055  */
3056  if (!P_ISLEAF(opaque) && P_ISHALFDEAD(opaque))
3057  ereport(ERROR,
3058  (errcode(ERRCODE_INDEX_CORRUPTED),
3059  errmsg("internal page block %u in index \"%s\" is half-dead",
3060  blocknum, RelationGetRelationName(state->rel)),
3061  errhint("This can be caused by an interrupted VACUUM in version 9.3 or older, before upgrade. Please REINDEX it.")));
3062 
3063  /*
3064  * Check that internal pages have no garbage items, and that no page has
3065  * an invalid combination of deletion-related page level flags
3066  */
3067  if (!P_ISLEAF(opaque) && P_HAS_GARBAGE(opaque))
3068  ereport(ERROR,
3069  (errcode(ERRCODE_INDEX_CORRUPTED),
3070  errmsg_internal("internal page block %u in index \"%s\" has garbage items",
3071  blocknum, RelationGetRelationName(state->rel))));
3072 
3073  if (P_HAS_FULLXID(opaque) && !P_ISDELETED(opaque))
3074  ereport(ERROR,
3075  (errcode(ERRCODE_INDEX_CORRUPTED),
3076  errmsg_internal("full transaction id page flag appears in non-deleted block %u in index \"%s\"",
3077  blocknum, RelationGetRelationName(state->rel))));
3078 
3079  if (P_ISDELETED(opaque) && P_ISHALFDEAD(opaque))
3080  ereport(ERROR,
3081  (errcode(ERRCODE_INDEX_CORRUPTED),
3082  errmsg_internal("deleted page block %u in index \"%s\" is half-dead",
3083  blocknum, RelationGetRelationName(state->rel))));
3084 
3085  return page;
3086 }
int errhint(const char *fmt,...)
Definition: elog.c:1162
uint32 btm_version
Definition: nbtree.h:104
#define BTREE_VERSION
Definition: nbtree.h:148
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:350
uint32 btm_magic
Definition: nbtree.h:103
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:666
#define P_HAS_GARBAGE(opaque)
Definition: nbtree.h:225
int errcode(int sqlerrcode)
Definition: elog.c:704
BufferAccessStrategy checkstrategy
Definition: verify_nbtree.c:84
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
#define P_HAS_FULLXID(opaque)
Definition: nbtree.h:227
uint16 OffsetNumber
Definition: off.h:24
#define P_ISMETA(opaque)
Definition: nbtree.h:222
#define BT_READ
Definition: nbtree.h:693
#define BTREE_MAGIC
Definition: nbtree.h:147
void _bt_checkpage(Relation rel, Buffer buf)
Definition: nbtpage.c:755
#define P_ISHALFDEAD(opaque)
Definition: nbtree.h:223
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3723
#define ERROR
Definition: elog.h:45
#define BTPageGetMeta(p)
Definition: nbtree.h:119
uint32 btpo_level
Definition: nbtree.h:66
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
#define BTREE_METAPAGE
Definition: nbtree.h:146
#define P_ISDELETED(opaque)
Definition: nbtree.h:221
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3939
#define BTREE_MIN_VERSION
Definition: nbtree.h:149
#define ereport(elevel,...)
Definition: elog.h:155
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
#define PageGetSpecialPointer(page)
Definition: bufpage.h:326
#define P_HIKEY
Definition: nbtree.h:348
#define MaxIndexTuplesPerPage
Definition: itup.h:145
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:915
int Buffer
Definition: buf.h:23
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:218
Pointer Page
Definition: bufpage.h:78
#define P_ISLEAF(opaque)
Definition: nbtree.h:219

◆ PG_FUNCTION_INFO_V1() [1/2]

PG_FUNCTION_INFO_V1 ( bt_index_check  )

◆ PG_FUNCTION_INFO_V1() [2/2]

PG_FUNCTION_INFO_V1 ( bt_index_parent_check  )

Variable Documentation

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 43 of file verify_nbtree.c.