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