Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * verify_heapam.c
4 : : * Functions to check postgresql heap relations for corruption
5 : : *
6 : : * Copyright (c) 2016-2026, PostgreSQL Global Development Group
7 : : *
8 : : * contrib/amcheck/verify_heapam.c
9 : : *-------------------------------------------------------------------------
10 : : */
11 : : #include "postgres.h"
12 : :
13 : : #include "access/detoast.h"
14 : : #include "access/genam.h"
15 : : #include "access/heaptoast.h"
16 : : #include "access/multixact.h"
17 : : #include "access/relation.h"
18 : : #include "access/table.h"
19 : : #include "access/toast_compression.h"
20 : : #include "access/toast_internals.h"
21 : : #include "access/visibilitymap.h"
22 : : #include "access/xact.h"
23 : : #include "catalog/pg_am.h"
24 : : #include "catalog/pg_class.h"
25 : : #include "funcapi.h"
26 : : #include "miscadmin.h"
27 : : #include "storage/bufmgr.h"
28 : : #include "storage/lwlock.h"
29 : : #include "storage/procarray.h"
30 : : #include "storage/read_stream.h"
31 : : #include "utils/builtins.h"
32 : : #include "utils/rel.h"
33 : : #include "utils/tuplestore.h"
34 : :
35 : 305 : PG_FUNCTION_INFO_V1(verify_heapam);
36 : :
37 : : /* The number of columns in tuples returned by verify_heapam */
38 : : #define HEAPCHECK_RELATION_COLS 4
39 : :
40 : : /* The largest valid toast va_rawsize */
41 : : #define VARLENA_SIZE_LIMIT 0x3FFFFFFF
42 : :
43 : : /*
44 : : * Despite the name, we use this for reporting problems with both XIDs and
45 : : * MXIDs.
46 : : */
47 : : typedef enum XidBoundsViolation
48 : : {
49 : : XID_INVALID,
50 : : XID_IN_FUTURE,
51 : : XID_PRECEDES_CLUSTERMIN,
52 : : XID_PRECEDES_RELMIN,
53 : : XID_BOUNDS_OK,
54 : : } XidBoundsViolation;
55 : :
56 : : typedef enum XidCommitStatus
57 : : {
58 : : XID_COMMITTED,
59 : : XID_IS_CURRENT_XID,
60 : : XID_IN_PROGRESS,
61 : : XID_ABORTED,
62 : : } XidCommitStatus;
63 : :
64 : : typedef enum SkipPages
65 : : {
66 : : SKIP_PAGES_ALL_FROZEN,
67 : : SKIP_PAGES_ALL_VISIBLE,
68 : : SKIP_PAGES_NONE,
69 : : } SkipPages;
70 : :
71 : : /*
72 : : * Struct holding information about a toasted attribute sufficient to both
73 : : * check the toasted attribute and, if found to be corrupt, to report where it
74 : : * was encountered in the main table.
75 : : */
76 : : typedef struct ToastedAttribute
77 : : {
78 : : Oid8 va_valueid; /* value ID (works for both Oid and Oid8) */
79 : : uint32 va_extinfo; /* external size and compression method */
80 : : vartag_external tag; /* VARTAG_ONDISK_OID or VARTAG_ONDISK_OID8 */
81 : : BlockNumber blkno; /* block in main table */
82 : : OffsetNumber offnum; /* offset in main table */
83 : : AttrNumber attnum; /* attribute in main table */
84 : : } ToastedAttribute;
85 : :
86 : : /*
87 : : * Struct holding the running context information during
88 : : * a lifetime of a verify_heapam execution.
89 : : */
90 : : typedef struct HeapCheckContext
91 : : {
92 : : /*
93 : : * Cached copies of values from TransamVariables and computed values from
94 : : * them.
95 : : */
96 : : FullTransactionId next_fxid; /* TransamVariables->nextXid */
97 : : TransactionId next_xid; /* 32-bit version of next_fxid */
98 : : TransactionId oldest_xid; /* TransamVariables->oldestXid */
99 : : FullTransactionId oldest_fxid; /* 64-bit version of oldest_xid, computed
100 : : * relative to next_fxid */
101 : : TransactionId safe_xmin; /* this XID and newer ones can't become
102 : : * all-visible while we're running */
103 : :
104 : : /*
105 : : * Cached copy of value from MultiXactState
106 : : */
107 : : MultiXactId next_mxact; /* MultiXactState->nextMXact */
108 : : MultiXactId oldest_mxact; /* MultiXactState->oldestMultiXactId */
109 : :
110 : : /*
111 : : * Cached copies of the most recently checked xid and its status.
112 : : */
113 : : TransactionId cached_xid;
114 : : XidCommitStatus cached_status;
115 : :
116 : : /* Values concerning the heap relation being checked */
117 : : Relation rel;
118 : : TransactionId relfrozenxid;
119 : : FullTransactionId relfrozenfxid;
120 : : TransactionId relminmxid;
121 : : Relation toast_rel;
122 : : Relation *toast_indexes;
123 : : Relation valid_toast_index;
124 : : int num_toast_indexes;
125 : :
126 : : /*
127 : : * Values for iterating over pages in the relation. `blkno` is the most
128 : : * recent block in the buffer yielded by the read stream API.
129 : : */
130 : : BlockNumber blkno;
131 : : BufferAccessStrategy bstrategy;
132 : : Buffer buffer;
133 : : Page page;
134 : :
135 : : /* Values for iterating over tuples within a page */
136 : : OffsetNumber offnum;
137 : : ItemId itemid;
138 : : uint16 lp_len;
139 : : uint16 lp_off;
140 : : HeapTupleHeader tuphdr;
141 : : int natts;
142 : :
143 : : /* Values for iterating over attributes within the tuple */
144 : : uint32 offset; /* offset in tuple data */
145 : : AttrNumber attnum;
146 : :
147 : : /* True if tuple's xmax makes it eligible for pruning */
148 : : bool tuple_could_be_pruned;
149 : :
150 : : /*
151 : : * List of ToastedAttribute structs for toasted attributes which are not
152 : : * eligible for pruning and should be checked
153 : : */
154 : : List *toasted_attributes;
155 : :
156 : : /* Whether verify_heapam has yet encountered any corrupt tuples */
157 : : bool is_corrupt;
158 : :
159 : : /* The descriptor and tuplestore for verify_heapam's result tuples */
160 : : TupleDesc tupdesc;
161 : : Tuplestorestate *tupstore;
162 : : } HeapCheckContext;
163 : :
164 : : /*
165 : : * The per-relation data provided to the read stream API for heap amcheck to
166 : : * use in its callback for the SKIP_PAGES_ALL_FROZEN and
167 : : * SKIP_PAGES_ALL_VISIBLE options.
168 : : */
169 : : typedef struct HeapCheckReadStreamData
170 : : {
171 : : /*
172 : : * `range` is used by all SkipPages options. SKIP_PAGES_NONE uses the
173 : : * default read stream callback, block_range_read_stream_cb(), which takes
174 : : * a BlockRangeReadStreamPrivate as its callback_private_data. `range`
175 : : * keeps track of the current block number across
176 : : * read_stream_next_buffer() invocations.
177 : : */
178 : : BlockRangeReadStreamPrivate range;
179 : : SkipPages skip_option;
180 : : Relation rel;
181 : : Buffer *vmbuffer;
182 : : } HeapCheckReadStreamData;
183 : :
184 : :
185 : : /* Internal implementation */
186 : : static BlockNumber heapcheck_read_stream_next_unskippable(ReadStream *stream,
187 : : void *callback_private_data,
188 : : void *per_buffer_data);
189 : :
190 : : static void check_tuple(HeapCheckContext *ctx,
191 : : bool *xmin_commit_status_ok,
192 : : XidCommitStatus *xmin_commit_status);
193 : : static void check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx,
194 : : ToastedAttribute *ta, int32 *expected_chunk_seq,
195 : : uint32 extsize, int32 max_chunk_size);
196 : :
197 : : static bool check_tuple_attribute(HeapCheckContext *ctx);
198 : : static void check_toasted_attribute(HeapCheckContext *ctx,
199 : : ToastedAttribute *ta);
200 : :
201 : : static bool check_tuple_header(HeapCheckContext *ctx);
202 : : static bool check_tuple_visibility(HeapCheckContext *ctx,
203 : : bool *xmin_commit_status_ok,
204 : : XidCommitStatus *xmin_commit_status);
205 : :
206 : : static void report_corruption(HeapCheckContext *ctx, char *msg);
207 : : static void report_toast_corruption(HeapCheckContext *ctx,
208 : : ToastedAttribute *ta, char *msg);
209 : : static FullTransactionId FullTransactionIdFromXidAndCtx(TransactionId xid,
210 : : const HeapCheckContext *ctx);
211 : : static void update_cached_xid_range(HeapCheckContext *ctx);
212 : : static void update_cached_mxid_range(HeapCheckContext *ctx);
213 : : static XidBoundsViolation check_mxid_in_range(MultiXactId mxid,
214 : : HeapCheckContext *ctx);
215 : : static XidBoundsViolation check_mxid_valid_in_rel(MultiXactId mxid,
216 : : HeapCheckContext *ctx);
217 : : static XidBoundsViolation get_xid_status(TransactionId xid,
218 : : HeapCheckContext *ctx,
219 : : XidCommitStatus *status);
220 : :
221 : : /*
222 : : * Scan and report corruption in heap pages, optionally reconciling toasted
223 : : * attributes with entries in the associated toast table. Intended to be
224 : : * called from SQL with the following parameters:
225 : : *
226 : : * relation:
227 : : * The Oid of the heap relation to be checked.
228 : : *
229 : : * on_error_stop:
230 : : * Whether to stop at the end of the first page for which errors are
231 : : * detected. Note that multiple rows may be returned.
232 : : *
233 : : * check_toast:
234 : : * Whether to check each toasted attribute against the toast table to
235 : : * verify that it can be found there.
236 : : *
237 : : * skip:
238 : : * What kinds of pages in the heap relation should be skipped. Valid
239 : : * options are "all-visible", "all-frozen", and "none".
240 : : *
241 : : * Returns to the SQL caller a set of tuples, each containing the location
242 : : * and a description of a corruption found in the heap.
243 : : *
244 : : * This code goes to some trouble to avoid crashing the server even if the
245 : : * table pages are badly corrupted, but it's probably not perfect. If
246 : : * check_toast is true, we'll use regular index lookups to try to fetch TOAST
247 : : * tuples, which can certainly cause crashes if the right kind of corruption
248 : : * exists in the toast table or index. No matter what parameters you pass,
249 : : * we can't protect against crashes that might occur trying to look up the
250 : : * commit status of transaction IDs (though we avoid trying to do such lookups
251 : : * for transaction IDs that can't legally appear in the table).
252 : : */
253 : : Datum
254 : 3599 : verify_heapam(PG_FUNCTION_ARGS)
255 : : {
256 : 3599 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
257 : : HeapCheckContext ctx;
258 : 3599 : Buffer vmbuffer = InvalidBuffer;
259 : : Oid relid;
260 : : bool on_error_stop;
261 : : bool check_toast;
262 : 3599 : SkipPages skip_option = SKIP_PAGES_NONE;
263 : : BlockNumber first_block;
264 : : BlockNumber last_block;
265 : : BlockNumber nblocks;
266 : : const char *skip;
267 : : ReadStream *stream;
268 : : int stream_flags;
269 : : ReadStreamBlockNumberCB stream_cb;
270 : : void *stream_data;
271 : : HeapCheckReadStreamData stream_skip_data;
272 : :
273 : : /* Check supplied arguments */
274 [ - + ]: 3599 : if (PG_ARGISNULL(0))
275 [ # # ]: 0 : ereport(ERROR,
276 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
277 : : errmsg("relation cannot be null")));
278 : 3599 : relid = PG_GETARG_OID(0);
279 : :
280 [ - + ]: 3599 : if (PG_ARGISNULL(1))
281 [ # # ]: 0 : ereport(ERROR,
282 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
283 : : errmsg("on_error_stop cannot be null")));
284 : 3599 : on_error_stop = PG_GETARG_BOOL(1);
285 : :
286 [ - + ]: 3599 : if (PG_ARGISNULL(2))
287 [ # # ]: 0 : ereport(ERROR,
288 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
289 : : errmsg("check_toast cannot be null")));
290 : 3599 : check_toast = PG_GETARG_BOOL(2);
291 : :
292 [ - + ]: 3599 : if (PG_ARGISNULL(3))
293 [ # # ]: 0 : ereport(ERROR,
294 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
295 : : errmsg("skip cannot be null")));
296 : 3599 : skip = text_to_cstring(PG_GETARG_TEXT_PP(3));
297 [ + + ]: 3599 : if (pg_strcasecmp(skip, "all-visible") == 0)
298 : 84 : skip_option = SKIP_PAGES_ALL_VISIBLE;
299 [ + + ]: 3515 : else if (pg_strcasecmp(skip, "all-frozen") == 0)
300 : 87 : skip_option = SKIP_PAGES_ALL_FROZEN;
301 [ + + ]: 3428 : else if (pg_strcasecmp(skip, "none") == 0)
302 : 3427 : skip_option = SKIP_PAGES_NONE;
303 : : else
304 [ + - ]: 1 : ereport(ERROR,
305 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
306 : : errmsg("invalid skip option"),
307 : : errhint("Valid skip options are \"all-visible\", \"all-frozen\", and \"none\".")));
308 : :
309 : 3598 : memset(&ctx, 0, sizeof(HeapCheckContext));
310 : 3598 : ctx.cached_xid = InvalidTransactionId;
311 : 3598 : ctx.toasted_attributes = NIL;
312 : :
313 : : /*
314 : : * Any xmin newer than the xmin of our snapshot can't become all-visible
315 : : * while we're running.
316 : : */
317 : 3598 : ctx.safe_xmin = GetTransactionSnapshot()->xmin;
318 : :
319 : : /*
320 : : * If we report corruption when not examining some individual attribute,
321 : : * we need attnum to be reported as NULL. Set that up before any
322 : : * corruption reporting might happen.
323 : : */
324 : 3598 : ctx.attnum = -1;
325 : :
326 : : /* Construct the tuplestore and tuple descriptor */
327 : 3598 : InitMaterializedSRF(fcinfo, 0);
328 : 3598 : ctx.tupdesc = rsinfo->setDesc;
329 : 3598 : ctx.tupstore = rsinfo->setResult;
330 : :
331 : : /* Open relation, check relkind and access method */
332 : 3598 : ctx.rel = relation_open(relid, AccessShareLock);
333 : :
334 : : /*
335 : : * Check that a relation's relkind and access method are both supported.
336 : : */
337 [ + + + + : 3598 : if (!RELKIND_HAS_TABLE_AM(ctx.rel->rd_rel->relkind) &&
+ + ]
338 [ + + ]: 195 : ctx.rel->rd_rel->relkind != RELKIND_SEQUENCE)
339 [ + - ]: 4 : ereport(ERROR,
340 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
341 : : errmsg("cannot check relation \"%s\"",
342 : : RelationGetRelationName(ctx.rel)),
343 : : errdetail_relkind_not_supported(ctx.rel->rd_rel->relkind)));
344 : :
345 : : /*
346 : : * Sequences always use heap AM, but they don't show that in the catalogs.
347 : : * Other relkinds might be using a different AM, so check.
348 : : */
349 [ + + ]: 3594 : if (ctx.rel->rd_rel->relkind != RELKIND_SEQUENCE &&
350 [ - + ]: 3403 : ctx.rel->rd_rel->relam != HEAP_TABLE_AM_OID)
351 [ # # ]: 0 : ereport(ERROR,
352 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
353 : : errmsg("only heap AM is supported")));
354 : :
355 : : /*
356 : : * Early exit for unlogged relations during recovery. These will have no
357 : : * relation fork, so there won't be anything to check. We behave as if
358 : : * the relation is empty.
359 : : */
360 [ - + - - ]: 3594 : if (ctx.rel->rd_rel->relpersistence == RELPERSISTENCE_UNLOGGED &&
361 : 0 : RecoveryInProgress())
362 : : {
363 [ # # ]: 0 : ereport(DEBUG1,
364 : : (errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
365 : : errmsg("cannot verify unlogged relation \"%s\" during recovery, skipping",
366 : : RelationGetRelationName(ctx.rel))));
367 : 0 : relation_close(ctx.rel, AccessShareLock);
368 : 0 : PG_RETURN_NULL();
369 : : }
370 : :
371 : : /* Early exit if the relation is empty */
372 : 3594 : nblocks = RelationGetNumberOfBlocks(ctx.rel);
373 [ + + ]: 3577 : if (!nblocks)
374 : : {
375 : 2028 : relation_close(ctx.rel, AccessShareLock);
376 : 2028 : PG_RETURN_NULL();
377 : : }
378 : :
379 : 1549 : ctx.bstrategy = GetAccessStrategy(BAS_BULKREAD);
380 : 1549 : ctx.buffer = InvalidBuffer;
381 : 1549 : ctx.page = NULL;
382 : :
383 : : /* Validate block numbers, or handle nulls. */
384 [ + + ]: 1549 : if (PG_ARGISNULL(4))
385 : 1426 : first_block = 0;
386 : : else
387 : : {
388 : 123 : int64 fb = PG_GETARG_INT64(4);
389 : :
390 [ + - + + ]: 123 : if (fb < 0 || fb >= nblocks)
391 [ + - ]: 1 : ereport(ERROR,
392 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
393 : : errmsg("starting block number must be between 0 and %u",
394 : : nblocks - 1)));
395 : 122 : first_block = (BlockNumber) fb;
396 : : }
397 [ + + ]: 1548 : if (PG_ARGISNULL(5))
398 : 1425 : last_block = nblocks - 1;
399 : : else
400 : : {
401 : 123 : int64 lb = PG_GETARG_INT64(5);
402 : :
403 [ + - + + ]: 123 : if (lb < 0 || lb >= nblocks)
404 [ + - ]: 1 : ereport(ERROR,
405 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
406 : : errmsg("ending block number must be between 0 and %u",
407 : : nblocks - 1)));
408 : 122 : last_block = (BlockNumber) lb;
409 : : }
410 : :
411 : : /* Optionally open the toast relation, if any. */
412 [ + + + + ]: 1547 : if (ctx.rel->rd_rel->reltoastrelid && check_toast)
413 : 740 : {
414 : : int offset;
415 : :
416 : : /* Main relation has associated toast relation */
417 : 740 : ctx.toast_rel = table_open(ctx.rel->rd_rel->reltoastrelid,
418 : : AccessShareLock);
419 : 740 : offset = toast_open_indexes(ctx.toast_rel,
420 : : AccessShareLock,
421 : : &(ctx.toast_indexes),
422 : : &(ctx.num_toast_indexes));
423 : 740 : ctx.valid_toast_index = ctx.toast_indexes[offset];
424 : : }
425 : : else
426 : : {
427 : : /*
428 : : * Main relation has no associated toast relation, or we're
429 : : * intentionally skipping it.
430 : : */
431 : 807 : ctx.toast_rel = NULL;
432 : 807 : ctx.toast_indexes = NULL;
433 : 807 : ctx.num_toast_indexes = 0;
434 : : }
435 : :
436 : 1547 : update_cached_xid_range(&ctx);
437 : 1547 : update_cached_mxid_range(&ctx);
438 : 1547 : ctx.relfrozenxid = ctx.rel->rd_rel->relfrozenxid;
439 : 1547 : ctx.relfrozenfxid = FullTransactionIdFromXidAndCtx(ctx.relfrozenxid, &ctx);
440 : 1547 : ctx.relminmxid = ctx.rel->rd_rel->relminmxid;
441 : :
442 [ + + ]: 1547 : if (TransactionIdIsNormal(ctx.relfrozenxid))
443 : 1356 : ctx.oldest_xid = ctx.relfrozenxid;
444 : :
445 : : /* Now that `ctx` is set up, set up the read stream */
446 : 1547 : stream_skip_data.range.current_blocknum = first_block;
447 : 1547 : stream_skip_data.range.last_exclusive = last_block + 1;
448 : 1547 : stream_skip_data.skip_option = skip_option;
449 : 1547 : stream_skip_data.rel = ctx.rel;
450 : 1547 : stream_skip_data.vmbuffer = &vmbuffer;
451 : :
452 [ + + ]: 1547 : if (skip_option == SKIP_PAGES_NONE)
453 : : {
454 : : /*
455 : : * It is safe to use batchmode as block_range_read_stream_cb takes no
456 : : * locks.
457 : : */
458 : 1382 : stream_cb = block_range_read_stream_cb;
459 : 1382 : stream_flags = READ_STREAM_SEQUENTIAL |
460 : : READ_STREAM_FULL |
461 : : READ_STREAM_USE_BATCHING;
462 : 1382 : stream_data = &stream_skip_data.range;
463 : : }
464 : : else
465 : : {
466 : : /*
467 : : * It would not be safe to naively use batchmode, as
468 : : * heapcheck_read_stream_next_unskippable takes locks. It shouldn't be
469 : : * too hard to convert though.
470 : : */
471 : 165 : stream_cb = heapcheck_read_stream_next_unskippable;
472 : 165 : stream_flags = READ_STREAM_DEFAULT;
473 : 165 : stream_data = &stream_skip_data;
474 : : }
475 : :
476 : 1547 : stream = read_stream_begin_relation(stream_flags,
477 : : ctx.bstrategy,
478 : : ctx.rel,
479 : : MAIN_FORKNUM,
480 : : stream_cb,
481 : : stream_data,
482 : : 0);
483 : :
484 [ + + ]: 14128 : while ((ctx.buffer = read_stream_next_buffer(stream, NULL)) != InvalidBuffer)
485 : : {
486 : : uint8 vmbits;
487 : : OffsetNumber maxoff;
488 : : OffsetNumber predecessor[MaxOffsetNumber];
489 : : OffsetNumber successor[MaxOffsetNumber];
490 : : bool lp_valid[MaxOffsetNumber];
491 : : bool xmin_commit_status_ok[MaxOffsetNumber];
492 : : XidCommitStatus xmin_commit_status[MaxOffsetNumber];
493 : :
494 [ - + ]: 12584 : CHECK_FOR_INTERRUPTS();
495 : :
496 : 12584 : memset(predecessor, 0, sizeof(OffsetNumber) * MaxOffsetNumber);
497 : :
498 : : /* Lock the next page. */
499 : : Assert(BufferIsValid(ctx.buffer));
500 : 12584 : LockBuffer(ctx.buffer, BUFFER_LOCK_SHARE);
501 : :
502 : 12584 : ctx.blkno = BufferGetBlockNumber(ctx.buffer);
503 : 12584 : ctx.page = BufferGetPage(ctx.buffer);
504 : :
505 : : /*
506 : : * It is corruption if PD_ALL_VISIBLE is clear while either VM bit is
507 : : * set. Missing VM pages are treated as having no bits set. VM pages
508 : : * that fail page verification are read with RBM_ZERO_ON_ERROR, so
509 : : * those failures are not reported as corruption rows here.
510 : : */
511 : 12584 : vmbits = visibilitymap_get_status(ctx.rel, ctx.blkno, &vmbuffer);
512 : :
513 [ + + ]: 12584 : if (!PageIsAllVisible(ctx.page) &&
514 [ - + ]: 2865 : (vmbits & VISIBILITYMAP_VALID_BITS) != 0)
515 : : {
516 : 0 : ctx.offnum = InvalidOffsetNumber;
517 : 0 : ctx.attnum = -1;
518 : 0 : report_corruption(&ctx,
519 : : psprintf("page is not marked all-visible in page header but visibility map bit is set"));
520 : : }
521 : :
522 : : /* Perform tuple checks */
523 : 12584 : maxoff = PageGetMaxOffsetNumber(ctx.page);
524 [ + + ]: 604677 : for (ctx.offnum = FirstOffsetNumber; ctx.offnum <= maxoff;
525 : 592093 : ctx.offnum = OffsetNumberNext(ctx.offnum))
526 : : {
527 : : BlockNumber nextblkno;
528 : : OffsetNumber nextoffnum;
529 : :
530 : 592093 : successor[ctx.offnum] = InvalidOffsetNumber;
531 : 592093 : lp_valid[ctx.offnum] = false;
532 : 592093 : xmin_commit_status_ok[ctx.offnum] = false;
533 : 592093 : ctx.itemid = PageGetItemId(ctx.page, ctx.offnum);
534 : :
535 : : /* Skip over unused/dead line pointers */
536 [ + + + + ]: 592093 : if (!ItemIdIsUsed(ctx.itemid) || ItemIdIsDead(ctx.itemid))
537 : 9440 : continue;
538 : :
539 : : /*
540 : : * If this line pointer has been redirected, check that it
541 : : * redirects to a valid offset within the line pointer array
542 : : */
543 [ + + ]: 582653 : if (ItemIdIsRedirected(ctx.itemid))
544 : 4800 : {
545 : 4821 : OffsetNumber rdoffnum = ItemIdGetRedirect(ctx.itemid);
546 : : ItemId rditem;
547 : :
548 [ + + ]: 4821 : if (rdoffnum < FirstOffsetNumber)
549 : : {
550 : 6 : report_corruption(&ctx,
551 : : psprintf("line pointer redirection to item at offset %d precedes minimum offset %d",
552 : : rdoffnum,
553 : : FirstOffsetNumber));
554 : 6 : continue;
555 : : }
556 [ + + ]: 4815 : if (rdoffnum > maxoff)
557 : : {
558 : 14 : report_corruption(&ctx,
559 : : psprintf("line pointer redirection to item at offset %d exceeds maximum offset %d",
560 : : rdoffnum,
561 : : maxoff));
562 : 14 : continue;
563 : : }
564 : :
565 : : /*
566 : : * Since we've checked that this redirect points to a line
567 : : * pointer between FirstOffsetNumber and maxoff, it should now
568 : : * be safe to fetch the referenced line pointer. We expect it
569 : : * to be LP_NORMAL; if not, that's corruption.
570 : : */
571 : 4801 : rditem = PageGetItemId(ctx.page, rdoffnum);
572 [ - + ]: 4801 : if (!ItemIdIsUsed(rditem))
573 : : {
574 : 0 : report_corruption(&ctx,
575 : : psprintf("redirected line pointer points to an unused item at offset %d",
576 : : rdoffnum));
577 : 0 : continue;
578 : : }
579 [ - + ]: 4801 : else if (ItemIdIsDead(rditem))
580 : : {
581 : 0 : report_corruption(&ctx,
582 : : psprintf("redirected line pointer points to a dead item at offset %d",
583 : : rdoffnum));
584 : 0 : continue;
585 : : }
586 [ + + ]: 4801 : else if (ItemIdIsRedirected(rditem))
587 : : {
588 : 1 : report_corruption(&ctx,
589 : : psprintf("redirected line pointer points to another redirected line pointer at offset %d",
590 : : rdoffnum));
591 : 1 : continue;
592 : : }
593 : :
594 : : /*
595 : : * Record the fact that this line pointer has passed basic
596 : : * sanity checking, and also the offset number to which it
597 : : * points.
598 : : */
599 : 4800 : lp_valid[ctx.offnum] = true;
600 : 4800 : successor[ctx.offnum] = rdoffnum;
601 : 4800 : continue;
602 : : }
603 : :
604 : : /* Sanity-check the line pointer's offset and length values */
605 : 577832 : ctx.lp_len = ItemIdGetLength(ctx.itemid);
606 : 577832 : ctx.lp_off = ItemIdGetOffset(ctx.itemid);
607 : :
608 [ + + ]: 577832 : if (ctx.lp_off != MAXALIGN(ctx.lp_off))
609 : : {
610 : 6 : report_corruption(&ctx,
611 : : psprintf("line pointer to page offset %u is not maximally aligned",
612 : 6 : ctx.lp_off));
613 : 6 : continue;
614 : : }
615 [ + + ]: 577826 : if (ctx.lp_len < MAXALIGN(SizeofHeapTupleHeader))
616 : : {
617 : 12 : report_corruption(&ctx,
618 : : psprintf("line pointer length %u is less than the minimum tuple header size %u",
619 : 12 : ctx.lp_len,
620 : : (unsigned) MAXALIGN(SizeofHeapTupleHeader)));
621 : 12 : continue;
622 : : }
623 [ + + ]: 577814 : if (ctx.lp_off + ctx.lp_len > BLCKSZ)
624 : : {
625 : 14 : report_corruption(&ctx,
626 : : psprintf("line pointer to page offset %u with length %u ends beyond maximum page offset %d",
627 : 14 : ctx.lp_off,
628 : 14 : ctx.lp_len,
629 : : BLCKSZ));
630 : 14 : continue;
631 : : }
632 : :
633 : : /* It should be safe to examine the tuple's header, at least */
634 : 577800 : lp_valid[ctx.offnum] = true;
635 : 577800 : ctx.tuphdr = (HeapTupleHeader) PageGetItem(ctx.page, ctx.itemid);
636 : 577800 : ctx.natts = HeapTupleHeaderGetNatts(ctx.tuphdr);
637 : :
638 : : /* Ok, ready to check this next tuple */
639 : 577800 : check_tuple(&ctx,
640 : 577800 : &xmin_commit_status_ok[ctx.offnum],
641 : 577800 : &xmin_commit_status[ctx.offnum]);
642 : :
643 : : /*
644 : : * If the CTID field of this tuple seems to point to another tuple
645 : : * on the same page, record that tuple as the successor of this
646 : : * one.
647 : : */
648 : 577800 : nextblkno = ItemPointerGetBlockNumber(&(ctx.tuphdr)->t_ctid);
649 : 577800 : nextoffnum = ItemPointerGetOffsetNumber(&(ctx.tuphdr)->t_ctid);
650 [ + + + + : 577800 : if (nextblkno == ctx.blkno && nextoffnum != ctx.offnum &&
+ - ]
651 [ + - ]: 205 : nextoffnum >= FirstOffsetNumber && nextoffnum <= maxoff)
652 : 205 : successor[ctx.offnum] = nextoffnum;
653 : : }
654 : :
655 : : /*
656 : : * Update chain validation. Check each line pointer that's got a valid
657 : : * successor against that successor.
658 : : */
659 : 12584 : ctx.attnum = -1;
660 [ + + ]: 604677 : for (ctx.offnum = FirstOffsetNumber; ctx.offnum <= maxoff;
661 : 592093 : ctx.offnum = OffsetNumberNext(ctx.offnum))
662 : : {
663 : : ItemId curr_lp;
664 : : ItemId next_lp;
665 : : HeapTupleHeader curr_htup;
666 : : HeapTupleHeader next_htup;
667 : : TransactionId curr_xmin;
668 : : TransactionId curr_xmax;
669 : : TransactionId next_xmin;
670 : 592093 : OffsetNumber nextoffnum = successor[ctx.offnum];
671 : :
672 : : /*
673 : : * The current line pointer may not have a successor, either
674 : : * because it's not valid or because it didn't point to anything.
675 : : * In either case, we have to give up.
676 : : *
677 : : * If the current line pointer does point to something, it's
678 : : * possible that the target line pointer isn't valid. We have to
679 : : * give up in that case, too.
680 : : */
681 [ + + - + ]: 592093 : if (nextoffnum == InvalidOffsetNumber || !lp_valid[nextoffnum])
682 : 587088 : continue;
683 : :
684 : : /* We have two valid line pointers that we can examine. */
685 : 5005 : curr_lp = PageGetItemId(ctx.page, ctx.offnum);
686 : 5005 : next_lp = PageGetItemId(ctx.page, nextoffnum);
687 : :
688 : : /* Handle the cases where the current line pointer is a redirect. */
689 [ + + ]: 5005 : if (ItemIdIsRedirected(curr_lp))
690 : : {
691 : : /*
692 : : * We should not have set successor[ctx.offnum] to a value
693 : : * other than InvalidOffsetNumber unless that line pointer is
694 : : * LP_NORMAL.
695 : : */
696 : : Assert(ItemIdIsNormal(next_lp));
697 : :
698 : : /* Can only redirect to a HOT tuple. */
699 : 4800 : next_htup = (HeapTupleHeader) PageGetItem(ctx.page, next_lp);
700 [ + + ]: 4800 : if (!HeapTupleHeaderIsHeapOnly(next_htup))
701 : : {
702 : 1 : report_corruption(&ctx,
703 : : psprintf("redirected line pointer points to a non-heap-only tuple at offset %d",
704 : : nextoffnum));
705 : : }
706 : :
707 : : /* HOT chains should not intersect. */
708 [ + + ]: 4800 : if (predecessor[nextoffnum] != InvalidOffsetNumber)
709 : : {
710 : 1 : report_corruption(&ctx,
711 : : psprintf("redirect line pointer points to offset %d, but offset %d also points there",
712 : 1 : nextoffnum, predecessor[nextoffnum]));
713 : 1 : continue;
714 : : }
715 : :
716 : : /*
717 : : * This redirect and the tuple to which it points seem to be
718 : : * part of an update chain.
719 : : */
720 : 4799 : predecessor[nextoffnum] = ctx.offnum;
721 : 4799 : continue;
722 : : }
723 : :
724 : : /*
725 : : * If the next line pointer is a redirect, or if it's a tuple but
726 : : * the XMAX of this tuple doesn't match the XMIN of the next
727 : : * tuple, then the two aren't part of the same update chain and
728 : : * there is nothing more to do.
729 : : */
730 [ - + ]: 205 : if (ItemIdIsRedirected(next_lp))
731 : 0 : continue;
732 : 205 : curr_htup = (HeapTupleHeader) PageGetItem(ctx.page, curr_lp);
733 : 205 : curr_xmax = HeapTupleHeaderGetUpdateXid(curr_htup);
734 : 205 : next_htup = (HeapTupleHeader) PageGetItem(ctx.page, next_lp);
735 : 205 : next_xmin = HeapTupleHeaderGetXmin(next_htup);
736 [ + + - + ]: 205 : if (!TransactionIdIsValid(curr_xmax) ||
737 : : !TransactionIdEquals(curr_xmax, next_xmin))
738 : 4 : continue;
739 : :
740 : : /* HOT chains should not intersect. */
741 [ + + ]: 201 : if (predecessor[nextoffnum] != InvalidOffsetNumber)
742 : : {
743 : 1 : report_corruption(&ctx,
744 : : psprintf("tuple points to new version at offset %d, but offset %d also points there",
745 : 1 : nextoffnum, predecessor[nextoffnum]));
746 : 1 : continue;
747 : : }
748 : :
749 : : /*
750 : : * This tuple and the tuple to which it points seem to be part of
751 : : * an update chain.
752 : : */
753 : 200 : predecessor[nextoffnum] = ctx.offnum;
754 : :
755 : : /*
756 : : * If the current tuple is marked as HOT-updated, then the next
757 : : * tuple should be marked as a heap-only tuple. Conversely, if the
758 : : * current tuple isn't marked as HOT-updated, then the next tuple
759 : : * shouldn't be marked as a heap-only tuple.
760 : : *
761 : : * NB: Can't use HeapTupleHeaderIsHotUpdated() as it checks if
762 : : * hint bits indicate xmin/xmax aborted.
763 : : */
764 [ + + + - ]: 201 : if (!(curr_htup->t_infomask2 & HEAP_HOT_UPDATED) &&
765 : 1 : HeapTupleHeaderIsHeapOnly(next_htup))
766 : : {
767 : 1 : report_corruption(&ctx,
768 : : psprintf("non-heap-only update produced a heap-only tuple at offset %d",
769 : : nextoffnum));
770 : : }
771 [ + + ]: 200 : if ((curr_htup->t_infomask2 & HEAP_HOT_UPDATED) &&
772 [ + + ]: 199 : !HeapTupleHeaderIsHeapOnly(next_htup))
773 : : {
774 : 1 : report_corruption(&ctx,
775 : : psprintf("heap-only update produced a non-heap only tuple at offset %d",
776 : : nextoffnum));
777 : : }
778 : :
779 : : /*
780 : : * If the current tuple's xmin is still in progress but the
781 : : * successor tuple's xmin is committed, that's corruption.
782 : : *
783 : : * NB: We recheck the commit status of the current tuple's xmin
784 : : * here, because it might have committed after we checked it and
785 : : * before we checked the commit status of the successor tuple's
786 : : * xmin. This should be safe because the xmin itself can't have
787 : : * changed, only its commit status.
788 : : */
789 : 200 : curr_xmin = HeapTupleHeaderGetXmin(curr_htup);
790 [ + - ]: 200 : if (xmin_commit_status_ok[ctx.offnum] &&
791 [ + + ]: 200 : xmin_commit_status[ctx.offnum] == XID_IN_PROGRESS &&
792 [ + - ]: 1 : xmin_commit_status_ok[nextoffnum] &&
793 [ + - + - ]: 2 : xmin_commit_status[nextoffnum] == XID_COMMITTED &&
794 : 1 : TransactionIdIsInProgress(curr_xmin))
795 : : {
796 : 1 : report_corruption(&ctx,
797 : : psprintf("tuple with in-progress xmin %u was updated to produce a tuple at offset %d with committed xmin %u",
798 : : curr_xmin,
799 : 1 : ctx.offnum,
800 : : next_xmin));
801 : : }
802 : :
803 : : /*
804 : : * If the current tuple's xmin is aborted but the successor
805 : : * tuple's xmin is in-progress or committed, that's corruption.
806 : : */
807 [ + - ]: 200 : if (xmin_commit_status_ok[ctx.offnum] &&
808 [ + + ]: 200 : xmin_commit_status[ctx.offnum] == XID_ABORTED &&
809 [ + - ]: 2 : xmin_commit_status_ok[nextoffnum])
810 : : {
811 [ + + ]: 2 : if (xmin_commit_status[nextoffnum] == XID_IN_PROGRESS)
812 : 1 : report_corruption(&ctx,
813 : : psprintf("tuple with aborted xmin %u was updated to produce a tuple at offset %d with in-progress xmin %u",
814 : : curr_xmin,
815 : 1 : ctx.offnum,
816 : : next_xmin));
817 [ + - ]: 1 : else if (xmin_commit_status[nextoffnum] == XID_COMMITTED)
818 : 1 : report_corruption(&ctx,
819 : : psprintf("tuple with aborted xmin %u was updated to produce a tuple at offset %d with committed xmin %u",
820 : : curr_xmin,
821 : 1 : ctx.offnum,
822 : : next_xmin));
823 : : }
824 : : }
825 : :
826 : : /*
827 : : * An update chain can start either with a non-heap-only tuple or with
828 : : * a redirect line pointer, but not with a heap-only tuple.
829 : : *
830 : : * (This check is in a separate loop because we need the predecessor
831 : : * array to be fully populated before we can perform it.)
832 : : */
833 : 12584 : for (ctx.offnum = FirstOffsetNumber;
834 [ + + ]: 604677 : ctx.offnum <= maxoff;
835 : 592093 : ctx.offnum = OffsetNumberNext(ctx.offnum))
836 : : {
837 [ + + ]: 592093 : if (xmin_commit_status_ok[ctx.offnum] &&
838 [ + + ]: 577791 : (xmin_commit_status[ctx.offnum] == XID_COMMITTED ||
839 [ + + ]: 7 : xmin_commit_status[ctx.offnum] == XID_IN_PROGRESS) &&
840 [ + + ]: 577786 : predecessor[ctx.offnum] == InvalidOffsetNumber)
841 : : {
842 : : ItemId curr_lp;
843 : :
844 : 572790 : curr_lp = PageGetItemId(ctx.page, ctx.offnum);
845 [ + - ]: 572790 : if (!ItemIdIsRedirected(curr_lp))
846 : : {
847 : : HeapTupleHeader curr_htup;
848 : :
849 : : curr_htup = (HeapTupleHeader)
850 : 572790 : PageGetItem(ctx.page, curr_lp);
851 [ + + ]: 572790 : if (HeapTupleHeaderIsHeapOnly(curr_htup))
852 : 4 : report_corruption(&ctx,
853 : : psprintf("tuple is root of chain but is marked as heap-only tuple"));
854 : : }
855 : : }
856 : : }
857 : :
858 : : /* clean up */
859 : 12584 : UnlockReleaseBuffer(ctx.buffer);
860 : :
861 : : /*
862 : : * Check any toast pointers from the page whose lock we just released
863 : : */
864 [ + + ]: 12584 : if (ctx.toasted_attributes != NIL)
865 : : {
866 : : ListCell *cell;
867 : :
868 [ + - + + : 13376 : foreach(cell, ctx.toasted_attributes)
+ + ]
869 : 12461 : check_toasted_attribute(&ctx, lfirst(cell));
870 : 915 : list_free_deep(ctx.toasted_attributes);
871 : 915 : ctx.toasted_attributes = NIL;
872 : : }
873 : :
874 [ + + - + ]: 12581 : if (on_error_stop && ctx.is_corrupt)
875 : 0 : break;
876 : : }
877 : :
878 : 1544 : read_stream_end(stream);
879 : :
880 [ + + ]: 1544 : if (vmbuffer != InvalidBuffer)
881 : 1199 : ReleaseBuffer(vmbuffer);
882 : :
883 : : /* Close the associated toast table and indexes, if any. */
884 [ + + ]: 1544 : if (ctx.toast_indexes)
885 : 737 : toast_close_indexes(ctx.toast_indexes, ctx.num_toast_indexes,
886 : : AccessShareLock);
887 [ + + ]: 1544 : if (ctx.toast_rel)
888 : 737 : table_close(ctx.toast_rel, AccessShareLock);
889 : :
890 : : /* Close the main relation */
891 : 1544 : relation_close(ctx.rel, AccessShareLock);
892 : :
893 : 1544 : PG_RETURN_NULL();
894 : : }
895 : :
896 : : /*
897 : : * Heap amcheck's read stream callback for getting the next unskippable block.
898 : : * This callback is only used when 'all-visible' or 'all-frozen' is provided
899 : : * as the skip option to verify_heapam(). With the default 'none',
900 : : * block_range_read_stream_cb() is used instead.
901 : : */
902 : : static BlockNumber
903 : 867 : heapcheck_read_stream_next_unskippable(ReadStream *stream,
904 : : void *callback_private_data,
905 : : void *per_buffer_data)
906 : : {
907 : 867 : HeapCheckReadStreamData *p = callback_private_data;
908 : :
909 : : /* Loops over [current_blocknum, last_exclusive) blocks */
910 [ + + ]: 900 : for (BlockNumber i; (i = p->range.current_blocknum++) < p->range.last_exclusive;)
911 : : {
912 : 735 : uint8 mapbits = visibilitymap_get_status(p->rel, i, p->vmbuffer);
913 : :
914 [ + + ]: 735 : if (p->skip_option == SKIP_PAGES_ALL_FROZEN)
915 : : {
916 [ + + ]: 384 : if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
917 : 32 : continue;
918 : : }
919 : :
920 [ + + ]: 703 : if (p->skip_option == SKIP_PAGES_ALL_VISIBLE)
921 : : {
922 [ + + ]: 351 : if ((mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0)
923 : 1 : continue;
924 : : }
925 : :
926 : 702 : return i;
927 : : }
928 : :
929 : 165 : return InvalidBlockNumber;
930 : : }
931 : :
932 : : /*
933 : : * Shared internal implementation for report_corruption and
934 : : * report_toast_corruption.
935 : : */
936 : : static void
937 : 88 : report_corruption_internal(Tuplestorestate *tupstore, TupleDesc tupdesc,
938 : : BlockNumber blkno, OffsetNumber offnum,
939 : : AttrNumber attnum, char *msg)
940 : : {
941 : 88 : Datum values[HEAPCHECK_RELATION_COLS] = {0};
942 : 88 : bool nulls[HEAPCHECK_RELATION_COLS] = {0};
943 : : HeapTuple tuple;
944 : :
945 : 88 : values[0] = Int64GetDatum(blkno);
946 : 88 : values[1] = Int32GetDatum(offnum);
947 : 88 : values[2] = Int32GetDatum(attnum);
948 : 88 : nulls[2] = (attnum < 0);
949 : 88 : values[3] = CStringGetTextDatum(msg);
950 : :
951 : : /*
952 : : * In principle, there is nothing to prevent a scan over a large, highly
953 : : * corrupted table from using work_mem worth of memory building up the
954 : : * tuplestore. That's ok, but if we also leak the msg argument memory
955 : : * until the end of the query, we could exceed work_mem by more than a
956 : : * trivial amount. Therefore, free the msg argument each time we are
957 : : * called rather than waiting for our current memory context to be freed.
958 : : */
959 : 88 : pfree(msg);
960 : :
961 : 88 : tuple = heap_form_tuple(tupdesc, values, nulls);
962 : 88 : tuplestore_puttuple(tupstore, tuple);
963 : 88 : }
964 : :
965 : : /*
966 : : * Record a single corruption found in the main table. The values in ctx should
967 : : * indicate the location of the corruption, and the msg argument should contain
968 : : * a human-readable description of the corruption.
969 : : *
970 : : * The msg argument is pfree'd by this function.
971 : : */
972 : : static void
973 : 87 : report_corruption(HeapCheckContext *ctx, char *msg)
974 : : {
975 : 87 : report_corruption_internal(ctx->tupstore, ctx->tupdesc, ctx->blkno,
976 : 87 : ctx->offnum, ctx->attnum, msg);
977 : 87 : ctx->is_corrupt = true;
978 : 87 : }
979 : :
980 : : /*
981 : : * Record corruption found in the toast table. The values in ta should
982 : : * indicate the location in the main table where the toast pointer was
983 : : * encountered, and the msg argument should contain a human-readable
984 : : * description of the toast table corruption.
985 : : *
986 : : * As above, the msg argument is pfree'd by this function.
987 : : */
988 : : static void
989 : 1 : report_toast_corruption(HeapCheckContext *ctx, ToastedAttribute *ta,
990 : : char *msg)
991 : : {
992 : 1 : report_corruption_internal(ctx->tupstore, ctx->tupdesc, ta->blkno,
993 : 1 : ta->offnum, ta->attnum, msg);
994 : 1 : ctx->is_corrupt = true;
995 : 1 : }
996 : :
997 : : /*
998 : : * Check for tuple header corruption.
999 : : *
1000 : : * Some kinds of corruption make it unsafe to check the tuple attributes, for
1001 : : * example when the line pointer refers to a range of bytes outside the page.
1002 : : * In such cases, we return false (not checkable) after recording appropriate
1003 : : * corruption messages.
1004 : : *
1005 : : * Some other kinds of tuple header corruption confuse the question of where
1006 : : * the tuple attributes begin, or how long the nulls bitmap is, etc., making it
1007 : : * unreasonable to attempt to check attributes, even if all candidate answers
1008 : : * to those questions would not result in reading past the end of the line
1009 : : * pointer or page. In such cases, like above, we record corruption messages
1010 : : * about the header and then return false.
1011 : : *
1012 : : * Other kinds of tuple header corruption do not bear on the question of
1013 : : * whether the tuple attributes can be checked, so we record corruption
1014 : : * messages for them but we do not return false merely because we detected
1015 : : * them.
1016 : : *
1017 : : * Returns whether the tuple is sufficiently sensible to undergo visibility and
1018 : : * attribute checks.
1019 : : */
1020 : : static bool
1021 : 577800 : check_tuple_header(HeapCheckContext *ctx)
1022 : : {
1023 : 577800 : HeapTupleHeader tuphdr = ctx->tuphdr;
1024 : 577800 : uint16 infomask = tuphdr->t_infomask;
1025 : 577800 : TransactionId curr_xmax = HeapTupleHeaderGetUpdateXid(tuphdr);
1026 : 577800 : bool result = true;
1027 : : unsigned expected_hoff;
1028 : :
1029 [ + + ]: 577800 : if (ctx->tuphdr->t_hoff > ctx->lp_len)
1030 : : {
1031 : 1 : report_corruption(ctx,
1032 : : psprintf("data begins at offset %u beyond the tuple length %u",
1033 : 1 : ctx->tuphdr->t_hoff, ctx->lp_len));
1034 : 1 : result = false;
1035 : : }
1036 : :
1037 [ + + ]: 577800 : if ((ctx->tuphdr->t_infomask & HEAP_XMAX_COMMITTED) &&
1038 [ + + ]: 204 : (ctx->tuphdr->t_infomask & HEAP_XMAX_IS_MULTI))
1039 : : {
1040 : 2 : report_corruption(ctx,
1041 : : pstrdup("multixact should not be marked committed"));
1042 : :
1043 : : /*
1044 : : * This condition is clearly wrong, but it's not enough to justify
1045 : : * skipping further checks, because we don't rely on this to determine
1046 : : * whether the tuple is visible or to interpret other relevant header
1047 : : * fields.
1048 : : */
1049 : : }
1050 : :
1051 [ + + ]: 577800 : if (HeapTupleHeaderIsDatum(ctx->tuphdr))
1052 : : {
1053 : 2 : report_corruption(ctx,
1054 : : pstrdup("tuple marked as datum tuple in table"));
1055 : : /* Here again, we can still perform further checks. */
1056 : : }
1057 : :
1058 [ + + + + ]: 1154430 : if (!TransactionIdIsValid(curr_xmax) &&
1059 : 576630 : HeapTupleHeaderIsHotUpdated(tuphdr))
1060 : : {
1061 : 1 : report_corruption(ctx,
1062 : : psprintf("tuple has been HOT updated, but xmax is 0"));
1063 : :
1064 : : /*
1065 : : * As above, even though this shouldn't happen, it's not sufficient
1066 : : * justification for skipping further checks, we should still be able
1067 : : * to perform sensibly.
1068 : : */
1069 : : }
1070 : :
1071 [ + + ]: 577800 : if (HeapTupleHeaderIsHeapOnly(tuphdr) &&
1072 [ + + ]: 5001 : ((tuphdr->t_infomask & HEAP_UPDATED) == 0))
1073 : : {
1074 : 1 : report_corruption(ctx,
1075 : : psprintf("tuple is heap only, but not the result of an update"));
1076 : :
1077 : : /* Here again, we can still perform further checks. */
1078 : : }
1079 : :
1080 [ + + ]: 577800 : if (infomask & HEAP_HASNULL)
1081 : 261032 : expected_hoff = MAXALIGN(SizeofHeapTupleHeader + BITMAPLEN(ctx->natts));
1082 : : else
1083 : 316768 : expected_hoff = MAXALIGN(SizeofHeapTupleHeader);
1084 [ + + ]: 577800 : if (ctx->tuphdr->t_hoff != expected_hoff)
1085 : : {
1086 [ + + - + ]: 5 : if ((infomask & HEAP_HASNULL) && ctx->natts == 1)
1087 : 0 : report_corruption(ctx,
1088 : : psprintf("tuple data should begin at byte %u, but actually begins at byte %u (1 attribute, has nulls)",
1089 : 0 : expected_hoff, ctx->tuphdr->t_hoff));
1090 [ + + ]: 5 : else if ((infomask & HEAP_HASNULL))
1091 : 1 : report_corruption(ctx,
1092 : : psprintf("tuple data should begin at byte %u, but actually begins at byte %u (%u attributes, has nulls)",
1093 : 1 : expected_hoff, ctx->tuphdr->t_hoff, ctx->natts));
1094 [ - + ]: 4 : else if (ctx->natts == 1)
1095 : 0 : report_corruption(ctx,
1096 : : psprintf("tuple data should begin at byte %u, but actually begins at byte %u (1 attribute, no nulls)",
1097 : 0 : expected_hoff, ctx->tuphdr->t_hoff));
1098 : : else
1099 : 4 : report_corruption(ctx,
1100 : : psprintf("tuple data should begin at byte %u, but actually begins at byte %u (%u attributes, no nulls)",
1101 : 4 : expected_hoff, ctx->tuphdr->t_hoff, ctx->natts));
1102 : 5 : result = false;
1103 : : }
1104 : :
1105 : 577800 : return result;
1106 : : }
1107 : :
1108 : : /*
1109 : : * Checks tuple visibility so we know which further checks are safe to
1110 : : * perform.
1111 : : *
1112 : : * If a tuple could have been inserted by a transaction that also added a
1113 : : * column to the table, but which ultimately did not commit, or which has not
1114 : : * yet committed, then the table's current TupleDesc might differ from the one
1115 : : * used to construct this tuple, so we must not check it.
1116 : : *
1117 : : * As a special case, if our own transaction inserted the tuple, even if we
1118 : : * added a column to the table, our TupleDesc should match. We could check the
1119 : : * tuple, but choose not to do so.
1120 : : *
1121 : : * If a tuple has been updated or deleted, we can still read the old tuple for
1122 : : * corruption checking purposes, as long as we are careful about concurrent
1123 : : * vacuums. The main table tuple itself cannot be vacuumed away because we
1124 : : * hold a buffer lock on the page, but if the deleting transaction is older
1125 : : * than our transaction snapshot's xmin, then vacuum could remove the toast at
1126 : : * any time, so we must not try to follow TOAST pointers.
1127 : : *
1128 : : * If xmin or xmax values are older than can be checked against clog, or appear
1129 : : * to be in the future (possibly due to wrap-around), then we cannot make a
1130 : : * determination about the visibility of the tuple, so we skip further checks.
1131 : : *
1132 : : * Returns true if the tuple itself should be checked, false otherwise. Sets
1133 : : * ctx->tuple_could_be_pruned if the tuple -- and thus also any associated
1134 : : * TOAST tuples -- are eligible for pruning.
1135 : : *
1136 : : * Sets *xmin_commit_status_ok to true if the commit status of xmin is known
1137 : : * and false otherwise. If it's set to true, then also set *xmin_commit_status
1138 : : * to the actual commit status.
1139 : : */
1140 : : static bool
1141 : 577795 : check_tuple_visibility(HeapCheckContext *ctx, bool *xmin_commit_status_ok,
1142 : : XidCommitStatus *xmin_commit_status)
1143 : : {
1144 : : TransactionId xmin;
1145 : : TransactionId xvac;
1146 : : TransactionId xmax;
1147 : : XidCommitStatus xmin_status;
1148 : : XidCommitStatus xvac_status;
1149 : : XidCommitStatus xmax_status;
1150 : 577795 : HeapTupleHeader tuphdr = ctx->tuphdr;
1151 : :
1152 : 577795 : ctx->tuple_could_be_pruned = true; /* have not yet proven otherwise */
1153 : 577795 : *xmin_commit_status_ok = false; /* have not yet proven otherwise */
1154 : :
1155 : : /* If xmin is normal, it should be within valid range */
1156 : 577795 : xmin = HeapTupleHeaderGetXmin(tuphdr);
1157 [ - + + + : 577795 : switch (get_xid_status(xmin, ctx, &xmin_status))
+ - ]
1158 : : {
1159 : 0 : case XID_INVALID:
1160 : : /* Could be the result of a speculative insertion that aborted. */
1161 : 0 : return false;
1162 : 577791 : case XID_BOUNDS_OK:
1163 : 577791 : *xmin_commit_status_ok = true;
1164 : 577791 : *xmin_commit_status = xmin_status;
1165 : 577791 : break;
1166 : 1 : case XID_IN_FUTURE:
1167 : 1 : report_corruption(ctx,
1168 : : psprintf("xmin %u equals or exceeds next valid transaction ID %u:%u",
1169 : : xmin,
1170 : 1 : EpochFromFullTransactionId(ctx->next_fxid),
1171 : 1 : XidFromFullTransactionId(ctx->next_fxid)));
1172 : 1 : return false;
1173 : 2 : case XID_PRECEDES_CLUSTERMIN:
1174 : 2 : report_corruption(ctx,
1175 : : psprintf("xmin %u precedes oldest valid transaction ID %u:%u",
1176 : : xmin,
1177 : 2 : EpochFromFullTransactionId(ctx->oldest_fxid),
1178 : 2 : XidFromFullTransactionId(ctx->oldest_fxid)));
1179 : 2 : return false;
1180 : 1 : case XID_PRECEDES_RELMIN:
1181 : 1 : report_corruption(ctx,
1182 : : psprintf("xmin %u precedes relation freeze threshold %u:%u",
1183 : : xmin,
1184 : 1 : EpochFromFullTransactionId(ctx->relfrozenfxid),
1185 : 1 : XidFromFullTransactionId(ctx->relfrozenfxid)));
1186 : 1 : return false;
1187 : : }
1188 : :
1189 : : /*
1190 : : * Has inserting transaction committed?
1191 : : */
1192 [ + + ]: 577791 : if (!HeapTupleHeaderXminCommitted(tuphdr))
1193 : : {
1194 [ - + ]: 8104 : if (HeapTupleHeaderXminInvalid(tuphdr))
1195 : 0 : return false; /* inserter aborted, don't check */
1196 : : /* Used by pre-9.0 binary upgrades */
1197 [ - + ]: 8104 : else if (tuphdr->t_infomask & HEAP_MOVED_OFF)
1198 : : {
1199 : 0 : xvac = HeapTupleHeaderGetXvac(tuphdr);
1200 : :
1201 [ # # # # : 0 : switch (get_xid_status(xvac, ctx, &xvac_status))
# # ]
1202 : : {
1203 : 0 : case XID_INVALID:
1204 : 0 : report_corruption(ctx,
1205 : : pstrdup("old-style VACUUM FULL transaction ID for moved off tuple is invalid"));
1206 : 0 : return false;
1207 : 0 : case XID_IN_FUTURE:
1208 : 0 : report_corruption(ctx,
1209 : : psprintf("old-style VACUUM FULL transaction ID %u for moved off tuple equals or exceeds next valid transaction ID %u:%u",
1210 : : xvac,
1211 : 0 : EpochFromFullTransactionId(ctx->next_fxid),
1212 : 0 : XidFromFullTransactionId(ctx->next_fxid)));
1213 : 0 : return false;
1214 : 0 : case XID_PRECEDES_RELMIN:
1215 : 0 : report_corruption(ctx,
1216 : : psprintf("old-style VACUUM FULL transaction ID %u for moved off tuple precedes relation freeze threshold %u:%u",
1217 : : xvac,
1218 : 0 : EpochFromFullTransactionId(ctx->relfrozenfxid),
1219 : 0 : XidFromFullTransactionId(ctx->relfrozenfxid)));
1220 : 0 : return false;
1221 : 0 : case XID_PRECEDES_CLUSTERMIN:
1222 : 0 : report_corruption(ctx,
1223 : : psprintf("old-style VACUUM FULL transaction ID %u for moved off tuple precedes oldest valid transaction ID %u:%u",
1224 : : xvac,
1225 : 0 : EpochFromFullTransactionId(ctx->oldest_fxid),
1226 : 0 : XidFromFullTransactionId(ctx->oldest_fxid)));
1227 : 0 : return false;
1228 : 0 : case XID_BOUNDS_OK:
1229 : 0 : break;
1230 : : }
1231 : :
1232 [ # # # # : 0 : switch (xvac_status)
# ]
1233 : : {
1234 : 0 : case XID_IS_CURRENT_XID:
1235 : 0 : report_corruption(ctx,
1236 : : psprintf("old-style VACUUM FULL transaction ID %u for moved off tuple matches our current transaction ID",
1237 : : xvac));
1238 : 0 : return false;
1239 : 0 : case XID_IN_PROGRESS:
1240 : 0 : report_corruption(ctx,
1241 : : psprintf("old-style VACUUM FULL transaction ID %u for moved off tuple appears to be in progress",
1242 : : xvac));
1243 : 0 : return false;
1244 : :
1245 : 0 : case XID_COMMITTED:
1246 : :
1247 : : /*
1248 : : * The tuple is dead, because the xvac transaction moved
1249 : : * it off and committed. It's checkable, but also
1250 : : * prunable.
1251 : : */
1252 : 0 : return true;
1253 : :
1254 : 0 : case XID_ABORTED:
1255 : :
1256 : : /*
1257 : : * The original xmin must have committed, because the xvac
1258 : : * transaction tried to move it later. Since xvac is
1259 : : * aborted, whether it's still alive now depends on the
1260 : : * status of xmax.
1261 : : */
1262 : 0 : break;
1263 : : }
1264 : : }
1265 : : /* Used by pre-9.0 binary upgrades */
1266 [ - + ]: 8104 : else if (tuphdr->t_infomask & HEAP_MOVED_IN)
1267 : : {
1268 : 0 : xvac = HeapTupleHeaderGetXvac(tuphdr);
1269 : :
1270 [ # # # # : 0 : switch (get_xid_status(xvac, ctx, &xvac_status))
# # ]
1271 : : {
1272 : 0 : case XID_INVALID:
1273 : 0 : report_corruption(ctx,
1274 : : pstrdup("old-style VACUUM FULL transaction ID for moved in tuple is invalid"));
1275 : 0 : return false;
1276 : 0 : case XID_IN_FUTURE:
1277 : 0 : report_corruption(ctx,
1278 : : psprintf("old-style VACUUM FULL transaction ID %u for moved in tuple equals or exceeds next valid transaction ID %u:%u",
1279 : : xvac,
1280 : 0 : EpochFromFullTransactionId(ctx->next_fxid),
1281 : 0 : XidFromFullTransactionId(ctx->next_fxid)));
1282 : 0 : return false;
1283 : 0 : case XID_PRECEDES_RELMIN:
1284 : 0 : report_corruption(ctx,
1285 : : psprintf("old-style VACUUM FULL transaction ID %u for moved in tuple precedes relation freeze threshold %u:%u",
1286 : : xvac,
1287 : 0 : EpochFromFullTransactionId(ctx->relfrozenfxid),
1288 : 0 : XidFromFullTransactionId(ctx->relfrozenfxid)));
1289 : 0 : return false;
1290 : 0 : case XID_PRECEDES_CLUSTERMIN:
1291 : 0 : report_corruption(ctx,
1292 : : psprintf("old-style VACUUM FULL transaction ID %u for moved in tuple precedes oldest valid transaction ID %u:%u",
1293 : : xvac,
1294 : 0 : EpochFromFullTransactionId(ctx->oldest_fxid),
1295 : 0 : XidFromFullTransactionId(ctx->oldest_fxid)));
1296 : 0 : return false;
1297 : 0 : case XID_BOUNDS_OK:
1298 : 0 : break;
1299 : : }
1300 : :
1301 [ # # # # : 0 : switch (xvac_status)
# ]
1302 : : {
1303 : 0 : case XID_IS_CURRENT_XID:
1304 : 0 : report_corruption(ctx,
1305 : : psprintf("old-style VACUUM FULL transaction ID %u for moved in tuple matches our current transaction ID",
1306 : : xvac));
1307 : 0 : return false;
1308 : 0 : case XID_IN_PROGRESS:
1309 : 0 : report_corruption(ctx,
1310 : : psprintf("old-style VACUUM FULL transaction ID %u for moved in tuple appears to be in progress",
1311 : : xvac));
1312 : 0 : return false;
1313 : :
1314 : 0 : case XID_COMMITTED:
1315 : :
1316 : : /*
1317 : : * The original xmin must have committed, because the xvac
1318 : : * transaction moved it later. Whether it's still alive
1319 : : * now depends on the status of xmax.
1320 : : */
1321 : 0 : break;
1322 : :
1323 : 0 : case XID_ABORTED:
1324 : :
1325 : : /*
1326 : : * The tuple is dead, because the xvac transaction moved
1327 : : * it off and committed. It's checkable, but also
1328 : : * prunable.
1329 : : */
1330 : 0 : return true;
1331 : : }
1332 : : }
1333 [ + + ]: 8104 : else if (xmin_status != XID_COMMITTED)
1334 : : {
1335 : : /*
1336 : : * Inserting transaction is not in progress, and not committed, so
1337 : : * it might have changed the TupleDesc in ways we don't know
1338 : : * about. Thus, don't try to check the tuple structure.
1339 : : *
1340 : : * If xmin_status happens to be XID_IS_CURRENT_XID, then in theory
1341 : : * any such DDL changes ought to be visible to us, so perhaps we
1342 : : * could check anyway in that case. But, for now, let's be
1343 : : * conservative and treat this like any other uncommitted insert.
1344 : : */
1345 : 7 : return false;
1346 : : }
1347 : : }
1348 : :
1349 : : /*
1350 : : * Okay, the inserter committed, so it was good at some point. Now what
1351 : : * about the deleting transaction?
1352 : : */
1353 : :
1354 [ + + ]: 577784 : if (tuphdr->t_infomask & HEAP_XMAX_IS_MULTI)
1355 : : {
1356 : : /*
1357 : : * xmax is a multixact, so sanity-check the MXID. Note that we do this
1358 : : * prior to checking for HEAP_XMAX_INVALID or
1359 : : * HEAP_XMAX_IS_LOCKED_ONLY. This might therefore complain about
1360 : : * things that wouldn't actually be a problem during a normal scan,
1361 : : * but eventually we're going to have to freeze, and that process will
1362 : : * ignore hint bits.
1363 : : *
1364 : : * Even if the MXID is out of range, we still know that the original
1365 : : * insert committed, so we can check the tuple itself. However, we
1366 : : * can't rule out the possibility that this tuple is dead, so don't
1367 : : * clear ctx->tuple_could_be_pruned. Possibly we should go ahead and
1368 : : * clear that flag anyway if HEAP_XMAX_INVALID is set or if
1369 : : * HEAP_XMAX_IS_LOCKED_ONLY is true, but for now we err on the side of
1370 : : * avoiding possibly-bogus complaints about missing TOAST entries.
1371 : : */
1372 : 58 : xmax = HeapTupleHeaderGetRawXmax(tuphdr);
1373 [ - + - + : 58 : switch (check_mxid_valid_in_rel(xmax, ctx))
+ - ]
1374 : : {
1375 : 0 : case XID_INVALID:
1376 : 0 : report_corruption(ctx,
1377 : : pstrdup("multitransaction ID is invalid"));
1378 : 0 : return true;
1379 : 1 : case XID_PRECEDES_RELMIN:
1380 : 1 : report_corruption(ctx,
1381 : : psprintf("multitransaction ID %u precedes relation minimum multitransaction ID threshold %u",
1382 : : xmax, ctx->relminmxid));
1383 : 1 : return true;
1384 : 0 : case XID_PRECEDES_CLUSTERMIN:
1385 : 0 : report_corruption(ctx,
1386 : : psprintf("multitransaction ID %u precedes oldest valid multitransaction ID threshold %u",
1387 : : xmax, ctx->oldest_mxact));
1388 : 0 : return true;
1389 : 1 : case XID_IN_FUTURE:
1390 : 1 : report_corruption(ctx,
1391 : : psprintf("multitransaction ID %u equals or exceeds next valid multitransaction ID %u",
1392 : : xmax,
1393 : : ctx->next_mxact));
1394 : 1 : return true;
1395 : 56 : case XID_BOUNDS_OK:
1396 : 56 : break;
1397 : : }
1398 : : }
1399 : :
1400 [ + + ]: 577782 : if (tuphdr->t_infomask & HEAP_XMAX_INVALID)
1401 : : {
1402 : : /*
1403 : : * This tuple is live. A concurrently running transaction could
1404 : : * delete it before we get around to checking the toast, but any such
1405 : : * running transaction is surely not less than our safe_xmin, so the
1406 : : * toast cannot be vacuumed out from under us.
1407 : : */
1408 : 576617 : ctx->tuple_could_be_pruned = false;
1409 : 576617 : return true;
1410 : : }
1411 : :
1412 [ + + ]: 1165 : if (HEAP_XMAX_IS_LOCKED_ONLY(tuphdr->t_infomask))
1413 : : {
1414 : : /*
1415 : : * "Deleting" xact really only locked it, so the tuple is live in any
1416 : : * case. As above, a concurrently running transaction could delete
1417 : : * it, but it cannot be vacuumed out from under us.
1418 : : */
1419 : 28 : ctx->tuple_could_be_pruned = false;
1420 : 28 : return true;
1421 : : }
1422 : :
1423 [ + + ]: 1137 : if (tuphdr->t_infomask & HEAP_XMAX_IS_MULTI)
1424 : : {
1425 : : /*
1426 : : * We already checked above that this multixact is within limits for
1427 : : * this table. Now check the update xid from this multixact.
1428 : : */
1429 : 28 : xmax = HeapTupleGetUpdateXid(tuphdr);
1430 [ - - - - : 28 : switch (get_xid_status(xmax, ctx, &xmax_status))
+ - ]
1431 : : {
1432 : 0 : case XID_INVALID:
1433 : : /* not LOCKED_ONLY, so it has to have an xmax */
1434 : 0 : report_corruption(ctx,
1435 : : pstrdup("update xid is invalid"));
1436 : 0 : return true;
1437 : 0 : case XID_IN_FUTURE:
1438 : 0 : report_corruption(ctx,
1439 : : psprintf("update xid %u equals or exceeds next valid transaction ID %u:%u",
1440 : : xmax,
1441 : 0 : EpochFromFullTransactionId(ctx->next_fxid),
1442 : 0 : XidFromFullTransactionId(ctx->next_fxid)));
1443 : 0 : return true;
1444 : 0 : case XID_PRECEDES_RELMIN:
1445 : 0 : report_corruption(ctx,
1446 : : psprintf("update xid %u precedes relation freeze threshold %u:%u",
1447 : : xmax,
1448 : 0 : EpochFromFullTransactionId(ctx->relfrozenfxid),
1449 : 0 : XidFromFullTransactionId(ctx->relfrozenfxid)));
1450 : 0 : return true;
1451 : 0 : case XID_PRECEDES_CLUSTERMIN:
1452 : 0 : report_corruption(ctx,
1453 : : psprintf("update xid %u precedes oldest valid transaction ID %u:%u",
1454 : : xmax,
1455 : 0 : EpochFromFullTransactionId(ctx->oldest_fxid),
1456 : 0 : XidFromFullTransactionId(ctx->oldest_fxid)));
1457 : 0 : return true;
1458 : 28 : case XID_BOUNDS_OK:
1459 : 28 : break;
1460 : : }
1461 : :
1462 [ - + - - ]: 28 : switch (xmax_status)
1463 : : {
1464 : 0 : case XID_IS_CURRENT_XID:
1465 : : case XID_IN_PROGRESS:
1466 : :
1467 : : /*
1468 : : * The delete is in progress, so it cannot be visible to our
1469 : : * snapshot.
1470 : : */
1471 : 0 : ctx->tuple_could_be_pruned = false;
1472 : 0 : break;
1473 : 28 : case XID_COMMITTED:
1474 : :
1475 : : /*
1476 : : * The delete committed. Whether the toast can be vacuumed
1477 : : * away depends on how old the deleting transaction is.
1478 : : */
1479 : 28 : ctx->tuple_could_be_pruned = TransactionIdPrecedes(xmax,
1480 : : ctx->safe_xmin);
1481 : 28 : break;
1482 : 0 : case XID_ABORTED:
1483 : :
1484 : : /*
1485 : : * The delete aborted or crashed. The tuple is still live.
1486 : : */
1487 : 0 : ctx->tuple_could_be_pruned = false;
1488 : 0 : break;
1489 : : }
1490 : :
1491 : : /* Tuple itself is checkable even if it's dead. */
1492 : 28 : return true;
1493 : : }
1494 : :
1495 : : /* xmax is an XID, not a MXID. Sanity check it. */
1496 : 1109 : xmax = HeapTupleHeaderGetRawXmax(tuphdr);
1497 [ + - - + : 1109 : switch (get_xid_status(xmax, ctx, &xmax_status))
+ - ]
1498 : : {
1499 : 1 : case XID_INVALID:
1500 : 1 : ctx->tuple_could_be_pruned = false;
1501 : 1 : return true;
1502 : 0 : case XID_IN_FUTURE:
1503 : 0 : report_corruption(ctx,
1504 : : psprintf("xmax %u equals or exceeds next valid transaction ID %u:%u",
1505 : : xmax,
1506 : 0 : EpochFromFullTransactionId(ctx->next_fxid),
1507 : 0 : XidFromFullTransactionId(ctx->next_fxid)));
1508 : 0 : return false; /* corrupt */
1509 : 0 : case XID_PRECEDES_RELMIN:
1510 : 0 : report_corruption(ctx,
1511 : : psprintf("xmax %u precedes relation freeze threshold %u:%u",
1512 : : xmax,
1513 : 0 : EpochFromFullTransactionId(ctx->relfrozenfxid),
1514 : 0 : XidFromFullTransactionId(ctx->relfrozenfxid)));
1515 : 0 : return false; /* corrupt */
1516 : 1 : case XID_PRECEDES_CLUSTERMIN:
1517 : 1 : report_corruption(ctx,
1518 : : psprintf("xmax %u precedes oldest valid transaction ID %u:%u",
1519 : : xmax,
1520 : 1 : EpochFromFullTransactionId(ctx->oldest_fxid),
1521 : 1 : XidFromFullTransactionId(ctx->oldest_fxid)));
1522 : 1 : return false; /* corrupt */
1523 : 1107 : case XID_BOUNDS_OK:
1524 : 1107 : break;
1525 : : }
1526 : :
1527 : : /*
1528 : : * Whether the toast can be vacuumed away depends on how old the deleting
1529 : : * transaction is.
1530 : : */
1531 [ - + + - ]: 1107 : switch (xmax_status)
1532 : : {
1533 : 0 : case XID_IS_CURRENT_XID:
1534 : : case XID_IN_PROGRESS:
1535 : :
1536 : : /*
1537 : : * The delete is in progress, so it cannot be visible to our
1538 : : * snapshot.
1539 : : */
1540 : 0 : ctx->tuple_could_be_pruned = false;
1541 : 0 : break;
1542 : :
1543 : 1104 : case XID_COMMITTED:
1544 : :
1545 : : /*
1546 : : * The delete committed. Whether the toast can be vacuumed away
1547 : : * depends on how old the deleting transaction is.
1548 : : */
1549 : 1104 : ctx->tuple_could_be_pruned = TransactionIdPrecedes(xmax,
1550 : : ctx->safe_xmin);
1551 : 1104 : break;
1552 : :
1553 : 3 : case XID_ABORTED:
1554 : :
1555 : : /*
1556 : : * The delete aborted or crashed. The tuple is still live.
1557 : : */
1558 : 3 : ctx->tuple_could_be_pruned = false;
1559 : 3 : break;
1560 : : }
1561 : :
1562 : : /* Tuple itself is checkable even if it's dead. */
1563 : 1107 : return true;
1564 : : }
1565 : :
1566 : :
1567 : : /*
1568 : : * Check the current toast tuple against the state tracked in ctx, recording
1569 : : * any corruption found in ctx->tupstore.
1570 : : *
1571 : : * This is not equivalent to running verify_heapam on the toast table itself,
1572 : : * and is not hardened against corruption of the toast table. Rather, when
1573 : : * validating a toasted attribute in the main table, the sequence of toast
1574 : : * tuples that store the toasted value are retrieved and checked in order, with
1575 : : * each toast tuple being checked against where we are in the sequence, as well
1576 : : * as each toast tuple having its varlena structure sanity checked.
1577 : : *
1578 : : * On entry, *expected_chunk_seq should be the chunk_seq value that we expect
1579 : : * to find in toasttup. On exit, it will be updated to the value the next call
1580 : : * to this function should expect to see.
1581 : : */
1582 : : static void
1583 : 42140 : check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx,
1584 : : ToastedAttribute *ta, int32 *expected_chunk_seq,
1585 : : uint32 extsize, int32 max_chunk_size)
1586 : : {
1587 : : int32 chunk_seq;
1588 : : int32 last_chunk_seq;
1589 : : Pointer chunk;
1590 : : bool isnull;
1591 : : int32 chunksize;
1592 : : int32 expected_size;
1593 : 42140 : Oid8 toast_valueid = ta->va_valueid;
1594 : :
1595 : 42140 : last_chunk_seq = (extsize - 1) / max_chunk_size;
1596 : :
1597 : : /* Sanity-check the sequence number. */
1598 : 42140 : chunk_seq = DatumGetInt32(fastgetattr(toasttup, 2,
1599 : 42140 : ctx->toast_rel->rd_att, &isnull));
1600 [ - + ]: 42140 : if (isnull)
1601 : : {
1602 : 0 : report_toast_corruption(ctx, ta,
1603 : : psprintf("toast value %" PRIu64 " has toast chunk with null sequence number",
1604 : : toast_valueid));
1605 : 0 : return;
1606 : : }
1607 [ - + ]: 42140 : if (chunk_seq != *expected_chunk_seq)
1608 : : {
1609 : : /* Either the TOAST index is corrupt, or we don't have all chunks. */
1610 : 0 : report_toast_corruption(ctx, ta,
1611 : : psprintf("toast value %" PRIu64 " index scan returned chunk %d when expecting chunk %d",
1612 : : toast_valueid,
1613 : : chunk_seq, *expected_chunk_seq));
1614 : : }
1615 : 42140 : *expected_chunk_seq = chunk_seq + 1;
1616 : :
1617 : : /* Sanity-check the chunk data. */
1618 : 42140 : chunk = DatumGetPointer(fastgetattr(toasttup, 3,
1619 : 42140 : ctx->toast_rel->rd_att, &isnull));
1620 [ - + ]: 42140 : if (isnull)
1621 : : {
1622 : 0 : report_toast_corruption(ctx, ta,
1623 : : psprintf("toast value %" PRIu64 " chunk %d has null data",
1624 : : toast_valueid,
1625 : : chunk_seq));
1626 : 0 : return;
1627 : : }
1628 [ + - ]: 42140 : if (!VARATT_IS_EXTENDED(chunk))
1629 : 42140 : chunksize = VARSIZE(chunk) - VARHDRSZ;
1630 [ # # ]: 0 : else if (VARATT_IS_SHORT(chunk))
1631 : : {
1632 : : /*
1633 : : * could happen due to heap_form_tuple doing its thing
1634 : : */
1635 : 0 : chunksize = VARSIZE_SHORT(chunk) - VARHDRSZ_SHORT;
1636 : : }
1637 : : else
1638 : : {
1639 : : /* should never happen */
1640 : 0 : uint32 header = ((varattrib_4b *) chunk)->va_4byte.va_header;
1641 : :
1642 : 0 : report_toast_corruption(ctx, ta,
1643 : : psprintf("toast value %" PRIu64 " chunk %d has invalid varlena header %0x",
1644 : : toast_valueid,
1645 : : chunk_seq, header));
1646 : 0 : return;
1647 : : }
1648 : :
1649 : : /*
1650 : : * Some checks on the data we've found
1651 : : */
1652 [ - + ]: 42140 : if (chunk_seq > last_chunk_seq)
1653 : : {
1654 : 0 : report_toast_corruption(ctx, ta,
1655 : : psprintf("toast value %" PRIu64 " chunk %d follows last expected chunk %d",
1656 : : toast_valueid,
1657 : : chunk_seq, last_chunk_seq));
1658 : 0 : return;
1659 : : }
1660 : :
1661 : 42140 : expected_size = chunk_seq < last_chunk_seq ? max_chunk_size
1662 [ + + ]: 42140 : : extsize - (last_chunk_seq * max_chunk_size);
1663 : :
1664 [ - + ]: 42140 : if (chunksize != expected_size)
1665 : 0 : report_toast_corruption(ctx, ta,
1666 : : psprintf("toast value %" PRIu64 " chunk %d has size %u, but expected size %u",
1667 : : toast_valueid,
1668 : : chunk_seq, chunksize, expected_size));
1669 : : }
1670 : :
1671 : : /*
1672 : : * Check the current attribute as tracked in ctx, recording any corruption
1673 : : * found in ctx->tupstore.
1674 : : *
1675 : : * This function follows the logic performed by heap_deform_tuple(), and in the
1676 : : * case of a toasted value, optionally stores the toast pointer so later it can
1677 : : * be checked following the logic of detoast_external_attr(), checking for any
1678 : : * conditions that would result in either of those functions Asserting or
1679 : : * crashing the backend. The checks performed by Asserts present in those two
1680 : : * functions are also performed here and in check_toasted_attribute. In cases
1681 : : * where those two functions are a bit cavalier in their assumptions about data
1682 : : * being correct, we perform additional checks not present in either of those
1683 : : * two functions. Where some condition is checked in both of those functions,
1684 : : * we perform it here twice, as we parallel the logical flow of those two
1685 : : * functions. The presence of duplicate checks seems a reasonable price to pay
1686 : : * for keeping this code tightly coupled with the code it protects.
1687 : : *
1688 : : * Returns true if the tuple attribute is sane enough for processing to
1689 : : * continue on to the next attribute, false otherwise.
1690 : : */
1691 : : static bool
1692 : 8425279 : check_tuple_attribute(HeapCheckContext *ctx)
1693 : : {
1694 : : Datum attdatum;
1695 : : varlena *attr;
1696 : : char *tp; /* pointer to the tuple data */
1697 : : uint16 infomask;
1698 : : Oid8 toast_pointer_valueid;
1699 : : int32 va_rawsize;
1700 : : uint32 va_extinfo;
1701 : : CompactAttribute *thisatt;
1702 : : vartag_external va_tag_value;
1703 : : toast_external_data toast_ext_data;
1704 : :
1705 : 8425279 : infomask = ctx->tuphdr->t_infomask;
1706 : 8425279 : thisatt = TupleDescCompactAttr(RelationGetDescr(ctx->rel), ctx->attnum);
1707 : :
1708 : 8425279 : tp = (char *) ctx->tuphdr + ctx->tuphdr->t_hoff;
1709 : :
1710 [ - + ]: 8425279 : if (ctx->tuphdr->t_hoff + ctx->offset > ctx->lp_len)
1711 : : {
1712 : 0 : report_corruption(ctx,
1713 : : psprintf("attribute with length %u starts at offset %u beyond total tuple length %u",
1714 : 0 : thisatt->attlen,
1715 : 0 : ctx->tuphdr->t_hoff + ctx->offset,
1716 : 0 : ctx->lp_len));
1717 : 0 : return false;
1718 : : }
1719 : :
1720 : : /* Skip null values */
1721 [ + + + + ]: 8425279 : if (infomask & HEAP_HASNULL && att_isnull(ctx->attnum, ctx->tuphdr->t_bits))
1722 : 1428422 : return true;
1723 : :
1724 : : /* Skip non-varlena values, but update offset first */
1725 [ + + ]: 6996857 : if (thisatt->attlen != -1)
1726 : : {
1727 : 6430102 : ctx->offset = att_nominal_alignby(ctx->offset, thisatt->attalignby);
1728 [ + - - - ]: 6430102 : ctx->offset = att_addlength_pointer(ctx->offset, thisatt->attlen,
1729 : : tp + ctx->offset);
1730 [ - + ]: 6430102 : if (ctx->tuphdr->t_hoff + ctx->offset > ctx->lp_len)
1731 : : {
1732 : 0 : report_corruption(ctx,
1733 : : psprintf("attribute with length %u ends at offset %u beyond total tuple length %u",
1734 : 0 : thisatt->attlen,
1735 : 0 : ctx->tuphdr->t_hoff + ctx->offset,
1736 : 0 : ctx->lp_len));
1737 : 0 : return false;
1738 : : }
1739 : 6430102 : return true;
1740 : : }
1741 : :
1742 : : /* Ok, we're looking at a varlena attribute. */
1743 [ + + ]: 566755 : ctx->offset = att_pointer_alignby(ctx->offset, thisatt->attalignby, -1,
1744 : : tp + ctx->offset);
1745 : :
1746 : : /* Get the (possibly corrupt) varlena datum */
1747 : 566755 : attdatum = fetchatt(thisatt, tp + ctx->offset);
1748 : :
1749 : : /*
1750 : : * We have the datum, but we cannot decode it carelessly, as it may still
1751 : : * be corrupt.
1752 : : */
1753 : :
1754 : : /*
1755 : : * Check that VARTAG_SIZE won't hit an Assert on a corrupt va_tag before
1756 : : * risking a call into att_addlength_pointer
1757 : : */
1758 [ + + ]: 566755 : if (VARATT_IS_EXTERNAL(tp + ctx->offset))
1759 : : {
1760 : 26898 : uint8 va_tag = VARTAG_EXTERNAL(tp + ctx->offset);
1761 : :
1762 [ + + - + ]: 26898 : if (va_tag != VARTAG_ONDISK_OID && va_tag != VARTAG_ONDISK_OID8)
1763 : : {
1764 : 0 : report_corruption(ctx,
1765 : : psprintf("toasted attribute has unexpected TOAST tag %u",
1766 : : va_tag));
1767 : : /* We can't know where the next attribute begins */
1768 : 0 : return false;
1769 : : }
1770 : : }
1771 : :
1772 : : /* Ok, should be safe now */
1773 [ - + + - ]: 566755 : ctx->offset = att_addlength_pointer(ctx->offset, thisatt->attlen,
1774 : : tp + ctx->offset);
1775 : :
1776 [ + + ]: 566755 : if (ctx->tuphdr->t_hoff + ctx->offset > ctx->lp_len)
1777 : : {
1778 : 1 : report_corruption(ctx,
1779 : : psprintf("attribute with length %u ends at offset %u beyond total tuple length %u",
1780 : 1 : thisatt->attlen,
1781 : 1 : ctx->tuphdr->t_hoff + ctx->offset,
1782 : 1 : ctx->lp_len));
1783 : :
1784 : 1 : return false;
1785 : : }
1786 : :
1787 : : /*
1788 : : * heap_deform_tuple would be done with this attribute at this point,
1789 : : * having stored it in values[], and would continue to the next attribute.
1790 : : * We go further, because we need to check if the toast datum is corrupt.
1791 : : */
1792 : :
1793 : 566754 : attr = (varlena *) DatumGetPointer(attdatum);
1794 : :
1795 : : /*
1796 : : * Now we follow the logic of detoast_external_attr(), with the same
1797 : : * caveats about being paranoid about corruption.
1798 : : */
1799 : :
1800 : : /* Skip values that are not external */
1801 [ + + ]: 566754 : if (!VARATT_IS_EXTERNAL(attr))
1802 : 539856 : return true;
1803 : :
1804 : : /* It is external, and we're looking at a page on disk */
1805 : :
1806 : : /* Must copy attr into a decoded pointer for alignment considerations */
1807 : 26898 : toast_external_info_get(attr, &toast_ext_data);
1808 : 26898 : va_tag_value = toast_ext_data.tag;
1809 : 26898 : toast_pointer_valueid = toast_ext_data.valueid;
1810 : 26898 : va_rawsize = toast_ext_data.rawsize;
1811 : 26898 : va_extinfo = toast_ext_data.extinfo;
1812 : :
1813 : : /* Toasted attributes too large to be untoasted should never be stored */
1814 [ - + ]: 26898 : if (va_rawsize > VARLENA_SIZE_LIMIT)
1815 : 0 : report_corruption(ctx,
1816 : : psprintf("toast value %" PRIu64 " rawsize %d exceeds limit %d",
1817 : : toast_pointer_valueid,
1818 : : va_rawsize,
1819 : : VARLENA_SIZE_LIMIT));
1820 : :
1821 [ + + ]: 26898 : if (VARATT_EXTINFO_IS_COMPRESSED(toast_ext_data.extinfo, toast_ext_data.rawsize))
1822 : : {
1823 : : ToastCompressionId cmid;
1824 : 2653 : bool valid = false;
1825 : :
1826 : : /* Compressed attributes should have a valid compression method */
1827 : 2653 : cmid = VARATT_EXTINFO_GET_COMPRESS_METHOD(toast_ext_data.extinfo);
1828 [ + - - ]: 2653 : switch (cmid)
1829 : : {
1830 : : /* List of all valid compression method IDs */
1831 : 2653 : case TOAST_PGLZ_COMPRESSION_ID:
1832 : : case TOAST_LZ4_COMPRESSION_ID:
1833 : 2653 : valid = true;
1834 : 2653 : break;
1835 : :
1836 : : /* Recognized but invalid compression method ID */
1837 : 0 : case TOAST_INVALID_COMPRESSION_ID:
1838 : 0 : break;
1839 : :
1840 : : /* Intentionally no default here */
1841 : : }
1842 [ - + ]: 2653 : if (!valid)
1843 : 0 : report_corruption(ctx,
1844 : : psprintf("toast value %" PRIu64 " has invalid compression method id %d",
1845 : : toast_pointer_valueid, cmid));
1846 : : }
1847 : :
1848 : : /* The tuple header better claim to contain toasted values */
1849 [ - + ]: 26898 : if (!(infomask & HEAP_HASEXTERNAL))
1850 : : {
1851 : 0 : report_corruption(ctx,
1852 : : psprintf("toast value %" PRIu64 " is external but tuple header flag HEAP_HASEXTERNAL not set",
1853 : : toast_pointer_valueid));
1854 : 0 : return true;
1855 : : }
1856 : :
1857 : : /* The relation better have a toast table */
1858 [ - + ]: 26898 : if (!ctx->rel->rd_rel->reltoastrelid)
1859 : : {
1860 : 0 : report_corruption(ctx,
1861 : : psprintf("toast value %" PRIu64 " is external but relation has no toast relation",
1862 : : toast_pointer_valueid));
1863 : 0 : return true;
1864 : : }
1865 : :
1866 : : /* If we were told to skip toast checking, then we're done. */
1867 [ + + ]: 26898 : if (ctx->toast_rel == NULL)
1868 : 14429 : return true;
1869 : :
1870 : : /*
1871 : : * If this tuple is eligible to be pruned, we cannot check the toast.
1872 : : * Otherwise, we push a copy of the toast tuple so we can check it after
1873 : : * releasing the main table buffer lock.
1874 : : */
1875 [ + + ]: 12469 : if (!ctx->tuple_could_be_pruned)
1876 : : {
1877 : : ToastedAttribute *ta;
1878 : :
1879 : 12467 : ta = palloc0_object(ToastedAttribute);
1880 : :
1881 : : /* The pointer has already been decoded above, just reuse it */
1882 : 12467 : ta->tag = va_tag_value;
1883 : 12467 : ta->va_valueid = toast_pointer_valueid;
1884 : 12467 : ta->va_extinfo = va_extinfo;
1885 : 12467 : ta->blkno = ctx->blkno;
1886 : 12467 : ta->offnum = ctx->offnum;
1887 : 12467 : ta->attnum = ctx->attnum;
1888 : 12467 : ctx->toasted_attributes = lappend(ctx->toasted_attributes, ta);
1889 : : }
1890 : :
1891 : 12469 : return true;
1892 : : }
1893 : :
1894 : : /*
1895 : : * For each attribute collected in ctx->toasted_attributes, look up the value
1896 : : * in the toast table and perform checks on it. This function should only be
1897 : : * called on toast pointers which cannot be vacuumed away during our
1898 : : * processing.
1899 : : */
1900 : : static void
1901 : 12461 : check_toasted_attribute(HeapCheckContext *ctx, ToastedAttribute *ta)
1902 : : {
1903 : : ScanKeyData toastkey;
1904 : : SysScanDesc toastscan;
1905 : : bool found_toasttup;
1906 : : HeapTuple toasttup;
1907 : : uint32 extsize;
1908 : 12461 : int32 expected_chunk_seq = 0;
1909 : : int32 last_chunk_seq;
1910 : : int32 max_chunk_size;
1911 : : Oid8 toast_valueid;
1912 : : Oid toast_typid;
1913 : : vartag_external expected_tag;
1914 : :
1915 : 12461 : toast_valueid = ta->va_valueid;
1916 : 12461 : extsize = VARATT_EXTINFO_GET_EXTSIZE(ta->va_extinfo);
1917 : :
1918 : : /*
1919 : : * Take the chunk_id type from the TOAST table's own definition, not from
1920 : : * the vartag in the main table as that pointer is the very thing under
1921 : : * scrutiny here. The two must agree.
1922 : : */
1923 : 12461 : toast_typid = TupleDescAttr(ctx->toast_rel->rd_att, 0)->atttypid;
1924 [ + + ]: 12461 : if (toast_typid == OID8OID)
1925 : 2 : expected_tag = VARTAG_ONDISK_OID8;
1926 [ + - ]: 12459 : else if (toast_typid == OIDOID)
1927 : 12459 : expected_tag = VARTAG_ONDISK_OID;
1928 : : else
1929 : : {
1930 : 0 : report_toast_corruption(ctx, ta,
1931 : : psprintf("toast value %" PRIu64 " stored in toast table whose chunk_id has unexpected type %u",
1932 : : toast_valueid, toast_typid));
1933 : 0 : return;
1934 : : }
1935 : :
1936 [ - + ]: 12461 : if (ta->tag != expected_tag)
1937 : : {
1938 : 0 : report_toast_corruption(ctx, ta,
1939 : : psprintf("toast value %" PRIu64 " has TOAST tag %u, but chunk_id of toast table has type %u",
1940 : 0 : toast_valueid, (uint8) ta->tag,
1941 : : toast_typid));
1942 : 0 : return;
1943 : : }
1944 : :
1945 [ + + ]: 12461 : max_chunk_size = TOAST_MAX_CHUNK_SIZE(toast_typid);
1946 : 12461 : last_chunk_seq = (extsize - 1) / max_chunk_size;
1947 : :
1948 : : /*
1949 : : * Setup a scan key to find chunks in toast table with matching value ID
1950 : : */
1951 : 12461 : toast_valueid_scankey_init(&toastkey, toast_typid, toast_valueid);
1952 : :
1953 : : /*
1954 : : * Check if any chunks for this toasted object exist in the toast table,
1955 : : * accessible via the index.
1956 : : */
1957 : 12461 : toastscan = systable_beginscan_ordered(ctx->toast_rel,
1958 : : ctx->valid_toast_index,
1959 : : get_toast_snapshot(), 1,
1960 : : &toastkey);
1961 : 12461 : found_toasttup = false;
1962 : 12461 : while ((toasttup =
1963 : 54601 : systable_getnext_ordered(toastscan,
1964 [ + + ]: 54598 : ForwardScanDirection)) != NULL)
1965 : : {
1966 : 42140 : found_toasttup = true;
1967 : 42140 : check_toast_tuple(toasttup, ctx, ta, &expected_chunk_seq, extsize,
1968 : : max_chunk_size);
1969 : : }
1970 : 12458 : systable_endscan_ordered(toastscan);
1971 : :
1972 [ + + ]: 12458 : if (!found_toasttup)
1973 : 1 : report_toast_corruption(ctx, ta,
1974 : : psprintf("toast value %" PRIu64 " not found in toast table",
1975 : : toast_valueid));
1976 [ - + ]: 12457 : else if (expected_chunk_seq <= last_chunk_seq)
1977 : 0 : report_toast_corruption(ctx, ta,
1978 : : psprintf("toast value %" PRIu64 " was expected to end at chunk %d, but ended while expecting chunk %d",
1979 : : toast_valueid,
1980 : : last_chunk_seq, expected_chunk_seq));
1981 : : }
1982 : :
1983 : : /*
1984 : : * Check the current tuple as tracked in ctx, recording any corruption found in
1985 : : * ctx->tupstore.
1986 : : *
1987 : : * We return some information about the status of xmin to aid in validating
1988 : : * update chains.
1989 : : */
1990 : : static void
1991 : 577800 : check_tuple(HeapCheckContext *ctx, bool *xmin_commit_status_ok,
1992 : : XidCommitStatus *xmin_commit_status)
1993 : : {
1994 : : /*
1995 : : * Check various forms of tuple header corruption, and if the header is
1996 : : * too corrupt, do not continue with other checks.
1997 : : */
1998 [ + + ]: 577800 : if (!check_tuple_header(ctx))
1999 : 5 : return;
2000 : :
2001 : : /*
2002 : : * Check tuple visibility. If the inserting transaction aborted, we
2003 : : * cannot assume our relation description matches the tuple structure, and
2004 : : * therefore cannot check it.
2005 : : */
2006 [ + + ]: 577795 : if (!check_tuple_visibility(ctx, xmin_commit_status_ok,
2007 : : xmin_commit_status))
2008 : 12 : return;
2009 : :
2010 : : /*
2011 : : * The tuple is visible, so it must be compatible with the current version
2012 : : * of the relation descriptor. It might have fewer columns than are
2013 : : * present in the relation descriptor, but it cannot have more.
2014 : : */
2015 [ + + ]: 577783 : if (RelationGetDescr(ctx->rel)->natts < ctx->natts)
2016 : : {
2017 : 2 : report_corruption(ctx,
2018 : : psprintf("number of attributes %u exceeds maximum %u expected for table",
2019 : : ctx->natts,
2020 : 2 : RelationGetDescr(ctx->rel)->natts));
2021 : 2 : return;
2022 : : }
2023 : :
2024 : : /*
2025 : : * Check each attribute unless we hit corruption that confuses what to do
2026 : : * next, at which point we abort further attribute checks for this tuple.
2027 : : * Note that we don't abort for all types of corruption, only for those
2028 : : * types where we don't know how to continue. We also don't abort the
2029 : : * checking of toasted attributes collected from the tuple prior to
2030 : : * aborting. Those will still be checked later along with other toasted
2031 : : * attributes collected from the page.
2032 : : */
2033 : 577781 : ctx->offset = 0;
2034 [ + + ]: 9003059 : for (ctx->attnum = 0; ctx->attnum < ctx->natts; ctx->attnum++)
2035 [ + + ]: 8425279 : if (!check_tuple_attribute(ctx))
2036 : 1 : break; /* cannot continue */
2037 : :
2038 : : /* revert attnum to -1 until we again examine individual attributes */
2039 : 577781 : ctx->attnum = -1;
2040 : : }
2041 : :
2042 : : /*
2043 : : * Convert a TransactionId into a FullTransactionId using our cached values of
2044 : : * the valid transaction ID range. It is the caller's responsibility to have
2045 : : * already updated the cached values, if necessary. This is akin to
2046 : : * FullTransactionIdFromAllowableAt(), but it tolerates corruption in the form
2047 : : * of an xid before epoch 0.
2048 : : */
2049 : : static FullTransactionId
2050 : 78067 : FullTransactionIdFromXidAndCtx(TransactionId xid, const HeapCheckContext *ctx)
2051 : : {
2052 : : uint64 nextfxid_i;
2053 : : int32 diff;
2054 : : FullTransactionId fxid;
2055 : :
2056 : : Assert(TransactionIdIsNormal(ctx->next_xid));
2057 : : Assert(FullTransactionIdIsNormal(ctx->next_fxid));
2058 : : Assert(XidFromFullTransactionId(ctx->next_fxid) == ctx->next_xid);
2059 : :
2060 [ + + ]: 78067 : if (!TransactionIdIsNormal(xid))
2061 : 191 : return FullTransactionIdFromEpochAndXid(0, xid);
2062 : :
2063 : 77876 : nextfxid_i = U64FromFullTransactionId(ctx->next_fxid);
2064 : :
2065 : : /* compute the 32bit modulo difference */
2066 : 77876 : diff = (int32) (ctx->next_xid - xid);
2067 : :
2068 : : /*
2069 : : * In cases of corruption we might see a 32bit xid that is before epoch 0.
2070 : : * We can't represent that as a 64bit xid, due to 64bit xids being
2071 : : * unsigned integers, without the modulo arithmetic of 32bit xid. There's
2072 : : * no really nice way to deal with that, but it works ok enough to use
2073 : : * FirstNormalFullTransactionId in that case, as a freshly initdb'd
2074 : : * cluster already has a newer horizon.
2075 : : */
2076 [ + + + + ]: 77876 : if (diff > 0 && (nextfxid_i - FirstNormalTransactionId) < (int64) diff)
2077 : : {
2078 : : Assert(EpochFromFullTransactionId(ctx->next_fxid) == 0);
2079 : 4 : fxid = FirstNormalFullTransactionId;
2080 : : }
2081 : : else
2082 : 77872 : fxid = FullTransactionIdFromU64(nextfxid_i - diff);
2083 : :
2084 : : Assert(FullTransactionIdIsNormal(fxid));
2085 : 77876 : return fxid;
2086 : : }
2087 : :
2088 : : /*
2089 : : * Update our cached range of valid transaction IDs.
2090 : : */
2091 : : static void
2092 : 1551 : update_cached_xid_range(HeapCheckContext *ctx)
2093 : : {
2094 : : /* Make cached copies */
2095 : 1551 : LWLockAcquire(XidGenLock, LW_SHARED);
2096 : 1551 : ctx->next_fxid = TransamVariables->nextXid;
2097 : 1551 : ctx->oldest_xid = TransamVariables->oldestXid;
2098 : 1551 : LWLockRelease(XidGenLock);
2099 : :
2100 : : /* And compute alternate versions of the same */
2101 : 1551 : ctx->next_xid = XidFromFullTransactionId(ctx->next_fxid);
2102 : 1551 : ctx->oldest_fxid = FullTransactionIdFromXidAndCtx(ctx->oldest_xid, ctx);
2103 : 1551 : }
2104 : :
2105 : : /*
2106 : : * Update our cached range of valid multitransaction IDs.
2107 : : */
2108 : : static void
2109 : 1549 : update_cached_mxid_range(HeapCheckContext *ctx)
2110 : : {
2111 : 1549 : ReadMultiXactIdRange(&ctx->oldest_mxact, &ctx->next_mxact);
2112 : 1549 : }
2113 : :
2114 : : /*
2115 : : * Return whether the given FullTransactionId is within our cached valid
2116 : : * transaction ID range.
2117 : : */
2118 : : static inline bool
2119 : 65091 : fxid_in_cached_range(FullTransactionId fxid, const HeapCheckContext *ctx)
2120 : : {
2121 [ + + ]: 130179 : return (FullTransactionIdPrecedesOrEquals(ctx->oldest_fxid, fxid) &&
2122 [ + + ]: 65088 : FullTransactionIdPrecedes(fxid, ctx->next_fxid));
2123 : : }
2124 : :
2125 : : /*
2126 : : * Checks whether a multitransaction ID is in the cached valid range, returning
2127 : : * the nature of the range violation, if any.
2128 : : */
2129 : : static XidBoundsViolation
2130 : 60 : check_mxid_in_range(MultiXactId mxid, HeapCheckContext *ctx)
2131 : : {
2132 [ - + ]: 60 : if (!TransactionIdIsValid(mxid))
2133 : 0 : return XID_INVALID;
2134 [ + + ]: 60 : if (MultiXactIdPrecedes(mxid, ctx->relminmxid))
2135 : 2 : return XID_PRECEDES_RELMIN;
2136 [ - + ]: 58 : if (MultiXactIdPrecedes(mxid, ctx->oldest_mxact))
2137 : 0 : return XID_PRECEDES_CLUSTERMIN;
2138 [ + + ]: 58 : if (MultiXactIdPrecedesOrEquals(ctx->next_mxact, mxid))
2139 : 2 : return XID_IN_FUTURE;
2140 : 56 : return XID_BOUNDS_OK;
2141 : : }
2142 : :
2143 : : /*
2144 : : * Checks whether the given mxid is valid to appear in the heap being checked,
2145 : : * returning the nature of the range violation, if any.
2146 : : *
2147 : : * This function attempts to return quickly by caching the known valid mxid
2148 : : * range in ctx. Callers should already have performed the initial setup of
2149 : : * the cache prior to the first call to this function.
2150 : : */
2151 : : static XidBoundsViolation
2152 : 58 : check_mxid_valid_in_rel(MultiXactId mxid, HeapCheckContext *ctx)
2153 : : {
2154 : : XidBoundsViolation result;
2155 : :
2156 : 58 : result = check_mxid_in_range(mxid, ctx);
2157 [ + + ]: 58 : if (result == XID_BOUNDS_OK)
2158 : 56 : return XID_BOUNDS_OK;
2159 : :
2160 : : /* The range may have advanced. Recheck. */
2161 : 2 : update_cached_mxid_range(ctx);
2162 : 2 : return check_mxid_in_range(mxid, ctx);
2163 : : }
2164 : :
2165 : : /*
2166 : : * Checks whether the given transaction ID is (or was recently) valid to appear
2167 : : * in the heap being checked, or whether it is too old or too new to appear in
2168 : : * the relation, returning information about the nature of the bounds violation.
2169 : : *
2170 : : * We cache the range of valid transaction IDs. If xid is in that range, we
2171 : : * conclude that it is valid, even though concurrent changes to the table might
2172 : : * invalidate it under certain corrupt conditions. (For example, if the table
2173 : : * contains corrupt all-frozen bits, a concurrent vacuum might skip the page(s)
2174 : : * containing the xid and then truncate clog and advance the relfrozenxid
2175 : : * beyond xid.) Reporting the xid as valid under such conditions seems
2176 : : * acceptable, since if we had checked it earlier in our scan it would have
2177 : : * truly been valid at that time.
2178 : : *
2179 : : * If the status argument is not NULL, and if and only if the transaction ID
2180 : : * appears to be valid in this relation, the status argument will be set with
2181 : : * the commit status of the transaction ID.
2182 : : */
2183 : : static XidBoundsViolation
2184 : 578932 : get_xid_status(TransactionId xid, HeapCheckContext *ctx,
2185 : : XidCommitStatus *status)
2186 : : {
2187 : : FullTransactionId fxid;
2188 : : FullTransactionId clog_horizon;
2189 : :
2190 : : /* Quick check for special xids */
2191 [ + + ]: 578932 : if (!TransactionIdIsValid(xid))
2192 : 1 : return XID_INVALID;
2193 [ + + + + ]: 578931 : else if (xid == BootstrapTransactionId || xid == FrozenTransactionId)
2194 : : {
2195 [ + - ]: 513840 : if (status != NULL)
2196 : 513840 : *status = XID_COMMITTED;
2197 : 513840 : return XID_BOUNDS_OK;
2198 : : }
2199 : :
2200 : : /* Check if the xid is within bounds */
2201 : 65091 : fxid = FullTransactionIdFromXidAndCtx(xid, ctx);
2202 [ + + ]: 65091 : if (!fxid_in_cached_range(fxid, ctx))
2203 : : {
2204 : : /*
2205 : : * We may have been checking against stale values. Update the cached
2206 : : * range to be sure, and since we relied on the cached range when we
2207 : : * performed the full xid conversion, reconvert.
2208 : : */
2209 : 4 : update_cached_xid_range(ctx);
2210 : 4 : fxid = FullTransactionIdFromXidAndCtx(xid, ctx);
2211 : : }
2212 : :
2213 [ + + ]: 65091 : if (FullTransactionIdPrecedesOrEquals(ctx->next_fxid, fxid))
2214 : 1 : return XID_IN_FUTURE;
2215 [ + + ]: 65090 : if (FullTransactionIdPrecedes(fxid, ctx->oldest_fxid))
2216 : 3 : return XID_PRECEDES_CLUSTERMIN;
2217 [ + + ]: 65087 : if (FullTransactionIdPrecedes(fxid, ctx->relfrozenfxid))
2218 : 1 : return XID_PRECEDES_RELMIN;
2219 : :
2220 : : /* Early return if the caller does not request clog checking */
2221 [ - + ]: 65086 : if (status == NULL)
2222 : 0 : return XID_BOUNDS_OK;
2223 : :
2224 : : /* Early return if we just checked this xid in a prior call */
2225 [ + + ]: 65086 : if (xid == ctx->cached_xid)
2226 : : {
2227 : 55212 : *status = ctx->cached_status;
2228 : 55212 : return XID_BOUNDS_OK;
2229 : : }
2230 : :
2231 : 9874 : *status = XID_COMMITTED;
2232 : 9874 : LWLockAcquire(XactTruncationLock, LW_SHARED);
2233 : : clog_horizon =
2234 : 9874 : FullTransactionIdFromXidAndCtx(TransamVariables->oldestClogXid,
2235 : : ctx);
2236 [ + - ]: 9874 : if (FullTransactionIdPrecedesOrEquals(clog_horizon, fxid))
2237 : : {
2238 [ - + ]: 9874 : if (TransactionIdIsCurrentTransactionId(xid))
2239 : 0 : *status = XID_IS_CURRENT_XID;
2240 [ + + ]: 9874 : else if (TransactionIdIsInProgress(xid))
2241 : 2 : *status = XID_IN_PROGRESS;
2242 [ + + ]: 9872 : else if (TransactionIdDidCommit(xid))
2243 : 9865 : *status = XID_COMMITTED;
2244 : : else
2245 : 7 : *status = XID_ABORTED;
2246 : : }
2247 : 9874 : LWLockRelease(XactTruncationLock);
2248 : 9874 : ctx->cached_xid = xid;
2249 : 9874 : ctx->cached_status = *status;
2250 : 9874 : return XID_BOUNDS_OK;
2251 : : }
|