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 418 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().

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

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

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

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

2235 {
2237  ItemId itemid;
2238  IndexTuple itup;
2239  Page child;
2240  BTPageOpaque copaque;
2241  uint32 level;
2242  BlockNumber childblk;
2243  XLogRecPtr pagelsn;
2244 
2245  Assert(state->readonly);
2246  Assert(!P_IGNORE(opaque));
2247 
2248  /* No next level up with downlinks to fingerprint from the true root */
2249  if (P_ISROOT(opaque))
2250  return;
2251 
2252  pagelsn = PageGetLSN(page);
2253 
2254  /*
2255  * Incomplete (interrupted) page splits can account for the lack of a
2256  * downlink. Some inserting transaction should eventually complete the
2257  * page split in passing, when it notices that the left sibling page is
2258  * P_INCOMPLETE_SPLIT().
2259  *
2260  * In general, VACUUM is not prepared for there to be no downlink to a
2261  * page that it deletes. This is the main reason why the lack of a
2262  * downlink can be reported as corruption here. It's not obvious that an
2263  * invalid missing downlink can result in wrong answers to queries,
2264  * though, since index scans that land on the child may end up
2265  * consistently moving right. The handling of concurrent page splits (and
2266  * page deletions) within _bt_moveright() cannot distinguish
2267  * inconsistencies that last for a moment from inconsistencies that are
2268  * permanent and irrecoverable.
2269  *
2270  * VACUUM isn't even prepared to delete pages that have no downlink due to
2271  * an incomplete page split, but it can detect and reason about that case
2272  * by design, so it shouldn't be taken to indicate corruption. See
2273  * _bt_pagedel() for full details.
2274  */
2275  if (rightsplit)
2276  {
2277  ereport(DEBUG1,
2278  (errcode(ERRCODE_NO_DATA),
2279  errmsg_internal("harmless interrupted page split detected in index \"%s\"",
2280  RelationGetRelationName(state->rel)),
2281  errdetail_internal("Block=%u level=%u left sibling=%u page lsn=%X/%X.",
2282  blkno, opaque->btpo_level,
2283  opaque->btpo_prev,
2284  LSN_FORMAT_ARGS(pagelsn))));
2285  return;
2286  }
2287 
2288  /*
2289  * Page under check is probably the "top parent" of a multi-level page
2290  * deletion. We'll need to descend the subtree to make sure that
2291  * descendant pages are consistent with that, though.
2292  *
2293  * If the page (which must be non-ignorable) is a leaf page, then clearly
2294  * it can't be the top parent. The lack of a downlink is probably a
2295  * symptom of a broad problem that could just as easily cause
2296  * inconsistencies anywhere else.
2297  */
2298  if (P_ISLEAF(opaque))
2299  ereport(ERROR,
2300  (errcode(ERRCODE_INDEX_CORRUPTED),
2301  errmsg("leaf index block lacks downlink in index \"%s\"",
2302  RelationGetRelationName(state->rel)),
2303  errdetail_internal("Block=%u page lsn=%X/%X.",
2304  blkno,
2305  LSN_FORMAT_ARGS(pagelsn))));
2306 
2307  /* Descend from the given page, which is an internal page */
2308  elog(DEBUG1, "checking for interrupted multi-level deletion due to missing downlink in index \"%s\"",
2309  RelationGetRelationName(state->rel));
2310 
2311  level = opaque->btpo_level;
2312  itemid = PageGetItemIdCareful(state, blkno, page, P_FIRSTDATAKEY(opaque));
2313  itup = (IndexTuple) PageGetItem(page, itemid);
2314  childblk = BTreeTupleGetDownLink(itup);
2315  for (;;)
2316  {
2318 
2319  child = palloc_btree_page(state, childblk);
2320  copaque = (BTPageOpaque) PageGetSpecialPointer(child);
2321 
2322  if (P_ISLEAF(copaque))
2323  break;
2324 
2325  /* Do an extra sanity check in passing on internal pages */
2326  if (copaque->btpo_level != level - 1)
2327  ereport(ERROR,
2328  (errcode(ERRCODE_INDEX_CORRUPTED),
2329  errmsg_internal("downlink points to block in index \"%s\" whose level is not one level down",
2330  RelationGetRelationName(state->rel)),
2331  errdetail_internal("Top parent/under check block=%u block pointed to=%u expected level=%u level in pointed to block=%u.",
2332  blkno, childblk,
2333  level - 1, copaque->btpo_level)));
2334 
2335  level = copaque->btpo_level;
2336  itemid = PageGetItemIdCareful(state, childblk, child,
2337  P_FIRSTDATAKEY(copaque));
2338  itup = (IndexTuple) PageGetItem(child, itemid);
2339  childblk = BTreeTupleGetDownLink(itup);
2340  /* Be slightly more pro-active in freeing this memory, just in case */
2341  pfree(child);
2342  }
2343 
2344  /*
2345  * Since there cannot be a concurrent VACUUM operation in readonly mode,
2346  * and since a page has no links within other pages (siblings and parent)
2347  * once it is marked fully deleted, it should be impossible to land on a
2348  * fully deleted page. See bt_child_check() for further details.
2349  *
2350  * The bt_child_check() P_ISDELETED() check is repeated here because
2351  * bt_child_check() does not visit pages reachable through negative
2352  * infinity items. Besides, bt_child_check() is unwilling to descend
2353  * multiple levels. (The similar bt_child_check() P_ISDELETED() check
2354  * within bt_check_level_from_leftmost() won't reach the page either,
2355  * since the leaf's live siblings should have their sibling links updated
2356  * to bypass the deletion target page when it is marked fully dead.)
2357  *
2358  * If this error is raised, it might be due to a previous multi-level page
2359  * deletion that failed to realize that it wasn't yet safe to mark the
2360  * leaf page as fully dead. A "dangling downlink" will still remain when
2361  * this happens. The fact that the dangling downlink's page (the leaf's
2362  * parent/ancestor page) lacked a downlink is incidental.
2363  */
2364  if (P_ISDELETED(copaque))
2365  ereport(ERROR,
2366  (errcode(ERRCODE_INDEX_CORRUPTED),
2367  errmsg_internal("downlink to deleted leaf page found in index \"%s\"",
2368  RelationGetRelationName(state->rel)),
2369  errdetail_internal("Top parent/target block=%u leaf block=%u top parent/under check lsn=%X/%X.",
2370  blkno, childblk,
2371  LSN_FORMAT_ARGS(pagelsn))));
2372 
2373  /*
2374  * Iff leaf page is half-dead, its high key top parent link should point
2375  * to what VACUUM considered to be the top parent page at the instant it
2376  * was interrupted. Provided the high key link actually points to the
2377  * page under check, the missing downlink we detected is consistent with
2378  * there having been an interrupted multi-level page deletion. This means
2379  * that the subtree with the page under check at its root (a page deletion
2380  * chain) is in a consistent state, enabling VACUUM to resume deleting the
2381  * entire chain the next time it encounters the half-dead leaf page.
2382  */
2383  if (P_ISHALFDEAD(copaque) && !P_RIGHTMOST(copaque))
2384  {
2385  itemid = PageGetItemIdCareful(state, childblk, child, P_HIKEY);
2386  itup = (IndexTuple) PageGetItem(child, itemid);
2387  if (BTreeTupleGetTopParent(itup) == blkno)
2388  return;
2389  }
2390 
2391  ereport(ERROR,
2392  (errcode(ERRCODE_INDEX_CORRUPTED),
2393  errmsg("internal index block lacks downlink in index \"%s\"",
2394  RelationGetRelationName(state->rel)),
2395  errdetail_internal("Block=%u level=%u page lsn=%X/%X.",
2396  blkno, opaque->btpo_level,
2397  LSN_FORMAT_ARGS(pagelsn))));
2398 }
#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:369
static BlockNumber BTreeTupleGetDownLink(IndexTuple pivot)
Definition: nbtree.h:549
int errcode(int sqlerrcode)
Definition: elog.c:698
uint32 BlockNumber
Definition: block.h:31
BTPageOpaqueData * BTPageOpaque
Definition: nbtree.h:71
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
void pfree(void *pointer)
Definition: mcxt.c:1169
#define P_ISHALFDEAD(opaque)
Definition: nbtree.h:223
#define ERROR
Definition: elog.h:46
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:511
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:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
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:367
int errmsg(const char *fmt,...)
Definition: elog.c:909
static ItemId PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
#define elog(elevel,...)
Definition: elog.h:232
static BlockNumber BTreeTupleGetTopParent(IndexTuple leafhikey)
Definition: nbtree.h:613
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
#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, RelationGetRelationName, RelationGetSmgr(), 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  if (!smgrexists(RelationGetSmgr(indrel), MAIN_FORKNUM))
305  ereport(ERROR,
306  (errcode(ERRCODE_INDEX_CORRUPTED),
307  errmsg("index \"%s\" lacks a main relation fork",
308  RelationGetRelationName(indrel))));
309 
310  /* Extract metadata from metapage, and sanitize it in passing */
311  _bt_metaversion(indrel, &heapkeyspace, &allequalimage);
312  if (allequalimage && !heapkeyspace)
313  ereport(ERROR,
314  (errcode(ERRCODE_INDEX_CORRUPTED),
315  errmsg("index \"%s\" metapage has equalimage field set on unsupported nbtree version",
316  RelationGetRelationName(indrel))));
317  if (allequalimage && !_bt_allequalimage(indrel, false))
318  ereport(ERROR,
319  (errcode(ERRCODE_INDEX_CORRUPTED),
320  errmsg("index \"%s\" metapage incorrectly indicates that deduplication is safe",
321  RelationGetRelationName(indrel))));
322 
323  /* Check index, possibly against table it is an index on */
324  bt_check_every_level(indrel, heaprel, heapkeyspace, parentcheck,
325  heapallindexed, rootdescend);
326  }
327 
328  /*
329  * Release locks early. That's ok here because nothing in the called
330  * routines will trigger shared cache invalidations to be sent, so we can
331  * relax the usual pattern of only releasing locks after commit.
332  */
333  index_close(indrel, lockmode);
334  if (heaprel)
335  table_close(heaprel, lockmode);
336 }
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3475
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:78
static void btree_index_checkable(Relation rel)
int LOCKMODE
Definition: lockdefs.h:26
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
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 ERROR
Definition: elog.h:46
static void bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace, bool readonly, bool heapallindexed, bool rootdescend)
#define RelationGetRelationName(relation)
Definition: rel.h:511
void _bt_metaversion(Relation rel, bool *heapkeyspace, bool *allequalimage)
Definition: nbtpage.c:736
#define ereport(elevel,...)
Definition: elog.h:157
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:544
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
int errmsg(const char *fmt,...)
Definition: elog.c:909
#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 3106 of file verify_nbtree.c.

References _bt_mkscankey(), and BTScanInsertData::pivotsearch.

Referenced by bt_right_page_check_scankey(), and bt_target_page_check().

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

◆ bt_normalize_tuple()

static IndexTuple bt_normalize_tuple ( BtreeCheckState state,
IndexTuple  itup 
)
static

Definition at line 2524 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().

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

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

Referenced by bt_child_highkey_check().

1750 {
1751  if (IndexTupleSize(itup1) != IndexTupleSize(itup2))
1752  return false;
1753 
1754  if (heapkeyspace)
1755  {
1756  /*
1757  * Offset number will contain important information in heapkeyspace
1758  * indexes: the number of attributes left in the pivot tuple following
1759  * suffix truncation. Don't skip over it (compare it too).
1760  */
1761  if (memcmp(&itup1->t_tid.ip_posid, &itup2->t_tid.ip_posid,
1762  IndexTupleSize(itup1) -
1763  offsetof(ItemPointerData, ip_posid)) != 0)
1764  return false;
1765  }
1766  else
1767  {
1768  /*
1769  * Cannot rely on offset number field having consistent value across
1770  * levels on pg_upgrade'd !heapkeyspace indexes. Compare contents of
1771  * tuple starting from just after item pointer (i.e. after block
1772  * number and offset number).
1773  */
1774  if (memcmp(&itup1->t_info, &itup2->t_info,
1775  IndexTupleSize(itup1) -
1776  offsetof(IndexTupleData, t_info)) != 0)
1777  return false;
1778  }
1779 
1780  return true;
1781 }
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 2614 of file verify_nbtree.c.

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

Referenced by bt_target_page_check().

2615 {
2616  Assert(BTreeTupleIsPosting(itup));
2617 
2618  /* Returns non-posting-list tuple */
2619  return _bt_form_posting(itup, BTreeTupleGetPostingN(itup, n), 1);
2620 }
IndexTuple _bt_form_posting(IndexTuple base, ItemPointer htids, int nhtids)
Definition: nbtdedup.c:859
static ItemPointer BTreeTupleGetPostingN(IndexTuple posting, int n)
Definition: nbtree.h:537
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:485
#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 910 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().

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

References bt_mkscankey_pivotsearch(), BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_next, CHECK_FOR_INTERRUPTS, DEBUG2, 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().

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

2648 {
2649  BTScanInsert key;
2650  BTStack stack;
2651  Buffer lbuf;
2652  bool exists;
2653 
2654  key = _bt_mkscankey(state->rel, itup);
2655  Assert(key->heapkeyspace && key->scantid != NULL);
2656 
2657  /*
2658  * Search from root.
2659  *
2660  * Ideally, we would arrange to only move right within _bt_search() when
2661  * an interrupted page split is detected (i.e. when the incomplete split
2662  * bit is found to be set), but for now we accept the possibility that
2663  * that could conceal an inconsistency.
2664  */
2665  Assert(state->readonly && state->rootdescend);
2666  exists = false;
2667  stack = _bt_search(state->rel, key, &lbuf, BT_READ, NULL);
2668 
2669  if (BufferIsValid(lbuf))
2670  {
2671  BTInsertStateData insertstate;
2672  OffsetNumber offnum;
2673  Page page;
2674 
2675  insertstate.itup = itup;
2676  insertstate.itemsz = MAXALIGN(IndexTupleSize(itup));
2677  insertstate.itup_key = key;
2678  insertstate.postingoff = 0;
2679  insertstate.bounds_valid = false;
2680  insertstate.buf = lbuf;
2681 
2682  /* Get matching tuple on leaf page */
2683  offnum = _bt_binsrch_insert(state->rel, &insertstate);
2684  /* Compare first >= matching item on leaf page, if any */
2685  page = BufferGetPage(lbuf);
2686  /* Should match on first heap TID when tuple has a posting list */
2687  if (offnum <= PageGetMaxOffsetNumber(page) &&
2688  insertstate.postingoff <= 0 &&
2689  _bt_compare(state->rel, key, page, offnum) == 0)
2690  exists = true;
2691  _bt_relbuf(state->rel, lbuf);
2692  }
2693 
2694  _bt_freestack(stack);
2695  pfree(key);
2696 
2697  return exists;
2698 }
void _bt_freestack(BTStack stack)
Definition: nbtutils.c:175
bool bounds_valid
Definition: nbtree.h:821
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:90
ItemPointer scantid
Definition: nbtree.h:789
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
uint16 OffsetNumber
Definition: off.h:24
#define BT_READ
Definition: nbtree.h:712
void pfree(void *pointer)
Definition: mcxt.c:1169
OffsetNumber _bt_binsrch_insert(Relation rel, BTInsertState insertstate)
Definition: nbtsearch.c:447
IndexTuple itup
Definition: nbtree.h:809
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:1035
BTScanInsert itup_key
Definition: nbtree.h:811
#define Assert(condition)
Definition: c.h:804
bool heapkeyspace
Definition: nbtree.h:784
#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 1044 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().

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

2458 {
2459  BtreeCheckState *state = (BtreeCheckState *) checkstate;
2460  IndexTuple itup,
2461  norm;
2462 
2463  Assert(state->heapallindexed);
2464 
2465  /* Generate a normalized index tuple for fingerprinting */
2466  itup = index_form_tuple(RelationGetDescr(index), values, isnull);
2467  itup->t_tid = *tid;
2468  norm = bt_normalize_tuple(state, itup);
2469 
2470  /* Probe Bloom filter -- tuple should be present */
2471  if (bloom_lacks_element(state->filter, (unsigned char *) norm,
2472  IndexTupleSize(norm)))
2473  ereport(ERROR,
2475  errmsg("heap tuple (%u,%u) from table \"%s\" lacks matching index tuple within index \"%s\"",
2476  ItemPointerGetBlockNumber(&(itup->t_tid)),
2479  RelationGetRelationName(state->rel)),
2480  !state->readonly
2481  ? errhint("Retrying verification using the function bt_index_parent_check() might provide a more specific error.")
2482  : 0));
2483 
2484  state->heaptuplespresent++;
2485  pfree(itup);
2486  /* Cannot leak memory here */
2487  if (norm != itup)
2488  pfree(norm);
2489 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define RelationGetDescr(relation)
Definition: rel.h:503
static IndexTuple bt_normalize_tuple(BtreeCheckState *state, IndexTuple itup)
ItemPointerData t_tid
Definition: itup.h:37
int errcode(int sqlerrcode)
Definition: elog.c:698
bloom_filter * filter
IndexTuple index_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:47
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
#define RelationGetRelationName(relation)
Definition: rel.h:511
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:47
Relation heaprel
Definition: verify_nbtree.c:72
#define ereport(elevel,...)
Definition: elog.h:157
#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:166
int errmsg(const char *fmt,...)
Definition: elog.c:909
#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 347 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().

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

◆ btree_index_mainfork_expected()

static bool btree_index_mainfork_expected ( Relation  rel)
inlinestatic

Definition at line 380 of file verify_nbtree.c.

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

Referenced by bt_index_check_internal().

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

◆ BTreeTupleGetHeapTIDCareful()

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

Definition at line 3170 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().

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

◆ BTreeTupleGetPointsToTID()

static ItemPointer BTreeTupleGetPointsToTID ( IndexTuple  itup)
inlinestatic

Definition at line 3218 of file verify_nbtree.c.

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

Referenced by bt_target_page_check().

3219 {
3220  /*
3221  * Rely on the assumption that !heapkeyspace internal page data items will
3222  * correctly return TID with downlink here -- BTreeTupleGetHeapTID() won't
3223  * recognize it as a pivot tuple, but everything still works out because
3224  * the t_tid field is still returned
3225  */
3226  if (!BTreeTupleIsPivot(itup))
3227  return BTreeTupleGetHeapTID(itup);
3228 
3229  /* Pivot tuple returns TID with downlink block (heapkeyspace variant) */
3230  return &itup->t_tid;
3231 }
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:473
static ItemPointer BTreeTupleGetHeapTID(IndexTuple itup)
Definition: nbtree.h:631
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 2832 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().

2834 {
2835  int32 cmp;
2836 
2837  Assert(key->pivotsearch);
2838 
2839  cmp = _bt_compare(state->rel, key, state->target, lowerbound);
2840 
2841  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2842  if (!key->heapkeyspace)
2843  return cmp >= 0;
2844 
2845  /*
2846  * No need to consider the possibility that scankey has attributes that we
2847  * need to force to be interpreted as negative infinity. _bt_compare() is
2848  * able to determine that scankey is greater than negative infinity. The
2849  * distinction between "==" and "<" isn't interesting here, since
2850  * corruption is indicated either way.
2851  */
2852  return cmp > 0;
2853 }
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:788
#define Assert(condition)
Definition: c.h:804
bool heapkeyspace
Definition: nbtree.h:784
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 2868 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().

2871 {
2872  ItemId itemid;
2873  int32 cmp;
2874 
2875  Assert(key->pivotsearch);
2876 
2877  /* Verify line pointer before checking tuple */
2878  itemid = PageGetItemIdCareful(state, nontargetblock, nontarget,
2879  upperbound);
2880  cmp = _bt_compare(state->rel, key, nontarget, upperbound);
2881 
2882  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2883  if (!key->heapkeyspace)
2884  return cmp <= 0;
2885 
2886  /* See invariant_l_offset() for an explanation of this extra step */
2887  if (cmp == 0)
2888  {
2889  IndexTuple child;
2890  int uppnkeyatts;
2891  ItemPointer childheaptid;
2892  BTPageOpaque copaque;
2893  bool nonpivot;
2894 
2895  child = (IndexTuple) PageGetItem(nontarget, itemid);
2896  copaque = (BTPageOpaque) PageGetSpecialPointer(nontarget);
2897  nonpivot = P_ISLEAF(copaque) && upperbound >= P_FIRSTDATAKEY(copaque);
2898 
2899  /* Get number of keys + heap TID for child/non-target item */
2900  uppnkeyatts = BTreeTupleGetNKeyAtts(child, state->rel);
2901  childheaptid = BTreeTupleGetHeapTIDCareful(state, child, nonpivot);
2902 
2903  /* Heap TID is tiebreaker key attribute */
2904  if (key->keysz == uppnkeyatts)
2905  return key->scantid == NULL && childheaptid != NULL;
2906 
2907  return key->keysz < uppnkeyatts;
2908  }
2909 
2910  return cmp < 0;
2911 }
ItemPointer scantid
Definition: nbtree.h:789
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:369
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:788
#define Assert(condition)
Definition: c.h:804
#define BTreeTupleGetNKeyAtts(itup, rel)
Definition: verify_nbtree.c:50
bool heapkeyspace
Definition: nbtree.h:784
#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 2746 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().

2748 {
2749  ItemId itemid;
2750  int32 cmp;
2751 
2752  Assert(key->pivotsearch);
2753 
2754  /* Verify line pointer before checking tuple */
2755  itemid = PageGetItemIdCareful(state, state->targetblock, state->target,
2756  upperbound);
2757  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2758  if (!key->heapkeyspace)
2759  return invariant_leq_offset(state, key, upperbound);
2760 
2761  cmp = _bt_compare(state->rel, key, state->target, upperbound);
2762 
2763  /*
2764  * _bt_compare() is capable of determining that a scankey with a
2765  * filled-out attribute is greater than pivot tuples where the comparison
2766  * is resolved at a truncated attribute (value of attribute in pivot is
2767  * minus infinity). However, it is not capable of determining that a
2768  * scankey is _less than_ a tuple on the basis of a comparison resolved at
2769  * _scankey_ minus infinity attribute. Complete an extra step to simulate
2770  * having minus infinity values for omitted scankey attribute(s).
2771  */
2772  if (cmp == 0)
2773  {
2774  BTPageOpaque topaque;
2775  IndexTuple ritup;
2776  int uppnkeyatts;
2777  ItemPointer rheaptid;
2778  bool nonpivot;
2779 
2780  ritup = (IndexTuple) PageGetItem(state->target, itemid);
2781  topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
2782  nonpivot = P_ISLEAF(topaque) && upperbound >= P_FIRSTDATAKEY(topaque);
2783 
2784  /* Get number of keys + heap TID for item to the right */
2785  uppnkeyatts = BTreeTupleGetNKeyAtts(ritup, state->rel);
2786  rheaptid = BTreeTupleGetHeapTIDCareful(state, ritup, nonpivot);
2787 
2788  /* Heap TID is tiebreaker key attribute */
2789  if (key->keysz == uppnkeyatts)
2790  return key->scantid == NULL && rheaptid != NULL;
2791 
2792  return key->keysz < uppnkeyatts;
2793  }
2794 
2795  return cmp < 0;
2796 }
static bool invariant_leq_offset(BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound)
BlockNumber targetblock
Definition: verify_nbtree.c:93
ItemPointer scantid
Definition: nbtree.h:789
#define P_FIRSTDATAKEY(opaque)
Definition: nbtree.h:369
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:788
#define Assert(condition)
Definition: c.h:804
#define BTreeTupleGetNKeyAtts(itup, rel)
Definition: verify_nbtree.c:50
bool heapkeyspace
Definition: nbtree.h:784
#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 2809 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().

2811 {
2812  int32 cmp;
2813 
2814  Assert(key->pivotsearch);
2815 
2816  cmp = _bt_compare(state->rel, key, state->target, upperbound);
2817 
2818  return cmp <= 0;
2819 }
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:788
#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 2711 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().

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

◆ PageGetItemIdCareful()

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

Definition at line 3130 of file verify_nbtree.c.

References ereport, errcode(), errdetail_internal(), errmsg(), ERROR, ItemIdGetFlags, ItemIdGetLength, ItemIdGetOffset, ItemIdIsRedirected, ItemIdIsUsed, MAXALIGN, 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().

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

◆ palloc_btree_page()

static Page palloc_btree_page ( BtreeCheckState state,
BlockNumber  blocknum 
)
static

Definition at line 2928 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().

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