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 "common/pg_prng.h"
#include "lib/bloomfilter.h"
#include "miscadmin.h"
#include "storage/lmgr.h"
#include "storage/smgr.h"
#include "utils/guc.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 blkno, Page page)
 
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 52 of file verify_nbtree.c.

◆ InvalidBtreeLevel

#define InvalidBtreeLevel   ((uint32) InvalidBlockNumber)

Definition at line 51 of file verify_nbtree.c.

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 448 of file verify_nbtree.c.

450 {
452  Page metapage;
453  BTMetaPageData *metad;
454  uint32 previouslevel;
455  BtreeLevel current;
456  Snapshot snapshot = SnapshotAny;
457 
458  if (!readonly)
459  elog(DEBUG1, "verifying consistency of tree structure for index \"%s\"",
461  else
462  elog(DEBUG1, "verifying consistency of tree structure for index \"%s\" with cross-level checks",
464 
465  /*
466  * This assertion matches the one in index_getnext_tid(). See page
467  * recycling/"visible to everyone" notes in nbtree README.
468  */
470 
471  /*
472  * Initialize state for entire verification operation
473  */
474  state = palloc0(sizeof(BtreeCheckState));
475  state->rel = rel;
476  state->heaprel = heaprel;
477  state->heapkeyspace = heapkeyspace;
478  state->readonly = readonly;
479  state->heapallindexed = heapallindexed;
480  state->rootdescend = rootdescend;
481 
482  if (state->heapallindexed)
483  {
484  int64 total_pages;
485  int64 total_elems;
486  uint64 seed;
487 
488  /*
489  * Size Bloom filter based on estimated number of tuples in index,
490  * while conservatively assuming that each block must contain at least
491  * MaxTIDsPerBTreePage / 3 "plain" tuples -- see
492  * bt_posting_plain_tuple() for definition, and details of how posting
493  * list tuples are handled.
494  */
495  total_pages = RelationGetNumberOfBlocks(rel);
496  total_elems = Max(total_pages * (MaxTIDsPerBTreePage / 3),
497  (int64) state->rel->rd_rel->reltuples);
498  /* Generate a random seed to avoid repetition */
500  /* Create Bloom filter to fingerprint index */
501  state->filter = bloom_create(total_elems, maintenance_work_mem, seed);
502  state->heaptuplespresent = 0;
503 
504  /*
505  * Register our own snapshot in !readonly case, rather than asking
506  * table_index_build_scan() to do this for us later. This needs to
507  * happen before index fingerprinting begins, so we can later be
508  * certain that index fingerprinting should have reached all tuples
509  * returned by table_index_build_scan().
510  */
511  if (!state->readonly)
512  {
514 
515  /*
516  * GetTransactionSnapshot() always acquires a new MVCC snapshot in
517  * READ COMMITTED mode. A new snapshot is guaranteed to have all
518  * the entries it requires in the index.
519  *
520  * We must defend against the possibility that an old xact
521  * snapshot was returned at higher isolation levels when that
522  * snapshot is not safe for index scans of the target index. This
523  * is possible when the snapshot sees tuples that are before the
524  * index's indcheckxmin horizon. Throwing an error here should be
525  * very rare. It doesn't seem worth using a secondary snapshot to
526  * avoid this.
527  */
528  if (IsolationUsesXactSnapshot() && rel->rd_index->indcheckxmin &&
530  snapshot->xmin))
531  ereport(ERROR,
533  errmsg("index \"%s\" cannot be verified using transaction snapshot",
534  RelationGetRelationName(rel))));
535  }
536  }
537 
538  Assert(!state->rootdescend || state->readonly);
539  if (state->rootdescend && !state->heapkeyspace)
540  ereport(ERROR,
541  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
542  errmsg("cannot verify that tuples from index \"%s\" can each be found by an independent index search",
544  errhint("Only B-Tree version 4 indexes support rootdescend verification.")));
545 
546  /* Create context for page */
548  "amcheck context",
550  state->checkstrategy = GetAccessStrategy(BAS_BULKREAD);
551 
552  /* Get true root block from meta-page */
554  metad = BTPageGetMeta(metapage);
555 
556  /*
557  * Certain deletion patterns can result in "skinny" B-Tree indexes, where
558  * the fast root and true root differ.
559  *
560  * Start from the true root, not the fast root, unlike conventional index
561  * scans. This approach is more thorough, and removes the risk of
562  * following a stale fast root from the meta page.
563  */
564  if (metad->btm_fastroot != metad->btm_root)
565  ereport(DEBUG1,
566  (errcode(ERRCODE_NO_DATA),
567  errmsg_internal("harmless fast root mismatch in index \"%s\"",
569  errdetail_internal("Fast root block %u (level %u) differs from true root block %u (level %u).",
570  metad->btm_fastroot, metad->btm_fastlevel,
571  metad->btm_root, metad->btm_level)));
572 
573  /*
574  * Starting at the root, verify every level. Move left to right, top to
575  * bottom. Note that there may be no pages other than the meta page (meta
576  * page can indicate that root is P_NONE when the index is totally empty).
577  */
578  previouslevel = InvalidBtreeLevel;
579  current.level = metad->btm_level;
580  current.leftmost = metad->btm_root;
581  current.istruerootlevel = true;
582  while (current.leftmost != P_NONE)
583  {
584  /*
585  * Verify this level, and get left most page for next level down, if
586  * not at leaf level
587  */
588  current = bt_check_level_from_leftmost(state, current);
589 
590  if (current.leftmost == InvalidBlockNumber)
591  ereport(ERROR,
592  (errcode(ERRCODE_INDEX_CORRUPTED),
593  errmsg("index \"%s\" has no valid pages on level below %u or first level",
594  RelationGetRelationName(rel), previouslevel)));
595 
596  previouslevel = current.level;
597  }
598 
599  /*
600  * * Check whether heap contains unindexed/malformed tuples *
601  */
602  if (state->heapallindexed)
603  {
604  IndexInfo *indexinfo = BuildIndexInfo(state->rel);
605  TableScanDesc scan;
606 
607  /*
608  * Create our own scan for table_index_build_scan(), rather than
609  * getting it to do so for us. This is required so that we can
610  * actually use the MVCC snapshot registered earlier in !readonly
611  * case.
612  *
613  * Note that table_index_build_scan() calls heap_endscan() for us.
614  */
615  scan = table_beginscan_strat(state->heaprel, /* relation */
616  snapshot, /* snapshot */
617  0, /* number of keys */
618  NULL, /* scan key */
619  true, /* buffer access strategy OK */
620  true); /* syncscan OK? */
621 
622  /*
623  * Scan will behave as the first scan of a CREATE INDEX CONCURRENTLY
624  * behaves in !readonly case.
625  *
626  * It's okay that we don't actually use the same lock strength for the
627  * heap relation as any other ii_Concurrent caller would in !readonly
628  * case. We have no reason to care about a concurrent VACUUM
629  * operation, since there isn't going to be a second scan of the heap
630  * that needs to be sure that there was no concurrent recycling of
631  * TIDs.
632  */
633  indexinfo->ii_Concurrent = !state->readonly;
634 
635  /*
636  * Don't wait for uncommitted tuple xact commit/abort when index is a
637  * unique index on a catalog (or an index used by an exclusion
638  * constraint). This could otherwise happen in the readonly case.
639  */
640  indexinfo->ii_Unique = false;
641  indexinfo->ii_ExclusionOps = NULL;
642  indexinfo->ii_ExclusionProcs = NULL;
643  indexinfo->ii_ExclusionStrats = NULL;
644 
645  elog(DEBUG1, "verifying that tuples from index \"%s\" are present in \"%s\"",
647  RelationGetRelationName(state->heaprel));
648 
649  table_index_build_scan(state->heaprel, state->rel, indexinfo, true, false,
650  bt_tuple_present_callback, (void *) state, scan);
651 
652  ereport(DEBUG1,
653  (errmsg_internal("finished verifying presence of " INT64_FORMAT " tuples from table \"%s\" with bitset %.2f%% set",
654  state->heaptuplespresent, RelationGetRelationName(heaprel),
655  100.0 * bloom_prop_bits_set(state->filter))));
656 
657  if (snapshot != SnapshotAny)
658  UnregisterSnapshot(snapshot);
659 
660  bloom_free(state->filter);
661  }
662 
663  /* Be tidy: */
664  MemoryContextDelete(state->targetcontext);
665 }
#define InvalidBlockNumber
Definition: block.h:33
void bloom_free(bloom_filter *filter)
Definition: bloomfilter.c:126
bloom_filter * bloom_create(int64 total_elems, int bloom_work_mem, uint64 seed)
Definition: bloomfilter.c:87
double bloom_prop_bits_set(bloom_filter *filter)
Definition: bloomfilter.c:187
@ BAS_BULKREAD
Definition: bufmgr.h:35
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:161
Pointer Page
Definition: bufpage.h:78
unsigned int uint32
Definition: c.h:490
#define Max(x, y)
Definition: c.h:982
#define INT64_FORMAT
Definition: c.h:532
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1229
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
int maintenance_work_mem
Definition: globals.c:127
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:309
IndexInfo * BuildIndexInfo(Relation index)
Definition: index.c:2430
Assert(fmt[strlen(fmt) - 1] !='\n')
void * palloc0(Size size)
Definition: mcxt.c:1241
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:387
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define BTPageGetMeta(p)
Definition: nbtree.h:121
#define MaxTIDsPerBTreePage
Definition: nbtree.h:185
#define P_NONE
Definition: nbtree.h:212
#define BTREE_METAPAGE
Definition: nbtree.h:148
uint64 pg_prng_uint64(pg_prng_state *state)
Definition: pg_prng.c:134
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76
#define RelationGetRelationName(relation)
Definition: rel.h:537
TransactionId RecentXmin
Definition: snapmgr.c:114
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:251
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:871
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:829
#define SnapshotAny
Definition: snapmgr.h:67
uint32 btm_level
Definition: nbtree.h:108
BlockNumber btm_fastroot
Definition: nbtree.h:109
BlockNumber btm_root
Definition: nbtree.h:107
uint32 btm_fastlevel
Definition: nbtree.h:110
bool istruerootlevel
uint32 level
BlockNumber leftmost
HeapTupleHeader t_data
Definition: htup.h:68
bool ii_Unique
Definition: execnodes.h:191
uint16 * ii_ExclusionStrats
Definition: execnodes.h:186
Oid * ii_ExclusionOps
Definition: execnodes.h:184
bool ii_Concurrent
Definition: execnodes.h:196
Oid * ii_ExclusionProcs
Definition: execnodes.h:185
struct HeapTupleData * rd_indextuple
Definition: rel.h:192
Form_pg_index rd_index
Definition: rel.h:190
TransactionId xmin
Definition: snapshot.h:157
Definition: regguts.h:318
static TableScanDesc table_beginscan_strat(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key, bool allow_strat, bool allow_sync)
Definition: tableam.h:927
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:1782
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static BtreeLevel bt_check_level_from_leftmost(BtreeCheckState *state, BtreeLevel level)
static void bt_tuple_present_callback(Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *checkstate)
#define InvalidBtreeLevel
Definition: verify_nbtree.c:51
static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
#define IsolationUsesXactSnapshot()
Definition: xact.h:51

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(), CurrentMemoryContext, DEBUG1, elog(), ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, GetAccessStrategy(), GetTransactionSnapshot(), HeapTupleHeaderGetXmin, 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(), pg_global_prng_state, pg_prng_uint64(), RelationData::rd_index, RelationData::rd_indextuple, RecentXmin, RegisterSnapshot(), RelationGetNumberOfBlocks, RelationGetRelationName, SnapshotAny, HeapTupleData::t_data, table_beginscan_strat(), table_index_build_scan(), TransactionIdIsValid, TransactionIdPrecedes(), UnregisterSnapshot(), and SnapshotData::xmin.

Referenced by bt_index_check_internal().

◆ bt_check_level_from_leftmost()

static BtreeLevel bt_check_level_from_leftmost ( BtreeCheckState state,
BtreeLevel  level 
)
static

Definition at line 686 of file verify_nbtree.c.

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

References Assert(), bt_recheck_sibling_links(), bt_target_page_check(), BTPageGetOpaque, 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, MemoryContextAlloc(), MemoryContextReset(), MemoryContextSwitchTo(), P_FIRSTDATAKEY, P_HIKEY, P_IGNORE, P_ISDELETED, P_ISLEAF, P_ISROOT, P_LEFTMOST, P_NONE, P_RIGHTMOST, PageGetItem(), PageGetItemIdCareful(), PageGetLSN(), palloc_btree_page(), pfree(), and RelationGetRelationName.

Referenced by bt_check_every_level().

◆ bt_child_check()

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

Definition at line 2098 of file verify_nbtree.c.

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

References Assert(), bt_child_highkey_check(), BTPageGetOpaque, 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(), palloc_btree_page(), pfree(), and RelationGetRelationName.

Referenced by bt_target_page_check().

◆ 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 1852 of file verify_nbtree.c.

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

References BlockNumberIsValid(), bt_downlink_missing_check(), bt_pivot_tuple_identical(), BTPageGetOpaque, BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_next, BTPageOpaqueData::btpo_prev, BTreeTupleGetDownLink(), ereport, errcode(), errdetail_internal(), errmsg(), ERROR, InvalidBlockNumber, 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(), palloc_btree_page(), pfree(), and RelationGetRelationName.

Referenced by bt_child_check(), and bt_target_page_check().

◆ bt_downlink_missing_check()

static void bt_downlink_missing_check ( BtreeCheckState state,
bool  rightsplit,
BlockNumber  blkno,
Page  page 
)
static

Definition at line 2263 of file verify_nbtree.c.

2265 {
2266  BTPageOpaque opaque = BTPageGetOpaque(page);
2267  ItemId itemid;
2268  IndexTuple itup;
2269  Page child;
2270  BTPageOpaque copaque;
2271  uint32 level;
2272  BlockNumber childblk;
2273  XLogRecPtr pagelsn;
2274 
2275  Assert(state->readonly);
2276  Assert(!P_IGNORE(opaque));
2277 
2278  /* No next level up with downlinks to fingerprint from the true root */
2279  if (P_ISROOT(opaque))
2280  return;
2281 
2282  pagelsn = PageGetLSN(page);
2283 
2284  /*
2285  * Incomplete (interrupted) page splits can account for the lack of a
2286  * downlink. Some inserting transaction should eventually complete the
2287  * page split in passing, when it notices that the left sibling page is
2288  * P_INCOMPLETE_SPLIT().
2289  *
2290  * In general, VACUUM is not prepared for there to be no downlink to a
2291  * page that it deletes. This is the main reason why the lack of a
2292  * downlink can be reported as corruption here. It's not obvious that an
2293  * invalid missing downlink can result in wrong answers to queries,
2294  * though, since index scans that land on the child may end up
2295  * consistently moving right. The handling of concurrent page splits (and
2296  * page deletions) within _bt_moveright() cannot distinguish
2297  * inconsistencies that last for a moment from inconsistencies that are
2298  * permanent and irrecoverable.
2299  *
2300  * VACUUM isn't even prepared to delete pages that have no downlink due to
2301  * an incomplete page split, but it can detect and reason about that case
2302  * by design, so it shouldn't be taken to indicate corruption. See
2303  * _bt_pagedel() for full details.
2304  */
2305  if (rightsplit)
2306  {
2307  ereport(DEBUG1,
2308  (errcode(ERRCODE_NO_DATA),
2309  errmsg_internal("harmless interrupted page split detected in index \"%s\"",
2311  errdetail_internal("Block=%u level=%u left sibling=%u page lsn=%X/%X.",
2312  blkno, opaque->btpo_level,
2313  opaque->btpo_prev,
2314  LSN_FORMAT_ARGS(pagelsn))));
2315  return;
2316  }
2317 
2318  /*
2319  * Page under check is probably the "top parent" of a multi-level page
2320  * deletion. We'll need to descend the subtree to make sure that
2321  * descendant pages are consistent with that, though.
2322  *
2323  * If the page (which must be non-ignorable) is a leaf page, then clearly
2324  * it can't be the top parent. The lack of a downlink is probably a
2325  * symptom of a broad problem that could just as easily cause
2326  * inconsistencies anywhere else.
2327  */
2328  if (P_ISLEAF(opaque))
2329  ereport(ERROR,
2330  (errcode(ERRCODE_INDEX_CORRUPTED),
2331  errmsg("leaf index block lacks downlink in index \"%s\"",
2333  errdetail_internal("Block=%u page lsn=%X/%X.",
2334  blkno,
2335  LSN_FORMAT_ARGS(pagelsn))));
2336 
2337  /* Descend from the given page, which is an internal page */
2338  elog(DEBUG1, "checking for interrupted multi-level deletion due to missing downlink in index \"%s\"",
2340 
2341  level = opaque->btpo_level;
2342  itemid = PageGetItemIdCareful(state, blkno, page, P_FIRSTDATAKEY(opaque));
2343  itup = (IndexTuple) PageGetItem(page, itemid);
2344  childblk = BTreeTupleGetDownLink(itup);
2345  for (;;)
2346  {
2348 
2349  child = palloc_btree_page(state, childblk);
2350  copaque = BTPageGetOpaque(child);
2351 
2352  if (P_ISLEAF(copaque))
2353  break;
2354 
2355  /* Do an extra sanity check in passing on internal pages */
2356  if (copaque->btpo_level != level - 1)
2357  ereport(ERROR,
2358  (errcode(ERRCODE_INDEX_CORRUPTED),
2359  errmsg_internal("downlink points to block in index \"%s\" whose level is not one level down",
2361  errdetail_internal("Top parent/under check block=%u block pointed to=%u expected level=%u level in pointed to block=%u.",
2362  blkno, childblk,
2363  level - 1, copaque->btpo_level)));
2364 
2365  level = copaque->btpo_level;
2366  itemid = PageGetItemIdCareful(state, childblk, child,
2367  P_FIRSTDATAKEY(copaque));
2368  itup = (IndexTuple) PageGetItem(child, itemid);
2369  childblk = BTreeTupleGetDownLink(itup);
2370  /* Be slightly more pro-active in freeing this memory, just in case */
2371  pfree(child);
2372  }
2373 
2374  /*
2375  * Since there cannot be a concurrent VACUUM operation in readonly mode,
2376  * and since a page has no links within other pages (siblings and parent)
2377  * once it is marked fully deleted, it should be impossible to land on a
2378  * fully deleted page. See bt_child_check() for further details.
2379  *
2380  * The bt_child_check() P_ISDELETED() check is repeated here because
2381  * bt_child_check() does not visit pages reachable through negative
2382  * infinity items. Besides, bt_child_check() is unwilling to descend
2383  * multiple levels. (The similar bt_child_check() P_ISDELETED() check
2384  * within bt_check_level_from_leftmost() won't reach the page either,
2385  * since the leaf's live siblings should have their sibling links updated
2386  * to bypass the deletion target page when it is marked fully dead.)
2387  *
2388  * If this error is raised, it might be due to a previous multi-level page
2389  * deletion that failed to realize that it wasn't yet safe to mark the
2390  * leaf page as fully dead. A "dangling downlink" will still remain when
2391  * this happens. The fact that the dangling downlink's page (the leaf's
2392  * parent/ancestor page) lacked a downlink is incidental.
2393  */
2394  if (P_ISDELETED(copaque))
2395  ereport(ERROR,
2396  (errcode(ERRCODE_INDEX_CORRUPTED),
2397  errmsg_internal("downlink to deleted leaf page found in index \"%s\"",
2399  errdetail_internal("Top parent/target block=%u leaf block=%u top parent/under check lsn=%X/%X.",
2400  blkno, childblk,
2401  LSN_FORMAT_ARGS(pagelsn))));
2402 
2403  /*
2404  * Iff leaf page is half-dead, its high key top parent link should point
2405  * to what VACUUM considered to be the top parent page at the instant it
2406  * was interrupted. Provided the high key link actually points to the
2407  * page under check, the missing downlink we detected is consistent with
2408  * there having been an interrupted multi-level page deletion. This means
2409  * that the subtree with the page under check at its root (a page deletion
2410  * chain) is in a consistent state, enabling VACUUM to resume deleting the
2411  * entire chain the next time it encounters the half-dead leaf page.
2412  */
2413  if (P_ISHALFDEAD(copaque) && !P_RIGHTMOST(copaque))
2414  {
2415  itemid = PageGetItemIdCareful(state, childblk, child, P_HIKEY);
2416  itup = (IndexTuple) PageGetItem(child, itemid);
2417  if (BTreeTupleGetTopParent(itup) == blkno)
2418  return;
2419  }
2420 
2421  ereport(ERROR,
2422  (errcode(ERRCODE_INDEX_CORRUPTED),
2423  errmsg("internal index block lacks downlink in index \"%s\"",
2425  errdetail_internal("Block=%u level=%u page lsn=%X/%X.",
2426  blkno, opaque->btpo_level,
2427  LSN_FORMAT_ARGS(pagelsn))));
2428 }
#define P_ISHALFDEAD(opaque)
Definition: nbtree.h:224
static BlockNumber BTreeTupleGetTopParent(IndexTuple leafhikey)
Definition: nbtree.h:621
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References Assert(), BTPageGetOpaque, 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(), palloc_btree_page(), pfree(), and RelationGetRelationName.

Referenced by bt_child_highkey_check().

◆ bt_index_check()

Datum bt_index_check ( PG_FUNCTION_ARGS  )

Definition at line 203 of file verify_nbtree.c.

204 {
205  Oid indrelid = PG_GETARG_OID(0);
206  bool heapallindexed = false;
207 
208  if (PG_NARGS() == 2)
209  heapallindexed = PG_GETARG_BOOL(1);
210 
211  bt_index_check_internal(indrelid, false, heapallindexed, false);
212 
213  PG_RETURN_VOID();
214 }
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#define PG_NARGS()
Definition: fmgr.h:203
#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)

References bt_index_check_internal(), PG_GETARG_BOOL, PG_GETARG_OID, PG_NARGS, and PG_RETURN_VOID.

◆ bt_index_check_internal()

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

Definition at line 246 of file verify_nbtree.c.

248 {
249  Oid heapid;
250  Relation indrel;
251  Relation heaprel;
252  LOCKMODE lockmode;
253  Oid save_userid;
254  int save_sec_context;
255  int save_nestlevel;
256 
257  if (parentcheck)
258  lockmode = ShareLock;
259  else
260  lockmode = AccessShareLock;
261 
262  /*
263  * We must lock table before index to avoid deadlocks. However, if the
264  * passed indrelid isn't an index then IndexGetRelation() will fail.
265  * Rather than emitting a not-very-helpful error message, postpone
266  * complaining, expecting that the is-it-an-index test below will fail.
267  *
268  * In hot standby mode this will raise an error when parentcheck is true.
269  */
270  heapid = IndexGetRelation(indrelid, true);
271  if (OidIsValid(heapid))
272  {
273  heaprel = table_open(heapid, lockmode);
274 
275  /*
276  * Switch to the table owner's userid, so that any index functions are
277  * run as that user. Also lock down security-restricted operations
278  * and arrange to make GUC variable changes local to this command.
279  */
280  GetUserIdAndSecContext(&save_userid, &save_sec_context);
281  SetUserIdAndSecContext(heaprel->rd_rel->relowner,
282  save_sec_context | SECURITY_RESTRICTED_OPERATION);
283  save_nestlevel = NewGUCNestLevel();
284  }
285  else
286  {
287  heaprel = NULL;
288  /* Set these just to suppress "uninitialized variable" warnings */
289  save_userid = InvalidOid;
290  save_sec_context = -1;
291  save_nestlevel = -1;
292  }
293 
294  /*
295  * Open the target index relations separately (like relation_openrv(), but
296  * with heap relation locked first to prevent deadlocking). In hot
297  * standby mode this will raise an error when parentcheck is true.
298  *
299  * There is no need for the usual indcheckxmin usability horizon test
300  * here, even in the heapallindexed case, because index undergoing
301  * verification only needs to have entries for a new transaction snapshot.
302  * (If this is a parentcheck verification, there is no question about
303  * committed or recently dead heap tuples lacking index entries due to
304  * concurrent activity.)
305  */
306  indrel = index_open(indrelid, lockmode);
307 
308  /*
309  * Since we did the IndexGetRelation call above without any lock, it's
310  * barely possible that a race against an index drop/recreation could have
311  * netted us the wrong table.
312  */
313  if (heaprel == NULL || heapid != IndexGetRelation(indrelid, false))
314  ereport(ERROR,
316  errmsg("could not open parent table of index \"%s\"",
317  RelationGetRelationName(indrel))));
318 
319  /* Relation suitable for checking as B-Tree? */
320  btree_index_checkable(indrel);
321 
322  if (btree_index_mainfork_expected(indrel))
323  {
324  bool heapkeyspace,
325  allequalimage;
326 
327  if (!smgrexists(RelationGetSmgr(indrel), MAIN_FORKNUM))
328  ereport(ERROR,
329  (errcode(ERRCODE_INDEX_CORRUPTED),
330  errmsg("index \"%s\" lacks a main relation fork",
331  RelationGetRelationName(indrel))));
332 
333  /* Extract metadata from metapage, and sanitize it in passing */
334  _bt_metaversion(indrel, &heapkeyspace, &allequalimage);
335  if (allequalimage && !heapkeyspace)
336  ereport(ERROR,
337  (errcode(ERRCODE_INDEX_CORRUPTED),
338  errmsg("index \"%s\" metapage has equalimage field set on unsupported nbtree version",
339  RelationGetRelationName(indrel))));
340  if (allequalimage && !_bt_allequalimage(indrel, false))
341  ereport(ERROR,
342  (errcode(ERRCODE_INDEX_CORRUPTED),
343  errmsg("index \"%s\" metapage incorrectly indicates that deduplication is safe",
344  RelationGetRelationName(indrel))));
345 
346  /* Check index, possibly against table it is an index on */
347  bt_check_every_level(indrel, heaprel, heapkeyspace, parentcheck,
348  heapallindexed, rootdescend);
349  }
350 
351  /* Roll back any GUC changes executed by index functions */
352  AtEOXact_GUC(false, save_nestlevel);
353 
354  /* Restore userid and security context */
355  SetUserIdAndSecContext(save_userid, save_sec_context);
356 
357  /*
358  * Release locks early. That's ok here because nothing in the called
359  * routines will trigger shared cache invalidations to be sent, so we can
360  * relax the usual pattern of only releasing locks after commit.
361  */
362  index_close(indrel, lockmode);
363  if (heaprel)
364  table_close(heaprel, lockmode);
365 }
#define OidIsValid(objectId)
Definition: c.h:759
int NewGUCNestLevel(void)
Definition: guc.c:2201
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2215
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3533
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
int LOCKMODE
Definition: lockdefs.h:26
#define AccessShareLock
Definition: lockdefs.h:36
#define ShareLock
Definition: lockdefs.h:40
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:305
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:631
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:638
void _bt_metaversion(Relation rel, bool *heapkeyspace, bool *allequalimage)
Definition: nbtpage.c:736
bool _bt_allequalimage(Relation rel, bool debugmessage)
Definition: nbtutils.c:2689
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78
#define InvalidOid
Definition: postgres_ext.h:36
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:571
@ MAIN_FORKNUM
Definition: relpath.h:50
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:247
Form_pg_class rd_rel
Definition: rel.h:110
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
static void bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace, bool readonly, bool heapallindexed, bool rootdescend)
static bool btree_index_mainfork_expected(Relation rel)
static void btree_index_checkable(Relation rel)

References _bt_allequalimage(), _bt_metaversion(), AccessShareLock, AtEOXact_GUC(), bt_check_every_level(), btree_index_checkable(), btree_index_mainfork_expected(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg(), ERROR, GetUserIdAndSecContext(), index_close(), index_open(), IndexGetRelation(), InvalidOid, MAIN_FORKNUM, NewGUCNestLevel(), OidIsValid, RelationData::rd_rel, RelationGetRelationName, RelationGetSmgr(), SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), ShareLock, smgrexists(), table_close(), and table_open().

Referenced by bt_index_check(), and bt_index_parent_check().

◆ bt_index_parent_check()

Datum bt_index_parent_check ( PG_FUNCTION_ARGS  )

Definition at line 226 of file verify_nbtree.c.

227 {
228  Oid indrelid = PG_GETARG_OID(0);
229  bool heapallindexed = false;
230  bool rootdescend = false;
231 
232  if (PG_NARGS() >= 2)
233  heapallindexed = PG_GETARG_BOOL(1);
234  if (PG_NARGS() == 3)
235  rootdescend = PG_GETARG_BOOL(2);
236 
237  bt_index_check_internal(indrelid, true, heapallindexed, rootdescend);
238 
239  PG_RETURN_VOID();
240 }

References bt_index_check_internal(), PG_GETARG_BOOL, PG_GETARG_OID, PG_NARGS, and PG_RETURN_VOID.

◆ bt_mkscankey_pivotsearch()

static BTScanInsert bt_mkscankey_pivotsearch ( Relation  rel,
IndexTuple  itup 
)
inlinestatic

Definition at line 3136 of file verify_nbtree.c.

3137 {
3138  BTScanInsert skey;
3139 
3140  skey = _bt_mkscankey(rel, itup);
3141  skey->pivotsearch = true;
3142 
3143  return skey;
3144 }
BTScanInsert _bt_mkscankey(Relation rel, IndexTuple itup)
Definition: nbtutils.c:90
bool pivotsearch
Definition: nbtree.h:796

References _bt_mkscankey(), and BTScanInsertData::pivotsearch.

Referenced by bt_right_page_check_scankey(), and bt_target_page_check().

◆ bt_normalize_tuple()

static IndexTuple bt_normalize_tuple ( BtreeCheckState state,
IndexTuple  itup 
)
static

Definition at line 2554 of file verify_nbtree.c.

2555 {
2556  TupleDesc tupleDescriptor = RelationGetDescr(state->rel);
2557  Datum normalized[INDEX_MAX_KEYS];
2558  bool isnull[INDEX_MAX_KEYS];
2559  bool toast_free[INDEX_MAX_KEYS];
2560  bool formnewtup = false;
2561  IndexTuple reformed;
2562  int i;
2563 
2564  /* Caller should only pass "logical" non-pivot tuples here */
2565  Assert(!BTreeTupleIsPosting(itup) && !BTreeTupleIsPivot(itup));
2566 
2567  /* Easy case: It's immediately clear that tuple has no varlena datums */
2568  if (!IndexTupleHasVarwidths(itup))
2569  return itup;
2570 
2571  for (i = 0; i < tupleDescriptor->natts; i++)
2572  {
2573  Form_pg_attribute att;
2574 
2575  att = TupleDescAttr(tupleDescriptor, i);
2576 
2577  /* Assume untoasted/already normalized datum initially */
2578  toast_free[i] = false;
2579  normalized[i] = index_getattr(itup, att->attnum,
2580  tupleDescriptor,
2581  &isnull[i]);
2582  if (att->attbyval || att->attlen != -1 || isnull[i])
2583  continue;
2584 
2585  /*
2586  * Callers always pass a tuple that could safely be inserted into the
2587  * index without further processing, so an external varlena header
2588  * should never be encountered here
2589  */
2590  if (VARATT_IS_EXTERNAL(DatumGetPointer(normalized[i])))
2591  ereport(ERROR,
2592  (errcode(ERRCODE_INDEX_CORRUPTED),
2593  errmsg("external varlena datum in tuple that references heap row (%u,%u) in index \"%s\"",
2594  ItemPointerGetBlockNumber(&(itup->t_tid)),
2596  RelationGetRelationName(state->rel))));
2597  else if (VARATT_IS_COMPRESSED(DatumGetPointer(normalized[i])))
2598  {
2599  formnewtup = true;
2600  normalized[i] = PointerGetDatum(PG_DETOAST_DATUM(normalized[i]));
2601  toast_free[i] = true;
2602  }
2603  }
2604 
2605  /* Easier case: Tuple has varlena datums, none of which are compressed */
2606  if (!formnewtup)
2607  return itup;
2608 
2609  /*
2610  * Hard case: Tuple had compressed varlena datums that necessitate
2611  * creating normalized version of the tuple from uncompressed input datums
2612  * (normalized input datums). This is rather naive, but shouldn't be
2613  * necessary too often.
2614  *
2615  * Note that we rely on deterministic index_form_tuple() TOAST compression
2616  * of normalized input.
2617  */
2618  reformed = index_form_tuple(tupleDescriptor, normalized, isnull);
2619  reformed->t_tid = itup->t_tid;
2620 
2621  /* Cannot leak memory here */
2622  for (i = 0; i < tupleDescriptor->natts; i++)
2623  if (toast_free[i])
2624  pfree(DatumGetPointer(normalized[i]));
2625 
2626  return reformed;
2627 }
#define PG_DETOAST_DATUM(datum)
Definition: fmgr.h:240
IndexTuple index_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: indextuple.c:44
int i
Definition: isn.c:73
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
#define IndexTupleHasVarwidths(itup)
Definition: itup.h:72
static Datum index_getattr(IndexTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: itup.h:117
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:481
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:493
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define INDEX_MAX_KEYS
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
#define RelationGetDescr(relation)
Definition: rel.h:529
ItemPointerData t_tid
Definition: itup.h:37
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define VARATT_IS_COMPRESSED(PTR)
Definition: varatt.h:288
#define VARATT_IS_EXTERNAL(PTR)
Definition: varatt.h:289

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(), RelationGetDescr, RelationGetRelationName, IndexTupleData::t_tid, TupleDescAttr, VARATT_IS_COMPRESSED, and VARATT_IS_EXTERNAL.

Referenced by bt_target_page_check(), and bt_tuple_present_callback().

◆ bt_pivot_tuple_identical()

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

Definition at line 1779 of file verify_nbtree.c.

1780 {
1781  if (IndexTupleSize(itup1) != IndexTupleSize(itup2))
1782  return false;
1783 
1784  if (heapkeyspace)
1785  {
1786  /*
1787  * Offset number will contain important information in heapkeyspace
1788  * indexes: the number of attributes left in the pivot tuple following
1789  * suffix truncation. Don't skip over it (compare it too).
1790  */
1791  if (memcmp(&itup1->t_tid.ip_posid, &itup2->t_tid.ip_posid,
1792  IndexTupleSize(itup1) -
1793  offsetof(ItemPointerData, ip_posid)) != 0)
1794  return false;
1795  }
1796  else
1797  {
1798  /*
1799  * Cannot rely on offset number field having consistent value across
1800  * levels on pg_upgrade'd !heapkeyspace indexes. Compare contents of
1801  * tuple starting from just after item pointer (i.e. after block
1802  * number and offset number).
1803  */
1804  if (memcmp(&itup1->t_info, &itup2->t_info,
1805  IndexTupleSize(itup1) -
1806  offsetof(IndexTupleData, t_info)) != 0)
1807  return false;
1808  }
1809 
1810  return true;
1811 }
unsigned short t_info
Definition: itup.h:49
OffsetNumber ip_posid
Definition: itemptr.h:39

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

Referenced by bt_child_highkey_check().

◆ bt_posting_plain_tuple()

static IndexTuple bt_posting_plain_tuple ( IndexTuple  itup,
int  n 
)
inlinestatic

Definition at line 2644 of file verify_nbtree.c.

2645 {
2646  Assert(BTreeTupleIsPosting(itup));
2647 
2648  /* Returns non-posting-list tuple */
2649  return _bt_form_posting(itup, BTreeTupleGetPostingN(itup, n), 1);
2650 }
IndexTuple _bt_form_posting(IndexTuple base, ItemPointer htids, int nhtids)
Definition: nbtdedup.c:864
static ItemPointer BTreeTupleGetPostingN(IndexTuple posting, int n)
Definition: nbtree.h:545

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

Referenced by bt_target_page_check().

◆ bt_recheck_sibling_links()

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

Definition at line 940 of file verify_nbtree.c.

943 {
944  if (!state->readonly)
945  {
946  Buffer lbuf;
947  Buffer newtargetbuf;
948  Page page;
949  BTPageOpaque opaque;
950  BlockNumber newtargetblock;
951 
952  /* Couple locks in the usual order for nbtree: Left to right */
953  lbuf = ReadBufferExtended(state->rel, MAIN_FORKNUM, leftcurrent,
954  RBM_NORMAL, state->checkstrategy);
955  LockBuffer(lbuf, BT_READ);
956  _bt_checkpage(state->rel, lbuf);
957  page = BufferGetPage(lbuf);
958  opaque = BTPageGetOpaque(page);
959  if (P_ISDELETED(opaque))
960  {
961  /*
962  * Cannot reason about concurrently deleted page -- the left link
963  * in the page to the right is expected to point to some other
964  * page to the left (not leftcurrent page).
965  *
966  * Note that we deliberately don't give up with a half-dead page.
967  */
968  UnlockReleaseBuffer(lbuf);
969  return;
970  }
971 
972  newtargetblock = opaque->btpo_next;
973  /* Avoid self-deadlock when newtargetblock == leftcurrent */
974  if (newtargetblock != leftcurrent)
975  {
976  newtargetbuf = ReadBufferExtended(state->rel, MAIN_FORKNUM,
977  newtargetblock, RBM_NORMAL,
978  state->checkstrategy);
979  LockBuffer(newtargetbuf, BT_READ);
980  _bt_checkpage(state->rel, newtargetbuf);
981  page = BufferGetPage(newtargetbuf);
982  opaque = BTPageGetOpaque(page);
983  /* btpo_prev_from_target may have changed; update it */
984  btpo_prev_from_target = opaque->btpo_prev;
985  }
986  else
987  {
988  /*
989  * leftcurrent right sibling points back to leftcurrent block.
990  * Index is corrupt. Easiest way to handle this is to pretend
991  * that we actually read from a distinct page that has an invalid
992  * block number in its btpo_prev.
993  */
994  newtargetbuf = InvalidBuffer;
995  btpo_prev_from_target = InvalidBlockNumber;
996  }
997 
998  /*
999  * No need to check P_ISDELETED here, since new target block cannot be
1000  * marked deleted as long as we hold a lock on lbuf
1001  */
1002  if (BufferIsValid(newtargetbuf))
1003  UnlockReleaseBuffer(newtargetbuf);
1004  UnlockReleaseBuffer(lbuf);
1005 
1006  if (btpo_prev_from_target == leftcurrent)
1007  {
1008  /* Report split in left sibling, not target (or new target) */
1009  ereport(DEBUG1,
1010  (errcode(ERRCODE_INTERNAL_ERROR),
1011  errmsg_internal("harmless concurrent page split detected in index \"%s\"",
1013  errdetail_internal("Block=%u new right sibling=%u original right sibling=%u.",
1014  leftcurrent, newtargetblock,
1015  state->targetblock)));
1016  return;
1017  }
1018 
1019  /*
1020  * Index is corrupt. Make sure that we report correct target page.
1021  *
1022  * This could have changed in cases where there was a concurrent page
1023  * split, as well as index corruption (at least in theory). Note that
1024  * btpo_prev_from_target was already updated above.
1025  */
1026  state->targetblock = newtargetblock;
1027  }
1028 
1029  ereport(ERROR,
1030  (errcode(ERRCODE_INDEX_CORRUPTED),
1031  errmsg("left link/right link pair in index \"%s\" not in agreement",
1033  errdetail_internal("Block=%u left block=%u left link from block=%u.",
1034  state->targetblock, leftcurrent,
1035  btpo_prev_from_target)));
1036 }
int Buffer
Definition: buf.h:23
#define InvalidBuffer
Definition: buf.h:25
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4008
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4226
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:751
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:284
@ RBM_NORMAL
Definition: bufmgr.h:44
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:232
void _bt_checkpage(Relation rel, Buffer buf)
Definition: nbtpage.c:794
#define BT_READ
Definition: nbtree.h:720

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

Referenced by bt_check_level_from_leftmost().

◆ bt_right_page_check_scankey()

static BTScanInsert bt_right_page_check_scankey ( BtreeCheckState state)
static

Definition at line 1573 of file verify_nbtree.c.

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

References bt_mkscankey_pivotsearch(), BTPageGetOpaque, 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(), palloc_btree_page(), pfree(), and RelationGetRelationName.

Referenced by bt_target_page_check().

◆ bt_rootdescend()

static bool bt_rootdescend ( BtreeCheckState state,
IndexTuple  itup 
)
static

Definition at line 2677 of file verify_nbtree.c.

2678 {
2679  BTScanInsert key;
2680  BTStack stack;
2681  Buffer lbuf;
2682  bool exists;
2683 
2684  key = _bt_mkscankey(state->rel, itup);
2685  Assert(key->heapkeyspace && key->scantid != NULL);
2686 
2687  /*
2688  * Search from root.
2689  *
2690  * Ideally, we would arrange to only move right within _bt_search() when
2691  * an interrupted page split is detected (i.e. when the incomplete split
2692  * bit is found to be set), but for now we accept the possibility that
2693  * that could conceal an inconsistency.
2694  */
2695  Assert(state->readonly && state->rootdescend);
2696  exists = false;
2697  stack = _bt_search(state->rel, key, &lbuf, BT_READ, NULL);
2698 
2699  if (BufferIsValid(lbuf))
2700  {
2701  BTInsertStateData insertstate;
2702  OffsetNumber offnum;
2703  Page page;
2704 
2705  insertstate.itup = itup;
2706  insertstate.itemsz = MAXALIGN(IndexTupleSize(itup));
2707  insertstate.itup_key = key;
2708  insertstate.postingoff = 0;
2709  insertstate.bounds_valid = false;
2710  insertstate.buf = lbuf;
2711 
2712  /* Get matching tuple on leaf page */
2713  offnum = _bt_binsrch_insert(state->rel, &insertstate);
2714  /* Compare first >= matching item on leaf page, if any */
2715  page = BufferGetPage(lbuf);
2716  /* Should match on first heap TID when tuple has a posting list */
2717  if (offnum <= PageGetMaxOffsetNumber(page) &&
2718  insertstate.postingoff <= 0 &&
2719  _bt_compare(state->rel, key, page, offnum) == 0)
2720  exists = true;
2721  _bt_relbuf(state->rel, lbuf);
2722  }
2723 
2724  _bt_freestack(stack);
2725  pfree(key);
2726 
2727  return exists;
2728 }
#define MAXALIGN(LEN)
Definition: c.h:795
void _bt_relbuf(Relation rel, Buffer buf)
Definition: nbtpage.c:1035
OffsetNumber _bt_binsrch_insert(Relation rel, BTInsertState insertstate)
Definition: nbtsearch.c:442
int32 _bt_compare(Relation rel, BTScanInsert key, Page page, OffsetNumber offnum)
Definition: nbtsearch.c:656
BTStack _bt_search(Relation rel, BTScanInsert key, Buffer *bufP, int access, Snapshot snapshot)
Definition: nbtsearch.c:96
void _bt_freestack(BTStack stack)
Definition: nbtutils.c:182
bool bounds_valid
Definition: nbtree.h:829
IndexTuple itup
Definition: nbtree.h:817
BTScanInsert itup_key
Definition: nbtree.h:819

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

Referenced by bt_target_page_check().

◆ bt_target_page_check()

static void bt_target_page_check ( BtreeCheckState state)
static

Definition at line 1074 of file verify_nbtree.c.

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

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, BTPageGetOpaque, BTPageOpaqueData::btpo_level, BTreeTupleGetHeapTID(), BTreeTupleGetMaxHeapTID(), BTreeTupleGetNAtts, BTreeTupleGetNPosting(), BTreeTupleGetPointsToTID(), BTreeTupleGetPostingN(), BTreeTupleIsPosting(), CHECK_FOR_INTERRUPTS, DEBUG2, elog(), ereport, errcode(), errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, 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(), palloc_btree_page(), pfree(), psprintf(), RelationGetRelationName, and BTScanInsertData::scantid.

Referenced by bt_check_level_from_leftmost().

◆ 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 2486 of file verify_nbtree.c.

2488 {
2489  BtreeCheckState *state = (BtreeCheckState *) checkstate;
2490  IndexTuple itup,
2491  norm;
2492 
2493  Assert(state->heapallindexed);
2494 
2495  /* Generate a normalized index tuple for fingerprinting */
2496  itup = index_form_tuple(RelationGetDescr(index), values, isnull);
2497  itup->t_tid = *tid;
2498  norm = bt_normalize_tuple(state, itup);
2499 
2500  /* Probe Bloom filter -- tuple should be present */
2501  if (bloom_lacks_element(state->filter, (unsigned char *) norm,
2502  IndexTupleSize(norm)))
2503  ereport(ERROR,
2505  errmsg("heap tuple (%u,%u) from table \"%s\" lacks matching index tuple within index \"%s\"",
2506  ItemPointerGetBlockNumber(&(itup->t_tid)),
2508  RelationGetRelationName(state->heaprel),
2510  !state->readonly
2511  ? errhint("Retrying verification using the function bt_index_parent_check() might provide a more specific error.")
2512  : 0));
2513 
2514  state->heaptuplespresent++;
2515  pfree(itup);
2516  /* Cannot leak memory here */
2517  if (norm != itup)
2518  pfree(norm);
2519 }
bool bloom_lacks_element(bloom_filter *filter, unsigned char *elem, size_t len)
Definition: bloomfilter.c:157
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
Definition: type.h:95

References Assert(), bloom_lacks_element(), bt_normalize_tuple(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errhint(), errmsg(), ERROR, index_form_tuple(), IndexTupleSize, ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), pfree(), RelationGetDescr, RelationGetRelationName, IndexTupleData::t_tid, and values.

Referenced by bt_check_every_level().

◆ btree_index_checkable()

static void btree_index_checkable ( Relation  rel)
inlinestatic

Definition at line 376 of file verify_nbtree.c.

377 {
378  if (rel->rd_rel->relkind != RELKIND_INDEX ||
379  rel->rd_rel->relam != BTREE_AM_OID)
380  ereport(ERROR,
381  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
382  errmsg("only B-Tree indexes are supported as targets for verification"),
383  errdetail("Relation \"%s\" is not a B-Tree index.",
384  RelationGetRelationName(rel))));
385 
386  if (RELATION_IS_OTHER_TEMP(rel))
387  ereport(ERROR,
388  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
389  errmsg("cannot access temporary tables of other sessions"),
390  errdetail("Index \"%s\" is associated with temporary relation.",
391  RelationGetRelationName(rel))));
392 
393  if (!rel->rd_index->indisvalid)
394  ereport(ERROR,
395  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
396  errmsg("cannot check index \"%s\"",
398  errdetail("Index is not valid.")));
399 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:658

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

Referenced by bt_index_check_internal().

◆ btree_index_mainfork_expected()

static bool btree_index_mainfork_expected ( Relation  rel)
inlinestatic

Definition at line 410 of file verify_nbtree.c.

411 {
412  if (rel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED ||
414  return true;
415 
416  ereport(DEBUG1,
417  (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
418  errmsg("cannot verify unlogged index \"%s\" during recovery, skipping",
419  RelationGetRelationName(rel))));
420 
421  return false;
422 }
bool RecoveryInProgress(void)
Definition: xlog.c:5907

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

Referenced by bt_index_check_internal().

◆ BTreeTupleGetHeapTIDCareful()

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

Definition at line 3200 of file verify_nbtree.c.

3202 {
3203  ItemPointer htid;
3204 
3205  /*
3206  * Caller determines whether this is supposed to be a pivot or non-pivot
3207  * tuple using page type and item offset number. Verify that tuple
3208  * metadata agrees with this.
3209  */
3210  Assert(state->heapkeyspace);
3211  if (BTreeTupleIsPivot(itup) && nonpivot)
3212  ereport(ERROR,
3213  (errcode(ERRCODE_INDEX_CORRUPTED),
3214  errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected pivot tuple",
3215  state->targetblock,
3216  RelationGetRelationName(state->rel))));
3217 
3218  if (!BTreeTupleIsPivot(itup) && !nonpivot)
3219  ereport(ERROR,
3220  (errcode(ERRCODE_INDEX_CORRUPTED),
3221  errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected non-pivot tuple",
3222  state->targetblock,
3223  RelationGetRelationName(state->rel))));
3224 
3225  htid = BTreeTupleGetHeapTID(itup);
3226  if (!ItemPointerIsValid(htid) && nonpivot)
3227  ereport(ERROR,
3228  (errcode(ERRCODE_INDEX_CORRUPTED),
3229  errmsg("block %u or its right sibling block or child block in index \"%s\" contains non-pivot tuple that lacks a heap TID",
3230  state->targetblock,
3231  RelationGetRelationName(state->rel))));
3232 
3233  return htid;
3234 }
static bool ItemPointerIsValid(const ItemPointerData *pointer)
Definition: itemptr.h:83

References Assert(), BTreeTupleGetHeapTID(), BTreeTupleIsPivot(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, ItemPointerIsValid(), and RelationGetRelationName.

Referenced by invariant_l_nontarget_offset(), and invariant_l_offset().

◆ BTreeTupleGetPointsToTID()

static ItemPointer BTreeTupleGetPointsToTID ( IndexTuple  itup)
inlinestatic

Definition at line 3248 of file verify_nbtree.c.

3249 {
3250  /*
3251  * Rely on the assumption that !heapkeyspace internal page data items will
3252  * correctly return TID with downlink here -- BTreeTupleGetHeapTID() won't
3253  * recognize it as a pivot tuple, but everything still works out because
3254  * the t_tid field is still returned
3255  */
3256  if (!BTreeTupleIsPivot(itup))
3257  return BTreeTupleGetHeapTID(itup);
3258 
3259  /* Pivot tuple returns TID with downlink block (heapkeyspace variant) */
3260  return &itup->t_tid;
3261 }

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

Referenced by bt_target_page_check().

◆ invariant_g_offset()

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

Definition at line 2862 of file verify_nbtree.c.

2864 {
2865  int32 cmp;
2866 
2867  Assert(key->pivotsearch);
2868 
2869  cmp = _bt_compare(state->rel, key, state->target, lowerbound);
2870 
2871  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2872  if (!key->heapkeyspace)
2873  return cmp >= 0;
2874 
2875  /*
2876  * No need to consider the possibility that scankey has attributes that we
2877  * need to force to be interpreted as negative infinity. _bt_compare() is
2878  * able to determine that scankey is greater than negative infinity. The
2879  * distinction between "==" and "<" isn't interesting here, since
2880  * corruption is indicated either way.
2881  */
2882  return cmp > 0;
2883 }
signed int int32
Definition: c.h:478
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:747

References _bt_compare(), Assert(), cmp(), and sort-test::key.

Referenced by bt_target_page_check().

◆ invariant_l_nontarget_offset()

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

Definition at line 2898 of file verify_nbtree.c.

2901 {
2902  ItemId itemid;
2903  int32 cmp;
2904 
2905  Assert(key->pivotsearch);
2906 
2907  /* Verify line pointer before checking tuple */
2908  itemid = PageGetItemIdCareful(state, nontargetblock, nontarget,
2909  upperbound);
2910  cmp = _bt_compare(state->rel, key, nontarget, upperbound);
2911 
2912  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2913  if (!key->heapkeyspace)
2914  return cmp <= 0;
2915 
2916  /* See invariant_l_offset() for an explanation of this extra step */
2917  if (cmp == 0)
2918  {
2919  IndexTuple child;
2920  int uppnkeyatts;
2921  ItemPointer childheaptid;
2922  BTPageOpaque copaque;
2923  bool nonpivot;
2924 
2925  child = (IndexTuple) PageGetItem(nontarget, itemid);
2926  copaque = BTPageGetOpaque(nontarget);
2927  nonpivot = P_ISLEAF(copaque) && upperbound >= P_FIRSTDATAKEY(copaque);
2928 
2929  /* Get number of keys + heap TID for child/non-target item */
2930  uppnkeyatts = BTreeTupleGetNKeyAtts(child, state->rel);
2931  childheaptid = BTreeTupleGetHeapTIDCareful(state, child, nonpivot);
2932 
2933  /* Heap TID is tiebreaker key attribute */
2934  if (key->keysz == uppnkeyatts)
2935  return key->scantid == NULL && childheaptid != NULL;
2936 
2937  return key->keysz < uppnkeyatts;
2938  }
2939 
2940  return cmp < 0;
2941 }
static ItemPointer BTreeTupleGetHeapTIDCareful(BtreeCheckState *state, IndexTuple itup, bool nonpivot)
#define BTreeTupleGetNKeyAtts(itup, rel)
Definition: verify_nbtree.c:52

References _bt_compare(), Assert(), BTPageGetOpaque, BTreeTupleGetHeapTIDCareful(), BTreeTupleGetNKeyAtts, cmp(), sort-test::key, P_FIRSTDATAKEY, P_ISLEAF, PageGetItem(), and PageGetItemIdCareful().

Referenced by bt_child_check().

◆ invariant_l_offset()

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

Definition at line 2776 of file verify_nbtree.c.

2778 {
2779  ItemId itemid;
2780  int32 cmp;
2781 
2782  Assert(key->pivotsearch);
2783 
2784  /* Verify line pointer before checking tuple */
2785  itemid = PageGetItemIdCareful(state, state->targetblock, state->target,
2786  upperbound);
2787  /* pg_upgrade'd indexes may legally have equal sibling tuples */
2788  if (!key->heapkeyspace)
2789  return invariant_leq_offset(state, key, upperbound);
2790 
2791  cmp = _bt_compare(state->rel, key, state->target, upperbound);
2792 
2793  /*
2794  * _bt_compare() is capable of determining that a scankey with a
2795  * filled-out attribute is greater than pivot tuples where the comparison
2796  * is resolved at a truncated attribute (value of attribute in pivot is
2797  * minus infinity). However, it is not capable of determining that a
2798  * scankey is _less than_ a tuple on the basis of a comparison resolved at
2799  * _scankey_ minus infinity attribute. Complete an extra step to simulate
2800  * having minus infinity values for omitted scankey attribute(s).
2801  */
2802  if (cmp == 0)
2803  {
2804  BTPageOpaque topaque;
2805  IndexTuple ritup;
2806  int uppnkeyatts;
2807  ItemPointer rheaptid;
2808  bool nonpivot;
2809 
2810  ritup = (IndexTuple) PageGetItem(state->target, itemid);
2811  topaque = BTPageGetOpaque(state->target);
2812  nonpivot = P_ISLEAF(topaque) && upperbound >= P_FIRSTDATAKEY(topaque);
2813 
2814  /* Get number of keys + heap TID for item to the right */
2815  uppnkeyatts = BTreeTupleGetNKeyAtts(ritup, state->rel);
2816  rheaptid = BTreeTupleGetHeapTIDCareful(state, ritup, nonpivot);
2817 
2818  /* Heap TID is tiebreaker key attribute */
2819  if (key->keysz == uppnkeyatts)
2820  return key->scantid == NULL && rheaptid != NULL;
2821 
2822  return key->keysz < uppnkeyatts;
2823  }
2824 
2825  return cmp < 0;
2826 }

References _bt_compare(), Assert(), BTPageGetOpaque, BTreeTupleGetHeapTIDCareful(), BTreeTupleGetNKeyAtts, cmp(), invariant_leq_offset(), sort-test::key, P_FIRSTDATAKEY, P_ISLEAF, PageGetItem(), and PageGetItemIdCareful().

Referenced by bt_target_page_check().

◆ invariant_leq_offset()

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

Definition at line 2839 of file verify_nbtree.c.

2841 {
2842  int32 cmp;
2843 
2844  Assert(key->pivotsearch);
2845 
2846  cmp = _bt_compare(state->rel, key, state->target, upperbound);
2847 
2848  return cmp <= 0;
2849 }

References _bt_compare(), Assert(), cmp(), and sort-test::key.

Referenced by bt_target_page_check(), and invariant_l_offset().

◆ offset_is_negative_infinity()

static bool offset_is_negative_infinity ( BTPageOpaque  opaque,
OffsetNumber  offset 
)
inlinestatic

Definition at line 2741 of file verify_nbtree.c.

2742 {
2743  /*
2744  * For internal pages only, the first item after high key, if any, is
2745  * negative infinity item. Internal pages always have a negative infinity
2746  * item, whereas leaf pages never have one. This implies that negative
2747  * infinity item is either first or second line item, or there is none
2748  * within page.
2749  *
2750  * Negative infinity items are a special case among pivot tuples. They
2751  * always have zero attributes, while all other pivot tuples always have
2752  * nkeyatts attributes.
2753  *
2754  * Right-most pages don't have a high key, but could be said to
2755  * conceptually have a "positive infinity" high key. Thus, there is a
2756  * symmetry between down link items in parent pages, and high keys in
2757  * children. Together, they represent the part of the key space that
2758  * belongs to each page in the index. For example, all children of the
2759  * root page will have negative infinity as a lower bound from root
2760  * negative infinity downlink, and positive infinity as an upper bound
2761  * (implicitly, from "imaginary" positive infinity high key in root).
2762  */
2763  return !P_ISLEAF(opaque) && offset == P_FIRSTDATAKEY(opaque);
2764 }

References P_FIRSTDATAKEY, and P_ISLEAF.

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

◆ PageGetItemIdCareful()

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

Definition at line 3160 of file verify_nbtree.c.

3162 {
3163  ItemId itemid = PageGetItemId(page, offset);
3164 
3165  if (ItemIdGetOffset(itemid) + ItemIdGetLength(itemid) >
3166  BLCKSZ - MAXALIGN(sizeof(BTPageOpaqueData)))
3167  ereport(ERROR,
3168  (errcode(ERRCODE_INDEX_CORRUPTED),
3169  errmsg("line pointer points past end of tuple space in index \"%s\"",
3171  errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.",
3172  block, offset, ItemIdGetOffset(itemid),
3173  ItemIdGetLength(itemid),
3174  ItemIdGetFlags(itemid))));
3175 
3176  /*
3177  * Verify that line pointer isn't LP_REDIRECT or LP_UNUSED, since nbtree
3178  * never uses either. Verify that line pointer has storage, too, since
3179  * even LP_DEAD items should within nbtree.
3180  */
3181  if (ItemIdIsRedirected(itemid) || !ItemIdIsUsed(itemid) ||
3182  ItemIdGetLength(itemid) == 0)
3183  ereport(ERROR,
3184  (errcode(ERRCODE_INDEX_CORRUPTED),
3185  errmsg("invalid line pointer storage in index \"%s\"",
3187  errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.",
3188  block, offset, ItemIdGetOffset(itemid),
3189  ItemIdGetLength(itemid),
3190  ItemIdGetFlags(itemid))));
3191 
3192  return itemid;
3193 }
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
#define ItemIdGetOffset(itemId)
Definition: itemid.h:65
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
#define ItemIdGetFlags(itemId)
Definition: itemid.h:71

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

◆ palloc_btree_page()

static Page palloc_btree_page ( BtreeCheckState state,
BlockNumber  blocknum 
)
static

Definition at line 2958 of file verify_nbtree.c.

2959 {
2960  Buffer buffer;
2961  Page page;
2962  BTPageOpaque opaque;
2963  OffsetNumber maxoffset;
2964 
2965  page = palloc(BLCKSZ);
2966 
2967  /*
2968  * We copy the page into local storage to avoid holding pin on the buffer
2969  * longer than we must.
2970  */
2971  buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum, RBM_NORMAL,
2972  state->checkstrategy);
2973  LockBuffer(buffer, BT_READ);
2974 
2975  /*
2976  * Perform the same basic sanity checking that nbtree itself performs for
2977  * every page:
2978  */
2979  _bt_checkpage(state->rel, buffer);
2980 
2981  /* Only use copy of page in palloc()'d memory */
2982  memcpy(page, BufferGetPage(buffer), BLCKSZ);
2983  UnlockReleaseBuffer(buffer);
2984 
2985  opaque = BTPageGetOpaque(page);
2986 
2987  if (P_ISMETA(opaque) && blocknum != BTREE_METAPAGE)
2988  ereport(ERROR,
2989  (errcode(ERRCODE_INDEX_CORRUPTED),
2990  errmsg("invalid meta page found at block %u in index \"%s\"",
2991  blocknum, RelationGetRelationName(state->rel))));
2992 
2993  /* Check page from block that ought to be meta page */
2994  if (blocknum == BTREE_METAPAGE)
2995  {
2996  BTMetaPageData *metad = BTPageGetMeta(page);
2997 
2998  if (!P_ISMETA(opaque) ||
2999  metad->btm_magic != BTREE_MAGIC)
3000  ereport(ERROR,
3001  (errcode(ERRCODE_INDEX_CORRUPTED),
3002  errmsg("index \"%s\" meta page is corrupt",
3003  RelationGetRelationName(state->rel))));
3004 
3005  if (metad->btm_version < BTREE_MIN_VERSION ||
3006  metad->btm_version > BTREE_VERSION)
3007  ereport(ERROR,
3008  (errcode(ERRCODE_INDEX_CORRUPTED),
3009  errmsg("version mismatch in index \"%s\": file version %d, "
3010  "current version %d, minimum supported version %d",
3012  metad->btm_version, BTREE_VERSION,
3013  BTREE_MIN_VERSION)));
3014 
3015  /* Finished with metapage checks */
3016  return page;
3017  }
3018 
3019  /*
3020  * Deleted pages that still use the old 32-bit XID representation have no
3021  * sane "level" field because they type pun the field, but all other pages
3022  * (including pages deleted on Postgres 14+) have a valid value.
3023  */
3024  if (!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque))
3025  {
3026  /* Okay, no reason not to trust btpo_level field from page */
3027 
3028  if (P_ISLEAF(opaque) && opaque->btpo_level != 0)
3029  ereport(ERROR,
3030  (errcode(ERRCODE_INDEX_CORRUPTED),
3031  errmsg_internal("invalid leaf page level %u for block %u in index \"%s\"",
3032  opaque->btpo_level, blocknum,
3033  RelationGetRelationName(state->rel))));
3034 
3035  if (!P_ISLEAF(opaque) && opaque->btpo_level == 0)
3036  ereport(ERROR,
3037  (errcode(ERRCODE_INDEX_CORRUPTED),
3038  errmsg_internal("invalid internal page level 0 for block %u in index \"%s\"",
3039  blocknum,
3040  RelationGetRelationName(state->rel))));
3041  }
3042 
3043  /*
3044  * Sanity checks for number of items on page.
3045  *
3046  * As noted at the beginning of _bt_binsrch(), an internal page must have
3047  * children, since there must always be a negative infinity downlink
3048  * (there may also be a highkey). In the case of non-rightmost leaf
3049  * pages, there must be at least a highkey. The exceptions are deleted
3050  * pages, which contain no items.
3051  *
3052  * This is correct when pages are half-dead, since internal pages are
3053  * never half-dead, and leaf pages must have a high key when half-dead
3054  * (the rightmost page can never be deleted). It's also correct with
3055  * fully deleted pages: _bt_unlink_halfdead_page() doesn't change anything
3056  * about the target page other than setting the page as fully dead, and
3057  * setting its xact field. In particular, it doesn't change the sibling
3058  * links in the deletion target itself, since they're required when index
3059  * scans land on the deletion target, and then need to move right (or need
3060  * to move left, in the case of backward index scans).
3061  */
3062  maxoffset = PageGetMaxOffsetNumber(page);
3063  if (maxoffset > MaxIndexTuplesPerPage)
3064  ereport(ERROR,
3065  (errcode(ERRCODE_INDEX_CORRUPTED),
3066  errmsg("Number of items on block %u of index \"%s\" exceeds MaxIndexTuplesPerPage (%u)",
3067  blocknum, RelationGetRelationName(state->rel),
3069 
3070  if (!P_ISLEAF(opaque) && !P_ISDELETED(opaque) && maxoffset < P_FIRSTDATAKEY(opaque))
3071  ereport(ERROR,
3072  (errcode(ERRCODE_INDEX_CORRUPTED),
3073  errmsg("internal block %u in index \"%s\" lacks high key and/or at least one downlink",
3074  blocknum, RelationGetRelationName(state->rel))));
3075 
3076  if (P_ISLEAF(opaque) && !P_ISDELETED(opaque) && !P_RIGHTMOST(opaque) && maxoffset < P_HIKEY)
3077  ereport(ERROR,
3078  (errcode(ERRCODE_INDEX_CORRUPTED),
3079  errmsg("non-rightmost leaf block %u in index \"%s\" lacks high key item",
3080  blocknum, RelationGetRelationName(state->rel))));
3081 
3082  /*
3083  * In general, internal pages are never marked half-dead, except on
3084  * versions of Postgres prior to 9.4, where it can be valid transient
3085  * state. This state is nonetheless treated as corruption by VACUUM on
3086  * from version 9.4 on, so do the same here. See _bt_pagedel() for full
3087  * details.
3088  */
3089  if (!P_ISLEAF(opaque) && P_ISHALFDEAD(opaque))
3090  ereport(ERROR,
3091  (errcode(ERRCODE_INDEX_CORRUPTED),
3092  errmsg("internal page block %u in index \"%s\" is half-dead",
3093  blocknum, RelationGetRelationName(state->rel)),
3094  errhint("This can be caused by an interrupted VACUUM in version 9.3 or older, before upgrade. Please REINDEX it.")));
3095 
3096  /*
3097  * Check that internal pages have no garbage items, and that no page has
3098  * an invalid combination of deletion-related page level flags
3099  */
3100  if (!P_ISLEAF(opaque) && P_HAS_GARBAGE(opaque))
3101  ereport(ERROR,
3102  (errcode(ERRCODE_INDEX_CORRUPTED),
3103  errmsg_internal("internal page block %u in index \"%s\" has garbage items",
3104  blocknum, RelationGetRelationName(state->rel))));
3105 
3106  if (P_HAS_FULLXID(opaque) && !P_ISDELETED(opaque))
3107  ereport(ERROR,
3108  (errcode(ERRCODE_INDEX_CORRUPTED),
3109  errmsg_internal("full transaction id page flag appears in non-deleted block %u in index \"%s\"",
3110  blocknum, RelationGetRelationName(state->rel))));
3111 
3112  if (P_ISDELETED(opaque) && P_ISHALFDEAD(opaque))
3113  ereport(ERROR,
3114  (errcode(ERRCODE_INDEX_CORRUPTED),
3115  errmsg_internal("deleted page block %u in index \"%s\" is half-dead",
3116  blocknum, RelationGetRelationName(state->rel))));
3117 
3118  return page;
3119 }
#define MaxIndexTuplesPerPage
Definition: itup.h:165
void * palloc(Size size)
Definition: mcxt.c:1210
#define BTREE_MIN_VERSION
Definition: nbtree.h:151
#define P_HAS_GARBAGE(opaque)
Definition: nbtree.h:226
#define P_ISMETA(opaque)
Definition: nbtree.h:223
#define BTREE_MAGIC
Definition: nbtree.h:149
#define BTREE_VERSION
Definition: nbtree.h:150
uint32 btm_version
Definition: nbtree.h:106
uint32 btm_magic
Definition: nbtree.h:105

References _bt_checkpage(), BT_READ, BTMetaPageData::btm_magic, BTMetaPageData::btm_version, BTPageGetMeta, BTPageGetOpaque, BTPageOpaqueData::btpo_level, BTREE_MAGIC, BTREE_METAPAGE, BTREE_MIN_VERSION, BTREE_VERSION, BufferGetPage(), 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(), palloc(), RBM_NORMAL, ReadBufferExtended(), 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().

◆ 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 45 of file verify_nbtree.c.