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/memutils.h"
#include "utils/snapmgr.h"
Include dependency graph for verify_nbtree.c:

Go to the source code of this file.

Data Structures

struct  BtreeCheckState
 
struct  BtreeLevel
 

Macros

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

Typedefs

typedef struct BtreeCheckState BtreeCheckState
 
typedef struct BtreeLevel BtreeLevel
 

Functions

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

Variables

 PG_MODULE_MAGIC
 

Macro Definition Documentation

◆ BTreeTupleGetNKeyAtts

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

Definition at line 51 of file verify_nbtree.c.

◆ InvalidBtreeLevel

#define InvalidBtreeLevel   ((uint32) InvalidBlockNumber)

Definition at line 50 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 447 of file verify_nbtree.c.

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

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

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

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

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  targetblock,
Page  target 
)
static

Definition at line 2262 of file verify_nbtree.c.

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

203 {
204  Oid indrelid = PG_GETARG_OID(0);
205  bool heapallindexed = false;
206 
207  if (PG_NARGS() == 2)
208  heapallindexed = PG_GETARG_BOOL(1);
209 
210  bt_index_check_internal(indrelid, false, heapallindexed, false);
211 
212  PG_RETURN_VOID();
213 }
#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 245 of file verify_nbtree.c.

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

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

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

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

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

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

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

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

References IndexTupleSize, ItemPointerData::ip_posid, offsetof, 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 2643 of file verify_nbtree.c.

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

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

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

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

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

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

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

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

2487 {
2488  BtreeCheckState *state = (BtreeCheckState *) checkstate;
2489  IndexTuple itup,
2490  norm;
2491 
2492  Assert(state->heapallindexed);
2493 
2494  /* Generate a normalized index tuple for fingerprinting */
2495  itup = index_form_tuple(RelationGetDescr(index), values, isnull);
2496  itup->t_tid = *tid;
2497  norm = bt_normalize_tuple(state, itup);
2498 
2499  /* Probe Bloom filter -- tuple should be present */
2500  if (bloom_lacks_element(state->filter, (unsigned char *) norm,
2501  IndexTupleSize(norm)))
2502  ereport(ERROR,
2504  errmsg("heap tuple (%u,%u) from table \"%s\" lacks matching index tuple within index \"%s\"",
2505  ItemPointerGetBlockNumber(&(itup->t_tid)),
2507  RelationGetRelationName(state->heaprel),
2509  !state->readonly
2510  ? errhint("Retrying verification using the function bt_index_parent_check() might provide a more specific error.")
2511  : 0));
2512 
2513  state->heaptuplespresent++;
2514  pfree(itup);
2515  /* Cannot leak memory here */
2516  if (norm != itup)
2517  pfree(norm);
2518 }
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:43
Definition: type.h:90

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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