LCOV - differential code coverage report
Current view: top level - contrib/amcheck - verify_heapam.c (source / functions) Coverage Total Hit UNC UBC GNC CBC ECB DCB
Current: f76c13edadc2b319036e0d238703ed56bb23f934 vs 9e17d25e79d4756be08b4a5521b4b58450217137 Lines: 76.1 % 728 554 5 169 28 526 1 13
Current Date: 2026-09-20 14:13:17 +0900 Functions: 100.0 % 19 19 3 16
Baseline: lcov-20260920-baseline Branches: 70.6 % 449 317 4 128 14 303
Baseline Date: 2026-09-20 14:13:13 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 82.8 % 29 24 5 24
(7,30] days: 100.0 % 4 4 4
(30,360] days: 100.0 % 7 7 7
(360..) days: 75.4 % 688 519 169 519 1
Function coverage date bins:
(360..) days: 100.0 % 19 19 3 16
Branch coverage date bins:
(1,7] days: 75.0 % 16 12 4 12
(7,30] days: 100.0 % 2 2 2
(360..) days: 70.3 % 431 303 128 303

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

Generated by: LCOV version 2.0-1