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