1 /*-------------------------------------------------------------------------
2  *
3  * verify_nbtree.c
4  *		Verifies the integrity of nbtree indexes based on invariants.
5  *
6  * For B-Tree indexes, verification includes checking that each page in the
7  * target index has items in logical order as reported by an insertion scankey
8  * (the insertion scankey sort-wise NULL semantics are needed for
9  * verification).
10  *
11  * When index-to-heap verification is requested, a Bloom filter is used to
12  * fingerprint all tuples in the target index, as the index is traversed to
13  * verify its structure.  A heap scan later uses Bloom filter probes to verify
14  * that every visible heap tuple has a matching index tuple.
15  *
16  *
17  * Copyright (c) 2017-2018, PostgreSQL Global Development Group
18  *
19  * IDENTIFICATION
20  *	  contrib/amcheck/verify_nbtree.c
21  *
22  *-------------------------------------------------------------------------
23  */
24 #include "postgres.h"
25 
26 #include "access/htup_details.h"
27 #include "access/nbtree.h"
28 #include "access/transam.h"
29 #include "access/xact.h"
30 #include "catalog/index.h"
31 #include "catalog/pg_am.h"
32 #include "commands/tablecmds.h"
33 #include "lib/bloomfilter.h"
34 #include "miscadmin.h"
35 #include "storage/lmgr.h"
36 #include "storage/smgr.h"
37 #include "utils/memutils.h"
38 #include "utils/snapmgr.h"
39 
40 
41 PG_MODULE_MAGIC;
42 
43 /*
44  * A B-Tree cannot possibly have this many levels, since there must be one
45  * block per level, which is bound by the range of BlockNumber:
46  */
47 #define InvalidBtreeLevel	((uint32) InvalidBlockNumber)
48 
49 /*
50  * State associated with verifying a B-Tree index
51  *
52  * target is the point of reference for a verification operation.
53  *
54  * Other B-Tree pages may be allocated, but those are always auxiliary (e.g.,
55  * they are current target's child pages).  Conceptually, problems are only
56  * ever found in the current target page (or for a particular heap tuple during
57  * heapallindexed verification).  Each page found by verification's left/right,
58  * top/bottom scan becomes the target exactly once.
59  */
60 typedef struct BtreeCheckState
61 {
62 	/*
63 	 * Unchanging state, established at start of verification:
64 	 */
65 
66 	/* B-Tree Index Relation and associated heap relation */
67 	Relation	rel;
68 	Relation	heaprel;
69 	/* ShareLock held on heap/index, rather than AccessShareLock? */
70 	bool		readonly;
71 	/* Also verifying heap has no unindexed tuples? */
72 	bool		heapallindexed;
73 	/* Per-page context */
74 	MemoryContext targetcontext;
75 	/* Buffer access strategy */
76 	BufferAccessStrategy checkstrategy;
77 
78 	/*
79 	 * Mutable state, for verification of particular page:
80 	 */
81 
82 	/* Current target page */
83 	Page		target;
84 	/* Target block number */
85 	BlockNumber targetblock;
86 	/* Target page's LSN */
87 	XLogRecPtr	targetlsn;
88 
89 	/*
90 	 * Mutable state, for optional heapallindexed verification:
91 	 */
92 
93 	/* Bloom filter fingerprints B-Tree index */
94 	bloom_filter *filter;
95 	/* Bloom filter fingerprints downlink blocks within tree */
96 	bloom_filter *downlinkfilter;
97 	/* Right half of incomplete split marker */
98 	bool		rightsplit;
99 	/* Debug counter */
100 	int64		heaptuplespresent;
101 } BtreeCheckState;
102 
103 /*
104  * Starting point for verifying an entire B-Tree index level
105  */
106 typedef struct BtreeLevel
107 {
108 	/* Level number (0 is leaf page level). */
109 	uint32		level;
110 
111 	/* Left most block on level.  Scan of level begins here. */
112 	BlockNumber leftmost;
113 
114 	/* Is this level reported as "true" root level by meta page? */
115 	bool		istruerootlevel;
116 } BtreeLevel;
117 
118 PG_FUNCTION_INFO_V1(bt_index_check);
119 PG_FUNCTION_INFO_V1(bt_index_parent_check);
120 
121 static void bt_index_check_internal(Oid indrelid, bool parentcheck,
122 						bool heapallindexed);
123 static inline void btree_index_checkable(Relation rel);
124 static inline bool btree_index_mainfork_expected(Relation rel);
125 static void bt_check_every_level(Relation rel, Relation heaprel,
126 					 bool readonly, bool heapallindexed);
127 static BtreeLevel bt_check_level_from_leftmost(BtreeCheckState *state,
128 							 BtreeLevel level);
129 static void bt_target_page_check(BtreeCheckState *state);
130 static ScanKey bt_right_page_check_scankey(BtreeCheckState *state);
131 static void bt_downlink_check(BtreeCheckState *state, BlockNumber childblock,
132 				  ScanKey targetkey);
133 static void bt_downlink_missing_check(BtreeCheckState *state);
134 static void bt_tuple_present_callback(Relation index, HeapTuple htup,
135 						  Datum *values, bool *isnull,
136 						  bool tupleIsAlive, void *checkstate);
137 static IndexTuple bt_normalize_tuple(BtreeCheckState *state,
138 						   IndexTuple itup);
139 static inline bool offset_is_negative_infinity(BTPageOpaque opaque,
140 							OffsetNumber offset);
141 static inline bool invariant_leq_offset(BtreeCheckState *state,
142 					 ScanKey key,
143 					 OffsetNumber upperbound);
144 static inline bool invariant_geq_offset(BtreeCheckState *state,
145 					 ScanKey key,
146 					 OffsetNumber lowerbound);
147 static inline bool invariant_leq_nontarget_offset(BtreeCheckState *state,
148 							   Page other,
149 							   ScanKey key,
150 							   OffsetNumber upperbound);
151 static Page palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum);
152 
153 /*
154  * bt_index_check(index regclass, heapallindexed boolean)
155  *
156  * Verify integrity of B-Tree index.
157  *
158  * Acquires AccessShareLock on heap & index relations.  Does not consider
159  * invariants that exist between parent/child pages.  Optionally verifies
160  * that heap does not contain any unindexed or incorrectly indexed tuples.
161  */
162 Datum
163 bt_index_check(PG_FUNCTION_ARGS)
164 {
165 	Oid			indrelid = PG_GETARG_OID(0);
166 	bool		heapallindexed = false;
167 
168 	if (PG_NARGS() == 2)
169 		heapallindexed = PG_GETARG_BOOL(1);
170 
171 	bt_index_check_internal(indrelid, false, heapallindexed);
172 
173 	PG_RETURN_VOID();
174 }
175 
176 /*
177  * bt_index_parent_check(index regclass, heapallindexed boolean)
178  *
179  * Verify integrity of B-Tree index.
180  *
181  * Acquires ShareLock on heap & index relations.  Verifies that downlinks in
182  * parent pages are valid lower bounds on child pages.  Optionally verifies
183  * that heap does not contain any unindexed or incorrectly indexed tuples.
184  */
185 Datum
186 bt_index_parent_check(PG_FUNCTION_ARGS)
187 {
188 	Oid			indrelid = PG_GETARG_OID(0);
189 	bool		heapallindexed = false;
190 
191 	if (PG_NARGS() == 2)
192 		heapallindexed = PG_GETARG_BOOL(1);
193 
194 	bt_index_check_internal(indrelid, true, heapallindexed);
195 
196 	PG_RETURN_VOID();
197 }
198 
199 /*
200  * Helper for bt_index_[parent_]check, coordinating the bulk of the work.
201  */
202 static void
203 bt_index_check_internal(Oid indrelid, bool parentcheck, bool heapallindexed)
204 {
205 	Oid			heapid;
206 	Relation	indrel;
207 	Relation	heaprel;
208 	LOCKMODE	lockmode;
209 
210 	if (parentcheck)
211 		lockmode = ShareLock;
212 	else
213 		lockmode = AccessShareLock;
214 
215 	/*
216 	 * We must lock table before index to avoid deadlocks.  However, if the
217 	 * passed indrelid isn't an index then IndexGetRelation() will fail.
218 	 * Rather than emitting a not-very-helpful error message, postpone
219 	 * complaining, expecting that the is-it-an-index test below will fail.
220 	 *
221 	 * In hot standby mode this will raise an error when parentcheck is true.
222 	 */
223 	heapid = IndexGetRelation(indrelid, true);
224 	if (OidIsValid(heapid))
225 		heaprel = heap_open(heapid, lockmode);
226 	else
227 		heaprel = NULL;
228 
229 	/*
230 	 * Open the target index relations separately (like relation_openrv(), but
231 	 * with heap relation locked first to prevent deadlocking).  In hot
232 	 * standby mode this will raise an error when parentcheck is true.
233 	 *
234 	 * There is no need for the usual indcheckxmin usability horizon test
235 	 * here, even in the heapallindexed case, because index undergoing
236 	 * verification only needs to have entries for a new transaction snapshot.
237 	 * (If this is a parentcheck verification, there is no question about
238 	 * committed or recently dead heap tuples lacking index entries due to
239 	 * concurrent activity.)
240 	 */
241 	indrel = index_open(indrelid, lockmode);
242 
243 	/*
244 	 * Since we did the IndexGetRelation call above without any lock, it's
245 	 * barely possible that a race against an index drop/recreation could have
246 	 * netted us the wrong table.
247 	 */
248 	if (heaprel == NULL || heapid != IndexGetRelation(indrelid, false))
249 		ereport(ERROR,
250 				(errcode(ERRCODE_UNDEFINED_TABLE),
251 				 errmsg("could not open parent table of index %s",
252 						RelationGetRelationName(indrel))));
253 
254 	/* Relation suitable for checking as B-Tree? */
255 	btree_index_checkable(indrel);
256 
257 	if (btree_index_mainfork_expected(indrel))
258 	{
259 		RelationOpenSmgr(indrel);
260 		if (!smgrexists(indrel->rd_smgr, MAIN_FORKNUM))
261 			ereport(ERROR,
262 					(errcode(ERRCODE_INDEX_CORRUPTED),
263 					 errmsg("index \"%s\" lacks a main relation fork",
264 							RelationGetRelationName(indrel))));
265 
266 		/* Check index, possibly against table it is an index on */
267 		bt_check_every_level(indrel, heaprel, parentcheck, heapallindexed);
268 	}
269 
270 	/*
271 	 * Release locks early. That's ok here because nothing in the called
272 	 * routines will trigger shared cache invalidations to be sent, so we can
273 	 * relax the usual pattern of only releasing locks after commit.
274 	 */
275 	index_close(indrel, lockmode);
276 	if (heaprel)
277 		heap_close(heaprel, lockmode);
278 }
279 
280 /*
281  * Basic checks about the suitability of a relation for checking as a B-Tree
282  * index.
283  *
284  * NB: Intentionally not checking permissions, the function is normally not
285  * callable by non-superusers. If granted, it's useful to be able to check a
286  * whole cluster.
287  */
288 static inline void
289 btree_index_checkable(Relation rel)
290 {
291 	if (rel->rd_rel->relkind != RELKIND_INDEX ||
292 		rel->rd_rel->relam != BTREE_AM_OID)
293 		ereport(ERROR,
294 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
295 				 errmsg("only B-Tree indexes are supported as targets for verification"),
296 				 errdetail("Relation \"%s\" is not a B-Tree index.",
297 						   RelationGetRelationName(rel))));
298 
299 	if (RELATION_IS_OTHER_TEMP(rel))
300 		ereport(ERROR,
301 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
302 				 errmsg("cannot access temporary tables of other sessions"),
303 				 errdetail("Index \"%s\" is associated with temporary relation.",
304 						   RelationGetRelationName(rel))));
305 
306 	if (!IndexIsValid(rel->rd_index))
307 		ereport(ERROR,
308 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
309 				 errmsg("cannot check index \"%s\"",
310 						RelationGetRelationName(rel)),
311 				 errdetail("Index is not valid")));
312 }
313 
314 /*
315  * Check if B-Tree index relation should have a file for its main relation
316  * fork.  Verification uses this to skip unlogged indexes when in hot standby
317  * mode, where there is simply nothing to verify.
318  *
319  * NB: Caller should call btree_index_checkable() before calling here.
320  */
321 static inline bool
322 btree_index_mainfork_expected(Relation rel)
323 {
324 	if (rel->rd_rel->relpersistence != RELPERSISTENCE_UNLOGGED ||
325 		!RecoveryInProgress())
326 		return true;
327 
328 	ereport(NOTICE,
329 			(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
330 			 errmsg("cannot verify unlogged index \"%s\" during recovery, skipping",
331 					RelationGetRelationName(rel))));
332 
333 	return false;
334 }
335 
336 /*
337  * Main entry point for B-Tree SQL-callable functions. Walks the B-Tree in
338  * logical order, verifying invariants as it goes.  Optionally, verification
339  * checks if the heap relation contains any tuples that are not represented in
340  * the index but should be.
341  *
342  * It is the caller's responsibility to acquire appropriate heavyweight lock on
343  * the index relation, and advise us if extra checks are safe when a ShareLock
344  * is held.  (A lock of the same type must also have been acquired on the heap
345  * relation.)
346  *
347  * A ShareLock is generally assumed to prevent any kind of physical
348  * modification to the index structure, including modifications that VACUUM may
349  * make.  This does not include setting of the LP_DEAD bit by concurrent index
350  * scans, although that is just metadata that is not able to directly affect
351  * any check performed here.  Any concurrent process that might act on the
352  * LP_DEAD bit being set (recycle space) requires a heavyweight lock that
353  * cannot be held while we hold a ShareLock.  (Besides, even if that could
354  * happen, the ad-hoc recycling when a page might otherwise split is performed
355  * per-page, and requires an exclusive buffer lock, which wouldn't cause us
356  * trouble.  _bt_delitems_vacuum() may only delete leaf items, and so the extra
357  * parent/child check cannot be affected.)
358  */
359 static void
360 bt_check_every_level(Relation rel, Relation heaprel, bool readonly,
361 					 bool heapallindexed)
362 {
363 	BtreeCheckState *state;
364 	Page		metapage;
365 	BTMetaPageData *metad;
366 	uint32		previouslevel;
367 	BtreeLevel	current;
368 	Snapshot	snapshot = SnapshotAny;
369 
370 	/*
371 	 * RecentGlobalXmin assertion matches index_getnext_tid().  See note on
372 	 * RecentGlobalXmin/B-Tree page deletion.
373 	 */
374 	Assert(TransactionIdIsValid(RecentGlobalXmin));
375 
376 	/*
377 	 * Initialize state for entire verification operation
378 	 */
379 	state = palloc0(sizeof(BtreeCheckState));
380 	state->rel = rel;
381 	state->heaprel = heaprel;
382 	state->readonly = readonly;
383 	state->heapallindexed = heapallindexed;
384 
385 	if (state->heapallindexed)
386 	{
387 		int64		total_pages;
388 		int64		total_elems;
389 		uint64		seed;
390 
391 		/*
392 		 * Size Bloom filter based on estimated number of tuples in index,
393 		 * while conservatively assuming that each block must contain at least
394 		 * MaxIndexTuplesPerPage / 5 non-pivot tuples.  (Non-leaf pages cannot
395 		 * contain non-pivot tuples.  That's okay because they generally make
396 		 * up no more than about 1% of all pages in the index.)
397 		 */
398 		total_pages = RelationGetNumberOfBlocks(rel);
399 		total_elems = Max(total_pages * (MaxIndexTuplesPerPage / 5),
400 						  (int64) state->rel->rd_rel->reltuples);
401 		/* Random seed relies on backend srandom() call to avoid repetition */
402 		seed = random();
403 		/* Create Bloom filter to fingerprint index */
404 		state->filter = bloom_create(total_elems, maintenance_work_mem, seed);
405 		state->heaptuplespresent = 0;
406 
407 		/*
408 		 * Register our own snapshot in !readonly case, rather than asking
409 		 * IndexBuildHeapScan() to do this for us later.  This needs to happen
410 		 * before index fingerprinting begins, so we can later be certain that
411 		 * index fingerprinting should have reached all tuples returned by
412 		 * IndexBuildHeapScan().
413 		 *
414 		 * In readonly case, we also check for problems with missing
415 		 * downlinks. A second Bloom filter is used for this.
416 		 */
417 		if (!state->readonly)
418 		{
419 			snapshot = RegisterSnapshot(GetTransactionSnapshot());
420 
421 			/*
422 			 * GetTransactionSnapshot() always acquires a new MVCC snapshot in
423 			 * READ COMMITTED mode.  A new snapshot is guaranteed to have all
424 			 * the entries it requires in the index.
425 			 *
426 			 * We must defend against the possibility that an old xact
427 			 * snapshot was returned at higher isolation levels when that
428 			 * snapshot is not safe for index scans of the target index.  This
429 			 * is possible when the snapshot sees tuples that are before the
430 			 * index's indcheckxmin horizon.  Throwing an error here should be
431 			 * very rare.  It doesn't seem worth using a secondary snapshot to
432 			 * avoid this.
433 			 */
434 			if (IsolationUsesXactSnapshot() && rel->rd_index->indcheckxmin &&
435 				!TransactionIdPrecedes(HeapTupleHeaderGetXmin(rel->rd_indextuple->t_data),
436 									   snapshot->xmin))
437 				ereport(ERROR,
438 						(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
439 						 errmsg("index \"%s\" cannot be verified using transaction snapshot",
440 								RelationGetRelationName(rel))));
441 		}
442 		else
443 		{
444 			/*
445 			 * Extra readonly downlink check.
446 			 *
447 			 * In readonly case, we know that there cannot be a concurrent
448 			 * page split or a concurrent page deletion, which gives us the
449 			 * opportunity to verify that every non-ignorable page had a
450 			 * downlink one level up.  We must be tolerant of interrupted page
451 			 * splits and page deletions, though.  This is taken care of in
452 			 * bt_downlink_missing_check().
453 			 */
454 			state->downlinkfilter = bloom_create(total_pages, work_mem, seed);
455 		}
456 	}
457 
458 	/* Create context for page */
459 	state->targetcontext = AllocSetContextCreate(CurrentMemoryContext,
460 												 "amcheck context",
461 												 ALLOCSET_DEFAULT_SIZES);
462 	state->checkstrategy = GetAccessStrategy(BAS_BULKREAD);
463 
464 	/* Get true root block from meta-page */
465 	metapage = palloc_btree_page(state, BTREE_METAPAGE);
466 	metad = BTPageGetMeta(metapage);
467 
468 	/*
469 	 * Certain deletion patterns can result in "skinny" B-Tree indexes, where
470 	 * the fast root and true root differ.
471 	 *
472 	 * Start from the true root, not the fast root, unlike conventional index
473 	 * scans.  This approach is more thorough, and removes the risk of
474 	 * following a stale fast root from the meta page.
475 	 */
476 	if (metad->btm_fastroot != metad->btm_root)
477 		ereport(DEBUG1,
478 				(errcode(ERRCODE_NO_DATA),
479 				 errmsg("harmless fast root mismatch in index %s",
480 						RelationGetRelationName(rel)),
481 				 errdetail_internal("Fast root block %u (level %u) differs from true root block %u (level %u).",
482 									metad->btm_fastroot, metad->btm_fastlevel,
483 									metad->btm_root, metad->btm_level)));
484 
485 	/*
486 	 * Starting at the root, verify every level.  Move left to right, top to
487 	 * bottom.  Note that there may be no pages other than the meta page (meta
488 	 * page can indicate that root is P_NONE when the index is totally empty).
489 	 */
490 	previouslevel = InvalidBtreeLevel;
491 	current.level = metad->btm_level;
492 	current.leftmost = metad->btm_root;
493 	current.istruerootlevel = true;
494 	while (current.leftmost != P_NONE)
495 	{
496 		/*
497 		 * Leftmost page on level cannot be right half of incomplete split.
498 		 * This can go stale immediately in !readonly case.
499 		 */
500 		state->rightsplit = false;
501 
502 		/*
503 		 * Verify this level, and get left most page for next level down, if
504 		 * not at leaf level
505 		 */
506 		current = bt_check_level_from_leftmost(state, current);
507 
508 		if (current.leftmost == InvalidBlockNumber)
509 			ereport(ERROR,
510 					(errcode(ERRCODE_INDEX_CORRUPTED),
511 					 errmsg("index \"%s\" has no valid pages on level below %u or first level",
512 							RelationGetRelationName(rel), previouslevel)));
513 
514 		previouslevel = current.level;
515 	}
516 
517 	/*
518 	 * * Check whether heap contains unindexed/malformed tuples *
519 	 */
520 	if (state->heapallindexed)
521 	{
522 		IndexInfo  *indexinfo = BuildIndexInfo(state->rel);
523 		HeapScanDesc scan;
524 
525 		/* Report on extra downlink checks performed in readonly case */
526 		if (state->readonly)
527 		{
528 			ereport(DEBUG1,
529 					(errmsg_internal("finished verifying presence of downlink blocks within index \"%s\" with bitset %.2f%% set",
530 									 RelationGetRelationName(rel),
531 									 100.0 * bloom_prop_bits_set(state->downlinkfilter))));
532 			bloom_free(state->downlinkfilter);
533 		}
534 
535 		/*
536 		 * Create our own scan for IndexBuildHeapScan(), rather than getting
537 		 * it to do so for us.  This is required so that we can actually use
538 		 * the MVCC snapshot registered earlier in !readonly case.
539 		 *
540 		 * Note that IndexBuildHeapScan() calls heap_endscan() for us.
541 		 */
542 		scan = heap_beginscan_strat(state->heaprel, /* relation */
543 									snapshot,	/* snapshot */
544 									0,	/* number of keys */
545 									NULL,	/* scan key */
546 									true,	/* buffer access strategy OK */
547 									true);	/* syncscan OK? */
548 
549 		/*
550 		 * Scan will behave as the first scan of a CREATE INDEX CONCURRENTLY
551 		 * behaves in !readonly case.
552 		 *
553 		 * It's okay that we don't actually use the same lock strength for the
554 		 * heap relation as any other ii_Concurrent caller would in !readonly
555 		 * case.  We have no reason to care about a concurrent VACUUM
556 		 * operation, since there isn't going to be a second scan of the heap
557 		 * that needs to be sure that there was no concurrent recycling of
558 		 * TIDs.
559 		 */
560 		indexinfo->ii_Concurrent = !state->readonly;
561 
562 		/*
563 		 * Don't wait for uncommitted tuple xact commit/abort when index is a
564 		 * unique index on a catalog (or an index used by an exclusion
565 		 * constraint).  This could otherwise happen in the readonly case.
566 		 */
567 		indexinfo->ii_Unique = false;
568 		indexinfo->ii_ExclusionOps = NULL;
569 		indexinfo->ii_ExclusionProcs = NULL;
570 		indexinfo->ii_ExclusionStrats = NULL;
571 
572 		elog(DEBUG1, "verifying that tuples from index \"%s\" are present in \"%s\"",
573 			 RelationGetRelationName(state->rel),
574 			 RelationGetRelationName(state->heaprel));
575 
576 		IndexBuildHeapScan(state->heaprel, state->rel, indexinfo, true,
577 						   bt_tuple_present_callback, (void *) state, scan);
578 
579 		ereport(DEBUG1,
580 				(errmsg_internal("finished verifying presence of " INT64_FORMAT " tuples from table \"%s\" with bitset %.2f%% set",
581 								 state->heaptuplespresent, RelationGetRelationName(heaprel),
582 								 100.0 * bloom_prop_bits_set(state->filter))));
583 
584 		if (snapshot != SnapshotAny)
585 			UnregisterSnapshot(snapshot);
586 
587 		bloom_free(state->filter);
588 	}
589 
590 	/* Be tidy: */
591 	MemoryContextDelete(state->targetcontext);
592 }
593 
594 /*
595  * Given a left-most block at some level, move right, verifying each page
596  * individually (with more verification across pages for "readonly"
597  * callers).  Caller should pass the true root page as the leftmost initially,
598  * working their way down by passing what is returned for the last call here
599  * until level 0 (leaf page level) was reached.
600  *
601  * Returns state for next call, if any.  This includes left-most block number
602  * one level lower that should be passed on next level/call, which is set to
603  * P_NONE on last call here (when leaf level is verified).  Level numbers
604  * follow the nbtree convention: higher levels have higher numbers, because new
605  * levels are added only due to a root page split.  Note that prior to the
606  * first root page split, the root is also a leaf page, so there is always a
607  * level 0 (leaf level), and it's always the last level processed.
608  *
609  * Note on memory management:  State's per-page context is reset here, between
610  * each call to bt_target_page_check().
611  */
612 static BtreeLevel
613 bt_check_level_from_leftmost(BtreeCheckState *state, BtreeLevel level)
614 {
615 	/* State to establish early, concerning entire level */
616 	BTPageOpaque opaque;
617 	MemoryContext oldcontext;
618 	BtreeLevel	nextleveldown;
619 
620 	/* Variables for iterating across level using right links */
621 	BlockNumber leftcurrent = P_NONE;
622 	BlockNumber current = level.leftmost;
623 
624 	/* Initialize return state */
625 	nextleveldown.leftmost = InvalidBlockNumber;
626 	nextleveldown.level = InvalidBtreeLevel;
627 	nextleveldown.istruerootlevel = false;
628 
629 	/* Use page-level context for duration of this call */
630 	oldcontext = MemoryContextSwitchTo(state->targetcontext);
631 
632 	elog(DEBUG2, "verifying level %u%s", level.level,
633 		 level.istruerootlevel ?
634 		 " (true root level)" : level.level == 0 ? " (leaf level)" : "");
635 
636 	do
637 	{
638 		/* Don't rely on CHECK_FOR_INTERRUPTS() calls at lower level */
639 		CHECK_FOR_INTERRUPTS();
640 
641 		/* Initialize state for this iteration */
642 		state->targetblock = current;
643 		state->target = palloc_btree_page(state, state->targetblock);
644 		state->targetlsn = PageGetLSN(state->target);
645 
646 		opaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
647 
648 		if (P_IGNORE(opaque))
649 		{
650 			/*
651 			 * Since there cannot be a concurrent VACUUM operation in readonly
652 			 * mode, and since a page has no links within other pages
653 			 * (siblings and parent) once it is marked fully deleted, it
654 			 * should be impossible to land on a fully deleted page in
655 			 * readonly mode. See bt_downlink_check() for further details.
656 			 *
657 			 * The bt_downlink_check() P_ISDELETED() check is repeated here so
658 			 * that pages that are only reachable through sibling links get
659 			 * checked.
660 			 */
661 			if (state->readonly && P_ISDELETED(opaque))
662 				ereport(ERROR,
663 						(errcode(ERRCODE_INDEX_CORRUPTED),
664 						 errmsg("downlink or sibling link points to deleted block in index \"%s\"",
665 								RelationGetRelationName(state->rel)),
666 						 errdetail_internal("Block=%u left block=%u left link from block=%u.",
667 											current, leftcurrent, opaque->btpo_prev)));
668 
669 			if (P_RIGHTMOST(opaque))
670 				ereport(ERROR,
671 						(errcode(ERRCODE_INDEX_CORRUPTED),
672 						 errmsg("block %u fell off the end of index \"%s\"",
673 								current, RelationGetRelationName(state->rel))));
674 			else
675 				ereport(DEBUG1,
676 						(errcode(ERRCODE_NO_DATA),
677 						 errmsg("block %u of index \"%s\" ignored",
678 								current, RelationGetRelationName(state->rel))));
679 			goto nextpage;
680 		}
681 		else if (nextleveldown.leftmost == InvalidBlockNumber)
682 		{
683 			/*
684 			 * A concurrent page split could make the caller supplied leftmost
685 			 * block no longer contain the leftmost page, or no longer be the
686 			 * true root, but where that isn't possible due to heavyweight
687 			 * locking, check that the first valid page meets caller's
688 			 * expectations.
689 			 */
690 			if (state->readonly)
691 			{
692 				if (!P_LEFTMOST(opaque))
693 					ereport(ERROR,
694 							(errcode(ERRCODE_INDEX_CORRUPTED),
695 							 errmsg("block %u is not leftmost in index \"%s\"",
696 									current, RelationGetRelationName(state->rel))));
697 
698 				if (level.istruerootlevel && !P_ISROOT(opaque))
699 					ereport(ERROR,
700 							(errcode(ERRCODE_INDEX_CORRUPTED),
701 							 errmsg("block %u is not true root in index \"%s\"",
702 									current, RelationGetRelationName(state->rel))));
703 			}
704 
705 			/*
706 			 * Before beginning any non-trivial examination of level, prepare
707 			 * state for next bt_check_level_from_leftmost() invocation for
708 			 * the next level for the next level down (if any).
709 			 *
710 			 * There should be at least one non-ignorable page per level,
711 			 * unless this is the leaf level, which is assumed by caller to be
712 			 * final level.
713 			 */
714 			if (!P_ISLEAF(opaque))
715 			{
716 				IndexTuple	itup;
717 				ItemId		itemid;
718 
719 				/* Internal page -- downlink gets leftmost on next level */
720 				itemid = PageGetItemId(state->target, P_FIRSTDATAKEY(opaque));
721 				itup = (IndexTuple) PageGetItem(state->target, itemid);
722 				nextleveldown.leftmost = BTreeInnerTupleGetDownLink(itup);
723 				nextleveldown.level = opaque->btpo.level - 1;
724 			}
725 			else
726 			{
727 				/*
728 				 * Leaf page -- final level caller must process.
729 				 *
730 				 * Note that this could also be the root page, if there has
731 				 * been no root page split yet.
732 				 */
733 				nextleveldown.leftmost = P_NONE;
734 				nextleveldown.level = InvalidBtreeLevel;
735 			}
736 
737 			/*
738 			 * Finished setting up state for this call/level.  Control will
739 			 * never end up back here in any future loop iteration for this
740 			 * level.
741 			 */
742 		}
743 
744 		/*
745 		 * readonly mode can only ever land on live pages and half-dead pages,
746 		 * so sibling pointers should always be in mutual agreement
747 		 */
748 		if (state->readonly && opaque->btpo_prev != leftcurrent)
749 			ereport(ERROR,
750 					(errcode(ERRCODE_INDEX_CORRUPTED),
751 					 errmsg("left link/right link pair in index \"%s\" not in agreement",
752 							RelationGetRelationName(state->rel)),
753 					 errdetail_internal("Block=%u left block=%u left link from block=%u.",
754 										current, leftcurrent, opaque->btpo_prev)));
755 
756 		/* Check level, which must be valid for non-ignorable page */
757 		if (level.level != opaque->btpo.level)
758 			ereport(ERROR,
759 					(errcode(ERRCODE_INDEX_CORRUPTED),
760 					 errmsg("leftmost down link for level points to block in index \"%s\" whose level is not one level down",
761 							RelationGetRelationName(state->rel)),
762 					 errdetail_internal("Block pointed to=%u expected level=%u level in pointed to block=%u.",
763 										current, level.level, opaque->btpo.level)));
764 
765 		/* Verify invariants for page */
766 		bt_target_page_check(state);
767 
768 nextpage:
769 
770 		/* Try to detect circular links */
771 		if (current == leftcurrent || current == opaque->btpo_prev)
772 			ereport(ERROR,
773 					(errcode(ERRCODE_INDEX_CORRUPTED),
774 					 errmsg("circular link chain found in block %u of index \"%s\"",
775 							current, RelationGetRelationName(state->rel))));
776 
777 		/*
778 		 * Record if page that is about to become target is the right half of
779 		 * an incomplete page split.  This can go stale immediately in
780 		 * !readonly case.
781 		 */
782 		state->rightsplit = P_INCOMPLETE_SPLIT(opaque);
783 
784 		leftcurrent = current;
785 		current = opaque->btpo_next;
786 
787 		/* Free page and associated memory for this iteration */
788 		MemoryContextReset(state->targetcontext);
789 	}
790 	while (current != P_NONE);
791 
792 	/* Don't change context for caller */
793 	MemoryContextSwitchTo(oldcontext);
794 
795 	return nextleveldown;
796 }
797 
798 /*
799  * Function performs the following checks on target page, or pages ancillary to
800  * target page:
801  *
802  * - That every "real" data item is less than or equal to the high key, which
803  *	 is an upper bound on the items on the pages (where there is a high key at
804  *	 all -- pages that are rightmost lack one).
805  *
806  * - That within the page, every "real" item is less than or equal to the item
807  *	 immediately to its right, if any (i.e., that the items are in order within
808  *	 the page, so that the binary searches performed by index scans are sane).
809  *
810  * - That the last item stored on the page is less than or equal to the first
811  *	 "real" data item on the page to the right (if such a first item is
812  *	 available).
813  *
814  * - That tuples report that they have the expected number of attributes.
815  *	 INCLUDE index pivot tuples should not contain non-key attributes.
816  *
817  * Furthermore, when state passed shows ShareLock held, function also checks:
818  *
819  * - That all child pages respect downlinks lower bound.
820  *
821  * - That downlink to block was encountered in parent where that's expected.
822  *   (Limited to heapallindexed readonly callers.)
823  *
824  * This is also where heapallindexed callers use their Bloom filter to
825  * fingerprint IndexTuples for later IndexBuildHeapScan() verification.
826  *
827  * Note:  Memory allocated in this routine is expected to be released by caller
828  * resetting state->targetcontext.
829  */
830 static void
831 bt_target_page_check(BtreeCheckState *state)
832 {
833 	OffsetNumber offset;
834 	OffsetNumber max;
835 	BTPageOpaque topaque;
836 
837 	topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
838 	max = PageGetMaxOffsetNumber(state->target);
839 
840 	elog(DEBUG2, "verifying %u items on %s block %u", max,
841 		 P_ISLEAF(topaque) ? "leaf" : "internal", state->targetblock);
842 
843 	/*
844 	 * Check the number of attributes in high key. Note, rightmost page
845 	 * doesn't contain a high key, so nothing to check
846 	 */
847 	if (!P_RIGHTMOST(topaque) &&
848 		!_bt_check_natts(state->rel, state->target, P_HIKEY))
849 	{
850 		ItemId		itemid;
851 		IndexTuple	itup;
852 
853 		itemid = PageGetItemId(state->target, P_HIKEY);
854 		itup = (IndexTuple) PageGetItem(state->target, itemid);
855 
856 		ereport(ERROR,
857 				(errcode(ERRCODE_INDEX_CORRUPTED),
858 				 errmsg("wrong number of high key index tuple attributes in index \"%s\"",
859 						RelationGetRelationName(state->rel)),
860 				 errdetail_internal("Index block=%u natts=%u block type=%s page lsn=%X/%X.",
861 									state->targetblock,
862 									BTreeTupleGetNAtts(itup, state->rel),
863 									P_ISLEAF(topaque) ? "heap" : "index",
864 									(uint32) (state->targetlsn >> 32),
865 									(uint32) state->targetlsn)));
866 	}
867 
868 	/*
869 	 * Loop over page items, starting from first non-highkey item, not high
870 	 * key (if any).  Most tests are not performed for the "negative infinity"
871 	 * real item (if any).
872 	 */
873 	for (offset = P_FIRSTDATAKEY(topaque);
874 		 offset <= max;
875 		 offset = OffsetNumberNext(offset))
876 	{
877 		ItemId		itemid;
878 		IndexTuple	itup;
879 		ScanKey		skey;
880 		size_t		tupsize;
881 
882 		CHECK_FOR_INTERRUPTS();
883 
884 		itemid = PageGetItemId(state->target, offset);
885 		itup = (IndexTuple) PageGetItem(state->target, itemid);
886 		tupsize = IndexTupleSize(itup);
887 
888 		/*
889 		 * lp_len should match the IndexTuple reported length exactly, since
890 		 * lp_len is completely redundant in indexes, and both sources of
891 		 * tuple length are MAXALIGN()'d.  nbtree does not use lp_len all that
892 		 * frequently, and is surprisingly tolerant of corrupt lp_len fields.
893 		 */
894 		if (tupsize != ItemIdGetLength(itemid))
895 			ereport(ERROR,
896 					(errcode(ERRCODE_INDEX_CORRUPTED),
897 					 errmsg("index tuple size does not equal lp_len in index \"%s\"",
898 							RelationGetRelationName(state->rel)),
899 					 errdetail_internal("Index tid=(%u,%u) tuple size=%zu lp_len=%u page lsn=%X/%X.",
900 										state->targetblock, offset,
901 										tupsize, ItemIdGetLength(itemid),
902 										(uint32) (state->targetlsn >> 32),
903 										(uint32) state->targetlsn),
904 					 errhint("This could be a torn page problem.")));
905 
906 		/* Check the number of index tuple attributes */
907 		if (!_bt_check_natts(state->rel, state->target, offset))
908 		{
909 			char	   *itid,
910 					   *htid;
911 
912 			itid = psprintf("(%u,%u)", state->targetblock, offset);
913 			htid = psprintf("(%u,%u)",
914 							ItemPointerGetBlockNumberNoCheck(&(itup->t_tid)),
915 							ItemPointerGetOffsetNumberNoCheck(&(itup->t_tid)));
916 
917 			ereport(ERROR,
918 					(errcode(ERRCODE_INDEX_CORRUPTED),
919 					 errmsg("wrong number of index tuple attributes in index \"%s\"",
920 							RelationGetRelationName(state->rel)),
921 					 errdetail_internal("Index tid=%s natts=%u points to %s tid=%s page lsn=%X/%X.",
922 										itid,
923 										BTreeTupleGetNAtts(itup, state->rel),
924 										P_ISLEAF(topaque) ? "heap" : "index",
925 										htid,
926 										(uint32) (state->targetlsn >> 32),
927 										(uint32) state->targetlsn)));
928 		}
929 
930 		/* Fingerprint downlink blocks in heapallindexed + readonly case */
931 		if (state->heapallindexed && state->readonly && !P_ISLEAF(topaque))
932 		{
933 			BlockNumber childblock = BTreeInnerTupleGetDownLink(itup);
934 
935 			bloom_add_element(state->downlinkfilter,
936 							  (unsigned char *) &childblock,
937 							  sizeof(BlockNumber));
938 		}
939 
940 		/*
941 		 * Don't try to generate scankey using "negative infinity" item on
942 		 * internal pages. They are always truncated to zero attributes.
943 		 */
944 		if (offset_is_negative_infinity(topaque, offset))
945 			continue;
946 
947 		/* Build insertion scankey for current page offset */
948 		skey = _bt_mkscankey(state->rel, itup);
949 
950 		/* Fingerprint leaf page tuples (those that point to the heap) */
951 		if (state->heapallindexed && P_ISLEAF(topaque) && !ItemIdIsDead(itemid))
952 		{
953 			IndexTuple		norm;
954 
955 			norm = bt_normalize_tuple(state, itup);
956 			bloom_add_element(state->filter, (unsigned char *) norm,
957 							  IndexTupleSize(norm));
958 			/* Be tidy */
959 			if (norm != itup)
960 				pfree(norm);
961 		}
962 
963 		/*
964 		 * * High key check *
965 		 *
966 		 * If there is a high key (if this is not the rightmost page on its
967 		 * entire level), check that high key actually is upper bound on all
968 		 * page items.
969 		 *
970 		 * We prefer to check all items against high key rather than checking
971 		 * just the last and trusting that the operator class obeys the
972 		 * transitive law (which implies that all previous items also
973 		 * respected the high key invariant if they pass the item order
974 		 * check).
975 		 *
976 		 * Ideally, we'd compare every item in the index against every other
977 		 * item in the index, and not trust opclass obedience of the
978 		 * transitive law to bridge the gap between children and their
979 		 * grandparents (as well as great-grandparents, and so on).  We don't
980 		 * go to those lengths because that would be prohibitively expensive,
981 		 * and probably not markedly more effective in practice.
982 		 */
983 		if (!P_RIGHTMOST(topaque) &&
984 			!invariant_leq_offset(state, skey, P_HIKEY))
985 		{
986 			char	   *itid,
987 					   *htid;
988 
989 			itid = psprintf("(%u,%u)", state->targetblock, offset);
990 			htid = psprintf("(%u,%u)",
991 							ItemPointerGetBlockNumberNoCheck(&(itup->t_tid)),
992 							ItemPointerGetOffsetNumberNoCheck(&(itup->t_tid)));
993 
994 			ereport(ERROR,
995 					(errcode(ERRCODE_INDEX_CORRUPTED),
996 					 errmsg("high key invariant violated for index \"%s\"",
997 							RelationGetRelationName(state->rel)),
998 					 errdetail_internal("Index tid=%s points to %s tid=%s page lsn=%X/%X.",
999 										itid,
1000 										P_ISLEAF(topaque) ? "heap" : "index",
1001 										htid,
1002 										(uint32) (state->targetlsn >> 32),
1003 										(uint32) state->targetlsn)));
1004 		}
1005 
1006 		/*
1007 		 * * Item order check *
1008 		 *
1009 		 * Check that items are stored on page in logical order, by checking
1010 		 * current item is less than or equal to next item (if any).
1011 		 */
1012 		if (OffsetNumberNext(offset) <= max &&
1013 			!invariant_leq_offset(state, skey,
1014 								  OffsetNumberNext(offset)))
1015 		{
1016 			char	   *itid,
1017 					   *htid,
1018 					   *nitid,
1019 					   *nhtid;
1020 
1021 			itid = psprintf("(%u,%u)", state->targetblock, offset);
1022 			htid = psprintf("(%u,%u)",
1023 							ItemPointerGetBlockNumberNoCheck(&(itup->t_tid)),
1024 							ItemPointerGetOffsetNumberNoCheck(&(itup->t_tid)));
1025 			nitid = psprintf("(%u,%u)", state->targetblock,
1026 							 OffsetNumberNext(offset));
1027 
1028 			/* Reuse itup to get pointed-to heap location of second item */
1029 			itemid = PageGetItemId(state->target, OffsetNumberNext(offset));
1030 			itup = (IndexTuple) PageGetItem(state->target, itemid);
1031 			nhtid = psprintf("(%u,%u)",
1032 							 ItemPointerGetBlockNumberNoCheck(&(itup->t_tid)),
1033 							 ItemPointerGetOffsetNumberNoCheck(&(itup->t_tid)));
1034 
1035 			ereport(ERROR,
1036 					(errcode(ERRCODE_INDEX_CORRUPTED),
1037 					 errmsg("item order invariant violated for index \"%s\"",
1038 							RelationGetRelationName(state->rel)),
1039 					 errdetail_internal("Lower index tid=%s (points to %s tid=%s) "
1040 										"higher index tid=%s (points to %s tid=%s) "
1041 										"page lsn=%X/%X.",
1042 										itid,
1043 										P_ISLEAF(topaque) ? "heap" : "index",
1044 										htid,
1045 										nitid,
1046 										P_ISLEAF(topaque) ? "heap" : "index",
1047 										nhtid,
1048 										(uint32) (state->targetlsn >> 32),
1049 										(uint32) state->targetlsn)));
1050 		}
1051 
1052 		/*
1053 		 * * Last item check *
1054 		 *
1055 		 * Check last item against next/right page's first data item's when
1056 		 * last item on page is reached.  This additional check will detect
1057 		 * transposed pages iff the supposed right sibling page happens to
1058 		 * belong before target in the key space.  (Otherwise, a subsequent
1059 		 * heap verification will probably detect the problem.)
1060 		 *
1061 		 * This check is similar to the item order check that will have
1062 		 * already been performed for every other "real" item on target page
1063 		 * when last item is checked.  The difference is that the next item
1064 		 * (the item that is compared to target's last item) needs to come
1065 		 * from the next/sibling page.  There may not be such an item
1066 		 * available from sibling for various reasons, though (e.g., target is
1067 		 * the rightmost page on level).
1068 		 */
1069 		else if (offset == max)
1070 		{
1071 			ScanKey		rightkey;
1072 
1073 			/* Get item in next/right page */
1074 			rightkey = bt_right_page_check_scankey(state);
1075 
1076 			if (rightkey &&
1077 				!invariant_geq_offset(state, rightkey, max))
1078 			{
1079 				/*
1080 				 * As explained at length in bt_right_page_check_scankey(),
1081 				 * there is a known !readonly race that could account for
1082 				 * apparent violation of invariant, which we must check for
1083 				 * before actually proceeding with raising error.  Our canary
1084 				 * condition is that target page was deleted.
1085 				 */
1086 				if (!state->readonly)
1087 				{
1088 					/* Get fresh copy of target page */
1089 					state->target = palloc_btree_page(state, state->targetblock);
1090 					/* Note that we deliberately do not update target LSN */
1091 					topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
1092 
1093 					/*
1094 					 * All !readonly checks now performed; just return
1095 					 */
1096 					if (P_IGNORE(topaque))
1097 						return;
1098 				}
1099 
1100 				ereport(ERROR,
1101 						(errcode(ERRCODE_INDEX_CORRUPTED),
1102 						 errmsg("cross page item order invariant violated for index \"%s\"",
1103 								RelationGetRelationName(state->rel)),
1104 						 errdetail_internal("Last item on page tid=(%u,%u) page lsn=%X/%X.",
1105 											state->targetblock, offset,
1106 											(uint32) (state->targetlsn >> 32),
1107 											(uint32) state->targetlsn)));
1108 			}
1109 		}
1110 
1111 		/*
1112 		 * * Downlink check *
1113 		 *
1114 		 * Additional check of child items iff this is an internal page and
1115 		 * caller holds a ShareLock.  This happens for every downlink (item)
1116 		 * in target excluding the negative-infinity downlink (again, this is
1117 		 * because it has no useful value to compare).
1118 		 */
1119 		if (!P_ISLEAF(topaque) && state->readonly)
1120 		{
1121 			BlockNumber childblock = BTreeInnerTupleGetDownLink(itup);
1122 
1123 			bt_downlink_check(state, childblock, skey);
1124 		}
1125 	}
1126 
1127 	/*
1128 	 * * Check if page has a downlink in parent *
1129 	 *
1130 	 * This can only be checked in heapallindexed + readonly case.
1131 	 */
1132 	if (state->heapallindexed && state->readonly)
1133 		bt_downlink_missing_check(state);
1134 }
1135 
1136 /*
1137  * Return a scankey for an item on page to right of current target (or the
1138  * first non-ignorable page), sufficient to check ordering invariant on last
1139  * item in current target page.  Returned scankey relies on local memory
1140  * allocated for the child page, which caller cannot pfree().  Caller's memory
1141  * context should be reset between calls here.
1142  *
1143  * This is the first data item, and so all adjacent items are checked against
1144  * their immediate sibling item (which may be on a sibling page, or even a
1145  * "cousin" page at parent boundaries where target's rightlink points to page
1146  * with different parent page).  If no such valid item is available, return
1147  * NULL instead.
1148  *
1149  * Note that !readonly callers must reverify that target page has not
1150  * been concurrently deleted.
1151  */
1152 static ScanKey
1153 bt_right_page_check_scankey(BtreeCheckState *state)
1154 {
1155 	BTPageOpaque opaque;
1156 	ItemId		rightitem;
1157 	BlockNumber targetnext;
1158 	Page		rightpage;
1159 	OffsetNumber nline;
1160 
1161 	/* Determine target's next block number */
1162 	opaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
1163 
1164 	/* If target is already rightmost, no right sibling; nothing to do here */
1165 	if (P_RIGHTMOST(opaque))
1166 		return NULL;
1167 
1168 	/*
1169 	 * General notes on concurrent page splits and page deletion:
1170 	 *
1171 	 * Routines like _bt_search() don't require *any* page split interlock
1172 	 * when descending the tree, including something very light like a buffer
1173 	 * pin. That's why it's okay that we don't either.  This avoidance of any
1174 	 * need to "couple" buffer locks is the raison d' etre of the Lehman & Yao
1175 	 * algorithm, in fact.
1176 	 *
1177 	 * That leaves deletion.  A deleted page won't actually be recycled by
1178 	 * VACUUM early enough for us to fail to at least follow its right link
1179 	 * (or left link, or downlink) and find its sibling, because recycling
1180 	 * does not occur until no possible index scan could land on the page.
1181 	 * Index scans can follow links with nothing more than their snapshot as
1182 	 * an interlock and be sure of at least that much.  (See page
1183 	 * recycling/RecentGlobalXmin notes in nbtree README.)
1184 	 *
1185 	 * Furthermore, it's okay if we follow a rightlink and find a half-dead or
1186 	 * dead (ignorable) page one or more times.  There will either be a
1187 	 * further right link to follow that leads to a live page before too long
1188 	 * (before passing by parent's rightmost child), or we will find the end
1189 	 * of the entire level instead (possible when parent page is itself the
1190 	 * rightmost on its level).
1191 	 */
1192 	targetnext = opaque->btpo_next;
1193 	for (;;)
1194 	{
1195 		CHECK_FOR_INTERRUPTS();
1196 
1197 		rightpage = palloc_btree_page(state, targetnext);
1198 		opaque = (BTPageOpaque) PageGetSpecialPointer(rightpage);
1199 
1200 		if (!P_IGNORE(opaque) || P_RIGHTMOST(opaque))
1201 			break;
1202 
1203 		/* We landed on a deleted page, so step right to find a live page */
1204 		targetnext = opaque->btpo_next;
1205 		ereport(DEBUG1,
1206 				(errcode(ERRCODE_NO_DATA),
1207 				 errmsg("level %u leftmost page of index \"%s\" was found deleted or half dead",
1208 						opaque->btpo.level, RelationGetRelationName(state->rel)),
1209 				 errdetail_internal("Deleted page found when building scankey from right sibling.")));
1210 
1211 		/* Be slightly more pro-active in freeing this memory, just in case */
1212 		pfree(rightpage);
1213 	}
1214 
1215 	/*
1216 	 * No ShareLock held case -- why it's safe to proceed.
1217 	 *
1218 	 * Problem:
1219 	 *
1220 	 * We must avoid false positive reports of corruption when caller treats
1221 	 * item returned here as an upper bound on target's last item.  In
1222 	 * general, false positives are disallowed.  Avoiding them here when
1223 	 * caller is !readonly is subtle.
1224 	 *
1225 	 * A concurrent page deletion by VACUUM of the target page can result in
1226 	 * the insertion of items on to this right sibling page that would
1227 	 * previously have been inserted on our target page.  There might have
1228 	 * been insertions that followed the target's downlink after it was made
1229 	 * to point to right sibling instead of target by page deletion's first
1230 	 * phase. The inserters insert items that would belong on target page.
1231 	 * This race is very tight, but it's possible.  This is our only problem.
1232 	 *
1233 	 * Non-problems:
1234 	 *
1235 	 * We are not hindered by a concurrent page split of the target; we'll
1236 	 * never land on the second half of the page anyway.  A concurrent split
1237 	 * of the right page will also not matter, because the first data item
1238 	 * remains the same within the left half, which we'll reliably land on. If
1239 	 * we had to skip over ignorable/deleted pages, it cannot matter because
1240 	 * their key space has already been atomically merged with the first
1241 	 * non-ignorable page we eventually find (doesn't matter whether the page
1242 	 * we eventually find is a true sibling or a cousin of target, which we go
1243 	 * into below).
1244 	 *
1245 	 * Solution:
1246 	 *
1247 	 * Caller knows that it should reverify that target is not ignorable
1248 	 * (half-dead or deleted) when cross-page sibling item comparison appears
1249 	 * to indicate corruption (invariant fails).  This detects the single race
1250 	 * condition that exists for caller.  This is correct because the
1251 	 * continued existence of target block as non-ignorable (not half-dead or
1252 	 * deleted) implies that target page was not merged into from the right by
1253 	 * deletion; the key space at or after target never moved left.  Target's
1254 	 * parent either has the same downlink to target as before, or a <=
1255 	 * downlink due to deletion at the left of target.  Target either has the
1256 	 * same highkey as before, or a highkey <= before when there is a page
1257 	 * split. (The rightmost concurrently-split-from-target-page page will
1258 	 * still have the same highkey as target was originally found to have,
1259 	 * which for our purposes is equivalent to target's highkey itself never
1260 	 * changing, since we reliably skip over
1261 	 * concurrently-split-from-target-page pages.)
1262 	 *
1263 	 * In simpler terms, we allow that the key space of the target may expand
1264 	 * left (the key space can move left on the left side of target only), but
1265 	 * the target key space cannot expand right and get ahead of us without
1266 	 * our detecting it.  The key space of the target cannot shrink, unless it
1267 	 * shrinks to zero due to the deletion of the original page, our canary
1268 	 * condition.  (To be very precise, we're a bit stricter than that because
1269 	 * it might just have been that the target page split and only the
1270 	 * original target page was deleted.  We can be more strict, just not more
1271 	 * lax.)
1272 	 *
1273 	 * Top level tree walk caller moves on to next page (makes it the new
1274 	 * target) following recovery from this race.  (cf.  The rationale for
1275 	 * child/downlink verification needing a ShareLock within
1276 	 * bt_downlink_check(), where page deletion is also the main source of
1277 	 * trouble.)
1278 	 *
1279 	 * Note that it doesn't matter if right sibling page here is actually a
1280 	 * cousin page, because in order for the key space to be readjusted in a
1281 	 * way that causes us issues in next level up (guiding problematic
1282 	 * concurrent insertions to the cousin from the grandparent rather than to
1283 	 * the sibling from the parent), there'd have to be page deletion of
1284 	 * target's parent page (affecting target's parent's downlink in target's
1285 	 * grandparent page).  Internal page deletion only occurs when there are
1286 	 * no child pages (they were all fully deleted), and caller is checking
1287 	 * that the target's parent has at least one non-deleted (so
1288 	 * non-ignorable) child: the target page.  (Note that the first phase of
1289 	 * deletion atomically marks the page to be deleted half-dead/ignorable at
1290 	 * the same time downlink in its parent is removed, so caller will
1291 	 * definitely not fail to detect that this happened.)
1292 	 *
1293 	 * This trick is inspired by the method backward scans use for dealing
1294 	 * with concurrent page splits; concurrent page deletion is a problem that
1295 	 * similarly receives special consideration sometimes (it's possible that
1296 	 * the backwards scan will re-read its "original" block after failing to
1297 	 * find a right-link to it, having already moved in the opposite direction
1298 	 * (right/"forwards") a few times to try to locate one).  Just like us,
1299 	 * that happens only to determine if there was a concurrent page deletion
1300 	 * of a reference page, and just like us if there was a page deletion of
1301 	 * that reference page it means we can move on from caring about the
1302 	 * reference page.  See the nbtree README for a full description of how
1303 	 * that works.
1304 	 */
1305 	nline = PageGetMaxOffsetNumber(rightpage);
1306 
1307 	/*
1308 	 * Get first data item, if any
1309 	 */
1310 	if (P_ISLEAF(opaque) && nline >= P_FIRSTDATAKEY(opaque))
1311 	{
1312 		/* Return first data item (if any) */
1313 		rightitem = PageGetItemId(rightpage, P_FIRSTDATAKEY(opaque));
1314 	}
1315 	else if (!P_ISLEAF(opaque) &&
1316 			 nline >= OffsetNumberNext(P_FIRSTDATAKEY(opaque)))
1317 	{
1318 		/*
1319 		 * Return first item after the internal page's "negative infinity"
1320 		 * item
1321 		 */
1322 		rightitem = PageGetItemId(rightpage,
1323 								  OffsetNumberNext(P_FIRSTDATAKEY(opaque)));
1324 	}
1325 	else
1326 	{
1327 		/*
1328 		 * No first item.  Page is probably empty leaf page, but it's also
1329 		 * possible that it's an internal page with only a negative infinity
1330 		 * item.
1331 		 */
1332 		ereport(DEBUG1,
1333 				(errcode(ERRCODE_NO_DATA),
1334 				 errmsg("%s block %u of index \"%s\" has no first data item",
1335 						P_ISLEAF(opaque) ? "leaf" : "internal", targetnext,
1336 						RelationGetRelationName(state->rel))));
1337 		return NULL;
1338 	}
1339 
1340 	/*
1341 	 * Return first real item scankey.  Note that this relies on right page
1342 	 * memory remaining allocated.
1343 	 */
1344 	return _bt_mkscankey(state->rel,
1345 						 (IndexTuple) PageGetItem(rightpage, rightitem));
1346 }
1347 
1348 /*
1349  * Checks one of target's downlink against its child page.
1350  *
1351  * Conceptually, the target page continues to be what is checked here.  The
1352  * target block is still blamed in the event of finding an invariant violation.
1353  * The downlink insertion into the target is probably where any problem raised
1354  * here arises, and there is no such thing as a parent link, so doing the
1355  * verification this way around is much more practical.
1356  */
1357 static void
1358 bt_downlink_check(BtreeCheckState *state, BlockNumber childblock,
1359 				  ScanKey targetkey)
1360 {
1361 	OffsetNumber offset;
1362 	OffsetNumber maxoffset;
1363 	Page		child;
1364 	BTPageOpaque copaque;
1365 
1366 	/*
1367 	 * Caller must have ShareLock on target relation, because of
1368 	 * considerations around page deletion by VACUUM.
1369 	 *
1370 	 * NB: In general, page deletion deletes the right sibling's downlink, not
1371 	 * the downlink of the page being deleted; the deleted page's downlink is
1372 	 * reused for its sibling.  The key space is thereby consolidated between
1373 	 * the deleted page and its right sibling.  (We cannot delete a parent
1374 	 * page's rightmost child unless it is the last child page, and we intend
1375 	 * to also delete the parent itself.)
1376 	 *
1377 	 * If this verification happened without a ShareLock, the following race
1378 	 * condition could cause false positives:
1379 	 *
1380 	 * In general, concurrent page deletion might occur, including deletion of
1381 	 * the left sibling of the child page that is examined here.  If such a
1382 	 * page deletion were to occur, closely followed by an insertion into the
1383 	 * newly expanded key space of the child, a window for the false positive
1384 	 * opens up: the stale parent/target downlink originally followed to get
1385 	 * to the child legitimately ceases to be a lower bound on all items in
1386 	 * the page, since the key space was concurrently expanded "left".
1387 	 * (Insertion followed the "new" downlink for the child, not our now-stale
1388 	 * downlink, which was concurrently physically removed in target/parent as
1389 	 * part of deletion's first phase.)
1390 	 *
1391 	 * Note that while the cross-page-same-level last item check uses a trick
1392 	 * that allows it to perform verification for !readonly callers, a similar
1393 	 * trick seems difficult here.  The trick that that other check uses is,
1394 	 * in essence, to lock down race conditions to those that occur due to
1395 	 * concurrent page deletion of the target; that's a race that can be
1396 	 * reliably detected before actually reporting corruption.
1397 	 *
1398 	 * On the other hand, we'd need to lock down race conditions involving
1399 	 * deletion of child's left page, for long enough to read the child page
1400 	 * into memory (in other words, a scheme with concurrently held buffer
1401 	 * locks on both child and left-of-child pages).  That's unacceptable for
1402 	 * amcheck functions on general principle, though.
1403 	 */
1404 	Assert(state->readonly);
1405 
1406 	/*
1407 	 * Verify child page has the downlink key from target page (its parent) as
1408 	 * a lower bound.
1409 	 *
1410 	 * Check all items, rather than checking just the first and trusting that
1411 	 * the operator class obeys the transitive law.
1412 	 */
1413 	child = palloc_btree_page(state, childblock);
1414 	copaque = (BTPageOpaque) PageGetSpecialPointer(child);
1415 	maxoffset = PageGetMaxOffsetNumber(child);
1416 
1417 	/*
1418 	 * Since there cannot be a concurrent VACUUM operation in readonly mode,
1419 	 * and since a page has no links within other pages (siblings and parent)
1420 	 * once it is marked fully deleted, it should be impossible to land on a
1421 	 * fully deleted page.
1422 	 *
1423 	 * It does not quite make sense to enforce that the page cannot even be
1424 	 * half-dead, despite the fact the downlink is modified at the same stage
1425 	 * that the child leaf page is marked half-dead.  That's incorrect because
1426 	 * there may occasionally be multiple downlinks from a chain of pages
1427 	 * undergoing deletion, where multiple successive calls are made to
1428 	 * _bt_unlink_halfdead_page() by VACUUM before it can finally safely mark
1429 	 * the leaf page as fully dead.  While _bt_mark_page_halfdead() usually
1430 	 * removes the downlink to the leaf page that is marked half-dead, that's
1431 	 * not guaranteed, so it's possible we'll land on a half-dead page with a
1432 	 * downlink due to an interrupted multi-level page deletion.
1433 	 *
1434 	 * We go ahead with our checks if the child page is half-dead.  It's safe
1435 	 * to do so because we do not test the child's high key, so it does not
1436 	 * matter that the original high key will have been replaced by a dummy
1437 	 * truncated high key within _bt_mark_page_halfdead().  All other page
1438 	 * items are left intact on a half-dead page, so there is still something
1439 	 * to test.
1440 	 */
1441 	if (P_ISDELETED(copaque))
1442 		ereport(ERROR,
1443 				(errcode(ERRCODE_INDEX_CORRUPTED),
1444 				 errmsg("downlink to deleted page found in index \"%s\"",
1445 						RelationGetRelationName(state->rel)),
1446 				 errdetail_internal("Parent block=%u child block=%u parent page lsn=%X/%X.",
1447 									state->targetblock, childblock,
1448 									(uint32) (state->targetlsn >> 32),
1449 									(uint32) state->targetlsn)));
1450 
1451 	for (offset = P_FIRSTDATAKEY(copaque);
1452 		 offset <= maxoffset;
1453 		 offset = OffsetNumberNext(offset))
1454 	{
1455 		/*
1456 		 * Skip comparison of target page key against "negative infinity"
1457 		 * item, if any.  Checking it would indicate that it's not an upper
1458 		 * bound, but that's only because of the hard-coding within
1459 		 * _bt_compare().
1460 		 */
1461 		if (offset_is_negative_infinity(copaque, offset))
1462 			continue;
1463 
1464 		if (!invariant_leq_nontarget_offset(state, child,
1465 											targetkey, offset))
1466 			ereport(ERROR,
1467 					(errcode(ERRCODE_INDEX_CORRUPTED),
1468 					 errmsg("down-link lower bound invariant violated for index \"%s\"",
1469 							RelationGetRelationName(state->rel)),
1470 					 errdetail_internal("Parent block=%u child index tid=(%u,%u) parent page lsn=%X/%X.",
1471 										state->targetblock, childblock, offset,
1472 										(uint32) (state->targetlsn >> 32),
1473 										(uint32) state->targetlsn)));
1474 	}
1475 
1476 	pfree(child);
1477 }
1478 
1479 /*
1480  * Checks if page is missing a downlink that it should have.
1481  *
1482  * A page that lacks a downlink/parent may indicate corruption.  However, we
1483  * must account for the fact that a missing downlink can occasionally be
1484  * encountered in a non-corrupt index.  This can be due to an interrupted page
1485  * split, or an interrupted multi-level page deletion (i.e. there was a hard
1486  * crash or an error during a page split, or while VACUUM was deleting a
1487  * multi-level chain of pages).
1488  *
1489  * Note that this can only be called in readonly mode, so there is no need to
1490  * be concerned about concurrent page splits or page deletions.
1491  */
1492 static void
1493 bt_downlink_missing_check(BtreeCheckState *state)
1494 {
1495 	BTPageOpaque topaque = (BTPageOpaque) PageGetSpecialPointer(state->target);
1496 	ItemId		itemid;
1497 	IndexTuple	itup;
1498 	Page		child;
1499 	BTPageOpaque copaque;
1500 	uint32		level;
1501 	BlockNumber childblk;
1502 
1503 	Assert(state->heapallindexed && state->readonly);
1504 	Assert(!P_IGNORE(topaque));
1505 
1506 	/* No next level up with downlinks to fingerprint from the true root */
1507 	if (P_ISROOT(topaque))
1508 		return;
1509 
1510 	/*
1511 	 * Incomplete (interrupted) page splits can account for the lack of a
1512 	 * downlink.  Some inserting transaction should eventually complete the
1513 	 * page split in passing, when it notices that the left sibling page is
1514 	 * P_INCOMPLETE_SPLIT().
1515 	 *
1516 	 * In general, VACUUM is not prepared for there to be no downlink to a
1517 	 * page that it deletes.  This is the main reason why the lack of a
1518 	 * downlink can be reported as corruption here.  It's not obvious that an
1519 	 * invalid missing downlink can result in wrong answers to queries,
1520 	 * though, since index scans that land on the child may end up
1521 	 * consistently moving right. The handling of concurrent page splits (and
1522 	 * page deletions) within _bt_moveright() cannot distinguish
1523 	 * inconsistencies that last for a moment from inconsistencies that are
1524 	 * permanent and irrecoverable.
1525 	 *
1526 	 * VACUUM isn't even prepared to delete pages that have no downlink due to
1527 	 * an incomplete page split, but it can detect and reason about that case
1528 	 * by design, so it shouldn't be taken to indicate corruption.  See
1529 	 * _bt_pagedel() for full details.
1530 	 */
1531 	if (state->rightsplit)
1532 	{
1533 		ereport(DEBUG1,
1534 				(errcode(ERRCODE_NO_DATA),
1535 				 errmsg("harmless interrupted page split detected in index %s",
1536 						RelationGetRelationName(state->rel)),
1537 				 errdetail_internal("Block=%u level=%u left sibling=%u page lsn=%X/%X.",
1538 									state->targetblock, topaque->btpo.level,
1539 									topaque->btpo_prev,
1540 									(uint32) (state->targetlsn >> 32),
1541 									(uint32) state->targetlsn)));
1542 		return;
1543 	}
1544 
1545 	/* Target's downlink is typically present in parent/fingerprinted */
1546 	if (!bloom_lacks_element(state->downlinkfilter,
1547 							 (unsigned char *) &state->targetblock,
1548 							 sizeof(BlockNumber)))
1549 		return;
1550 
1551 	/*
1552 	 * Target is probably the "top parent" of a multi-level page deletion.
1553 	 * We'll need to descend the subtree to make sure that descendant pages
1554 	 * are consistent with that, though.
1555 	 *
1556 	 * If the target page (which must be non-ignorable) is a leaf page, then
1557 	 * clearly it can't be the top parent.  The lack of a downlink is probably
1558 	 * a symptom of a broad problem that could just as easily cause
1559 	 * inconsistencies anywhere else.
1560 	 */
1561 	if (P_ISLEAF(topaque))
1562 		ereport(ERROR,
1563 				(errcode(ERRCODE_INDEX_CORRUPTED),
1564 				 errmsg("leaf index block lacks downlink in index \"%s\"",
1565 						RelationGetRelationName(state->rel)),
1566 				 errdetail_internal("Block=%u page lsn=%X/%X.",
1567 									state->targetblock,
1568 									(uint32) (state->targetlsn >> 32),
1569 									(uint32) state->targetlsn)));
1570 
1571 	/* Descend from the target page, which is an internal page */
1572 	elog(DEBUG1, "checking for interrupted multi-level deletion due to missing downlink in index \"%s\"",
1573 		 RelationGetRelationName(state->rel));
1574 
1575 	level = topaque->btpo.level;
1576 	itemid = PageGetItemId(state->target, P_FIRSTDATAKEY(topaque));
1577 	itup = (IndexTuple) PageGetItem(state->target, itemid);
1578 	childblk = BTreeInnerTupleGetDownLink(itup);
1579 	for (;;)
1580 	{
1581 		CHECK_FOR_INTERRUPTS();
1582 
1583 		child = palloc_btree_page(state, childblk);
1584 		copaque = (BTPageOpaque) PageGetSpecialPointer(child);
1585 
1586 		if (P_ISLEAF(copaque))
1587 			break;
1588 
1589 		/* Do an extra sanity check in passing on internal pages */
1590 		if (copaque->btpo.level != level - 1)
1591 			ereport(ERROR,
1592 					(errcode(ERRCODE_INDEX_CORRUPTED),
1593 					 errmsg_internal("downlink points to block in index \"%s\" whose level is not one level down",
1594 									 RelationGetRelationName(state->rel)),
1595 					 errdetail_internal("Top parent/target block=%u block pointed to=%u expected level=%u level in pointed to block=%u.",
1596 										state->targetblock, childblk,
1597 										level - 1, copaque->btpo.level)));
1598 
1599 		level = copaque->btpo.level;
1600 		itemid = PageGetItemId(child, P_FIRSTDATAKEY(copaque));
1601 		itup = (IndexTuple) PageGetItem(child, itemid);
1602 		childblk = BTreeInnerTupleGetDownLink(itup);
1603 		/* Be slightly more pro-active in freeing this memory, just in case */
1604 		pfree(child);
1605 	}
1606 
1607 	/*
1608 	 * Since there cannot be a concurrent VACUUM operation in readonly mode,
1609 	 * and since a page has no links within other pages (siblings and parent)
1610 	 * once it is marked fully deleted, it should be impossible to land on a
1611 	 * fully deleted page.  See bt_downlink_check() for further details.
1612 	 *
1613 	 * The bt_downlink_check() P_ISDELETED() check is repeated here because
1614 	 * bt_downlink_check() does not visit pages reachable through negative
1615 	 * infinity items.  Besides, bt_downlink_check() is unwilling to descend
1616 	 * multiple levels.  (The similar bt_downlink_check() P_ISDELETED() check
1617 	 * within bt_check_level_from_leftmost() won't reach the page either,
1618 	 * since the leaf's live siblings should have their sibling links updated
1619 	 * to bypass the deletion target page when it is marked fully dead.)
1620 	 *
1621 	 * If this error is raised, it might be due to a previous multi-level page
1622 	 * deletion that failed to realize that it wasn't yet safe to mark the
1623 	 * leaf page as fully dead.  A "dangling downlink" will still remain when
1624 	 * this happens.  The fact that the dangling downlink's page (the leaf's
1625 	 * parent/ancestor page) lacked a downlink is incidental.
1626 	 */
1627 	if (P_ISDELETED(copaque))
1628 		ereport(ERROR,
1629 				(errcode(ERRCODE_INDEX_CORRUPTED),
1630 				 errmsg_internal("downlink to deleted leaf page found in index \"%s\"",
1631 								 RelationGetRelationName(state->rel)),
1632 				 errdetail_internal("Top parent/target block=%u leaf block=%u top parent/target lsn=%X/%X.",
1633 									state->targetblock, childblk,
1634 									(uint32) (state->targetlsn >> 32),
1635 									(uint32) state->targetlsn)));
1636 
1637 	/*
1638 	 * Iff leaf page is half-dead, its high key top parent link should point
1639 	 * to what VACUUM considered to be the top parent page at the instant it
1640 	 * was interrupted.  Provided the high key link actually points to the
1641 	 * target page, the missing downlink we detected is consistent with there
1642 	 * having been an interrupted multi-level page deletion.  This means that
1643 	 * the subtree with the target page at its root (a page deletion chain) is
1644 	 * in a consistent state, enabling VACUUM to resume deleting the entire
1645 	 * chain the next time it encounters the half-dead leaf page.
1646 	 */
1647 	if (P_ISHALFDEAD(copaque) && !P_RIGHTMOST(copaque))
1648 	{
1649 		itemid = PageGetItemId(child, P_HIKEY);
1650 		itup = (IndexTuple) PageGetItem(child, itemid);
1651 		if (BTreeTupleGetTopParent(itup) == state->targetblock)
1652 			return;
1653 	}
1654 
1655 	ereport(ERROR,
1656 			(errcode(ERRCODE_INDEX_CORRUPTED),
1657 			 errmsg("internal index block lacks downlink in index \"%s\"",
1658 					RelationGetRelationName(state->rel)),
1659 			 errdetail_internal("Block=%u level=%u page lsn=%X/%X.",
1660 								state->targetblock, topaque->btpo.level,
1661 								(uint32) (state->targetlsn >> 32),
1662 								(uint32) state->targetlsn)));
1663 }
1664 
1665 /*
1666  * Per-tuple callback from IndexBuildHeapScan, used to determine if index has
1667  * all the entries that definitely should have been observed in leaf pages of
1668  * the target index (that is, all IndexTuples that were fingerprinted by our
1669  * Bloom filter).  All heapallindexed checks occur here.
1670  *
1671  * The redundancy between an index and the table it indexes provides a good
1672  * opportunity to detect corruption, especially corruption within the table.
1673  * The high level principle behind the verification performed here is that any
1674  * IndexTuple that should be in an index following a fresh CREATE INDEX (based
1675  * on the same index definition) should also have been in the original,
1676  * existing index, which should have used exactly the same representation
1677  *
1678  * Since the overall structure of the index has already been verified, the most
1679  * likely explanation for error here is a corrupt heap page (could be logical
1680  * or physical corruption).  Index corruption may still be detected here,
1681  * though.  Only readonly callers will have verified that left links and right
1682  * links are in agreement, and so it's possible that a leaf page transposition
1683  * within index is actually the source of corruption detected here (for
1684  * !readonly callers).  The checks performed only for readonly callers might
1685  * more accurately frame the problem as a cross-page invariant issue (this
1686  * could even be due to recovery not replaying all WAL records).  The !readonly
1687  * ERROR message raised here includes a HINT about retrying with readonly
1688  * verification, just in case it's a cross-page invariant issue, though that
1689  * isn't particularly likely.
1690  *
1691  * IndexBuildHeapScan() expects to be able to find the root tuple when a
1692  * heap-only tuple (the live tuple at the end of some HOT chain) needs to be
1693  * indexed, in order to replace the actual tuple's TID with the root tuple's
1694  * TID (which is what we're actually passed back here).  The index build heap
1695  * scan code will raise an error when a tuple that claims to be the root of the
1696  * heap-only tuple's HOT chain cannot be located.  This catches cases where the
1697  * original root item offset/root tuple for a HOT chain indicates (for whatever
1698  * reason) that the entire HOT chain is dead, despite the fact that the latest
1699  * heap-only tuple should be indexed.  When this happens, sequential scans may
1700  * always give correct answers, and all indexes may be considered structurally
1701  * consistent (i.e. the nbtree structural checks would not detect corruption).
1702  * It may be the case that only index scans give wrong answers, and yet heap or
1703  * SLRU corruption is the real culprit.  (While it's true that LP_DEAD bit
1704  * setting will probably also leave the index in a corrupt state before too
1705  * long, the problem is nonetheless that there is heap corruption.)
1706  *
1707  * Heap-only tuple handling within IndexBuildHeapScan() works in a way that
1708  * helps us to detect index tuples that contain the wrong values (values that
1709  * don't match the latest tuple in the HOT chain).  This can happen when there
1710  * is no superseding index tuple due to a faulty assessment of HOT safety,
1711  * perhaps during the original CREATE INDEX.  Because the latest tuple's
1712  * contents are used with the root TID, an error will be raised when a tuple
1713  * with the same TID but non-matching attribute values is passed back to us.
1714  * Faulty assessment of HOT-safety was behind at least two distinct CREATE
1715  * INDEX CONCURRENTLY bugs that made it into stable releases, one of which was
1716  * undetected for many years.  In short, the same principle that allows a
1717  * REINDEX to repair corruption when there was an (undetected) broken HOT chain
1718  * also allows us to detect the corruption in many cases.
1719  */
1720 static void
1721 bt_tuple_present_callback(Relation index, HeapTuple htup, Datum *values,
1722 						  bool *isnull, bool tupleIsAlive, void *checkstate)
1723 {
1724 	BtreeCheckState *state = (BtreeCheckState *) checkstate;
1725 	IndexTuple	itup, norm;
1726 
1727 	Assert(state->heapallindexed);
1728 
1729 	/* Generate a normalized index tuple for fingerprinting */
1730 	itup = index_form_tuple(RelationGetDescr(index), values, isnull);
1731 	itup->t_tid = htup->t_self;
1732 	norm = bt_normalize_tuple(state, itup);
1733 
1734 	/* Probe Bloom filter -- tuple should be present */
1735 	if (bloom_lacks_element(state->filter, (unsigned char *) norm,
1736 							IndexTupleSize(norm)))
1737 		ereport(ERROR,
1738 				(errcode(ERRCODE_DATA_CORRUPTED),
1739 				 errmsg("heap tuple (%u,%u) from table \"%s\" lacks matching index tuple within index \"%s\"",
1740 						ItemPointerGetBlockNumber(&(itup->t_tid)),
1741 						ItemPointerGetOffsetNumber(&(itup->t_tid)),
1742 						RelationGetRelationName(state->heaprel),
1743 						RelationGetRelationName(state->rel)),
1744 				 !state->readonly
1745 				 ? errhint("Retrying verification using the function bt_index_parent_check() might provide a more specific error.")
1746 				 : 0));
1747 
1748 	state->heaptuplespresent++;
1749 	pfree(itup);
1750 	/* Cannot leak memory here */
1751 	if (norm != itup)
1752 		pfree(norm);
1753 }
1754 
1755 /*
1756  * Normalize an index tuple for fingerprinting.
1757  *
1758  * In general, index tuple formation is assumed to be deterministic by
1759  * heapallindexed verification, and IndexTuples are assumed immutable.  While
1760  * the LP_DEAD bit is mutable in leaf pages, that's ItemId metadata, which is
1761  * not fingerprinted.  Normalization is required to compensate for corner
1762  * cases where the determinism assumption doesn't quite work.
1763  *
1764  * There is currently one such case: index_form_tuple() does not try to hide
1765  * the source TOAST state of input datums.  The executor applies TOAST
1766  * compression for heap tuples based on different criteria to the compression
1767  * applied within btinsert()'s call to index_form_tuple(): it sometimes
1768  * compresses more aggressively, resulting in compressed heap tuple datums but
1769  * uncompressed corresponding index tuple datums.  A subsequent heapallindexed
1770  * verification will get a logically equivalent though bitwise unequal tuple
1771  * from index_form_tuple().  False positive heapallindexed corruption reports
1772  * could occur without normalizing away the inconsistency.
1773  *
1774  * Returned tuple is often caller's own original tuple.  Otherwise, it is a
1775  * new representation of caller's original index tuple, palloc()'d in caller's
1776  * memory context.
1777  *
1778  * Note: This routine is not concerned with distinctions about the
1779  * representation of tuples beyond those that might break heapallindexed
1780  * verification.  In particular, it won't try to normalize opclass-equal
1781  * datums with potentially distinct representations (e.g., btree/numeric_ops
1782  * index datums will not get their display scale normalized-away here).
1783  * Normalization may need to be expanded to handle more cases in the future,
1784  * though.  For example, it's possible that non-pivot tuples could in the
1785  * future have alternative logically equivalent representations due to using
1786  * the INDEX_ALT_TID_MASK bit to implement intelligent deduplication.
1787  */
1788 static IndexTuple
1789 bt_normalize_tuple(BtreeCheckState *state, IndexTuple itup)
1790 {
1791 	TupleDesc	tupleDescriptor = RelationGetDescr(state->rel);
1792 	Datum		normalized[INDEX_MAX_KEYS];
1793 	bool		isnull[INDEX_MAX_KEYS];
1794 	bool		toast_free[INDEX_MAX_KEYS];
1795 	bool		formnewtup = false;
1796 	IndexTuple	reformed;
1797 	int			i;
1798 
1799 	/* Easy case: It's immediately clear that tuple has no varlena datums */
1800 	if (!IndexTupleHasVarwidths(itup))
1801 		return itup;
1802 
1803 	for (i = 0; i < tupleDescriptor->natts; i++)
1804 	{
1805 		Form_pg_attribute	att;
1806 
1807 		att = TupleDescAttr(tupleDescriptor, i);
1808 
1809 		/* Assume untoasted/already normalized datum initially */
1810 		toast_free[i] = false;
1811 		normalized[i] = index_getattr(itup, att->attnum,
1812 									  tupleDescriptor,
1813 									  &isnull[i]);
1814 		if (att->attbyval || att->attlen != -1 || isnull[i])
1815 			continue;
1816 
1817 		/*
1818 		 * Callers always pass a tuple that could safely be inserted into the
1819 		 * index without further processing, so an external varlena header
1820 		 * should never be encountered here
1821 		 */
1822 		if (VARATT_IS_EXTERNAL(DatumGetPointer(normalized[i])))
1823 			ereport(ERROR,
1824 					(errcode(ERRCODE_INDEX_CORRUPTED),
1825 					 errmsg("external varlena datum in tuple that references heap row (%u,%u) in index \"%s\"",
1826 							ItemPointerGetBlockNumber(&(itup->t_tid)),
1827 							ItemPointerGetOffsetNumber(&(itup->t_tid)),
1828 							RelationGetRelationName(state->rel))));
1829 		else if (VARATT_IS_COMPRESSED(DatumGetPointer(normalized[i])))
1830 		{
1831 			formnewtup = true;
1832 			normalized[i] = PointerGetDatum(PG_DETOAST_DATUM(normalized[i]));
1833 			toast_free[i] = true;
1834 		}
1835 	}
1836 
1837 	/* Easier case: Tuple has varlena datums, none of which are compressed */
1838 	if (!formnewtup)
1839 		return itup;
1840 
1841 	/*
1842 	 * Hard case: Tuple had compressed varlena datums that necessitate
1843 	 * creating normalized version of the tuple from uncompressed input datums
1844 	 * (normalized input datums).  This is rather naive, but shouldn't be
1845 	 * necessary too often.
1846 	 *
1847 	 * Note that we rely on deterministic index_form_tuple() TOAST compression
1848 	 * of normalized input.
1849 	 */
1850 	reformed = index_form_tuple(tupleDescriptor, normalized, isnull);
1851 	reformed->t_tid = itup->t_tid;
1852 
1853 	/* Cannot leak memory here */
1854 	for (i = 0; i < tupleDescriptor->natts; i++)
1855 		if (toast_free[i])
1856 			pfree(DatumGetPointer(normalized[i]));
1857 
1858 	return reformed;
1859 }
1860 
1861 /*
1862  * Is particular offset within page (whose special state is passed by caller)
1863  * the page negative-infinity item?
1864  *
1865  * As noted in comments above _bt_compare(), there is special handling of the
1866  * first data item as a "negative infinity" item.  The hard-coding within
1867  * _bt_compare() makes comparing this item for the purposes of verification
1868  * pointless at best, since the IndexTuple only contains a valid TID (a
1869  * reference TID to child page).
1870  */
1871 static inline bool
1872 offset_is_negative_infinity(BTPageOpaque opaque, OffsetNumber offset)
1873 {
1874 	/*
1875 	 * For internal pages only, the first item after high key, if any, is
1876 	 * negative infinity item.  Internal pages always have a negative infinity
1877 	 * item, whereas leaf pages never have one.  This implies that negative
1878 	 * infinity item is either first or second line item, or there is none
1879 	 * within page.
1880 	 *
1881 	 * Negative infinity items are a special case among pivot tuples.  They
1882 	 * always have zero attributes, while all other pivot tuples always have
1883 	 * nkeyatts attributes.
1884 	 *
1885 	 * Right-most pages don't have a high key, but could be said to
1886 	 * conceptually have a "positive infinity" high key.  Thus, there is a
1887 	 * symmetry between down link items in parent pages, and high keys in
1888 	 * children.  Together, they represent the part of the key space that
1889 	 * belongs to each page in the index.  For example, all children of the
1890 	 * root page will have negative infinity as a lower bound from root
1891 	 * negative infinity downlink, and positive infinity as an upper bound
1892 	 * (implicitly, from "imaginary" positive infinity high key in root).
1893 	 */
1894 	return !P_ISLEAF(opaque) && offset == P_FIRSTDATAKEY(opaque);
1895 }
1896 
1897 /*
1898  * Does the invariant hold that the key is less than or equal to a given upper
1899  * bound offset item?
1900  *
1901  * If this function returns false, convention is that caller throws error due
1902  * to corruption.
1903  */
1904 static inline bool
1905 invariant_leq_offset(BtreeCheckState *state, ScanKey key,
1906 					 OffsetNumber upperbound)
1907 {
1908 	int16		nkeyatts = IndexRelationGetNumberOfKeyAttributes(state->rel);
1909 	int32		cmp;
1910 
1911 	cmp = _bt_compare(state->rel, nkeyatts, key, state->target, upperbound);
1912 
1913 	return cmp <= 0;
1914 }
1915 
1916 /*
1917  * Does the invariant hold that the key is greater than or equal to a given
1918  * lower bound offset item?
1919  *
1920  * If this function returns false, convention is that caller throws error due
1921  * to corruption.
1922  */
1923 static inline bool
1924 invariant_geq_offset(BtreeCheckState *state, ScanKey key,
1925 					 OffsetNumber lowerbound)
1926 {
1927 	int16		nkeyatts = IndexRelationGetNumberOfKeyAttributes(state->rel);
1928 	int32		cmp;
1929 
1930 	cmp = _bt_compare(state->rel, nkeyatts, key, state->target, lowerbound);
1931 
1932 	return cmp >= 0;
1933 }
1934 
1935 /*
1936  * Does the invariant hold that the key is less than or equal to a given upper
1937  * bound offset item, with the offset relating to a caller-supplied page that
1938  * is not the current target page? Caller's non-target page is typically a
1939  * child page of the target, checked as part of checking a property of the
1940  * target page (i.e. the key comes from the target).
1941  *
1942  * If this function returns false, convention is that caller throws error due
1943  * to corruption.
1944  */
1945 static inline bool
1946 invariant_leq_nontarget_offset(BtreeCheckState *state,
1947 							   Page nontarget, ScanKey key,
1948 							   OffsetNumber upperbound)
1949 {
1950 	int16		nkeyatts = IndexRelationGetNumberOfKeyAttributes(state->rel);
1951 	int32		cmp;
1952 
1953 	cmp = _bt_compare(state->rel, nkeyatts, key, nontarget, upperbound);
1954 
1955 	return cmp <= 0;
1956 }
1957 
1958 /*
1959  * Given a block number of a B-Tree page, return page in palloc()'d memory.
1960  * While at it, perform some basic checks of the page.
1961  *
1962  * There is never an attempt to get a consistent view of multiple pages using
1963  * multiple concurrent buffer locks; in general, we only acquire a single pin
1964  * and buffer lock at a time, which is often all that the nbtree code requires.
1965  *
1966  * Operating on a copy of the page is useful because it prevents control
1967  * getting stuck in an uninterruptible state when an underlying operator class
1968  * misbehaves.
1969  */
1970 static Page
1971 palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum)
1972 {
1973 	Buffer		buffer;
1974 	Page		page;
1975 	BTPageOpaque opaque;
1976 	OffsetNumber maxoffset;
1977 
1978 	page = palloc(BLCKSZ);
1979 
1980 	/*
1981 	 * We copy the page into local storage to avoid holding pin on the buffer
1982 	 * longer than we must.
1983 	 */
1984 	buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum, RBM_NORMAL,
1985 								state->checkstrategy);
1986 	LockBuffer(buffer, BT_READ);
1987 
1988 	/*
1989 	 * Perform the same basic sanity checking that nbtree itself performs for
1990 	 * every page:
1991 	 */
1992 	_bt_checkpage(state->rel, buffer);
1993 
1994 	/* Only use copy of page in palloc()'d memory */
1995 	memcpy(page, BufferGetPage(buffer), BLCKSZ);
1996 	UnlockReleaseBuffer(buffer);
1997 
1998 	opaque = (BTPageOpaque) PageGetSpecialPointer(page);
1999 
2000 	if (P_ISMETA(opaque) && blocknum != BTREE_METAPAGE)
2001 		ereport(ERROR,
2002 				(errcode(ERRCODE_INDEX_CORRUPTED),
2003 				 errmsg("invalid meta page found at block %u in index \"%s\"",
2004 						blocknum, RelationGetRelationName(state->rel))));
2005 
2006 	/* Check page from block that ought to be meta page */
2007 	if (blocknum == BTREE_METAPAGE)
2008 	{
2009 		BTMetaPageData *metad = BTPageGetMeta(page);
2010 
2011 		if (!P_ISMETA(opaque) ||
2012 			metad->btm_magic != BTREE_MAGIC)
2013 			ereport(ERROR,
2014 					(errcode(ERRCODE_INDEX_CORRUPTED),
2015 					 errmsg("index \"%s\" meta page is corrupt",
2016 							RelationGetRelationName(state->rel))));
2017 
2018 		if (metad->btm_version < BTREE_MIN_VERSION ||
2019 			metad->btm_version > BTREE_VERSION)
2020 			ereport(ERROR,
2021 					(errcode(ERRCODE_INDEX_CORRUPTED),
2022 					 errmsg("version mismatch in index \"%s\": file version %d, "
2023 							"current version %d, minimum supported version %d",
2024 							RelationGetRelationName(state->rel),
2025 							metad->btm_version, BTREE_VERSION,
2026 							BTREE_MIN_VERSION)));
2027 
2028 		/* Finished with metapage checks */
2029 		return page;
2030 	}
2031 
2032 	/*
2033 	 * Deleted pages have no sane "level" field, so can only check non-deleted
2034 	 * page level
2035 	 */
2036 	if (P_ISLEAF(opaque) && !P_ISDELETED(opaque) && opaque->btpo.level != 0)
2037 		ereport(ERROR,
2038 				(errcode(ERRCODE_INDEX_CORRUPTED),
2039 				 errmsg("invalid leaf page level %u for block %u in index \"%s\"",
2040 						opaque->btpo.level, blocknum, RelationGetRelationName(state->rel))));
2041 
2042 	if (!P_ISLEAF(opaque) && !P_ISDELETED(opaque) &&
2043 		opaque->btpo.level == 0)
2044 		ereport(ERROR,
2045 				(errcode(ERRCODE_INDEX_CORRUPTED),
2046 				 errmsg("invalid internal page level 0 for block %u in index \"%s\"",
2047 						blocknum, RelationGetRelationName(state->rel))));
2048 
2049 	/*
2050 	 * Sanity checks for number of items on page.
2051 	 *
2052 	 * As noted at the beginning of _bt_binsrch(), an internal page must have
2053 	 * children, since there must always be a negative infinity downlink
2054 	 * (there may also be a highkey).  In the case of non-rightmost leaf
2055 	 * pages, there must be at least a highkey.  Deleted pages on replica
2056 	 * might contain no items, because page unlink re-initializes
2057 	 * page-to-be-deleted.  Deleted pages with no items might be on primary
2058 	 * too due to preceding recovery, but on primary new deletions can't
2059 	 * happen concurrently to amcheck.
2060 	 *
2061 	 * This is correct when pages are half-dead, since internal pages are
2062 	 * never half-dead, and leaf pages must have a high key when half-dead
2063 	 * (the rightmost page can never be deleted).  It's also correct with
2064 	 * fully deleted pages: _bt_unlink_halfdead_page() doesn't change anything
2065 	 * about the target page other than setting the page as fully dead, and
2066 	 * setting its xact field.  In particular, it doesn't change the sibling
2067 	 * links in the deletion target itself, since they're required when index
2068 	 * scans land on the deletion target, and then need to move right (or need
2069 	 * to move left, in the case of backward index scans).
2070 	 */
2071 	maxoffset = PageGetMaxOffsetNumber(page);
2072 	if (maxoffset > MaxIndexTuplesPerPage)
2073 		ereport(ERROR,
2074 				(errcode(ERRCODE_INDEX_CORRUPTED),
2075 				 errmsg("Number of items on block %u of index \"%s\" exceeds MaxIndexTuplesPerPage (%u)",
2076 						blocknum, RelationGetRelationName(state->rel),
2077 						MaxIndexTuplesPerPage)));
2078 
2079 	if (!P_ISLEAF(opaque) && !P_ISDELETED(opaque) && maxoffset < P_FIRSTDATAKEY(opaque))
2080 		ereport(ERROR,
2081 				(errcode(ERRCODE_INDEX_CORRUPTED),
2082 				 errmsg("internal block %u in index \"%s\" lacks high key and/or at least one downlink",
2083 						blocknum, RelationGetRelationName(state->rel))));
2084 
2085 	if (P_ISLEAF(opaque) && !P_ISDELETED(opaque) && !P_RIGHTMOST(opaque) && maxoffset < P_HIKEY)
2086 		ereport(ERROR,
2087 				(errcode(ERRCODE_INDEX_CORRUPTED),
2088 				 errmsg("non-rightmost leaf block %u in index \"%s\" lacks high key item",
2089 						blocknum, RelationGetRelationName(state->rel))));
2090 
2091 	/*
2092 	 * In general, internal pages are never marked half-dead, except on
2093 	 * versions of Postgres prior to 9.4, where it can be valid transient
2094 	 * state.  This state is nonetheless treated as corruption by VACUUM on
2095 	 * from version 9.4 on, so do the same here.  See _bt_pagedel() for full
2096 	 * details.
2097 	 *
2098 	 * Internal pages should never have garbage items, either.
2099 	 */
2100 	if (!P_ISLEAF(opaque) && P_ISHALFDEAD(opaque))
2101 		ereport(ERROR,
2102 				(errcode(ERRCODE_INDEX_CORRUPTED),
2103 				 errmsg("internal page block %u in index \"%s\" is half-dead",
2104 						blocknum, RelationGetRelationName(state->rel)),
2105 				 errhint("This can be caused by an interrupted VACUUM in version 9.3 or older, before upgrade. Please REINDEX it.")));
2106 
2107 	if (!P_ISLEAF(opaque) && P_HAS_GARBAGE(opaque))
2108 		ereport(ERROR,
2109 				(errcode(ERRCODE_INDEX_CORRUPTED),
2110 				 errmsg("internal page block %u in index \"%s\" has garbage items",
2111 						blocknum, RelationGetRelationName(state->rel))));
2112 
2113 	return page;
2114 }
2115