LCOV - code coverage report
Current view: top level - src/backend/access/heap - vacuumlazy.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18beta1 Lines: 825 966 85.4 %
Date: 2025-06-27 18:18:35 Functions: 30 30 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * vacuumlazy.c
       4             :  *    Concurrent ("lazy") vacuuming.
       5             :  *
       6             :  * Heap relations are vacuumed in three main phases. In phase I, vacuum scans
       7             :  * relation pages, pruning and freezing tuples and saving dead tuples' TIDs in
       8             :  * a TID store. If that TID store fills up or vacuum finishes scanning the
       9             :  * relation, it progresses to phase II: index vacuuming. Index vacuuming
      10             :  * deletes the dead index entries referenced in the TID store. In phase III,
      11             :  * vacuum scans the blocks of the relation referred to by the TIDs in the TID
      12             :  * store and reaps the corresponding dead items, freeing that space for future
      13             :  * tuples.
      14             :  *
      15             :  * If there are no indexes or index scanning is disabled, phase II may be
      16             :  * skipped. If phase I identified very few dead index entries or if vacuum's
      17             :  * failsafe mechanism has triggered (to avoid transaction ID wraparound),
      18             :  * vacuum may skip phases II and III.
      19             :  *
      20             :  * If the TID store fills up in phase I, vacuum suspends phase I and proceeds
      21             :  * to phases II and III, cleaning up the dead tuples referenced in the current
      22             :  * TID store. This empties the TID store, allowing vacuum to resume phase I.
      23             :  *
      24             :  * In a way, the phases are more like states in a state machine, but they have
      25             :  * been referred to colloquially as phases for so long that they are referred
      26             :  * to as such here.
      27             :  *
      28             :  * Manually invoked VACUUMs may scan indexes during phase II in parallel. For
      29             :  * more information on this, see the comment at the top of vacuumparallel.c.
      30             :  *
      31             :  * In between phases, vacuum updates the freespace map (every
      32             :  * VACUUM_FSM_EVERY_PAGES).
      33             :  *
      34             :  * After completing all three phases, vacuum may truncate the relation if it
      35             :  * has emptied pages at the end. Finally, vacuum updates relation statistics
      36             :  * in pg_class and the cumulative statistics subsystem.
      37             :  *
      38             :  * Relation Scanning:
      39             :  *
      40             :  * Vacuum scans the heap relation, starting at the beginning and progressing
      41             :  * to the end, skipping pages as permitted by their visibility status, vacuum
      42             :  * options, and various other requirements.
      43             :  *
      44             :  * Vacuums are either aggressive or normal. Aggressive vacuums must scan every
      45             :  * unfrozen tuple in order to advance relfrozenxid and avoid transaction ID
      46             :  * wraparound. Normal vacuums may scan otherwise skippable pages for one of
      47             :  * two reasons:
      48             :  *
      49             :  * When page skipping is not disabled, a normal vacuum may scan pages that are
      50             :  * marked all-visible (and even all-frozen) in the visibility map if the range
      51             :  * of skippable pages is below SKIP_PAGES_THRESHOLD. This is primarily for the
      52             :  * benefit of kernel readahead (see comment in heap_vac_scan_next_block()).
      53             :  *
      54             :  * A normal vacuum may also scan skippable pages in an effort to freeze them
      55             :  * and decrease the backlog of all-visible but not all-frozen pages that have
      56             :  * to be processed by the next aggressive vacuum. These are referred to as
      57             :  * eagerly scanned pages. Pages scanned due to SKIP_PAGES_THRESHOLD do not
      58             :  * count as eagerly scanned pages.
      59             :  *
      60             :  * Eagerly scanned pages that are set all-frozen in the VM are successful
      61             :  * eager freezes and those not set all-frozen in the VM are failed eager
      62             :  * freezes.
      63             :  *
      64             :  * Because we want to amortize the overhead of freezing pages over multiple
      65             :  * vacuums, normal vacuums cap the number of successful eager freezes to
      66             :  * MAX_EAGER_FREEZE_SUCCESS_RATE of the number of all-visible but not
      67             :  * all-frozen pages at the beginning of the vacuum. Since eagerly frozen pages
      68             :  * may be unfrozen before the next aggressive vacuum, capping the number of
      69             :  * successful eager freezes also caps the downside of eager freezing:
      70             :  * potentially wasted work.
      71             :  *
      72             :  * Once the success cap has been hit, eager scanning is disabled for the
      73             :  * remainder of the vacuum of the relation.
      74             :  *
      75             :  * Success is capped globally because we don't want to limit our successes if
      76             :  * old data happens to be concentrated in a particular part of the table. This
      77             :  * is especially likely to happen for append-mostly workloads where the oldest
      78             :  * data is at the beginning of the unfrozen portion of the relation.
      79             :  *
      80             :  * On the assumption that different regions of the table are likely to contain
      81             :  * similarly aged data, normal vacuums use a localized eager freeze failure
      82             :  * cap. The failure count is reset for each region of the table -- comprised
      83             :  * of EAGER_SCAN_REGION_SIZE blocks. In each region, we tolerate
      84             :  * vacuum_max_eager_freeze_failure_rate of EAGER_SCAN_REGION_SIZE failures
      85             :  * before suspending eager scanning until the end of the region.
      86             :  * vacuum_max_eager_freeze_failure_rate is configurable both globally and per
      87             :  * table.
      88             :  *
      89             :  * Aggressive vacuums must examine every unfrozen tuple and thus are not
      90             :  * subject to any of the limits imposed by the eager scanning algorithm.
      91             :  *
      92             :  * Once vacuum has decided to scan a given block, it must read the block and
      93             :  * obtain a cleanup lock to prune tuples on the page. A non-aggressive vacuum
      94             :  * may choose to skip pruning and freezing if it cannot acquire a cleanup lock
      95             :  * on the buffer right away. In this case, it may miss cleaning up dead tuples
      96             :  * and their associated index entries (though it is free to reap any existing
      97             :  * dead items on the page).
      98             :  *
      99             :  * After pruning and freezing, pages that are newly all-visible and all-frozen
     100             :  * are marked as such in the visibility map.
     101             :  *
     102             :  * Dead TID Storage:
     103             :  *
     104             :  * The major space usage for vacuuming is storage for the dead tuple IDs that
     105             :  * are to be removed from indexes.  We want to ensure we can vacuum even the
     106             :  * very largest relations with finite memory space usage.  To do that, we set
     107             :  * upper bounds on the memory that can be used for keeping track of dead TIDs
     108             :  * at once.
     109             :  *
     110             :  * We are willing to use at most maintenance_work_mem (or perhaps
     111             :  * autovacuum_work_mem) memory space to keep track of dead TIDs.  If the
     112             :  * TID store is full, we must call lazy_vacuum to vacuum indexes (and to vacuum
     113             :  * the pages that we've pruned). This frees up the memory space dedicated to
     114             :  * store dead TIDs.
     115             :  *
     116             :  * In practice VACUUM will often complete its initial pass over the target
     117             :  * heap relation without ever running out of space to store TIDs.  This means
     118             :  * that there only needs to be one call to lazy_vacuum, after the initial pass
     119             :  * completes.
     120             :  *
     121             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
     122             :  * Portions Copyright (c) 1994, Regents of the University of California
     123             :  *
     124             :  *
     125             :  * IDENTIFICATION
     126             :  *    src/backend/access/heap/vacuumlazy.c
     127             :  *
     128             :  *-------------------------------------------------------------------------
     129             :  */
     130             : #include "postgres.h"
     131             : 
     132             : #include <math.h>
     133             : 
     134             : #include "access/genam.h"
     135             : #include "access/heapam.h"
     136             : #include "access/htup_details.h"
     137             : #include "access/multixact.h"
     138             : #include "access/tidstore.h"
     139             : #include "access/transam.h"
     140             : #include "access/visibilitymap.h"
     141             : #include "access/xloginsert.h"
     142             : #include "catalog/storage.h"
     143             : #include "commands/dbcommands.h"
     144             : #include "commands/progress.h"
     145             : #include "commands/vacuum.h"
     146             : #include "common/int.h"
     147             : #include "common/pg_prng.h"
     148             : #include "executor/instrument.h"
     149             : #include "miscadmin.h"
     150             : #include "pgstat.h"
     151             : #include "portability/instr_time.h"
     152             : #include "postmaster/autovacuum.h"
     153             : #include "storage/bufmgr.h"
     154             : #include "storage/freespace.h"
     155             : #include "storage/lmgr.h"
     156             : #include "storage/read_stream.h"
     157             : #include "utils/lsyscache.h"
     158             : #include "utils/pg_rusage.h"
     159             : #include "utils/timestamp.h"
     160             : 
     161             : 
     162             : /*
     163             :  * Space/time tradeoff parameters: do these need to be user-tunable?
     164             :  *
     165             :  * To consider truncating the relation, we want there to be at least
     166             :  * REL_TRUNCATE_MINIMUM or (relsize / REL_TRUNCATE_FRACTION) (whichever
     167             :  * is less) potentially-freeable pages.
     168             :  */
     169             : #define REL_TRUNCATE_MINIMUM    1000
     170             : #define REL_TRUNCATE_FRACTION   16
     171             : 
     172             : /*
     173             :  * Timing parameters for truncate locking heuristics.
     174             :  *
     175             :  * These were not exposed as user tunable GUC values because it didn't seem
     176             :  * that the potential for improvement was great enough to merit the cost of
     177             :  * supporting them.
     178             :  */
     179             : #define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL     20  /* ms */
     180             : #define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL      50  /* ms */
     181             : #define VACUUM_TRUNCATE_LOCK_TIMEOUT            5000    /* ms */
     182             : 
     183             : /*
     184             :  * Threshold that controls whether we bypass index vacuuming and heap
     185             :  * vacuuming as an optimization
     186             :  */
     187             : #define BYPASS_THRESHOLD_PAGES  0.02    /* i.e. 2% of rel_pages */
     188             : 
     189             : /*
     190             :  * Perform a failsafe check each time we scan another 4GB of pages.
     191             :  * (Note that this is deliberately kept to a power-of-two, usually 2^19.)
     192             :  */
     193             : #define FAILSAFE_EVERY_PAGES \
     194             :     ((BlockNumber) (((uint64) 4 * 1024 * 1024 * 1024) / BLCKSZ))
     195             : 
     196             : /*
     197             :  * When a table has no indexes, vacuum the FSM after every 8GB, approximately
     198             :  * (it won't be exact because we only vacuum FSM after processing a heap page
     199             :  * that has some removable tuples).  When there are indexes, this is ignored,
     200             :  * and we vacuum FSM after each index/heap cleaning pass.
     201             :  */
     202             : #define VACUUM_FSM_EVERY_PAGES \
     203             :     ((BlockNumber) (((uint64) 8 * 1024 * 1024 * 1024) / BLCKSZ))
     204             : 
     205             : /*
     206             :  * Before we consider skipping a page that's marked as clean in
     207             :  * visibility map, we must've seen at least this many clean pages.
     208             :  */
     209             : #define SKIP_PAGES_THRESHOLD    ((BlockNumber) 32)
     210             : 
     211             : /*
     212             :  * Size of the prefetch window for lazy vacuum backwards truncation scan.
     213             :  * Needs to be a power of 2.
     214             :  */
     215             : #define PREFETCH_SIZE           ((BlockNumber) 32)
     216             : 
     217             : /*
     218             :  * Macro to check if we are in a parallel vacuum.  If true, we are in the
     219             :  * parallel mode and the DSM segment is initialized.
     220             :  */
     221             : #define ParallelVacuumIsActive(vacrel) ((vacrel)->pvs != NULL)
     222             : 
     223             : /* Phases of vacuum during which we report error context. */
     224             : typedef enum
     225             : {
     226             :     VACUUM_ERRCB_PHASE_UNKNOWN,
     227             :     VACUUM_ERRCB_PHASE_SCAN_HEAP,
     228             :     VACUUM_ERRCB_PHASE_VACUUM_INDEX,
     229             :     VACUUM_ERRCB_PHASE_VACUUM_HEAP,
     230             :     VACUUM_ERRCB_PHASE_INDEX_CLEANUP,
     231             :     VACUUM_ERRCB_PHASE_TRUNCATE,
     232             : } VacErrPhase;
     233             : 
     234             : /*
     235             :  * An eager scan of a page that is set all-frozen in the VM is considered
     236             :  * "successful". To spread out freezing overhead across multiple normal
     237             :  * vacuums, we limit the number of successful eager page freezes. The maximum
     238             :  * number of eager page freezes is calculated as a ratio of the all-visible
     239             :  * but not all-frozen pages at the beginning of the vacuum.
     240             :  */
     241             : #define MAX_EAGER_FREEZE_SUCCESS_RATE 0.2
     242             : 
     243             : /*
     244             :  * On the assumption that different regions of the table tend to have
     245             :  * similarly aged data, once vacuum fails to freeze
     246             :  * vacuum_max_eager_freeze_failure_rate of the blocks in a region of size
     247             :  * EAGER_SCAN_REGION_SIZE, it suspends eager scanning until it has progressed
     248             :  * to another region of the table with potentially older data.
     249             :  */
     250             : #define EAGER_SCAN_REGION_SIZE 4096
     251             : 
     252             : /*
     253             :  * heap_vac_scan_next_block() sets these flags to communicate information
     254             :  * about the block it read to the caller.
     255             :  */
     256             : #define VAC_BLK_WAS_EAGER_SCANNED (1 << 0)
     257             : #define VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM (1 << 1)
     258             : 
     259             : typedef struct LVRelState
     260             : {
     261             :     /* Target heap relation and its indexes */
     262             :     Relation    rel;
     263             :     Relation   *indrels;
     264             :     int         nindexes;
     265             : 
     266             :     /* Buffer access strategy and parallel vacuum state */
     267             :     BufferAccessStrategy bstrategy;
     268             :     ParallelVacuumState *pvs;
     269             : 
     270             :     /* Aggressive VACUUM? (must set relfrozenxid >= FreezeLimit) */
     271             :     bool        aggressive;
     272             :     /* Use visibility map to skip? (disabled by DISABLE_PAGE_SKIPPING) */
     273             :     bool        skipwithvm;
     274             :     /* Consider index vacuuming bypass optimization? */
     275             :     bool        consider_bypass_optimization;
     276             : 
     277             :     /* Doing index vacuuming, index cleanup, rel truncation? */
     278             :     bool        do_index_vacuuming;
     279             :     bool        do_index_cleanup;
     280             :     bool        do_rel_truncate;
     281             : 
     282             :     /* VACUUM operation's cutoffs for freezing and pruning */
     283             :     struct VacuumCutoffs cutoffs;
     284             :     GlobalVisState *vistest;
     285             :     /* Tracks oldest extant XID/MXID for setting relfrozenxid/relminmxid */
     286             :     TransactionId NewRelfrozenXid;
     287             :     MultiXactId NewRelminMxid;
     288             :     bool        skippedallvis;
     289             : 
     290             :     /* Error reporting state */
     291             :     char       *dbname;
     292             :     char       *relnamespace;
     293             :     char       *relname;
     294             :     char       *indname;        /* Current index name */
     295             :     BlockNumber blkno;          /* used only for heap operations */
     296             :     OffsetNumber offnum;        /* used only for heap operations */
     297             :     VacErrPhase phase;
     298             :     bool        verbose;        /* VACUUM VERBOSE? */
     299             : 
     300             :     /*
     301             :      * dead_items stores TIDs whose index tuples are deleted by index
     302             :      * vacuuming. Each TID points to an LP_DEAD line pointer from a heap page
     303             :      * that has been processed by lazy_scan_prune.  Also needed by
     304             :      * lazy_vacuum_heap_rel, which marks the same LP_DEAD line pointers as
     305             :      * LP_UNUSED during second heap pass.
     306             :      *
     307             :      * Both dead_items and dead_items_info are allocated in shared memory in
     308             :      * parallel vacuum cases.
     309             :      */
     310             :     TidStore   *dead_items;     /* TIDs whose index tuples we'll delete */
     311             :     VacDeadItemsInfo *dead_items_info;
     312             : 
     313             :     BlockNumber rel_pages;      /* total number of pages */
     314             :     BlockNumber scanned_pages;  /* # pages examined (not skipped via VM) */
     315             : 
     316             :     /*
     317             :      * Count of all-visible blocks eagerly scanned (for logging only). This
     318             :      * does not include skippable blocks scanned due to SKIP_PAGES_THRESHOLD.
     319             :      */
     320             :     BlockNumber eager_scanned_pages;
     321             : 
     322             :     BlockNumber removed_pages;  /* # pages removed by relation truncation */
     323             :     BlockNumber new_frozen_tuple_pages; /* # pages with newly frozen tuples */
     324             : 
     325             :     /* # pages newly set all-visible in the VM */
     326             :     BlockNumber vm_new_visible_pages;
     327             : 
     328             :     /*
     329             :      * # pages newly set all-visible and all-frozen in the VM. This is a
     330             :      * subset of vm_new_visible_pages. That is, vm_new_visible_pages includes
     331             :      * all pages set all-visible, but vm_new_visible_frozen_pages includes
     332             :      * only those which were also set all-frozen.
     333             :      */
     334             :     BlockNumber vm_new_visible_frozen_pages;
     335             : 
     336             :     /* # all-visible pages newly set all-frozen in the VM */
     337             :     BlockNumber vm_new_frozen_pages;
     338             : 
     339             :     BlockNumber lpdead_item_pages;  /* # pages with LP_DEAD items */
     340             :     BlockNumber missed_dead_pages;  /* # pages with missed dead tuples */
     341             :     BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
     342             : 
     343             :     /* Statistics output by us, for table */
     344             :     double      new_rel_tuples; /* new estimated total # of tuples */
     345             :     double      new_live_tuples;    /* new estimated total # of live tuples */
     346             :     /* Statistics output by index AMs */
     347             :     IndexBulkDeleteResult **indstats;
     348             : 
     349             :     /* Instrumentation counters */
     350             :     int         num_index_scans;
     351             :     /* Counters that follow are only for scanned_pages */
     352             :     int64       tuples_deleted; /* # deleted from table */
     353             :     int64       tuples_frozen;  /* # newly frozen */
     354             :     int64       lpdead_items;   /* # deleted from indexes */
     355             :     int64       live_tuples;    /* # live tuples remaining */
     356             :     int64       recently_dead_tuples;   /* # dead, but not yet removable */
     357             :     int64       missed_dead_tuples; /* # removable, but not removed */
     358             : 
     359             :     /* State maintained by heap_vac_scan_next_block() */
     360             :     BlockNumber current_block;  /* last block returned */
     361             :     BlockNumber next_unskippable_block; /* next unskippable block */
     362             :     bool        next_unskippable_allvis;    /* its visibility status */
     363             :     bool        next_unskippable_eager_scanned; /* if it was eagerly scanned */
     364             :     Buffer      next_unskippable_vmbuffer;  /* buffer containing its VM bit */
     365             : 
     366             :     /* State related to managing eager scanning of all-visible pages */
     367             : 
     368             :     /*
     369             :      * A normal vacuum that has failed to freeze too many eagerly scanned
     370             :      * blocks in a region suspends eager scanning.
     371             :      * next_eager_scan_region_start is the block number of the first block
     372             :      * eligible for resumed eager scanning.
     373             :      *
     374             :      * When eager scanning is permanently disabled, either initially
     375             :      * (including for aggressive vacuum) or due to hitting the success cap,
     376             :      * this is set to InvalidBlockNumber.
     377             :      */
     378             :     BlockNumber next_eager_scan_region_start;
     379             : 
     380             :     /*
     381             :      * The remaining number of blocks a normal vacuum will consider eager
     382             :      * scanning when it is successful. When eager scanning is enabled, this is
     383             :      * initialized to MAX_EAGER_FREEZE_SUCCESS_RATE of the total number of
     384             :      * all-visible but not all-frozen pages. For each eager freeze success,
     385             :      * this is decremented. Once it hits 0, eager scanning is permanently
     386             :      * disabled. It is initialized to 0 if eager scanning starts out disabled
     387             :      * (including for aggressive vacuum).
     388             :      */
     389             :     BlockNumber eager_scan_remaining_successes;
     390             : 
     391             :     /*
     392             :      * The maximum number of blocks which may be eagerly scanned and not
     393             :      * frozen before eager scanning is temporarily suspended. This is
     394             :      * configurable both globally, via the
     395             :      * vacuum_max_eager_freeze_failure_rate GUC, and per table, with a table
     396             :      * storage parameter of the same name. It is calculated as
     397             :      * vacuum_max_eager_freeze_failure_rate of EAGER_SCAN_REGION_SIZE blocks.
     398             :      * It is 0 when eager scanning is disabled.
     399             :      */
     400             :     BlockNumber eager_scan_max_fails_per_region;
     401             : 
     402             :     /*
     403             :      * The number of eagerly scanned blocks vacuum failed to freeze (due to
     404             :      * age) in the current eager scan region. Vacuum resets it to
     405             :      * eager_scan_max_fails_per_region each time it enters a new region of the
     406             :      * relation. If eager_scan_remaining_fails hits 0, eager scanning is
     407             :      * suspended until the next region. It is also 0 if eager scanning has
     408             :      * been permanently disabled.
     409             :      */
     410             :     BlockNumber eager_scan_remaining_fails;
     411             : } LVRelState;
     412             : 
     413             : 
     414             : /* Struct for saving and restoring vacuum error information. */
     415             : typedef struct LVSavedErrInfo
     416             : {
     417             :     BlockNumber blkno;
     418             :     OffsetNumber offnum;
     419             :     VacErrPhase phase;
     420             : } LVSavedErrInfo;
     421             : 
     422             : 
     423             : /* non-export function prototypes */
     424             : static void lazy_scan_heap(LVRelState *vacrel);
     425             : static void heap_vacuum_eager_scan_setup(LVRelState *vacrel,
     426             :                                          VacuumParams *params);
     427             : static BlockNumber heap_vac_scan_next_block(ReadStream *stream,
     428             :                                             void *callback_private_data,
     429             :                                             void *per_buffer_data);
     430             : static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis);
     431             : static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf,
     432             :                                    BlockNumber blkno, Page page,
     433             :                                    bool sharelock, Buffer vmbuffer);
     434             : static void lazy_scan_prune(LVRelState *vacrel, Buffer buf,
     435             :                             BlockNumber blkno, Page page,
     436             :                             Buffer vmbuffer, bool all_visible_according_to_vm,
     437             :                             bool *has_lpdead_items, bool *vm_page_frozen);
     438             : static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf,
     439             :                               BlockNumber blkno, Page page,
     440             :                               bool *has_lpdead_items);
     441             : static void lazy_vacuum(LVRelState *vacrel);
     442             : static bool lazy_vacuum_all_indexes(LVRelState *vacrel);
     443             : static void lazy_vacuum_heap_rel(LVRelState *vacrel);
     444             : static void lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno,
     445             :                                   Buffer buffer, OffsetNumber *deadoffsets,
     446             :                                   int num_offsets, Buffer vmbuffer);
     447             : static bool lazy_check_wraparound_failsafe(LVRelState *vacrel);
     448             : static void lazy_cleanup_all_indexes(LVRelState *vacrel);
     449             : static IndexBulkDeleteResult *lazy_vacuum_one_index(Relation indrel,
     450             :                                                     IndexBulkDeleteResult *istat,
     451             :                                                     double reltuples,
     452             :                                                     LVRelState *vacrel);
     453             : static IndexBulkDeleteResult *lazy_cleanup_one_index(Relation indrel,
     454             :                                                      IndexBulkDeleteResult *istat,
     455             :                                                      double reltuples,
     456             :                                                      bool estimated_count,
     457             :                                                      LVRelState *vacrel);
     458             : static bool should_attempt_truncation(LVRelState *vacrel);
     459             : static void lazy_truncate_heap(LVRelState *vacrel);
     460             : static BlockNumber count_nondeletable_pages(LVRelState *vacrel,
     461             :                                             bool *lock_waiter_detected);
     462             : static void dead_items_alloc(LVRelState *vacrel, int nworkers);
     463             : static void dead_items_add(LVRelState *vacrel, BlockNumber blkno, OffsetNumber *offsets,
     464             :                            int num_offsets);
     465             : static void dead_items_reset(LVRelState *vacrel);
     466             : static void dead_items_cleanup(LVRelState *vacrel);
     467             : static bool heap_page_is_all_visible(LVRelState *vacrel, Buffer buf,
     468             :                                      TransactionId *visibility_cutoff_xid, bool *all_frozen);
     469             : static void update_relstats_all_indexes(LVRelState *vacrel);
     470             : static void vacuum_error_callback(void *arg);
     471             : static void update_vacuum_error_info(LVRelState *vacrel,
     472             :                                      LVSavedErrInfo *saved_vacrel,
     473             :                                      int phase, BlockNumber blkno,
     474             :                                      OffsetNumber offnum);
     475             : static void restore_vacuum_error_info(LVRelState *vacrel,
     476             :                                       const LVSavedErrInfo *saved_vacrel);
     477             : 
     478             : 
     479             : 
     480             : /*
     481             :  * Helper to set up the eager scanning state for vacuuming a single relation.
     482             :  * Initializes the eager scan management related members of the LVRelState.
     483             :  *
     484             :  * Caller provides whether or not an aggressive vacuum is required due to
     485             :  * vacuum options or for relfrozenxid/relminmxid advancement.
     486             :  */
     487             : static void
     488      238900 : heap_vacuum_eager_scan_setup(LVRelState *vacrel, VacuumParams *params)
     489             : {
     490             :     uint32      randseed;
     491             :     BlockNumber allvisible;
     492             :     BlockNumber allfrozen;
     493             :     float       first_region_ratio;
     494      238900 :     bool        oldest_unfrozen_before_cutoff = false;
     495             : 
     496             :     /*
     497             :      * Initialize eager scan management fields to their disabled values.
     498             :      * Aggressive vacuums, normal vacuums of small tables, and normal vacuums
     499             :      * of tables without sufficiently old tuples disable eager scanning.
     500             :      */
     501      238900 :     vacrel->next_eager_scan_region_start = InvalidBlockNumber;
     502      238900 :     vacrel->eager_scan_max_fails_per_region = 0;
     503      238900 :     vacrel->eager_scan_remaining_fails = 0;
     504      238900 :     vacrel->eager_scan_remaining_successes = 0;
     505             : 
     506             :     /* If eager scanning is explicitly disabled, just return. */
     507      238900 :     if (params->max_eager_freeze_failure_rate == 0)
     508      238900 :         return;
     509             : 
     510             :     /*
     511             :      * The caller will have determined whether or not an aggressive vacuum is
     512             :      * required by either the vacuum parameters or the relative age of the
     513             :      * oldest unfrozen transaction IDs. An aggressive vacuum must scan every
     514             :      * all-visible page to safely advance the relfrozenxid and/or relminmxid,
     515             :      * so scans of all-visible pages are not considered eager.
     516             :      */
     517      238900 :     if (vacrel->aggressive)
     518      228230 :         return;
     519             : 
     520             :     /*
     521             :      * Aggressively vacuuming a small relation shouldn't take long, so it
     522             :      * isn't worth amortizing. We use two times the region size as the size
     523             :      * cutoff because the eager scan start block is a random spot somewhere in
     524             :      * the first region, making the second region the first to be eager
     525             :      * scanned normally.
     526             :      */
     527       10670 :     if (vacrel->rel_pages < 2 * EAGER_SCAN_REGION_SIZE)
     528       10670 :         return;
     529             : 
     530             :     /*
     531             :      * We only want to enable eager scanning if we are likely to be able to
     532             :      * freeze some of the pages in the relation.
     533             :      *
     534             :      * Tuples with XIDs older than OldestXmin or MXIDs older than OldestMxact
     535             :      * are technically freezable, but we won't freeze them unless the criteria
     536             :      * for opportunistic freezing is met. Only tuples with XIDs/MXIDs older
     537             :      * than the FreezeLimit/MultiXactCutoff are frozen in the common case.
     538             :      *
     539             :      * So, as a heuristic, we wait until the FreezeLimit has advanced past the
     540             :      * relfrozenxid or the MultiXactCutoff has advanced past the relminmxid to
     541             :      * enable eager scanning.
     542             :      */
     543           0 :     if (TransactionIdIsNormal(vacrel->cutoffs.relfrozenxid) &&
     544           0 :         TransactionIdPrecedes(vacrel->cutoffs.relfrozenxid,
     545             :                               vacrel->cutoffs.FreezeLimit))
     546           0 :         oldest_unfrozen_before_cutoff = true;
     547             : 
     548           0 :     if (!oldest_unfrozen_before_cutoff &&
     549           0 :         MultiXactIdIsValid(vacrel->cutoffs.relminmxid) &&
     550           0 :         MultiXactIdPrecedes(vacrel->cutoffs.relminmxid,
     551             :                             vacrel->cutoffs.MultiXactCutoff))
     552           0 :         oldest_unfrozen_before_cutoff = true;
     553             : 
     554           0 :     if (!oldest_unfrozen_before_cutoff)
     555           0 :         return;
     556             : 
     557             :     /* We have met the criteria to eagerly scan some pages. */
     558             : 
     559             :     /*
     560             :      * Our success cap is MAX_EAGER_FREEZE_SUCCESS_RATE of the number of
     561             :      * all-visible but not all-frozen blocks in the relation.
     562             :      */
     563           0 :     visibilitymap_count(vacrel->rel, &allvisible, &allfrozen);
     564             : 
     565           0 :     vacrel->eager_scan_remaining_successes =
     566           0 :         (BlockNumber) (MAX_EAGER_FREEZE_SUCCESS_RATE *
     567           0 :                        (allvisible - allfrozen));
     568             : 
     569             :     /* If every all-visible page is frozen, eager scanning is disabled. */
     570           0 :     if (vacrel->eager_scan_remaining_successes == 0)
     571           0 :         return;
     572             : 
     573             :     /*
     574             :      * Now calculate the bounds of the first eager scan region. Its end block
     575             :      * will be a random spot somewhere in the first EAGER_SCAN_REGION_SIZE
     576             :      * blocks. This affects the bounds of all subsequent regions and avoids
     577             :      * eager scanning and failing to freeze the same blocks each vacuum of the
     578             :      * relation.
     579             :      */
     580           0 :     randseed = pg_prng_uint32(&pg_global_prng_state);
     581             : 
     582           0 :     vacrel->next_eager_scan_region_start = randseed % EAGER_SCAN_REGION_SIZE;
     583             : 
     584             :     Assert(params->max_eager_freeze_failure_rate > 0 &&
     585             :            params->max_eager_freeze_failure_rate <= 1);
     586             : 
     587           0 :     vacrel->eager_scan_max_fails_per_region =
     588           0 :         params->max_eager_freeze_failure_rate *
     589             :         EAGER_SCAN_REGION_SIZE;
     590             : 
     591             :     /*
     592             :      * The first region will be smaller than subsequent regions. As such,
     593             :      * adjust the eager freeze failures tolerated for this region.
     594             :      */
     595           0 :     first_region_ratio = 1 - (float) vacrel->next_eager_scan_region_start /
     596             :         EAGER_SCAN_REGION_SIZE;
     597             : 
     598           0 :     vacrel->eager_scan_remaining_fails =
     599           0 :         vacrel->eager_scan_max_fails_per_region *
     600             :         first_region_ratio;
     601             : }
     602             : 
     603             : /*
     604             :  *  heap_vacuum_rel() -- perform VACUUM for one heap relation
     605             :  *
     606             :  *      This routine sets things up for and then calls lazy_scan_heap, where
     607             :  *      almost all work actually takes place.  Finalizes everything after call
     608             :  *      returns by managing relation truncation and updating rel's pg_class
     609             :  *      entry. (Also updates pg_class entries for any indexes that need it.)
     610             :  *
     611             :  *      At entry, we have already established a transaction and opened
     612             :  *      and locked the relation.
     613             :  */
     614             : void
     615      238900 : heap_vacuum_rel(Relation rel, VacuumParams *params,
     616             :                 BufferAccessStrategy bstrategy)
     617             : {
     618             :     LVRelState *vacrel;
     619             :     bool        verbose,
     620             :                 instrument,
     621             :                 skipwithvm,
     622             :                 frozenxid_updated,
     623             :                 minmulti_updated;
     624             :     BlockNumber orig_rel_pages,
     625             :                 new_rel_pages,
     626             :                 new_rel_allvisible,
     627             :                 new_rel_allfrozen;
     628             :     PGRUsage    ru0;
     629      238900 :     TimestampTz starttime = 0;
     630      238900 :     PgStat_Counter startreadtime = 0,
     631      238900 :                 startwritetime = 0;
     632      238900 :     WalUsage    startwalusage = pgWalUsage;
     633      238900 :     BufferUsage startbufferusage = pgBufferUsage;
     634             :     ErrorContextCallback errcallback;
     635      238900 :     char      **indnames = NULL;
     636             : 
     637      238900 :     verbose = (params->options & VACOPT_VERBOSE) != 0;
     638      451838 :     instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
     639      212938 :                               params->log_min_duration >= 0));
     640      238900 :     if (instrument)
     641             :     {
     642      212958 :         pg_rusage_init(&ru0);
     643      212958 :         if (track_io_timing)
     644             :         {
     645           0 :             startreadtime = pgStatBlockReadTime;
     646           0 :             startwritetime = pgStatBlockWriteTime;
     647             :         }
     648             :     }
     649             : 
     650             :     /* Used for instrumentation and stats report */
     651      238900 :     starttime = GetCurrentTimestamp();
     652             : 
     653      238900 :     pgstat_progress_start_command(PROGRESS_COMMAND_VACUUM,
     654             :                                   RelationGetRelid(rel));
     655             : 
     656             :     /*
     657             :      * Setup error traceback support for ereport() first.  The idea is to set
     658             :      * up an error context callback to display additional information on any
     659             :      * error during a vacuum.  During different phases of vacuum, we update
     660             :      * the state so that the error context callback always display current
     661             :      * information.
     662             :      *
     663             :      * Copy the names of heap rel into local memory for error reporting
     664             :      * purposes, too.  It isn't always safe to assume that we can get the name
     665             :      * of each rel.  It's convenient for code in lazy_scan_heap to always use
     666             :      * these temp copies.
     667             :      */
     668      238900 :     vacrel = (LVRelState *) palloc0(sizeof(LVRelState));
     669      238900 :     vacrel->dbname = get_database_name(MyDatabaseId);
     670      238900 :     vacrel->relnamespace = get_namespace_name(RelationGetNamespace(rel));
     671      238900 :     vacrel->relname = pstrdup(RelationGetRelationName(rel));
     672      238900 :     vacrel->indname = NULL;
     673      238900 :     vacrel->phase = VACUUM_ERRCB_PHASE_UNKNOWN;
     674      238900 :     vacrel->verbose = verbose;
     675      238900 :     errcallback.callback = vacuum_error_callback;
     676      238900 :     errcallback.arg = vacrel;
     677      238900 :     errcallback.previous = error_context_stack;
     678      238900 :     error_context_stack = &errcallback;
     679             : 
     680             :     /* Set up high level stuff about rel and its indexes */
     681      238900 :     vacrel->rel = rel;
     682      238900 :     vac_open_indexes(vacrel->rel, RowExclusiveLock, &vacrel->nindexes,
     683             :                      &vacrel->indrels);
     684      238900 :     vacrel->bstrategy = bstrategy;
     685      238900 :     if (instrument && vacrel->nindexes > 0)
     686             :     {
     687             :         /* Copy index names used by instrumentation (not error reporting) */
     688      203594 :         indnames = palloc(sizeof(char *) * vacrel->nindexes);
     689      524690 :         for (int i = 0; i < vacrel->nindexes; i++)
     690      321096 :             indnames[i] = pstrdup(RelationGetRelationName(vacrel->indrels[i]));
     691             :     }
     692             : 
     693             :     /*
     694             :      * The index_cleanup param either disables index vacuuming and cleanup or
     695             :      * forces it to go ahead when we would otherwise apply the index bypass
     696             :      * optimization.  The default is 'auto', which leaves the final decision
     697             :      * up to lazy_vacuum().
     698             :      *
     699             :      * The truncate param allows user to avoid attempting relation truncation,
     700             :      * though it can't force truncation to happen.
     701             :      */
     702             :     Assert(params->index_cleanup != VACOPTVALUE_UNSPECIFIED);
     703             :     Assert(params->truncate != VACOPTVALUE_UNSPECIFIED &&
     704             :            params->truncate != VACOPTVALUE_AUTO);
     705             : 
     706             :     /*
     707             :      * While VacuumFailSafeActive is reset to false before calling this, we
     708             :      * still need to reset it here due to recursive calls.
     709             :      */
     710      238900 :     VacuumFailsafeActive = false;
     711      238900 :     vacrel->consider_bypass_optimization = true;
     712      238900 :     vacrel->do_index_vacuuming = true;
     713      238900 :     vacrel->do_index_cleanup = true;
     714      238900 :     vacrel->do_rel_truncate = (params->truncate != VACOPTVALUE_DISABLED);
     715      238900 :     if (params->index_cleanup == VACOPTVALUE_DISABLED)
     716             :     {
     717             :         /* Force disable index vacuuming up-front */
     718         260 :         vacrel->do_index_vacuuming = false;
     719         260 :         vacrel->do_index_cleanup = false;
     720             :     }
     721      238640 :     else if (params->index_cleanup == VACOPTVALUE_ENABLED)
     722             :     {
     723             :         /* Force index vacuuming.  Note that failsafe can still bypass. */
     724          30 :         vacrel->consider_bypass_optimization = false;
     725             :     }
     726             :     else
     727             :     {
     728             :         /* Default/auto, make all decisions dynamically */
     729             :         Assert(params->index_cleanup == VACOPTVALUE_AUTO);
     730             :     }
     731             : 
     732             :     /* Initialize page counters explicitly (be tidy) */
     733      238900 :     vacrel->scanned_pages = 0;
     734      238900 :     vacrel->eager_scanned_pages = 0;
     735      238900 :     vacrel->removed_pages = 0;
     736      238900 :     vacrel->new_frozen_tuple_pages = 0;
     737      238900 :     vacrel->lpdead_item_pages = 0;
     738      238900 :     vacrel->missed_dead_pages = 0;
     739      238900 :     vacrel->nonempty_pages = 0;
     740             :     /* dead_items_alloc allocates vacrel->dead_items later on */
     741             : 
     742             :     /* Allocate/initialize output statistics state */
     743      238900 :     vacrel->new_rel_tuples = 0;
     744      238900 :     vacrel->new_live_tuples = 0;
     745      238900 :     vacrel->indstats = (IndexBulkDeleteResult **)
     746      238900 :         palloc0(vacrel->nindexes * sizeof(IndexBulkDeleteResult *));
     747             : 
     748             :     /* Initialize remaining counters (be tidy) */
     749      238900 :     vacrel->num_index_scans = 0;
     750      238900 :     vacrel->tuples_deleted = 0;
     751      238900 :     vacrel->tuples_frozen = 0;
     752      238900 :     vacrel->lpdead_items = 0;
     753      238900 :     vacrel->live_tuples = 0;
     754      238900 :     vacrel->recently_dead_tuples = 0;
     755      238900 :     vacrel->missed_dead_tuples = 0;
     756             : 
     757      238900 :     vacrel->vm_new_visible_pages = 0;
     758      238900 :     vacrel->vm_new_visible_frozen_pages = 0;
     759      238900 :     vacrel->vm_new_frozen_pages = 0;
     760             : 
     761             :     /*
     762             :      * Get cutoffs that determine which deleted tuples are considered DEAD,
     763             :      * not just RECENTLY_DEAD, and which XIDs/MXIDs to freeze.  Then determine
     764             :      * the extent of the blocks that we'll scan in lazy_scan_heap.  It has to
     765             :      * happen in this order to ensure that the OldestXmin cutoff field works
     766             :      * as an upper bound on the XIDs stored in the pages we'll actually scan
     767             :      * (NewRelfrozenXid tracking must never be allowed to miss unfrozen XIDs).
     768             :      *
     769             :      * Next acquire vistest, a related cutoff that's used in pruning.  We use
     770             :      * vistest in combination with OldestXmin to ensure that
     771             :      * heap_page_prune_and_freeze() always removes any deleted tuple whose
     772             :      * xmax is < OldestXmin.  lazy_scan_prune must never become confused about
     773             :      * whether a tuple should be frozen or removed.  (In the future we might
     774             :      * want to teach lazy_scan_prune to recompute vistest from time to time,
     775             :      * to increase the number of dead tuples it can prune away.)
     776             :      */
     777      238900 :     vacrel->aggressive = vacuum_get_cutoffs(rel, params, &vacrel->cutoffs);
     778      238900 :     vacrel->rel_pages = orig_rel_pages = RelationGetNumberOfBlocks(rel);
     779      238900 :     vacrel->vistest = GlobalVisTestFor(rel);
     780             : 
     781             :     /* Initialize state used to track oldest extant XID/MXID */
     782      238900 :     vacrel->NewRelfrozenXid = vacrel->cutoffs.OldestXmin;
     783      238900 :     vacrel->NewRelminMxid = vacrel->cutoffs.OldestMxact;
     784             : 
     785             :     /*
     786             :      * Initialize state related to tracking all-visible page skipping. This is
     787             :      * very important to determine whether or not it is safe to advance the
     788             :      * relfrozenxid/relminmxid.
     789             :      */
     790      238900 :     vacrel->skippedallvis = false;
     791      238900 :     skipwithvm = true;
     792      238900 :     if (params->options & VACOPT_DISABLE_PAGE_SKIPPING)
     793             :     {
     794             :         /*
     795             :          * Force aggressive mode, and disable skipping blocks using the
     796             :          * visibility map (even those set all-frozen)
     797             :          */
     798         344 :         vacrel->aggressive = true;
     799         344 :         skipwithvm = false;
     800             :     }
     801             : 
     802      238900 :     vacrel->skipwithvm = skipwithvm;
     803             : 
     804             :     /*
     805             :      * Set up eager scan tracking state. This must happen after determining
     806             :      * whether or not the vacuum must be aggressive, because only normal
     807             :      * vacuums use the eager scan algorithm.
     808             :      */
     809      238900 :     heap_vacuum_eager_scan_setup(vacrel, params);
     810             : 
     811      238900 :     if (verbose)
     812             :     {
     813          20 :         if (vacrel->aggressive)
     814           2 :             ereport(INFO,
     815             :                     (errmsg("aggressively vacuuming \"%s.%s.%s\"",
     816             :                             vacrel->dbname, vacrel->relnamespace,
     817             :                             vacrel->relname)));
     818             :         else
     819          18 :             ereport(INFO,
     820             :                     (errmsg("vacuuming \"%s.%s.%s\"",
     821             :                             vacrel->dbname, vacrel->relnamespace,
     822             :                             vacrel->relname)));
     823             :     }
     824             : 
     825             :     /*
     826             :      * Allocate dead_items memory using dead_items_alloc.  This handles
     827             :      * parallel VACUUM initialization as part of allocating shared memory
     828             :      * space used for dead_items.  (But do a failsafe precheck first, to
     829             :      * ensure that parallel VACUUM won't be attempted at all when relfrozenxid
     830             :      * is already dangerously old.)
     831             :      */
     832      238900 :     lazy_check_wraparound_failsafe(vacrel);
     833      238900 :     dead_items_alloc(vacrel, params->nworkers);
     834             : 
     835             :     /*
     836             :      * Call lazy_scan_heap to perform all required heap pruning, index
     837             :      * vacuuming, and heap vacuuming (plus related processing)
     838             :      */
     839      238900 :     lazy_scan_heap(vacrel);
     840             : 
     841             :     /*
     842             :      * Free resources managed by dead_items_alloc.  This ends parallel mode in
     843             :      * passing when necessary.
     844             :      */
     845      238900 :     dead_items_cleanup(vacrel);
     846             :     Assert(!IsInParallelMode());
     847             : 
     848             :     /*
     849             :      * Update pg_class entries for each of rel's indexes where appropriate.
     850             :      *
     851             :      * Unlike the later update to rel's pg_class entry, this is not critical.
     852             :      * Maintains relpages/reltuples statistics used by the planner only.
     853             :      */
     854      238900 :     if (vacrel->do_index_cleanup)
     855      175776 :         update_relstats_all_indexes(vacrel);
     856             : 
     857             :     /* Done with rel's indexes */
     858      238900 :     vac_close_indexes(vacrel->nindexes, vacrel->indrels, NoLock);
     859             : 
     860             :     /* Optionally truncate rel */
     861      238900 :     if (should_attempt_truncation(vacrel))
     862         284 :         lazy_truncate_heap(vacrel);
     863             : 
     864             :     /* Pop the error context stack */
     865      238900 :     error_context_stack = errcallback.previous;
     866             : 
     867             :     /* Report that we are now doing final cleanup */
     868      238900 :     pgstat_progress_update_param(PROGRESS_VACUUM_PHASE,
     869             :                                  PROGRESS_VACUUM_PHASE_FINAL_CLEANUP);
     870             : 
     871             :     /*
     872             :      * Prepare to update rel's pg_class entry.
     873             :      *
     874             :      * Aggressive VACUUMs must always be able to advance relfrozenxid to a
     875             :      * value >= FreezeLimit, and relminmxid to a value >= MultiXactCutoff.
     876             :      * Non-aggressive VACUUMs may advance them by any amount, or not at all.
     877             :      */
     878             :     Assert(vacrel->NewRelfrozenXid == vacrel->cutoffs.OldestXmin ||
     879             :            TransactionIdPrecedesOrEquals(vacrel->aggressive ? vacrel->cutoffs.FreezeLimit :
     880             :                                          vacrel->cutoffs.relfrozenxid,
     881             :                                          vacrel->NewRelfrozenXid));
     882             :     Assert(vacrel->NewRelminMxid == vacrel->cutoffs.OldestMxact ||
     883             :            MultiXactIdPrecedesOrEquals(vacrel->aggressive ? vacrel->cutoffs.MultiXactCutoff :
     884             :                                        vacrel->cutoffs.relminmxid,
     885             :                                        vacrel->NewRelminMxid));
     886      238900 :     if (vacrel->skippedallvis)
     887             :     {
     888             :         /*
     889             :          * Must keep original relfrozenxid in a non-aggressive VACUUM that
     890             :          * chose to skip an all-visible page range.  The state that tracks new
     891             :          * values will have missed unfrozen XIDs from the pages we skipped.
     892             :          */
     893             :         Assert(!vacrel->aggressive);
     894          60 :         vacrel->NewRelfrozenXid = InvalidTransactionId;
     895          60 :         vacrel->NewRelminMxid = InvalidMultiXactId;
     896             :     }
     897             : 
     898             :     /*
     899             :      * For safety, clamp relallvisible to be not more than what we're setting
     900             :      * pg_class.relpages to
     901             :      */
     902      238900 :     new_rel_pages = vacrel->rel_pages;   /* After possible rel truncation */
     903      238900 :     visibilitymap_count(rel, &new_rel_allvisible, &new_rel_allfrozen);
     904      238900 :     if (new_rel_allvisible > new_rel_pages)
     905           0 :         new_rel_allvisible = new_rel_pages;
     906             : 
     907             :     /*
     908             :      * An all-frozen block _must_ be all-visible. As such, clamp the count of
     909             :      * all-frozen blocks to the count of all-visible blocks. This matches the
     910             :      * clamping of relallvisible above.
     911             :      */
     912      238900 :     if (new_rel_allfrozen > new_rel_allvisible)
     913           0 :         new_rel_allfrozen = new_rel_allvisible;
     914             : 
     915             :     /*
     916             :      * Now actually update rel's pg_class entry.
     917             :      *
     918             :      * In principle new_live_tuples could be -1 indicating that we (still)
     919             :      * don't know the tuple count.  In practice that can't happen, since we
     920             :      * scan every page that isn't skipped using the visibility map.
     921             :      */
     922      238900 :     vac_update_relstats(rel, new_rel_pages, vacrel->new_live_tuples,
     923             :                         new_rel_allvisible, new_rel_allfrozen,
     924      238900 :                         vacrel->nindexes > 0,
     925             :                         vacrel->NewRelfrozenXid, vacrel->NewRelminMxid,
     926             :                         &frozenxid_updated, &minmulti_updated, false);
     927             : 
     928             :     /*
     929             :      * Report results to the cumulative stats system, too.
     930             :      *
     931             :      * Deliberately avoid telling the stats system about LP_DEAD items that
     932             :      * remain in the table due to VACUUM bypassing index and heap vacuuming.
     933             :      * ANALYZE will consider the remaining LP_DEAD items to be dead "tuples".
     934             :      * It seems like a good idea to err on the side of not vacuuming again too
     935             :      * soon in cases where the failsafe prevented significant amounts of heap
     936             :      * vacuuming.
     937             :      */
     938      143310 :     pgstat_report_vacuum(RelationGetRelid(rel),
     939      238900 :                          rel->rd_rel->relisshared,
     940       95590 :                          Max(vacrel->new_live_tuples, 0),
     941      238900 :                          vacrel->recently_dead_tuples +
     942      238900 :                          vacrel->missed_dead_tuples,
     943             :                          starttime);
     944      238900 :     pgstat_progress_end_command();
     945             : 
     946      238900 :     if (instrument)
     947             :     {
     948      212958 :         TimestampTz endtime = GetCurrentTimestamp();
     949             : 
     950      213150 :         if (verbose || params->log_min_duration == 0 ||
     951         192 :             TimestampDifferenceExceeds(starttime, endtime,
     952             :                                        params->log_min_duration))
     953             :         {
     954             :             long        secs_dur;
     955             :             int         usecs_dur;
     956             :             WalUsage    walusage;
     957             :             BufferUsage bufferusage;
     958             :             StringInfoData buf;
     959             :             char       *msgfmt;
     960             :             int32       diff;
     961      212766 :             double      read_rate = 0,
     962      212766 :                         write_rate = 0;
     963             :             int64       total_blks_hit;
     964             :             int64       total_blks_read;
     965             :             int64       total_blks_dirtied;
     966             : 
     967      212766 :             TimestampDifference(starttime, endtime, &secs_dur, &usecs_dur);
     968      212766 :             memset(&walusage, 0, sizeof(WalUsage));
     969      212766 :             WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
     970      212766 :             memset(&bufferusage, 0, sizeof(BufferUsage));
     971      212766 :             BufferUsageAccumDiff(&bufferusage, &pgBufferUsage, &startbufferusage);
     972             : 
     973      212766 :             total_blks_hit = bufferusage.shared_blks_hit +
     974      212766 :                 bufferusage.local_blks_hit;
     975      212766 :             total_blks_read = bufferusage.shared_blks_read +
     976      212766 :                 bufferusage.local_blks_read;
     977      212766 :             total_blks_dirtied = bufferusage.shared_blks_dirtied +
     978      212766 :                 bufferusage.local_blks_dirtied;
     979             : 
     980      212766 :             initStringInfo(&buf);
     981      212766 :             if (verbose)
     982             :             {
     983             :                 /*
     984             :                  * Aggressiveness already reported earlier, in dedicated
     985             :                  * VACUUM VERBOSE ereport
     986             :                  */
     987             :                 Assert(!params->is_wraparound);
     988          20 :                 msgfmt = _("finished vacuuming \"%s.%s.%s\": index scans: %d\n");
     989             :             }
     990      212746 :             else if (params->is_wraparound)
     991             :             {
     992             :                 /*
     993             :                  * While it's possible for a VACUUM to be both is_wraparound
     994             :                  * and !aggressive, that's just a corner-case -- is_wraparound
     995             :                  * implies aggressive.  Produce distinct output for the corner
     996             :                  * case all the same, just in case.
     997             :                  */
     998      212706 :                 if (vacrel->aggressive)
     999      212690 :                     msgfmt = _("automatic aggressive vacuum to prevent wraparound of table \"%s.%s.%s\": index scans: %d\n");
    1000             :                 else
    1001          16 :                     msgfmt = _("automatic vacuum to prevent wraparound of table \"%s.%s.%s\": index scans: %d\n");
    1002             :             }
    1003             :             else
    1004             :             {
    1005          40 :                 if (vacrel->aggressive)
    1006          32 :                     msgfmt = _("automatic aggressive vacuum of table \"%s.%s.%s\": index scans: %d\n");
    1007             :                 else
    1008           8 :                     msgfmt = _("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n");
    1009             :             }
    1010      212766 :             appendStringInfo(&buf, msgfmt,
    1011             :                              vacrel->dbname,
    1012             :                              vacrel->relnamespace,
    1013             :                              vacrel->relname,
    1014             :                              vacrel->num_index_scans);
    1015      297486 :             appendStringInfo(&buf, _("pages: %u removed, %u remain, %u scanned (%.2f%% of total), %u eagerly scanned\n"),
    1016             :                              vacrel->removed_pages,
    1017             :                              new_rel_pages,
    1018             :                              vacrel->scanned_pages,
    1019             :                              orig_rel_pages == 0 ? 100.0 :
    1020       84720 :                              100.0 * vacrel->scanned_pages /
    1021             :                              orig_rel_pages,
    1022             :                              vacrel->eager_scanned_pages);
    1023      212766 :             appendStringInfo(&buf,
    1024      212766 :                              _("tuples: %" PRId64 " removed, %" PRId64 " remain, %" PRId64 " are dead but not yet removable\n"),
    1025             :                              vacrel->tuples_deleted,
    1026      212766 :                              (int64) vacrel->new_rel_tuples,
    1027             :                              vacrel->recently_dead_tuples);
    1028      212766 :             if (vacrel->missed_dead_tuples > 0)
    1029           0 :                 appendStringInfo(&buf,
    1030           0 :                                  _("tuples missed: %" PRId64 " dead from %u pages not removed due to cleanup lock contention\n"),
    1031             :                                  vacrel->missed_dead_tuples,
    1032             :                                  vacrel->missed_dead_pages);
    1033      212766 :             diff = (int32) (ReadNextTransactionId() -
    1034      212766 :                             vacrel->cutoffs.OldestXmin);
    1035      212766 :             appendStringInfo(&buf,
    1036      212766 :                              _("removable cutoff: %u, which was %d XIDs old when operation ended\n"),
    1037             :                              vacrel->cutoffs.OldestXmin, diff);
    1038      212766 :             if (frozenxid_updated)
    1039             :             {
    1040       39490 :                 diff = (int32) (vacrel->NewRelfrozenXid -
    1041       39490 :                                 vacrel->cutoffs.relfrozenxid);
    1042       39490 :                 appendStringInfo(&buf,
    1043       39490 :                                  _("new relfrozenxid: %u, which is %d XIDs ahead of previous value\n"),
    1044             :                                  vacrel->NewRelfrozenXid, diff);
    1045             :             }
    1046      212766 :             if (minmulti_updated)
    1047             :             {
    1048          10 :                 diff = (int32) (vacrel->NewRelminMxid -
    1049          10 :                                 vacrel->cutoffs.relminmxid);
    1050          10 :                 appendStringInfo(&buf,
    1051          10 :                                  _("new relminmxid: %u, which is %d MXIDs ahead of previous value\n"),
    1052             :                                  vacrel->NewRelminMxid, diff);
    1053             :             }
    1054      297486 :             appendStringInfo(&buf, _("frozen: %u pages from table (%.2f%% of total) had %" PRId64 " tuples frozen\n"),
    1055             :                              vacrel->new_frozen_tuple_pages,
    1056             :                              orig_rel_pages == 0 ? 100.0 :
    1057       84720 :                              100.0 * vacrel->new_frozen_tuple_pages /
    1058             :                              orig_rel_pages,
    1059             :                              vacrel->tuples_frozen);
    1060             : 
    1061      212766 :             appendStringInfo(&buf,
    1062      212766 :                              _("visibility map: %u pages set all-visible, %u pages set all-frozen (%u were all-visible)\n"),
    1063             :                              vacrel->vm_new_visible_pages,
    1064      212766 :                              vacrel->vm_new_visible_frozen_pages +
    1065      212766 :                              vacrel->vm_new_frozen_pages,
    1066             :                              vacrel->vm_new_frozen_pages);
    1067      212766 :             if (vacrel->do_index_vacuuming)
    1068             :             {
    1069      150120 :                 if (vacrel->nindexes == 0 || vacrel->num_index_scans == 0)
    1070      150088 :                     appendStringInfoString(&buf, _("index scan not needed: "));
    1071             :                 else
    1072          32 :                     appendStringInfoString(&buf, _("index scan needed: "));
    1073             : 
    1074      150120 :                 msgfmt = _("%u pages from table (%.2f%% of total) had %" PRId64 " dead item identifiers removed\n");
    1075             :             }
    1076             :             else
    1077             :             {
    1078       62646 :                 if (!VacuumFailsafeActive)
    1079           0 :                     appendStringInfoString(&buf, _("index scan bypassed: "));
    1080             :                 else
    1081       62646 :                     appendStringInfoString(&buf, _("index scan bypassed by failsafe: "));
    1082             : 
    1083       62646 :                 msgfmt = _("%u pages from table (%.2f%% of total) have %" PRId64 " dead item identifiers\n");
    1084             :             }
    1085      297486 :             appendStringInfo(&buf, msgfmt,
    1086             :                              vacrel->lpdead_item_pages,
    1087             :                              orig_rel_pages == 0 ? 100.0 :
    1088       84720 :                              100.0 * vacrel->lpdead_item_pages / orig_rel_pages,
    1089             :                              vacrel->lpdead_items);
    1090      533486 :             for (int i = 0; i < vacrel->nindexes; i++)
    1091             :             {
    1092      320720 :                 IndexBulkDeleteResult *istat = vacrel->indstats[i];
    1093             : 
    1094      320720 :                 if (!istat)
    1095      320666 :                     continue;
    1096             : 
    1097          54 :                 appendStringInfo(&buf,
    1098          54 :                                  _("index \"%s\": pages: %u in total, %u newly deleted, %u currently deleted, %u reusable\n"),
    1099          54 :                                  indnames[i],
    1100             :                                  istat->num_pages,
    1101             :                                  istat->pages_newly_deleted,
    1102             :                                  istat->pages_deleted,
    1103             :                                  istat->pages_free);
    1104             :             }
    1105      212766 :             if (track_cost_delay_timing)
    1106             :             {
    1107             :                 /*
    1108             :                  * We bypass the changecount mechanism because this value is
    1109             :                  * only updated by the calling process.  We also rely on the
    1110             :                  * above call to pgstat_progress_end_command() to not clear
    1111             :                  * the st_progress_param array.
    1112             :                  */
    1113           0 :                 appendStringInfo(&buf, _("delay time: %.3f ms\n"),
    1114           0 :                                  (double) MyBEEntry->st_progress_param[PROGRESS_VACUUM_DELAY_TIME] / 1000000.0);
    1115             :             }
    1116      212766 :             if (track_io_timing)
    1117             :             {
    1118           0 :                 double      read_ms = (double) (pgStatBlockReadTime - startreadtime) / 1000;
    1119           0 :                 double      write_ms = (double) (pgStatBlockWriteTime - startwritetime) / 1000;
    1120             : 
    1121           0 :                 appendStringInfo(&buf, _("I/O timings: read: %.3f ms, write: %.3f ms\n"),
    1122             :                                  read_ms, write_ms);
    1123             :             }
    1124      212766 :             if (secs_dur > 0 || usecs_dur > 0)
    1125             :             {
    1126      212766 :                 read_rate = (double) BLCKSZ * total_blks_read /
    1127      212766 :                     (1024 * 1024) / (secs_dur + usecs_dur / 1000000.0);
    1128      212766 :                 write_rate = (double) BLCKSZ * total_blks_dirtied /
    1129      212766 :                     (1024 * 1024) / (secs_dur + usecs_dur / 1000000.0);
    1130             :             }
    1131      212766 :             appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
    1132             :                              read_rate, write_rate);
    1133      212766 :             appendStringInfo(&buf,
    1134      212766 :                              _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
    1135             :                              total_blks_hit,
    1136             :                              total_blks_read,
    1137             :                              total_blks_dirtied);
    1138      212766 :             appendStringInfo(&buf,
    1139      212766 :                              _("WAL usage: %" PRId64 " records, %" PRId64 " full page images, %" PRIu64 " bytes, %" PRId64 " buffers full\n"),
    1140             :                              walusage.wal_records,
    1141             :                              walusage.wal_fpi,
    1142             :                              walusage.wal_bytes,
    1143             :                              walusage.wal_buffers_full);
    1144      212766 :             appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
    1145             : 
    1146      212766 :             ereport(verbose ? INFO : LOG,
    1147             :                     (errmsg_internal("%s", buf.data)));
    1148      212764 :             pfree(buf.data);
    1149             :         }
    1150             :     }
    1151             : 
    1152             :     /* Cleanup index statistics and index names */
    1153      597188 :     for (int i = 0; i < vacrel->nindexes; i++)
    1154             :     {
    1155      358290 :         if (vacrel->indstats[i])
    1156        2702 :             pfree(vacrel->indstats[i]);
    1157             : 
    1158      358290 :         if (instrument)
    1159      321090 :             pfree(indnames[i]);
    1160             :     }
    1161      238898 : }
    1162             : 
    1163             : /*
    1164             :  *  lazy_scan_heap() -- workhorse function for VACUUM
    1165             :  *
    1166             :  *      This routine prunes each page in the heap, and considers the need to
    1167             :  *      freeze remaining tuples with storage (not including pages that can be
    1168             :  *      skipped using the visibility map).  Also performs related maintenance
    1169             :  *      of the FSM and visibility map.  These steps all take place during an
    1170             :  *      initial pass over the target heap relation.
    1171             :  *
    1172             :  *      Also invokes lazy_vacuum_all_indexes to vacuum indexes, which largely
    1173             :  *      consists of deleting index tuples that point to LP_DEAD items left in
    1174             :  *      heap pages following pruning.  Earlier initial pass over the heap will
    1175             :  *      have collected the TIDs whose index tuples need to be removed.
    1176             :  *
    1177             :  *      Finally, invokes lazy_vacuum_heap_rel to vacuum heap pages, which
    1178             :  *      largely consists of marking LP_DEAD items (from vacrel->dead_items)
    1179             :  *      as LP_UNUSED.  This has to happen in a second, final pass over the
    1180             :  *      heap, to preserve a basic invariant that all index AMs rely on: no
    1181             :  *      extant index tuple can ever be allowed to contain a TID that points to
    1182             :  *      an LP_UNUSED line pointer in the heap.  We must disallow premature
    1183             :  *      recycling of line pointers to avoid index scans that get confused
    1184             :  *      about which TID points to which tuple immediately after recycling.
    1185             :  *      (Actually, this isn't a concern when target heap relation happens to
    1186             :  *      have no indexes, which allows us to safely apply the one-pass strategy
    1187             :  *      as an optimization).
    1188             :  *
    1189             :  *      In practice we often have enough space to fit all TIDs, and so won't
    1190             :  *      need to call lazy_vacuum more than once, after our initial pass over
    1191             :  *      the heap has totally finished.  Otherwise things are slightly more
    1192             :  *      complicated: our "initial pass" over the heap applies only to those
    1193             :  *      pages that were pruned before we needed to call lazy_vacuum, and our
    1194             :  *      "final pass" over the heap only vacuums these same heap pages.
    1195             :  *      However, we process indexes in full every time lazy_vacuum is called,
    1196             :  *      which makes index processing very inefficient when memory is in short
    1197             :  *      supply.
    1198             :  */
    1199             : static void
    1200      238900 : lazy_scan_heap(LVRelState *vacrel)
    1201             : {
    1202             :     ReadStream *stream;
    1203      238900 :     BlockNumber rel_pages = vacrel->rel_pages,
    1204      238900 :                 blkno = 0,
    1205      238900 :                 next_fsm_block_to_vacuum = 0;
    1206      238900 :     BlockNumber orig_eager_scan_success_limit =
    1207             :         vacrel->eager_scan_remaining_successes; /* for logging */
    1208      238900 :     Buffer      vmbuffer = InvalidBuffer;
    1209      238900 :     const int   initprog_index[] = {
    1210             :         PROGRESS_VACUUM_PHASE,
    1211             :         PROGRESS_VACUUM_TOTAL_HEAP_BLKS,
    1212             :         PROGRESS_VACUUM_MAX_DEAD_TUPLE_BYTES
    1213             :     };
    1214             :     int64       initprog_val[3];
    1215             : 
    1216             :     /* Report that we're scanning the heap, advertising total # of blocks */
    1217      238900 :     initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
    1218      238900 :     initprog_val[1] = rel_pages;
    1219      238900 :     initprog_val[2] = vacrel->dead_items_info->max_bytes;
    1220      238900 :     pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
    1221             : 
    1222             :     /* Initialize for the first heap_vac_scan_next_block() call */
    1223      238900 :     vacrel->current_block = InvalidBlockNumber;
    1224      238900 :     vacrel->next_unskippable_block = InvalidBlockNumber;
    1225      238900 :     vacrel->next_unskippable_allvis = false;
    1226      238900 :     vacrel->next_unskippable_eager_scanned = false;
    1227      238900 :     vacrel->next_unskippable_vmbuffer = InvalidBuffer;
    1228             : 
    1229             :     /*
    1230             :      * Set up the read stream for vacuum's first pass through the heap.
    1231             :      *
    1232             :      * This could be made safe for READ_STREAM_USE_BATCHING, but only with
    1233             :      * explicit work in heap_vac_scan_next_block.
    1234             :      */
    1235      238900 :     stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE,
    1236             :                                         vacrel->bstrategy,
    1237             :                                         vacrel->rel,
    1238             :                                         MAIN_FORKNUM,
    1239             :                                         heap_vac_scan_next_block,
    1240             :                                         vacrel,
    1241             :                                         sizeof(uint8));
    1242             : 
    1243             :     while (true)
    1244      877746 :     {
    1245             :         Buffer      buf;
    1246             :         Page        page;
    1247     1116646 :         uint8       blk_info = 0;
    1248             :         bool        has_lpdead_items;
    1249     1116646 :         void       *per_buffer_data = NULL;
    1250     1116646 :         bool        vm_page_frozen = false;
    1251     1116646 :         bool        got_cleanup_lock = false;
    1252             : 
    1253     1116646 :         vacuum_delay_point(false);
    1254             : 
    1255             :         /*
    1256             :          * Regularly check if wraparound failsafe should trigger.
    1257             :          *
    1258             :          * There is a similar check inside lazy_vacuum_all_indexes(), but
    1259             :          * relfrozenxid might start to look dangerously old before we reach
    1260             :          * that point.  This check also provides failsafe coverage for the
    1261             :          * one-pass strategy, and the two-pass strategy with the index_cleanup
    1262             :          * param set to 'off'.
    1263             :          */
    1264     1116646 :         if (vacrel->scanned_pages > 0 &&
    1265      877746 :             vacrel->scanned_pages % FAILSAFE_EVERY_PAGES == 0)
    1266           0 :             lazy_check_wraparound_failsafe(vacrel);
    1267             : 
    1268             :         /*
    1269             :          * Consider if we definitely have enough space to process TIDs on page
    1270             :          * already.  If we are close to overrunning the available space for
    1271             :          * dead_items TIDs, pause and do a cycle of vacuuming before we tackle
    1272             :          * this page. However, let's force at least one page-worth of tuples
    1273             :          * to be stored as to ensure we do at least some work when the memory
    1274             :          * configured is so low that we run out before storing anything.
    1275             :          */
    1276     1116646 :         if (vacrel->dead_items_info->num_items > 0 &&
    1277       47506 :             TidStoreMemoryUsage(vacrel->dead_items) > vacrel->dead_items_info->max_bytes)
    1278             :         {
    1279             :             /*
    1280             :              * Before beginning index vacuuming, we release any pin we may
    1281             :              * hold on the visibility map page.  This isn't necessary for
    1282             :              * correctness, but we do it anyway to avoid holding the pin
    1283             :              * across a lengthy, unrelated operation.
    1284             :              */
    1285           4 :             if (BufferIsValid(vmbuffer))
    1286             :             {
    1287           4 :                 ReleaseBuffer(vmbuffer);
    1288           4 :                 vmbuffer = InvalidBuffer;
    1289             :             }
    1290             : 
    1291             :             /* Perform a round of index and heap vacuuming */
    1292           4 :             vacrel->consider_bypass_optimization = false;
    1293           4 :             lazy_vacuum(vacrel);
    1294             : 
    1295             :             /*
    1296             :              * Vacuum the Free Space Map to make newly-freed space visible on
    1297             :              * upper-level FSM pages. Note that blkno is the previously
    1298             :              * processed block.
    1299             :              */
    1300           4 :             FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
    1301             :                                     blkno + 1);
    1302           4 :             next_fsm_block_to_vacuum = blkno;
    1303             : 
    1304             :             /* Report that we are once again scanning the heap */
    1305           4 :             pgstat_progress_update_param(PROGRESS_VACUUM_PHASE,
    1306             :                                          PROGRESS_VACUUM_PHASE_SCAN_HEAP);
    1307             :         }
    1308             : 
    1309     1116646 :         buf = read_stream_next_buffer(stream, &per_buffer_data);
    1310             : 
    1311             :         /* The relation is exhausted. */
    1312     1116646 :         if (!BufferIsValid(buf))
    1313      238900 :             break;
    1314             : 
    1315      877746 :         blk_info = *((uint8 *) per_buffer_data);
    1316      877746 :         CheckBufferIsPinnedOnce(buf);
    1317      877746 :         page = BufferGetPage(buf);
    1318      877746 :         blkno = BufferGetBlockNumber(buf);
    1319             : 
    1320      877746 :         vacrel->scanned_pages++;
    1321      877746 :         if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
    1322           0 :             vacrel->eager_scanned_pages++;
    1323             : 
    1324             :         /* Report as block scanned, update error traceback information */
    1325      877746 :         pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
    1326      877746 :         update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
    1327             :                                  blkno, InvalidOffsetNumber);
    1328             : 
    1329             :         /*
    1330             :          * Pin the visibility map page in case we need to mark the page
    1331             :          * all-visible.  In most cases this will be very cheap, because we'll
    1332             :          * already have the correct page pinned anyway.
    1333             :          */
    1334      877746 :         visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
    1335             : 
    1336             :         /*
    1337             :          * We need a buffer cleanup lock to prune HOT chains and defragment
    1338             :          * the page in lazy_scan_prune.  But when it's not possible to acquire
    1339             :          * a cleanup lock right away, we may be able to settle for reduced
    1340             :          * processing using lazy_scan_noprune.
    1341             :          */
    1342      877746 :         got_cleanup_lock = ConditionalLockBufferForCleanup(buf);
    1343             : 
    1344      877746 :         if (!got_cleanup_lock)
    1345         408 :             LockBuffer(buf, BUFFER_LOCK_SHARE);
    1346             : 
    1347             :         /* Check for new or empty pages before lazy_scan_[no]prune call */
    1348      877746 :         if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock,
    1349      877746 :                                    vmbuffer))
    1350             :         {
    1351             :             /* Processed as new/empty page (lock and pin released) */
    1352        1224 :             continue;
    1353             :         }
    1354             : 
    1355             :         /*
    1356             :          * If we didn't get the cleanup lock, we can still collect LP_DEAD
    1357             :          * items in the dead_items area for later vacuuming, count live and
    1358             :          * recently dead tuples for vacuum logging, and determine if this
    1359             :          * block could later be truncated. If we encounter any xid/mxids that
    1360             :          * require advancing the relfrozenxid/relminxid, we'll have to wait
    1361             :          * for a cleanup lock and call lazy_scan_prune().
    1362             :          */
    1363      876522 :         if (!got_cleanup_lock &&
    1364         408 :             !lazy_scan_noprune(vacrel, buf, blkno, page, &has_lpdead_items))
    1365             :         {
    1366             :             /*
    1367             :              * lazy_scan_noprune could not do all required processing.  Wait
    1368             :              * for a cleanup lock, and call lazy_scan_prune in the usual way.
    1369             :              */
    1370             :             Assert(vacrel->aggressive);
    1371         166 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
    1372         166 :             LockBufferForCleanup(buf);
    1373         166 :             got_cleanup_lock = true;
    1374             :         }
    1375             : 
    1376             :         /*
    1377             :          * If we have a cleanup lock, we must now prune, freeze, and count
    1378             :          * tuples. We may have acquired the cleanup lock originally, or we may
    1379             :          * have gone back and acquired it after lazy_scan_noprune() returned
    1380             :          * false. Either way, the page hasn't been processed yet.
    1381             :          *
    1382             :          * Like lazy_scan_noprune(), lazy_scan_prune() will count
    1383             :          * recently_dead_tuples and live tuples for vacuum logging, determine
    1384             :          * if the block can later be truncated, and accumulate the details of
    1385             :          * remaining LP_DEAD line pointers on the page into dead_items. These
    1386             :          * dead items include those pruned by lazy_scan_prune() as well as
    1387             :          * line pointers previously marked LP_DEAD.
    1388             :          */
    1389      876522 :         if (got_cleanup_lock)
    1390      876280 :             lazy_scan_prune(vacrel, buf, blkno, page,
    1391             :                             vmbuffer,
    1392      876280 :                             blk_info & VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM,
    1393             :                             &has_lpdead_items, &vm_page_frozen);
    1394             : 
    1395             :         /*
    1396             :          * Count an eagerly scanned page as a failure or a success.
    1397             :          *
    1398             :          * Only lazy_scan_prune() freezes pages, so if we didn't get the
    1399             :          * cleanup lock, we won't have frozen the page. However, we only count
    1400             :          * pages that were too new to require freezing as eager freeze
    1401             :          * failures.
    1402             :          *
    1403             :          * We could gather more information from lazy_scan_noprune() about
    1404             :          * whether or not there were tuples with XIDs or MXIDs older than the
    1405             :          * FreezeLimit or MultiXactCutoff. However, for simplicity, we simply
    1406             :          * exclude pages skipped due to cleanup lock contention from eager
    1407             :          * freeze algorithm caps.
    1408             :          */
    1409      876522 :         if (got_cleanup_lock &&
    1410      876280 :             (blk_info & VAC_BLK_WAS_EAGER_SCANNED))
    1411             :         {
    1412             :             /* Aggressive vacuums do not eager scan. */
    1413             :             Assert(!vacrel->aggressive);
    1414             : 
    1415           0 :             if (vm_page_frozen)
    1416             :             {
    1417           0 :                 if (vacrel->eager_scan_remaining_successes > 0)
    1418           0 :                     vacrel->eager_scan_remaining_successes--;
    1419             : 
    1420           0 :                 if (vacrel->eager_scan_remaining_successes == 0)
    1421             :                 {
    1422             :                     /*
    1423             :                      * Report only once that we disabled eager scanning. We
    1424             :                      * may eagerly read ahead blocks in excess of the success
    1425             :                      * or failure caps before attempting to freeze them, so we
    1426             :                      * could reach here even after disabling additional eager
    1427             :                      * scanning.
    1428             :                      */
    1429           0 :                     if (vacrel->eager_scan_max_fails_per_region > 0)
    1430           0 :                         ereport(vacrel->verbose ? INFO : DEBUG2,
    1431             :                                 (errmsg("disabling eager scanning after freezing %u eagerly scanned blocks of \"%s.%s.%s\"",
    1432             :                                         orig_eager_scan_success_limit,
    1433             :                                         vacrel->dbname, vacrel->relnamespace,
    1434             :                                         vacrel->relname)));
    1435             : 
    1436             :                     /*
    1437             :                      * If we hit our success cap, permanently disable eager
    1438             :                      * scanning by setting the other eager scan management
    1439             :                      * fields to their disabled values.
    1440             :                      */
    1441           0 :                     vacrel->eager_scan_remaining_fails = 0;
    1442           0 :                     vacrel->next_eager_scan_region_start = InvalidBlockNumber;
    1443           0 :                     vacrel->eager_scan_max_fails_per_region = 0;
    1444             :                 }
    1445             :             }
    1446           0 :             else if (vacrel->eager_scan_remaining_fails > 0)
    1447           0 :                 vacrel->eager_scan_remaining_fails--;
    1448             :         }
    1449             : 
    1450             :         /*
    1451             :          * Now drop the buffer lock and, potentially, update the FSM.
    1452             :          *
    1453             :          * Our goal is to update the freespace map the last time we touch the
    1454             :          * page. If we'll process a block in the second pass, we may free up
    1455             :          * additional space on the page, so it is better to update the FSM
    1456             :          * after the second pass. If the relation has no indexes, or if index
    1457             :          * vacuuming is disabled, there will be no second heap pass; if this
    1458             :          * particular page has no dead items, the second heap pass will not
    1459             :          * touch this page. So, in those cases, update the FSM now.
    1460             :          *
    1461             :          * Note: In corner cases, it's possible to miss updating the FSM
    1462             :          * entirely. If index vacuuming is currently enabled, we'll skip the
    1463             :          * FSM update now. But if failsafe mode is later activated, or there
    1464             :          * are so few dead tuples that index vacuuming is bypassed, there will
    1465             :          * also be no opportunity to update the FSM later, because we'll never
    1466             :          * revisit this page. Since updating the FSM is desirable but not
    1467             :          * absolutely required, that's OK.
    1468             :          */
    1469      876522 :         if (vacrel->nindexes == 0
    1470      842356 :             || !vacrel->do_index_vacuuming
    1471      638188 :             || !has_lpdead_items)
    1472      851292 :         {
    1473      851292 :             Size        freespace = PageGetHeapFreeSpace(page);
    1474             : 
    1475      851292 :             UnlockReleaseBuffer(buf);
    1476      851292 :             RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
    1477             : 
    1478             :             /*
    1479             :              * Periodically perform FSM vacuuming to make newly-freed space
    1480             :              * visible on upper FSM pages. This is done after vacuuming if the
    1481             :              * table has indexes. There will only be newly-freed space if we
    1482             :              * held the cleanup lock and lazy_scan_prune() was called.
    1483             :              */
    1484      851292 :             if (got_cleanup_lock && vacrel->nindexes == 0 && has_lpdead_items &&
    1485           0 :                 blkno - next_fsm_block_to_vacuum >= VACUUM_FSM_EVERY_PAGES)
    1486             :             {
    1487           0 :                 FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
    1488             :                                         blkno);
    1489           0 :                 next_fsm_block_to_vacuum = blkno;
    1490             :             }
    1491             :         }
    1492             :         else
    1493       25230 :             UnlockReleaseBuffer(buf);
    1494             :     }
    1495             : 
    1496      238900 :     vacrel->blkno = InvalidBlockNumber;
    1497      238900 :     if (BufferIsValid(vmbuffer))
    1498       95760 :         ReleaseBuffer(vmbuffer);
    1499             : 
    1500             :     /*
    1501             :      * Report that everything is now scanned. We never skip scanning the last
    1502             :      * block in the relation, so we can pass rel_pages here.
    1503             :      */
    1504      238900 :     pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED,
    1505             :                                  rel_pages);
    1506             : 
    1507             :     /* now we can compute the new value for pg_class.reltuples */
    1508      477800 :     vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
    1509             :                                                      vacrel->scanned_pages,
    1510      238900 :                                                      vacrel->live_tuples);
    1511             : 
    1512             :     /*
    1513             :      * Also compute the total number of surviving heap entries.  In the
    1514             :      * (unlikely) scenario that new_live_tuples is -1, take it as zero.
    1515             :      */
    1516      238900 :     vacrel->new_rel_tuples =
    1517      238900 :         Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
    1518      238900 :         vacrel->missed_dead_tuples;
    1519             : 
    1520      238900 :     read_stream_end(stream);
    1521             : 
    1522             :     /*
    1523             :      * Do index vacuuming (call each index's ambulkdelete routine), then do
    1524             :      * related heap vacuuming
    1525             :      */
    1526      238900 :     if (vacrel->dead_items_info->num_items > 0)
    1527        1290 :         lazy_vacuum(vacrel);
    1528             : 
    1529             :     /*
    1530             :      * Vacuum the remainder of the Free Space Map.  We must do this whether or
    1531             :      * not there were indexes, and whether or not we bypassed index vacuuming.
    1532             :      * We can pass rel_pages here because we never skip scanning the last
    1533             :      * block of the relation.
    1534             :      */
    1535      238900 :     if (rel_pages > next_fsm_block_to_vacuum)
    1536       95760 :         FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
    1537             : 
    1538             :     /* report all blocks vacuumed */
    1539      238900 :     pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
    1540             : 
    1541             :     /* Do final index cleanup (call each index's amvacuumcleanup routine) */
    1542      238900 :     if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
    1543      167132 :         lazy_cleanup_all_indexes(vacrel);
    1544      238900 : }
    1545             : 
    1546             : /*
    1547             :  *  heap_vac_scan_next_block() -- read stream callback to get the next block
    1548             :  *  for vacuum to process
    1549             :  *
    1550             :  * Every time lazy_scan_heap() needs a new block to process during its first
    1551             :  * phase, it invokes read_stream_next_buffer() with a stream set up to call
    1552             :  * heap_vac_scan_next_block() to get the next block.
    1553             :  *
    1554             :  * heap_vac_scan_next_block() uses the visibility map, vacuum options, and
    1555             :  * various thresholds to skip blocks which do not need to be processed and
    1556             :  * returns the next block to process or InvalidBlockNumber if there are no
    1557             :  * remaining blocks.
    1558             :  *
    1559             :  * The visibility status of the next block to process and whether or not it
    1560             :  * was eager scanned is set in the per_buffer_data.
    1561             :  *
    1562             :  * callback_private_data contains a reference to the LVRelState, passed to the
    1563             :  * read stream API during stream setup. The LVRelState is an in/out parameter
    1564             :  * here (locally named `vacrel`). Vacuum options and information about the
    1565             :  * relation are read from it. vacrel->skippedallvis is set if we skip a block
    1566             :  * that's all-visible but not all-frozen (to ensure that we don't update
    1567             :  * relfrozenxid in that case). vacrel also holds information about the next
    1568             :  * unskippable block -- as bookkeeping for this function.
    1569             :  */
    1570             : static BlockNumber
    1571     1116646 : heap_vac_scan_next_block(ReadStream *stream,
    1572             :                          void *callback_private_data,
    1573             :                          void *per_buffer_data)
    1574             : {
    1575             :     BlockNumber next_block;
    1576     1116646 :     LVRelState *vacrel = callback_private_data;
    1577     1116646 :     uint8       blk_info = 0;
    1578             : 
    1579             :     /* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
    1580     1116646 :     next_block = vacrel->current_block + 1;
    1581             : 
    1582             :     /* Have we reached the end of the relation? */
    1583     1116646 :     if (next_block >= vacrel->rel_pages)
    1584             :     {
    1585      238900 :         if (BufferIsValid(vacrel->next_unskippable_vmbuffer))
    1586             :         {
    1587       92858 :             ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
    1588       92858 :             vacrel->next_unskippable_vmbuffer = InvalidBuffer;
    1589             :         }
    1590      238900 :         return InvalidBlockNumber;
    1591             :     }
    1592             : 
    1593             :     /*
    1594             :      * We must be in one of the three following states:
    1595             :      */
    1596      877746 :     if (next_block > vacrel->next_unskippable_block ||
    1597      387182 :         vacrel->next_unskippable_block == InvalidBlockNumber)
    1598             :     {
    1599             :         /*
    1600             :          * 1. We have just processed an unskippable block (or we're at the
    1601             :          * beginning of the scan).  Find the next unskippable block using the
    1602             :          * visibility map.
    1603             :          */
    1604             :         bool        skipsallvis;
    1605             : 
    1606      586324 :         find_next_unskippable_block(vacrel, &skipsallvis);
    1607             : 
    1608             :         /*
    1609             :          * We now know the next block that we must process.  It can be the
    1610             :          * next block after the one we just processed, or something further
    1611             :          * ahead.  If it's further ahead, we can jump to it, but we choose to
    1612             :          * do so only if we can skip at least SKIP_PAGES_THRESHOLD consecutive
    1613             :          * pages.  Since we're reading sequentially, the OS should be doing
    1614             :          * readahead for us, so there's no gain in skipping a page now and
    1615             :          * then.  Skipping such a range might even discourage sequential
    1616             :          * detection.
    1617             :          *
    1618             :          * This test also enables more frequent relfrozenxid advancement
    1619             :          * during non-aggressive VACUUMs.  If the range has any all-visible
    1620             :          * pages then skipping makes updating relfrozenxid unsafe, which is a
    1621             :          * real downside.
    1622             :          */
    1623      586324 :         if (vacrel->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
    1624             :         {
    1625        8530 :             next_block = vacrel->next_unskippable_block;
    1626        8530 :             if (skipsallvis)
    1627          64 :                 vacrel->skippedallvis = true;
    1628             :         }
    1629             :     }
    1630             : 
    1631             :     /* Now we must be in one of the two remaining states: */
    1632      877746 :     if (next_block < vacrel->next_unskippable_block)
    1633             :     {
    1634             :         /*
    1635             :          * 2. We are processing a range of blocks that we could have skipped
    1636             :          * but chose not to.  We know that they are all-visible in the VM,
    1637             :          * otherwise they would've been unskippable.
    1638             :          */
    1639      291422 :         vacrel->current_block = next_block;
    1640      291422 :         blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
    1641      291422 :         *((uint8 *) per_buffer_data) = blk_info;
    1642      291422 :         return vacrel->current_block;
    1643             :     }
    1644             :     else
    1645             :     {
    1646             :         /*
    1647             :          * 3. We reached the next unskippable block.  Process it.  On next
    1648             :          * iteration, we will be back in state 1.
    1649             :          */
    1650             :         Assert(next_block == vacrel->next_unskippable_block);
    1651             : 
    1652      586324 :         vacrel->current_block = next_block;
    1653      586324 :         if (vacrel->next_unskippable_allvis)
    1654       87646 :             blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
    1655      586324 :         if (vacrel->next_unskippable_eager_scanned)
    1656           0 :             blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
    1657      586324 :         *((uint8 *) per_buffer_data) = blk_info;
    1658      586324 :         return vacrel->current_block;
    1659             :     }
    1660             : }
    1661             : 
    1662             : /*
    1663             :  * Find the next unskippable block in a vacuum scan using the visibility map.
    1664             :  * The next unskippable block and its visibility information is updated in
    1665             :  * vacrel.
    1666             :  *
    1667             :  * Note: our opinion of which blocks can be skipped can go stale immediately.
    1668             :  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
    1669             :  * was concurrently cleared, though.  All that matters is that caller scan all
    1670             :  * pages whose tuples might contain XIDs < OldestXmin, or MXIDs < OldestMxact.
    1671             :  * (Actually, non-aggressive VACUUMs can choose to skip all-visible pages with
    1672             :  * older XIDs/MXIDs.  The *skippedallvis flag will be set here when the choice
    1673             :  * to skip such a range is actually made, making everything safe.)
    1674             :  */
    1675             : static void
    1676      586324 : find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis)
    1677             : {
    1678      586324 :     BlockNumber rel_pages = vacrel->rel_pages;
    1679      586324 :     BlockNumber next_unskippable_block = vacrel->next_unskippable_block + 1;
    1680      586324 :     Buffer      next_unskippable_vmbuffer = vacrel->next_unskippable_vmbuffer;
    1681      586324 :     bool        next_unskippable_eager_scanned = false;
    1682             :     bool        next_unskippable_allvis;
    1683             : 
    1684      586324 :     *skipsallvis = false;
    1685             : 
    1686      889920 :     for (;; next_unskippable_block++)
    1687      889920 :     {
    1688     1476244 :         uint8       mapbits = visibilitymap_get_status(vacrel->rel,
    1689             :                                                        next_unskippable_block,
    1690             :                                                        &next_unskippable_vmbuffer);
    1691             : 
    1692     1476244 :         next_unskippable_allvis = (mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0;
    1693             : 
    1694             :         /*
    1695             :          * At the start of each eager scan region, normal vacuums with eager
    1696             :          * scanning enabled reset the failure counter, allowing vacuum to
    1697             :          * resume eager scanning if it had been suspended in the previous
    1698             :          * region.
    1699             :          */
    1700     1476244 :         if (next_unskippable_block >= vacrel->next_eager_scan_region_start)
    1701             :         {
    1702           0 :             vacrel->eager_scan_remaining_fails =
    1703           0 :                 vacrel->eager_scan_max_fails_per_region;
    1704           0 :             vacrel->next_eager_scan_region_start += EAGER_SCAN_REGION_SIZE;
    1705             :         }
    1706             : 
    1707             :         /*
    1708             :          * A block is unskippable if it is not all visible according to the
    1709             :          * visibility map.
    1710             :          */
    1711     1476244 :         if (!next_unskippable_allvis)
    1712             :         {
    1713             :             Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
    1714      498678 :             break;
    1715             :         }
    1716             : 
    1717             :         /*
    1718             :          * Caller must scan the last page to determine whether it has tuples
    1719             :          * (caller must have the opportunity to set vacrel->nonempty_pages).
    1720             :          * This rule avoids having lazy_truncate_heap() take access-exclusive
    1721             :          * lock on rel to attempt a truncation that fails anyway, just because
    1722             :          * there are tuples on the last page (it is likely that there will be
    1723             :          * tuples on other nearby pages as well, but those can be skipped).
    1724             :          *
    1725             :          * Implement this by always treating the last block as unsafe to skip.
    1726             :          */
    1727      977566 :         if (next_unskippable_block == rel_pages - 1)
    1728       86838 :             break;
    1729             : 
    1730             :         /* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
    1731      890728 :         if (!vacrel->skipwithvm)
    1732         808 :             break;
    1733             : 
    1734             :         /*
    1735             :          * All-frozen pages cannot contain XIDs < OldestXmin (XIDs that aren't
    1736             :          * already frozen by now), so this page can be skipped.
    1737             :          */
    1738      889920 :         if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
    1739      884562 :             continue;
    1740             : 
    1741             :         /*
    1742             :          * Aggressive vacuums cannot skip any all-visible pages that are not
    1743             :          * also all-frozen.
    1744             :          */
    1745        5358 :         if (vacrel->aggressive)
    1746           0 :             break;
    1747             : 
    1748             :         /*
    1749             :          * Normal vacuums with eager scanning enabled only skip all-visible
    1750             :          * but not all-frozen pages if they have hit the failure limit for the
    1751             :          * current eager scan region.
    1752             :          */
    1753        5358 :         if (vacrel->eager_scan_remaining_fails > 0)
    1754             :         {
    1755           0 :             next_unskippable_eager_scanned = true;
    1756           0 :             break;
    1757             :         }
    1758             : 
    1759             :         /*
    1760             :          * All-visible blocks are safe to skip in a normal vacuum. But
    1761             :          * remember that the final range contains such a block for later.
    1762             :          */
    1763        5358 :         *skipsallvis = true;
    1764             :     }
    1765             : 
    1766             :     /* write the local variables back to vacrel */
    1767      586324 :     vacrel->next_unskippable_block = next_unskippable_block;
    1768      586324 :     vacrel->next_unskippable_allvis = next_unskippable_allvis;
    1769      586324 :     vacrel->next_unskippable_eager_scanned = next_unskippable_eager_scanned;
    1770      586324 :     vacrel->next_unskippable_vmbuffer = next_unskippable_vmbuffer;
    1771      586324 : }
    1772             : 
    1773             : /*
    1774             :  *  lazy_scan_new_or_empty() -- lazy_scan_heap() new/empty page handling.
    1775             :  *
    1776             :  * Must call here to handle both new and empty pages before calling
    1777             :  * lazy_scan_prune or lazy_scan_noprune, since they're not prepared to deal
    1778             :  * with new or empty pages.
    1779             :  *
    1780             :  * It's necessary to consider new pages as a special case, since the rules for
    1781             :  * maintaining the visibility map and FSM with empty pages are a little
    1782             :  * different (though new pages can be truncated away during rel truncation).
    1783             :  *
    1784             :  * Empty pages are not really a special case -- they're just heap pages that
    1785             :  * have no allocated tuples (including even LP_UNUSED items).  You might
    1786             :  * wonder why we need to handle them here all the same.  It's only necessary
    1787             :  * because of a corner-case involving a hard crash during heap relation
    1788             :  * extension.  If we ever make relation-extension crash safe, then it should
    1789             :  * no longer be necessary to deal with empty pages here (or new pages, for
    1790             :  * that matter).
    1791             :  *
    1792             :  * Caller must hold at least a shared lock.  We might need to escalate the
    1793             :  * lock in that case, so the type of lock caller holds needs to be specified
    1794             :  * using 'sharelock' argument.
    1795             :  *
    1796             :  * Returns false in common case where caller should go on to call
    1797             :  * lazy_scan_prune (or lazy_scan_noprune).  Otherwise returns true, indicating
    1798             :  * that lazy_scan_heap is done processing the page, releasing lock on caller's
    1799             :  * behalf.
    1800             :  *
    1801             :  * No vm_page_frozen output parameter (like that passed to lazy_scan_prune())
    1802             :  * is passed here because neither empty nor new pages can be eagerly frozen.
    1803             :  * New pages are never frozen. Empty pages are always set frozen in the VM at
    1804             :  * the same time that they are set all-visible, and we don't eagerly scan
    1805             :  * frozen pages.
    1806             :  */
    1807             : static bool
    1808      877746 : lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
    1809             :                        Page page, bool sharelock, Buffer vmbuffer)
    1810             : {
    1811             :     Size        freespace;
    1812             : 
    1813      877746 :     if (PageIsNew(page))
    1814             :     {
    1815             :         /*
    1816             :          * All-zeroes pages can be left over if either a backend extends the
    1817             :          * relation by a single page, but crashes before the newly initialized
    1818             :          * page has been written out, or when bulk-extending the relation
    1819             :          * (which creates a number of empty pages at the tail end of the
    1820             :          * relation), and then enters them into the FSM.
    1821             :          *
    1822             :          * Note we do not enter the page into the visibilitymap. That has the
    1823             :          * downside that we repeatedly visit this page in subsequent vacuums,
    1824             :          * but otherwise we'll never discover the space on a promoted standby.
    1825             :          * The harm of repeated checking ought to normally not be too bad. The
    1826             :          * space usually should be used at some point, otherwise there
    1827             :          * wouldn't be any regular vacuums.
    1828             :          *
    1829             :          * Make sure these pages are in the FSM, to ensure they can be reused.
    1830             :          * Do that by testing if there's any space recorded for the page. If
    1831             :          * not, enter it. We do so after releasing the lock on the heap page,
    1832             :          * the FSM is approximate, after all.
    1833             :          */
    1834        1170 :         UnlockReleaseBuffer(buf);
    1835             : 
    1836        1170 :         if (GetRecordedFreeSpace(vacrel->rel, blkno) == 0)
    1837             :         {
    1838         858 :             freespace = BLCKSZ - SizeOfPageHeaderData;
    1839             : 
    1840         858 :             RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
    1841             :         }
    1842             : 
    1843        1170 :         return true;
    1844             :     }
    1845             : 
    1846      876576 :     if (PageIsEmpty(page))
    1847             :     {
    1848             :         /*
    1849             :          * It seems likely that caller will always be able to get a cleanup
    1850             :          * lock on an empty page.  But don't take any chances -- escalate to
    1851             :          * an exclusive lock (still don't need a cleanup lock, though).
    1852             :          */
    1853          54 :         if (sharelock)
    1854             :         {
    1855           0 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
    1856           0 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    1857             : 
    1858           0 :             if (!PageIsEmpty(page))
    1859             :             {
    1860             :                 /* page isn't new or empty -- keep lock and pin for now */
    1861           0 :                 return false;
    1862             :             }
    1863             :         }
    1864             :         else
    1865             :         {
    1866             :             /* Already have a full cleanup lock (which is more than enough) */
    1867             :         }
    1868             : 
    1869             :         /*
    1870             :          * Unlike new pages, empty pages are always set all-visible and
    1871             :          * all-frozen.
    1872             :          */
    1873          54 :         if (!PageIsAllVisible(page))
    1874             :         {
    1875           0 :             START_CRIT_SECTION();
    1876             : 
    1877             :             /* mark buffer dirty before writing a WAL record */
    1878           0 :             MarkBufferDirty(buf);
    1879             : 
    1880             :             /*
    1881             :              * It's possible that another backend has extended the heap,
    1882             :              * initialized the page, and then failed to WAL-log the page due
    1883             :              * to an ERROR.  Since heap extension is not WAL-logged, recovery
    1884             :              * might try to replay our record setting the page all-visible and
    1885             :              * find that the page isn't initialized, which will cause a PANIC.
    1886             :              * To prevent that, check whether the page has been previously
    1887             :              * WAL-logged, and if not, do that now.
    1888             :              */
    1889           0 :             if (RelationNeedsWAL(vacrel->rel) &&
    1890           0 :                 PageGetLSN(page) == InvalidXLogRecPtr)
    1891           0 :                 log_newpage_buffer(buf, true);
    1892             : 
    1893           0 :             PageSetAllVisible(page);
    1894           0 :             visibilitymap_set(vacrel->rel, blkno, buf,
    1895             :                               InvalidXLogRecPtr,
    1896             :                               vmbuffer, InvalidTransactionId,
    1897             :                               VISIBILITYMAP_ALL_VISIBLE |
    1898             :                               VISIBILITYMAP_ALL_FROZEN);
    1899           0 :             END_CRIT_SECTION();
    1900             : 
    1901             :             /* Count the newly all-frozen pages for logging */
    1902           0 :             vacrel->vm_new_visible_pages++;
    1903           0 :             vacrel->vm_new_visible_frozen_pages++;
    1904             :         }
    1905             : 
    1906          54 :         freespace = PageGetHeapFreeSpace(page);
    1907          54 :         UnlockReleaseBuffer(buf);
    1908          54 :         RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
    1909          54 :         return true;
    1910             :     }
    1911             : 
    1912             :     /* page isn't new or empty -- keep lock and pin */
    1913      876522 :     return false;
    1914             : }
    1915             : 
    1916             : /* qsort comparator for sorting OffsetNumbers */
    1917             : static int
    1918     5282672 : cmpOffsetNumbers(const void *a, const void *b)
    1919             : {
    1920     5282672 :     return pg_cmp_u16(*(const OffsetNumber *) a, *(const OffsetNumber *) b);
    1921             : }
    1922             : 
    1923             : /*
    1924             :  *  lazy_scan_prune() -- lazy_scan_heap() pruning and freezing.
    1925             :  *
    1926             :  * Caller must hold pin and buffer cleanup lock on the buffer.
    1927             :  *
    1928             :  * vmbuffer is the buffer containing the VM block with visibility information
    1929             :  * for the heap block, blkno. all_visible_according_to_vm is the saved
    1930             :  * visibility status of the heap block looked up earlier by the caller. We
    1931             :  * won't rely entirely on this status, as it may be out of date.
    1932             :  *
    1933             :  * *has_lpdead_items is set to true or false depending on whether, upon return
    1934             :  * from this function, any LP_DEAD items are still present on the page.
    1935             :  *
    1936             :  * *vm_page_frozen is set to true if the page is newly set all-frozen in the
    1937             :  * VM. The caller currently only uses this for determining whether an eagerly
    1938             :  * scanned page was successfully set all-frozen.
    1939             :  */
    1940             : static void
    1941      876280 : lazy_scan_prune(LVRelState *vacrel,
    1942             :                 Buffer buf,
    1943             :                 BlockNumber blkno,
    1944             :                 Page page,
    1945             :                 Buffer vmbuffer,
    1946             :                 bool all_visible_according_to_vm,
    1947             :                 bool *has_lpdead_items,
    1948             :                 bool *vm_page_frozen)
    1949             : {
    1950      876280 :     Relation    rel = vacrel->rel;
    1951             :     PruneFreezeResult presult;
    1952      876280 :     int         prune_options = 0;
    1953             : 
    1954             :     Assert(BufferGetBlockNumber(buf) == blkno);
    1955             : 
    1956             :     /*
    1957             :      * Prune all HOT-update chains and potentially freeze tuples on this page.
    1958             :      *
    1959             :      * If the relation has no indexes, we can immediately mark would-be dead
    1960             :      * items LP_UNUSED.
    1961             :      *
    1962             :      * The number of tuples removed from the page is returned in
    1963             :      * presult.ndeleted.  It should not be confused with presult.lpdead_items;
    1964             :      * presult.lpdead_items's final value can be thought of as the number of
    1965             :      * tuples that were deleted from indexes.
    1966             :      *
    1967             :      * We will update the VM after collecting LP_DEAD items and freezing
    1968             :      * tuples. Pruning will have determined whether or not the page is
    1969             :      * all-visible.
    1970             :      */
    1971      876280 :     prune_options = HEAP_PAGE_PRUNE_FREEZE;
    1972      876280 :     if (vacrel->nindexes == 0)
    1973       34166 :         prune_options |= HEAP_PAGE_PRUNE_MARK_UNUSED_NOW;
    1974             : 
    1975      876280 :     heap_page_prune_and_freeze(rel, buf, vacrel->vistest, prune_options,
    1976             :                                &vacrel->cutoffs, &presult, PRUNE_VACUUM_SCAN,
    1977             :                                &vacrel->offnum,
    1978             :                                &vacrel->NewRelfrozenXid, &vacrel->NewRelminMxid);
    1979             : 
    1980             :     Assert(MultiXactIdIsValid(vacrel->NewRelminMxid));
    1981             :     Assert(TransactionIdIsValid(vacrel->NewRelfrozenXid));
    1982             : 
    1983      876280 :     if (presult.nfrozen > 0)
    1984             :     {
    1985             :         /*
    1986             :          * We don't increment the new_frozen_tuple_pages instrumentation
    1987             :          * counter when nfrozen == 0, since it only counts pages with newly
    1988             :          * frozen tuples (don't confuse that with pages newly set all-frozen
    1989             :          * in VM).
    1990             :          */
    1991       45070 :         vacrel->new_frozen_tuple_pages++;
    1992             :     }
    1993             : 
    1994             :     /*
    1995             :      * VACUUM will call heap_page_is_all_visible() during the second pass over
    1996             :      * the heap to determine all_visible and all_frozen for the page -- this
    1997             :      * is a specialized version of the logic from this function.  Now that
    1998             :      * we've finished pruning and freezing, make sure that we're in total
    1999             :      * agreement with heap_page_is_all_visible() using an assertion.
    2000             :      */
    2001             : #ifdef USE_ASSERT_CHECKING
    2002             :     /* Note that all_frozen value does not matter when !all_visible */
    2003             :     if (presult.all_visible)
    2004             :     {
    2005             :         TransactionId debug_cutoff;
    2006             :         bool        debug_all_frozen;
    2007             : 
    2008             :         Assert(presult.lpdead_items == 0);
    2009             : 
    2010             :         if (!heap_page_is_all_visible(vacrel, buf,
    2011             :                                       &debug_cutoff, &debug_all_frozen))
    2012             :             Assert(false);
    2013             : 
    2014             :         Assert(presult.all_frozen == debug_all_frozen);
    2015             : 
    2016             :         Assert(!TransactionIdIsValid(debug_cutoff) ||
    2017             :                debug_cutoff == presult.vm_conflict_horizon);
    2018             :     }
    2019             : #endif
    2020             : 
    2021             :     /*
    2022             :      * Now save details of the LP_DEAD items from the page in vacrel
    2023             :      */
    2024      876280 :     if (presult.lpdead_items > 0)
    2025             :     {
    2026       29852 :         vacrel->lpdead_item_pages++;
    2027             : 
    2028             :         /*
    2029             :          * deadoffsets are collected incrementally in
    2030             :          * heap_page_prune_and_freeze() as each dead line pointer is recorded,
    2031             :          * with an indeterminate order, but dead_items_add requires them to be
    2032             :          * sorted.
    2033             :          */
    2034       29852 :         qsort(presult.deadoffsets, presult.lpdead_items, sizeof(OffsetNumber),
    2035             :               cmpOffsetNumbers);
    2036             : 
    2037       29852 :         dead_items_add(vacrel, blkno, presult.deadoffsets, presult.lpdead_items);
    2038             :     }
    2039             : 
    2040             :     /* Finally, add page-local counts to whole-VACUUM counts */
    2041      876280 :     vacrel->tuples_deleted += presult.ndeleted;
    2042      876280 :     vacrel->tuples_frozen += presult.nfrozen;
    2043      876280 :     vacrel->lpdead_items += presult.lpdead_items;
    2044      876280 :     vacrel->live_tuples += presult.live_tuples;
    2045      876280 :     vacrel->recently_dead_tuples += presult.recently_dead_tuples;
    2046             : 
    2047             :     /* Can't truncate this page */
    2048      876280 :     if (presult.hastup)
    2049      861924 :         vacrel->nonempty_pages = blkno + 1;
    2050             : 
    2051             :     /* Did we find LP_DEAD items? */
    2052      876280 :     *has_lpdead_items = (presult.lpdead_items > 0);
    2053             : 
    2054             :     Assert(!presult.all_visible || !(*has_lpdead_items));
    2055             : 
    2056             :     /*
    2057             :      * Handle setting visibility map bit based on information from the VM (as
    2058             :      * of last heap_vac_scan_next_block() call), and from all_visible and
    2059             :      * all_frozen variables
    2060             :      */
    2061      876280 :     if (!all_visible_according_to_vm && presult.all_visible)
    2062       69974 :     {
    2063             :         uint8       old_vmbits;
    2064       69974 :         uint8       flags = VISIBILITYMAP_ALL_VISIBLE;
    2065             : 
    2066       69974 :         if (presult.all_frozen)
    2067             :         {
    2068             :             Assert(!TransactionIdIsValid(presult.vm_conflict_horizon));
    2069       52530 :             flags |= VISIBILITYMAP_ALL_FROZEN;
    2070             :         }
    2071             : 
    2072             :         /*
    2073             :          * It should never be the case that the visibility map page is set
    2074             :          * while the page-level bit is clear, but the reverse is allowed (if
    2075             :          * checksums are not enabled).  Regardless, set both bits so that we
    2076             :          * get back in sync.
    2077             :          *
    2078             :          * NB: If the heap page is all-visible but the VM bit is not set, we
    2079             :          * don't need to dirty the heap page.  However, if checksums are
    2080             :          * enabled, we do need to make sure that the heap page is dirtied
    2081             :          * before passing it to visibilitymap_set(), because it may be logged.
    2082             :          * Given that this situation should only happen in rare cases after a
    2083             :          * crash, it is not worth optimizing.
    2084             :          */
    2085       69974 :         PageSetAllVisible(page);
    2086       69974 :         MarkBufferDirty(buf);
    2087       69974 :         old_vmbits = visibilitymap_set(vacrel->rel, blkno, buf,
    2088             :                                        InvalidXLogRecPtr,
    2089             :                                        vmbuffer, presult.vm_conflict_horizon,
    2090             :                                        flags);
    2091             : 
    2092             :         /*
    2093             :          * If the page wasn't already set all-visible and/or all-frozen in the
    2094             :          * VM, count it as newly set for logging.
    2095             :          */
    2096       69974 :         if ((old_vmbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
    2097             :         {
    2098       69974 :             vacrel->vm_new_visible_pages++;
    2099       69974 :             if (presult.all_frozen)
    2100             :             {
    2101       52530 :                 vacrel->vm_new_visible_frozen_pages++;
    2102       52530 :                 *vm_page_frozen = true;
    2103             :             }
    2104             :         }
    2105           0 :         else if ((old_vmbits & VISIBILITYMAP_ALL_FROZEN) == 0 &&
    2106           0 :                  presult.all_frozen)
    2107             :         {
    2108           0 :             vacrel->vm_new_frozen_pages++;
    2109           0 :             *vm_page_frozen = true;
    2110             :         }
    2111             :     }
    2112             : 
    2113             :     /*
    2114             :      * As of PostgreSQL 9.2, the visibility map bit should never be set if the
    2115             :      * page-level bit is clear.  However, it's possible that the bit got
    2116             :      * cleared after heap_vac_scan_next_block() was called, so we must recheck
    2117             :      * with buffer lock before concluding that the VM is corrupt.
    2118             :      */
    2119      806306 :     else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
    2120           0 :              visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
    2121             :     {
    2122           0 :         elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
    2123             :              vacrel->relname, blkno);
    2124           0 :         visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
    2125             :                             VISIBILITYMAP_VALID_BITS);
    2126             :     }
    2127             : 
    2128             :     /*
    2129             :      * It's possible for the value returned by
    2130             :      * GetOldestNonRemovableTransactionId() to move backwards, so it's not
    2131             :      * wrong for us to see tuples that appear to not be visible to everyone
    2132             :      * yet, while PD_ALL_VISIBLE is already set. The real safe xmin value
    2133             :      * never moves backwards, but GetOldestNonRemovableTransactionId() is
    2134             :      * conservative and sometimes returns a value that's unnecessarily small,
    2135             :      * so if we see that contradiction it just means that the tuples that we
    2136             :      * think are not visible to everyone yet actually are, and the
    2137             :      * PD_ALL_VISIBLE flag is correct.
    2138             :      *
    2139             :      * There should never be LP_DEAD items on a page with PD_ALL_VISIBLE set,
    2140             :      * however.
    2141             :      */
    2142      806306 :     else if (presult.lpdead_items > 0 && PageIsAllVisible(page))
    2143             :     {
    2144           0 :         elog(WARNING, "page containing LP_DEAD items is marked as all-visible in relation \"%s\" page %u",
    2145             :              vacrel->relname, blkno);
    2146           0 :         PageClearAllVisible(page);
    2147           0 :         MarkBufferDirty(buf);
    2148           0 :         visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
    2149             :                             VISIBILITYMAP_VALID_BITS);
    2150             :     }
    2151             : 
    2152             :     /*
    2153             :      * If the all-visible page is all-frozen but not marked as such yet, mark
    2154             :      * it as all-frozen.  Note that all_frozen is only valid if all_visible is
    2155             :      * true, so we must check both all_visible and all_frozen.
    2156             :      */
    2157      806306 :     else if (all_visible_according_to_vm && presult.all_visible &&
    2158      378790 :              presult.all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
    2159             :     {
    2160             :         uint8       old_vmbits;
    2161             : 
    2162             :         /*
    2163             :          * Avoid relying on all_visible_according_to_vm as a proxy for the
    2164             :          * page-level PD_ALL_VISIBLE bit being set, since it might have become
    2165             :          * stale -- even when all_visible is set
    2166             :          */
    2167          44 :         if (!PageIsAllVisible(page))
    2168             :         {
    2169           0 :             PageSetAllVisible(page);
    2170           0 :             MarkBufferDirty(buf);
    2171             :         }
    2172             : 
    2173             :         /*
    2174             :          * Set the page all-frozen (and all-visible) in the VM.
    2175             :          *
    2176             :          * We can pass InvalidTransactionId as our cutoff_xid, since a
    2177             :          * snapshotConflictHorizon sufficient to make everything safe for REDO
    2178             :          * was logged when the page's tuples were frozen.
    2179             :          */
    2180             :         Assert(!TransactionIdIsValid(presult.vm_conflict_horizon));
    2181          44 :         old_vmbits = visibilitymap_set(vacrel->rel, blkno, buf,
    2182             :                                        InvalidXLogRecPtr,
    2183             :                                        vmbuffer, InvalidTransactionId,
    2184             :                                        VISIBILITYMAP_ALL_VISIBLE |
    2185             :                                        VISIBILITYMAP_ALL_FROZEN);
    2186             : 
    2187             :         /*
    2188             :          * The page was likely already set all-visible in the VM. However,
    2189             :          * there is a small chance that it was modified sometime between
    2190             :          * setting all_visible_according_to_vm and checking the visibility
    2191             :          * during pruning. Check the return value of old_vmbits anyway to
    2192             :          * ensure the visibility map counters used for logging are accurate.
    2193             :          */
    2194          44 :         if ((old_vmbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
    2195             :         {
    2196           0 :             vacrel->vm_new_visible_pages++;
    2197           0 :             vacrel->vm_new_visible_frozen_pages++;
    2198           0 :             *vm_page_frozen = true;
    2199             :         }
    2200             : 
    2201             :         /*
    2202             :          * We already checked that the page was not set all-frozen in the VM
    2203             :          * above, so we don't need to test the value of old_vmbits.
    2204             :          */
    2205             :         else
    2206             :         {
    2207          44 :             vacrel->vm_new_frozen_pages++;
    2208          44 :             *vm_page_frozen = true;
    2209             :         }
    2210             :     }
    2211      876280 : }
    2212             : 
    2213             : /*
    2214             :  *  lazy_scan_noprune() -- lazy_scan_prune() without pruning or freezing
    2215             :  *
    2216             :  * Caller need only hold a pin and share lock on the buffer, unlike
    2217             :  * lazy_scan_prune, which requires a full cleanup lock.  While pruning isn't
    2218             :  * performed here, it's quite possible that an earlier opportunistic pruning
    2219             :  * operation left LP_DEAD items behind.  We'll at least collect any such items
    2220             :  * in dead_items for removal from indexes.
    2221             :  *
    2222             :  * For aggressive VACUUM callers, we may return false to indicate that a full
    2223             :  * cleanup lock is required for processing by lazy_scan_prune.  This is only
    2224             :  * necessary when the aggressive VACUUM needs to freeze some tuple XIDs from
    2225             :  * one or more tuples on the page.  We always return true for non-aggressive
    2226             :  * callers.
    2227             :  *
    2228             :  * If this function returns true, *has_lpdead_items gets set to true or false
    2229             :  * depending on whether, upon return from this function, any LP_DEAD items are
    2230             :  * present on the page. If this function returns false, *has_lpdead_items
    2231             :  * is not updated.
    2232             :  */
    2233             : static bool
    2234         408 : lazy_scan_noprune(LVRelState *vacrel,
    2235             :                   Buffer buf,
    2236             :                   BlockNumber blkno,
    2237             :                   Page page,
    2238             :                   bool *has_lpdead_items)
    2239             : {
    2240             :     OffsetNumber offnum,
    2241             :                 maxoff;
    2242             :     int         lpdead_items,
    2243             :                 live_tuples,
    2244             :                 recently_dead_tuples,
    2245             :                 missed_dead_tuples;
    2246             :     bool        hastup;
    2247             :     HeapTupleHeader tupleheader;
    2248         408 :     TransactionId NoFreezePageRelfrozenXid = vacrel->NewRelfrozenXid;
    2249         408 :     MultiXactId NoFreezePageRelminMxid = vacrel->NewRelminMxid;
    2250             :     OffsetNumber deadoffsets[MaxHeapTuplesPerPage];
    2251             : 
    2252             :     Assert(BufferGetBlockNumber(buf) == blkno);
    2253             : 
    2254         408 :     hastup = false;             /* for now */
    2255             : 
    2256         408 :     lpdead_items = 0;
    2257         408 :     live_tuples = 0;
    2258         408 :     recently_dead_tuples = 0;
    2259         408 :     missed_dead_tuples = 0;
    2260             : 
    2261         408 :     maxoff = PageGetMaxOffsetNumber(page);
    2262         408 :     for (offnum = FirstOffsetNumber;
    2263       12774 :          offnum <= maxoff;
    2264       12366 :          offnum = OffsetNumberNext(offnum))
    2265             :     {
    2266             :         ItemId      itemid;
    2267             :         HeapTupleData tuple;
    2268             : 
    2269       12532 :         vacrel->offnum = offnum;
    2270       12532 :         itemid = PageGetItemId(page, offnum);
    2271             : 
    2272       12532 :         if (!ItemIdIsUsed(itemid))
    2273        2538 :             continue;
    2274             : 
    2275       11122 :         if (ItemIdIsRedirected(itemid))
    2276             :         {
    2277        1128 :             hastup = true;
    2278        1128 :             continue;
    2279             :         }
    2280             : 
    2281        9994 :         if (ItemIdIsDead(itemid))
    2282             :         {
    2283             :             /*
    2284             :              * Deliberately don't set hastup=true here.  See same point in
    2285             :              * lazy_scan_prune for an explanation.
    2286             :              */
    2287           0 :             deadoffsets[lpdead_items++] = offnum;
    2288           0 :             continue;
    2289             :         }
    2290             : 
    2291        9994 :         hastup = true;          /* page prevents rel truncation */
    2292        9994 :         tupleheader = (HeapTupleHeader) PageGetItem(page, itemid);
    2293        9994 :         if (heap_tuple_should_freeze(tupleheader, &vacrel->cutoffs,
    2294             :                                      &NoFreezePageRelfrozenXid,
    2295             :                                      &NoFreezePageRelminMxid))
    2296             :         {
    2297             :             /* Tuple with XID < FreezeLimit (or MXID < MultiXactCutoff) */
    2298         294 :             if (vacrel->aggressive)
    2299             :             {
    2300             :                 /*
    2301             :                  * Aggressive VACUUMs must always be able to advance rel's
    2302             :                  * relfrozenxid to a value >= FreezeLimit (and be able to
    2303             :                  * advance rel's relminmxid to a value >= MultiXactCutoff).
    2304             :                  * The ongoing aggressive VACUUM won't be able to do that
    2305             :                  * unless it can freeze an XID (or MXID) from this tuple now.
    2306             :                  *
    2307             :                  * The only safe option is to have caller perform processing
    2308             :                  * of this page using lazy_scan_prune.  Caller might have to
    2309             :                  * wait a while for a cleanup lock, but it can't be helped.
    2310             :                  */
    2311         166 :                 vacrel->offnum = InvalidOffsetNumber;
    2312         166 :                 return false;
    2313             :             }
    2314             : 
    2315             :             /*
    2316             :              * Non-aggressive VACUUMs are under no obligation to advance
    2317             :              * relfrozenxid (even by one XID).  We can be much laxer here.
    2318             :              *
    2319             :              * Currently we always just accept an older final relfrozenxid
    2320             :              * and/or relminmxid value.  We never make caller wait or work a
    2321             :              * little harder, even when it likely makes sense to do so.
    2322             :              */
    2323             :         }
    2324             : 
    2325        9828 :         ItemPointerSet(&(tuple.t_self), blkno, offnum);
    2326        9828 :         tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
    2327        9828 :         tuple.t_len = ItemIdGetLength(itemid);
    2328        9828 :         tuple.t_tableOid = RelationGetRelid(vacrel->rel);
    2329             : 
    2330        9828 :         switch (HeapTupleSatisfiesVacuum(&tuple, vacrel->cutoffs.OldestXmin,
    2331             :                                          buf))
    2332             :         {
    2333        9820 :             case HEAPTUPLE_DELETE_IN_PROGRESS:
    2334             :             case HEAPTUPLE_LIVE:
    2335             : 
    2336             :                 /*
    2337             :                  * Count both cases as live, just like lazy_scan_prune
    2338             :                  */
    2339        9820 :                 live_tuples++;
    2340             : 
    2341        9820 :                 break;
    2342           4 :             case HEAPTUPLE_DEAD:
    2343             : 
    2344             :                 /*
    2345             :                  * There is some useful work for pruning to do, that won't be
    2346             :                  * done due to failure to get a cleanup lock.
    2347             :                  */
    2348           4 :                 missed_dead_tuples++;
    2349           4 :                 break;
    2350           4 :             case HEAPTUPLE_RECENTLY_DEAD:
    2351             : 
    2352             :                 /*
    2353             :                  * Count in recently_dead_tuples, just like lazy_scan_prune
    2354             :                  */
    2355           4 :                 recently_dead_tuples++;
    2356           4 :                 break;
    2357           0 :             case HEAPTUPLE_INSERT_IN_PROGRESS:
    2358             : 
    2359             :                 /*
    2360             :                  * Do not count these rows as live, just like lazy_scan_prune
    2361             :                  */
    2362           0 :                 break;
    2363           0 :             default:
    2364           0 :                 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
    2365             :                 break;
    2366             :         }
    2367             :     }
    2368             : 
    2369         242 :     vacrel->offnum = InvalidOffsetNumber;
    2370             : 
    2371             :     /*
    2372             :      * By here we know for sure that caller can put off freezing and pruning
    2373             :      * this particular page until the next VACUUM.  Remember its details now.
    2374             :      * (lazy_scan_prune expects a clean slate, so we have to do this last.)
    2375             :      */
    2376         242 :     vacrel->NewRelfrozenXid = NoFreezePageRelfrozenXid;
    2377         242 :     vacrel->NewRelminMxid = NoFreezePageRelminMxid;
    2378             : 
    2379             :     /* Save any LP_DEAD items found on the page in dead_items */
    2380         242 :     if (vacrel->nindexes == 0)
    2381             :     {
    2382             :         /* Using one-pass strategy (since table has no indexes) */
    2383           0 :         if (lpdead_items > 0)
    2384             :         {
    2385             :             /*
    2386             :              * Perfunctory handling for the corner case where a single pass
    2387             :              * strategy VACUUM cannot get a cleanup lock, and it turns out
    2388             :              * that there is one or more LP_DEAD items: just count the LP_DEAD
    2389             :              * items as missed_dead_tuples instead. (This is a bit dishonest,
    2390             :              * but it beats having to maintain specialized heap vacuuming code
    2391             :              * forever, for vanishingly little benefit.)
    2392             :              */
    2393           0 :             hastup = true;
    2394           0 :             missed_dead_tuples += lpdead_items;
    2395             :         }
    2396             :     }
    2397         242 :     else if (lpdead_items > 0)
    2398             :     {
    2399             :         /*
    2400             :          * Page has LP_DEAD items, and so any references/TIDs that remain in
    2401             :          * indexes will be deleted during index vacuuming (and then marked
    2402             :          * LP_UNUSED in the heap)
    2403             :          */
    2404           0 :         vacrel->lpdead_item_pages++;
    2405             : 
    2406           0 :         dead_items_add(vacrel, blkno, deadoffsets, lpdead_items);
    2407             : 
    2408           0 :         vacrel->lpdead_items += lpdead_items;
    2409             :     }
    2410             : 
    2411             :     /*
    2412             :      * Finally, add relevant page-local counts to whole-VACUUM counts
    2413             :      */
    2414         242 :     vacrel->live_tuples += live_tuples;
    2415         242 :     vacrel->recently_dead_tuples += recently_dead_tuples;
    2416         242 :     vacrel->missed_dead_tuples += missed_dead_tuples;
    2417         242 :     if (missed_dead_tuples > 0)
    2418           4 :         vacrel->missed_dead_pages++;
    2419             : 
    2420             :     /* Can't truncate this page */
    2421         242 :     if (hastup)
    2422         242 :         vacrel->nonempty_pages = blkno + 1;
    2423             : 
    2424             :     /* Did we find LP_DEAD items? */
    2425         242 :     *has_lpdead_items = (lpdead_items > 0);
    2426             : 
    2427             :     /* Caller won't need to call lazy_scan_prune with same page */
    2428         242 :     return true;
    2429             : }
    2430             : 
    2431             : /*
    2432             :  * Main entry point for index vacuuming and heap vacuuming.
    2433             :  *
    2434             :  * Removes items collected in dead_items from table's indexes, then marks the
    2435             :  * same items LP_UNUSED in the heap.  See the comments above lazy_scan_heap
    2436             :  * for full details.
    2437             :  *
    2438             :  * Also empties dead_items, freeing up space for later TIDs.
    2439             :  *
    2440             :  * We may choose to bypass index vacuuming at this point, though only when the
    2441             :  * ongoing VACUUM operation will definitely only have one index scan/round of
    2442             :  * index vacuuming.
    2443             :  */
    2444             : static void
    2445        1294 : lazy_vacuum(LVRelState *vacrel)
    2446             : {
    2447             :     bool        bypass;
    2448             : 
    2449             :     /* Should not end up here with no indexes */
    2450             :     Assert(vacrel->nindexes > 0);
    2451             :     Assert(vacrel->lpdead_item_pages > 0);
    2452             : 
    2453        1294 :     if (!vacrel->do_index_vacuuming)
    2454             :     {
    2455             :         Assert(!vacrel->do_index_cleanup);
    2456          30 :         dead_items_reset(vacrel);
    2457          30 :         return;
    2458             :     }
    2459             : 
    2460             :     /*
    2461             :      * Consider bypassing index vacuuming (and heap vacuuming) entirely.
    2462             :      *
    2463             :      * We currently only do this in cases where the number of LP_DEAD items
    2464             :      * for the entire VACUUM operation is close to zero.  This avoids sharp
    2465             :      * discontinuities in the duration and overhead of successive VACUUM
    2466             :      * operations that run against the same table with a fixed workload.
    2467             :      * Ideally, successive VACUUM operations will behave as if there are
    2468             :      * exactly zero LP_DEAD items in cases where there are close to zero.
    2469             :      *
    2470             :      * This is likely to be helpful with a table that is continually affected
    2471             :      * by UPDATEs that can mostly apply the HOT optimization, but occasionally
    2472             :      * have small aberrations that lead to just a few heap pages retaining
    2473             :      * only one or two LP_DEAD items.  This is pretty common; even when the
    2474             :      * DBA goes out of their way to make UPDATEs use HOT, it is practically
    2475             :      * impossible to predict whether HOT will be applied in 100% of cases.
    2476             :      * It's far easier to ensure that 99%+ of all UPDATEs against a table use
    2477             :      * HOT through careful tuning.
    2478             :      */
    2479        1264 :     bypass = false;
    2480        1264 :     if (vacrel->consider_bypass_optimization && vacrel->rel_pages > 0)
    2481             :     {
    2482             :         BlockNumber threshold;
    2483             : 
    2484             :         Assert(vacrel->num_index_scans == 0);
    2485             :         Assert(vacrel->lpdead_items == vacrel->dead_items_info->num_items);
    2486             :         Assert(vacrel->do_index_vacuuming);
    2487             :         Assert(vacrel->do_index_cleanup);
    2488             : 
    2489             :         /*
    2490             :          * This crossover point at which we'll start to do index vacuuming is
    2491             :          * expressed as a percentage of the total number of heap pages in the
    2492             :          * table that are known to have at least one LP_DEAD item.  This is
    2493             :          * much more important than the total number of LP_DEAD items, since
    2494             :          * it's a proxy for the number of heap pages whose visibility map bits
    2495             :          * cannot be set on account of bypassing index and heap vacuuming.
    2496             :          *
    2497             :          * We apply one further precautionary test: the space currently used
    2498             :          * to store the TIDs (TIDs that now all point to LP_DEAD items) must
    2499             :          * not exceed 32MB.  This limits the risk that we will bypass index
    2500             :          * vacuuming again and again until eventually there is a VACUUM whose
    2501             :          * dead_items space is not CPU cache resident.
    2502             :          *
    2503             :          * We don't take any special steps to remember the LP_DEAD items (such
    2504             :          * as counting them in our final update to the stats system) when the
    2505             :          * optimization is applied.  Though the accounting used in analyze.c's
    2506             :          * acquire_sample_rows() will recognize the same LP_DEAD items as dead
    2507             :          * rows in its own stats report, that's okay. The discrepancy should
    2508             :          * be negligible.  If this optimization is ever expanded to cover more
    2509             :          * cases then this may need to be reconsidered.
    2510             :          */
    2511        1234 :         threshold = (double) vacrel->rel_pages * BYPASS_THRESHOLD_PAGES;
    2512        1236 :         bypass = (vacrel->lpdead_item_pages < threshold &&
    2513           2 :                   TidStoreMemoryUsage(vacrel->dead_items) < 32 * 1024 * 1024);
    2514             :     }
    2515             : 
    2516        1264 :     if (bypass)
    2517             :     {
    2518             :         /*
    2519             :          * There are almost zero TIDs.  Behave as if there were precisely
    2520             :          * zero: bypass index vacuuming, but do index cleanup.
    2521             :          *
    2522             :          * We expect that the ongoing VACUUM operation will finish very
    2523             :          * quickly, so there is no point in considering speeding up as a
    2524             :          * failsafe against wraparound failure. (Index cleanup is expected to
    2525             :          * finish very quickly in cases where there were no ambulkdelete()
    2526             :          * calls.)
    2527             :          */
    2528           2 :         vacrel->do_index_vacuuming = false;
    2529             :     }
    2530        1262 :     else if (lazy_vacuum_all_indexes(vacrel))
    2531             :     {
    2532             :         /*
    2533             :          * We successfully completed a round of index vacuuming.  Do related
    2534             :          * heap vacuuming now.
    2535             :          */
    2536        1262 :         lazy_vacuum_heap_rel(vacrel);
    2537             :     }
    2538             :     else
    2539             :     {
    2540             :         /*
    2541             :          * Failsafe case.
    2542             :          *
    2543             :          * We attempted index vacuuming, but didn't finish a full round/full
    2544             :          * index scan.  This happens when relfrozenxid or relminmxid is too
    2545             :          * far in the past.
    2546             :          *
    2547             :          * From this point on the VACUUM operation will do no further index
    2548             :          * vacuuming or heap vacuuming.  This VACUUM operation won't end up
    2549             :          * back here again.
    2550             :          */
    2551             :         Assert(VacuumFailsafeActive);
    2552             :     }
    2553             : 
    2554             :     /*
    2555             :      * Forget the LP_DEAD items that we just vacuumed (or just decided to not
    2556             :      * vacuum)
    2557             :      */
    2558        1264 :     dead_items_reset(vacrel);
    2559             : }
    2560             : 
    2561             : /*
    2562             :  *  lazy_vacuum_all_indexes() -- Main entry for index vacuuming
    2563             :  *
    2564             :  * Returns true in the common case when all indexes were successfully
    2565             :  * vacuumed.  Returns false in rare cases where we determined that the ongoing
    2566             :  * VACUUM operation is at risk of taking too long to finish, leading to
    2567             :  * wraparound failure.
    2568             :  */
    2569             : static bool
    2570        1262 : lazy_vacuum_all_indexes(LVRelState *vacrel)
    2571             : {
    2572        1262 :     bool        allindexes = true;
    2573        1262 :     double      old_live_tuples = vacrel->rel->rd_rel->reltuples;
    2574        1262 :     const int   progress_start_index[] = {
    2575             :         PROGRESS_VACUUM_PHASE,
    2576             :         PROGRESS_VACUUM_INDEXES_TOTAL
    2577             :     };
    2578        1262 :     const int   progress_end_index[] = {
    2579             :         PROGRESS_VACUUM_INDEXES_TOTAL,
    2580             :         PROGRESS_VACUUM_INDEXES_PROCESSED,
    2581             :         PROGRESS_VACUUM_NUM_INDEX_VACUUMS
    2582             :     };
    2583             :     int64       progress_start_val[2];
    2584             :     int64       progress_end_val[3];
    2585             : 
    2586             :     Assert(vacrel->nindexes > 0);
    2587             :     Assert(vacrel->do_index_vacuuming);
    2588             :     Assert(vacrel->do_index_cleanup);
    2589             : 
    2590             :     /* Precheck for XID wraparound emergencies */
    2591        1262 :     if (lazy_check_wraparound_failsafe(vacrel))
    2592             :     {
    2593             :         /* Wraparound emergency -- don't even start an index scan */
    2594           0 :         return false;
    2595             :     }
    2596             : 
    2597             :     /*
    2598             :      * Report that we are now vacuuming indexes and the number of indexes to
    2599             :      * vacuum.
    2600             :      */
    2601        1262 :     progress_start_val[0] = PROGRESS_VACUUM_PHASE_VACUUM_INDEX;
    2602        1262 :     progress_start_val[1] = vacrel->nindexes;
    2603        1262 :     pgstat_progress_update_multi_param(2, progress_start_index, progress_start_val);
    2604             : 
    2605        1262 :     if (!ParallelVacuumIsActive(vacrel))
    2606             :     {
    2607        3666 :         for (int idx = 0; idx < vacrel->nindexes; idx++)
    2608             :         {
    2609        2416 :             Relation    indrel = vacrel->indrels[idx];
    2610        2416 :             IndexBulkDeleteResult *istat = vacrel->indstats[idx];
    2611             : 
    2612        2416 :             vacrel->indstats[idx] = lazy_vacuum_one_index(indrel, istat,
    2613             :                                                           old_live_tuples,
    2614             :                                                           vacrel);
    2615             : 
    2616             :             /* Report the number of indexes vacuumed */
    2617        2416 :             pgstat_progress_update_param(PROGRESS_VACUUM_INDEXES_PROCESSED,
    2618        2416 :                                          idx + 1);
    2619             : 
    2620        2416 :             if (lazy_check_wraparound_failsafe(vacrel))
    2621             :             {
    2622             :                 /* Wraparound emergency -- end current index scan */
    2623           0 :                 allindexes = false;
    2624           0 :                 break;
    2625             :             }
    2626             :         }
    2627             :     }
    2628             :     else
    2629             :     {
    2630             :         /* Outsource everything to parallel variant */
    2631          12 :         parallel_vacuum_bulkdel_all_indexes(vacrel->pvs, old_live_tuples,
    2632             :                                             vacrel->num_index_scans);
    2633             : 
    2634             :         /*
    2635             :          * Do a postcheck to consider applying wraparound failsafe now.  Note
    2636             :          * that parallel VACUUM only gets the precheck and this postcheck.
    2637             :          */
    2638          12 :         if (lazy_check_wraparound_failsafe(vacrel))
    2639           0 :             allindexes = false;
    2640             :     }
    2641             : 
    2642             :     /*
    2643             :      * We delete all LP_DEAD items from the first heap pass in all indexes on
    2644             :      * each call here (except calls where we choose to do the failsafe). This
    2645             :      * makes the next call to lazy_vacuum_heap_rel() safe (except in the event
    2646             :      * of the failsafe triggering, which prevents the next call from taking
    2647             :      * place).
    2648             :      */
    2649             :     Assert(vacrel->num_index_scans > 0 ||
    2650             :            vacrel->dead_items_info->num_items == vacrel->lpdead_items);
    2651             :     Assert(allindexes || VacuumFailsafeActive);
    2652             : 
    2653             :     /*
    2654             :      * Increase and report the number of index scans.  Also, we reset
    2655             :      * PROGRESS_VACUUM_INDEXES_TOTAL and PROGRESS_VACUUM_INDEXES_PROCESSED.
    2656             :      *
    2657             :      * We deliberately include the case where we started a round of bulk
    2658             :      * deletes that we weren't able to finish due to the failsafe triggering.
    2659             :      */
    2660        1262 :     vacrel->num_index_scans++;
    2661        1262 :     progress_end_val[0] = 0;
    2662        1262 :     progress_end_val[1] = 0;
    2663        1262 :     progress_end_val[2] = vacrel->num_index_scans;
    2664        1262 :     pgstat_progress_update_multi_param(3, progress_end_index, progress_end_val);
    2665             : 
    2666        1262 :     return allindexes;
    2667             : }
    2668             : 
    2669             : /*
    2670             :  * Read stream callback for vacuum's third phase (second pass over the heap).
    2671             :  * Gets the next block from the TID store and returns it or InvalidBlockNumber
    2672             :  * if there are no further blocks to vacuum.
    2673             :  *
    2674             :  * NB: Assumed to be safe to use with READ_STREAM_USE_BATCHING.
    2675             :  */
    2676             : static BlockNumber
    2677       26490 : vacuum_reap_lp_read_stream_next(ReadStream *stream,
    2678             :                                 void *callback_private_data,
    2679             :                                 void *per_buffer_data)
    2680             : {
    2681       26490 :     TidStoreIter *iter = callback_private_data;
    2682             :     TidStoreIterResult *iter_result;
    2683             : 
    2684       26490 :     iter_result = TidStoreIterateNext(iter);
    2685       26490 :     if (iter_result == NULL)
    2686        1262 :         return InvalidBlockNumber;
    2687             : 
    2688             :     /*
    2689             :      * Save the TidStoreIterResult for later, so we can extract the offsets.
    2690             :      * It is safe to copy the result, according to TidStoreIterateNext().
    2691             :      */
    2692       25228 :     memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
    2693             : 
    2694       25228 :     return iter_result->blkno;
    2695             : }
    2696             : 
    2697             : /*
    2698             :  *  lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
    2699             :  *
    2700             :  * This routine marks LP_DEAD items in vacrel->dead_items as LP_UNUSED. Pages
    2701             :  * that never had lazy_scan_prune record LP_DEAD items are not visited at all.
    2702             :  *
    2703             :  * We may also be able to truncate the line pointer array of the heap pages we
    2704             :  * visit.  If there is a contiguous group of LP_UNUSED items at the end of the
    2705             :  * array, it can be reclaimed as free space.  These LP_UNUSED items usually
    2706             :  * start out as LP_DEAD items recorded by lazy_scan_prune (we set items from
    2707             :  * each page to LP_UNUSED, and then consider if it's possible to truncate the
    2708             :  * page's line pointer array).
    2709             :  *
    2710             :  * Note: the reason for doing this as a second pass is we cannot remove the
    2711             :  * tuples until we've removed their index entries, and we want to process
    2712             :  * index entry removal in batches as large as possible.
    2713             :  */
    2714             : static void
    2715        1262 : lazy_vacuum_heap_rel(LVRelState *vacrel)
    2716             : {
    2717             :     ReadStream *stream;
    2718        1262 :     BlockNumber vacuumed_pages = 0;
    2719        1262 :     Buffer      vmbuffer = InvalidBuffer;
    2720             :     LVSavedErrInfo saved_err_info;
    2721             :     TidStoreIter *iter;
    2722             : 
    2723             :     Assert(vacrel->do_index_vacuuming);
    2724             :     Assert(vacrel->do_index_cleanup);
    2725             :     Assert(vacrel->num_index_scans > 0);
    2726             : 
    2727             :     /* Report that we are now vacuuming the heap */
    2728        1262 :     pgstat_progress_update_param(PROGRESS_VACUUM_PHASE,
    2729             :                                  PROGRESS_VACUUM_PHASE_VACUUM_HEAP);
    2730             : 
    2731             :     /* Update error traceback information */
    2732        1262 :     update_vacuum_error_info(vacrel, &saved_err_info,
    2733             :                              VACUUM_ERRCB_PHASE_VACUUM_HEAP,
    2734             :                              InvalidBlockNumber, InvalidOffsetNumber);
    2735             : 
    2736        1262 :     iter = TidStoreBeginIterate(vacrel->dead_items);
    2737             : 
    2738             :     /*
    2739             :      * Set up the read stream for vacuum's second pass through the heap.
    2740             :      *
    2741             :      * It is safe to use batchmode, as vacuum_reap_lp_read_stream_next() does
    2742             :      * not need to wait for IO and does not perform locking. Once we support
    2743             :      * parallelism it should still be fine, as presumably the holder of locks
    2744             :      * would never be blocked by IO while holding the lock.
    2745             :      */
    2746        1262 :     stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE |
    2747             :                                         READ_STREAM_USE_BATCHING,
    2748             :                                         vacrel->bstrategy,
    2749             :                                         vacrel->rel,
    2750             :                                         MAIN_FORKNUM,
    2751             :                                         vacuum_reap_lp_read_stream_next,
    2752             :                                         iter,
    2753             :                                         sizeof(TidStoreIterResult));
    2754             : 
    2755             :     while (true)
    2756       25228 :     {
    2757             :         BlockNumber blkno;
    2758             :         Buffer      buf;
    2759             :         Page        page;
    2760             :         TidStoreIterResult *iter_result;
    2761             :         Size        freespace;
    2762             :         OffsetNumber offsets[MaxOffsetNumber];
    2763             :         int         num_offsets;
    2764             : 
    2765       26490 :         vacuum_delay_point(false);
    2766             : 
    2767       26490 :         buf = read_stream_next_buffer(stream, (void **) &iter_result);
    2768             : 
    2769             :         /* The relation is exhausted */
    2770       26490 :         if (!BufferIsValid(buf))
    2771        1262 :             break;
    2772             : 
    2773       25228 :         vacrel->blkno = blkno = BufferGetBlockNumber(buf);
    2774             : 
    2775             :         Assert(iter_result);
    2776       25228 :         num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
    2777             :         Assert(num_offsets <= lengthof(offsets));
    2778             : 
    2779             :         /*
    2780             :          * Pin the visibility map page in case we need to mark the page
    2781             :          * all-visible.  In most cases this will be very cheap, because we'll
    2782             :          * already have the correct page pinned anyway.
    2783             :          */
    2784       25228 :         visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
    2785             : 
    2786             :         /* We need a non-cleanup exclusive lock to mark dead_items unused */
    2787       25228 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    2788       25228 :         lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
    2789             :                               num_offsets, vmbuffer);
    2790             : 
    2791             :         /* Now that we've vacuumed the page, record its available space */
    2792       25228 :         page = BufferGetPage(buf);
    2793       25228 :         freespace = PageGetHeapFreeSpace(page);
    2794             : 
    2795       25228 :         UnlockReleaseBuffer(buf);
    2796       25228 :         RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
    2797       25228 :         vacuumed_pages++;
    2798             :     }
    2799             : 
    2800        1262 :     read_stream_end(stream);
    2801        1262 :     TidStoreEndIterate(iter);
    2802             : 
    2803        1262 :     vacrel->blkno = InvalidBlockNumber;
    2804        1262 :     if (BufferIsValid(vmbuffer))
    2805        1262 :         ReleaseBuffer(vmbuffer);
    2806             : 
    2807             :     /*
    2808             :      * We set all LP_DEAD items from the first heap pass to LP_UNUSED during
    2809             :      * the second heap pass.  No more, no less.
    2810             :      */
    2811             :     Assert(vacrel->num_index_scans > 1 ||
    2812             :            (vacrel->dead_items_info->num_items == vacrel->lpdead_items &&
    2813             :             vacuumed_pages == vacrel->lpdead_item_pages));
    2814             : 
    2815        1262 :     ereport(DEBUG2,
    2816             :             (errmsg("table \"%s\": removed %" PRId64 " dead item identifiers in %u pages",
    2817             :                     vacrel->relname, vacrel->dead_items_info->num_items,
    2818             :                     vacuumed_pages)));
    2819             : 
    2820             :     /* Revert to the previous phase information for error traceback */
    2821        1262 :     restore_vacuum_error_info(vacrel, &saved_err_info);
    2822        1262 : }
    2823             : 
    2824             : /*
    2825             :  *  lazy_vacuum_heap_page() -- free page's LP_DEAD items listed in the
    2826             :  *                        vacrel->dead_items store.
    2827             :  *
    2828             :  * Caller must have an exclusive buffer lock on the buffer (though a full
    2829             :  * cleanup lock is also acceptable).  vmbuffer must be valid and already have
    2830             :  * a pin on blkno's visibility map page.
    2831             :  */
    2832             : static void
    2833       25228 : lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
    2834             :                       OffsetNumber *deadoffsets, int num_offsets,
    2835             :                       Buffer vmbuffer)
    2836             : {
    2837       25228 :     Page        page = BufferGetPage(buffer);
    2838             :     OffsetNumber unused[MaxHeapTuplesPerPage];
    2839       25228 :     int         nunused = 0;
    2840             :     TransactionId visibility_cutoff_xid;
    2841             :     bool        all_frozen;
    2842             :     LVSavedErrInfo saved_err_info;
    2843             : 
    2844             :     Assert(vacrel->do_index_vacuuming);
    2845             : 
    2846       25228 :     pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
    2847             : 
    2848             :     /* Update error traceback information */
    2849       25228 :     update_vacuum_error_info(vacrel, &saved_err_info,
    2850             :                              VACUUM_ERRCB_PHASE_VACUUM_HEAP, blkno,
    2851             :                              InvalidOffsetNumber);
    2852             : 
    2853       25228 :     START_CRIT_SECTION();
    2854             : 
    2855     1542238 :     for (int i = 0; i < num_offsets; i++)
    2856             :     {
    2857             :         ItemId      itemid;
    2858     1517010 :         OffsetNumber toff = deadoffsets[i];
    2859             : 
    2860     1517010 :         itemid = PageGetItemId(page, toff);
    2861             : 
    2862             :         Assert(ItemIdIsDead(itemid) && !ItemIdHasStorage(itemid));
    2863     1517010 :         ItemIdSetUnused(itemid);
    2864     1517010 :         unused[nunused++] = toff;
    2865             :     }
    2866             : 
    2867             :     Assert(nunused > 0);
    2868             : 
    2869             :     /* Attempt to truncate line pointer array now */
    2870       25228 :     PageTruncateLinePointerArray(page);
    2871             : 
    2872             :     /*
    2873             :      * Mark buffer dirty before we write WAL.
    2874             :      */
    2875       25228 :     MarkBufferDirty(buffer);
    2876             : 
    2877             :     /* XLOG stuff */
    2878       25228 :     if (RelationNeedsWAL(vacrel->rel))
    2879             :     {
    2880       23528 :         log_heap_prune_and_freeze(vacrel->rel, buffer,
    2881             :                                   InvalidTransactionId,
    2882             :                                   false,    /* no cleanup lock required */
    2883             :                                   PRUNE_VACUUM_CLEANUP,
    2884             :                                   NULL, 0,  /* frozen */
    2885             :                                   NULL, 0,  /* redirected */
    2886             :                                   NULL, 0,  /* dead */
    2887             :                                   unused, nunused);
    2888             :     }
    2889             : 
    2890             :     /*
    2891             :      * End critical section, so we safely can do visibility tests (which
    2892             :      * possibly need to perform IO and allocate memory!). If we crash now the
    2893             :      * page (including the corresponding vm bit) might not be marked all
    2894             :      * visible, but that's fine. A later vacuum will fix that.
    2895             :      */
    2896       25228 :     END_CRIT_SECTION();
    2897             : 
    2898             :     /*
    2899             :      * Now that we have removed the LP_DEAD items from the page, once again
    2900             :      * check if the page has become all-visible.  The page is already marked
    2901             :      * dirty, exclusively locked, and, if needed, a full page image has been
    2902             :      * emitted.
    2903             :      */
    2904             :     Assert(!PageIsAllVisible(page));
    2905       25228 :     if (heap_page_is_all_visible(vacrel, buffer, &visibility_cutoff_xid,
    2906             :                                  &all_frozen))
    2907             :     {
    2908       24938 :         uint8       flags = VISIBILITYMAP_ALL_VISIBLE;
    2909             : 
    2910       24938 :         if (all_frozen)
    2911             :         {
    2912             :             Assert(!TransactionIdIsValid(visibility_cutoff_xid));
    2913       19994 :             flags |= VISIBILITYMAP_ALL_FROZEN;
    2914             :         }
    2915             : 
    2916       24938 :         PageSetAllVisible(page);
    2917       24938 :         visibilitymap_set(vacrel->rel, blkno, buffer,
    2918             :                           InvalidXLogRecPtr,
    2919             :                           vmbuffer, visibility_cutoff_xid,
    2920             :                           flags);
    2921             : 
    2922             :         /* Count the newly set VM page for logging */
    2923       24938 :         vacrel->vm_new_visible_pages++;
    2924       24938 :         if (all_frozen)
    2925       19994 :             vacrel->vm_new_visible_frozen_pages++;
    2926             :     }
    2927             : 
    2928             :     /* Revert to the previous phase information for error traceback */
    2929       25228 :     restore_vacuum_error_info(vacrel, &saved_err_info);
    2930       25228 : }
    2931             : 
    2932             : /*
    2933             :  * Trigger the failsafe to avoid wraparound failure when vacrel table has a
    2934             :  * relfrozenxid and/or relminmxid that is dangerously far in the past.
    2935             :  * Triggering the failsafe makes the ongoing VACUUM bypass any further index
    2936             :  * vacuuming and heap vacuuming.  Truncating the heap is also bypassed.
    2937             :  *
    2938             :  * Any remaining work (work that VACUUM cannot just bypass) is typically sped
    2939             :  * up when the failsafe triggers.  VACUUM stops applying any cost-based delay
    2940             :  * that it started out with.
    2941             :  *
    2942             :  * Returns true when failsafe has been triggered.
    2943             :  */
    2944             : static bool
    2945      242590 : lazy_check_wraparound_failsafe(LVRelState *vacrel)
    2946             : {
    2947             :     /* Don't warn more than once per VACUUM */
    2948      242590 :     if (VacuumFailsafeActive)
    2949           0 :         return true;
    2950             : 
    2951      242590 :     if (unlikely(vacuum_xid_failsafe_check(&vacrel->cutoffs)))
    2952             :     {
    2953       62864 :         const int   progress_index[] = {
    2954             :             PROGRESS_VACUUM_INDEXES_TOTAL,
    2955             :             PROGRESS_VACUUM_INDEXES_PROCESSED
    2956             :         };
    2957       62864 :         int64       progress_val[2] = {0, 0};
    2958             : 
    2959       62864 :         VacuumFailsafeActive = true;
    2960             : 
    2961             :         /*
    2962             :          * Abandon use of a buffer access strategy to allow use of all of
    2963             :          * shared buffers.  We assume the caller who allocated the memory for
    2964             :          * the BufferAccessStrategy will free it.
    2965             :          */
    2966       62864 :         vacrel->bstrategy = NULL;
    2967             : 
    2968             :         /* Disable index vacuuming, index cleanup, and heap rel truncation */
    2969       62864 :         vacrel->do_index_vacuuming = false;
    2970       62864 :         vacrel->do_index_cleanup = false;
    2971       62864 :         vacrel->do_rel_truncate = false;
    2972             : 
    2973             :         /* Reset the progress counters */
    2974       62864 :         pgstat_progress_update_multi_param(2, progress_index, progress_val);
    2975             : 
    2976       62864 :         ereport(WARNING,
    2977             :                 (errmsg("bypassing nonessential maintenance of table \"%s.%s.%s\" as a failsafe after %d index scans",
    2978             :                         vacrel->dbname, vacrel->relnamespace, vacrel->relname,
    2979             :                         vacrel->num_index_scans),
    2980             :                  errdetail("The table's relfrozenxid or relminmxid is too far in the past."),
    2981             :                  errhint("Consider increasing configuration parameter \"maintenance_work_mem\" or \"autovacuum_work_mem\".\n"
    2982             :                          "You might also need to consider other ways for VACUUM to keep up with the allocation of transaction IDs.")));
    2983             : 
    2984             :         /* Stop applying cost limits from this point on */
    2985       62864 :         VacuumCostActive = false;
    2986       62864 :         VacuumCostBalance = 0;
    2987             : 
    2988       62864 :         return true;
    2989             :     }
    2990             : 
    2991      179726 :     return false;
    2992             : }
    2993             : 
    2994             : /*
    2995             :  *  lazy_cleanup_all_indexes() -- cleanup all indexes of relation.
    2996             :  */
    2997             : static void
    2998      167132 : lazy_cleanup_all_indexes(LVRelState *vacrel)
    2999             : {
    3000      167132 :     double      reltuples = vacrel->new_rel_tuples;
    3001      167132 :     bool        estimated_count = vacrel->scanned_pages < vacrel->rel_pages;
    3002      167132 :     const int   progress_start_index[] = {
    3003             :         PROGRESS_VACUUM_PHASE,
    3004             :         PROGRESS_VACUUM_INDEXES_TOTAL
    3005             :     };
    3006      167132 :     const int   progress_end_index[] = {
    3007             :         PROGRESS_VACUUM_INDEXES_TOTAL,
    3008             :         PROGRESS_VACUUM_INDEXES_PROCESSED
    3009             :     };
    3010             :     int64       progress_start_val[2];
    3011      167132 :     int64       progress_end_val[2] = {0, 0};
    3012             : 
    3013             :     Assert(vacrel->do_index_cleanup);
    3014             :     Assert(vacrel->nindexes > 0);
    3015             : 
    3016             :     /*
    3017             :      * Report that we are now cleaning up indexes and the number of indexes to
    3018             :      * cleanup.
    3019             :      */
    3020      167132 :     progress_start_val[0] = PROGRESS_VACUUM_PHASE_INDEX_CLEANUP;
    3021      167132 :     progress_start_val[1] = vacrel->nindexes;
    3022      167132 :     pgstat_progress_update_multi_param(2, progress_start_index, progress_start_val);
    3023             : 
    3024      167132 :     if (!ParallelVacuumIsActive(vacrel))
    3025             :     {
    3026      430438 :         for (int idx = 0; idx < vacrel->nindexes; idx++)
    3027             :         {
    3028      263340 :             Relation    indrel = vacrel->indrels[idx];
    3029      263340 :             IndexBulkDeleteResult *istat = vacrel->indstats[idx];
    3030             : 
    3031      526680 :             vacrel->indstats[idx] =
    3032      263340 :                 lazy_cleanup_one_index(indrel, istat, reltuples,
    3033             :                                        estimated_count, vacrel);
    3034             : 
    3035             :             /* Report the number of indexes cleaned up */
    3036      263340 :             pgstat_progress_update_param(PROGRESS_VACUUM_INDEXES_PROCESSED,
    3037      263340 :                                          idx + 1);
    3038             :         }
    3039             :     }
    3040             :     else
    3041             :     {
    3042             :         /* Outsource everything to parallel variant */
    3043          34 :         parallel_vacuum_cleanup_all_indexes(vacrel->pvs, reltuples,
    3044             :                                             vacrel->num_index_scans,
    3045             :                                             estimated_count);
    3046             :     }
    3047             : 
    3048             :     /* Reset the progress counters */
    3049      167132 :     pgstat_progress_update_multi_param(2, progress_end_index, progress_end_val);
    3050      167132 : }
    3051             : 
    3052             : /*
    3053             :  *  lazy_vacuum_one_index() -- vacuum index relation.
    3054             :  *
    3055             :  *      Delete all the index tuples containing a TID collected in
    3056             :  *      vacrel->dead_items.  Also update running statistics. Exact
    3057             :  *      details depend on index AM's ambulkdelete routine.
    3058             :  *
    3059             :  *      reltuples is the number of heap tuples to be passed to the
    3060             :  *      bulkdelete callback.  It's always assumed to be estimated.
    3061             :  *      See indexam.sgml for more info.
    3062             :  *
    3063             :  * Returns bulk delete stats derived from input stats
    3064             :  */
    3065             : static IndexBulkDeleteResult *
    3066        2416 : lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat,
    3067             :                       double reltuples, LVRelState *vacrel)
    3068             : {
    3069             :     IndexVacuumInfo ivinfo;
    3070             :     LVSavedErrInfo saved_err_info;
    3071             : 
    3072        2416 :     ivinfo.index = indrel;
    3073        2416 :     ivinfo.heaprel = vacrel->rel;
    3074        2416 :     ivinfo.analyze_only = false;
    3075        2416 :     ivinfo.report_progress = false;
    3076        2416 :     ivinfo.estimated_count = true;
    3077        2416 :     ivinfo.message_level = DEBUG2;
    3078        2416 :     ivinfo.num_heap_tuples = reltuples;
    3079        2416 :     ivinfo.strategy = vacrel->bstrategy;
    3080             : 
    3081             :     /*
    3082             :      * Update error traceback information.
    3083             :      *
    3084             :      * The index name is saved during this phase and restored immediately
    3085             :      * after this phase.  See vacuum_error_callback.
    3086             :      */
    3087             :     Assert(vacrel->indname == NULL);
    3088        2416 :     vacrel->indname = pstrdup(RelationGetRelationName(indrel));
    3089        2416 :     update_vacuum_error_info(vacrel, &saved_err_info,
    3090             :                              VACUUM_ERRCB_PHASE_VACUUM_INDEX,
    3091             :                              InvalidBlockNumber, InvalidOffsetNumber);
    3092             : 
    3093             :     /* Do bulk deletion */
    3094        2416 :     istat = vac_bulkdel_one_index(&ivinfo, istat, vacrel->dead_items,
    3095             :                                   vacrel->dead_items_info);
    3096             : 
    3097             :     /* Revert to the previous phase information for error traceback */
    3098        2416 :     restore_vacuum_error_info(vacrel, &saved_err_info);
    3099        2416 :     pfree(vacrel->indname);
    3100        2416 :     vacrel->indname = NULL;
    3101             : 
    3102        2416 :     return istat;
    3103             : }
    3104             : 
    3105             : /*
    3106             :  *  lazy_cleanup_one_index() -- do post-vacuum cleanup for index relation.
    3107             :  *
    3108             :  *      Calls index AM's amvacuumcleanup routine.  reltuples is the number
    3109             :  *      of heap tuples and estimated_count is true if reltuples is an
    3110             :  *      estimated value.  See indexam.sgml for more info.
    3111             :  *
    3112             :  * Returns bulk delete stats derived from input stats
    3113             :  */
    3114             : static IndexBulkDeleteResult *
    3115      263340 : lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat,
    3116             :                        double reltuples, bool estimated_count,
    3117             :                        LVRelState *vacrel)
    3118             : {
    3119             :     IndexVacuumInfo ivinfo;
    3120             :     LVSavedErrInfo saved_err_info;
    3121             : 
    3122      263340 :     ivinfo.index = indrel;
    3123      263340 :     ivinfo.heaprel = vacrel->rel;
    3124      263340 :     ivinfo.analyze_only = false;
    3125      263340 :     ivinfo.report_progress = false;
    3126      263340 :     ivinfo.estimated_count = estimated_count;
    3127      263340 :     ivinfo.message_level = DEBUG2;
    3128             : 
    3129      263340 :     ivinfo.num_heap_tuples = reltuples;
    3130      263340 :     ivinfo.strategy = vacrel->bstrategy;
    3131             : 
    3132             :     /*
    3133             :      * Update error traceback information.
    3134             :      *
    3135             :      * The index name is saved during this phase and restored immediately
    3136             :      * after this phase.  See vacuum_error_callback.
    3137             :      */
    3138             :     Assert(vacrel->indname == NULL);
    3139      263340 :     vacrel->indname = pstrdup(RelationGetRelationName(indrel));
    3140      263340 :     update_vacuum_error_info(vacrel, &saved_err_info,
    3141             :                              VACUUM_ERRCB_PHASE_INDEX_CLEANUP,
    3142             :                              InvalidBlockNumber, InvalidOffsetNumber);
    3143             : 
    3144      263340 :     istat = vac_cleanup_one_index(&ivinfo, istat);
    3145             : 
    3146             :     /* Revert to the previous phase information for error traceback */
    3147      263340 :     restore_vacuum_error_info(vacrel, &saved_err_info);
    3148      263340 :     pfree(vacrel->indname);
    3149      263340 :     vacrel->indname = NULL;
    3150             : 
    3151      263340 :     return istat;
    3152             : }
    3153             : 
    3154             : /*
    3155             :  * should_attempt_truncation - should we attempt to truncate the heap?
    3156             :  *
    3157             :  * Don't even think about it unless we have a shot at releasing a goodly
    3158             :  * number of pages.  Otherwise, the time taken isn't worth it, mainly because
    3159             :  * an AccessExclusive lock must be replayed on any hot standby, where it can
    3160             :  * be particularly disruptive.
    3161             :  *
    3162             :  * Also don't attempt it if wraparound failsafe is in effect.  The entire
    3163             :  * system might be refusing to allocate new XIDs at this point.  The system
    3164             :  * definitely won't return to normal unless and until VACUUM actually advances
    3165             :  * the oldest relfrozenxid -- which hasn't happened for target rel just yet.
    3166             :  * If lazy_truncate_heap attempted to acquire an AccessExclusiveLock to
    3167             :  * truncate the table under these circumstances, an XID exhaustion error might
    3168             :  * make it impossible for VACUUM to fix the underlying XID exhaustion problem.
    3169             :  * There is very little chance of truncation working out when the failsafe is
    3170             :  * in effect in any case.  lazy_scan_prune makes the optimistic assumption
    3171             :  * that any LP_DEAD items it encounters will always be LP_UNUSED by the time
    3172             :  * we're called.
    3173             :  */
    3174             : static bool
    3175      238900 : should_attempt_truncation(LVRelState *vacrel)
    3176             : {
    3177             :     BlockNumber possibly_freeable;
    3178             : 
    3179      238900 :     if (!vacrel->do_rel_truncate || VacuumFailsafeActive)
    3180       63154 :         return false;
    3181             : 
    3182      175746 :     possibly_freeable = vacrel->rel_pages - vacrel->nonempty_pages;
    3183      175746 :     if (possibly_freeable > 0 &&
    3184         306 :         (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
    3185         306 :          possibly_freeable >= vacrel->rel_pages / REL_TRUNCATE_FRACTION))
    3186         284 :         return true;
    3187             : 
    3188      175462 :     return false;
    3189             : }
    3190             : 
    3191             : /*
    3192             :  * lazy_truncate_heap - try to truncate off any empty pages at the end
    3193             :  */
    3194             : static void
    3195         284 : lazy_truncate_heap(LVRelState *vacrel)
    3196             : {
    3197         284 :     BlockNumber orig_rel_pages = vacrel->rel_pages;
    3198             :     BlockNumber new_rel_pages;
    3199             :     bool        lock_waiter_detected;
    3200             :     int         lock_retry;
    3201             : 
    3202             :     /* Report that we are now truncating */
    3203         284 :     pgstat_progress_update_param(PROGRESS_VACUUM_PHASE,
    3204             :                                  PROGRESS_VACUUM_PHASE_TRUNCATE);
    3205             : 
    3206             :     /* Update error traceback information one last time */
    3207         284 :     update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_TRUNCATE,
    3208             :                              vacrel->nonempty_pages, InvalidOffsetNumber);
    3209             : 
    3210             :     /*
    3211             :      * Loop until no more truncating can be done.
    3212             :      */
    3213             :     do
    3214             :     {
    3215             :         /*
    3216             :          * We need full exclusive lock on the relation in order to do
    3217             :          * truncation. If we can't get it, give up rather than waiting --- we
    3218             :          * don't want to block other backends, and we don't want to deadlock
    3219             :          * (which is quite possible considering we already hold a lower-grade
    3220             :          * lock).
    3221             :          */
    3222         284 :         lock_waiter_detected = false;
    3223         284 :         lock_retry = 0;
    3224             :         while (true)
    3225             :         {
    3226         684 :             if (ConditionalLockRelation(vacrel->rel, AccessExclusiveLock))
    3227         280 :                 break;
    3228             : 
    3229             :             /*
    3230             :              * Check for interrupts while trying to (re-)acquire the exclusive
    3231             :              * lock.
    3232             :              */
    3233         404 :             CHECK_FOR_INTERRUPTS();
    3234             : 
    3235         404 :             if (++lock_retry > (VACUUM_TRUNCATE_LOCK_TIMEOUT /
    3236             :                                 VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL))
    3237             :             {
    3238             :                 /*
    3239             :                  * We failed to establish the lock in the specified number of
    3240             :                  * retries. This means we give up truncating.
    3241             :                  */
    3242           4 :                 ereport(vacrel->verbose ? INFO : DEBUG2,
    3243             :                         (errmsg("\"%s\": stopping truncate due to conflicting lock request",
    3244             :                                 vacrel->relname)));
    3245           6 :                 return;
    3246             :             }
    3247             : 
    3248         400 :             (void) WaitLatch(MyLatch,
    3249             :                              WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
    3250             :                              VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL,
    3251             :                              WAIT_EVENT_VACUUM_TRUNCATE);
    3252         400 :             ResetLatch(MyLatch);
    3253             :         }
    3254             : 
    3255             :         /*
    3256             :          * Now that we have exclusive lock, look to see if the rel has grown
    3257             :          * whilst we were vacuuming with non-exclusive lock.  If so, give up;
    3258             :          * the newly added pages presumably contain non-deletable tuples.
    3259             :          */
    3260         280 :         new_rel_pages = RelationGetNumberOfBlocks(vacrel->rel);
    3261         280 :         if (new_rel_pages != orig_rel_pages)
    3262             :         {
    3263             :             /*
    3264             :              * Note: we intentionally don't update vacrel->rel_pages with the
    3265             :              * new rel size here.  If we did, it would amount to assuming that
    3266             :              * the new pages are empty, which is unlikely. Leaving the numbers
    3267             :              * alone amounts to assuming that the new pages have the same
    3268             :              * tuple density as existing ones, which is less unlikely.
    3269             :              */
    3270           0 :             UnlockRelation(vacrel->rel, AccessExclusiveLock);
    3271           0 :             return;
    3272             :         }
    3273             : 
    3274             :         /*
    3275             :          * Scan backwards from the end to verify that the end pages actually
    3276             :          * contain no tuples.  This is *necessary*, not optional, because
    3277             :          * other backends could have added tuples to these pages whilst we
    3278             :          * were vacuuming.
    3279             :          */
    3280         280 :         new_rel_pages = count_nondeletable_pages(vacrel, &lock_waiter_detected);
    3281         280 :         vacrel->blkno = new_rel_pages;
    3282             : 
    3283         280 :         if (new_rel_pages >= orig_rel_pages)
    3284             :         {
    3285             :             /* can't do anything after all */
    3286           2 :             UnlockRelation(vacrel->rel, AccessExclusiveLock);
    3287           2 :             return;
    3288             :         }
    3289             : 
    3290             :         /*
    3291             :          * Okay to truncate.
    3292             :          */
    3293         278 :         RelationTruncate(vacrel->rel, new_rel_pages);
    3294             : 
    3295             :         /*
    3296             :          * We can release the exclusive lock as soon as we have truncated.
    3297             :          * Other backends can't safely access the relation until they have
    3298             :          * processed the smgr invalidation that smgrtruncate sent out ... but
    3299             :          * that should happen as part of standard invalidation processing once
    3300             :          * they acquire lock on the relation.
    3301             :          */
    3302         278 :         UnlockRelation(vacrel->rel, AccessExclusiveLock);
    3303             : 
    3304             :         /*
    3305             :          * Update statistics.  Here, it *is* correct to adjust rel_pages
    3306             :          * without also touching reltuples, since the tuple count wasn't
    3307             :          * changed by the truncation.
    3308             :          */
    3309         278 :         vacrel->removed_pages += orig_rel_pages - new_rel_pages;
    3310         278 :         vacrel->rel_pages = new_rel_pages;
    3311             : 
    3312         278 :         ereport(vacrel->verbose ? INFO : DEBUG2,
    3313             :                 (errmsg("table \"%s\": truncated %u to %u pages",
    3314             :                         vacrel->relname,
    3315             :                         orig_rel_pages, new_rel_pages)));
    3316         278 :         orig_rel_pages = new_rel_pages;
    3317         278 :     } while (new_rel_pages > vacrel->nonempty_pages && lock_waiter_detected);
    3318             : }
    3319             : 
    3320             : /*
    3321             :  * Rescan end pages to verify that they are (still) empty of tuples.
    3322             :  *
    3323             :  * Returns number of nondeletable pages (last nonempty page + 1).
    3324             :  */
    3325             : static BlockNumber
    3326         280 : count_nondeletable_pages(LVRelState *vacrel, bool *lock_waiter_detected)
    3327             : {
    3328             :     BlockNumber blkno;
    3329             :     BlockNumber prefetchedUntil;
    3330             :     instr_time  starttime;
    3331             : 
    3332             :     /* Initialize the starttime if we check for conflicting lock requests */
    3333         280 :     INSTR_TIME_SET_CURRENT(starttime);
    3334             : 
    3335             :     /*
    3336             :      * Start checking blocks at what we believe relation end to be and move
    3337             :      * backwards.  (Strange coding of loop control is needed because blkno is
    3338             :      * unsigned.)  To make the scan faster, we prefetch a few blocks at a time
    3339             :      * in forward direction, so that OS-level readahead can kick in.
    3340             :      */
    3341         280 :     blkno = vacrel->rel_pages;
    3342             :     StaticAssertStmt((PREFETCH_SIZE & (PREFETCH_SIZE - 1)) == 0,
    3343             :                      "prefetch size must be power of 2");
    3344         280 :     prefetchedUntil = InvalidBlockNumber;
    3345        4142 :     while (blkno > vacrel->nonempty_pages)
    3346             :     {
    3347             :         Buffer      buf;
    3348             :         Page        page;
    3349             :         OffsetNumber offnum,
    3350             :                     maxoff;
    3351             :         bool        hastup;
    3352             : 
    3353             :         /*
    3354             :          * Check if another process requests a lock on our relation. We are
    3355             :          * holding an AccessExclusiveLock here, so they will be waiting. We
    3356             :          * only do this once per VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and we
    3357             :          * only check if that interval has elapsed once every 32 blocks to
    3358             :          * keep the number of system calls and actual shared lock table
    3359             :          * lookups to a minimum.
    3360             :          */
    3361        3868 :         if ((blkno % 32) == 0)
    3362             :         {
    3363             :             instr_time  currenttime;
    3364             :             instr_time  elapsed;
    3365             : 
    3366         124 :             INSTR_TIME_SET_CURRENT(currenttime);
    3367         124 :             elapsed = currenttime;
    3368         124 :             INSTR_TIME_SUBTRACT(elapsed, starttime);
    3369         124 :             if ((INSTR_TIME_GET_MICROSEC(elapsed) / 1000)
    3370             :                 >= VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL)
    3371             :             {
    3372           0 :                 if (LockHasWaitersRelation(vacrel->rel, AccessExclusiveLock))
    3373             :                 {
    3374           0 :                     ereport(vacrel->verbose ? INFO : DEBUG2,
    3375             :                             (errmsg("table \"%s\": suspending truncate due to conflicting lock request",
    3376             :                                     vacrel->relname)));
    3377             : 
    3378           0 :                     *lock_waiter_detected = true;
    3379           0 :                     return blkno;
    3380             :                 }
    3381           0 :                 starttime = currenttime;
    3382             :             }
    3383             :         }
    3384             : 
    3385             :         /*
    3386             :          * We don't insert a vacuum delay point here, because we have an
    3387             :          * exclusive lock on the table which we want to hold for as short a
    3388             :          * time as possible.  We still need to check for interrupts however.
    3389             :          */
    3390        3868 :         CHECK_FOR_INTERRUPTS();
    3391             : 
    3392        3868 :         blkno--;
    3393             : 
    3394             :         /* If we haven't prefetched this lot yet, do so now. */
    3395        3868 :         if (prefetchedUntil > blkno)
    3396             :         {
    3397             :             BlockNumber prefetchStart;
    3398             :             BlockNumber pblkno;
    3399             : 
    3400         368 :             prefetchStart = blkno & ~(PREFETCH_SIZE - 1);
    3401        5678 :             for (pblkno = prefetchStart; pblkno <= blkno; pblkno++)
    3402             :             {
    3403        5310 :                 PrefetchBuffer(vacrel->rel, MAIN_FORKNUM, pblkno);
    3404        5310 :                 CHECK_FOR_INTERRUPTS();
    3405             :             }
    3406         368 :             prefetchedUntil = prefetchStart;
    3407             :         }
    3408             : 
    3409        3868 :         buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
    3410             :                                  vacrel->bstrategy);
    3411             : 
    3412             :         /* In this phase we only need shared access to the buffer */
    3413        3868 :         LockBuffer(buf, BUFFER_LOCK_SHARE);
    3414             : 
    3415        3868 :         page = BufferGetPage(buf);
    3416             : 
    3417        3868 :         if (PageIsNew(page) || PageIsEmpty(page))
    3418             :         {
    3419        1478 :             UnlockReleaseBuffer(buf);
    3420        1478 :             continue;
    3421             :         }
    3422             : 
    3423        2390 :         hastup = false;
    3424        2390 :         maxoff = PageGetMaxOffsetNumber(page);
    3425        2390 :         for (offnum = FirstOffsetNumber;
    3426        5080 :              offnum <= maxoff;
    3427        2690 :              offnum = OffsetNumberNext(offnum))
    3428             :         {
    3429             :             ItemId      itemid;
    3430             : 
    3431        2696 :             itemid = PageGetItemId(page, offnum);
    3432             : 
    3433             :             /*
    3434             :              * Note: any non-unused item should be taken as a reason to keep
    3435             :              * this page.  Even an LP_DEAD item makes truncation unsafe, since
    3436             :              * we must not have cleaned out its index entries.
    3437             :              */
    3438        2696 :             if (ItemIdIsUsed(itemid))
    3439             :             {
    3440           6 :                 hastup = true;
    3441           6 :                 break;          /* can stop scanning */
    3442             :             }
    3443             :         }                       /* scan along page */
    3444             : 
    3445        2390 :         UnlockReleaseBuffer(buf);
    3446             : 
    3447             :         /* Done scanning if we found a tuple here */
    3448        2390 :         if (hastup)
    3449           6 :             return blkno + 1;
    3450             :     }
    3451             : 
    3452             :     /*
    3453             :      * If we fall out of the loop, all the previously-thought-to-be-empty
    3454             :      * pages still are; we need not bother to look at the last known-nonempty
    3455             :      * page.
    3456             :      */
    3457         274 :     return vacrel->nonempty_pages;
    3458             : }
    3459             : 
    3460             : /*
    3461             :  * Allocate dead_items and dead_items_info (either using palloc, or in dynamic
    3462             :  * shared memory). Sets both in vacrel for caller.
    3463             :  *
    3464             :  * Also handles parallel initialization as part of allocating dead_items in
    3465             :  * DSM when required.
    3466             :  */
    3467             : static void
    3468      238900 : dead_items_alloc(LVRelState *vacrel, int nworkers)
    3469             : {
    3470             :     VacDeadItemsInfo *dead_items_info;
    3471      690738 :     int         vac_work_mem = AmAutoVacuumWorkerProcess() &&
    3472      212938 :         autovacuum_work_mem != -1 ?
    3473      451838 :         autovacuum_work_mem : maintenance_work_mem;
    3474             : 
    3475             :     /*
    3476             :      * Initialize state for a parallel vacuum.  As of now, only one worker can
    3477             :      * be used for an index, so we invoke parallelism only if there are at
    3478             :      * least two indexes on a table.
    3479             :      */
    3480      238900 :     if (nworkers >= 0 && vacrel->nindexes > 1 && vacrel->do_index_vacuuming)
    3481             :     {
    3482             :         /*
    3483             :          * Since parallel workers cannot access data in temporary tables, we
    3484             :          * can't perform parallel vacuum on them.
    3485             :          */
    3486       10296 :         if (RelationUsesLocalBuffers(vacrel->rel))
    3487             :         {
    3488             :             /*
    3489             :              * Give warning only if the user explicitly tries to perform a
    3490             :              * parallel vacuum on the temporary table.
    3491             :              */
    3492           6 :             if (nworkers > 0)
    3493           6 :                 ereport(WARNING,
    3494             :                         (errmsg("disabling parallel option of vacuum on \"%s\" --- cannot vacuum temporary tables in parallel",
    3495             :                                 vacrel->relname)));
    3496             :         }
    3497             :         else
    3498       10290 :             vacrel->pvs = parallel_vacuum_init(vacrel->rel, vacrel->indrels,
    3499             :                                                vacrel->nindexes, nworkers,
    3500             :                                                vac_work_mem,
    3501       10290 :                                                vacrel->verbose ? INFO : DEBUG2,
    3502             :                                                vacrel->bstrategy);
    3503             : 
    3504             :         /*
    3505             :          * If parallel mode started, dead_items and dead_items_info spaces are
    3506             :          * allocated in DSM.
    3507             :          */
    3508       10296 :         if (ParallelVacuumIsActive(vacrel))
    3509             :         {
    3510          34 :             vacrel->dead_items = parallel_vacuum_get_dead_items(vacrel->pvs,
    3511             :                                                                 &vacrel->dead_items_info);
    3512          34 :             return;
    3513             :         }
    3514             :     }
    3515             : 
    3516             :     /*
    3517             :      * Serial VACUUM case. Allocate both dead_items and dead_items_info
    3518             :      * locally.
    3519             :      */
    3520             : 
    3521      238866 :     dead_items_info = (VacDeadItemsInfo *) palloc(sizeof(VacDeadItemsInfo));
    3522      238866 :     dead_items_info->max_bytes = vac_work_mem * (Size) 1024;
    3523      238866 :     dead_items_info->num_items = 0;
    3524      238866 :     vacrel->dead_items_info = dead_items_info;
    3525             : 
    3526      238866 :     vacrel->dead_items = TidStoreCreateLocal(dead_items_info->max_bytes, true);
    3527             : }
    3528             : 
    3529             : /*
    3530             :  * Add the given block number and offset numbers to dead_items.
    3531             :  */
    3532             : static void
    3533       29852 : dead_items_add(LVRelState *vacrel, BlockNumber blkno, OffsetNumber *offsets,
    3534             :                int num_offsets)
    3535             : {
    3536       29852 :     const int   prog_index[2] = {
    3537             :         PROGRESS_VACUUM_NUM_DEAD_ITEM_IDS,
    3538             :         PROGRESS_VACUUM_DEAD_TUPLE_BYTES
    3539             :     };
    3540             :     int64       prog_val[2];
    3541             : 
    3542       29852 :     TidStoreSetBlockOffsets(vacrel->dead_items, blkno, offsets, num_offsets);
    3543       29852 :     vacrel->dead_items_info->num_items += num_offsets;
    3544             : 
    3545             :     /* update the progress information */
    3546       29852 :     prog_val[0] = vacrel->dead_items_info->num_items;
    3547       29852 :     prog_val[1] = TidStoreMemoryUsage(vacrel->dead_items);
    3548       29852 :     pgstat_progress_update_multi_param(2, prog_index, prog_val);
    3549       29852 : }
    3550             : 
    3551             : /*
    3552             :  * Forget all collected dead items.
    3553             :  */
    3554             : static void
    3555        1294 : dead_items_reset(LVRelState *vacrel)
    3556             : {
    3557        1294 :     if (ParallelVacuumIsActive(vacrel))
    3558             :     {
    3559          12 :         parallel_vacuum_reset_dead_items(vacrel->pvs);
    3560          12 :         return;
    3561             :     }
    3562             : 
    3563             :     /* Recreate the tidstore with the same max_bytes limitation */
    3564        1282 :     TidStoreDestroy(vacrel->dead_items);
    3565        1282 :     vacrel->dead_items = TidStoreCreateLocal(vacrel->dead_items_info->max_bytes, true);
    3566             : 
    3567             :     /* Reset the counter */
    3568        1282 :     vacrel->dead_items_info->num_items = 0;
    3569             : }
    3570             : 
    3571             : /*
    3572             :  * Perform cleanup for resources allocated in dead_items_alloc
    3573             :  */
    3574             : static void
    3575      238900 : dead_items_cleanup(LVRelState *vacrel)
    3576             : {
    3577      238900 :     if (!ParallelVacuumIsActive(vacrel))
    3578             :     {
    3579             :         /* Don't bother with pfree here */
    3580      238866 :         return;
    3581             :     }
    3582             : 
    3583             :     /* End parallel mode */
    3584          34 :     parallel_vacuum_end(vacrel->pvs, vacrel->indstats);
    3585          34 :     vacrel->pvs = NULL;
    3586             : }
    3587             : 
    3588             : /*
    3589             :  * Check if every tuple in the given page is visible to all current and future
    3590             :  * transactions. Also return the visibility_cutoff_xid which is the highest
    3591             :  * xmin amongst the visible tuples.  Set *all_frozen to true if every tuple
    3592             :  * on this page is frozen.
    3593             :  *
    3594             :  * This is a stripped down version of lazy_scan_prune().  If you change
    3595             :  * anything here, make sure that everything stays in sync.  Note that an
    3596             :  * assertion calls us to verify that everybody still agrees.  Be sure to avoid
    3597             :  * introducing new side-effects here.
    3598             :  */
    3599             : static bool
    3600       25228 : heap_page_is_all_visible(LVRelState *vacrel, Buffer buf,
    3601             :                          TransactionId *visibility_cutoff_xid,
    3602             :                          bool *all_frozen)
    3603             : {
    3604       25228 :     Page        page = BufferGetPage(buf);
    3605       25228 :     BlockNumber blockno = BufferGetBlockNumber(buf);
    3606             :     OffsetNumber offnum,
    3607             :                 maxoff;
    3608       25228 :     bool        all_visible = true;
    3609             : 
    3610       25228 :     *visibility_cutoff_xid = InvalidTransactionId;
    3611       25228 :     *all_frozen = true;
    3612             : 
    3613       25228 :     maxoff = PageGetMaxOffsetNumber(page);
    3614       25228 :     for (offnum = FirstOffsetNumber;
    3615     1246106 :          offnum <= maxoff && all_visible;
    3616     1220878 :          offnum = OffsetNumberNext(offnum))
    3617             :     {
    3618             :         ItemId      itemid;
    3619             :         HeapTupleData tuple;
    3620             : 
    3621             :         /*
    3622             :          * Set the offset number so that we can display it along with any
    3623             :          * error that occurred while processing this tuple.
    3624             :          */
    3625     1220878 :         vacrel->offnum = offnum;
    3626     1220878 :         itemid = PageGetItemId(page, offnum);
    3627             : 
    3628             :         /* Unused or redirect line pointers are of no interest */
    3629     1220878 :         if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
    3630      320926 :             continue;
    3631             : 
    3632      899952 :         ItemPointerSet(&(tuple.t_self), blockno, offnum);
    3633             : 
    3634             :         /*
    3635             :          * Dead line pointers can have index pointers pointing to them. So
    3636             :          * they can't be treated as visible
    3637             :          */
    3638      899952 :         if (ItemIdIsDead(itemid))
    3639             :         {
    3640           0 :             all_visible = false;
    3641           0 :             *all_frozen = false;
    3642           0 :             break;
    3643             :         }
    3644             : 
    3645             :         Assert(ItemIdIsNormal(itemid));
    3646             : 
    3647      899952 :         tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
    3648      899952 :         tuple.t_len = ItemIdGetLength(itemid);
    3649      899952 :         tuple.t_tableOid = RelationGetRelid(vacrel->rel);
    3650             : 
    3651      899952 :         switch (HeapTupleSatisfiesVacuum(&tuple, vacrel->cutoffs.OldestXmin,
    3652             :                                          buf))
    3653             :         {
    3654      899762 :             case HEAPTUPLE_LIVE:
    3655             :                 {
    3656             :                     TransactionId xmin;
    3657             : 
    3658             :                     /* Check comments in lazy_scan_prune. */
    3659      899762 :                     if (!HeapTupleHeaderXminCommitted(tuple.t_data))
    3660             :                     {
    3661           0 :                         all_visible = false;
    3662           0 :                         *all_frozen = false;
    3663           0 :                         break;
    3664             :                     }
    3665             : 
    3666             :                     /*
    3667             :                      * The inserter definitely committed. But is it old enough
    3668             :                      * that everyone sees it as committed?
    3669             :                      */
    3670      899762 :                     xmin = HeapTupleHeaderGetXmin(tuple.t_data);
    3671      899762 :                     if (!TransactionIdPrecedes(xmin,
    3672             :                                                vacrel->cutoffs.OldestXmin))
    3673             :                     {
    3674         100 :                         all_visible = false;
    3675         100 :                         *all_frozen = false;
    3676         100 :                         break;
    3677             :                     }
    3678             : 
    3679             :                     /* Track newest xmin on page. */
    3680      899662 :                     if (TransactionIdFollows(xmin, *visibility_cutoff_xid) &&
    3681             :                         TransactionIdIsNormal(xmin))
    3682       16048 :                         *visibility_cutoff_xid = xmin;
    3683             : 
    3684             :                     /* Check whether this tuple is already frozen or not */
    3685     1181904 :                     if (all_visible && *all_frozen &&
    3686      282242 :                         heap_tuple_needs_eventual_freeze(tuple.t_data))
    3687        4986 :                         *all_frozen = false;
    3688             :                 }
    3689      899662 :                 break;
    3690             : 
    3691         190 :             case HEAPTUPLE_DEAD:
    3692             :             case HEAPTUPLE_RECENTLY_DEAD:
    3693             :             case HEAPTUPLE_INSERT_IN_PROGRESS:
    3694             :             case HEAPTUPLE_DELETE_IN_PROGRESS:
    3695             :                 {
    3696         190 :                     all_visible = false;
    3697         190 :                     *all_frozen = false;
    3698         190 :                     break;
    3699             :                 }
    3700           0 :             default:
    3701           0 :                 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
    3702             :                 break;
    3703             :         }
    3704             :     }                           /* scan along page */
    3705             : 
    3706             :     /* Clear the offset information once we have processed the given page. */
    3707       25228 :     vacrel->offnum = InvalidOffsetNumber;
    3708             : 
    3709       25228 :     return all_visible;
    3710             : }
    3711             : 
    3712             : /*
    3713             :  * Update index statistics in pg_class if the statistics are accurate.
    3714             :  */
    3715             : static void
    3716      175776 : update_relstats_all_indexes(LVRelState *vacrel)
    3717             : {
    3718      175776 :     Relation   *indrels = vacrel->indrels;
    3719      175776 :     int         nindexes = vacrel->nindexes;
    3720      175776 :     IndexBulkDeleteResult **indstats = vacrel->indstats;
    3721             : 
    3722             :     Assert(vacrel->do_index_cleanup);
    3723             : 
    3724      439238 :     for (int idx = 0; idx < nindexes; idx++)
    3725             :     {
    3726      263462 :         Relation    indrel = indrels[idx];
    3727      263462 :         IndexBulkDeleteResult *istat = indstats[idx];
    3728             : 
    3729      263462 :         if (istat == NULL || istat->estimated_count)
    3730      260772 :             continue;
    3731             : 
    3732             :         /* Update index statistics */
    3733        2690 :         vac_update_relstats(indrel,
    3734             :                             istat->num_pages,
    3735             :                             istat->num_index_tuples,
    3736             :                             0, 0,
    3737             :                             false,
    3738             :                             InvalidTransactionId,
    3739             :                             InvalidMultiXactId,
    3740             :                             NULL, NULL, false);
    3741             :     }
    3742      175776 : }
    3743             : 
    3744             : /*
    3745             :  * Error context callback for errors occurring during vacuum.  The error
    3746             :  * context messages for index phases should match the messages set in parallel
    3747             :  * vacuum.  If you change this function for those phases, change
    3748             :  * parallel_vacuum_error_callback() as well.
    3749             :  */
    3750             : static void
    3751      236764 : vacuum_error_callback(void *arg)
    3752             : {
    3753      236764 :     LVRelState *errinfo = arg;
    3754             : 
    3755      236764 :     switch (errinfo->phase)
    3756             :     {
    3757           0 :         case VACUUM_ERRCB_PHASE_SCAN_HEAP:
    3758           0 :             if (BlockNumberIsValid(errinfo->blkno))
    3759             :             {
    3760           0 :                 if (OffsetNumberIsValid(errinfo->offnum))
    3761           0 :                     errcontext("while scanning block %u offset %u of relation \"%s.%s\"",
    3762           0 :                                errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
    3763             :                 else
    3764           0 :                     errcontext("while scanning block %u of relation \"%s.%s\"",
    3765             :                                errinfo->blkno, errinfo->relnamespace, errinfo->relname);
    3766             :             }
    3767             :             else
    3768           0 :                 errcontext("while scanning relation \"%s.%s\"",
    3769             :                            errinfo->relnamespace, errinfo->relname);
    3770           0 :             break;
    3771             : 
    3772           0 :         case VACUUM_ERRCB_PHASE_VACUUM_HEAP:
    3773           0 :             if (BlockNumberIsValid(errinfo->blkno))
    3774             :             {
    3775           0 :                 if (OffsetNumberIsValid(errinfo->offnum))
    3776           0 :                     errcontext("while vacuuming block %u offset %u of relation \"%s.%s\"",
    3777           0 :                                errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
    3778             :                 else
    3779           0 :                     errcontext("while vacuuming block %u of relation \"%s.%s\"",
    3780             :                                errinfo->blkno, errinfo->relnamespace, errinfo->relname);
    3781             :             }
    3782             :             else
    3783           0 :                 errcontext("while vacuuming relation \"%s.%s\"",
    3784             :                            errinfo->relnamespace, errinfo->relname);
    3785           0 :             break;
    3786             : 
    3787           0 :         case VACUUM_ERRCB_PHASE_VACUUM_INDEX:
    3788           0 :             errcontext("while vacuuming index \"%s\" of relation \"%s.%s\"",
    3789             :                        errinfo->indname, errinfo->relnamespace, errinfo->relname);
    3790           0 :             break;
    3791             : 
    3792           0 :         case VACUUM_ERRCB_PHASE_INDEX_CLEANUP:
    3793           0 :             errcontext("while cleaning up index \"%s\" of relation \"%s.%s\"",
    3794             :                        errinfo->indname, errinfo->relnamespace, errinfo->relname);
    3795           0 :             break;
    3796             : 
    3797           6 :         case VACUUM_ERRCB_PHASE_TRUNCATE:
    3798           6 :             if (BlockNumberIsValid(errinfo->blkno))
    3799           6 :                 errcontext("while truncating relation \"%s.%s\" to %u blocks",
    3800             :                            errinfo->relnamespace, errinfo->relname, errinfo->blkno);
    3801           6 :             break;
    3802             : 
    3803      236758 :         case VACUUM_ERRCB_PHASE_UNKNOWN:
    3804             :         default:
    3805      236758 :             return;             /* do nothing; the errinfo may not be
    3806             :                                  * initialized */
    3807             :     }
    3808             : }
    3809             : 
    3810             : /*
    3811             :  * Updates the information required for vacuum error callback.  This also saves
    3812             :  * the current information which can be later restored via restore_vacuum_error_info.
    3813             :  */
    3814             : static void
    3815     1170276 : update_vacuum_error_info(LVRelState *vacrel, LVSavedErrInfo *saved_vacrel,
    3816             :                          int phase, BlockNumber blkno, OffsetNumber offnum)
    3817             : {
    3818     1170276 :     if (saved_vacrel)
    3819             :     {
    3820      292246 :         saved_vacrel->offnum = vacrel->offnum;
    3821      292246 :         saved_vacrel->blkno = vacrel->blkno;
    3822      292246 :         saved_vacrel->phase = vacrel->phase;
    3823             :     }
    3824             : 
    3825     1170276 :     vacrel->blkno = blkno;
    3826     1170276 :     vacrel->offnum = offnum;
    3827     1170276 :     vacrel->phase = phase;
    3828     1170276 : }
    3829             : 
    3830             : /*
    3831             :  * Restores the vacuum information saved via a prior call to update_vacuum_error_info.
    3832             :  */
    3833             : static void
    3834      292246 : restore_vacuum_error_info(LVRelState *vacrel,
    3835             :                           const LVSavedErrInfo *saved_vacrel)
    3836             : {
    3837      292246 :     vacrel->blkno = saved_vacrel->blkno;
    3838      292246 :     vacrel->offnum = saved_vacrel->offnum;
    3839      292246 :     vacrel->phase = saved_vacrel->phase;
    3840      292246 : }

Generated by: LCOV version 1.16