| 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-2025, 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 |
|
| 46 |
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 |
|
| 176 |
PG_FUNCTION_INFO_V1(bt_index_check); |
| 177 |
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 |
bt_index_check(PG_FUNCTION_ARGS) |
| 253 |
{ |
| 254 |
Oid indrelid = PG_GETARG_OID(0); |
| 255 |
BTCallbackState args; |
| 256 |
|
| 257 |
args.heapallindexed = false; |
| 258 |
args.rootdescend = false; |
| 259 |
args.parentcheck = false; |
| 260 |
args.checkunique = false; |
| 261 |
|
| 262 |
if (PG_NARGS() >= 2) |
| 263 |
args.heapallindexed = PG_GETARG_BOOL(1); |
| 264 |
if (PG_NARGS() >= 3) |
| 265 |
args.checkunique = PG_GETARG_BOOL(2); |
| 266 |
|
| 267 |
amcheck_lock_relation_and_check(indrelid, BTREE_AM_OID, |
| 268 |
bt_index_check_callback, |
| 269 |
AccessShareLock, &args); |
| 270 |
|
| 271 |
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 |
bt_index_parent_check(PG_FUNCTION_ARGS) |
| 285 |
{ |
| 286 |
Oid indrelid = PG_GETARG_OID(0); |
| 287 |
BTCallbackState args; |
| 288 |
|
| 289 |
args.heapallindexed = false; |
| 290 |
args.rootdescend = false; |
| 291 |
args.parentcheck = true; |
| 292 |
args.checkunique = false; |
| 293 |
|
| 294 |
if (PG_NARGS() >= 2) |
| 295 |
args.heapallindexed = PG_GETARG_BOOL(1); |
| 296 |
if (PG_NARGS() >= 3) |
| 297 |
args.rootdescend = PG_GETARG_BOOL(2); |
| 298 |
if (PG_NARGS() >= 4) |
| 299 |
args.checkunique = PG_GETARG_BOOL(3); |
| 300 |
|
| 301 |
amcheck_lock_relation_and_check(indrelid, BTREE_AM_OID, |
| 302 |
bt_index_check_callback, |
| 303 |
ShareLock, &args); |
| 304 |
|
| 305 |
PG_RETURN_VOID(); |
| 306 |
} |
| 307 |
|
| 308 |
/* |
| 309 |
* Helper for bt_index_[parent_]check, coordinating the bulk of the work. |
| 310 |
*/ |
| 311 |
static void |
| 312 |
bt_index_check_callback(Relation indrel, Relation heaprel, void *state, bool readonly) |
| 313 |
{ |
| 314 |
BTCallbackState *args = (BTCallbackState *) state; |
| 315 |
bool heapkeyspace, |
| 316 |
allequalimage; |
| 317 |
|
| 318 |
if (!smgrexists(RelationGetSmgr(indrel), MAIN_FORKNUM)) |
| 319 |
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 */ |
| 325 |
_bt_metaversion(indrel, &heapkeyspace, &allequalimage); |
| 326 |
if (allequalimage && !heapkeyspace) |
| 327 |
ereport(ERROR, |
| 328 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 329 |
errmsg("index \"%s\" metapage has equalimage field set on unsupported nbtree version", |
| 330 |
RelationGetRelationName(indrel)))); |
| 331 |
if (allequalimage && !_bt_allequalimage(indrel, false)) |
| 332 |
{ |
| 333 |
bool has_interval_ops = false; |
| 334 |
|
| 335 |
for (int i = 0; i < IndexRelationGetNumberOfKeyAttributes(indrel); i++) |
| 336 |
if (indrel->rd_opfamily[i] == INTERVAL_BTREE_FAM_OID) |
| 337 |
{ |
| 338 |
has_interval_ops = true; |
| 339 |
break; |
| 340 |
} |
| 341 |
|
| 342 |
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 */ |
| 352 |
bt_check_every_level(indrel, heaprel, heapkeyspace, readonly, |
| 353 |
args->heapallindexed, args->rootdescend, args->checkunique); |
| 354 |
} |
| 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 |
| 380 |
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 |
|
| 390 |
if (!readonly) |
| 391 |
elog(DEBUG1, "verifying consistency of tree structure for index \"%s\"", |
| 392 |
RelationGetRelationName(rel)); |
| 393 |
else |
| 394 |
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 |
*/ |
| 401 |
Assert(TransactionIdIsValid(RecentXmin)); |
| 402 |
|
| 403 |
/* |
| 404 |
* Initialize state for entire verification operation |
| 405 |
*/ |
| 406 |
state = palloc0(sizeof(BtreeCheckState)); |
| 407 |
state->rel = rel; |
| 408 |
state->heaprel = heaprel; |
| 409 |
state->heapkeyspace = heapkeyspace; |
| 410 |
state->readonly = readonly; |
| 411 |
state->heapallindexed = heapallindexed; |
| 412 |
state->rootdescend = rootdescend; |
| 413 |
state->checkunique = checkunique; |
| 414 |
state->snapshot = InvalidSnapshot; |
| 415 |
|
| 416 |
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 |
*/ |
| 429 |
total_pages = RelationGetNumberOfBlocks(rel); |
| 430 |
total_elems = Max(total_pages * (MaxTIDsPerBTreePage / 3), |
| 431 |
(int64) state->rel->rd_rel->reltuples); |
| 432 |
/* Generate a random seed to avoid repetition */ |
| 433 |
seed = pg_prng_uint64(&pg_global_prng_state); |
| 434 |
/* Create Bloom filter to fingerprint index */ |
| 435 |
state->filter = bloom_create(total_elems, maintenance_work_mem, seed); |
| 436 |
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 |
*/ |
| 445 |
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 |
if (IsolationUsesXactSnapshot() && rel->rd_index->indcheckxmin && |
| 460 |
!TransactionIdPrecedes(HeapTupleHeaderGetXmin(rel->rd_indextuple->t_data), |
| 461 |
state->snapshot->xmin)) |
| 462 |
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 |
*/ |
| 473 |
if (state->checkunique) |
| 474 |
{ |
| 475 |
state->indexinfo = BuildIndexInfo(state->rel); |
| 476 |
|
| 477 |
if (state->indexinfo->ii_Unique && state->snapshot == InvalidSnapshot) |
| 478 |
state->snapshot = RegisterSnapshot(GetTransactionSnapshot()); |
| 479 |
} |
| 480 |
|
| 481 |
Assert(!state->rootdescend || state->readonly); |
| 482 |
if (state->rootdescend && !state->heapkeyspace) |
| 483 |
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 */ |
| 490 |
state->targetcontext = AllocSetContextCreate(CurrentMemoryContext, |
| 491 |
"amcheck context", |
| 492 |
ALLOCSET_DEFAULT_SIZES); |
| 493 |
state->checkstrategy = GetAccessStrategy(BAS_BULKREAD); |
| 494 |
|
| 495 |
/* Get true root block from meta-page */ |
| 496 |
metapage = palloc_btree_page(state, BTREE_METAPAGE); |
| 497 |
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 |
if (metad->btm_fastroot != metad->btm_root) |
| 508 |
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 |
previouslevel = InvalidBtreeLevel; |
| 522 |
current.level = metad->btm_level; |
| 523 |
current.leftmost = metad->btm_root; |
| 524 |
current.istruerootlevel = true; |
| 525 |
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 |
current = bt_check_level_from_leftmost(state, current); |
| 532 |
|
| 533 |
if (current.leftmost == InvalidBlockNumber) |
| 534 |
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 |
|
| 539 |
previouslevel = current.level; |
| 540 |
} |
| 541 |
|
| 542 |
/* |
| 543 |
* * Check whether heap contains unindexed/malformed tuples * |
| 544 |
*/ |
| 545 |
if (state->heapallindexed) |
| 546 |
{ |
| 547 |
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 |
*/ |
| 557 |
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 |
*/ |
| 574 |
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 |
*/ |
| 581 |
indexinfo->ii_Unique = false; |
| 582 |
indexinfo->ii_ExclusionOps = NULL; |
| 583 |
indexinfo->ii_ExclusionProcs = NULL; |
| 584 |
indexinfo->ii_ExclusionStrats = NULL; |
| 585 |
|
| 586 |
elog(DEBUG1, "verifying that tuples from index \"%s\" are present in \"%s\"", |
| 587 |
RelationGetRelationName(state->rel), |
| 588 |
RelationGetRelationName(state->heaprel)); |
| 589 |
|
| 590 |
table_index_build_scan(state->heaprel, state->rel, indexinfo, true, false, |
| 591 |
bt_tuple_present_callback, state, scan); |
| 592 |
|
| 593 |
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 |
bloom_free(state->filter); |
| 599 |
} |
| 600 |
|
| 601 |
/* Be tidy: */ |
| 602 |
if (state->snapshot != InvalidSnapshot) |
| 603 |
UnregisterSnapshot(state->snapshot); |
| 604 |
MemoryContextDelete(state->targetcontext); |
| 605 |
} |
| 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 |
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 |
BlockNumber leftcurrent = P_NONE; |
| 635 |
BlockNumber current = level.leftmost; |
| 636 |
|
| 637 |
/* Initialize return state */ |
| 638 |
nextleveldown.leftmost = InvalidBlockNumber; |
| 639 |
nextleveldown.level = InvalidBtreeLevel; |
| 640 |
nextleveldown.istruerootlevel = false; |
| 641 |
|
| 642 |
/* Use page-level context for duration of this call */ |
| 643 |
oldcontext = MemoryContextSwitchTo(state->targetcontext); |
| 644 |
|
| 645 |
elog(DEBUG1, "verifying level %u%s", level.level, |
| 646 |
level.istruerootlevel ? |
| 647 |
" (true root level)" : level.level == 0 ? " (leaf level)" : ""); |
| 648 |
|
| 649 |
state->prevrightlink = InvalidBlockNumber; |
| 650 |
state->previncompletesplit = false; |
| 651 |
|
| 652 |
do |
| 653 |
{ |
| 654 |
/* Don't rely on CHECK_FOR_INTERRUPTS() calls at lower level */ |
| 655 |
CHECK_FOR_INTERRUPTS(); |
| 656 |
|
| 657 |
/* Initialize state for this iteration */ |
| 658 |
state->targetblock = current; |
| 659 |
state->target = palloc_btree_page(state, state->targetblock); |
| 660 |
state->targetlsn = PageGetLSN(state->target); |
| 661 |
|
| 662 |
opaque = BTPageGetOpaque(state->target); |
| 663 |
|
| 664 |
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 |
*/ |
| 677 |
if (state->readonly && P_ISDELETED(opaque)) |
| 678 |
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 |
|
| 685 |
if (P_RIGHTMOST(opaque)) |
| 686 |
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 |
| 691 |
ereport(DEBUG1, |
| 692 |
(errcode(ERRCODE_NO_DATA), |
| 693 |
errmsg_internal("block %u of index \"%s\" concurrently deleted", |
| 694 |
current, RelationGetRelationName(state->rel)))); |
| 695 |
goto nextpage; |
| 696 |
} |
| 697 |
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 |
if (state->readonly) |
| 707 |
{ |
| 708 |
if (!bt_leftmost_ignoring_half_dead(state, current, opaque)) |
| 709 |
ereport(ERROR, |
| 710 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 711 |
errmsg("block %u is not leftmost in index \"%s\"", |
| 712 |
current, RelationGetRelationName(state->rel)))); |
| 713 |
|
| 714 |
if (level.istruerootlevel && (!P_ISROOT(opaque) && !P_INCOMPLETE_SPLIT(opaque))) |
| 715 |
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 |
*/ |
| 730 |
if (!P_ISLEAF(opaque)) |
| 731 |
{ |
| 732 |
IndexTuple itup; |
| 733 |
ItemId itemid; |
| 734 |
|
| 735 |
/* Internal page -- downlink gets leftmost on next level */ |
| 736 |
itemid = PageGetItemIdCareful(state, state->targetblock, |
| 737 |
state->target, |
| 738 |
P_FIRSTDATAKEY(opaque)); |
| 739 |
itup = (IndexTuple) PageGetItem(state->target, itemid); |
| 740 |
nextleveldown.leftmost = BTreeTupleGetDownLink(itup); |
| 741 |
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 |
*/ |
| 751 |
nextleveldown.leftmost = P_NONE; |
| 752 |
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 |
*/ |
| 771 |
if (opaque->btpo_prev != leftcurrent && leftcurrent != P_NONE) |
| 772 |
bt_recheck_sibling_links(state, opaque->btpo_prev, leftcurrent); |
| 773 |
|
| 774 |
/* Check level */ |
| 775 |
if (level.level != opaque->btpo_level) |
| 776 |
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 */ |
| 784 |
bt_target_page_check(state); |
| 785 |
|
| 786 |
nextpage: |
| 787 |
|
| 788 |
/* Try to detect circular links */ |
| 789 |
if (current == leftcurrent || current == opaque->btpo_prev) |
| 790 |
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 |
|
| 795 |
leftcurrent = current; |
| 796 |
current = opaque->btpo_next; |
| 797 |
|
| 798 |
if (state->lowkey) |
| 799 |
{ |
| 800 |
Assert(state->readonly); |
| 801 |
pfree(state->lowkey); |
| 802 |
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 |
if (state->readonly && !P_RIGHTMOST(opaque)) |
| 822 |
{ |
| 823 |
IndexTuple itup; |
| 824 |
ItemId itemid; |
| 825 |
|
| 826 |
itemid = PageGetItemIdCareful(state, state->targetblock, |
| 827 |
state->target, P_HIKEY); |
| 828 |
itup = (IndexTuple) PageGetItem(state->target, itemid); |
| 829 |
|
| 830 |
state->lowkey = MemoryContextAlloc(oldcontext, IndexTupleSize(itup)); |
| 831 |
memcpy(state->lowkey, itup, IndexTupleSize(itup)); |
| 832 |
} |
| 833 |
|
| 834 |
/* Free page and associated memory for this iteration */ |
| 835 |
MemoryContextReset(state->targetcontext); |
| 836 |
} |
| 837 |
while (current != P_NONE); |
| 838 |
|
| 839 |
if (state->lowkey) |
| 840 |
{ |
| 841 |
Assert(state->readonly); |
| 842 |
pfree(state->lowkey); |
| 843 |
state->lowkey = NULL; |
| 844 |
} |
| 845 |
|
| 846 |
/* Don't change context for caller */ |
| 847 |
MemoryContextSwitchTo(oldcontext); |
| 848 |
|
| 849 |
return nextleveldown; |
| 850 |
} |
| 851 |
|
| 852 |
/* Check visibility of the table entry referenced by nbtree index */ |
| 853 |
static bool |
| 854 |
heap_entry_is_visible(BtreeCheckState *state, ItemPointer tid) |
| 855 |
{ |
| 856 |
bool tid_visible; |
| 857 |
|
| 858 |
TupleTableSlot *slot = table_slot_create(state->heaprel, NULL); |
| 859 |
|
| 860 |
tid_visible = table_tuple_fetch_row_version(state->heaprel, |
| 861 |
tid, state->snapshot, slot); |
| 862 |
if (slot != NULL) |
| 863 |
ExecDropSingleTupleTableSlot(slot); |
| 864 |
|
| 865 |
return tid_visible; |
| 866 |
} |
| 867 |
|
| 868 |
/* |
| 869 |
* Prepare an error message for unique constrain violation in |
| 870 |
* a btree index and report ERROR. |
| 871 |
*/ |
| 872 |
static void |
| 873 |
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 |
*nitid = "", |
| 882 |
*pposting = "", |
| 883 |
*pnposting = ""; |
| 884 |
|
| 885 |
htid = psprintf("tid=(%u,%u)", |
| 886 |
ItemPointerGetBlockNumberNoCheck(lVis->tid), |
| 887 |
ItemPointerGetOffsetNumberNoCheck(lVis->tid)); |
| 888 |
nhtid = psprintf("tid=(%u,%u)", |
| 889 |
ItemPointerGetBlockNumberNoCheck(nexttid), |
| 890 |
ItemPointerGetOffsetNumberNoCheck(nexttid)); |
| 891 |
itid = psprintf("tid=(%u,%u)", lVis->blkno, lVis->offset); |
| 892 |
|
| 893 |
if (nblock != lVis->blkno || noffset != lVis->offset) |
| 894 |
nitid = psprintf(" tid=(%u,%u)", nblock, noffset); |
| 895 |
|
| 896 |
if (lVis->postingIndex >= 0) |
| 897 |
pposting = psprintf(" posting %u", lVis->postingIndex); |
| 898 |
|
| 899 |
if (nposting >= 0) |
| 900 |
pnposting = psprintf(" posting %u", nposting); |
| 901 |
|
| 902 |
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/%X.", |
| 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 |
bt_entry_unique_check(BtreeCheckState *state, IndexTuple itup, |
| 914 |
BlockNumber targetblock, OffsetNumber offset, |
| 915 |
BtreeLastVisibleEntry *lVis) |
| 916 |
{ |
| 917 |
ItemPointer tid; |
| 918 |
bool has_visible_entry = false; |
| 919 |
|
| 920 |
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 |
if (BTreeTupleIsPosting(itup)) |
| 927 |
{ |
| 928 |
for (int i = 0; i < BTreeTupleGetNPosting(itup); i++) |
| 929 |
{ |
| 930 |
tid = BTreeTupleGetPostingN(itup, i); |
| 931 |
if (heap_entry_is_visible(state, tid)) |
| 932 |
{ |
| 933 |
has_visible_entry = true; |
| 934 |
if (ItemPointerIsValid(lVis->tid)) |
| 935 |
{ |
| 936 |
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 |
*/ |
| 947 |
if (lVis->blkno != targetblock && ItemPointerIsValid(lVis->tid)) |
| 948 |
return; |
| 949 |
|
| 950 |
lVis->blkno = targetblock; |
| 951 |
lVis->offset = offset; |
| 952 |
lVis->postingIndex = i; |
| 953 |
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 |
{ |
| 965 |
tid = BTreeTupleGetHeapTID(itup); |
| 966 |
if (heap_entry_is_visible(state, tid)) |
| 967 |
{ |
| 968 |
has_visible_entry = true; |
| 969 |
if (ItemPointerIsValid(lVis->tid)) |
| 970 |
{ |
| 971 |
bt_report_duplicate(state, |
| 972 |
lVis, |
| 973 |
tid, targetblock, |
| 974 |
offset, -1); |
| 975 |
} |
| 976 |
|
| 977 |
lVis->blkno = targetblock; |
| 978 |
lVis->offset = offset; |
| 979 |
lVis->tid = tid; |
| 980 |
lVis->postingIndex = -1; |
| 981 |
} |
| 982 |
} |
| 983 |
|
| 984 |
if (!has_visible_entry && |
| 985 |
lVis->blkno != InvalidBlockNumber && |
| 986 |
lVis->blkno != targetblock) |
| 987 |
{ |
| 988 |
char *posting = ""; |
| 989 |
|
| 990 |
if (lVis->postingIndex >= 0) |
| 991 |
posting = psprintf(" posting %u", lVis->postingIndex); |
| 992 |
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 |
| 1012 |
bt_leftmost_ignoring_half_dead(BtreeCheckState *state, |
| 1013 |
BlockNumber start, |
| 1014 |
BTPageOpaque start_opaque) |
| 1015 |
{ |
| 1016 |
BlockNumber reached = start_opaque->btpo_prev, |
| 1017 |
reached_from = start; |
| 1018 |
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 |
Assert(state->readonly); |
| 1025 |
|
| 1026 |
while (reached != P_NONE && all_half_dead) |
| 1027 |
{ |
| 1028 |
Page page = palloc_btree_page(state, reached); |
| 1029 |
BTPageOpaque reached_opaque = BTPageGetOpaque(page); |
| 1030 |
|
| 1031 |
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 |
all_half_dead = P_ISHALFDEAD(reached_opaque) && |
| 1039 |
reached != start && |
| 1040 |
reached != reached_from && |
| 1041 |
reached_opaque->btpo_next == reached_from; |
| 1042 |
if (all_half_dead) |
| 1043 |
{ |
| 1044 |
XLogRecPtr pagelsn = PageGetLSN(page); |
| 1045 |
|
| 1046 |
/* pagelsn should point to an XLOG_BTREE_MARK_PAGE_HALFDEAD */ |
| 1047 |
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/%X.", |
| 1052 |
reached, reached_from, |
| 1053 |
LSN_FORMAT_ARGS(pagelsn)))); |
| 1054 |
|
| 1055 |
reached_from = reached; |
| 1056 |
reached = reached_opaque->btpo_prev; |
| 1057 |
} |
| 1058 |
|
| 1059 |
pfree(page); |
| 1060 |
} |
| 1061 |
|
| 1062 |
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 |
| 1101 |
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 */ |
| 1106 |
Assert(leftcurrent != P_NONE); |
| 1107 |
|
| 1108 |
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 |
lbuf = ReadBufferExtended(state->rel, MAIN_FORKNUM, leftcurrent, |
| 1118 |
RBM_NORMAL, state->checkstrategy); |
| 1119 |
LockBuffer(lbuf, BT_READ); |
| 1120 |
_bt_checkpage(state->rel, lbuf); |
| 1121 |
page = BufferGetPage(lbuf); |
| 1122 |
opaque = BTPageGetOpaque(page); |
| 1123 |
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 |
UnlockReleaseBuffer(lbuf); |
| 1133 |
return; |
| 1134 |
} |
| 1135 |
|
| 1136 |
newtargetblock = opaque->btpo_next; |
| 1137 |
/* Avoid self-deadlock when newtargetblock == leftcurrent */ |
| 1138 |
if (newtargetblock != leftcurrent) |
| 1139 |
{ |
| 1140 |
newtargetbuf = ReadBufferExtended(state->rel, MAIN_FORKNUM, |
| 1141 |
newtargetblock, RBM_NORMAL, |
| 1142 |
state->checkstrategy); |
| 1143 |
LockBuffer(newtargetbuf, BT_READ); |
| 1144 |
_bt_checkpage(state->rel, newtargetbuf); |
| 1145 |
page = BufferGetPage(newtargetbuf); |
| 1146 |
opaque = BTPageGetOpaque(page); |
| 1147 |
/* btpo_prev_from_target may have changed; update it */ |
| 1148 |
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 |
newtargetbuf = InvalidBuffer; |
| 1159 |
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 |
if (BufferIsValid(newtargetbuf)) |
| 1167 |
UnlockReleaseBuffer(newtargetbuf); |
| 1168 |
UnlockReleaseBuffer(lbuf); |
| 1169 |
|
| 1170 |
if (btpo_prev_from_target == leftcurrent) |
| 1171 |
{ |
| 1172 |
/* Report split in left sibling, not target (or new target) */ |
| 1173 |
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 |
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 |
state->targetblock = newtargetblock; |
| 1191 |
} |
| 1192 |
|
| 1193 |
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 |
| 1241 |
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 */ |
| 1248 |
BtreeLastVisibleEntry lVis = {InvalidBlockNumber, InvalidOffsetNumber, -1, NULL}; |
| 1249 |
|
| 1250 |
topaque = BTPageGetOpaque(state->target); |
| 1251 |
max = PageGetMaxOffsetNumber(state->target); |
| 1252 |
|
| 1253 |
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 |
*/ |
| 1260 |
if (!P_RIGHTMOST(topaque)) |
| 1261 |
{ |
| 1262 |
ItemId itemid; |
| 1263 |
IndexTuple itup; |
| 1264 |
|
| 1265 |
/* Verify line pointer before checking tuple */ |
| 1266 |
itemid = PageGetItemIdCareful(state, state->targetblock, |
| 1267 |
state->target, P_HIKEY); |
| 1268 |
if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target, |
| 1269 |
P_HIKEY)) |
| 1270 |
{ |
| 1271 |
itup = (IndexTuple) PageGetItem(state->target, itemid); |
| 1272 |
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/%X.", |
| 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 |
*/ |
| 1289 |
for (offset = P_FIRSTDATAKEY(topaque); |
| 1290 |
offset <= max; |
| 1291 |
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 |
*/ |
| 1305 |
bool unique_checked = false; |
| 1306 |
|
| 1307 |
CHECK_FOR_INTERRUPTS(); |
| 1308 |
|
| 1309 |
itemid = PageGetItemIdCareful(state, state->targetblock, |
| 1310 |
state->target, offset); |
| 1311 |
itup = (IndexTuple) PageGetItem(state->target, itemid); |
| 1312 |
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 |
if (tupsize != ItemIdGetLength(itemid)) |
| 1321 |
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/%X.", |
| 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 */ |
| 1332 |
if (!_bt_check_natts(state->rel, state->heapkeyspace, state->target, |
| 1333 |
offset)) |
| 1334 |
{ |
| 1335 |
ItemPointer tid; |
| 1336 |
char *itid, |
| 1337 |
*htid; |
| 1338 |
|
| 1339 |
itid = psprintf("(%u,%u)", state->targetblock, offset); |
| 1340 |
tid = BTreeTupleGetPointsToTID(itup); |
| 1341 |
htid = psprintf("(%u,%u)", |
| 1342 |
ItemPointerGetBlockNumberNoCheck(tid), |
| 1343 |
ItemPointerGetOffsetNumberNoCheck(tid)); |
| 1344 |
|
| 1345 |
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/%X.", |
| 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 |
*/ |
| 1361 |
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 |
*/ |
| 1368 |
if (!P_ISLEAF(topaque) && state->readonly) |
| 1369 |
{ |
| 1370 |
bt_child_highkey_check(state, |
| 1371 |
offset, |
| 1372 |
NULL, |
| 1373 |
topaque->btpo_level); |
| 1374 |
} |
| 1375 |
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 |
*/ |
| 1384 |
if (state->rootdescend && P_ISLEAF(topaque) && |
| 1385 |
!bt_rootdescend(state, itup)) |
| 1386 |
{ |
| 1387 |
ItemPointer tid = BTreeTupleGetPointsToTID(itup); |
| 1388 |
char *itid, |
| 1389 |
*htid; |
| 1390 |
|
| 1391 |
itid = psprintf("(%u,%u)", state->targetblock, offset); |
| 1392 |
htid = psprintf("(%u,%u)", ItemPointerGetBlockNumber(tid), |
| 1393 |
ItemPointerGetOffsetNumber(tid)); |
| 1394 |
|
| 1395 |
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/%X.", |
| 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 |
*/ |
| 1408 |
if (BTreeTupleIsPosting(itup)) |
| 1409 |
{ |
| 1410 |
ItemPointerData last; |
| 1411 |
ItemPointer current; |
| 1412 |
|
| 1413 |
ItemPointerCopy(BTreeTupleGetHeapTID(itup), &last); |
| 1414 |
|
| 1415 |
for (int i = 1; i < BTreeTupleGetNPosting(itup); i++) |
| 1416 |
{ |
| 1417 |
|
| 1418 |
current = BTreeTupleGetPostingN(itup, i); |
| 1419 |
|
| 1420 |
if (ItemPointerCompare(current, &last) <= 0) |
| 1421 |
{ |
| 1422 |
char *itid = psprintf("(%u,%u)", state->targetblock, offset); |
| 1423 |
|
| 1424 |
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/%X.", |
| 1429 |
itid, i, |
| 1430 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 1431 |
} |
| 1432 |
|
| 1433 |
ItemPointerCopy(current, &last); |
| 1434 |
} |
| 1435 |
} |
| 1436 |
|
| 1437 |
/* Build insertion scankey for current page offset */ |
| 1438 |
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 |
*/ |
| 1464 |
lowersizelimit = skey->heapkeyspace && |
| 1465 |
(P_ISLEAF(topaque) || BTreeTupleGetHeapTID(itup) == NULL); |
| 1466 |
if (tupsize > (lowersizelimit ? BTMaxItemSize : BTMaxItemSizeNoHeapTid)) |
| 1467 |
{ |
| 1468 |
ItemPointer tid = BTreeTupleGetPointsToTID(itup); |
| 1469 |
char *itid, |
| 1470 |
*htid; |
| 1471 |
|
| 1472 |
itid = psprintf("(%u,%u)", state->targetblock, offset); |
| 1473 |
htid = psprintf("(%u,%u)", |
| 1474 |
ItemPointerGetBlockNumberNoCheck(tid), |
| 1475 |
ItemPointerGetOffsetNumberNoCheck(tid)); |
| 1476 |
|
| 1477 |
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/%X.", |
| 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) */ |
| 1489 |
if (state->heapallindexed && P_ISLEAF(topaque) && !ItemIdIsDead(itemid)) |
| 1490 |
{ |
| 1491 |
IndexTuple norm; |
| 1492 |
|
| 1493 |
if (BTreeTupleIsPosting(itup)) |
| 1494 |
{ |
| 1495 |
/* Fingerprint all elements as distinct "plain" tuples */ |
| 1496 |
for (int i = 0; i < BTreeTupleGetNPosting(itup); i++) |
| 1497 |
{ |
| 1498 |
IndexTuple logtuple; |
| 1499 |
|
| 1500 |
logtuple = bt_posting_plain_tuple(itup, i); |
| 1501 |
norm = bt_normalize_tuple(state, logtuple); |
| 1502 |
bloom_add_element(state->filter, (unsigned char *) norm, |
| 1503 |
IndexTupleSize(norm)); |
| 1504 |
/* Be tidy */ |
| 1505 |
if (norm != logtuple) |
| 1506 |
pfree(norm); |
| 1507 |
pfree(logtuple); |
| 1508 |
} |
| 1509 |
} |
| 1510 |
else |
| 1511 |
{ |
| 1512 |
norm = bt_normalize_tuple(state, itup); |
| 1513 |
bloom_add_element(state->filter, (unsigned char *) norm, |
| 1514 |
IndexTupleSize(norm)); |
| 1515 |
/* Be tidy */ |
| 1516 |
if (norm != itup) |
| 1517 |
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 |
scantid = skey->scantid; |
| 1568 |
if (state->heapkeyspace && BTreeTupleIsPosting(itup)) |
| 1569 |
skey->scantid = BTreeTupleGetMaxHeapTID(itup); |
| 1570 |
|
| 1571 |
if (!P_RIGHTMOST(topaque) && |
| 1572 |
!(P_ISLEAF(topaque) ? invariant_leq_offset(state, skey, P_HIKEY) : |
| 1573 |
invariant_l_offset(state, skey, P_HIKEY))) |
| 1574 |
{ |
| 1575 |
ItemPointer tid = BTreeTupleGetPointsToTID(itup); |
| 1576 |
char *itid, |
| 1577 |
*htid; |
| 1578 |
|
| 1579 |
itid = psprintf("(%u,%u)", state->targetblock, offset); |
| 1580 |
htid = psprintf("(%u,%u)", |
| 1581 |
ItemPointerGetBlockNumberNoCheck(tid), |
| 1582 |
ItemPointerGetOffsetNumberNoCheck(tid)); |
| 1583 |
|
| 1584 |
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/%X.", |
| 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 */ |
| 1595 |
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 |
*/ |
| 1603 |
if (OffsetNumberNext(offset) <= max && |
| 1604 |
!invariant_l_offset(state, skey, OffsetNumberNext(offset))) |
| 1605 |
{ |
| 1606 |
ItemPointer tid; |
| 1607 |
char *itid, |
| 1608 |
*htid, |
| 1609 |
*nitid, |
| 1610 |
*nhtid; |
| 1611 |
|
| 1612 |
itid = psprintf("(%u,%u)", state->targetblock, offset); |
| 1613 |
tid = BTreeTupleGetPointsToTID(itup); |
| 1614 |
htid = psprintf("(%u,%u)", |
| 1615 |
ItemPointerGetBlockNumberNoCheck(tid), |
| 1616 |
ItemPointerGetOffsetNumberNoCheck(tid)); |
| 1617 |
nitid = psprintf("(%u,%u)", state->targetblock, |
| 1618 |
OffsetNumberNext(offset)); |
| 1619 |
|
| 1620 |
/* Reuse itup to get pointed-to heap location of second item */ |
| 1621 |
itemid = PageGetItemIdCareful(state, state->targetblock, |
| 1622 |
state->target, |
| 1623 |
OffsetNumberNext(offset)); |
| 1624 |
itup = (IndexTuple) PageGetItem(state->target, itemid); |
| 1625 |
tid = BTreeTupleGetPointsToTID(itup); |
| 1626 |
nhtid = psprintf("(%u,%u)", |
| 1627 |
ItemPointerGetBlockNumberNoCheck(tid), |
| 1628 |
ItemPointerGetOffsetNumberNoCheck(tid)); |
| 1629 |
|
| 1630 |
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) " |
| 1635 |
"higher index tid=%s (points to %s tid=%s) " |
| 1636 |
"page lsn=%X/%X.", |
| 1637 |
itid, |
| 1638 |
P_ISLEAF(topaque) ? "heap" : "index", |
| 1639 |
htid, |
| 1640 |
nitid, |
| 1641 |
P_ISLEAF(topaque) ? "heap" : "index", |
| 1642 |
nhtid, |
| 1643 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 1644 |
} |
| 1645 |
|
| 1646 |
/* |
| 1647 |
* If the index is unique verify entries uniqueness by checking the |
| 1648 |
* heap tuples visibility. Immediately check posting tuples and |
| 1649 |
* tuples with repeated keys. Postpone check for keys, which have the |
| 1650 |
* first appearance. |
| 1651 |
*/ |
| 1652 |
if (state->checkunique && state->indexinfo->ii_Unique && |
| 1653 |
P_ISLEAF(topaque) && !skey->anynullkeys && |
| 1654 |
(BTreeTupleIsPosting(itup) || ItemPointerIsValid(lVis.tid))) |
| 1655 |
{ |
| 1656 |
bt_entry_unique_check(state, itup, state->targetblock, offset, |
| 1657 |
&lVis); |
| 1658 |
unique_checked = true; |
| 1659 |
} |
| 1660 |
|
| 1661 |
if (state->checkunique && state->indexinfo->ii_Unique && |
| 1662 |
P_ISLEAF(topaque) && OffsetNumberNext(offset) <= max) |
| 1663 |
{ |
| 1664 |
/* Save current scankey tid */ |
| 1665 |
scantid = skey->scantid; |
| 1666 |
|
| 1667 |
/* |
| 1668 |
* Invalidate scankey tid to make _bt_compare compare only keys in |
| 1669 |
* the item to report equality even if heap TIDs are different |
| 1670 |
*/ |
| 1671 |
skey->scantid = NULL; |
| 1672 |
|
| 1673 |
/* |
| 1674 |
* If next key tuple is different, invalidate last visible entry |
| 1675 |
* data (whole index tuple or last posting in index tuple). Key |
| 1676 |
* containing null value does not violate unique constraint and |
| 1677 |
* treated as different to any other key. |
| 1678 |
* |
| 1679 |
* If the next key is the same as the previous one, do the |
| 1680 |
* bt_entry_unique_check() call if it was postponed. |
| 1681 |
*/ |
| 1682 |
if (_bt_compare(state->rel, skey, state->target, |
| 1683 |
OffsetNumberNext(offset)) != 0 || skey->anynullkeys) |
| 1684 |
{ |
| 1685 |
lVis.blkno = InvalidBlockNumber; |
| 1686 |
lVis.offset = InvalidOffsetNumber; |
| 1687 |
lVis.postingIndex = -1; |
| 1688 |
lVis.tid = NULL; |
| 1689 |
} |
| 1690 |
else if (!unique_checked) |
| 1691 |
{ |
| 1692 |
bt_entry_unique_check(state, itup, state->targetblock, offset, |
| 1693 |
&lVis); |
| 1694 |
} |
| 1695 |
skey->scantid = scantid; /* Restore saved scan key state */ |
| 1696 |
} |
| 1697 |
|
| 1698 |
/* |
| 1699 |
* * Last item check * |
| 1700 |
* |
| 1701 |
* Check last item against next/right page's first data item's when |
| 1702 |
* last item on page is reached. This additional check will detect |
| 1703 |
* transposed pages iff the supposed right sibling page happens to |
| 1704 |
* belong before target in the key space. (Otherwise, a subsequent |
| 1705 |
* heap verification will probably detect the problem.) |
| 1706 |
* |
| 1707 |
* This check is similar to the item order check that will have |
| 1708 |
* already been performed for every other "real" item on target page |
| 1709 |
* when last item is checked. The difference is that the next item |
| 1710 |
* (the item that is compared to target's last item) needs to come |
| 1711 |
* from the next/sibling page. There may not be such an item |
| 1712 |
* available from sibling for various reasons, though (e.g., target is |
| 1713 |
* the rightmost page on level). |
| 1714 |
*/ |
| 1715 |
if (offset == max) |
| 1716 |
{ |
| 1717 |
BTScanInsert rightkey; |
| 1718 |
|
| 1719 |
/* first offset on a right index page (log only) */ |
| 1720 |
OffsetNumber rightfirstoffset = InvalidOffsetNumber; |
| 1721 |
|
| 1722 |
/* Get item in next/right page */ |
| 1723 |
rightkey = bt_right_page_check_scankey(state, &rightfirstoffset); |
| 1724 |
|
| 1725 |
if (rightkey && |
| 1726 |
!invariant_g_offset(state, rightkey, max)) |
| 1727 |
{ |
| 1728 |
/* |
| 1729 |
* As explained at length in bt_right_page_check_scankey(), |
| 1730 |
* there is a known !readonly race that could account for |
| 1731 |
* apparent violation of invariant, which we must check for |
| 1732 |
* before actually proceeding with raising error. Our canary |
| 1733 |
* condition is that target page was deleted. |
| 1734 |
*/ |
| 1735 |
if (!state->readonly) |
| 1736 |
{ |
| 1737 |
/* Get fresh copy of target page */ |
| 1738 |
state->target = palloc_btree_page(state, state->targetblock); |
| 1739 |
/* Note that we deliberately do not update target LSN */ |
| 1740 |
topaque = BTPageGetOpaque(state->target); |
| 1741 |
|
| 1742 |
/* |
| 1743 |
* All !readonly checks now performed; just return |
| 1744 |
*/ |
| 1745 |
if (P_IGNORE(topaque)) |
| 1746 |
return; |
| 1747 |
} |
| 1748 |
|
| 1749 |
ereport(ERROR, |
| 1750 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 1751 |
errmsg("cross page item order invariant violated for index \"%s\"", |
| 1752 |
RelationGetRelationName(state->rel)), |
| 1753 |
errdetail_internal("Last item on page tid=(%u,%u) page lsn=%X/%X.", |
| 1754 |
state->targetblock, offset, |
| 1755 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 1756 |
} |
| 1757 |
|
| 1758 |
/* |
| 1759 |
* If index has unique constraint make sure that no more than one |
| 1760 |
* found equal items is visible. |
| 1761 |
*/ |
| 1762 |
if (state->checkunique && state->indexinfo->ii_Unique && |
| 1763 |
rightkey && P_ISLEAF(topaque) && !P_RIGHTMOST(topaque)) |
| 1764 |
{ |
| 1765 |
BlockNumber rightblock_number = topaque->btpo_next; |
| 1766 |
|
| 1767 |
elog(DEBUG2, "check cross page unique condition"); |
| 1768 |
|
| 1769 |
/* |
| 1770 |
* Make _bt_compare compare only index keys without heap TIDs. |
| 1771 |
* rightkey->scantid is modified destructively but it is ok |
| 1772 |
* for it is not used later. |
| 1773 |
*/ |
| 1774 |
rightkey->scantid = NULL; |
| 1775 |
|
| 1776 |
/* The first key on the next page is the same */ |
| 1777 |
if (_bt_compare(state->rel, rightkey, state->target, max) == 0 && |
| 1778 |
!rightkey->anynullkeys) |
| 1779 |
{ |
| 1780 |
Page rightpage; |
| 1781 |
|
| 1782 |
/* |
| 1783 |
* Do the bt_entry_unique_check() call if it was |
| 1784 |
* postponed. |
| 1785 |
*/ |
| 1786 |
if (!unique_checked) |
| 1787 |
bt_entry_unique_check(state, itup, state->targetblock, |
| 1788 |
offset, &lVis); |
| 1789 |
|
| 1790 |
elog(DEBUG2, "cross page equal keys"); |
| 1791 |
rightpage = palloc_btree_page(state, |
| 1792 |
rightblock_number); |
| 1793 |
topaque = BTPageGetOpaque(rightpage); |
| 1794 |
|
| 1795 |
if (P_IGNORE(topaque)) |
| 1796 |
{ |
| 1797 |
pfree(rightpage); |
| 1798 |
break; |
| 1799 |
} |
| 1800 |
|
| 1801 |
if (unlikely(!P_ISLEAF(topaque))) |
| 1802 |
ereport(ERROR, |
| 1803 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 1804 |
errmsg("right block of leaf block is non-leaf for index \"%s\"", |
| 1805 |
RelationGetRelationName(state->rel)), |
| 1806 |
errdetail_internal("Block=%u page lsn=%X/%X.", |
| 1807 |
state->targetblock, |
| 1808 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 1809 |
|
| 1810 |
itemid = PageGetItemIdCareful(state, rightblock_number, |
| 1811 |
rightpage, |
| 1812 |
rightfirstoffset); |
| 1813 |
itup = (IndexTuple) PageGetItem(rightpage, itemid); |
| 1814 |
|
| 1815 |
bt_entry_unique_check(state, itup, rightblock_number, rightfirstoffset, &lVis); |
| 1816 |
|
| 1817 |
pfree(rightpage); |
| 1818 |
} |
| 1819 |
} |
| 1820 |
} |
| 1821 |
|
| 1822 |
/* |
| 1823 |
* * Downlink check * |
| 1824 |
* |
| 1825 |
* Additional check of child items iff this is an internal page and |
| 1826 |
* caller holds a ShareLock. This happens for every downlink (item) |
| 1827 |
* in target excluding the negative-infinity downlink (again, this is |
| 1828 |
* because it has no useful value to compare). |
| 1829 |
*/ |
| 1830 |
if (!P_ISLEAF(topaque) && state->readonly) |
| 1831 |
bt_child_check(state, skey, offset); |
| 1832 |
} |
| 1833 |
|
| 1834 |
/* |
| 1835 |
* Special case bt_child_highkey_check() call |
| 1836 |
* |
| 1837 |
* We don't pass a real downlink, but we've to finish the level |
| 1838 |
* processing. If condition is satisfied, we've already processed all the |
| 1839 |
* downlinks from the target level. But there still might be pages to the |
| 1840 |
* right of the child page pointer to by our rightmost downlink. And they |
| 1841 |
* might have missing downlinks. This final call checks for them. |
| 1842 |
*/ |
| 1843 |
if (!P_ISLEAF(topaque) && P_RIGHTMOST(topaque) && state->readonly) |
| 1844 |
{ |
| 1845 |
bt_child_highkey_check(state, InvalidOffsetNumber, |
| 1846 |
NULL, topaque->btpo_level); |
| 1847 |
} |
| 1848 |
} |
| 1849 |
|
| 1850 |
/* |
| 1851 |
* Return a scankey for an item on page to right of current target (or the |
| 1852 |
* first non-ignorable page), sufficient to check ordering invariant on last |
| 1853 |
* item in current target page. Returned scankey relies on local memory |
| 1854 |
* allocated for the child page, which caller cannot pfree(). Caller's memory |
| 1855 |
* context should be reset between calls here. |
| 1856 |
* |
| 1857 |
* This is the first data item, and so all adjacent items are checked against |
| 1858 |
* their immediate sibling item (which may be on a sibling page, or even a |
| 1859 |
* "cousin" page at parent boundaries where target's rightlink points to page |
| 1860 |
* with different parent page). If no such valid item is available, return |
| 1861 |
* NULL instead. |
| 1862 |
* |
| 1863 |
* Note that !readonly callers must reverify that target page has not |
| 1864 |
* been concurrently deleted. |
| 1865 |
* |
| 1866 |
* Save rightfirstoffset for detailed error message. |
| 1867 |
*/ |
| 1868 |
static BTScanInsert |
| 1869 |
bt_right_page_check_scankey(BtreeCheckState *state, OffsetNumber *rightfirstoffset) |
| 1870 |
{ |
| 1871 |
BTPageOpaque opaque; |
| 1872 |
ItemId rightitem; |
| 1873 |
IndexTuple firstitup; |
| 1874 |
BlockNumber targetnext; |
| 1875 |
Page rightpage; |
| 1876 |
OffsetNumber nline; |
| 1877 |
|
| 1878 |
/* Determine target's next block number */ |
| 1879 |
opaque = BTPageGetOpaque(state->target); |
| 1880 |
|
| 1881 |
/* If target is already rightmost, no right sibling; nothing to do here */ |
| 1882 |
if (P_RIGHTMOST(opaque)) |
| 1883 |
return NULL; |
| 1884 |
|
| 1885 |
/* |
| 1886 |
* General notes on concurrent page splits and page deletion: |
| 1887 |
* |
| 1888 |
* Routines like _bt_search() don't require *any* page split interlock |
| 1889 |
* when descending the tree, including something very light like a buffer |
| 1890 |
* pin. That's why it's okay that we don't either. This avoidance of any |
| 1891 |
* need to "couple" buffer locks is the raison d' etre of the Lehman & Yao |
| 1892 |
* algorithm, in fact. |
| 1893 |
* |
| 1894 |
* That leaves deletion. A deleted page won't actually be recycled by |
| 1895 |
* VACUUM early enough for us to fail to at least follow its right link |
| 1896 |
* (or left link, or downlink) and find its sibling, because recycling |
| 1897 |
* does not occur until no possible index scan could land on the page. |
| 1898 |
* Index scans can follow links with nothing more than their snapshot as |
| 1899 |
* an interlock and be sure of at least that much. (See page |
| 1900 |
* recycling/"visible to everyone" notes in nbtree README.) |
| 1901 |
* |
| 1902 |
* Furthermore, it's okay if we follow a rightlink and find a half-dead or |
| 1903 |
* dead (ignorable) page one or more times. There will either be a |
| 1904 |
* further right link to follow that leads to a live page before too long |
| 1905 |
* (before passing by parent's rightmost child), or we will find the end |
| 1906 |
* of the entire level instead (possible when parent page is itself the |
| 1907 |
* rightmost on its level). |
| 1908 |
*/ |
| 1909 |
targetnext = opaque->btpo_next; |
| 1910 |
for (;;) |
| 1911 |
{ |
| 1912 |
CHECK_FOR_INTERRUPTS(); |
| 1913 |
|
| 1914 |
rightpage = palloc_btree_page(state, targetnext); |
| 1915 |
opaque = BTPageGetOpaque(rightpage); |
| 1916 |
|
| 1917 |
if (!P_IGNORE(opaque) || P_RIGHTMOST(opaque)) |
| 1918 |
break; |
| 1919 |
|
| 1920 |
/* |
| 1921 |
* We landed on a deleted or half-dead sibling page. Step right until |
| 1922 |
* we locate a live sibling page. |
| 1923 |
*/ |
| 1924 |
ereport(DEBUG2, |
| 1925 |
(errcode(ERRCODE_NO_DATA), |
| 1926 |
errmsg_internal("level %u sibling page in block %u of index \"%s\" was found deleted or half dead", |
| 1927 |
opaque->btpo_level, targetnext, RelationGetRelationName(state->rel)), |
| 1928 |
errdetail_internal("Deleted page found when building scankey from right sibling."))); |
| 1929 |
|
| 1930 |
targetnext = opaque->btpo_next; |
| 1931 |
|
| 1932 |
/* Be slightly more pro-active in freeing this memory, just in case */ |
| 1933 |
pfree(rightpage); |
| 1934 |
} |
| 1935 |
|
| 1936 |
/* |
| 1937 |
* No ShareLock held case -- why it's safe to proceed. |
| 1938 |
* |
| 1939 |
* Problem: |
| 1940 |
* |
| 1941 |
* We must avoid false positive reports of corruption when caller treats |
| 1942 |
* item returned here as an upper bound on target's last item. In |
| 1943 |
* general, false positives are disallowed. Avoiding them here when |
| 1944 |
* caller is !readonly is subtle. |
| 1945 |
* |
| 1946 |
* A concurrent page deletion by VACUUM of the target page can result in |
| 1947 |
* the insertion of items on to this right sibling page that would |
| 1948 |
* previously have been inserted on our target page. There might have |
| 1949 |
* been insertions that followed the target's downlink after it was made |
| 1950 |
* to point to right sibling instead of target by page deletion's first |
| 1951 |
* phase. The inserters insert items that would belong on target page. |
| 1952 |
* This race is very tight, but it's possible. This is our only problem. |
| 1953 |
* |
| 1954 |
* Non-problems: |
| 1955 |
* |
| 1956 |
* We are not hindered by a concurrent page split of the target; we'll |
| 1957 |
* never land on the second half of the page anyway. A concurrent split |
| 1958 |
* of the right page will also not matter, because the first data item |
| 1959 |
* remains the same within the left half, which we'll reliably land on. If |
| 1960 |
* we had to skip over ignorable/deleted pages, it cannot matter because |
| 1961 |
* their key space has already been atomically merged with the first |
| 1962 |
* non-ignorable page we eventually find (doesn't matter whether the page |
| 1963 |
* we eventually find is a true sibling or a cousin of target, which we go |
| 1964 |
* into below). |
| 1965 |
* |
| 1966 |
* Solution: |
| 1967 |
* |
| 1968 |
* Caller knows that it should reverify that target is not ignorable |
| 1969 |
* (half-dead or deleted) when cross-page sibling item comparison appears |
| 1970 |
* to indicate corruption (invariant fails). This detects the single race |
| 1971 |
* condition that exists for caller. This is correct because the |
| 1972 |
* continued existence of target block as non-ignorable (not half-dead or |
| 1973 |
* deleted) implies that target page was not merged into from the right by |
| 1974 |
* deletion; the key space at or after target never moved left. Target's |
| 1975 |
* parent either has the same downlink to target as before, or a < |
| 1976 |
* downlink due to deletion at the left of target. Target either has the |
| 1977 |
* same highkey as before, or a highkey < before when there is a page |
| 1978 |
* split. (The rightmost concurrently-split-from-target-page page will |
| 1979 |
* still have the same highkey as target was originally found to have, |
| 1980 |
* which for our purposes is equivalent to target's highkey itself never |
| 1981 |
* changing, since we reliably skip over |
| 1982 |
* concurrently-split-from-target-page pages.) |
| 1983 |
* |
| 1984 |
* In simpler terms, we allow that the key space of the target may expand |
| 1985 |
* left (the key space can move left on the left side of target only), but |
| 1986 |
* the target key space cannot expand right and get ahead of us without |
| 1987 |
* our detecting it. The key space of the target cannot shrink, unless it |
| 1988 |
* shrinks to zero due to the deletion of the original page, our canary |
| 1989 |
* condition. (To be very precise, we're a bit stricter than that because |
| 1990 |
* it might just have been that the target page split and only the |
| 1991 |
* original target page was deleted. We can be more strict, just not more |
| 1992 |
* lax.) |
| 1993 |
* |
| 1994 |
* Top level tree walk caller moves on to next page (makes it the new |
| 1995 |
* target) following recovery from this race. (cf. The rationale for |
| 1996 |
* child/downlink verification needing a ShareLock within |
| 1997 |
* bt_child_check(), where page deletion is also the main source of |
| 1998 |
* trouble.) |
| 1999 |
* |
| 2000 |
* Note that it doesn't matter if right sibling page here is actually a |
| 2001 |
* cousin page, because in order for the key space to be readjusted in a |
| 2002 |
* way that causes us issues in next level up (guiding problematic |
| 2003 |
* concurrent insertions to the cousin from the grandparent rather than to |
| 2004 |
* the sibling from the parent), there'd have to be page deletion of |
| 2005 |
* target's parent page (affecting target's parent's downlink in target's |
| 2006 |
* grandparent page). Internal page deletion only occurs when there are |
| 2007 |
* no child pages (they were all fully deleted), and caller is checking |
| 2008 |
* that the target's parent has at least one non-deleted (so |
| 2009 |
* non-ignorable) child: the target page. (Note that the first phase of |
| 2010 |
* deletion atomically marks the page to be deleted half-dead/ignorable at |
| 2011 |
* the same time downlink in its parent is removed, so caller will |
| 2012 |
* definitely not fail to detect that this happened.) |
| 2013 |
* |
| 2014 |
* This trick is inspired by the method backward scans use for dealing |
| 2015 |
* with concurrent page splits; concurrent page deletion is a problem that |
| 2016 |
* similarly receives special consideration sometimes (it's possible that |
| 2017 |
* the backwards scan will re-read its "original" block after failing to |
| 2018 |
* find a right-link to it, having already moved in the opposite direction |
| 2019 |
* (right/"forwards") a few times to try to locate one). Just like us, |
| 2020 |
* that happens only to determine if there was a concurrent page deletion |
| 2021 |
* of a reference page, and just like us if there was a page deletion of |
| 2022 |
* that reference page it means we can move on from caring about the |
| 2023 |
* reference page. See the nbtree README for a full description of how |
| 2024 |
* that works. |
| 2025 |
*/ |
| 2026 |
nline = PageGetMaxOffsetNumber(rightpage); |
| 2027 |
|
| 2028 |
/* |
| 2029 |
* Get first data item, if any |
| 2030 |
*/ |
| 2031 |
if (P_ISLEAF(opaque) && nline >= P_FIRSTDATAKEY(opaque)) |
| 2032 |
{ |
| 2033 |
/* Return first data item (if any) */ |
| 2034 |
rightitem = PageGetItemIdCareful(state, targetnext, rightpage, |
| 2035 |
P_FIRSTDATAKEY(opaque)); |
| 2036 |
*rightfirstoffset = P_FIRSTDATAKEY(opaque); |
| 2037 |
} |
| 2038 |
else if (!P_ISLEAF(opaque) && |
| 2039 |
nline >= OffsetNumberNext(P_FIRSTDATAKEY(opaque))) |
| 2040 |
{ |
| 2041 |
/* |
| 2042 |
* Return first item after the internal page's "negative infinity" |
| 2043 |
* item |
| 2044 |
*/ |
| 2045 |
rightitem = PageGetItemIdCareful(state, targetnext, rightpage, |
| 2046 |
OffsetNumberNext(P_FIRSTDATAKEY(opaque))); |
| 2047 |
} |
| 2048 |
else |
| 2049 |
{ |
| 2050 |
/* |
| 2051 |
* No first item. Page is probably empty leaf page, but it's also |
| 2052 |
* possible that it's an internal page with only a negative infinity |
| 2053 |
* item. |
| 2054 |
*/ |
| 2055 |
ereport(DEBUG2, |
| 2056 |
(errcode(ERRCODE_NO_DATA), |
| 2057 |
errmsg_internal("%s block %u of index \"%s\" has no first data item", |
| 2058 |
P_ISLEAF(opaque) ? "leaf" : "internal", targetnext, |
| 2059 |
RelationGetRelationName(state->rel)))); |
| 2060 |
return NULL; |
| 2061 |
} |
| 2062 |
|
| 2063 |
/* |
| 2064 |
* Return first real item scankey. Note that this relies on right page |
| 2065 |
* memory remaining allocated. |
| 2066 |
*/ |
| 2067 |
firstitup = (IndexTuple) PageGetItem(rightpage, rightitem); |
| 2068 |
return bt_mkscankey_pivotsearch(state->rel, firstitup); |
| 2069 |
} |
| 2070 |
|
| 2071 |
/* |
| 2072 |
* Check if two tuples are binary identical except the block number. So, |
| 2073 |
* this function is capable to compare pivot keys on different levels. |
| 2074 |
*/ |
| 2075 |
static bool |
| 2076 |
bt_pivot_tuple_identical(bool heapkeyspace, IndexTuple itup1, IndexTuple itup2) |
| 2077 |
{ |
| 2078 |
if (IndexTupleSize(itup1) != IndexTupleSize(itup2)) |
| 2079 |
return false; |
| 2080 |
|
| 2081 |
if (heapkeyspace) |
| 2082 |
{ |
| 2083 |
/* |
| 2084 |
* Offset number will contain important information in heapkeyspace |
| 2085 |
* indexes: the number of attributes left in the pivot tuple following |
| 2086 |
* suffix truncation. Don't skip over it (compare it too). |
| 2087 |
*/ |
| 2088 |
if (memcmp(&itup1->t_tid.ip_posid, &itup2->t_tid.ip_posid, |
| 2089 |
IndexTupleSize(itup1) - |
| 2090 |
offsetof(ItemPointerData, ip_posid)) != 0) |
| 2091 |
return false; |
| 2092 |
} |
| 2093 |
else |
| 2094 |
{ |
| 2095 |
/* |
| 2096 |
* Cannot rely on offset number field having consistent value across |
| 2097 |
* levels on pg_upgrade'd !heapkeyspace indexes. Compare contents of |
| 2098 |
* tuple starting from just after item pointer (i.e. after block |
| 2099 |
* number and offset number). |
| 2100 |
*/ |
| 2101 |
if (memcmp(&itup1->t_info, &itup2->t_info, |
| 2102 |
IndexTupleSize(itup1) - |
| 2103 |
offsetof(IndexTupleData, t_info)) != 0) |
| 2104 |
return false; |
| 2105 |
} |
| 2106 |
|
| 2107 |
return true; |
| 2108 |
} |
| 2109 |
|
| 2110 |
/*--- |
| 2111 |
* Check high keys on the child level. Traverse rightlinks from previous |
| 2112 |
* downlink to the current one. Check that there are no intermediate pages |
| 2113 |
* with missing downlinks. |
| 2114 |
* |
| 2115 |
* If 'loaded_child' is given, it's assumed to be the page pointed to by the |
| 2116 |
* downlink referenced by 'downlinkoffnum' of the target page. |
| 2117 |
* |
| 2118 |
* Basically this function is called for each target downlink and checks two |
| 2119 |
* invariants: |
| 2120 |
* |
| 2121 |
* 1) You can reach the next child from previous one via rightlinks; |
| 2122 |
* 2) Each child high key have matching pivot key on target level. |
| 2123 |
* |
| 2124 |
* Consider the sample tree picture. |
| 2125 |
* |
| 2126 |
* 1 |
| 2127 |
* / \ |
| 2128 |
* 2 <-> 3 |
| 2129 |
* / \ / \ |
| 2130 |
* 4 <> 5 <> 6 <> 7 <> 8 |
| 2131 |
* |
| 2132 |
* This function will be called for blocks 4, 5, 6 and 8. Consider what is |
| 2133 |
* happening for each function call. |
| 2134 |
* |
| 2135 |
* - The function call for block 4 initializes data structure and matches high |
| 2136 |
* key of block 4 to downlink's pivot key of block 2. |
| 2137 |
* - The high key of block 5 is matched to the high key of block 2. |
| 2138 |
* - The block 6 has an incomplete split flag set, so its high key isn't |
| 2139 |
* matched to anything. |
| 2140 |
* - The function call for block 8 checks that block 8 can be found while |
| 2141 |
* following rightlinks from block 6. The high key of block 7 will be |
| 2142 |
* matched to downlink's pivot key in block 3. |
| 2143 |
* |
| 2144 |
* There is also final call of this function, which checks that there is no |
| 2145 |
* missing downlinks for children to the right of the child referenced by |
| 2146 |
* rightmost downlink in target level. |
| 2147 |
*/ |
| 2148 |
static void |
| 2149 |
bt_child_highkey_check(BtreeCheckState *state, |
| 2150 |
OffsetNumber target_downlinkoffnum, |
| 2151 |
Page loaded_child, |
| 2152 |
uint32 target_level) |
| 2153 |
{ |
| 2154 |
BlockNumber blkno = state->prevrightlink; |
| 2155 |
Page page; |
| 2156 |
BTPageOpaque opaque; |
| 2157 |
bool rightsplit = state->previncompletesplit; |
| 2158 |
bool first = true; |
| 2159 |
ItemId itemid; |
| 2160 |
IndexTuple itup; |
| 2161 |
BlockNumber downlink; |
| 2162 |
|
| 2163 |
if (OffsetNumberIsValid(target_downlinkoffnum)) |
| 2164 |
{ |
| 2165 |
itemid = PageGetItemIdCareful(state, state->targetblock, |
| 2166 |
state->target, target_downlinkoffnum); |
| 2167 |
itup = (IndexTuple) PageGetItem(state->target, itemid); |
| 2168 |
downlink = BTreeTupleGetDownLink(itup); |
| 2169 |
} |
| 2170 |
else |
| 2171 |
{ |
| 2172 |
downlink = P_NONE; |
| 2173 |
} |
| 2174 |
|
| 2175 |
/* |
| 2176 |
* If no previous rightlink is memorized for current level just below |
| 2177 |
* target page's level, we are about to start from the leftmost page. We |
| 2178 |
* can't follow rightlinks from previous page, because there is no |
| 2179 |
* previous page. But we still can match high key. |
| 2180 |
* |
| 2181 |
* So we initialize variables for the loop above like there is previous |
| 2182 |
* page referencing current child. Also we imply previous page to not |
| 2183 |
* have incomplete split flag, that would make us require downlink for |
| 2184 |
* current child. That's correct, because leftmost page on the level |
| 2185 |
* should always have parent downlink. |
| 2186 |
*/ |
| 2187 |
if (!BlockNumberIsValid(blkno)) |
| 2188 |
{ |
| 2189 |
blkno = downlink; |
| 2190 |
rightsplit = false; |
| 2191 |
} |
| 2192 |
|
| 2193 |
/* Move to the right on the child level */ |
| 2194 |
while (true) |
| 2195 |
{ |
| 2196 |
/* |
| 2197 |
* Did we traverse the whole tree level and this is check for pages to |
| 2198 |
* the right of rightmost downlink? |
| 2199 |
*/ |
| 2200 |
if (blkno == P_NONE && downlink == P_NONE) |
| 2201 |
{ |
| 2202 |
state->prevrightlink = InvalidBlockNumber; |
| 2203 |
state->previncompletesplit = false; |
| 2204 |
return; |
| 2205 |
} |
| 2206 |
|
| 2207 |
/* Did we traverse the whole tree level and don't find next downlink? */ |
| 2208 |
if (blkno == P_NONE) |
| 2209 |
ereport(ERROR, |
| 2210 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2211 |
errmsg("can't traverse from downlink %u to downlink %u of index \"%s\"", |
| 2212 |
state->prevrightlink, downlink, |
| 2213 |
RelationGetRelationName(state->rel)))); |
| 2214 |
|
| 2215 |
/* Load page contents */ |
| 2216 |
if (blkno == downlink && loaded_child) |
| 2217 |
page = loaded_child; |
| 2218 |
else |
| 2219 |
page = palloc_btree_page(state, blkno); |
| 2220 |
|
| 2221 |
opaque = BTPageGetOpaque(page); |
| 2222 |
|
| 2223 |
/* The first page we visit at the level should be leftmost */ |
| 2224 |
if (first && !BlockNumberIsValid(state->prevrightlink) && |
| 2225 |
!bt_leftmost_ignoring_half_dead(state, blkno, opaque)) |
| 2226 |
ereport(ERROR, |
| 2227 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2228 |
errmsg("the first child of leftmost target page is not leftmost of its level in index \"%s\"", |
| 2229 |
RelationGetRelationName(state->rel)), |
| 2230 |
errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.", |
| 2231 |
state->targetblock, blkno, |
| 2232 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 2233 |
|
| 2234 |
/* Do level sanity check */ |
| 2235 |
if ((!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque)) && |
| 2236 |
opaque->btpo_level != target_level - 1) |
| 2237 |
ereport(ERROR, |
| 2238 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2239 |
errmsg("block found while following rightlinks from child of index \"%s\" has invalid level", |
| 2240 |
RelationGetRelationName(state->rel)), |
| 2241 |
errdetail_internal("Block pointed to=%u expected level=%u level in pointed to block=%u.", |
| 2242 |
blkno, target_level - 1, opaque->btpo_level))); |
| 2243 |
|
| 2244 |
/* Try to detect circular links */ |
| 2245 |
if ((!first && blkno == state->prevrightlink) || blkno == opaque->btpo_prev) |
| 2246 |
ereport(ERROR, |
| 2247 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2248 |
errmsg("circular link chain found in block %u of index \"%s\"", |
| 2249 |
blkno, RelationGetRelationName(state->rel)))); |
| 2250 |
|
| 2251 |
if (blkno != downlink && !P_IGNORE(opaque)) |
| 2252 |
{ |
| 2253 |
/* blkno probably has missing parent downlink */ |
| 2254 |
bt_downlink_missing_check(state, rightsplit, blkno, page); |
| 2255 |
} |
| 2256 |
|
| 2257 |
rightsplit = P_INCOMPLETE_SPLIT(opaque); |
| 2258 |
|
| 2259 |
/* |
| 2260 |
* If we visit page with high key, check that it is equal to the |
| 2261 |
* target key next to corresponding downlink. |
| 2262 |
*/ |
| 2263 |
if (!rightsplit && !P_RIGHTMOST(opaque) && !P_ISHALFDEAD(opaque)) |
| 2264 |
{ |
| 2265 |
BTPageOpaque topaque; |
| 2266 |
IndexTuple highkey; |
| 2267 |
OffsetNumber pivotkey_offset; |
| 2268 |
|
| 2269 |
/* Get high key */ |
| 2270 |
itemid = PageGetItemIdCareful(state, blkno, page, P_HIKEY); |
| 2271 |
highkey = (IndexTuple) PageGetItem(page, itemid); |
| 2272 |
|
| 2273 |
/* |
| 2274 |
* There might be two situations when we examine high key. If |
| 2275 |
* current child page is referenced by given target downlink, we |
| 2276 |
* should look to the next offset number for matching key from |
| 2277 |
* target page. |
| 2278 |
* |
| 2279 |
* Alternatively, we're following rightlinks somewhere in the |
| 2280 |
* middle between page referenced by previous target's downlink |
| 2281 |
* and the page referenced by current target's downlink. If |
| 2282 |
* current child page hasn't incomplete split flag set, then its |
| 2283 |
* high key should match to the target's key of current offset |
| 2284 |
* number. This happens when a previous call here (to |
| 2285 |
* bt_child_highkey_check()) found an incomplete split, and we |
| 2286 |
* reach a right sibling page without a downlink -- the right |
| 2287 |
* sibling page's high key still needs to be matched to a |
| 2288 |
* separator key on the parent/target level. |
| 2289 |
* |
| 2290 |
* Don't apply OffsetNumberNext() to target_downlinkoffnum when we |
| 2291 |
* already had to step right on the child level. Our traversal of |
| 2292 |
* the child level must try to move in perfect lockstep behind (to |
| 2293 |
* the left of) the target/parent level traversal. |
| 2294 |
*/ |
| 2295 |
if (blkno == downlink) |
| 2296 |
pivotkey_offset = OffsetNumberNext(target_downlinkoffnum); |
| 2297 |
else |
| 2298 |
pivotkey_offset = target_downlinkoffnum; |
| 2299 |
|
| 2300 |
topaque = BTPageGetOpaque(state->target); |
| 2301 |
|
| 2302 |
if (!offset_is_negative_infinity(topaque, pivotkey_offset)) |
| 2303 |
{ |
| 2304 |
/* |
| 2305 |
* If we're looking for the next pivot tuple in target page, |
| 2306 |
* but there is no more pivot tuples, then we should match to |
| 2307 |
* high key instead. |
| 2308 |
*/ |
| 2309 |
if (pivotkey_offset > PageGetMaxOffsetNumber(state->target)) |
| 2310 |
{ |
| 2311 |
if (P_RIGHTMOST(topaque)) |
| 2312 |
ereport(ERROR, |
| 2313 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2314 |
errmsg("child high key is greater than rightmost pivot key on target level in index \"%s\"", |
| 2315 |
RelationGetRelationName(state->rel)), |
| 2316 |
errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.", |
| 2317 |
state->targetblock, blkno, |
| 2318 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 2319 |
pivotkey_offset = P_HIKEY; |
| 2320 |
} |
| 2321 |
itemid = PageGetItemIdCareful(state, state->targetblock, |
| 2322 |
state->target, pivotkey_offset); |
| 2323 |
itup = (IndexTuple) PageGetItem(state->target, itemid); |
| 2324 |
} |
| 2325 |
else |
| 2326 |
{ |
| 2327 |
/* |
| 2328 |
* We cannot try to match child's high key to a negative |
| 2329 |
* infinity key in target, since there is nothing to compare. |
| 2330 |
* However, it's still possible to match child's high key |
| 2331 |
* outside of target page. The reason why we're are is that |
| 2332 |
* bt_child_highkey_check() was previously called for the |
| 2333 |
* cousin page of 'loaded_child', which is incomplete split. |
| 2334 |
* So, now we traverse to the right of that cousin page and |
| 2335 |
* current child level page under consideration still belongs |
| 2336 |
* to the subtree of target's left sibling. Thus, we need to |
| 2337 |
* match child's high key to its left uncle page high key. |
| 2338 |
* Thankfully we saved it, it's called a "low key" of target |
| 2339 |
* page. |
| 2340 |
*/ |
| 2341 |
if (!state->lowkey) |
| 2342 |
ereport(ERROR, |
| 2343 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2344 |
errmsg("can't find left sibling high key in index \"%s\"", |
| 2345 |
RelationGetRelationName(state->rel)), |
| 2346 |
errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.", |
| 2347 |
state->targetblock, blkno, |
| 2348 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 2349 |
itup = state->lowkey; |
| 2350 |
} |
| 2351 |
|
| 2352 |
if (!bt_pivot_tuple_identical(state->heapkeyspace, highkey, itup)) |
| 2353 |
{ |
| 2354 |
ereport(ERROR, |
| 2355 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2356 |
errmsg("mismatch between parent key and child high key in index \"%s\"", |
| 2357 |
RelationGetRelationName(state->rel)), |
| 2358 |
errdetail_internal("Target block=%u child block=%u target page lsn=%X/%X.", |
| 2359 |
state->targetblock, blkno, |
| 2360 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 2361 |
} |
| 2362 |
} |
| 2363 |
|
| 2364 |
/* Exit if we already found next downlink */ |
| 2365 |
if (blkno == downlink) |
| 2366 |
{ |
| 2367 |
state->prevrightlink = opaque->btpo_next; |
| 2368 |
state->previncompletesplit = rightsplit; |
| 2369 |
return; |
| 2370 |
} |
| 2371 |
|
| 2372 |
/* Traverse to the next page using rightlink */ |
| 2373 |
blkno = opaque->btpo_next; |
| 2374 |
|
| 2375 |
/* Free page contents if it's allocated by us */ |
| 2376 |
if (page != loaded_child) |
| 2377 |
pfree(page); |
| 2378 |
first = false; |
| 2379 |
} |
| 2380 |
} |
| 2381 |
|
| 2382 |
/* |
| 2383 |
* Checks one of target's downlink against its child page. |
| 2384 |
* |
| 2385 |
* Conceptually, the target page continues to be what is checked here. The |
| 2386 |
* target block is still blamed in the event of finding an invariant violation. |
| 2387 |
* The downlink insertion into the target is probably where any problem raised |
| 2388 |
* here arises, and there is no such thing as a parent link, so doing the |
| 2389 |
* verification this way around is much more practical. |
| 2390 |
* |
| 2391 |
* This function visits child page and it's sequentially called for each |
| 2392 |
* downlink of target page. Assuming this we also check downlink connectivity |
| 2393 |
* here in order to save child page visits. |
| 2394 |
*/ |
| 2395 |
static void |
| 2396 |
bt_child_check(BtreeCheckState *state, BTScanInsert targetkey, |
| 2397 |
OffsetNumber downlinkoffnum) |
| 2398 |
{ |
| 2399 |
ItemId itemid; |
| 2400 |
IndexTuple itup; |
| 2401 |
BlockNumber childblock; |
| 2402 |
OffsetNumber offset; |
| 2403 |
OffsetNumber maxoffset; |
| 2404 |
Page child; |
| 2405 |
BTPageOpaque copaque; |
| 2406 |
BTPageOpaque topaque; |
| 2407 |
|
| 2408 |
itemid = PageGetItemIdCareful(state, state->targetblock, |
| 2409 |
state->target, downlinkoffnum); |
| 2410 |
itup = (IndexTuple) PageGetItem(state->target, itemid); |
| 2411 |
childblock = BTreeTupleGetDownLink(itup); |
| 2412 |
|
| 2413 |
/* |
| 2414 |
* Caller must have ShareLock on target relation, because of |
| 2415 |
* considerations around page deletion by VACUUM. |
| 2416 |
* |
| 2417 |
* NB: In general, page deletion deletes the right sibling's downlink, not |
| 2418 |
* the downlink of the page being deleted; the deleted page's downlink is |
| 2419 |
* reused for its sibling. The key space is thereby consolidated between |
| 2420 |
* the deleted page and its right sibling. (We cannot delete a parent |
| 2421 |
* page's rightmost child unless it is the last child page, and we intend |
| 2422 |
* to also delete the parent itself.) |
| 2423 |
* |
| 2424 |
* If this verification happened without a ShareLock, the following race |
| 2425 |
* condition could cause false positives: |
| 2426 |
* |
| 2427 |
* In general, concurrent page deletion might occur, including deletion of |
| 2428 |
* the left sibling of the child page that is examined here. If such a |
| 2429 |
* page deletion were to occur, closely followed by an insertion into the |
| 2430 |
* newly expanded key space of the child, a window for the false positive |
| 2431 |
* opens up: the stale parent/target downlink originally followed to get |
| 2432 |
* to the child legitimately ceases to be a lower bound on all items in |
| 2433 |
* the page, since the key space was concurrently expanded "left". |
| 2434 |
* (Insertion followed the "new" downlink for the child, not our now-stale |
| 2435 |
* downlink, which was concurrently physically removed in target/parent as |
| 2436 |
* part of deletion's first phase.) |
| 2437 |
* |
| 2438 |
* While we use various techniques elsewhere to perform cross-page |
| 2439 |
* verification for !readonly callers, a similar trick seems difficult |
| 2440 |
* here. The tricks used by bt_recheck_sibling_links and by |
| 2441 |
* bt_right_page_check_scankey both involve verification of a same-level, |
| 2442 |
* cross-sibling invariant. Cross-level invariants are far more squishy, |
| 2443 |
* though. The nbtree REDO routines do not actually couple buffer locks |
| 2444 |
* across levels during page splits, so making any cross-level check work |
| 2445 |
* reliably in !readonly mode may be impossible. |
| 2446 |
*/ |
| 2447 |
Assert(state->readonly); |
| 2448 |
|
| 2449 |
/* |
| 2450 |
* Verify child page has the downlink key from target page (its parent) as |
| 2451 |
* a lower bound; downlink must be strictly less than all keys on the |
| 2452 |
* page. |
| 2453 |
* |
| 2454 |
* Check all items, rather than checking just the first and trusting that |
| 2455 |
* the operator class obeys the transitive law. |
| 2456 |
*/ |
| 2457 |
topaque = BTPageGetOpaque(state->target); |
| 2458 |
child = palloc_btree_page(state, childblock); |
| 2459 |
copaque = BTPageGetOpaque(child); |
| 2460 |
maxoffset = PageGetMaxOffsetNumber(child); |
| 2461 |
|
| 2462 |
/* |
| 2463 |
* Since we've already loaded the child block, combine this check with |
| 2464 |
* check for downlink connectivity. |
| 2465 |
*/ |
| 2466 |
bt_child_highkey_check(state, downlinkoffnum, |
| 2467 |
child, topaque->btpo_level); |
| 2468 |
|
| 2469 |
/* |
| 2470 |
* Since there cannot be a concurrent VACUUM operation in readonly mode, |
| 2471 |
* and since a page has no links within other pages (siblings and parent) |
| 2472 |
* once it is marked fully deleted, it should be impossible to land on a |
| 2473 |
* fully deleted page. |
| 2474 |
* |
| 2475 |
* It does not quite make sense to enforce that the page cannot even be |
| 2476 |
* half-dead, despite the fact the downlink is modified at the same stage |
| 2477 |
* that the child leaf page is marked half-dead. That's incorrect because |
| 2478 |
* there may occasionally be multiple downlinks from a chain of pages |
| 2479 |
* undergoing deletion, where multiple successive calls are made to |
| 2480 |
* _bt_unlink_halfdead_page() by VACUUM before it can finally safely mark |
| 2481 |
* the leaf page as fully dead. While _bt_mark_page_halfdead() usually |
| 2482 |
* removes the downlink to the leaf page that is marked half-dead, that's |
| 2483 |
* not guaranteed, so it's possible we'll land on a half-dead page with a |
| 2484 |
* downlink due to an interrupted multi-level page deletion. |
| 2485 |
* |
| 2486 |
* We go ahead with our checks if the child page is half-dead. It's safe |
| 2487 |
* to do so because we do not test the child's high key, so it does not |
| 2488 |
* matter that the original high key will have been replaced by a dummy |
| 2489 |
* truncated high key within _bt_mark_page_halfdead(). All other page |
| 2490 |
* items are left intact on a half-dead page, so there is still something |
| 2491 |
* to test. |
| 2492 |
*/ |
| 2493 |
if (P_ISDELETED(copaque)) |
| 2494 |
ereport(ERROR, |
| 2495 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2496 |
errmsg("downlink to deleted page found in index \"%s\"", |
| 2497 |
RelationGetRelationName(state->rel)), |
| 2498 |
errdetail_internal("Parent block=%u child block=%u parent page lsn=%X/%X.", |
| 2499 |
state->targetblock, childblock, |
| 2500 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 2501 |
|
| 2502 |
for (offset = P_FIRSTDATAKEY(copaque); |
| 2503 |
offset <= maxoffset; |
| 2504 |
offset = OffsetNumberNext(offset)) |
| 2505 |
{ |
| 2506 |
/* |
| 2507 |
* Skip comparison of target page key against "negative infinity" |
| 2508 |
* item, if any. Checking it would indicate that it's not a strict |
| 2509 |
* lower bound, but that's only because of the hard-coding for |
| 2510 |
* negative infinity items within _bt_compare(). |
| 2511 |
* |
| 2512 |
* If nbtree didn't truncate negative infinity tuples during internal |
| 2513 |
* page splits then we'd expect child's negative infinity key to be |
| 2514 |
* equal to the scankey/downlink from target/parent (it would be a |
| 2515 |
* "low key" in this hypothetical scenario, and so it would still need |
| 2516 |
* to be treated as a special case here). |
| 2517 |
* |
| 2518 |
* Negative infinity items can be thought of as a strict lower bound |
| 2519 |
* that works transitively, with the last non-negative-infinity pivot |
| 2520 |
* followed during a descent from the root as its "true" strict lower |
| 2521 |
* bound. Only a small number of negative infinity items are truly |
| 2522 |
* negative infinity; those that are the first items of leftmost |
| 2523 |
* internal pages. In more general terms, a negative infinity item is |
| 2524 |
* only negative infinity with respect to the subtree that the page is |
| 2525 |
* at the root of. |
| 2526 |
* |
| 2527 |
* See also: bt_rootdescend(), which can even detect transitive |
| 2528 |
* inconsistencies on cousin leaf pages. |
| 2529 |
*/ |
| 2530 |
if (offset_is_negative_infinity(copaque, offset)) |
| 2531 |
continue; |
| 2532 |
|
| 2533 |
if (!invariant_l_nontarget_offset(state, targetkey, childblock, child, |
| 2534 |
offset)) |
| 2535 |
ereport(ERROR, |
| 2536 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2537 |
errmsg("down-link lower bound invariant violated for index \"%s\"", |
| 2538 |
RelationGetRelationName(state->rel)), |
| 2539 |
errdetail_internal("Parent block=%u child index tid=(%u,%u) parent page lsn=%X/%X.", |
| 2540 |
state->targetblock, childblock, offset, |
| 2541 |
LSN_FORMAT_ARGS(state->targetlsn)))); |
| 2542 |
} |
| 2543 |
|
| 2544 |
pfree(child); |
| 2545 |
} |
| 2546 |
|
| 2547 |
/* |
| 2548 |
* Checks if page is missing a downlink that it should have. |
| 2549 |
* |
| 2550 |
* A page that lacks a downlink/parent may indicate corruption. However, we |
| 2551 |
* must account for the fact that a missing downlink can occasionally be |
| 2552 |
* encountered in a non-corrupt index. This can be due to an interrupted page |
| 2553 |
* split, or an interrupted multi-level page deletion (i.e. there was a hard |
| 2554 |
* crash or an error during a page split, or while VACUUM was deleting a |
| 2555 |
* multi-level chain of pages). |
| 2556 |
* |
| 2557 |
* Note that this can only be called in readonly mode, so there is no need to |
| 2558 |
* be concerned about concurrent page splits or page deletions. |
| 2559 |
*/ |
| 2560 |
static void |
| 2561 |
bt_downlink_missing_check(BtreeCheckState *state, bool rightsplit, |
| 2562 |
BlockNumber blkno, Page page) |
| 2563 |
{ |
| 2564 |
BTPageOpaque opaque = BTPageGetOpaque(page); |
| 2565 |
ItemId itemid; |
| 2566 |
IndexTuple itup; |
| 2567 |
Page child; |
| 2568 |
BTPageOpaque copaque; |
| 2569 |
uint32 level; |
| 2570 |
BlockNumber childblk; |
| 2571 |
XLogRecPtr pagelsn; |
| 2572 |
|
| 2573 |
Assert(state->readonly); |
| 2574 |
Assert(!P_IGNORE(opaque)); |
| 2575 |
|
| 2576 |
/* No next level up with downlinks to fingerprint from the true root */ |
| 2577 |
if (P_ISROOT(opaque)) |
| 2578 |
return; |
| 2579 |
|
| 2580 |
pagelsn = PageGetLSN(page); |
| 2581 |
|
| 2582 |
/* |
| 2583 |
* Incomplete (interrupted) page splits can account for the lack of a |
| 2584 |
* downlink. Some inserting transaction should eventually complete the |
| 2585 |
* page split in passing, when it notices that the left sibling page is |
| 2586 |
* P_INCOMPLETE_SPLIT(). |
| 2587 |
* |
| 2588 |
* In general, VACUUM is not prepared for there to be no downlink to a |
| 2589 |
* page that it deletes. This is the main reason why the lack of a |
| 2590 |
* downlink can be reported as corruption here. It's not obvious that an |
| 2591 |
* invalid missing downlink can result in wrong answers to queries, |
| 2592 |
* though, since index scans that land on the child may end up |
| 2593 |
* consistently moving right. The handling of concurrent page splits (and |
| 2594 |
* page deletions) within _bt_moveright() cannot distinguish |
| 2595 |
* inconsistencies that last for a moment from inconsistencies that are |
| 2596 |
* permanent and irrecoverable. |
| 2597 |
* |
| 2598 |
* VACUUM isn't even prepared to delete pages that have no downlink due to |
| 2599 |
* an incomplete page split, but it can detect and reason about that case |
| 2600 |
* by design, so it shouldn't be taken to indicate corruption. See |
| 2601 |
* _bt_pagedel() for full details. |
| 2602 |
*/ |
| 2603 |
if (rightsplit) |
| 2604 |
{ |
| 2605 |
ereport(DEBUG1, |
| 2606 |
(errcode(ERRCODE_NO_DATA), |
| 2607 |
errmsg_internal("harmless interrupted page split detected in index \"%s\"", |
| 2608 |
RelationGetRelationName(state->rel)), |
| 2609 |
errdetail_internal("Block=%u level=%u left sibling=%u page lsn=%X/%X.", |
| 2610 |
blkno, opaque->btpo_level, |
| 2611 |
opaque->btpo_prev, |
| 2612 |
LSN_FORMAT_ARGS(pagelsn)))); |
| 2613 |
return; |
| 2614 |
} |
| 2615 |
|
| 2616 |
/* |
| 2617 |
* Page under check is probably the "top parent" of a multi-level page |
| 2618 |
* deletion. We'll need to descend the subtree to make sure that |
| 2619 |
* descendant pages are consistent with that, though. |
| 2620 |
* |
| 2621 |
* If the page (which must be non-ignorable) is a leaf page, then clearly |
| 2622 |
* it can't be the top parent. The lack of a downlink is probably a |
| 2623 |
* symptom of a broad problem that could just as easily cause |
| 2624 |
* inconsistencies anywhere else. |
| 2625 |
*/ |
| 2626 |
if (P_ISLEAF(opaque)) |
| 2627 |
ereport(ERROR, |
| 2628 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2629 |
errmsg("leaf index block lacks downlink in index \"%s\"", |
| 2630 |
RelationGetRelationName(state->rel)), |
| 2631 |
errdetail_internal("Block=%u page lsn=%X/%X.", |
| 2632 |
blkno, |
| 2633 |
LSN_FORMAT_ARGS(pagelsn)))); |
| 2634 |
|
| 2635 |
/* Descend from the given page, which is an internal page */ |
| 2636 |
elog(DEBUG1, "checking for interrupted multi-level deletion due to missing downlink in index \"%s\"", |
| 2637 |
RelationGetRelationName(state->rel)); |
| 2638 |
|
| 2639 |
level = opaque->btpo_level; |
| 2640 |
itemid = PageGetItemIdCareful(state, blkno, page, P_FIRSTDATAKEY(opaque)); |
| 2641 |
itup = (IndexTuple) PageGetItem(page, itemid); |
| 2642 |
childblk = BTreeTupleGetDownLink(itup); |
| 2643 |
for (;;) |
| 2644 |
{ |
| 2645 |
CHECK_FOR_INTERRUPTS(); |
| 2646 |
|
| 2647 |
child = palloc_btree_page(state, childblk); |
| 2648 |
copaque = BTPageGetOpaque(child); |
| 2649 |
|
| 2650 |
if (P_ISLEAF(copaque)) |
| 2651 |
break; |
| 2652 |
|
| 2653 |
/* Do an extra sanity check in passing on internal pages */ |
| 2654 |
if (copaque->btpo_level != level - 1) |
| 2655 |
ereport(ERROR, |
| 2656 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2657 |
errmsg_internal("downlink points to block in index \"%s\" whose level is not one level down", |
| 2658 |
RelationGetRelationName(state->rel)), |
| 2659 |
errdetail_internal("Top parent/under check block=%u block pointed to=%u expected level=%u level in pointed to block=%u.", |
| 2660 |
blkno, childblk, |
| 2661 |
level - 1, copaque->btpo_level))); |
| 2662 |
|
| 2663 |
level = copaque->btpo_level; |
| 2664 |
itemid = PageGetItemIdCareful(state, childblk, child, |
| 2665 |
P_FIRSTDATAKEY(copaque)); |
| 2666 |
itup = (IndexTuple) PageGetItem(child, itemid); |
| 2667 |
childblk = BTreeTupleGetDownLink(itup); |
| 2668 |
/* Be slightly more pro-active in freeing this memory, just in case */ |
| 2669 |
pfree(child); |
| 2670 |
} |
| 2671 |
|
| 2672 |
/* |
| 2673 |
* Since there cannot be a concurrent VACUUM operation in readonly mode, |
| 2674 |
* and since a page has no links within other pages (siblings and parent) |
| 2675 |
* once it is marked fully deleted, it should be impossible to land on a |
| 2676 |
* fully deleted page. See bt_child_check() for further details. |
| 2677 |
* |
| 2678 |
* The bt_child_check() P_ISDELETED() check is repeated here because |
| 2679 |
* bt_child_check() does not visit pages reachable through negative |
| 2680 |
* infinity items. Besides, bt_child_check() is unwilling to descend |
| 2681 |
* multiple levels. (The similar bt_child_check() P_ISDELETED() check |
| 2682 |
* within bt_check_level_from_leftmost() won't reach the page either, |
| 2683 |
* since the leaf's live siblings should have their sibling links updated |
| 2684 |
* to bypass the deletion target page when it is marked fully dead.) |
| 2685 |
* |
| 2686 |
* If this error is raised, it might be due to a previous multi-level page |
| 2687 |
* deletion that failed to realize that it wasn't yet safe to mark the |
| 2688 |
* leaf page as fully dead. A "dangling downlink" will still remain when |
| 2689 |
* this happens. The fact that the dangling downlink's page (the leaf's |
| 2690 |
* parent/ancestor page) lacked a downlink is incidental. |
| 2691 |
*/ |
| 2692 |
if (P_ISDELETED(copaque)) |
| 2693 |
ereport(ERROR, |
| 2694 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2695 |
errmsg_internal("downlink to deleted leaf page found in index \"%s\"", |
| 2696 |
RelationGetRelationName(state->rel)), |
| 2697 |
errdetail_internal("Top parent/target block=%u leaf block=%u top parent/under check lsn=%X/%X.", |
| 2698 |
blkno, childblk, |
| 2699 |
LSN_FORMAT_ARGS(pagelsn)))); |
| 2700 |
|
| 2701 |
/* |
| 2702 |
* Iff leaf page is half-dead, its high key top parent link should point |
| 2703 |
* to what VACUUM considered to be the top parent page at the instant it |
| 2704 |
* was interrupted. Provided the high key link actually points to the |
| 2705 |
* page under check, the missing downlink we detected is consistent with |
| 2706 |
* there having been an interrupted multi-level page deletion. This means |
| 2707 |
* that the subtree with the page under check at its root (a page deletion |
| 2708 |
* chain) is in a consistent state, enabling VACUUM to resume deleting the |
| 2709 |
* entire chain the next time it encounters the half-dead leaf page. |
| 2710 |
*/ |
| 2711 |
if (P_ISHALFDEAD(copaque) && !P_RIGHTMOST(copaque)) |
| 2712 |
{ |
| 2713 |
itemid = PageGetItemIdCareful(state, childblk, child, P_HIKEY); |
| 2714 |
itup = (IndexTuple) PageGetItem(child, itemid); |
| 2715 |
if (BTreeTupleGetTopParent(itup) == blkno) |
| 2716 |
return; |
| 2717 |
} |
| 2718 |
|
| 2719 |
ereport(ERROR, |
| 2720 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2721 |
errmsg("internal index block lacks downlink in index \"%s\"", |
| 2722 |
RelationGetRelationName(state->rel)), |
| 2723 |
errdetail_internal("Block=%u level=%u page lsn=%X/%X.", |
| 2724 |
blkno, opaque->btpo_level, |
| 2725 |
LSN_FORMAT_ARGS(pagelsn)))); |
| 2726 |
} |
| 2727 |
|
| 2728 |
/* |
| 2729 |
* Per-tuple callback from table_index_build_scan, used to determine if index has |
| 2730 |
* all the entries that definitely should have been observed in leaf pages of |
| 2731 |
* the target index (that is, all IndexTuples that were fingerprinted by our |
| 2732 |
* Bloom filter). All heapallindexed checks occur here. |
| 2733 |
* |
| 2734 |
* The redundancy between an index and the table it indexes provides a good |
| 2735 |
* opportunity to detect corruption, especially corruption within the table. |
| 2736 |
* The high level principle behind the verification performed here is that any |
| 2737 |
* IndexTuple that should be in an index following a fresh CREATE INDEX (based |
| 2738 |
* on the same index definition) should also have been in the original, |
| 2739 |
* existing index, which should have used exactly the same representation |
| 2740 |
* |
| 2741 |
* Since the overall structure of the index has already been verified, the most |
| 2742 |
* likely explanation for error here is a corrupt heap page (could be logical |
| 2743 |
* or physical corruption). Index corruption may still be detected here, |
| 2744 |
* though. Only readonly callers will have verified that left links and right |
| 2745 |
* links are in agreement, and so it's possible that a leaf page transposition |
| 2746 |
* within index is actually the source of corruption detected here (for |
| 2747 |
* !readonly callers). The checks performed only for readonly callers might |
| 2748 |
* more accurately frame the problem as a cross-page invariant issue (this |
| 2749 |
* could even be due to recovery not replaying all WAL records). The !readonly |
| 2750 |
* ERROR message raised here includes a HINT about retrying with readonly |
| 2751 |
* verification, just in case it's a cross-page invariant issue, though that |
| 2752 |
* isn't particularly likely. |
| 2753 |
* |
| 2754 |
* table_index_build_scan() expects to be able to find the root tuple when a |
| 2755 |
* heap-only tuple (the live tuple at the end of some HOT chain) needs to be |
| 2756 |
* indexed, in order to replace the actual tuple's TID with the root tuple's |
| 2757 |
* TID (which is what we're actually passed back here). The index build heap |
| 2758 |
* scan code will raise an error when a tuple that claims to be the root of the |
| 2759 |
* heap-only tuple's HOT chain cannot be located. This catches cases where the |
| 2760 |
* original root item offset/root tuple for a HOT chain indicates (for whatever |
| 2761 |
* reason) that the entire HOT chain is dead, despite the fact that the latest |
| 2762 |
* heap-only tuple should be indexed. When this happens, sequential scans may |
| 2763 |
* always give correct answers, and all indexes may be considered structurally |
| 2764 |
* consistent (i.e. the nbtree structural checks would not detect corruption). |
| 2765 |
* It may be the case that only index scans give wrong answers, and yet heap or |
| 2766 |
* SLRU corruption is the real culprit. (While it's true that LP_DEAD bit |
| 2767 |
* setting will probably also leave the index in a corrupt state before too |
| 2768 |
* long, the problem is nonetheless that there is heap corruption.) |
| 2769 |
* |
| 2770 |
* Heap-only tuple handling within table_index_build_scan() works in a way that |
| 2771 |
* helps us to detect index tuples that contain the wrong values (values that |
| 2772 |
* don't match the latest tuple in the HOT chain). This can happen when there |
| 2773 |
* is no superseding index tuple due to a faulty assessment of HOT safety, |
| 2774 |
* perhaps during the original CREATE INDEX. Because the latest tuple's |
| 2775 |
* contents are used with the root TID, an error will be raised when a tuple |
| 2776 |
* with the same TID but non-matching attribute values is passed back to us. |
| 2777 |
* Faulty assessment of HOT-safety was behind at least two distinct CREATE |
| 2778 |
* INDEX CONCURRENTLY bugs that made it into stable releases, one of which was |
| 2779 |
* undetected for many years. In short, the same principle that allows a |
| 2780 |
* REINDEX to repair corruption when there was an (undetected) broken HOT chain |
| 2781 |
* also allows us to detect the corruption in many cases. |
| 2782 |
*/ |
| 2783 |
static void |
| 2784 |
bt_tuple_present_callback(Relation index, ItemPointer tid, Datum *values, |
| 2785 |
bool *isnull, bool tupleIsAlive, void *checkstate) |
| 2786 |
{ |
| 2787 |
BtreeCheckState *state = (BtreeCheckState *) checkstate; |
| 2788 |
IndexTuple itup, |
| 2789 |
norm; |
| 2790 |
|
| 2791 |
Assert(state->heapallindexed); |
| 2792 |
|
| 2793 |
/* Generate a normalized index tuple for fingerprinting */ |
| 2794 |
itup = index_form_tuple(RelationGetDescr(index), values, isnull); |
| 2795 |
itup->t_tid = *tid; |
| 2796 |
norm = bt_normalize_tuple(state, itup); |
| 2797 |
|
| 2798 |
/* Probe Bloom filter -- tuple should be present */ |
| 2799 |
if (bloom_lacks_element(state->filter, (unsigned char *) norm, |
| 2800 |
IndexTupleSize(norm))) |
| 2801 |
ereport(ERROR, |
| 2802 |
(errcode(ERRCODE_DATA_CORRUPTED), |
| 2803 |
errmsg("heap tuple (%u,%u) from table \"%s\" lacks matching index tuple within index \"%s\"", |
| 2804 |
ItemPointerGetBlockNumber(&(itup->t_tid)), |
| 2805 |
ItemPointerGetOffsetNumber(&(itup->t_tid)), |
| 2806 |
RelationGetRelationName(state->heaprel), |
| 2807 |
RelationGetRelationName(state->rel)), |
| 2808 |
!state->readonly |
| 2809 |
? errhint("Retrying verification using the function bt_index_parent_check() might provide a more specific error.") |
| 2810 |
: 0)); |
| 2811 |
|
| 2812 |
state->heaptuplespresent++; |
| 2813 |
pfree(itup); |
| 2814 |
/* Cannot leak memory here */ |
| 2815 |
if (norm != itup) |
| 2816 |
pfree(norm); |
| 2817 |
} |
| 2818 |
|
| 2819 |
/* |
| 2820 |
* Normalize an index tuple for fingerprinting. |
| 2821 |
* |
| 2822 |
* In general, index tuple formation is assumed to be deterministic by |
| 2823 |
* heapallindexed verification, and IndexTuples are assumed immutable. While |
| 2824 |
* the LP_DEAD bit is mutable in leaf pages, that's ItemId metadata, which is |
| 2825 |
* not fingerprinted. Normalization is required to compensate for corner |
| 2826 |
* cases where the determinism assumption doesn't quite work. |
| 2827 |
* |
| 2828 |
* There is currently one such case: index_form_tuple() does not try to hide |
| 2829 |
* the source TOAST state of input datums. The executor applies TOAST |
| 2830 |
* compression for heap tuples based on different criteria to the compression |
| 2831 |
* applied within btinsert()'s call to index_form_tuple(): it sometimes |
| 2832 |
* compresses more aggressively, resulting in compressed heap tuple datums but |
| 2833 |
* uncompressed corresponding index tuple datums. A subsequent heapallindexed |
| 2834 |
* verification will get a logically equivalent though bitwise unequal tuple |
| 2835 |
* from index_form_tuple(). False positive heapallindexed corruption reports |
| 2836 |
* could occur without normalizing away the inconsistency. |
| 2837 |
* |
| 2838 |
* Returned tuple is often caller's own original tuple. Otherwise, it is a |
| 2839 |
* new representation of caller's original index tuple, palloc()'d in caller's |
| 2840 |
* memory context. |
| 2841 |
* |
| 2842 |
* Note: This routine is not concerned with distinctions about the |
| 2843 |
* representation of tuples beyond those that might break heapallindexed |
| 2844 |
* verification. In particular, it won't try to normalize opclass-equal |
| 2845 |
* datums with potentially distinct representations (e.g., btree/numeric_ops |
| 2846 |
* index datums will not get their display scale normalized-away here). |
| 2847 |
* Caller does normalization for non-pivot tuples that have a posting list, |
| 2848 |
* since dummy CREATE INDEX callback code generates new tuples with the same |
| 2849 |
* normalized representation. |
| 2850 |
*/ |
| 2851 |
static IndexTuple |
| 2852 |
bt_normalize_tuple(BtreeCheckState *state, IndexTuple itup) |
| 2853 |
{ |
| 2854 |
TupleDesc tupleDescriptor = RelationGetDescr(state->rel); |
| 2855 |
Datum normalized[INDEX_MAX_KEYS]; |
| 2856 |
bool isnull[INDEX_MAX_KEYS]; |
| 2857 |
bool need_free[INDEX_MAX_KEYS]; |
| 2858 |
bool formnewtup = false; |
| 2859 |
IndexTuple reformed; |
| 2860 |
int i; |
| 2861 |
|
| 2862 |
/* Caller should only pass "logical" non-pivot tuples here */ |
| 2863 |
Assert(!BTreeTupleIsPosting(itup) && !BTreeTupleIsPivot(itup)); |
| 2864 |
|
| 2865 |
/* Easy case: It's immediately clear that tuple has no varlena datums */ |
| 2866 |
if (!IndexTupleHasVarwidths(itup)) |
| 2867 |
return itup; |
| 2868 |
|
| 2869 |
for (i = 0; i < tupleDescriptor->natts; i++) |
| 2870 |
{ |
| 2871 |
Form_pg_attribute att; |
| 2872 |
|
| 2873 |
att = TupleDescAttr(tupleDescriptor, i); |
| 2874 |
|
| 2875 |
/* Assume untoasted/already normalized datum initially */ |
| 2876 |
need_free[i] = false; |
| 2877 |
normalized[i] = index_getattr(itup, att->attnum, |
| 2878 |
tupleDescriptor, |
| 2879 |
&isnull[i]); |
| 2880 |
if (att->attbyval || att->attlen != -1 || isnull[i]) |
| 2881 |
continue; |
| 2882 |
|
| 2883 |
/* |
| 2884 |
* Callers always pass a tuple that could safely be inserted into the |
| 2885 |
* index without further processing, so an external varlena header |
| 2886 |
* should never be encountered here |
| 2887 |
*/ |
| 2888 |
if (VARATT_IS_EXTERNAL(DatumGetPointer(normalized[i]))) |
| 2889 |
ereport(ERROR, |
| 2890 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 2891 |
errmsg("external varlena datum in tuple that references heap row (%u,%u) in index \"%s\"", |
| 2892 |
ItemPointerGetBlockNumber(&(itup->t_tid)), |
| 2893 |
ItemPointerGetOffsetNumber(&(itup->t_tid)), |
| 2894 |
RelationGetRelationName(state->rel)))); |
| 2895 |
else if (!VARATT_IS_COMPRESSED(DatumGetPointer(normalized[i])) && |
| 2896 |
VARSIZE_ANY(DatumGetPointer(normalized[i])) > TOAST_INDEX_TARGET && |
| 2897 |
(att->attstorage == TYPSTORAGE_EXTENDED || |
| 2898 |
att->attstorage == TYPSTORAGE_MAIN)) |
| 2899 |
{ |
| 2900 |
/* |
| 2901 |
* This value will be compressed by index_form_tuple() with the |
| 2902 |
* current storage settings. We may be here because this tuple |
| 2903 |
* was formed with different storage settings. So, force forming. |
| 2904 |
*/ |
| 2905 |
formnewtup = true; |
| 2906 |
} |
| 2907 |
else if (VARATT_IS_COMPRESSED(DatumGetPointer(normalized[i]))) |
| 2908 |
{ |
| 2909 |
formnewtup = true; |
| 2910 |
normalized[i] = PointerGetDatum(PG_DETOAST_DATUM(normalized[i])); |
| 2911 |
need_free[i] = true; |
| 2912 |
} |
| 2913 |
|
| 2914 |
/* |
| 2915 |
* Short tuples may have 1B or 4B header. Convert 4B header of short |
| 2916 |
* tuples to 1B |
| 2917 |
*/ |
| 2918 |
else if (VARATT_CAN_MAKE_SHORT(DatumGetPointer(normalized[i]))) |
| 2919 |
{ |
| 2920 |
/* convert to short varlena */ |
| 2921 |
Size len = VARATT_CONVERTED_SHORT_SIZE(DatumGetPointer(normalized[i])); |
| 2922 |
char *data = palloc(len); |
| 2923 |
|
| 2924 |
SET_VARSIZE_SHORT(data, len); |
| 2925 |
memcpy(data + 1, VARDATA(DatumGetPointer(normalized[i])), len - 1); |
| 2926 |
|
| 2927 |
formnewtup = true; |
| 2928 |
normalized[i] = PointerGetDatum(data); |
| 2929 |
need_free[i] = true; |
| 2930 |
} |
| 2931 |
} |
| 2932 |
|
| 2933 |
/* |
| 2934 |
* Easier case: Tuple has varlena datums, none of which are compressed or |
| 2935 |
* short with 4B header |
| 2936 |
*/ |
| 2937 |
if (!formnewtup) |
| 2938 |
return itup; |
| 2939 |
|
| 2940 |
/* |
| 2941 |
* Hard case: Tuple had compressed varlena datums that necessitate |
| 2942 |
* creating normalized version of the tuple from uncompressed input datums |
| 2943 |
* (normalized input datums). This is rather naive, but shouldn't be |
| 2944 |
* necessary too often. |
| 2945 |
* |
| 2946 |
* In the heap, tuples may contain short varlena datums with both 1B |
| 2947 |
* header and 4B headers. But the corresponding index tuple should always |
| 2948 |
* have such varlena's with 1B headers. So, if there is a short varlena |
| 2949 |
* with 4B header, we need to convert it for fingerprinting. |
| 2950 |
* |
| 2951 |
* Note that we rely on deterministic index_form_tuple() TOAST compression |
| 2952 |
* of normalized input. |
| 2953 |
*/ |
| 2954 |
reformed = index_form_tuple(tupleDescriptor, normalized, isnull); |
| 2955 |
reformed->t_tid = itup->t_tid; |
| 2956 |
|
| 2957 |
/* Cannot leak memory here */ |
| 2958 |
for (i = 0; i < tupleDescriptor->natts; i++) |
| 2959 |
if (need_free[i]) |
| 2960 |
pfree(DatumGetPointer(normalized[i])); |
| 2961 |
|
| 2962 |
return reformed; |
| 2963 |
} |
| 2964 |
|
| 2965 |
/* |
| 2966 |
* Produce palloc()'d "plain" tuple for nth posting list entry/TID. |
| 2967 |
* |
| 2968 |
* In general, deduplication is not supposed to change the logical contents of |
| 2969 |
* an index. Multiple index tuples are merged together into one equivalent |
| 2970 |
* posting list index tuple when convenient. |
| 2971 |
* |
| 2972 |
* heapallindexed verification must normalize-away this variation in |
| 2973 |
* representation by converting posting list tuples into two or more "plain" |
| 2974 |
* tuples. Each tuple must be fingerprinted separately -- there must be one |
| 2975 |
* tuple for each corresponding Bloom filter probe during the heap scan. |
| 2976 |
* |
| 2977 |
* Note: Caller still needs to call bt_normalize_tuple() with returned tuple. |
| 2978 |
*/ |
| 2979 |
static inline IndexTuple |
| 2980 |
bt_posting_plain_tuple(IndexTuple itup, int n) |
| 2981 |
{ |
| 2982 |
Assert(BTreeTupleIsPosting(itup)); |
| 2983 |
|
| 2984 |
/* Returns non-posting-list tuple */ |
| 2985 |
return _bt_form_posting(itup, BTreeTupleGetPostingN(itup, n), 1); |
| 2986 |
} |
| 2987 |
|
| 2988 |
/* |
| 2989 |
* Search for itup in index, starting from fast root page. itup must be a |
| 2990 |
* non-pivot tuple. This is only supported with heapkeyspace indexes, since |
| 2991 |
* we rely on having fully unique keys to find a match with only a single |
| 2992 |
* visit to a leaf page, barring an interrupted page split, where we may have |
| 2993 |
* to move right. (A concurrent page split is impossible because caller must |
| 2994 |
* be readonly caller.) |
| 2995 |
* |
| 2996 |
* This routine can detect very subtle transitive consistency issues across |
| 2997 |
* more than one level of the tree. Leaf pages all have a high key (even the |
| 2998 |
* rightmost page has a conceptual positive infinity high key), but not a low |
| 2999 |
* key. Their downlink in parent is a lower bound, which along with the high |
| 3000 |
* key is almost enough to detect every possible inconsistency. A downlink |
| 3001 |
* separator key value won't always be available from parent, though, because |
| 3002 |
* the first items of internal pages are negative infinity items, truncated |
| 3003 |
* down to zero attributes during internal page splits. While it's true that |
| 3004 |
* bt_child_check() and the high key check can detect most imaginable key |
| 3005 |
* space problems, there are remaining problems it won't detect with non-pivot |
| 3006 |
* tuples in cousin leaf pages. Starting a search from the root for every |
| 3007 |
* existing leaf tuple detects small inconsistencies in upper levels of the |
| 3008 |
* tree that cannot be detected any other way. (Besides all this, this is |
| 3009 |
* probably also useful as a direct test of the code used by index scans |
| 3010 |
* themselves.) |
| 3011 |
*/ |
| 3012 |
static bool |
| 3013 |
bt_rootdescend(BtreeCheckState *state, IndexTuple itup) |
| 3014 |
{ |
| 3015 |
BTScanInsert key; |
| 3016 |
BTStack stack; |
| 3017 |
Buffer lbuf; |
| 3018 |
bool exists; |
| 3019 |
|
| 3020 |
key = _bt_mkscankey(state->rel, itup); |
| 3021 |
Assert(key->heapkeyspace && key->scantid != NULL); |
| 3022 |
|
| 3023 |
/* |
| 3024 |
* Search from root. |
| 3025 |
* |
| 3026 |
* Ideally, we would arrange to only move right within _bt_search() when |
| 3027 |
* an interrupted page split is detected (i.e. when the incomplete split |
| 3028 |
* bit is found to be set), but for now we accept the possibility that |
| 3029 |
* that could conceal an inconsistency. |
| 3030 |
*/ |
| 3031 |
Assert(state->readonly && state->rootdescend); |
| 3032 |
exists = false; |
| 3033 |
stack = _bt_search(state->rel, NULL, key, &lbuf, BT_READ); |
| 3034 |
|
| 3035 |
if (BufferIsValid(lbuf)) |
| 3036 |
{ |
| 3037 |
BTInsertStateData insertstate; |
| 3038 |
OffsetNumber offnum; |
| 3039 |
Page page; |
| 3040 |
|
| 3041 |
insertstate.itup = itup; |
| 3042 |
insertstate.itemsz = MAXALIGN(IndexTupleSize(itup)); |
| 3043 |
insertstate.itup_key = key; |
| 3044 |
insertstate.postingoff = 0; |
| 3045 |
insertstate.bounds_valid = false; |
| 3046 |
insertstate.buf = lbuf; |
| 3047 |
|
| 3048 |
/* Get matching tuple on leaf page */ |
| 3049 |
offnum = _bt_binsrch_insert(state->rel, &insertstate); |
| 3050 |
/* Compare first >= matching item on leaf page, if any */ |
| 3051 |
page = BufferGetPage(lbuf); |
| 3052 |
/* Should match on first heap TID when tuple has a posting list */ |
| 3053 |
if (offnum <= PageGetMaxOffsetNumber(page) && |
| 3054 |
insertstate.postingoff <= 0 && |
| 3055 |
_bt_compare(state->rel, key, page, offnum) == 0) |
| 3056 |
exists = true; |
| 3057 |
_bt_relbuf(state->rel, lbuf); |
| 3058 |
} |
| 3059 |
|
| 3060 |
_bt_freestack(stack); |
| 3061 |
pfree(key); |
| 3062 |
|
| 3063 |
return exists; |
| 3064 |
} |
| 3065 |
|
| 3066 |
/* |
| 3067 |
* Is particular offset within page (whose special state is passed by caller) |
| 3068 |
* the page negative-infinity item? |
| 3069 |
* |
| 3070 |
* As noted in comments above _bt_compare(), there is special handling of the |
| 3071 |
* first data item as a "negative infinity" item. The hard-coding within |
| 3072 |
* _bt_compare() makes comparing this item for the purposes of verification |
| 3073 |
* pointless at best, since the IndexTuple only contains a valid TID (a |
| 3074 |
* reference TID to child page). |
| 3075 |
*/ |
| 3076 |
static inline bool |
| 3077 |
offset_is_negative_infinity(BTPageOpaque opaque, OffsetNumber offset) |
| 3078 |
{ |
| 3079 |
/* |
| 3080 |
* For internal pages only, the first item after high key, if any, is |
| 3081 |
* negative infinity item. Internal pages always have a negative infinity |
| 3082 |
* item, whereas leaf pages never have one. This implies that negative |
| 3083 |
* infinity item is either first or second line item, or there is none |
| 3084 |
* within page. |
| 3085 |
* |
| 3086 |
* Negative infinity items are a special case among pivot tuples. They |
| 3087 |
* always have zero attributes, while all other pivot tuples always have |
| 3088 |
* nkeyatts attributes. |
| 3089 |
* |
| 3090 |
* Right-most pages don't have a high key, but could be said to |
| 3091 |
* conceptually have a "positive infinity" high key. Thus, there is a |
| 3092 |
* symmetry between down link items in parent pages, and high keys in |
| 3093 |
* children. Together, they represent the part of the key space that |
| 3094 |
* belongs to each page in the index. For example, all children of the |
| 3095 |
* root page will have negative infinity as a lower bound from root |
| 3096 |
* negative infinity downlink, and positive infinity as an upper bound |
| 3097 |
* (implicitly, from "imaginary" positive infinity high key in root). |
| 3098 |
*/ |
| 3099 |
return !P_ISLEAF(opaque) && offset == P_FIRSTDATAKEY(opaque); |
| 3100 |
} |
| 3101 |
|
| 3102 |
/* |
| 3103 |
* Does the invariant hold that the key is strictly less than a given upper |
| 3104 |
* bound offset item? |
| 3105 |
* |
| 3106 |
* Verifies line pointer on behalf of caller. |
| 3107 |
* |
| 3108 |
* If this function returns false, convention is that caller throws error due |
| 3109 |
* to corruption. |
| 3110 |
*/ |
| 3111 |
static inline bool |
| 3112 |
invariant_l_offset(BtreeCheckState *state, BTScanInsert key, |
| 3113 |
OffsetNumber upperbound) |
| 3114 |
{ |
| 3115 |
ItemId itemid; |
| 3116 |
int32 cmp; |
| 3117 |
|
| 3118 |
Assert(!key->nextkey && key->backward); |
| 3119 |
|
| 3120 |
/* Verify line pointer before checking tuple */ |
| 3121 |
itemid = PageGetItemIdCareful(state, state->targetblock, state->target, |
| 3122 |
upperbound); |
| 3123 |
/* pg_upgrade'd indexes may legally have equal sibling tuples */ |
| 3124 |
if (!key->heapkeyspace) |
| 3125 |
return invariant_leq_offset(state, key, upperbound); |
| 3126 |
|
| 3127 |
cmp = _bt_compare(state->rel, key, state->target, upperbound); |
| 3128 |
|
| 3129 |
/* |
| 3130 |
* _bt_compare() is capable of determining that a scankey with a |
| 3131 |
* filled-out attribute is greater than pivot tuples where the comparison |
| 3132 |
* is resolved at a truncated attribute (value of attribute in pivot is |
| 3133 |
* minus infinity). However, it is not capable of determining that a |
| 3134 |
* scankey is _less than_ a tuple on the basis of a comparison resolved at |
| 3135 |
* _scankey_ minus infinity attribute. Complete an extra step to simulate |
| 3136 |
* having minus infinity values for omitted scankey attribute(s). |
| 3137 |
*/ |
| 3138 |
if (cmp == 0) |
| 3139 |
{ |
| 3140 |
BTPageOpaque topaque; |
| 3141 |
IndexTuple ritup; |
| 3142 |
int uppnkeyatts; |
| 3143 |
ItemPointer rheaptid; |
| 3144 |
bool nonpivot; |
| 3145 |
|
| 3146 |
ritup = (IndexTuple) PageGetItem(state->target, itemid); |
| 3147 |
topaque = BTPageGetOpaque(state->target); |
| 3148 |
nonpivot = P_ISLEAF(topaque) && upperbound >= P_FIRSTDATAKEY(topaque); |
| 3149 |
|
| 3150 |
/* Get number of keys + heap TID for item to the right */ |
| 3151 |
uppnkeyatts = BTreeTupleGetNKeyAtts(ritup, state->rel); |
| 3152 |
rheaptid = BTreeTupleGetHeapTIDCareful(state, ritup, nonpivot); |
| 3153 |
|
| 3154 |
/* Heap TID is tiebreaker key attribute */ |
| 3155 |
if (key->keysz == uppnkeyatts) |
| 3156 |
return key->scantid == NULL && rheaptid != NULL; |
| 3157 |
|
| 3158 |
return key->keysz < uppnkeyatts; |
| 3159 |
} |
| 3160 |
|
| 3161 |
return cmp < 0; |
| 3162 |
} |
| 3163 |
|
| 3164 |
/* |
| 3165 |
* Does the invariant hold that the key is less than or equal to a given upper |
| 3166 |
* bound offset item? |
| 3167 |
* |
| 3168 |
* Caller should have verified that upperbound's line pointer is consistent |
| 3169 |
* using PageGetItemIdCareful() call. |
| 3170 |
* |
| 3171 |
* If this function returns false, convention is that caller throws error due |
| 3172 |
* to corruption. |
| 3173 |
*/ |
| 3174 |
static inline bool |
| 3175 |
invariant_leq_offset(BtreeCheckState *state, BTScanInsert key, |
| 3176 |
OffsetNumber upperbound) |
| 3177 |
{ |
| 3178 |
int32 cmp; |
| 3179 |
|
| 3180 |
Assert(!key->nextkey && key->backward); |
| 3181 |
|
| 3182 |
cmp = _bt_compare(state->rel, key, state->target, upperbound); |
| 3183 |
|
| 3184 |
return cmp <= 0; |
| 3185 |
} |
| 3186 |
|
| 3187 |
/* |
| 3188 |
* Does the invariant hold that the key is strictly greater than a given lower |
| 3189 |
* bound offset item? |
| 3190 |
* |
| 3191 |
* Caller should have verified that lowerbound's line pointer is consistent |
| 3192 |
* using PageGetItemIdCareful() call. |
| 3193 |
* |
| 3194 |
* If this function returns false, convention is that caller throws error due |
| 3195 |
* to corruption. |
| 3196 |
*/ |
| 3197 |
static inline bool |
| 3198 |
invariant_g_offset(BtreeCheckState *state, BTScanInsert key, |
| 3199 |
OffsetNumber lowerbound) |
| 3200 |
{ |
| 3201 |
int32 cmp; |
| 3202 |
|
| 3203 |
Assert(!key->nextkey && key->backward); |
| 3204 |
|
| 3205 |
cmp = _bt_compare(state->rel, key, state->target, lowerbound); |
| 3206 |
|
| 3207 |
/* pg_upgrade'd indexes may legally have equal sibling tuples */ |
| 3208 |
if (!key->heapkeyspace) |
| 3209 |
return cmp >= 0; |
| 3210 |
|
| 3211 |
/* |
| 3212 |
* No need to consider the possibility that scankey has attributes that we |
| 3213 |
* need to force to be interpreted as negative infinity. _bt_compare() is |
| 3214 |
* able to determine that scankey is greater than negative infinity. The |
| 3215 |
* distinction between "==" and "<" isn't interesting here, since |
| 3216 |
* corruption is indicated either way. |
| 3217 |
*/ |
| 3218 |
return cmp > 0; |
| 3219 |
} |
| 3220 |
|
| 3221 |
/* |
| 3222 |
* Does the invariant hold that the key is strictly less than a given upper |
| 3223 |
* bound offset item, with the offset relating to a caller-supplied page that |
| 3224 |
* is not the current target page? |
| 3225 |
* |
| 3226 |
* Caller's non-target page is a child page of the target, checked as part of |
| 3227 |
* checking a property of the target page (i.e. the key comes from the |
| 3228 |
* target). Verifies line pointer on behalf of caller. |
| 3229 |
* |
| 3230 |
* If this function returns false, convention is that caller throws error due |
| 3231 |
* to corruption. |
| 3232 |
*/ |
| 3233 |
static inline bool |
| 3234 |
invariant_l_nontarget_offset(BtreeCheckState *state, BTScanInsert key, |
| 3235 |
BlockNumber nontargetblock, Page nontarget, |
| 3236 |
OffsetNumber upperbound) |
| 3237 |
{ |
| 3238 |
ItemId itemid; |
| 3239 |
int32 cmp; |
| 3240 |
|
| 3241 |
Assert(!key->nextkey && key->backward); |
| 3242 |
|
| 3243 |
/* Verify line pointer before checking tuple */ |
| 3244 |
itemid = PageGetItemIdCareful(state, nontargetblock, nontarget, |
| 3245 |
upperbound); |
| 3246 |
cmp = _bt_compare(state->rel, key, nontarget, upperbound); |
| 3247 |
|
| 3248 |
/* pg_upgrade'd indexes may legally have equal sibling tuples */ |
| 3249 |
if (!key->heapkeyspace) |
| 3250 |
return cmp <= 0; |
| 3251 |
|
| 3252 |
/* See invariant_l_offset() for an explanation of this extra step */ |
| 3253 |
if (cmp == 0) |
| 3254 |
{ |
| 3255 |
IndexTuple child; |
| 3256 |
int uppnkeyatts; |
| 3257 |
ItemPointer childheaptid; |
| 3258 |
BTPageOpaque copaque; |
| 3259 |
bool nonpivot; |
| 3260 |
|
| 3261 |
child = (IndexTuple) PageGetItem(nontarget, itemid); |
| 3262 |
copaque = BTPageGetOpaque(nontarget); |
| 3263 |
nonpivot = P_ISLEAF(copaque) && upperbound >= P_FIRSTDATAKEY(copaque); |
| 3264 |
|
| 3265 |
/* Get number of keys + heap TID for child/non-target item */ |
| 3266 |
uppnkeyatts = BTreeTupleGetNKeyAtts(child, state->rel); |
| 3267 |
childheaptid = BTreeTupleGetHeapTIDCareful(state, child, nonpivot); |
| 3268 |
|
| 3269 |
/* Heap TID is tiebreaker key attribute */ |
| 3270 |
if (key->keysz == uppnkeyatts) |
| 3271 |
return key->scantid == NULL && childheaptid != NULL; |
| 3272 |
|
| 3273 |
return key->keysz < uppnkeyatts; |
| 3274 |
} |
| 3275 |
|
| 3276 |
return cmp < 0; |
| 3277 |
} |
| 3278 |
|
| 3279 |
/* |
| 3280 |
* Given a block number of a B-Tree page, return page in palloc()'d memory. |
| 3281 |
* While at it, perform some basic checks of the page. |
| 3282 |
* |
| 3283 |
* There is never an attempt to get a consistent view of multiple pages using |
| 3284 |
* multiple concurrent buffer locks; in general, we only acquire a single pin |
| 3285 |
* and buffer lock at a time, which is often all that the nbtree code requires. |
| 3286 |
* (Actually, bt_recheck_sibling_links couples buffer locks, which is the only |
| 3287 |
* exception to this general rule.) |
| 3288 |
* |
| 3289 |
* Operating on a copy of the page is useful because it prevents control |
| 3290 |
* getting stuck in an uninterruptible state when an underlying operator class |
| 3291 |
* misbehaves. |
| 3292 |
*/ |
| 3293 |
static Page |
| 3294 |
palloc_btree_page(BtreeCheckState *state, BlockNumber blocknum) |
| 3295 |
{ |
| 3296 |
Buffer buffer; |
| 3297 |
Page page; |
| 3298 |
BTPageOpaque opaque; |
| 3299 |
OffsetNumber maxoffset; |
| 3300 |
|
| 3301 |
page = palloc(BLCKSZ); |
| 3302 |
|
| 3303 |
/* |
| 3304 |
* We copy the page into local storage to avoid holding pin on the buffer |
| 3305 |
* longer than we must. |
| 3306 |
*/ |
| 3307 |
buffer = ReadBufferExtended(state->rel, MAIN_FORKNUM, blocknum, RBM_NORMAL, |
| 3308 |
state->checkstrategy); |
| 3309 |
LockBuffer(buffer, BT_READ); |
| 3310 |
|
| 3311 |
/* |
| 3312 |
* Perform the same basic sanity checking that nbtree itself performs for |
| 3313 |
* every page: |
| 3314 |
*/ |
| 3315 |
_bt_checkpage(state->rel, buffer); |
| 3316 |
|
| 3317 |
/* Only use copy of page in palloc()'d memory */ |
| 3318 |
memcpy(page, BufferGetPage(buffer), BLCKSZ); |
| 3319 |
UnlockReleaseBuffer(buffer); |
| 3320 |
|
| 3321 |
opaque = BTPageGetOpaque(page); |
| 3322 |
|
| 3323 |
if (P_ISMETA(opaque) && blocknum != BTREE_METAPAGE) |
| 3324 |
ereport(ERROR, |
| 3325 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3326 |
errmsg("invalid meta page found at block %u in index \"%s\"", |
| 3327 |
blocknum, RelationGetRelationName(state->rel)))); |
| 3328 |
|
| 3329 |
/* Check page from block that ought to be meta page */ |
| 3330 |
if (blocknum == BTREE_METAPAGE) |
| 3331 |
{ |
| 3332 |
BTMetaPageData *metad = BTPageGetMeta(page); |
| 3333 |
|
| 3334 |
if (!P_ISMETA(opaque) || |
| 3335 |
metad->btm_magic != BTREE_MAGIC) |
| 3336 |
ereport(ERROR, |
| 3337 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3338 |
errmsg("index \"%s\" meta page is corrupt", |
| 3339 |
RelationGetRelationName(state->rel)))); |
| 3340 |
|
| 3341 |
if (metad->btm_version < BTREE_MIN_VERSION || |
| 3342 |
metad->btm_version > BTREE_VERSION) |
| 3343 |
ereport(ERROR, |
| 3344 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3345 |
errmsg("version mismatch in index \"%s\": file version %d, " |
| 3346 |
"current version %d, minimum supported version %d", |
| 3347 |
RelationGetRelationName(state->rel), |
| 3348 |
metad->btm_version, BTREE_VERSION, |
| 3349 |
BTREE_MIN_VERSION))); |
| 3350 |
|
| 3351 |
/* Finished with metapage checks */ |
| 3352 |
return page; |
| 3353 |
} |
| 3354 |
|
| 3355 |
/* |
| 3356 |
* Deleted pages that still use the old 32-bit XID representation have no |
| 3357 |
* sane "level" field because they type pun the field, but all other pages |
| 3358 |
* (including pages deleted on Postgres 14+) have a valid value. |
| 3359 |
*/ |
| 3360 |
if (!P_ISDELETED(opaque) || P_HAS_FULLXID(opaque)) |
| 3361 |
{ |
| 3362 |
/* Okay, no reason not to trust btpo_level field from page */ |
| 3363 |
|
| 3364 |
if (P_ISLEAF(opaque) && opaque->btpo_level != 0) |
| 3365 |
ereport(ERROR, |
| 3366 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3367 |
errmsg_internal("invalid leaf page level %u for block %u in index \"%s\"", |
| 3368 |
opaque->btpo_level, blocknum, |
| 3369 |
RelationGetRelationName(state->rel)))); |
| 3370 |
|
| 3371 |
if (!P_ISLEAF(opaque) && opaque->btpo_level == 0) |
| 3372 |
ereport(ERROR, |
| 3373 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3374 |
errmsg_internal("invalid internal page level 0 for block %u in index \"%s\"", |
| 3375 |
blocknum, |
| 3376 |
RelationGetRelationName(state->rel)))); |
| 3377 |
} |
| 3378 |
|
| 3379 |
/* |
| 3380 |
* Sanity checks for number of items on page. |
| 3381 |
* |
| 3382 |
* As noted at the beginning of _bt_binsrch(), an internal page must have |
| 3383 |
* children, since there must always be a negative infinity downlink |
| 3384 |
* (there may also be a highkey). In the case of non-rightmost leaf |
| 3385 |
* pages, there must be at least a highkey. The exceptions are deleted |
| 3386 |
* pages, which contain no items. |
| 3387 |
* |
| 3388 |
* This is correct when pages are half-dead, since internal pages are |
| 3389 |
* never half-dead, and leaf pages must have a high key when half-dead |
| 3390 |
* (the rightmost page can never be deleted). It's also correct with |
| 3391 |
* fully deleted pages: _bt_unlink_halfdead_page() doesn't change anything |
| 3392 |
* about the target page other than setting the page as fully dead, and |
| 3393 |
* setting its xact field. In particular, it doesn't change the sibling |
| 3394 |
* links in the deletion target itself, since they're required when index |
| 3395 |
* scans land on the deletion target, and then need to move right (or need |
| 3396 |
* to move left, in the case of backward index scans). |
| 3397 |
*/ |
| 3398 |
maxoffset = PageGetMaxOffsetNumber(page); |
| 3399 |
if (maxoffset > MaxIndexTuplesPerPage) |
| 3400 |
ereport(ERROR, |
| 3401 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3402 |
errmsg("Number of items on block %u of index \"%s\" exceeds MaxIndexTuplesPerPage (%u)", |
| 3403 |
blocknum, RelationGetRelationName(state->rel), |
| 3404 |
MaxIndexTuplesPerPage))); |
| 3405 |
|
| 3406 |
if (!P_ISLEAF(opaque) && !P_ISDELETED(opaque) && maxoffset < P_FIRSTDATAKEY(opaque)) |
| 3407 |
ereport(ERROR, |
| 3408 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3409 |
errmsg("internal block %u in index \"%s\" lacks high key and/or at least one downlink", |
| 3410 |
blocknum, RelationGetRelationName(state->rel)))); |
| 3411 |
|
| 3412 |
if (P_ISLEAF(opaque) && !P_ISDELETED(opaque) && !P_RIGHTMOST(opaque) && maxoffset < P_HIKEY) |
| 3413 |
ereport(ERROR, |
| 3414 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3415 |
errmsg("non-rightmost leaf block %u in index \"%s\" lacks high key item", |
| 3416 |
blocknum, RelationGetRelationName(state->rel)))); |
| 3417 |
|
| 3418 |
/* |
| 3419 |
* In general, internal pages are never marked half-dead, except on |
| 3420 |
* versions of Postgres prior to 9.4, where it can be valid transient |
| 3421 |
* state. This state is nonetheless treated as corruption by VACUUM on |
| 3422 |
* from version 9.4 on, so do the same here. See _bt_pagedel() for full |
| 3423 |
* details. |
| 3424 |
*/ |
| 3425 |
if (!P_ISLEAF(opaque) && P_ISHALFDEAD(opaque)) |
| 3426 |
ereport(ERROR, |
| 3427 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3428 |
errmsg("internal page block %u in index \"%s\" is half-dead", |
| 3429 |
blocknum, RelationGetRelationName(state->rel)), |
| 3430 |
errhint("This can be caused by an interrupted VACUUM in version 9.3 or older, before upgrade. Please REINDEX it."))); |
| 3431 |
|
| 3432 |
/* |
| 3433 |
* Check that internal pages have no garbage items, and that no page has |
| 3434 |
* an invalid combination of deletion-related page level flags |
| 3435 |
*/ |
| 3436 |
if (!P_ISLEAF(opaque) && P_HAS_GARBAGE(opaque)) |
| 3437 |
ereport(ERROR, |
| 3438 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3439 |
errmsg_internal("internal page block %u in index \"%s\" has garbage items", |
| 3440 |
blocknum, RelationGetRelationName(state->rel)))); |
| 3441 |
|
| 3442 |
if (P_HAS_FULLXID(opaque) && !P_ISDELETED(opaque)) |
| 3443 |
ereport(ERROR, |
| 3444 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3445 |
errmsg_internal("full transaction id page flag appears in non-deleted block %u in index \"%s\"", |
| 3446 |
blocknum, RelationGetRelationName(state->rel)))); |
| 3447 |
|
| 3448 |
if (P_ISDELETED(opaque) && P_ISHALFDEAD(opaque)) |
| 3449 |
ereport(ERROR, |
| 3450 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3451 |
errmsg_internal("deleted page block %u in index \"%s\" is half-dead", |
| 3452 |
blocknum, RelationGetRelationName(state->rel)))); |
| 3453 |
|
| 3454 |
return page; |
| 3455 |
} |
| 3456 |
|
| 3457 |
/* |
| 3458 |
* _bt_mkscankey() wrapper that automatically prevents insertion scankey from |
| 3459 |
* being considered greater than the pivot tuple that its values originated |
| 3460 |
* from (or some other identical pivot tuple) in the common case where there |
| 3461 |
* are truncated/minus infinity attributes. Without this extra step, there |
| 3462 |
* are forms of corruption that amcheck could theoretically fail to report. |
| 3463 |
* |
| 3464 |
* For example, invariant_g_offset() might miss a cross-page invariant failure |
| 3465 |
* on an internal level if the scankey built from the first item on the |
| 3466 |
* target's right sibling page happened to be equal to (not greater than) the |
| 3467 |
* last item on target page. The !backward tiebreaker in _bt_compare() might |
| 3468 |
* otherwise cause amcheck to assume (rather than actually verify) that the |
| 3469 |
* scankey is greater. |
| 3470 |
*/ |
| 3471 |
static inline BTScanInsert |
| 3472 |
bt_mkscankey_pivotsearch(Relation rel, IndexTuple itup) |
| 3473 |
{ |
| 3474 |
BTScanInsert skey; |
| 3475 |
|
| 3476 |
skey = _bt_mkscankey(rel, itup); |
| 3477 |
skey->backward = true; |
| 3478 |
|
| 3479 |
return skey; |
| 3480 |
} |
| 3481 |
|
| 3482 |
/* |
| 3483 |
* PageGetItemId() wrapper that validates returned line pointer. |
| 3484 |
* |
| 3485 |
* Buffer page/page item access macros generally trust that line pointers are |
| 3486 |
* not corrupt, which might cause problems for verification itself. For |
| 3487 |
* example, there is no bounds checking in PageGetItem(). Passing it a |
| 3488 |
* corrupt line pointer can cause it to return a tuple/pointer that is unsafe |
| 3489 |
* to dereference. |
| 3490 |
* |
| 3491 |
* Validating line pointers before tuples avoids undefined behavior and |
| 3492 |
* assertion failures with corrupt indexes, making the verification process |
| 3493 |
* more robust and predictable. |
| 3494 |
*/ |
| 3495 |
static ItemId |
| 3496 |
PageGetItemIdCareful(BtreeCheckState *state, BlockNumber block, Page page, |
| 3497 |
OffsetNumber offset) |
| 3498 |
{ |
| 3499 |
ItemId itemid = PageGetItemId(page, offset); |
| 3500 |
|
| 3501 |
if (ItemIdGetOffset(itemid) + ItemIdGetLength(itemid) > |
| 3502 |
BLCKSZ - MAXALIGN(sizeof(BTPageOpaqueData))) |
| 3503 |
ereport(ERROR, |
| 3504 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3505 |
errmsg("line pointer points past end of tuple space in index \"%s\"", |
| 3506 |
RelationGetRelationName(state->rel)), |
| 3507 |
errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.", |
| 3508 |
block, offset, ItemIdGetOffset(itemid), |
| 3509 |
ItemIdGetLength(itemid), |
| 3510 |
ItemIdGetFlags(itemid)))); |
| 3511 |
|
| 3512 |
/* |
| 3513 |
* Verify that line pointer isn't LP_REDIRECT or LP_UNUSED, since nbtree |
| 3514 |
* never uses either. Verify that line pointer has storage, too, since |
| 3515 |
* even LP_DEAD items should within nbtree. |
| 3516 |
*/ |
| 3517 |
if (ItemIdIsRedirected(itemid) || !ItemIdIsUsed(itemid) || |
| 3518 |
ItemIdGetLength(itemid) == 0) |
| 3519 |
ereport(ERROR, |
| 3520 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3521 |
errmsg("invalid line pointer storage in index \"%s\"", |
| 3522 |
RelationGetRelationName(state->rel)), |
| 3523 |
errdetail_internal("Index tid=(%u,%u) lp_off=%u, lp_len=%u lp_flags=%u.", |
| 3524 |
block, offset, ItemIdGetOffset(itemid), |
| 3525 |
ItemIdGetLength(itemid), |
| 3526 |
ItemIdGetFlags(itemid)))); |
| 3527 |
|
| 3528 |
return itemid; |
| 3529 |
} |
| 3530 |
|
| 3531 |
/* |
| 3532 |
* BTreeTupleGetHeapTID() wrapper that enforces that a heap TID is present in |
| 3533 |
* cases where that is mandatory (i.e. for non-pivot tuples) |
| 3534 |
*/ |
| 3535 |
static inline ItemPointer |
| 3536 |
BTreeTupleGetHeapTIDCareful(BtreeCheckState *state, IndexTuple itup, |
| 3537 |
bool nonpivot) |
| 3538 |
{ |
| 3539 |
ItemPointer htid; |
| 3540 |
|
| 3541 |
/* |
| 3542 |
* Caller determines whether this is supposed to be a pivot or non-pivot |
| 3543 |
* tuple using page type and item offset number. Verify that tuple |
| 3544 |
* metadata agrees with this. |
| 3545 |
*/ |
| 3546 |
Assert(state->heapkeyspace); |
| 3547 |
if (BTreeTupleIsPivot(itup) && nonpivot) |
| 3548 |
ereport(ERROR, |
| 3549 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3550 |
errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected pivot tuple", |
| 3551 |
state->targetblock, |
| 3552 |
RelationGetRelationName(state->rel)))); |
| 3553 |
|
| 3554 |
if (!BTreeTupleIsPivot(itup) && !nonpivot) |
| 3555 |
ereport(ERROR, |
| 3556 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3557 |
errmsg_internal("block %u or its right sibling block or child block in index \"%s\" has unexpected non-pivot tuple", |
| 3558 |
state->targetblock, |
| 3559 |
RelationGetRelationName(state->rel)))); |
| 3560 |
|
| 3561 |
htid = BTreeTupleGetHeapTID(itup); |
| 3562 |
if (!ItemPointerIsValid(htid) && nonpivot) |
| 3563 |
ereport(ERROR, |
| 3564 |
(errcode(ERRCODE_INDEX_CORRUPTED), |
| 3565 |
errmsg("block %u or its right sibling block or child block in index \"%s\" contains non-pivot tuple that lacks a heap TID", |
| 3566 |
state->targetblock, |
| 3567 |
RelationGetRelationName(state->rel)))); |
| 3568 |
|
| 3569 |
return htid; |
| 3570 |
} |
| 3571 |
|
| 3572 |
/* |
| 3573 |
* Return the "pointed to" TID for itup, which is used to generate a |
| 3574 |
* descriptive error message. itup must be a "data item" tuple (it wouldn't |
| 3575 |
* make much sense to call here with a high key tuple, since there won't be a |
| 3576 |
* valid downlink/block number to display). |
| 3577 |
* |
| 3578 |
* Returns either a heap TID (which will be the first heap TID in posting list |
| 3579 |
* if itup is posting list tuple), or a TID that contains downlink block |
| 3580 |
* number, plus some encoded metadata (e.g., the number of attributes present |
| 3581 |
* in itup). |
| 3582 |
*/ |
| 3583 |
static inline ItemPointer |
| 3584 |
BTreeTupleGetPointsToTID(IndexTuple itup) |
| 3585 |
{ |
| 3586 |
/* |
| 3587 |
* Rely on the assumption that !heapkeyspace internal page data items will |
| 3588 |
* correctly return TID with downlink here -- BTreeTupleGetHeapTID() won't |
| 3589 |
* recognize it as a pivot tuple, but everything still works out because |
| 3590 |
* the t_tid field is still returned |
| 3591 |
*/ |
| 3592 |
if (!BTreeTupleIsPivot(itup)) |
| 3593 |
return BTreeTupleGetHeapTID(itup); |
| 3594 |
|
| 3595 |
/* Pivot tuple returns TID with downlink block (heapkeyspace variant) */ |
| 3596 |
return &itup->t_tid; |
| 3597 |
} |