PostgreSQL Source Code git master
Loading...
Searching...
No Matches
verify_nbtree.c File Reference
#include "postgres.h"
#include "access/heaptoast.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 "verify_common.h"
#include "catalog/index.h"
#include "catalog/pg_am.h"
#include "catalog/pg_opfamily_d.h"
#include "common/pg_prng.h"
#include "lib/bloomfilter.h"
#include "miscadmin.h"
#include "storage/smgr.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
Include dependency graph for verify_nbtree.c:

Go to the source code of this file.

Data Structures

struct  BtreeCheckState
 
struct  BtreeLevel
 
struct  BtreeLastVisibleEntry
 
struct  BTCallbackState
 

Macros

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

Typedefs

typedef struct BtreeCheckState BtreeCheckState
 
typedef struct BtreeLevel BtreeLevel
 
typedef struct BtreeLastVisibleEntry BtreeLastVisibleEntry
 
typedef struct BTCallbackState BTCallbackState
 

Functions

 PG_MODULE_MAGIC_EXT (.name="amcheck",.version=PG_VERSION)
 
 PG_FUNCTION_INFO_V1 (bt_index_check)
 
 PG_FUNCTION_INFO_V1 (bt_index_parent_check)
 
static void bt_index_check_callback (Relation indrel, Relation heaprel, void *state, bool readonly)
 
static void bt_check_every_level (Relation rel, Relation heaprel, bool heapkeyspace, bool readonly, bool heapallindexed, bool rootdescend, bool checkunique)
 
static BtreeLevel bt_check_level_from_leftmost (BtreeCheckState *state, BtreeLevel level)
 
static bool bt_leftmost_ignoring_half_dead (BtreeCheckState *state, BlockNumber start, BTPageOpaque start_opaque)
 
static void bt_recheck_sibling_links (BtreeCheckState *state, BlockNumber btpo_prev_from_target, BlockNumber leftcurrent)
 
static bool heap_entry_is_visible (BtreeCheckState *state, ItemPointer tid)
 
static void bt_report_duplicate (BtreeCheckState *state, BtreeLastVisibleEntry *lVis, ItemPointer nexttid, BlockNumber nblock, OffsetNumber noffset, int nposting)
 
static void bt_entry_unique_check (BtreeCheckState *state, IndexTuple itup, BlockNumber targetblock, OffsetNumber offset, BtreeLastVisibleEntry *lVis)
 
static void bt_target_page_check (BtreeCheckState *state)
 
static BTScanInsert bt_right_page_check_scankey (BtreeCheckState *state, OffsetNumber *rightfirstoffset)
 
static void bt_child_check (BtreeCheckState *state, BTScanInsert targetkey, OffsetNumber downlinkoffnum)
 
static void bt_child_highkey_check (BtreeCheckState *state, OffsetNumber target_downlinkoffnum, Page loaded_child, uint32 target_level)
 
static void bt_downlink_missing_check (BtreeCheckState *state, bool rightsplit, BlockNumber blkno, Page page)
 
static void bt_tuple_present_callback (Relation index, ItemPointer tid, Datum *values, bool *isnull, bool tupleIsAlive, void *checkstate)
 
static IndexTuple bt_normalize_tuple (BtreeCheckState *state, IndexTuple itup)
 
static IndexTuple bt_posting_plain_tuple (IndexTuple itup, int n)
 
static bool bt_rootdescend (BtreeCheckState *state, IndexTuple itup)
 
static bool offset_is_negative_infinity (BTPageOpaque opaque, OffsetNumber offset)
 
static bool invariant_l_offset (BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound)
 
static bool invariant_leq_offset (BtreeCheckState *state, BTScanInsert key, OffsetNumber upperbound)
 
static bool invariant_g_offset (BtreeCheckState *state, BTScanInsert key, OffsetNumber lowerbound)
 
static bool invariant_l_nontarget_offset (BtreeCheckState *state, BTScanInsert key, BlockNumber nontargetblock, Page nontarget, OffsetNumber upperbound)
 
static Page palloc_btree_page (BtreeCheckState *state, BlockNumber blocknum)
 
static BTScanInsert bt_mkscankey_pivotsearch (Relation rel, IndexTuple itup)
 
static ItemId PageGetItemIdCareful (BtreeCheckState *state, BlockNumber block, Page page, OffsetNumber offset)
 
static ItemPointer BTreeTupleGetHeapTIDCareful (BtreeCheckState *state, IndexTuple itup, bool nonpivot)
 
static ItemPointer BTreeTupleGetPointsToTID (IndexTuple itup)
 
Datum bt_index_check (PG_FUNCTION_ARGS)
 
Datum bt_index_parent_check (PG_FUNCTION_ARGS)
 
static bool bt_pivot_tuple_identical (bool heapkeyspace, IndexTuple itup1, IndexTuple itup2)
 

Macro Definition Documentation

◆ BTreeTupleGetNKeyAtts

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

Definition at line 56 of file verify_nbtree.c.

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

◆ InvalidBtreeLevel

#define InvalidBtreeLevel   ((uint32) InvalidBlockNumber)

Definition at line 55 of file verify_nbtree.c.

Typedef Documentation

◆ BTCallbackState

◆ BtreeCheckState

◆ BtreeLastVisibleEntry

◆ 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,
bool  checkunique 
)
static

Definition at line 378 of file verify_nbtree.c.

381{
386 BtreeLevel current;
387
388 if (!readonly)
389 elog(DEBUG1, "verifying consistency of tree structure for index \"%s\"",
391 else
392 elog(DEBUG1, "verifying consistency of tree structure for index \"%s\" with cross-level checks",
394
395 /*
396 * This assertion matches the one in index_getnext_tid(). See page
397 * recycling/"visible to everyone" notes in nbtree README.
398 */
400
401 /*
402 * Initialize state for entire verification operation
403 */
405 state->rel = rel;
406 state->heaprel = heaprel;
407 state->heapkeyspace = heapkeyspace;
408 state->readonly = readonly;
409 state->heapallindexed = heapallindexed;
410 state->rootdescend = rootdescend;
411 state->checkunique = checkunique;
412 state->snapshot = InvalidSnapshot;
413
414 if (state->heapallindexed)
415 {
418 uint64 seed;
419
420 /*
421 * Size Bloom filter based on estimated number of tuples in index,
422 * while conservatively assuming that each block must contain at least
423 * MaxTIDsPerBTreePage / 3 "plain" tuples -- see
424 * bt_posting_plain_tuple() for definition, and details of how posting
425 * list tuples are handled.
426 */
429 (int64) state->rel->rd_rel->reltuples);
430 /* Generate a random seed to avoid repetition */
432 /* Create Bloom filter to fingerprint index */
434 state->heaptuplespresent = 0;
435
436 /*
437 * Register our own snapshot for heapallindexed, rather than asking
438 * table_index_build_scan() to do this for us later. This needs to
439 * happen before index fingerprinting begins, so we can later be
440 * certain that index fingerprinting should have reached all tuples
441 * returned by table_index_build_scan().
442 */
444
445 /*
446 * GetTransactionSnapshot() always acquires a new MVCC snapshot in
447 * READ COMMITTED mode. A new snapshot is guaranteed to have all the
448 * entries it requires in the index.
449 *
450 * We must defend against the possibility that an old xact snapshot
451 * was returned at higher isolation levels when that snapshot is not
452 * safe for index scans of the target index. This is possible when
453 * the snapshot sees tuples that are before the index's indcheckxmin
454 * horizon. Throwing an error here should be very rare. It doesn't
455 * seem worth using a secondary snapshot to avoid this.
456 */
457 if (IsolationUsesXactSnapshot() && rel->rd_index->indcheckxmin &&
459 state->snapshot->xmin))
462 errmsg("index \"%s\" cannot be verified using transaction snapshot",
464 }
465
466 /*
467 * We need a snapshot to check the uniqueness of the index. For better
468 * performance, take it once per index check. If one was already taken
469 * above, use that.
470 */
471 if (state->checkunique)
472 {
473 state->indexinfo = BuildIndexInfo(state->rel);
474
475 if (state->indexinfo->ii_Unique && state->snapshot == InvalidSnapshot)
477 }
478
479 Assert(!state->rootdescend || state->readonly);
480 if (state->rootdescend && !state->heapkeyspace)
483 errmsg("cannot verify that tuples from index \"%s\" can each be found by an independent index search",
485 errhint("Only B-Tree version 4 indexes support rootdescend verification.")));
486
487 /* Create context for page */
489 "amcheck context",
491 state->checkstrategy = GetAccessStrategy(BAS_BULKREAD);
492
493 /* Get true root block from meta-page */
496
497 /*
498 * Certain deletion patterns can result in "skinny" B-Tree indexes, where
499 * the fast root and true root differ.
500 *
501 * Start from the true root, not the fast root, unlike conventional index
502 * scans. This approach is more thorough, and removes the risk of
503 * following a stale fast root from the meta page.
504 */
505 if (metad->btm_fastroot != metad->btm_root)
508 errmsg_internal("harmless fast root mismatch in index \"%s\"",
510 errdetail_internal("Fast root block %u (level %u) differs from true root block %u (level %u).",
511 metad->btm_fastroot, metad->btm_fastlevel,
512 metad->btm_root, metad->btm_level)));
513
514 /*
515 * Starting at the root, verify every level. Move left to right, top to
516 * bottom. Note that there may be no pages other than the meta page (meta
517 * page can indicate that root is P_NONE when the index is totally empty).
518 */
520 current.level = metad->btm_level;
521 current.leftmost = metad->btm_root;
522 current.istruerootlevel = true;
523 while (current.leftmost != P_NONE)
524 {
525 /*
526 * Verify this level, and get left most page for next level down, if
527 * not at leaf level
528 */
529 current = bt_check_level_from_leftmost(state, current);
530
531 if (current.leftmost == InvalidBlockNumber)
534 errmsg("index \"%s\" has no valid pages on level below %u or first level",
536
537 previouslevel = current.level;
538 }
539
540 /*
541 * * Check whether heap contains unindexed/malformed tuples *
542 */
543 if (state->heapallindexed)
544 {
545 IndexInfo *indexinfo = BuildIndexInfo(state->rel);
546 TableScanDesc scan;
547
548 /*
549 * Create our own scan for table_index_build_scan(), rather than
550 * getting it to do so for us. This is required so that we can
551 * actually use the MVCC snapshot registered earlier.
552 *
553 * Note that table_index_build_scan() calls heap_endscan() for us.
554 */
555 scan = table_beginscan_strat(state->heaprel, /* relation */
556 state->snapshot, /* snapshot */
557 0, /* number of keys */
558 NULL, /* scan key */
559 true, /* buffer access strategy OK */
560 true); /* syncscan OK? */
561
562 /*
563 * Scan will behave as the first scan of a CREATE INDEX CONCURRENTLY
564 * behaves.
565 *
566 * It's okay that we don't actually use the same lock strength for the
567 * heap relation as any other ii_Concurrent caller would. We have no
568 * reason to care about a concurrent VACUUM operation, since there
569 * isn't going to be a second scan of the heap that needs to be sure
570 * that there was no concurrent recycling of TIDs.
571 */
572 indexinfo->ii_Concurrent = true;
573
574 /*
575 * Don't wait for uncommitted tuple xact commit/abort when index is a
576 * unique index on a catalog (or an index used by an exclusion
577 * constraint). This could otherwise happen in the readonly case.
578 */
579 indexinfo->ii_Unique = false;
580 indexinfo->ii_ExclusionOps = NULL;
581 indexinfo->ii_ExclusionProcs = NULL;
582 indexinfo->ii_ExclusionStrats = NULL;
583
584 elog(DEBUG1, "verifying that tuples from index \"%s\" are present in \"%s\"",
587
588 table_index_build_scan(state->heaprel, state->rel, indexinfo, true, false,
590
592 (errmsg_internal("finished verifying presence of " INT64_FORMAT " tuples from table \"%s\" with bitset %.2f%% set",
593 state->heaptuplespresent, RelationGetRelationName(heaprel),
594 100.0 * bloom_prop_bits_set(state->filter))));
595
596 bloom_free(state->filter);
597 }
598
599 /* Be tidy: */
600 if (state->snapshot != InvalidSnapshot)
601 UnregisterSnapshot(state->snapshot);
602 MemoryContextDelete(state->targetcontext);
603}

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(), BTPageGetMeta, BTREE_METAPAGE, BuildIndexInfo(), CurrentMemoryContext, DEBUG1, elog, ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, fb(), GetAccessStrategy(), GetTransactionSnapshot(), HeapTupleHeaderGetXmin(), IndexInfo::ii_Concurrent, IndexInfo::ii_ExclusionOps, IndexInfo::ii_ExclusionProcs, IndexInfo::ii_ExclusionStrats, IndexInfo::ii_Unique, INT64_FORMAT, InvalidBlockNumber, InvalidBtreeLevel, InvalidSnapshot, IsolationUsesXactSnapshot, BtreeLevel::istruerootlevel, BtreeLevel::leftmost, BtreeLevel::level, maintenance_work_mem, Max, MaxTIDsPerBTreePage, MemoryContextDelete(), P_NONE, palloc0_object, palloc_btree_page(), pg_global_prng_state, pg_prng_uint64(), RelationData::rd_index, RelationData::rd_indextuple, RecentXmin, RegisterSnapshot(), RelationGetNumberOfBlocks, RelationGetRelationName, HeapTupleData::t_data, table_beginscan_strat(), table_index_build_scan(), TransactionIdIsValid, TransactionIdPrecedes(), and UnregisterSnapshot().

Referenced by bt_index_check_callback().

◆ bt_check_level_from_leftmost()

static BtreeLevel bt_check_level_from_leftmost ( BtreeCheckState state,
BtreeLevel  level 
)
static

Definition at line 624 of file verify_nbtree.c.

625{
626 /* State to establish early, concerning entire level */
627 BTPageOpaque opaque;
628 MemoryContext oldcontext;
630
631 /* Variables for iterating across level using right links */
633 BlockNumber current = level.leftmost;
634
635 /* Initialize return state */
638 nextleveldown.istruerootlevel = false;
639
640 /* Use page-level context for duration of this call */
641 oldcontext = MemoryContextSwitchTo(state->targetcontext);
642
643 elog(DEBUG1, "verifying level %u%s", level.level,
644 level.istruerootlevel ?
645 " (true root level)" : level.level == 0 ? " (leaf level)" : "");
646
647 state->prevrightlink = InvalidBlockNumber;
648 state->previncompletesplit = false;
649
650 do
651 {
652 /* Don't rely on CHECK_FOR_INTERRUPTS() calls at lower level */
654
655 /* Initialize state for this iteration */
656 state->targetblock = current;
657 state->target = palloc_btree_page(state, state->targetblock);
658 state->targetlsn = PageGetLSN(state->target);
659
660 opaque = BTPageGetOpaque(state->target);
661
662 if (P_IGNORE(opaque))
663 {
664 /*
665 * Since there cannot be a concurrent VACUUM operation in readonly
666 * mode, and since a page has no links within other pages
667 * (siblings and parent) once it is marked fully deleted, it
668 * should be impossible to land on a fully deleted page in
669 * readonly mode. See bt_child_check() for further details.
670 *
671 * The bt_child_check() P_ISDELETED() check is repeated here so
672 * that pages that are only reachable through sibling links get
673 * checked.
674 */
675 if (state->readonly && P_ISDELETED(opaque))
678 errmsg("downlink or sibling link points to deleted block in index \"%s\"",
680 errdetail_internal("Block=%u left block=%u left link from block=%u.",
681 current, leftcurrent, opaque->btpo_prev)));
682
683 if (P_RIGHTMOST(opaque))
686 errmsg("block %u fell off the end of index \"%s\"",
687 current, RelationGetRelationName(state->rel))));
688 else
691 errmsg_internal("block %u of index \"%s\" concurrently deleted",
692 current, RelationGetRelationName(state->rel))));
693 goto nextpage;
694 }
695 else if (nextleveldown.leftmost == InvalidBlockNumber)
696 {
697 /*
698 * A concurrent page split could make the caller supplied leftmost
699 * block no longer contain the leftmost page, or no longer be the
700 * true root, but where that isn't possible due to heavyweight
701 * locking, check that the first valid page meets caller's
702 * expectations.
703 */
704 if (state->readonly)
705 {
706 if (!bt_leftmost_ignoring_half_dead(state, current, opaque))
709 errmsg("block %u is not leftmost in index \"%s\"",
710 current, RelationGetRelationName(state->rel))));
711
712 if (level.istruerootlevel && (!P_ISROOT(opaque) && !P_INCOMPLETE_SPLIT(opaque)))
715 errmsg("block %u is not true root in index \"%s\"",
716 current, RelationGetRelationName(state->rel))));
717 }
718
719 /*
720 * Before beginning any non-trivial examination of level, prepare
721 * state for next bt_check_level_from_leftmost() invocation for
722 * the next level for the next level down (if any).
723 *
724 * There should be at least one non-ignorable page per level,
725 * unless this is the leaf level, which is assumed by caller to be
726 * final level.
727 */
728 if (!P_ISLEAF(opaque))
729 {
730 IndexTuple itup;
731 ItemId itemid;
732
733 /* Internal page -- downlink gets leftmost on next level */
734 itemid = PageGetItemIdCareful(state, state->targetblock,
735 state->target,
736 P_FIRSTDATAKEY(opaque));
737 itup = (IndexTuple) PageGetItem(state->target, itemid);
738 nextleveldown.leftmost = BTreeTupleGetDownLink(itup);
739 nextleveldown.level = opaque->btpo_level - 1;
740 }
741 else
742 {
743 /*
744 * Leaf page -- final level caller must process.
745 *
746 * Note that this could also be the root page, if there has
747 * been no root page split yet.
748 */
749 nextleveldown.leftmost = P_NONE;
751 }
752
753 /*
754 * Finished setting up state for this call/level. Control will
755 * never end up back here in any future loop iteration for this
756 * level.
757 */
758 }
759
760 /*
761 * Sibling links should be in mutual agreement. There arises
762 * leftcurrent == P_NONE && btpo_prev != P_NONE when the left sibling
763 * of the parent's low-key downlink is half-dead. (A half-dead page
764 * has no downlink from its parent.) Under heavyweight locking, the
765 * last bt_leftmost_ignoring_half_dead() validated this btpo_prev.
766 * Without heavyweight locking, validation of the P_NONE case remains
767 * unimplemented.
768 */
769 if (opaque->btpo_prev != leftcurrent && leftcurrent != P_NONE)
771
772 /* Check level */
773 if (level.level != opaque->btpo_level)
776 errmsg("leftmost down link for level points to block in index \"%s\" whose level is not one level down",
778 errdetail_internal("Block pointed to=%u expected level=%u level in pointed to block=%u.",
779 current, level.level, opaque->btpo_level)));
780
781 /* Verify invariants for page */
783
785
786 /* Try to detect circular links */
787 if (current == leftcurrent || current == opaque->btpo_prev)
790 errmsg("circular link chain found in block %u of index \"%s\"",
791 current, RelationGetRelationName(state->rel))));
792
793 leftcurrent = current;
794 current = opaque->btpo_next;
795
796 if (state->lowkey)
797 {
798 Assert(state->readonly);
799 pfree(state->lowkey);
800 state->lowkey = NULL;
801 }
802
803 /*
804 * Copy current target high key as the low key of right sibling.
805 * Allocate memory in upper level context, so it would be cleared
806 * after reset of target context.
807 *
808 * We only need the low key in corner cases of checking child high
809 * keys. We use high key only when incomplete split on the child level
810 * falls to the boundary of pages on the target level. See
811 * bt_child_highkey_check() for details. So, typically we won't end
812 * up doing anything with low key, but it's simpler for general case
813 * high key verification to always have it available.
814 *
815 * The correctness of managing low key in the case of concurrent
816 * splits wasn't investigated yet. Thankfully we only need low key
817 * for readonly verification and concurrent splits won't happen.
818 */
819 if (state->readonly && !P_RIGHTMOST(opaque))
820 {
821 IndexTuple itup;
822 ItemId itemid;
823
824 itemid = PageGetItemIdCareful(state, state->targetblock,
825 state->target, P_HIKEY);
826 itup = (IndexTuple) PageGetItem(state->target, itemid);
827
828 state->lowkey = MemoryContextAlloc(oldcontext, IndexTupleSize(itup));
829 memcpy(state->lowkey, itup, IndexTupleSize(itup));
830 }
831
832 /* Free page and associated memory for this iteration */
833 MemoryContextReset(state->targetcontext);
834 }
835 while (current != P_NONE);
836
837 if (state->lowkey)
838 {
839 Assert(state->readonly);
840 pfree(state->lowkey);
841 state->lowkey = NULL;
842 }
843
844 /* Don't change context for caller */
845 MemoryContextSwitchTo(oldcontext);
846
847 return nextleveldown;
848}

References Assert, bt_leftmost_ignoring_half_dead(), 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, fb(), IndexTupleSize(), InvalidBlockNumber, InvalidBtreeLevel, BtreeLevel::istruerootlevel, BtreeLevel::leftmost, BtreeLevel::level, MemoryContextAlloc(), MemoryContextReset(), MemoryContextSwitchTo(), P_FIRSTDATAKEY, P_HIKEY, P_IGNORE, P_INCOMPLETE_SPLIT, P_ISDELETED, P_ISLEAF, P_ISROOT, 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 2392 of file verify_nbtree.c.

2394{
2395 ItemId itemid;
2396 IndexTuple itup;
2398 OffsetNumber offset;
2400 Page child;
2403
2404 itemid = PageGetItemIdCareful(state, state->targetblock,
2405 state->target, downlinkoffnum);
2406 itup = (IndexTuple) PageGetItem(state->target, itemid);
2408
2409 /*
2410 * Caller must have ShareLock on target relation, because of
2411 * considerations around page deletion by VACUUM.
2412 *
2413 * NB: In general, page deletion deletes the right sibling's downlink, not
2414 * the downlink of the page being deleted; the deleted page's downlink is
2415 * reused for its sibling. The key space is thereby consolidated between
2416 * the deleted page and its right sibling. (We cannot delete a parent
2417 * page's rightmost child unless it is the last child page, and we intend
2418 * to also delete the parent itself.)
2419 *
2420 * If this verification happened without a ShareLock, the following race
2421 * condition could cause false positives:
2422 *
2423 * In general, concurrent page deletion might occur, including deletion of
2424 * the left sibling of the child page that is examined here. If such a
2425 * page deletion were to occur, closely followed by an insertion into the
2426 * newly expanded key space of the child, a window for the false positive
2427 * opens up: the stale parent/target downlink originally followed to get
2428 * to the child legitimately ceases to be a lower bound on all items in
2429 * the page, since the key space was concurrently expanded "left".
2430 * (Insertion followed the "new" downlink for the child, not our now-stale
2431 * downlink, which was concurrently physically removed in target/parent as
2432 * part of deletion's first phase.)
2433 *
2434 * While we use various techniques elsewhere to perform cross-page
2435 * verification for !readonly callers, a similar trick seems difficult
2436 * here. The tricks used by bt_recheck_sibling_links and by
2437 * bt_right_page_check_scankey both involve verification of a same-level,
2438 * cross-sibling invariant. Cross-level invariants are far more squishy,
2439 * though. The nbtree REDO routines do not actually couple buffer locks
2440 * across levels during page splits, so making any cross-level check work
2441 * reliably in !readonly mode may be impossible.
2442 */
2443 Assert(state->readonly);
2444
2445 /*
2446 * Verify child page has the downlink key from target page (its parent) as
2447 * a lower bound; downlink must be strictly less than all keys on the
2448 * page.
2449 *
2450 * Check all items, rather than checking just the first and trusting that
2451 * the operator class obeys the transitive law.
2452 */
2453 topaque = BTPageGetOpaque(state->target);
2455 copaque = BTPageGetOpaque(child);
2457
2458 /*
2459 * Since we've already loaded the child block, combine this check with
2460 * check for downlink connectivity.
2461 */
2462 bt_child_highkey_check(state, downlinkoffnum,
2463 child, topaque->btpo_level);
2464
2465 /*
2466 * Since there cannot be a concurrent VACUUM operation in readonly mode,
2467 * and since a page has no links within other pages (siblings and parent)
2468 * once it is marked fully deleted, it should be impossible to land on a
2469 * fully deleted page.
2470 *
2471 * It does not quite make sense to enforce that the page cannot even be
2472 * half-dead, despite the fact the downlink is modified at the same stage
2473 * that the child leaf page is marked half-dead. That's incorrect because
2474 * there may occasionally be multiple downlinks from a chain of pages
2475 * undergoing deletion, where multiple successive calls are made to
2476 * _bt_unlink_halfdead_page() by VACUUM before it can finally safely mark
2477 * the leaf page as fully dead. While _bt_mark_page_halfdead() usually
2478 * removes the downlink to the leaf page that is marked half-dead, that's
2479 * not guaranteed, so it's possible we'll land on a half-dead page with a
2480 * downlink due to an interrupted multi-level page deletion.
2481 *
2482 * We go ahead with our checks if the child page is half-dead. It's safe
2483 * to do so because we do not test the child's high key, so it does not
2484 * matter that the original high key will have been replaced by a dummy
2485 * truncated high key within _bt_mark_page_halfdead(). All other page
2486 * items are left intact on a half-dead page, so there is still something
2487 * to test.
2488 */
2489 if (P_ISDELETED(copaque))
2490 ereport(ERROR,
2492 errmsg("downlink to deleted page found in index \"%s\"",
2494 errdetail_internal("Parent block=%u child block=%u parent page lsn=%X/%08X.",
2495 state->targetblock, childblock,
2496 LSN_FORMAT_ARGS(state->targetlsn))));
2497
2498 for (offset = P_FIRSTDATAKEY(copaque);
2499 offset <= maxoffset;
2500 offset = OffsetNumberNext(offset))
2501 {
2502 /*
2503 * Skip comparison of target page key against "negative infinity"
2504 * item, if any. Checking it would indicate that it's not a strict
2505 * lower bound, but that's only because of the hard-coding for
2506 * negative infinity items within _bt_compare().
2507 *
2508 * If nbtree didn't truncate negative infinity tuples during internal
2509 * page splits then we'd expect child's negative infinity key to be
2510 * equal to the scankey/downlink from target/parent (it would be a
2511 * "low key" in this hypothetical scenario, and so it would still need
2512 * to be treated as a special case here).
2513 *
2514 * Negative infinity items can be thought of as a strict lower bound
2515 * that works transitively, with the last non-negative-infinity pivot
2516 * followed during a descent from the root as its "true" strict lower
2517 * bound. Only a small number of negative infinity items are truly
2518 * negative infinity; those that are the first items of leftmost
2519 * internal pages. In more general terms, a negative infinity item is
2520 * only negative infinity with respect to the subtree that the page is
2521 * at the root of.
2522 *
2523 * See also: bt_rootdescend(), which can even detect transitive
2524 * inconsistencies on cousin leaf pages.
2525 */
2527 continue;
2528
2530 offset))
2531 ereport(ERROR,
2533 errmsg("down-link lower bound invariant violated for index \"%s\"",
2535 errdetail_internal("Parent block=%u child index tid=(%u,%u) parent page lsn=%X/%08X.",
2536 state->targetblock, childblock, offset,
2537 LSN_FORMAT_ARGS(state->targetlsn))));
2538 }
2539
2540 pfree(child);
2541}

References Assert, bt_child_highkey_check(), BTPageGetOpaque, BTreeTupleGetDownLink(), ereport, errcode(), errdetail_internal(), errmsg(), ERROR, fb(), 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 2145 of file verify_nbtree.c.

2149{
2150 BlockNumber blkno = state->prevrightlink;
2151 Page page;
2152 BTPageOpaque opaque;
2153 bool rightsplit = state->previncompletesplit;
2154 bool first = true;
2155 ItemId itemid;
2156 IndexTuple itup;
2157 BlockNumber downlink;
2158
2160 {
2161 itemid = PageGetItemIdCareful(state, state->targetblock,
2162 state->target, target_downlinkoffnum);
2163 itup = (IndexTuple) PageGetItem(state->target, itemid);
2164 downlink = BTreeTupleGetDownLink(itup);
2165 }
2166 else
2167 {
2168 downlink = P_NONE;
2169 }
2170
2171 /*
2172 * If no previous rightlink is memorized for current level just below
2173 * target page's level, we are about to start from the leftmost page. We
2174 * can't follow rightlinks from previous page, because there is no
2175 * previous page. But we still can match high key.
2176 *
2177 * So we initialize variables for the loop above like there is previous
2178 * page referencing current child. Also we imply previous page to not
2179 * have incomplete split flag, that would make us require downlink for
2180 * current child. That's correct, because leftmost page on the level
2181 * should always have parent downlink.
2182 */
2183 if (!BlockNumberIsValid(blkno))
2184 {
2185 blkno = downlink;
2186 rightsplit = false;
2187 }
2188
2189 /* Move to the right on the child level */
2190 while (true)
2191 {
2192 /*
2193 * Did we traverse the whole tree level and this is check for pages to
2194 * the right of rightmost downlink?
2195 */
2196 if (blkno == P_NONE && downlink == P_NONE)
2197 {
2198 state->prevrightlink = InvalidBlockNumber;
2199 state->previncompletesplit = false;
2200 return;
2201 }
2202
2203 /* Did we traverse the whole tree level and don't find next downlink? */
2204 if (blkno == P_NONE)
2205 ereport(ERROR,
2207 errmsg("can't traverse from downlink %u to downlink %u of index \"%s\"",
2208 state->prevrightlink, downlink,
2210
2211 /* Load page contents */
2212 if (blkno == downlink && loaded_child)
2213 page = loaded_child;
2214 else
2215 page = palloc_btree_page(state, blkno);
2216
2217 opaque = BTPageGetOpaque(page);
2218
2219 /* The first page we visit at the level should be leftmost */
2220 if (first && !BlockNumberIsValid(state->prevrightlink) &&
2221 !bt_leftmost_ignoring_half_dead(state, blkno, opaque))
2222 ereport(ERROR,
2224 errmsg("the first child of leftmost target page is not leftmost of its level in index \"%s\"",
2226 errdetail_internal("Target block=%u child block=%u target page lsn=%X/%08X.",
2227 state->targetblock, blkno,
2228 LSN_FORMAT_ARGS(state->targetlsn))));
2229
2230 /* Do level sanity check */
2231 if ((!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque)) &&
2232 opaque->btpo_level != target_level - 1)
2233 ereport(ERROR,
2235 errmsg("block found while following rightlinks from child of index \"%s\" has invalid level",
2237 errdetail_internal("Block pointed to=%u expected level=%u level in pointed to block=%u.",
2238 blkno, target_level - 1, opaque->btpo_level)));
2239
2240 /* Try to detect circular links */
2241 if ((!first && blkno == state->prevrightlink) || blkno == opaque->btpo_prev)
2242 ereport(ERROR,
2244 errmsg("circular link chain found in block %u of index \"%s\"",
2245 blkno, RelationGetRelationName(state->rel))));
2246
2247 if (blkno != downlink && !P_IGNORE(opaque))
2248 {
2249 /* blkno probably has missing parent downlink */
2251 }
2252
2254
2255 /*
2256 * If we visit page with high key, check that it is equal to the
2257 * target key next to corresponding downlink.
2258 */
2259 if (!rightsplit && !P_RIGHTMOST(opaque) && !P_ISHALFDEAD(opaque))
2260 {
2264
2265 /* Get high key */
2266 itemid = PageGetItemIdCareful(state, blkno, page, P_HIKEY);
2267 highkey = (IndexTuple) PageGetItem(page, itemid);
2268
2269 /*
2270 * There might be two situations when we examine high key. If
2271 * current child page is referenced by given target downlink, we
2272 * should look to the next offset number for matching key from
2273 * target page.
2274 *
2275 * Alternatively, we're following rightlinks somewhere in the
2276 * middle between page referenced by previous target's downlink
2277 * and the page referenced by current target's downlink. If
2278 * current child page hasn't incomplete split flag set, then its
2279 * high key should match to the target's key of current offset
2280 * number. This happens when a previous call here (to
2281 * bt_child_highkey_check()) found an incomplete split, and we
2282 * reach a right sibling page without a downlink -- the right
2283 * sibling page's high key still needs to be matched to a
2284 * separator key on the parent/target level.
2285 *
2286 * Don't apply OffsetNumberNext() to target_downlinkoffnum when we
2287 * already had to step right on the child level. Our traversal of
2288 * the child level must try to move in perfect lockstep behind (to
2289 * the left of) the target/parent level traversal.
2290 */
2291 if (blkno == downlink)
2293 else
2295
2296 topaque = BTPageGetOpaque(state->target);
2297
2299 {
2300 /*
2301 * If we're looking for the next pivot tuple in target page,
2302 * but there is no more pivot tuples, then we should match to
2303 * high key instead.
2304 */
2306 {
2307 if (P_RIGHTMOST(topaque))
2308 ereport(ERROR,
2310 errmsg("child high key is greater than rightmost pivot key on target level in index \"%s\"",
2312 errdetail_internal("Target block=%u child block=%u target page lsn=%X/%08X.",
2313 state->targetblock, blkno,
2314 LSN_FORMAT_ARGS(state->targetlsn))));
2316 }
2317 itemid = PageGetItemIdCareful(state, state->targetblock,
2318 state->target, pivotkey_offset);
2319 itup = (IndexTuple) PageGetItem(state->target, itemid);
2320 }
2321 else
2322 {
2323 /*
2324 * We cannot try to match child's high key to a negative
2325 * infinity key in target, since there is nothing to compare.
2326 * However, it's still possible to match child's high key
2327 * outside of target page. The reason why we're are is that
2328 * bt_child_highkey_check() was previously called for the
2329 * cousin page of 'loaded_child', which is incomplete split.
2330 * So, now we traverse to the right of that cousin page and
2331 * current child level page under consideration still belongs
2332 * to the subtree of target's left sibling. Thus, we need to
2333 * match child's high key to its left uncle page high key.
2334 * Thankfully we saved it, it's called a "low key" of target
2335 * page.
2336 */
2337 if (!state->lowkey)
2338 ereport(ERROR,
2340 errmsg("can't find left sibling high key in index \"%s\"",
2342 errdetail_internal("Target block=%u child block=%u target page lsn=%X/%08X.",
2343 state->targetblock, blkno,
2344 LSN_FORMAT_ARGS(state->targetlsn))));
2345 itup = state->lowkey;
2346 }
2347
2348 if (!bt_pivot_tuple_identical(state->heapkeyspace, highkey, itup))
2349 {
2350 ereport(ERROR,
2352 errmsg("mismatch between parent key and child high key in index \"%s\"",
2354 errdetail_internal("Target block=%u child block=%u target page lsn=%X/%08X.",
2355 state->targetblock, blkno,
2356 LSN_FORMAT_ARGS(state->targetlsn))));
2357 }
2358 }
2359
2360 /* Exit if we already found next downlink */
2361 if (blkno == downlink)
2362 {
2363 state->prevrightlink = opaque->btpo_next;
2364 state->previncompletesplit = rightsplit;
2365 return;
2366 }
2367
2368 /* Traverse to the next page using rightlink */
2369 blkno = opaque->btpo_next;
2370
2371 /* Free page contents if it's allocated by us */
2372 if (page != loaded_child)
2373 pfree(page);
2374 first = false;
2375 }
2376}

References BlockNumberIsValid(), bt_downlink_missing_check(), bt_leftmost_ignoring_half_dead(), bt_pivot_tuple_identical(), BTPageGetOpaque, BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_next, BTPageOpaqueData::btpo_prev, BTreeTupleGetDownLink(), ereport, errcode(), errdetail_internal(), errmsg(), ERROR, fb(), InvalidBlockNumber, LSN_FORMAT_ARGS, offset_is_negative_infinity(), OffsetNumberIsValid, OffsetNumberNext, P_HAS_FULLXID, P_HIKEY, P_IGNORE, P_INCOMPLETE_SPLIT, P_ISDELETED, P_ISHALFDEAD, P_NONE, P_RIGHTMOST, PageGetItem(), PageGetItemIdCareful(), PageGetMaxOffsetNumber(), palloc_btree_page(), pfree(), and RelationGetRelationName.

Referenced by bt_child_check(), and bt_target_page_check().

◆ bt_downlink_missing_check()

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

Definition at line 2557 of file verify_nbtree.c.

2559{
2560 BTPageOpaque opaque = BTPageGetOpaque(page);
2561 ItemId itemid;
2562 IndexTuple itup;
2563 Page child;
2565 uint32 level;
2568
2569 Assert(state->readonly);
2570 Assert(!P_IGNORE(opaque));
2571
2572 /* No next level up with downlinks to fingerprint from the true root */
2573 if (P_ISROOT(opaque))
2574 return;
2575
2576 pagelsn = PageGetLSN(page);
2577
2578 /*
2579 * Incomplete (interrupted) page splits can account for the lack of a
2580 * downlink. Some inserting transaction should eventually complete the
2581 * page split in passing, when it notices that the left sibling page is
2582 * P_INCOMPLETE_SPLIT().
2583 *
2584 * In general, VACUUM is not prepared for there to be no downlink to a
2585 * page that it deletes. This is the main reason why the lack of a
2586 * downlink can be reported as corruption here. It's not obvious that an
2587 * invalid missing downlink can result in wrong answers to queries,
2588 * though, since index scans that land on the child may end up
2589 * consistently moving right. The handling of concurrent page splits (and
2590 * page deletions) within _bt_moveright() cannot distinguish
2591 * inconsistencies that last for a moment from inconsistencies that are
2592 * permanent and irrecoverable.
2593 *
2594 * VACUUM isn't even prepared to delete pages that have no downlink due to
2595 * an incomplete page split, but it can detect and reason about that case
2596 * by design, so it shouldn't be taken to indicate corruption. See
2597 * _bt_pagedel() for full details.
2598 */
2599 if (rightsplit)
2600 {
2603 errmsg_internal("harmless interrupted page split detected in index \"%s\"",
2605 errdetail_internal("Block=%u level=%u left sibling=%u page lsn=%X/%08X.",
2606 blkno, opaque->btpo_level,
2607 opaque->btpo_prev,
2609 return;
2610 }
2611
2612 /*
2613 * Page under check is probably the "top parent" of a multi-level page
2614 * deletion. We'll need to descend the subtree to make sure that
2615 * descendant pages are consistent with that, though.
2616 *
2617 * If the page (which must be non-ignorable) is a leaf page, then clearly
2618 * it can't be the top parent. The lack of a downlink is probably a
2619 * symptom of a broad problem that could just as easily cause
2620 * inconsistencies anywhere else.
2621 */
2622 if (P_ISLEAF(opaque))
2623 ereport(ERROR,
2625 errmsg("leaf index block lacks downlink in index \"%s\"",
2627 errdetail_internal("Block=%u page lsn=%X/%08X.",
2628 blkno,
2630
2631 /* Descend from the given page, which is an internal page */
2632 elog(DEBUG1, "checking for interrupted multi-level deletion due to missing downlink in index \"%s\"",
2634
2635 level = opaque->btpo_level;
2636 itemid = PageGetItemIdCareful(state, blkno, page, P_FIRSTDATAKEY(opaque));
2637 itup = (IndexTuple) PageGetItem(page, itemid);
2639 for (;;)
2640 {
2642
2644 copaque = BTPageGetOpaque(child);
2645
2646 if (P_ISLEAF(copaque))
2647 break;
2648
2649 /* Do an extra sanity check in passing on internal pages */
2650 if (copaque->btpo_level != level - 1)
2651 ereport(ERROR,
2653 errmsg_internal("downlink points to block in index \"%s\" whose level is not one level down",
2655 errdetail_internal("Top parent/under check block=%u block pointed to=%u expected level=%u level in pointed to block=%u.",
2656 blkno, childblk,
2657 level - 1, copaque->btpo_level)));
2658
2659 level = copaque->btpo_level;
2660 itemid = PageGetItemIdCareful(state, childblk, child,
2662 itup = (IndexTuple) PageGetItem(child, itemid);
2664 /* Be slightly more pro-active in freeing this memory, just in case */
2665 pfree(child);
2666 }
2667
2668 /*
2669 * Since there cannot be a concurrent VACUUM operation in readonly mode,
2670 * and since a page has no links within other pages (siblings and parent)
2671 * once it is marked fully deleted, it should be impossible to land on a
2672 * fully deleted page. See bt_child_check() for further details.
2673 *
2674 * The bt_child_check() P_ISDELETED() check is repeated here because
2675 * bt_child_check() does not visit pages reachable through negative
2676 * infinity items. Besides, bt_child_check() is unwilling to descend
2677 * multiple levels. (The similar bt_child_check() P_ISDELETED() check
2678 * within bt_check_level_from_leftmost() won't reach the page either,
2679 * since the leaf's live siblings should have their sibling links updated
2680 * to bypass the deletion target page when it is marked fully dead.)
2681 *
2682 * If this error is raised, it might be due to a previous multi-level page
2683 * deletion that failed to realize that it wasn't yet safe to mark the
2684 * leaf page as fully dead. A "dangling downlink" will still remain when
2685 * this happens. The fact that the dangling downlink's page (the leaf's
2686 * parent/ancestor page) lacked a downlink is incidental.
2687 */
2688 if (P_ISDELETED(copaque))
2689 ereport(ERROR,
2691 errmsg_internal("downlink to deleted leaf page found in index \"%s\"",
2693 errdetail_internal("Top parent/target block=%u leaf block=%u top parent/under check lsn=%X/%08X.",
2694 blkno, childblk,
2696
2697 /*
2698 * Iff leaf page is half-dead, its high key top parent link should point
2699 * to what VACUUM considered to be the top parent page at the instant it
2700 * was interrupted. Provided the high key link actually points to the
2701 * page under check, the missing downlink we detected is consistent with
2702 * there having been an interrupted multi-level page deletion. This means
2703 * that the subtree with the page under check at its root (a page deletion
2704 * chain) is in a consistent state, enabling VACUUM to resume deleting the
2705 * entire chain the next time it encounters the half-dead leaf page.
2706 */
2708 {
2709 itemid = PageGetItemIdCareful(state, childblk, child, P_HIKEY);
2710 itup = (IndexTuple) PageGetItem(child, itemid);
2711 if (BTreeTupleGetTopParent(itup) == blkno)
2712 return;
2713 }
2714
2715 ereport(ERROR,
2717 errmsg("internal index block lacks downlink in index \"%s\"",
2719 errdetail_internal("Block=%u level=%u page lsn=%X/%08X.",
2720 blkno, opaque->btpo_level,
2722}

References Assert, BTPageGetOpaque, BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_prev, BTreeTupleGetDownLink(), BTreeTupleGetTopParent(), CHECK_FOR_INTERRUPTS, DEBUG1, elog, ereport, errcode(), errdetail_internal(), errmsg(), errmsg_internal(), ERROR, fb(), 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_entry_unique_check()

static void bt_entry_unique_check ( BtreeCheckState state,
IndexTuple  itup,
BlockNumber  targetblock,
OffsetNumber  offset,
BtreeLastVisibleEntry lVis 
)
static

Definition at line 911 of file verify_nbtree.c.

914{
915 ItemPointer tid;
916 bool has_visible_entry = false;
917
918 Assert(targetblock != P_NONE);
919
920 /*
921 * Current tuple has posting list. Report duplicate if TID of any posting
922 * list entry is visible and lVis->tid is valid.
923 */
924 if (BTreeTupleIsPosting(itup))
925 {
926 for (int i = 0; i < BTreeTupleGetNPosting(itup); i++)
927 {
928 tid = BTreeTupleGetPostingN(itup, i);
930 {
931 has_visible_entry = true;
932 if (ItemPointerIsValid(lVis->tid))
933 {
935 lVis,
936 tid, targetblock,
937 offset, i);
938 }
939
940 /*
941 * Prevent double reporting unique constraint violation
942 * between the posting list entries of the first tuple on the
943 * page after cross-page check.
944 */
945 if (lVis->blkno != targetblock && ItemPointerIsValid(lVis->tid))
946 return;
947
948 lVis->blkno = targetblock;
949 lVis->offset = offset;
950 lVis->postingIndex = i;
951 lVis->tid = tid;
952 }
953 }
954 }
955
956 /*
957 * Current tuple has no posting list. If TID is visible save info about it
958 * for the next comparisons in the loop in bt_target_page_check(). Report
959 * duplicate if lVis->tid is already valid.
960 */
961 else
962 {
963 tid = BTreeTupleGetHeapTID(itup);
965 {
966 has_visible_entry = true;
967 if (ItemPointerIsValid(lVis->tid))
968 {
970 lVis,
971 tid, targetblock,
972 offset, -1);
973 }
974
975 lVis->blkno = targetblock;
976 lVis->offset = offset;
977 lVis->tid = tid;
978 lVis->postingIndex = -1;
979 }
980 }
981
982 if (!has_visible_entry &&
983 lVis->blkno != InvalidBlockNumber &&
984 lVis->blkno != targetblock)
985 {
986 char *posting = "";
987
988 if (lVis->postingIndex >= 0)
989 posting = psprintf(" posting %u", lVis->postingIndex);
992 errmsg("index uniqueness can not be checked for index tid=(%u,%u) in index \"%s\"",
993 targetblock, offset,
995 errdetail("It doesn't have visible heap tids and key is equal to the tid=(%u,%u)%s (points to heap tid=(%u,%u)).",
996 lVis->blkno, lVis->offset, posting,
999 errhint("VACUUM the table and repeat the check.")));
1000 }
1001}

References Assert, bt_report_duplicate(), BTreeTupleGetHeapTID(), BTreeTupleGetNPosting(), BTreeTupleGetPostingN(), BTreeTupleIsPosting(), DEBUG1, ereport, errcode(), errdetail(), errhint(), errmsg(), fb(), heap_entry_is_visible(), i, InvalidBlockNumber, ItemPointerGetBlockNumberNoCheck(), ItemPointerGetOffsetNumberNoCheck(), ItemPointerIsValid(), P_NONE, psprintf(), and RelationGetRelationName.

Referenced by bt_target_page_check().

◆ bt_index_check()

Datum bt_index_check ( PG_FUNCTION_ARGS  )

Definition at line 252 of file verify_nbtree.c.

253{
256
257 args.heapallindexed = false;
258 args.rootdescend = false;
259 args.parentcheck = false;
260 args.checkunique = false;
261
262 if (PG_NARGS() >= 2)
263 args.heapallindexed = PG_GETARG_BOOL(1);
264 if (PG_NARGS() >= 3)
265 args.checkunique = PG_GETARG_BOOL(2);
266
269 AccessShareLock, &args);
270
272}

References AccessShareLock, amcheck_lock_relation_and_check(), bt_index_check_callback(), fb(), PG_GETARG_BOOL, PG_GETARG_OID, PG_NARGS, and PG_RETURN_VOID.

◆ bt_index_check_callback()

static void bt_index_check_callback ( Relation  indrel,
Relation  heaprel,
void state,
bool  readonly 
)
static

Definition at line 312 of file verify_nbtree.c.

313{
315 bool heapkeyspace,
316 allequalimage;
317
321 errmsg("index \"%s\" lacks a main relation fork",
323
324 /* Extract metadata from metapage, and sanitize it in passing */
325 _bt_metaversion(indrel, &heapkeyspace, &allequalimage);
326 if (allequalimage && !heapkeyspace)
329 errmsg("index \"%s\" metapage has equalimage field set on unsupported nbtree version",
331 if (allequalimage && !_bt_allequalimage(indrel, false))
332 {
333 bool has_interval_ops = false;
334
336 if (indrel->rd_opfamily[i] == INTERVAL_BTREE_FAM_OID)
337 {
338 has_interval_ops = true;
341 errmsg("index \"%s\" metapage incorrectly indicates that deduplication is safe",
344 ? errhint("This is known of \"interval\" indexes last built on a version predating 2023-11.")
345 : 0));
346 }
347 }
348
349 /* Check index, possibly against table it is an index on */
350 bt_check_every_level(indrel, heaprel, heapkeyspace, readonly,
351 args->heapallindexed, args->rootdescend, args->checkunique);
352}

References _bt_allequalimage(), _bt_metaversion(), bt_check_every_level(), ereport, errcode(), errhint(), errmsg(), ERROR, fb(), i, IndexRelationGetNumberOfKeyAttributes, MAIN_FORKNUM, RelationGetRelationName, RelationGetSmgr(), and smgrexists().

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

285{
288
289 args.heapallindexed = false;
290 args.rootdescend = false;
291 args.parentcheck = true;
292 args.checkunique = false;
293
294 if (PG_NARGS() >= 2)
295 args.heapallindexed = PG_GETARG_BOOL(1);
296 if (PG_NARGS() >= 3)
297 args.rootdescend = PG_GETARG_BOOL(2);
298 if (PG_NARGS() >= 4)
299 args.checkunique = PG_GETARG_BOOL(3);
300
303 ShareLock, &args);
304
306}

References amcheck_lock_relation_and_check(), bt_index_check_callback(), fb(), PG_GETARG_BOOL, PG_GETARG_OID, PG_NARGS, PG_RETURN_VOID, and ShareLock.

◆ bt_leftmost_ignoring_half_dead()

static bool bt_leftmost_ignoring_half_dead ( BtreeCheckState state,
BlockNumber  start,
BTPageOpaque  start_opaque 
)
static

Definition at line 1010 of file verify_nbtree.c.

1013{
1014 BlockNumber reached = start_opaque->btpo_prev,
1016 bool all_half_dead = true;
1017
1018 /*
1019 * To handle the !readonly case, we'd need to accept BTP_DELETED pages and
1020 * potentially observe nbtree/README "Page deletion and backwards scans".
1021 */
1022 Assert(state->readonly);
1023
1024 while (reached != P_NONE && all_half_dead)
1025 {
1028
1030
1031 /*
1032 * Try to detect btpo_prev circular links. _bt_unlink_halfdead_page()
1033 * writes that side-links will continue to point to the siblings.
1034 * Check btpo_next for that property.
1035 */
1037 reached != start &&
1038 reached != reached_from &&
1039 reached_opaque->btpo_next == reached_from;
1040 if (all_half_dead)
1041 {
1043
1044 /* pagelsn should point to an XLOG_BTREE_MARK_PAGE_HALFDEAD */
1047 errmsg_internal("harmless interrupted page deletion detected in index \"%s\"",
1049 errdetail_internal("Block=%u right block=%u page lsn=%X/%08X.",
1052
1054 reached = reached_opaque->btpo_prev;
1055 }
1056
1057 pfree(page);
1058 }
1059
1060 return all_half_dead;
1061}

References Assert, BTPageGetOpaque, CHECK_FOR_INTERRUPTS, DEBUG1, ereport, errcode(), errdetail_internal(), errmsg_internal(), fb(), LSN_FORMAT_ARGS, P_ISHALFDEAD, P_NONE, PageGetLSN(), palloc_btree_page(), pfree(), RelationGetRelationName, and start.

Referenced by bt_check_level_from_leftmost(), and bt_child_highkey_check().

◆ bt_mkscankey_pivotsearch()

static BTScanInsert bt_mkscankey_pivotsearch ( Relation  rel,
IndexTuple  itup 
)
inlinestatic

Definition at line 3468 of file verify_nbtree.c.

3469{
3471
3472 skey = _bt_mkscankey(rel, itup);
3473 skey->backward = true;
3474
3475 return skey;
3476}

References _bt_mkscankey(), and fb().

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

2849{
2852 bool isnull[INDEX_MAX_KEYS];
2854 bool formnewtup = false;
2856 int i;
2857
2858 /* Caller should only pass "logical" non-pivot tuples here */
2860
2861 /* Easy case: It's immediately clear that tuple has no varlena datums */
2862 if (!IndexTupleHasVarwidths(itup))
2863 return itup;
2864
2865 for (i = 0; i < tupleDescriptor->natts; i++)
2866 {
2868
2870
2871 /* Assume untoasted/already normalized datum initially */
2872 need_free[i] = false;
2873 normalized[i] = index_getattr(itup, att->attnum,
2875 &isnull[i]);
2876 if (att->attbyval || att->attlen != -1 || isnull[i])
2877 continue;
2878
2879 /*
2880 * Callers always pass a tuple that could safely be inserted into the
2881 * index without further processing, so an external varlena header
2882 * should never be encountered here
2883 */
2885 ereport(ERROR,
2887 errmsg("external varlena datum in tuple that references heap row (%u,%u) in index \"%s\"",
2893 (att->attstorage == TYPSTORAGE_EXTENDED ||
2894 att->attstorage == TYPSTORAGE_MAIN))
2895 {
2896 /*
2897 * This value will be compressed by index_form_tuple() with the
2898 * current storage settings. We may be here because this tuple
2899 * was formed with different storage settings. So, force forming.
2900 */
2901 formnewtup = true;
2902 }
2904 {
2905 formnewtup = true;
2907 need_free[i] = true;
2908 }
2909
2910 /*
2911 * Short tuples may have 1B or 4B header. Convert 4B header of short
2912 * tuples to 1B
2913 */
2915 {
2916 /* convert to short varlena */
2918 char *data = palloc(len);
2919
2922
2923 formnewtup = true;
2925 need_free[i] = true;
2926 }
2927 }
2928
2929 /*
2930 * Easier case: Tuple has varlena datums, none of which are compressed or
2931 * short with 4B header
2932 */
2933 if (!formnewtup)
2934 return itup;
2935
2936 /*
2937 * Hard case: Tuple had compressed varlena datums that necessitate
2938 * creating normalized version of the tuple from uncompressed input datums
2939 * (normalized input datums). This is rather naive, but shouldn't be
2940 * necessary too often.
2941 *
2942 * In the heap, tuples may contain short varlena datums with both 1B
2943 * header and 4B headers. But the corresponding index tuple should always
2944 * have such varlena's with 1B headers. So, if there is a short varlena
2945 * with 4B header, we need to convert it for fingerprinting.
2946 *
2947 * Note that we rely on deterministic index_form_tuple() TOAST compression
2948 * of normalized input.
2949 */
2951 reformed->t_tid = itup->t_tid;
2952
2953 /* Cannot leak memory here */
2954 for (i = 0; i < tupleDescriptor->natts; i++)
2955 if (need_free[i])
2957
2958 return reformed;
2959}

References Assert, BTreeTupleIsPivot(), BTreeTupleIsPosting(), data, DatumGetPointer(), ereport, errcode(), errmsg(), ERROR, fb(), i, index_form_tuple(), index_getattr(), INDEX_MAX_KEYS, IndexTupleHasVarwidths(), ItemPointerGetBlockNumber(), ItemPointerGetOffsetNumber(), len, palloc(), pfree(), PG_DETOAST_DATUM, PointerGetDatum(), RelationGetDescr, RelationGetRelationName, SET_VARSIZE_SHORT(), IndexTupleData::t_tid, TOAST_INDEX_TARGET, TupleDescAttr(), VARATT_CAN_MAKE_SHORT(), VARATT_CONVERTED_SHORT_SIZE(), VARATT_IS_COMPRESSED(), VARATT_IS_EXTERNAL(), VARDATA(), and VARSIZE().

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

2073{
2075 return false;
2076
2077 if (heapkeyspace)
2078 {
2079 /*
2080 * Offset number will contain important information in heapkeyspace
2081 * indexes: the number of attributes left in the pivot tuple following
2082 * suffix truncation. Don't skip over it (compare it too).
2083 */
2084 if (memcmp(&itup1->t_tid.ip_posid, &itup2->t_tid.ip_posid,
2086 offsetof(ItemPointerData, ip_posid)) != 0)
2087 return false;
2088 }
2089 else
2090 {
2091 /*
2092 * Cannot rely on offset number field having consistent value across
2093 * levels on pg_upgrade'd !heapkeyspace indexes. Compare contents of
2094 * tuple starting from just after item pointer (i.e. after block
2095 * number and offset number).
2096 */
2097 if (memcmp(&itup1->t_info, &itup2->t_info,
2099 offsetof(IndexTupleData, t_info)) != 0)
2100 return false;
2101 }
2102
2103 return true;
2104}

References fb(), and IndexTupleSize().

Referenced by bt_child_highkey_check().

◆ bt_posting_plain_tuple()

static IndexTuple bt_posting_plain_tuple ( IndexTuple  itup,
int  n 
)
inlinestatic

Definition at line 2976 of file verify_nbtree.c.

2977{
2979
2980 /* Returns non-posting-list tuple */
2981 return _bt_form_posting(itup, BTreeTupleGetPostingN(itup, n), 1);
2982}

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

1102{
1103 /* passing metapage to BTPageGetOpaque() would give irrelevant findings */
1105
1106 if (!state->readonly)
1107 {
1108 Buffer lbuf;
1110 Page page;
1111 BTPageOpaque opaque;
1113
1114 /* Couple locks in the usual order for nbtree: Left to right */
1116 RBM_NORMAL, state->checkstrategy);
1118 _bt_checkpage(state->rel, lbuf);
1119 page = BufferGetPage(lbuf);
1120 opaque = BTPageGetOpaque(page);
1121 if (P_ISDELETED(opaque))
1122 {
1123 /*
1124 * Cannot reason about concurrently deleted page -- the left link
1125 * in the page to the right is expected to point to some other
1126 * page to the left (not leftcurrent page).
1127 *
1128 * Note that we deliberately don't give up with a half-dead page.
1129 */
1131 return;
1132 }
1133
1134 newtargetblock = opaque->btpo_next;
1135 /* Avoid self-deadlock when newtargetblock == leftcurrent */
1137 {
1140 state->checkstrategy);
1144 opaque = BTPageGetOpaque(page);
1145 /* btpo_prev_from_target may have changed; update it */
1147 }
1148 else
1149 {
1150 /*
1151 * leftcurrent right sibling points back to leftcurrent block.
1152 * Index is corrupt. Easiest way to handle this is to pretend
1153 * that we actually read from a distinct page that has an invalid
1154 * block number in its btpo_prev.
1155 */
1158 }
1159
1160 /*
1161 * No need to check P_ISDELETED here, since new target block cannot be
1162 * marked deleted as long as we hold a lock on lbuf
1163 */
1167
1169 {
1170 /* Report split in left sibling, not target (or new target) */
1173 errmsg_internal("harmless concurrent page split detected in index \"%s\"",
1175 errdetail_internal("Block=%u new right sibling=%u original right sibling=%u.",
1177 state->targetblock)));
1178 return;
1179 }
1180
1181 /*
1182 * Index is corrupt. Make sure that we report correct target page.
1183 *
1184 * This could have changed in cases where there was a concurrent page
1185 * split, as well as index corruption (at least in theory). Note that
1186 * btpo_prev_from_target was already updated above.
1187 */
1188 state->targetblock = newtargetblock;
1189 }
1190
1191 ereport(ERROR,
1193 errmsg("left link/right link pair in index \"%s\" not in agreement",
1195 errdetail_internal("Block=%u left block=%u left link from block=%u.",
1196 state->targetblock, leftcurrent,
1198}

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

Referenced by bt_check_level_from_leftmost().

◆ bt_report_duplicate()

static void bt_report_duplicate ( BtreeCheckState state,
BtreeLastVisibleEntry lVis,
ItemPointer  nexttid,
BlockNumber  nblock,
OffsetNumber  noffset,
int  nposting 
)
static

Definition at line 871 of file verify_nbtree.c.

875{
876 char *htid,
877 *nhtid,
878 *itid,
879 *nitid = "",
880 *pposting = "",
881 *pnposting = "";
882
883 htid = psprintf("tid=(%u,%u)",
886 nhtid = psprintf("tid=(%u,%u)",
889 itid = psprintf("tid=(%u,%u)", lVis->blkno, lVis->offset);
890
891 if (nblock != lVis->blkno || noffset != lVis->offset)
892 nitid = psprintf(" tid=(%u,%u)", nblock, noffset);
893
894 if (lVis->postingIndex >= 0)
895 pposting = psprintf(" posting %u", lVis->postingIndex);
896
897 if (nposting >= 0)
898 pnposting = psprintf(" posting %u", nposting);
899
902 errmsg("index uniqueness is violated for index \"%s\"",
904 errdetail("Index %s%s and%s%s (point to heap %s and %s) page lsn=%X/%08X.",
906 LSN_FORMAT_ARGS(state->targetlsn))));
907}

References ereport, errcode(), errdetail(), errmsg(), ERROR, fb(), ItemPointerGetBlockNumberNoCheck(), ItemPointerGetOffsetNumberNoCheck(), LSN_FORMAT_ARGS, psprintf(), and RelationGetRelationName.

Referenced by bt_entry_unique_check().

◆ bt_right_page_check_scankey()

static BTScanInsert bt_right_page_check_scankey ( BtreeCheckState state,
OffsetNumber rightfirstoffset 
)
static

Definition at line 1865 of file verify_nbtree.c.

1866{
1867 BTPageOpaque opaque;
1873
1874 /* Determine target's next block number */
1875 opaque = BTPageGetOpaque(state->target);
1876
1877 /* If target is already rightmost, no right sibling; nothing to do here */
1878 if (P_RIGHTMOST(opaque))
1879 return NULL;
1880
1881 /*
1882 * General notes on concurrent page splits and page deletion:
1883 *
1884 * Routines like _bt_search() don't require *any* page split interlock
1885 * when descending the tree, including something very light like a buffer
1886 * pin. That's why it's okay that we don't either. This avoidance of any
1887 * need to "couple" buffer locks is the raison d' etre of the Lehman & Yao
1888 * algorithm, in fact.
1889 *
1890 * That leaves deletion. A deleted page won't actually be recycled by
1891 * VACUUM early enough for us to fail to at least follow its right link
1892 * (or left link, or downlink) and find its sibling, because recycling
1893 * does not occur until no possible index scan could land on the page.
1894 * Index scans can follow links with nothing more than their snapshot as
1895 * an interlock and be sure of at least that much. (See page
1896 * recycling/"visible to everyone" notes in nbtree README.)
1897 *
1898 * Furthermore, it's okay if we follow a rightlink and find a half-dead or
1899 * dead (ignorable) page one or more times. There will either be a
1900 * further right link to follow that leads to a live page before too long
1901 * (before passing by parent's rightmost child), or we will find the end
1902 * of the entire level instead (possible when parent page is itself the
1903 * rightmost on its level).
1904 */
1905 targetnext = opaque->btpo_next;
1906 for (;;)
1907 {
1909
1911 opaque = BTPageGetOpaque(rightpage);
1912
1913 if (!P_IGNORE(opaque) || P_RIGHTMOST(opaque))
1914 break;
1915
1916 /*
1917 * We landed on a deleted or half-dead sibling page. Step right until
1918 * we locate a live sibling page.
1919 */
1922 errmsg_internal("level %u sibling page in block %u of index \"%s\" was found deleted or half dead",
1924 errdetail_internal("Deleted page found when building scankey from right sibling.")));
1925
1926 targetnext = opaque->btpo_next;
1927
1928 /* Be slightly more pro-active in freeing this memory, just in case */
1930 }
1931
1932 /*
1933 * No ShareLock held case -- why it's safe to proceed.
1934 *
1935 * Problem:
1936 *
1937 * We must avoid false positive reports of corruption when caller treats
1938 * item returned here as an upper bound on target's last item. In
1939 * general, false positives are disallowed. Avoiding them here when
1940 * caller is !readonly is subtle.
1941 *
1942 * A concurrent page deletion by VACUUM of the target page can result in
1943 * the insertion of items on to this right sibling page that would
1944 * previously have been inserted on our target page. There might have
1945 * been insertions that followed the target's downlink after it was made
1946 * to point to right sibling instead of target by page deletion's first
1947 * phase. The inserters insert items that would belong on target page.
1948 * This race is very tight, but it's possible. This is our only problem.
1949 *
1950 * Non-problems:
1951 *
1952 * We are not hindered by a concurrent page split of the target; we'll
1953 * never land on the second half of the page anyway. A concurrent split
1954 * of the right page will also not matter, because the first data item
1955 * remains the same within the left half, which we'll reliably land on. If
1956 * we had to skip over ignorable/deleted pages, it cannot matter because
1957 * their key space has already been atomically merged with the first
1958 * non-ignorable page we eventually find (doesn't matter whether the page
1959 * we eventually find is a true sibling or a cousin of target, which we go
1960 * into below).
1961 *
1962 * Solution:
1963 *
1964 * Caller knows that it should reverify that target is not ignorable
1965 * (half-dead or deleted) when cross-page sibling item comparison appears
1966 * to indicate corruption (invariant fails). This detects the single race
1967 * condition that exists for caller. This is correct because the
1968 * continued existence of target block as non-ignorable (not half-dead or
1969 * deleted) implies that target page was not merged into from the right by
1970 * deletion; the key space at or after target never moved left. Target's
1971 * parent either has the same downlink to target as before, or a <
1972 * downlink due to deletion at the left of target. Target either has the
1973 * same highkey as before, or a highkey < before when there is a page
1974 * split. (The rightmost concurrently-split-from-target-page page will
1975 * still have the same highkey as target was originally found to have,
1976 * which for our purposes is equivalent to target's highkey itself never
1977 * changing, since we reliably skip over
1978 * concurrently-split-from-target-page pages.)
1979 *
1980 * In simpler terms, we allow that the key space of the target may expand
1981 * left (the key space can move left on the left side of target only), but
1982 * the target key space cannot expand right and get ahead of us without
1983 * our detecting it. The key space of the target cannot shrink, unless it
1984 * shrinks to zero due to the deletion of the original page, our canary
1985 * condition. (To be very precise, we're a bit stricter than that because
1986 * it might just have been that the target page split and only the
1987 * original target page was deleted. We can be more strict, just not more
1988 * lax.)
1989 *
1990 * Top level tree walk caller moves on to next page (makes it the new
1991 * target) following recovery from this race. (cf. The rationale for
1992 * child/downlink verification needing a ShareLock within
1993 * bt_child_check(), where page deletion is also the main source of
1994 * trouble.)
1995 *
1996 * Note that it doesn't matter if right sibling page here is actually a
1997 * cousin page, because in order for the key space to be readjusted in a
1998 * way that causes us issues in next level up (guiding problematic
1999 * concurrent insertions to the cousin from the grandparent rather than to
2000 * the sibling from the parent), there'd have to be page deletion of
2001 * target's parent page (affecting target's parent's downlink in target's
2002 * grandparent page). Internal page deletion only occurs when there are
2003 * no child pages (they were all fully deleted), and caller is checking
2004 * that the target's parent has at least one non-deleted (so
2005 * non-ignorable) child: the target page. (Note that the first phase of
2006 * deletion atomically marks the page to be deleted half-dead/ignorable at
2007 * the same time downlink in its parent is removed, so caller will
2008 * definitely not fail to detect that this happened.)
2009 *
2010 * This trick is inspired by the method backward scans use for dealing
2011 * with concurrent page splits; concurrent page deletion is a problem that
2012 * similarly receives special consideration sometimes (it's possible that
2013 * the backwards scan will re-read its "original" block after failing to
2014 * find a right-link to it, having already moved in the opposite direction
2015 * (right/"forwards") a few times to try to locate one). Just like us,
2016 * that happens only to determine if there was a concurrent page deletion
2017 * of a reference page, and just like us if there was a page deletion of
2018 * that reference page it means we can move on from caring about the
2019 * reference page. See the nbtree README for a full description of how
2020 * that works.
2021 */
2023
2024 /*
2025 * Get first data item, if any
2026 */
2027 if (P_ISLEAF(opaque) && nline >= P_FIRSTDATAKEY(opaque))
2028 {
2029 /* Return first data item (if any) */
2031 P_FIRSTDATAKEY(opaque));
2033 }
2034 else if (!P_ISLEAF(opaque) &&
2036 {
2037 /*
2038 * Return first item after the internal page's "negative infinity"
2039 * item
2040 */
2043 }
2044 else
2045 {
2046 /*
2047 * No first item. Page is probably empty leaf page, but it's also
2048 * possible that it's an internal page with only a negative infinity
2049 * item.
2050 */
2053 errmsg_internal("%s block %u of index \"%s\" has no first data item",
2054 P_ISLEAF(opaque) ? "leaf" : "internal", targetnext,
2056 return NULL;
2057 }
2058
2059 /*
2060 * Return first real item scankey. Note that this relies on right page
2061 * memory remaining allocated.
2062 */
2065}

References bt_mkscankey_pivotsearch(), BTPageGetOpaque, BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_next, CHECK_FOR_INTERRUPTS, DEBUG2, ereport, errcode(), errdetail_internal(), errmsg_internal(), fb(), 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 3009 of file verify_nbtree.c.

3010{
3012 BTStack stack;
3013 Buffer lbuf;
3014 bool exists;
3015
3016 key = _bt_mkscankey(state->rel, itup);
3017 Assert(key->heapkeyspace && key->scantid != NULL);
3018
3019 /*
3020 * Search from root.
3021 *
3022 * Ideally, we would arrange to only move right within _bt_search() when
3023 * an interrupted page split is detected (i.e. when the incomplete split
3024 * bit is found to be set), but for now we accept the possibility that
3025 * that could conceal an inconsistency.
3026 */
3027 Assert(state->readonly && state->rootdescend);
3028 exists = false;
3029 stack = _bt_search(state->rel, NULL, key, &lbuf, BT_READ);
3030
3031 if (BufferIsValid(lbuf))
3032 {
3034 OffsetNumber offnum;
3035 Page page;
3036
3037 insertstate.itup = itup;
3038 insertstate.itemsz = MAXALIGN(IndexTupleSize(itup));
3039 insertstate.itup_key = key;
3040 insertstate.postingoff = 0;
3041 insertstate.bounds_valid = false;
3042 insertstate.buf = lbuf;
3043
3044 /* Get matching tuple on leaf page */
3045 offnum = _bt_binsrch_insert(state->rel, &insertstate);
3046 /* Compare first >= matching item on leaf page, if any */
3047 page = BufferGetPage(lbuf);
3048 /* Should match on first heap TID when tuple has a posting list */
3049 if (offnum <= PageGetMaxOffsetNumber(page) &&
3050 insertstate.postingoff <= 0 &&
3051 _bt_compare(state->rel, key, page, offnum) == 0)
3052 exists = true;
3053 _bt_relbuf(state->rel, lbuf);
3054 }
3055
3056 _bt_freestack(stack);
3057 pfree(key);
3058
3059 return exists;
3060}

References _bt_binsrch_insert(), _bt_compare(), _bt_freestack(), _bt_mkscankey(), _bt_relbuf(), _bt_search(), Assert, BT_READ, BufferGetPage(), BufferIsValid(), fb(), IndexTupleSize(), BTInsertStateData::itup, MAXALIGN, PageGetMaxOffsetNumber(), and pfree().

Referenced by bt_target_page_check().

◆ bt_target_page_check()

static void bt_target_page_check ( BtreeCheckState state)
static

Definition at line 1239 of file verify_nbtree.c.

1240{
1241 OffsetNumber offset;
1242 OffsetNumber max;
1244
1245 /* Last visible entry info for checking indexes with unique constraint */
1247
1248 topaque = BTPageGetOpaque(state->target);
1249 max = PageGetMaxOffsetNumber(state->target);
1250
1251 elog(DEBUG2, "verifying %u items on %s block %u", max,
1252 P_ISLEAF(topaque) ? "leaf" : "internal", state->targetblock);
1253
1254 /*
1255 * Check the number of attributes in high key. Note, rightmost page
1256 * doesn't contain a high key, so nothing to check
1257 */
1258 if (!P_RIGHTMOST(topaque))
1259 {
1260 ItemId itemid;
1261 IndexTuple itup;
1262
1263 /* Verify line pointer before checking tuple */
1264 itemid = PageGetItemIdCareful(state, state->targetblock,
1265 state->target, P_HIKEY);
1266 if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target,
1267 P_HIKEY))
1268 {
1269 itup = (IndexTuple) PageGetItem(state->target, itemid);
1270 ereport(ERROR,
1272 errmsg("wrong number of high key index tuple attributes in index \"%s\"",
1274 errdetail_internal("Index block=%u natts=%u block type=%s page lsn=%X/%08X.",
1275 state->targetblock,
1276 BTreeTupleGetNAtts(itup, state->rel),
1277 P_ISLEAF(topaque) ? "heap" : "index",
1278 LSN_FORMAT_ARGS(state->targetlsn))));
1279 }
1280 }
1281
1282 /*
1283 * Loop over page items, starting from first non-highkey item, not high
1284 * key (if any). Most tests are not performed for the "negative infinity"
1285 * real item (if any).
1286 */
1287 for (offset = P_FIRSTDATAKEY(topaque);
1288 offset <= max;
1289 offset = OffsetNumberNext(offset))
1290 {
1291 ItemId itemid;
1292 IndexTuple itup;
1293 size_t tupsize;
1295 bool lowersizelimit;
1296 ItemPointer scantid;
1297
1298 /*
1299 * True if we already called bt_entry_unique_check() for the current
1300 * item. This helps to avoid visiting the heap for keys, which are
1301 * anyway presented only once and can't comprise a unique violation.
1302 */
1303 bool unique_checked = false;
1304
1306
1307 itemid = PageGetItemIdCareful(state, state->targetblock,
1308 state->target, offset);
1309 itup = (IndexTuple) PageGetItem(state->target, itemid);
1310 tupsize = IndexTupleSize(itup);
1311
1312 /*
1313 * lp_len should match the IndexTuple reported length exactly, since
1314 * lp_len is completely redundant in indexes, and both sources of
1315 * tuple length are MAXALIGN()'d. nbtree does not use lp_len all that
1316 * frequently, and is surprisingly tolerant of corrupt lp_len fields.
1317 */
1318 if (tupsize != ItemIdGetLength(itemid))
1319 ereport(ERROR,
1321 errmsg("index tuple size does not equal lp_len in index \"%s\"",
1323 errdetail_internal("Index tid=(%u,%u) tuple size=%zu lp_len=%u page lsn=%X/%08X.",
1324 state->targetblock, offset,
1325 tupsize, ItemIdGetLength(itemid),
1326 LSN_FORMAT_ARGS(state->targetlsn)),
1327 errhint("This could be a torn page problem.")));
1328
1329 /* Check the number of index tuple attributes */
1330 if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target,
1331 offset))
1332 {
1333 ItemPointer tid;
1334 char *itid,
1335 *htid;
1336
1337 itid = psprintf("(%u,%u)", state->targetblock, offset);
1338 tid = BTreeTupleGetPointsToTID(itup);
1339 htid = psprintf("(%u,%u)",
1342
1343 ereport(ERROR,
1345 errmsg("wrong number of index tuple attributes in index \"%s\"",
1347 errdetail_internal("Index tid=%s natts=%u points to %s tid=%s page lsn=%X/%08X.",
1348 itid,
1349 BTreeTupleGetNAtts(itup, state->rel),
1350 P_ISLEAF(topaque) ? "heap" : "index",
1351 htid,
1352 LSN_FORMAT_ARGS(state->targetlsn))));
1353 }
1354
1355 /*
1356 * Don't try to generate scankey using "negative infinity" item on
1357 * internal pages. They are always truncated to zero attributes.
1358 */
1360 {
1361 /*
1362 * We don't call bt_child_check() for "negative infinity" items.
1363 * But if we're performing downlink connectivity check, we do it
1364 * for every item including "negative infinity" one.
1365 */
1366 if (!P_ISLEAF(topaque) && state->readonly)
1367 {
1369 offset,
1370 NULL,
1371 topaque->btpo_level);
1372 }
1373 continue;
1374 }
1375
1376 /*
1377 * Readonly callers may optionally verify that non-pivot tuples can
1378 * each be found by an independent search that starts from the root.
1379 * Note that we deliberately don't do individual searches for each
1380 * TID, since the posting list itself is validated by other checks.
1381 */
1382 if (state->rootdescend && P_ISLEAF(topaque) &&
1383 !bt_rootdescend(state, itup))
1384 {
1386 char *itid,
1387 *htid;
1388
1389 itid = psprintf("(%u,%u)", state->targetblock, offset);
1390 htid = psprintf("(%u,%u)", ItemPointerGetBlockNumber(tid),
1392
1393 ereport(ERROR,
1395 errmsg("could not find tuple using search from root page in index \"%s\"",
1397 errdetail_internal("Index tid=%s points to heap tid=%s page lsn=%X/%08X.",
1398 itid, htid,
1399 LSN_FORMAT_ARGS(state->targetlsn))));
1400 }
1401
1402 /*
1403 * If tuple is a posting list tuple, make sure posting list TIDs are
1404 * in order
1405 */
1406 if (BTreeTupleIsPosting(itup))
1407 {
1408 ItemPointerData last;
1409 ItemPointer current;
1410
1412
1413 for (int i = 1; i < BTreeTupleGetNPosting(itup); i++)
1414 {
1415
1416 current = BTreeTupleGetPostingN(itup, i);
1417
1418 if (ItemPointerCompare(current, &last) <= 0)
1419 {
1420 char *itid = psprintf("(%u,%u)", state->targetblock, offset);
1421
1422 ereport(ERROR,
1424 errmsg_internal("posting list contains misplaced TID in index \"%s\"",
1426 errdetail_internal("Index tid=%s posting list offset=%d page lsn=%X/%08X.",
1427 itid, i,
1428 LSN_FORMAT_ARGS(state->targetlsn))));
1429 }
1430
1431 ItemPointerCopy(current, &last);
1432 }
1433 }
1434
1435 /* Build insertion scankey for current page offset */
1436 skey = bt_mkscankey_pivotsearch(state->rel, itup);
1437
1438 /*
1439 * Make sure tuple size does not exceed the relevant BTREE_VERSION
1440 * specific limit.
1441 *
1442 * BTREE_VERSION 4 (which introduced heapkeyspace rules) requisitioned
1443 * a small amount of space from BTMaxItemSize() in order to ensure
1444 * that suffix truncation always has enough space to add an explicit
1445 * heap TID back to a tuple -- we pessimistically assume that every
1446 * newly inserted tuple will eventually need to have a heap TID
1447 * appended during a future leaf page split, when the tuple becomes
1448 * the basis of the new high key (pivot tuple) for the leaf page.
1449 *
1450 * Since the reclaimed space is reserved for that purpose, we must not
1451 * enforce the slightly lower limit when the extra space has been used
1452 * as intended. In other words, there is only a cross-version
1453 * difference in the limit on tuple size within leaf pages.
1454 *
1455 * Still, we're particular about the details within BTREE_VERSION 4
1456 * internal pages. Pivot tuples may only use the extra space for its
1457 * designated purpose. Enforce the lower limit for pivot tuples when
1458 * an explicit heap TID isn't actually present. (In all other cases
1459 * suffix truncation is guaranteed to generate a pivot tuple that's no
1460 * larger than the firstright tuple provided to it by its caller.)
1461 */
1462 lowersizelimit = skey->heapkeyspace &&
1465 {
1467 char *itid,
1468 *htid;
1469
1470 itid = psprintf("(%u,%u)", state->targetblock, offset);
1471 htid = psprintf("(%u,%u)",
1474
1475 ereport(ERROR,
1477 errmsg("index row size %zu exceeds maximum for index \"%s\"",
1479 errdetail_internal("Index tid=%s points to %s tid=%s page lsn=%X/%08X.",
1480 itid,
1481 P_ISLEAF(topaque) ? "heap" : "index",
1482 htid,
1483 LSN_FORMAT_ARGS(state->targetlsn))));
1484 }
1485
1486 /* Fingerprint leaf page tuples (those that point to the heap) */
1487 if (state->heapallindexed && P_ISLEAF(topaque) && !ItemIdIsDead(itemid))
1488 {
1490
1491 if (BTreeTupleIsPosting(itup))
1492 {
1493 /* Fingerprint all elements as distinct "plain" tuples */
1494 for (int i = 0; i < BTreeTupleGetNPosting(itup); i++)
1495 {
1497
1500 bloom_add_element(state->filter, (unsigned char *) norm,
1502 /* Be tidy */
1503 if (norm != logtuple)
1504 pfree(norm);
1505 pfree(logtuple);
1506 }
1507 }
1508 else
1509 {
1510 norm = bt_normalize_tuple(state, itup);
1511 bloom_add_element(state->filter, (unsigned char *) norm,
1513 /* Be tidy */
1514 if (norm != itup)
1515 pfree(norm);
1516 }
1517 }
1518
1519 /*
1520 * * High key check *
1521 *
1522 * If there is a high key (if this is not the rightmost page on its
1523 * entire level), check that high key actually is upper bound on all
1524 * page items. If this is a posting list tuple, we'll need to set
1525 * scantid to be highest TID in posting list.
1526 *
1527 * We prefer to check all items against high key rather than checking
1528 * just the last and trusting that the operator class obeys the
1529 * transitive law (which implies that all previous items also
1530 * respected the high key invariant if they pass the item order
1531 * check).
1532 *
1533 * Ideally, we'd compare every item in the index against every other
1534 * item in the index, and not trust opclass obedience of the
1535 * transitive law to bridge the gap between children and their
1536 * grandparents (as well as great-grandparents, and so on). We don't
1537 * go to those lengths because that would be prohibitively expensive,
1538 * and probably not markedly more effective in practice.
1539 *
1540 * On the leaf level, we check that the key is <= the highkey.
1541 * However, on non-leaf levels we check that the key is < the highkey,
1542 * because the high key is "just another separator" rather than a copy
1543 * of some existing key item; we expect it to be unique among all keys
1544 * on the same level. (Suffix truncation will sometimes produce a
1545 * leaf highkey that is an untruncated copy of the lastleft item, but
1546 * never any other item, which necessitates weakening the leaf level
1547 * check to <=.)
1548 *
1549 * Full explanation for why a highkey is never truly a copy of another
1550 * item from the same level on internal levels:
1551 *
1552 * While the new left page's high key is copied from the first offset
1553 * on the right page during an internal page split, that's not the
1554 * full story. In effect, internal pages are split in the middle of
1555 * the firstright tuple, not between the would-be lastleft and
1556 * firstright tuples: the firstright key ends up on the left side as
1557 * left's new highkey, and the firstright downlink ends up on the
1558 * right side as right's new "negative infinity" item. The negative
1559 * infinity tuple is truncated to zero attributes, so we're only left
1560 * with the downlink. In other words, the copying is just an
1561 * implementation detail of splitting in the middle of a (pivot)
1562 * tuple. (See also: "Notes About Data Representation" in the nbtree
1563 * README.)
1564 */
1565 scantid = skey->scantid;
1566 if (state->heapkeyspace && BTreeTupleIsPosting(itup))
1567 skey->scantid = BTreeTupleGetMaxHeapTID(itup);
1568
1569 if (!P_RIGHTMOST(topaque) &&
1572 {
1574 char *itid,
1575 *htid;
1576
1577 itid = psprintf("(%u,%u)", state->targetblock, offset);
1578 htid = psprintf("(%u,%u)",
1581
1582 ereport(ERROR,
1584 errmsg("high key invariant violated for index \"%s\"",
1586 errdetail_internal("Index tid=%s points to %s tid=%s page lsn=%X/%08X.",
1587 itid,
1588 P_ISLEAF(topaque) ? "heap" : "index",
1589 htid,
1590 LSN_FORMAT_ARGS(state->targetlsn))));
1591 }
1592 /* Reset, in case scantid was set to (itup) posting tuple's max TID */
1593 skey->scantid = scantid;
1594
1595 /*
1596 * * Item order check *
1597 *
1598 * Check that items are stored on page in logical order, by checking
1599 * current item is strictly less than next item (if any).
1600 */
1601 if (OffsetNumberNext(offset) <= max &&
1603 {
1604 ItemPointer tid;
1605 char *itid,
1606 *htid,
1607 *nitid,
1608 *nhtid;
1609
1610 itid = psprintf("(%u,%u)", state->targetblock, offset);
1611 tid = BTreeTupleGetPointsToTID(itup);
1612 htid = psprintf("(%u,%u)",
1615 nitid = psprintf("(%u,%u)", state->targetblock,
1616 OffsetNumberNext(offset));
1617
1618 /* Reuse itup to get pointed-to heap location of second item */
1619 itemid = PageGetItemIdCareful(state, state->targetblock,
1620 state->target,
1621 OffsetNumberNext(offset));
1622 itup = (IndexTuple) PageGetItem(state->target, itemid);
1623 tid = BTreeTupleGetPointsToTID(itup);
1624 nhtid = psprintf("(%u,%u)",
1627
1628 ereport(ERROR,
1630 errmsg("item order invariant violated for index \"%s\"",
1632 errdetail_internal("Lower index tid=%s (points to %s tid=%s) higher index tid=%s (points to %s tid=%s) page lsn=%X/%08X.",
1633 itid,
1634 P_ISLEAF(topaque) ? "heap" : "index",
1635 htid,
1636 nitid,
1637 P_ISLEAF(topaque) ? "heap" : "index",
1638 nhtid,
1639 LSN_FORMAT_ARGS(state->targetlsn))));
1640 }
1641
1642 /*
1643 * If the index is unique verify entries uniqueness by checking the
1644 * heap tuples visibility. Immediately check posting tuples and
1645 * tuples with repeated keys. Postpone check for keys, which have the
1646 * first appearance.
1647 */
1648 if (state->checkunique && state->indexinfo->ii_Unique &&
1649 P_ISLEAF(topaque) && !skey->anynullkeys &&
1651 {
1652 bt_entry_unique_check(state, itup, state->targetblock, offset,
1653 &lVis);
1654 unique_checked = true;
1655 }
1656
1657 if (state->checkunique && state->indexinfo->ii_Unique &&
1658 P_ISLEAF(topaque) && OffsetNumberNext(offset) <= max)
1659 {
1660 /* Save current scankey tid */
1661 scantid = skey->scantid;
1662
1663 /*
1664 * Invalidate scankey tid to make _bt_compare compare only keys in
1665 * the item to report equality even if heap TIDs are different
1666 */
1667 skey->scantid = NULL;
1668
1669 /*
1670 * If next key tuple is different, invalidate last visible entry
1671 * data (whole index tuple or last posting in index tuple). Key
1672 * containing null value does not violate unique constraint and
1673 * treated as different to any other key.
1674 *
1675 * If the next key is the same as the previous one, do the
1676 * bt_entry_unique_check() call if it was postponed.
1677 */
1678 if (_bt_compare(state->rel, skey, state->target,
1679 OffsetNumberNext(offset)) != 0 || skey->anynullkeys)
1680 {
1681 lVis.blkno = InvalidBlockNumber;
1682 lVis.offset = InvalidOffsetNumber;
1683 lVis.postingIndex = -1;
1684 lVis.tid = NULL;
1685 }
1686 else if (!unique_checked)
1687 {
1688 bt_entry_unique_check(state, itup, state->targetblock, offset,
1689 &lVis);
1690 }
1691 skey->scantid = scantid; /* Restore saved scan key state */
1692 }
1693
1694 /*
1695 * * Last item check *
1696 *
1697 * Check last item against next/right page's first data item's when
1698 * last item on page is reached. This additional check will detect
1699 * transposed pages iff the supposed right sibling page happens to
1700 * belong before target in the key space. (Otherwise, a subsequent
1701 * heap verification will probably detect the problem.)
1702 *
1703 * This check is similar to the item order check that will have
1704 * already been performed for every other "real" item on target page
1705 * when last item is checked. The difference is that the next item
1706 * (the item that is compared to target's last item) needs to come
1707 * from the next/sibling page. There may not be such an item
1708 * available from sibling for various reasons, though (e.g., target is
1709 * the rightmost page on level).
1710 */
1711 if (offset == max)
1712 {
1714
1715 /* first offset on a right index page (log only) */
1717
1718 /* Get item in next/right page */
1720
1721 if (rightkey &&
1723 {
1724 /*
1725 * As explained at length in bt_right_page_check_scankey(),
1726 * there is a known !readonly race that could account for
1727 * apparent violation of invariant, which we must check for
1728 * before actually proceeding with raising error. Our canary
1729 * condition is that target page was deleted.
1730 */
1731 if (!state->readonly)
1732 {
1733 /* Get fresh copy of target page */
1734 state->target = palloc_btree_page(state, state->targetblock);
1735 /* Note that we deliberately do not update target LSN */
1736 topaque = BTPageGetOpaque(state->target);
1737
1738 /*
1739 * All !readonly checks now performed; just return
1740 */
1741 if (P_IGNORE(topaque))
1742 return;
1743 }
1744
1745 ereport(ERROR,
1747 errmsg("cross page item order invariant violated for index \"%s\"",
1749 errdetail_internal("Last item on page tid=(%u,%u) page lsn=%X/%08X.",
1750 state->targetblock, offset,
1751 LSN_FORMAT_ARGS(state->targetlsn))));
1752 }
1753
1754 /*
1755 * If index has unique constraint make sure that no more than one
1756 * found equal items is visible.
1757 */
1758 if (state->checkunique && state->indexinfo->ii_Unique &&
1760 {
1762
1763 elog(DEBUG2, "check cross page unique condition");
1764
1765 /*
1766 * Make _bt_compare compare only index keys without heap TIDs.
1767 * rightkey->scantid is modified destructively but it is ok
1768 * for it is not used later.
1769 */
1770 rightkey->scantid = NULL;
1771
1772 /* The first key on the next page is the same */
1773 if (_bt_compare(state->rel, rightkey, state->target, max) == 0 &&
1774 !rightkey->anynullkeys)
1775 {
1777
1778 /*
1779 * Do the bt_entry_unique_check() call if it was
1780 * postponed.
1781 */
1782 if (!unique_checked)
1783 bt_entry_unique_check(state, itup, state->targetblock,
1784 offset, &lVis);
1785
1786 elog(DEBUG2, "cross page equal keys");
1790
1791 if (P_IGNORE(topaque))
1792 {
1794 break;
1795 }
1796
1797 if (unlikely(!P_ISLEAF(topaque)))
1798 ereport(ERROR,
1800 errmsg("right block of leaf block is non-leaf for index \"%s\"",
1802 errdetail_internal("Block=%u page lsn=%X/%08X.",
1803 state->targetblock,
1804 LSN_FORMAT_ARGS(state->targetlsn))));
1805
1807 rightpage,
1809 itup = (IndexTuple) PageGetItem(rightpage, itemid);
1810
1812
1814 }
1815 }
1816 }
1817
1818 /*
1819 * * Downlink check *
1820 *
1821 * Additional check of child items iff this is an internal page and
1822 * caller holds a ShareLock. This happens for every downlink (item)
1823 * in target excluding the negative-infinity downlink (again, this is
1824 * because it has no useful value to compare).
1825 */
1826 if (!P_ISLEAF(topaque) && state->readonly)
1827 bt_child_check(state, skey, offset);
1828 }
1829
1830 /*
1831 * Special case bt_child_highkey_check() call
1832 *
1833 * We don't pass a real downlink, but we've to finish the level
1834 * processing. If condition is satisfied, we've already processed all the
1835 * downlinks from the target level. But there still might be pages to the
1836 * right of the child page pointer to by our rightmost downlink. And they
1837 * might have missing downlinks. This final call checks for them.
1838 */
1839 if (!P_ISLEAF(topaque) && P_RIGHTMOST(topaque) && state->readonly)
1840 {
1842 NULL, topaque->btpo_level);
1843 }
1844}

References _bt_check_natts(), _bt_compare(), bloom_add_element(), bt_child_check(), bt_child_highkey_check(), bt_entry_unique_check(), bt_mkscankey_pivotsearch(), bt_normalize_tuple(), bt_posting_plain_tuple(), bt_right_page_check_scankey(), bt_rootdescend(), BTMaxItemSize, BTMaxItemSizeNoHeapTid, BTPageGetOpaque, BTreeTupleGetHeapTID(), BTreeTupleGetMaxHeapTID(), BTreeTupleGetNAtts, BTreeTupleGetNPosting(), BTreeTupleGetPointsToTID(), BTreeTupleGetPostingN(), BTreeTupleIsPosting(), CHECK_FOR_INTERRUPTS, DEBUG2, elog, ereport, errcode(), errdetail_internal(), errhint(), errmsg(), errmsg_internal(), ERROR, fb(), i, IndexTupleSize(), InvalidBlockNumber, InvalidOffsetNumber, invariant_g_offset(), invariant_l_offset(), invariant_leq_offset(), ItemIdGetLength, ItemIdIsDead, ItemPointerCompare(), ItemPointerCopy(), ItemPointerGetBlockNumber(), ItemPointerGetBlockNumberNoCheck(), ItemPointerGetOffsetNumber(), ItemPointerGetOffsetNumberNoCheck(), ItemPointerIsValid(), 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 unlikely.

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

2782{
2784 IndexTuple itup,
2785 norm;
2786
2787 Assert(state->heapallindexed);
2788
2789 /* Generate a normalized index tuple for fingerprinting */
2791 itup->t_tid = *tid;
2792 norm = bt_normalize_tuple(state, itup);
2793
2794 /* Probe Bloom filter -- tuple should be present */
2795 if (bloom_lacks_element(state->filter, (unsigned char *) norm,
2797 ereport(ERROR,
2799 errmsg("heap tuple (%u,%u) from table \"%s\" lacks matching index tuple within index \"%s\"",
2804 !state->readonly
2805 ? errhint("Retrying verification using the function bt_index_parent_check() might provide a more specific error.")
2806 : 0));
2807
2808 state->heaptuplespresent++;
2809 pfree(itup);
2810 /* Cannot leak memory here */
2811 if (norm != itup)
2812 pfree(norm);
2813}

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

Referenced by bt_check_every_level().

◆ BTreeTupleGetHeapTIDCareful()

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

Definition at line 3532 of file verify_nbtree.c.

3534{
3536
3537 /*
3538 * Caller determines whether this is supposed to be a pivot or non-pivot
3539 * tuple using page type and item offset number. Verify that tuple
3540 * metadata agrees with this.
3541 */
3542 Assert(state->heapkeyspace);
3543 if (BTreeTupleIsPivot(itup) && nonpivot)
3544 ereport(ERROR,
3546 errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected pivot tuple",
3547 state->targetblock,
3549
3550 if (!BTreeTupleIsPivot(itup) && !nonpivot)
3551 ereport(ERROR,
3553 errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected non-pivot tuple",
3554 state->targetblock,
3556
3557 htid = BTreeTupleGetHeapTID(itup);
3559 ereport(ERROR,
3561 errmsg("block %u or its right sibling block or child block in index \"%s\" contains non-pivot tuple that lacks a heap TID",
3562 state->targetblock,
3564
3565 return htid;
3566}

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

Referenced by invariant_l_nontarget_offset(), and invariant_l_offset().

◆ BTreeTupleGetPointsToTID()

static ItemPointer BTreeTupleGetPointsToTID ( IndexTuple  itup)
inlinestatic

Definition at line 3580 of file verify_nbtree.c.

3581{
3582 /*
3583 * Rely on the assumption that !heapkeyspace internal page data items will
3584 * correctly return TID with downlink here -- BTreeTupleGetHeapTID() won't
3585 * recognize it as a pivot tuple, but everything still works out because
3586 * the t_tid field is still returned
3587 */
3588 if (!BTreeTupleIsPivot(itup))
3589 return BTreeTupleGetHeapTID(itup);
3590
3591 /* Pivot tuple returns TID with downlink block (heapkeyspace variant) */
3592 return &itup->t_tid;
3593}

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

Referenced by bt_target_page_check().

◆ heap_entry_is_visible()

static bool heap_entry_is_visible ( BtreeCheckState state,
ItemPointer  tid 
)
static

Definition at line 852 of file verify_nbtree.c.

853{
854 bool tid_visible;
855
856 TupleTableSlot *slot = table_slot_create(state->heaprel, NULL);
857
859 tid, state->snapshot, slot);
860 if (slot != NULL)
862
863 return tid_visible;
864}

References ExecDropSingleTupleTableSlot(), fb(), table_slot_create(), and table_tuple_fetch_row_version().

Referenced by bt_entry_unique_check().

◆ invariant_g_offset()

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

Definition at line 3194 of file verify_nbtree.c.

3196{
3197 int32 cmp;
3198
3199 Assert(!key->nextkey && key->backward);
3200
3201 cmp = _bt_compare(state->rel, key, state->target, lowerbound);
3202
3203 /* pg_upgrade'd indexes may legally have equal sibling tuples */
3204 if (!key->heapkeyspace)
3205 return cmp >= 0;
3206
3207 /*
3208 * No need to consider the possibility that scankey has attributes that we
3209 * need to force to be interpreted as negative infinity. _bt_compare() is
3210 * able to determine that scankey is greater than negative infinity. The
3211 * distinction between "==" and "<" isn't interesting here, since
3212 * corruption is indicated either way.
3213 */
3214 return cmp > 0;
3215}

References _bt_compare(), Assert, cmp(), and fb().

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

3233{
3234 ItemId itemid;
3235 int32 cmp;
3236
3237 Assert(!key->nextkey && key->backward);
3238
3239 /* Verify line pointer before checking tuple */
3241 upperbound);
3242 cmp = _bt_compare(state->rel, key, nontarget, upperbound);
3243
3244 /* pg_upgrade'd indexes may legally have equal sibling tuples */
3245 if (!key->heapkeyspace)
3246 return cmp <= 0;
3247
3248 /* See invariant_l_offset() for an explanation of this extra step */
3249 if (cmp == 0)
3250 {
3251 IndexTuple child;
3252 int uppnkeyatts;
3255 bool nonpivot;
3256
3257 child = (IndexTuple) PageGetItem(nontarget, itemid);
3260
3261 /* Get number of keys + heap TID for child/non-target item */
3264
3265 /* Heap TID is tiebreaker key attribute */
3266 if (key->keysz == uppnkeyatts)
3267 return key->scantid == NULL && childheaptid != NULL;
3268
3269 return key->keysz < uppnkeyatts;
3270 }
3271
3272 return cmp < 0;
3273}

References _bt_compare(), Assert, BTPageGetOpaque, BTreeTupleGetHeapTIDCareful(), BTreeTupleGetNKeyAtts, cmp(), fb(), 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 3108 of file verify_nbtree.c.

3110{
3111 ItemId itemid;
3112 int32 cmp;
3113
3114 Assert(!key->nextkey && key->backward);
3115
3116 /* Verify line pointer before checking tuple */
3117 itemid = PageGetItemIdCareful(state, state->targetblock, state->target,
3118 upperbound);
3119 /* pg_upgrade'd indexes may legally have equal sibling tuples */
3120 if (!key->heapkeyspace)
3122
3123 cmp = _bt_compare(state->rel, key, state->target, upperbound);
3124
3125 /*
3126 * _bt_compare() is capable of determining that a scankey with a
3127 * filled-out attribute is greater than pivot tuples where the comparison
3128 * is resolved at a truncated attribute (value of attribute in pivot is
3129 * minus infinity). However, it is not capable of determining that a
3130 * scankey is _less than_ a tuple on the basis of a comparison resolved at
3131 * _scankey_ minus infinity attribute. Complete an extra step to simulate
3132 * having minus infinity values for omitted scankey attribute(s).
3133 */
3134 if (cmp == 0)
3135 {
3138 int uppnkeyatts;
3140 bool nonpivot;
3141
3142 ritup = (IndexTuple) PageGetItem(state->target, itemid);
3143 topaque = BTPageGetOpaque(state->target);
3145
3146 /* Get number of keys + heap TID for item to the right */
3149
3150 /* Heap TID is tiebreaker key attribute */
3151 if (key->keysz == uppnkeyatts)
3152 return key->scantid == NULL && rheaptid != NULL;
3153
3154 return key->keysz < uppnkeyatts;
3155 }
3156
3157 return cmp < 0;
3158}

References _bt_compare(), Assert, BTPageGetOpaque, BTreeTupleGetHeapTIDCareful(), BTreeTupleGetNKeyAtts, cmp(), fb(), invariant_leq_offset(), 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 3171 of file verify_nbtree.c.

3173{
3174 int32 cmp;
3175
3176 Assert(!key->nextkey && key->backward);
3177
3178 cmp = _bt_compare(state->rel, key, state->target, upperbound);
3179
3180 return cmp <= 0;
3181}

References _bt_compare(), Assert, cmp(), and fb().

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

3074{
3075 /*
3076 * For internal pages only, the first item after high key, if any, is
3077 * negative infinity item. Internal pages always have a negative infinity
3078 * item, whereas leaf pages never have one. This implies that negative
3079 * infinity item is either first or second line item, or there is none
3080 * within page.
3081 *
3082 * Negative infinity items are a special case among pivot tuples. They
3083 * always have zero attributes, while all other pivot tuples always have
3084 * nkeyatts attributes.
3085 *
3086 * Right-most pages don't have a high key, but could be said to
3087 * conceptually have a "positive infinity" high key. Thus, there is a
3088 * symmetry between down link items in parent pages, and high keys in
3089 * children. Together, they represent the part of the key space that
3090 * belongs to each page in the index. For example, all children of the
3091 * root page will have negative infinity as a lower bound from root
3092 * negative infinity downlink, and positive infinity as an upper bound
3093 * (implicitly, from "imaginary" positive infinity high key in root).
3094 */
3095 return !P_ISLEAF(opaque) && offset == P_FIRSTDATAKEY(opaque);
3096}

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

3494{
3495 ItemId itemid = PageGetItemId(page, offset);
3496
3497 if (ItemIdGetOffset(itemid) + ItemIdGetLength(itemid) >
3498 BLCKSZ - MAXALIGN(sizeof(BTPageOpaqueData)))
3499 ereport(ERROR,
3501 errmsg("line pointer points past end of tuple space in index \"%s\"",
3503 errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.",
3504 block, offset, ItemIdGetOffset(itemid),
3505 ItemIdGetLength(itemid),
3506 ItemIdGetFlags(itemid))));
3507
3508 /*
3509 * Verify that line pointer isn't LP_REDIRECT or LP_UNUSED, since nbtree
3510 * never uses either. Verify that line pointer has storage, too, since
3511 * even LP_DEAD items should within nbtree.
3512 */
3513 if (ItemIdIsRedirected(itemid) || !ItemIdIsUsed(itemid) ||
3514 ItemIdGetLength(itemid) == 0)
3515 ereport(ERROR,
3517 errmsg("invalid line pointer storage in index \"%s\"",
3519 errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.",
3520 block, offset, ItemIdGetOffset(itemid),
3521 ItemIdGetLength(itemid),
3522 ItemIdGetFlags(itemid))));
3523
3524 return itemid;
3525}

References ereport, errcode(), errdetail_internal(), errmsg(), ERROR, fb(), 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 3290 of file verify_nbtree.c.

3291{
3292 Buffer buffer;
3293 Page page;
3294 BTPageOpaque opaque;
3296
3297 page = palloc(BLCKSZ);
3298
3299 /*
3300 * We copy the page into local storage to avoid holding pin on the buffer
3301 * longer than we must.
3302 */
3303 buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum, RBM_NORMAL,
3304 state->checkstrategy);
3305 LockBuffer(buffer, BT_READ);
3306
3307 /*
3308 * Perform the same basic sanity checking that nbtree itself performs for
3309 * every page:
3310 */
3311 _bt_checkpage(state->rel, buffer);
3312
3313 /* Only use copy of page in palloc()'d memory */
3314 memcpy(page, BufferGetPage(buffer), BLCKSZ);
3315 UnlockReleaseBuffer(buffer);
3316
3317 opaque = BTPageGetOpaque(page);
3318
3319 if (P_ISMETA(opaque) && blocknum != BTREE_METAPAGE)
3320 ereport(ERROR,
3322 errmsg("invalid meta page found at block %u in index \"%s\"",
3323 blocknum, RelationGetRelationName(state->rel))));
3324
3325 /* Check page from block that ought to be meta page */
3326 if (blocknum == BTREE_METAPAGE)
3327 {
3329
3330 if (!P_ISMETA(opaque) ||
3331 metad->btm_magic != BTREE_MAGIC)
3332 ereport(ERROR,
3334 errmsg("index \"%s\" meta page is corrupt",
3336
3337 if (metad->btm_version < BTREE_MIN_VERSION ||
3338 metad->btm_version > BTREE_VERSION)
3339 ereport(ERROR,
3341 errmsg("version mismatch in index \"%s\": file version %d, "
3342 "current version %d, minimum supported version %d",
3344 metad->btm_version, BTREE_VERSION,
3346
3347 /* Finished with metapage checks */
3348 return page;
3349 }
3350
3351 /*
3352 * Deleted pages that still use the old 32-bit XID representation have no
3353 * sane "level" field because they type pun the field, but all other pages
3354 * (including pages deleted on Postgres 14+) have a valid value.
3355 */
3356 if (!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque))
3357 {
3358 /* Okay, no reason not to trust btpo_level field from page */
3359
3360 if (P_ISLEAF(opaque) && opaque->btpo_level != 0)
3361 ereport(ERROR,
3363 errmsg_internal("invalid leaf page level %u for block %u in index \"%s\"",
3364 opaque->btpo_level, blocknum,
3366
3367 if (!P_ISLEAF(opaque) && opaque->btpo_level == 0)
3368 ereport(ERROR,
3370 errmsg_internal("invalid internal page level 0 for block %u in index \"%s\"",
3371 blocknum,
3373 }
3374
3375 /*
3376 * Sanity checks for number of items on page.
3377 *
3378 * As noted at the beginning of _bt_binsrch(), an internal page must have
3379 * children, since there must always be a negative infinity downlink
3380 * (there may also be a highkey). In the case of non-rightmost leaf
3381 * pages, there must be at least a highkey. The exceptions are deleted
3382 * pages, which contain no items.
3383 *
3384 * This is correct when pages are half-dead, since internal pages are
3385 * never half-dead, and leaf pages must have a high key when half-dead
3386 * (the rightmost page can never be deleted). It's also correct with
3387 * fully deleted pages: _bt_unlink_halfdead_page() doesn't change anything
3388 * about the target page other than setting the page as fully dead, and
3389 * setting its xact field. In particular, it doesn't change the sibling
3390 * links in the deletion target itself, since they're required when index
3391 * scans land on the deletion target, and then need to move right (or need
3392 * to move left, in the case of backward index scans).
3393 */
3396 ereport(ERROR,
3398 errmsg("Number of items on block %u of index \"%s\" exceeds MaxIndexTuplesPerPage (%u)",
3399 blocknum, RelationGetRelationName(state->rel),
3401
3402 if (!P_ISLEAF(opaque) && !P_ISDELETED(opaque) && maxoffset < P_FIRSTDATAKEY(opaque))
3403 ereport(ERROR,
3405 errmsg("internal block %u in index \"%s\" lacks high key and/or at least one downlink",
3406 blocknum, RelationGetRelationName(state->rel))));
3407
3408 if (P_ISLEAF(opaque) && !P_ISDELETED(opaque) && !P_RIGHTMOST(opaque) && maxoffset < P_HIKEY)
3409 ereport(ERROR,
3411 errmsg("non-rightmost leaf block %u in index \"%s\" lacks high key item",
3412 blocknum, RelationGetRelationName(state->rel))));
3413
3414 /*
3415 * In general, internal pages are never marked half-dead, except on
3416 * versions of Postgres prior to 9.4, where it can be valid transient
3417 * state. This state is nonetheless treated as corruption by VACUUM on
3418 * from version 9.4 on, so do the same here. See _bt_pagedel() for full
3419 * details.
3420 */
3421 if (!P_ISLEAF(opaque) && P_ISHALFDEAD(opaque))
3422 ereport(ERROR,
3424 errmsg("internal page block %u in index \"%s\" is half-dead",
3425 blocknum, RelationGetRelationName(state->rel)),
3426 errhint("This can be caused by an interrupted VACUUM in version 9.3 or older, before upgrade. Please REINDEX it.")));
3427
3428 /*
3429 * Check that internal pages have no garbage items, and that no page has
3430 * an invalid combination of deletion-related page level flags
3431 */
3432 if (!P_ISLEAF(opaque) && P_HAS_GARBAGE(opaque))
3433 ereport(ERROR,
3435 errmsg_internal("internal page block %u in index \"%s\" has garbage items",
3436 blocknum, RelationGetRelationName(state->rel))));
3437
3438 if (P_HAS_FULLXID(opaque) && !P_ISDELETED(opaque))
3439 ereport(ERROR,
3441 errmsg_internal("full transaction id page flag appears in non-deleted block %u in index \"%s\"",
3442 blocknum, RelationGetRelationName(state->rel))));
3443
3444 if (P_ISDELETED(opaque) && P_ISHALFDEAD(opaque))
3445 ereport(ERROR,
3447 errmsg_internal("deleted page block %u in index \"%s\" is half-dead",
3448 blocknum, RelationGetRelationName(state->rel))));
3449
3450 return page;
3451}

References _bt_checkpage(), BT_READ, BTPageGetMeta, BTPageGetOpaque, BTPageOpaqueData::btpo_level, BTREE_MAGIC, BTREE_METAPAGE, BTREE_MIN_VERSION, BTREE_VERSION, BufferGetPage(), ereport, errcode(), errhint(), errmsg(), errmsg_internal(), ERROR, fb(), 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_leftmost_ignoring_half_dead(), 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  )

◆ PG_MODULE_MAGIC_EXT()

PG_MODULE_MAGIC_EXT ( name = "amcheck",
version = PG_VERSION 
)