From f6399dcd6e37cd29d3df03eeca5c557843d97db5 Mon Sep 17 00:00:00 2001 From: Mark Dilger Date: Mon, 29 Mar 2021 14:40:45 -0700 Subject: [PATCH v13 4/4] Checking toast separately from the main table. Rather than checking toasted attributes as we find them, creating a list of them and checking all the toast in the list after releasing the buffer lock for each main table page. --- contrib/amcheck/verify_heapam.c | 415 +++++++++++++++---------------- src/tools/pgindent/typedefs.list | 1 + 2 files changed, 201 insertions(+), 215 deletions(-) diff --git a/contrib/amcheck/verify_heapam.c b/contrib/amcheck/verify_heapam.c index c5bde63ea7..e3163e4bfa 100644 --- a/contrib/amcheck/verify_heapam.c +++ b/contrib/amcheck/verify_heapam.c @@ -58,6 +58,26 @@ typedef enum SkipPages SKIP_PAGES_NONE } SkipPages; +/* + * Struct holding information necessary to check a toasted attribute, including + * the toast pointer, state about the current toast chunk being checked, and + * the location in the main table of the toasted attribute. We have to track + * the tuple's location in the main table for reporting purposes because by the + * time the toast is checked our HeapCheckContext will no longer be pointing to + * the relevant tuple. + */ +typedef struct ToastCheckContext +{ + struct varatt_external toast_pointer; + BlockNumber blkno; /* block in main table */ + OffsetNumber offnum; /* offset in main table */ + AttrNumber attnum; /* attribute in main table */ + int32 chunkno; /* chunk number in toast table */ + int32 attrsize; /* size of toasted attribute */ + int32 endchunk; /* last chunk number in toast table */ + int32 totalchunks; /* total chunks in toast table */ +} ToastCheckContext; + /* * Struct holding the running context information during * a lifetime of a verify_heapam execution. @@ -119,11 +139,11 @@ typedef struct HeapCheckContext /* True if toast for this tuple could be vacuumed away */ bool tuple_is_volatile; - /* Values for iterating over toast for the attribute */ - int32 chunkno; - int32 attrsize; - int32 endchunk; - int32 totalchunks; + /* + * List of ToastCheckContext structs for toasted attributes which are not + * in danger of being vacuumed way and should be checked + */ + List *toasted_attributes; /* Whether verify_heapam has yet encountered any corrupt tuples */ bool is_corrupt; @@ -136,13 +156,18 @@ typedef struct HeapCheckContext /* Internal implementation */ static void sanity_check_relation(Relation rel); static void check_tuple(HeapCheckContext *ctx); -static void check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx); +static void check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx, + ToastCheckContext *tctx); -static bool check_tuple_attribute(HeapCheckContext *ctx); static bool check_tuple_header(HeapCheckContext *ctx); static bool check_tuple_visibility(HeapCheckContext *ctx); +static bool check_tuple_attribute(HeapCheckContext *ctx); +static void check_toasted_attributes(HeapCheckContext *ctx); + static void report_main_corruption(HeapCheckContext *ctx, char *msg); +static void report_toast_corruption(HeapCheckContext *ctx, + ToastCheckContext *tctx, char *msg); static TupleDesc verify_heapam_tupdesc(void); static FullTransactionId FullTransactionIdFromXidAndCtx(TransactionId xid, const HeapCheckContext *ctx); @@ -253,6 +278,7 @@ verify_heapam(PG_FUNCTION_ARGS) memset(&ctx, 0, sizeof(HeapCheckContext)); ctx.cached_xid = InvalidTransactionId; + ctx.toasted_attributes = NIL; /* * Any xmin newer than the xmin of our snapshot can't become all-visible @@ -469,6 +495,14 @@ verify_heapam(PG_FUNCTION_ARGS) /* clean up */ UnlockReleaseBuffer(ctx.buffer); + /* + * Check any toast pointers from the page whose lock we just released + * and reset the list to NIL. + */ + if (ctx.toasted_attributes != NIL) + check_toasted_attributes(&ctx); + Assert(ctx.toasted_attributes == NIL); + if (on_error_stop && ctx.is_corrupt) break; } @@ -510,14 +544,13 @@ sanity_check_relation(Relation rel) } /* - * Record a single corruption found in the table. The values in ctx should - * reflect the location of the corruption, and the msg argument should contain - * a human-readable description of the corruption. - * - * The msg argument is pfree'd by this function. + * Shared internal implementation for report_main_corruption and + * report_toast_corruption. */ static void -report_main_corruption(HeapCheckContext *ctx, char *msg) +report_corruption(Tuplestorestate *tupstore, TupleDesc tupdesc, + BlockNumber blkno, OffsetNumber offnum, AttrNumber attnum, + char *msg) { Datum values[HEAPCHECK_RELATION_COLS]; bool nulls[HEAPCHECK_RELATION_COLS]; @@ -525,10 +558,10 @@ report_main_corruption(HeapCheckContext *ctx, char *msg) MemSet(values, 0, sizeof(values)); MemSet(nulls, 0, sizeof(nulls)); - values[0] = Int64GetDatum(ctx->blkno); - values[1] = Int32GetDatum(ctx->offnum); - values[2] = Int32GetDatum(ctx->attnum); - nulls[2] = (ctx->attnum < 0); + values[0] = Int64GetDatum(blkno); + values[1] = Int32GetDatum(offnum); + values[2] = Int32GetDatum(attnum); + nulls[2] = (attnum < 0); values[3] = CStringGetTextDatum(msg); /* @@ -541,8 +574,39 @@ report_main_corruption(HeapCheckContext *ctx, char *msg) */ pfree(msg); - tuple = heap_form_tuple(ctx->tupdesc, values, nulls); - tuplestore_puttuple(ctx->tupstore, tuple); + tuple = heap_form_tuple(tupdesc, values, nulls); + tuplestore_puttuple(tupstore, tuple); +} + +/* + * Record a single corruption found in the main table. The values in ctx should + * indicate the location of the corruption, and the msg argument should contain + * a human-readable description of the corruption. + * + * The msg argument is pfree'd by this function. + */ +static void +report_main_corruption(HeapCheckContext *ctx, char *msg) +{ + report_corruption(ctx->tupstore, ctx->tupdesc, ctx->blkno, ctx->offnum, + ctx->attnum, msg); + ctx->is_corrupt = true; +} + +/* + * Record corruption found in the toast table. The values in tctx should + * indicate the location in the main table where the toast pointer was + * encountered, and the msg argument should contain a human-readable + * description of the toast table corruption. + * + * As above, the msg argument is pfree'd by this function. + */ +static void +report_toast_corruption(HeapCheckContext *ctx, ToastCheckContext *tctx, + char *msg) +{ + report_corruption(ctx->tupstore, ctx->tupdesc, tctx->blkno, tctx->offnum, + tctx->attnum, msg); ctx->is_corrupt = true; } @@ -1086,7 +1150,6 @@ check_tuple_visibility(HeapCheckContext *ctx) return false; /* not reached */ } - /* * Check the current toast tuple against the state tracked in ctx, recording * any corruption found in ctx->tupstore. @@ -1099,7 +1162,8 @@ check_tuple_visibility(HeapCheckContext *ctx) * as each toast tuple having its varlena structure sanity checked. */ static void -check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx) +check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx, + ToastCheckContext *tctx) { int32 curchunk; Pointer chunk; @@ -1114,16 +1178,16 @@ check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx) ctx->toast_rel->rd_att, &isnull)); if (isnull) { - report_main_corruption(ctx, - pstrdup("toast chunk sequence number is null")); + report_toast_corruption(ctx, tctx, + pstrdup("toast chunk sequence number is null")); return; } chunk = DatumGetPointer(fastgetattr(toasttup, 3, ctx->toast_rel->rd_att, &isnull)); if (isnull) { - report_main_corruption(ctx, - pstrdup("toast chunk data is null")); + report_toast_corruption(ctx, tctx, + pstrdup("toast chunk data is null")); return; } if (!VARATT_IS_EXTENDED(chunk)) @@ -1140,37 +1204,37 @@ check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx) /* should never happen */ uint32 header = ((varattrib_4b *) chunk)->va_4byte.va_header; - report_main_corruption(ctx, - psprintf("corrupt extended toast chunk has invalid varlena header: %0x (sequence number %d)", - header, curchunk)); + report_toast_corruption(ctx, tctx, + psprintf("corrupt extended toast chunk has invalid varlena header: %0x (sequence number %d)", + header, curchunk)); return; } /* * Some checks on the data we've found */ - if (curchunk != ctx->chunkno) + if (curchunk != tctx->chunkno) { - report_main_corruption(ctx, - psprintf("toast chunk sequence number %u does not match the expected sequence number %u", - curchunk, ctx->chunkno)); + report_toast_corruption(ctx, tctx, + psprintf("toast chunk sequence number %u does not match the expected sequence number %u", + curchunk, tctx->chunkno)); return; } - if (curchunk > ctx->endchunk) + if (curchunk > tctx->endchunk) { - report_main_corruption(ctx, - psprintf("toast chunk sequence number %u exceeds the end chunk sequence number %u", - curchunk, ctx->endchunk)); + report_toast_corruption(ctx, tctx, + psprintf("toast chunk sequence number %u exceeds the end chunk sequence number %u", + curchunk, tctx->endchunk)); return; } - expected_size = curchunk < ctx->totalchunks - 1 ? TOAST_MAX_CHUNK_SIZE - : ctx->attrsize - ((ctx->totalchunks - 1) * TOAST_MAX_CHUNK_SIZE); + expected_size = curchunk < tctx->totalchunks - 1 ? TOAST_MAX_CHUNK_SIZE + : tctx->attrsize - ((tctx->totalchunks - 1) * TOAST_MAX_CHUNK_SIZE); if (chunksize != expected_size) { - report_main_corruption(ctx, - psprintf("toast chunk size %u differs from the expected size %u", - chunksize, expected_size)); + report_toast_corruption(ctx, tctx, + psprintf("toast chunk size %u differs from the expected size %u", + chunksize, expected_size)); return; } } @@ -1180,17 +1244,17 @@ check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx) * found in ctx->tupstore. * * This function follows the logic performed by heap_deform_tuple(), and in the - * case of a toasted value, optionally continues along the logic of - * detoast_external_attr(), checking for any conditions that would result in - * either of those functions Asserting or crashing the backend. The checks - * performed by Asserts present in those two functions are also performed here. - * In cases where those two functions are a bit cavalier in their assumptions - * about data being correct, we perform additional checks not present in either - * of those two functions. Where some condition is checked in both of those - * functions, we perform it here twice, as we parallel the logical flow of - * those two functions. The presence of duplicate checks seems a reasonable - * price to pay for keeping this code tightly coupled with the code it - * protects. + * case of a toasted value, optionally stores the toast pointer so later it can + * be checked following the logic of detoast_external_attr(), checking for any + * conditions that would result in either of those functions Asserting or + * crashing the backend. The checks performed by Asserts present in those two + * functions are also performed here and in check_toasted_attributes. In cases + * where those two functions are a bit cavalier in their assumptions about data + * being correct, we perform additional checks not present in either of those + * two functions. Where some condition is checked in both of those functions, + * we perform it here twice, as we parallel the logical flow of those two + * functions. The presence of duplicate checks seems a reasonable price to pay + * for keeping this code tightly coupled with the code it protects. * * Returns true if the tuple attribute is sane enough for processing to * continue on to the next attribute, false otherwise. @@ -1198,12 +1262,6 @@ check_toast_tuple(HeapTuple toasttup, HeapCheckContext *ctx) static bool check_tuple_attribute(HeapCheckContext *ctx) { - struct varatt_external toast_pointer; - ScanKeyData toastkey; - SysScanDesc toastscan; - SnapshotData SnapshotToast; - HeapTuple toasttup; - bool found_toasttup; Datum attdatum; struct varlena *attr; char *tp; /* pointer to the tuple data */ @@ -1338,191 +1396,114 @@ check_tuple_attribute(HeapCheckContext *ctx) return true; /* - * Must copy attr into toast_pointer for alignment considerations + * If this tuple is at risk of being vacuumed away, we cannot check the + * toast. Otherwise, we push a copy of the toast tuple so we can check it + * after releasing the main table buffer lock. */ - VARATT_EXTERNAL_GET_POINTER(toast_pointer, attr); + if (!ctx->tuple_is_volatile) + { + ToastCheckContext *tctx; - ctx->attrsize = VARATT_EXTERNAL_GET_EXTSIZE(toast_pointer); - ctx->endchunk = (ctx->attrsize - 1) / TOAST_MAX_CHUNK_SIZE; - ctx->totalchunks = ctx->endchunk + 1; + tctx = (ToastCheckContext *) palloc0fast(sizeof(ToastCheckContext)); - /* - * Setup a scan key to find chunks in toast table with matching va_valueid - */ - ScanKeyInit(&toastkey, - (AttrNumber) 1, - BTEqualStrategyNumber, F_OIDEQ, - ObjectIdGetDatum(toast_pointer.va_valueid)); - - /* - * Check if any chunks for this toasted object exist in the toast table, - * accessible via the index. - */ - init_toast_snapshot(&SnapshotToast); - toastscan = systable_beginscan_ordered(ctx->toast_rel, - ctx->valid_toast_index, - &SnapshotToast, 1, - &toastkey); - ctx->chunkno = 0; - found_toasttup = false; - while ((toasttup = - systable_getnext_ordered(toastscan, - ForwardScanDirection)) != NULL) - { - found_toasttup = true; - check_toast_tuple(toasttup, ctx); - ctx->chunkno++; + VARATT_EXTERNAL_GET_POINTER(tctx->toast_pointer, attr); + tctx->blkno = ctx->blkno; + tctx->offnum = ctx->offnum; + tctx->attnum = ctx->attnum; + ctx->toasted_attributes = lappend(ctx->toasted_attributes, tctx); } - if (!found_toasttup) - report_main_corruption(ctx, - psprintf("toasted value for attribute %u missing from toast table", - ctx->attnum)); - else if (ctx->chunkno != (ctx->endchunk + 1)) - report_main_corruption(ctx, - psprintf("final toast chunk number %u differs from expected value %u", - ctx->chunkno, (ctx->endchunk + 1))); - systable_endscan_ordered(toastscan); return true; } /* - * Check the current tuple as tracked in ctx, recording any corruption found in - * ctx->tupstore. + * For each attribute collected in ctx->toasted_attributes, look up the value + * in the toast table and perform checks on it. This function should only be + * called on toast pointers which cannot be vacuumed away during our + * processing. */ static void -check_tuple(HeapCheckContext *ctx) +check_toasted_attributes(HeapCheckContext *ctx) { - TransactionId xmin; - TransactionId xmax; - bool fatal = false; - uint16 infomask = ctx->tuphdr->t_infomask; + ListCell *cell; - /* If xmin is normal, it should be within valid range */ - xmin = HeapTupleHeaderGetXmin(ctx->tuphdr); - switch (get_xid_status(xmin, ctx, NULL)) + foreach(cell, ctx->toasted_attributes) { - case XID_INVALID: - case XID_BOUNDS_OK: - break; - case XID_IN_FUTURE: - report_main_corruption(ctx, - psprintf("xmin %u equals or exceeds next valid transaction ID %u:%u", - xmin, - EpochFromFullTransactionId(ctx->next_fxid), - XidFromFullTransactionId(ctx->next_fxid))); - fatal = true; - break; - case XID_PRECEDES_CLUSTERMIN: - report_main_corruption(ctx, - psprintf("xmin %u precedes oldest valid transaction ID %u:%u", - xmin, - EpochFromFullTransactionId(ctx->oldest_fxid), - XidFromFullTransactionId(ctx->oldest_fxid))); - fatal = true; - break; - case XID_PRECEDES_RELMIN: - report_main_corruption(ctx, - psprintf("xmin %u precedes relation freeze threshold %u:%u", - xmin, - EpochFromFullTransactionId(ctx->relfrozenfxid), - XidFromFullTransactionId(ctx->relfrozenfxid))); - fatal = true; - break; - } + ToastCheckContext *tctx; + SnapshotData SnapshotToast; + ScanKeyData toastkey; + SysScanDesc toastscan; + bool found_toasttup; + HeapTuple toasttup; + + tctx = lfirst(cell); + tctx->attrsize = VARATT_EXTERNAL_GET_EXTSIZE(tctx->toast_pointer); + tctx->endchunk = (tctx->attrsize - 1) / TOAST_MAX_CHUNK_SIZE; + tctx->totalchunks = tctx->endchunk + 1; - xmax = HeapTupleHeaderGetRawXmax(ctx->tuphdr); + /* + * Setup a scan key to find chunks in toast table with matching + * va_valueid + */ + ScanKeyInit(&toastkey, + (AttrNumber) 1, + BTEqualStrategyNumber, F_OIDEQ, + ObjectIdGetDatum(tctx->toast_pointer.va_valueid)); - if (infomask & HEAP_XMAX_IS_MULTI) - { - /* xmax is a multixact, so it should be within valid MXID range */ - switch (check_mxid_valid_in_rel(xmax, ctx)) - { - case XID_INVALID: - report_main_corruption(ctx, - pstrdup("multitransaction ID is invalid")); - fatal = true; - break; - case XID_PRECEDES_RELMIN: - report_main_corruption(ctx, - psprintf("multitransaction ID %u precedes relation minimum multitransaction ID threshold %u", - xmax, ctx->relminmxid)); - fatal = true; - break; - case XID_PRECEDES_CLUSTERMIN: - report_main_corruption(ctx, - psprintf("multitransaction ID %u precedes oldest valid multitransaction ID threshold %u", - xmax, ctx->oldest_mxact)); - fatal = true; - break; - case XID_IN_FUTURE: - report_main_corruption(ctx, - psprintf("multitransaction ID %u equals or exceeds next valid multitransaction ID %u", - xmax, - ctx->next_mxact)); - fatal = true; - break; - case XID_BOUNDS_OK: - break; - } - } - else - { /* - * xmax is not a multixact and is normal, so it should be within the - * valid XID range. + * Check if any chunks for this toasted object exist in the toast + * table, accessible via the index. */ - switch (get_xid_status(xmax, ctx, NULL)) + init_toast_snapshot(&SnapshotToast); + toastscan = systable_beginscan_ordered(ctx->toast_rel, + ctx->valid_toast_index, + &SnapshotToast, 1, + &toastkey); + tctx->chunkno = 0; + found_toasttup = false; + while ((toasttup = + systable_getnext_ordered(toastscan, + ForwardScanDirection)) != NULL) { - case XID_INVALID: - case XID_BOUNDS_OK: - break; - case XID_IN_FUTURE: - report_main_corruption(ctx, - psprintf("xmax %u equals or exceeds next valid transaction ID %u:%u", - xmax, - EpochFromFullTransactionId(ctx->next_fxid), - XidFromFullTransactionId(ctx->next_fxid))); - fatal = true; - break; - case XID_PRECEDES_CLUSTERMIN: - report_main_corruption(ctx, - psprintf("xmax %u precedes oldest valid transaction ID %u:%u", - xmax, - EpochFromFullTransactionId(ctx->oldest_fxid), - XidFromFullTransactionId(ctx->oldest_fxid))); - fatal = true; - break; - case XID_PRECEDES_RELMIN: - report_main_corruption(ctx, - psprintf("xmax %u precedes relation freeze threshold %u:%u", - xmax, - EpochFromFullTransactionId(ctx->relfrozenfxid), - XidFromFullTransactionId(ctx->relfrozenfxid))); - fatal = true; + found_toasttup = true; + check_toast_tuple(toasttup, ctx, tctx); + tctx->chunkno++; } + if (!found_toasttup) + report_toast_corruption(ctx, tctx, + psprintf("toasted value for attribute %u missing from toast table", + tctx->attnum)); + else if (tctx->chunkno != (tctx->endchunk + 1)) + report_toast_corruption(ctx, tctx, + psprintf("final toast chunk number %u differs from expected value %u", + tctx->chunkno, (tctx->endchunk + 1))); + systable_endscan_ordered(toastscan); + + pfree(tctx); } + list_free(ctx->toasted_attributes); + ctx->toasted_attributes = NIL; +} - /* - * Cannot process tuple data if tuple header was corrupt, as the offsets - * within the page cannot be trusted, leaving too much risk of reading - * garbage if we continue. - * - * We also cannot process the tuple if the xmin or xmax were invalid - * relative to relfrozenxid or relminmxid, as clog entries for the xids - * may already be gone. - */ - if (fatal) - return; - +/* + * Check the current tuple as tracked in ctx, recording any corruption found in + * ctx->tupstore. + */ +static void +check_tuple(HeapCheckContext *ctx) +{ /* * Check various forms of tuple header corruption. If the header is too - * corrupt to continue checking, or if the tuple is not visible to anyone, - * we cannot continue with other checks. + * corrupt to continue checking, we cannot continue with other checks. */ if (!check_tuple_header(ctx)) return; + /* + * Check tuple visibility. If the inserting transaction aborted, we + * cannot assume our relation description matches the tuple structure, and + * therefore cannot check it. + */ if (!check_tuple_visibility(ctx)) return; @@ -1545,6 +1526,10 @@ check_tuple(HeapCheckContext *ctx) * next, at which point we abort further attribute checks for this tuple. * Note that we don't abort for all types of corruption, only for those * types where we don't know how to continue. + * + * While checking the tuple attributes, we build a list of toast pointers + * we encounter, to be checked later. If further attribute checking is + * aborted, we still have the pointers collected prior to aborting. */ ctx->offset = 0; for (ctx->attnum = 0; ctx->attnum < ctx->natts; ctx->attnum++) diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 9e6777e9d0..0ce261e2a2 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2557,6 +2557,7 @@ TimestampTz TmFromChar TmToChar ToastAttrInfo +ToastCheckContext ToastTupleContext TocEntry TokenAuxData -- 2.21.1 (Apple Git-122.3)