LCOV - code coverage report
Current view: top level - src/backend/access/heap - vacuumlazy.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 833 968 86.1 %
Date: 2025-07-19 06:18:44 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             :                                          const 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 int  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      245382 : heap_vacuum_eager_scan_setup(LVRelState *vacrel, const VacuumParams params)
     489             : {
     490             :     uint32      randseed;
     491             :     BlockNumber allvisible;
     492             :     BlockNumber allfrozen;
     493             :     float       first_region_ratio;
     494      245382 :     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      245382 :     vacrel->next_eager_scan_region_start = InvalidBlockNumber;
     502      245382 :     vacrel->eager_scan_max_fails_per_region = 0;
     503      245382 :     vacrel->eager_scan_remaining_fails = 0;
     504      245382 :     vacrel->eager_scan_remaining_successes = 0;
     505             : 
     506             :     /* If eager scanning is explicitly disabled, just return. */
     507      245382 :     if (params.max_eager_freeze_failure_rate == 0)
     508      245382 :         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      245382 :     if (vacrel->aggressive)
     518      234608 :         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       10774 :     if (vacrel->rel_pages < 2 * EAGER_SCAN_REGION_SIZE)
     528       10774 :         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      245382 : heap_vacuum_rel(Relation rel, const 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      245382 :     TimestampTz starttime = 0;
     630      245382 :     PgStat_Counter startreadtime = 0,
     631      245382 :                 startwritetime = 0;
     632      245382 :     WalUsage    startwalusage = pgWalUsage;
     633      245382 :     BufferUsage startbufferusage = pgBufferUsage;
     634             :     ErrorContextCallback errcallback;
     635      245382 :     char      **indnames = NULL;
     636             : 
     637      245382 :     verbose = (params.options & VACOPT_VERBOSE) != 0;
     638      464576 :     instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
     639      219194 :                               params.log_min_duration >= 0));
     640      245382 :     if (instrument)
     641             :     {
     642      219214 :         pg_rusage_init(&ru0);
     643      219214 :         if (track_io_timing)
     644             :         {
     645           0 :             startreadtime = pgStatBlockReadTime;
     646           0 :             startwritetime = pgStatBlockWriteTime;
     647             :         }
     648             :     }
     649             : 
     650             :     /* Used for instrumentation and stats report */
     651      245382 :     starttime = GetCurrentTimestamp();
     652             : 
     653      245382 :     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      245382 :     vacrel = (LVRelState *) palloc0(sizeof(LVRelState));
     669      245382 :     vacrel->dbname = get_database_name(MyDatabaseId);
     670      245382 :     vacrel->relnamespace = get_namespace_name(RelationGetNamespace(rel));
     671      245382 :     vacrel->relname = pstrdup(RelationGetRelationName(rel));
     672      245382 :     vacrel->indname = NULL;
     673      245382 :     vacrel->phase = VACUUM_ERRCB_PHASE_UNKNOWN;
     674      245382 :     vacrel->verbose = verbose;
     675      245382 :     errcallback.callback = vacuum_error_callback;
     676      245382 :     errcallback.arg = vacrel;
     677      245382 :     errcallback.previous = error_context_stack;
     678      245382 :     error_context_stack = &errcallback;
     679             : 
     680             :     /* Set up high level stuff about rel and its indexes */
     681      245382 :     vacrel->rel = rel;
     682      245382 :     vac_open_indexes(vacrel->rel, RowExclusiveLock, &vacrel->nindexes,
     683             :                      &vacrel->indrels);
     684      245382 :     vacrel->bstrategy = bstrategy;
     685      245382 :     if (instrument && vacrel->nindexes > 0)
     686             :     {
     687             :         /* Copy index names used by instrumentation (not error reporting) */
     688      209586 :         indnames = palloc(sizeof(char *) * vacrel->nindexes);
     689      540056 :         for (int i = 0; i < vacrel->nindexes; i++)
     690      330470 :             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      245382 :     VacuumFailsafeActive = false;
     711      245382 :     vacrel->consider_bypass_optimization = true;
     712      245382 :     vacrel->do_index_vacuuming = true;
     713      245382 :     vacrel->do_index_cleanup = true;
     714      245382 :     vacrel->do_rel_truncate = (params.truncate != VACOPTVALUE_DISABLED);
     715      245382 :     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      245122 :     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      245382 :     vacrel->scanned_pages = 0;
     734      245382 :     vacrel->eager_scanned_pages = 0;
     735      245382 :     vacrel->removed_pages = 0;
     736      245382 :     vacrel->new_frozen_tuple_pages = 0;
     737      245382 :     vacrel->lpdead_item_pages = 0;
     738      245382 :     vacrel->missed_dead_pages = 0;
     739      245382 :     vacrel->nonempty_pages = 0;
     740             :     /* dead_items_alloc allocates vacrel->dead_items later on */
     741             : 
     742             :     /* Allocate/initialize output statistics state */
     743      245382 :     vacrel->new_rel_tuples = 0;
     744      245382 :     vacrel->new_live_tuples = 0;
     745      245382 :     vacrel->indstats = (IndexBulkDeleteResult **)
     746      245382 :         palloc0(vacrel->nindexes * sizeof(IndexBulkDeleteResult *));
     747             : 
     748             :     /* Initialize remaining counters (be tidy) */
     749      245382 :     vacrel->num_index_scans = 0;
     750      245382 :     vacrel->tuples_deleted = 0;
     751      245382 :     vacrel->tuples_frozen = 0;
     752      245382 :     vacrel->lpdead_items = 0;
     753      245382 :     vacrel->live_tuples = 0;
     754      245382 :     vacrel->recently_dead_tuples = 0;
     755      245382 :     vacrel->missed_dead_tuples = 0;
     756             : 
     757      245382 :     vacrel->vm_new_visible_pages = 0;
     758      245382 :     vacrel->vm_new_visible_frozen_pages = 0;
     759      245382 :     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      245382 :     vacrel->aggressive = vacuum_get_cutoffs(rel, params, &vacrel->cutoffs);
     778      245382 :     vacrel->rel_pages = orig_rel_pages = RelationGetNumberOfBlocks(rel);
     779      245382 :     vacrel->vistest = GlobalVisTestFor(rel);
     780             : 
     781             :     /* Initialize state used to track oldest extant XID/MXID */
     782      245382 :     vacrel->NewRelfrozenXid = vacrel->cutoffs.OldestXmin;
     783      245382 :     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      245382 :     vacrel->skippedallvis = false;
     791      245382 :     skipwithvm = true;
     792      245382 :     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      245382 :     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      245382 :     heap_vacuum_eager_scan_setup(vacrel, params);
     810             : 
     811      245382 :     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      245382 :     lazy_check_wraparound_failsafe(vacrel);
     833      245382 :     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      245382 :     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      245382 :     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      245382 :     if (vacrel->do_index_cleanup)
     855      177494 :         update_relstats_all_indexes(vacrel);
     856             : 
     857             :     /* Done with rel's indexes */
     858      245382 :     vac_close_indexes(vacrel->nindexes, vacrel->indrels, NoLock);
     859             : 
     860             :     /* Optionally truncate rel */
     861      245382 :     if (should_attempt_truncation(vacrel))
     862         330 :         lazy_truncate_heap(vacrel);
     863             : 
     864             :     /* Pop the error context stack */
     865      245382 :     error_context_stack = errcallback.previous;
     866             : 
     867             :     /* Report that we are now doing final cleanup */
     868      245382 :     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      245382 :     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          70 :         vacrel->NewRelfrozenXid = InvalidTransactionId;
     895          70 :         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      245382 :     new_rel_pages = vacrel->rel_pages;   /* After possible rel truncation */
     903      245382 :     visibilitymap_count(rel, &new_rel_allvisible, &new_rel_allfrozen);
     904      245382 :     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      245382 :     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      245382 :     vac_update_relstats(rel, new_rel_pages, vacrel->new_live_tuples,
     923             :                         new_rel_allvisible, new_rel_allfrozen,
     924      245382 :                         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      147364 :     pgstat_report_vacuum(RelationGetRelid(rel),
     939      245382 :                          rel->rd_rel->relisshared,
     940       98018 :                          Max(vacrel->new_live_tuples, 0),
     941      245382 :                          vacrel->recently_dead_tuples +
     942      245382 :                          vacrel->missed_dead_tuples,
     943             :                          starttime);
     944      245382 :     pgstat_progress_end_command();
     945             : 
     946      245382 :     if (instrument)
     947             :     {
     948      219214 :         TimestampTz endtime = GetCurrentTimestamp();
     949             : 
     950      219496 :         if (verbose || params.log_min_duration == 0 ||
     951         282 :             TimestampDifferenceExceeds(starttime, endtime,
     952         282 :                                        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      218932 :             double      read_rate = 0,
     962      218932 :                         write_rate = 0;
     963             :             int64       total_blks_hit;
     964             :             int64       total_blks_read;
     965             :             int64       total_blks_dirtied;
     966             : 
     967      218932 :             TimestampDifference(starttime, endtime, &secs_dur, &usecs_dur);
     968      218932 :             memset(&walusage, 0, sizeof(WalUsage));
     969      218932 :             WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
     970      218932 :             memset(&bufferusage, 0, sizeof(BufferUsage));
     971      218932 :             BufferUsageAccumDiff(&bufferusage, &pgBufferUsage, &startbufferusage);
     972             : 
     973      218932 :             total_blks_hit = bufferusage.shared_blks_hit +
     974      218932 :                 bufferusage.local_blks_hit;
     975      218932 :             total_blks_read = bufferusage.shared_blks_read +
     976      218932 :                 bufferusage.local_blks_read;
     977      218932 :             total_blks_dirtied = bufferusage.shared_blks_dirtied +
     978      218932 :                 bufferusage.local_blks_dirtied;
     979             : 
     980      218932 :             initStringInfo(&buf);
     981      218932 :             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      218912 :             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      218874 :                 if (vacrel->aggressive)
     999      218858 :                     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          38 :                 if (vacrel->aggressive)
    1006          30 :                     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      218932 :             appendStringInfo(&buf, msgfmt,
    1011             :                              vacrel->dbname,
    1012             :                              vacrel->relnamespace,
    1013             :                              vacrel->relname,
    1014             :                              vacrel->num_index_scans);
    1015      305898 :             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       86966 :                              100.0 * vacrel->scanned_pages /
    1021             :                              orig_rel_pages,
    1022             :                              vacrel->eager_scanned_pages);
    1023      218932 :             appendStringInfo(&buf,
    1024      218932 :                              _("tuples: %" PRId64 " removed, %" PRId64 " remain, %" PRId64 " are dead but not yet removable\n"),
    1025             :                              vacrel->tuples_deleted,
    1026      218932 :                              (int64) vacrel->new_rel_tuples,
    1027             :                              vacrel->recently_dead_tuples);
    1028      218932 :             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      218932 :             diff = (int32) (ReadNextTransactionId() -
    1034      218932 :                             vacrel->cutoffs.OldestXmin);
    1035      218932 :             appendStringInfo(&buf,
    1036      218932 :                              _("removable cutoff: %u, which was %d XIDs old when operation ended\n"),
    1037             :                              vacrel->cutoffs.OldestXmin, diff);
    1038      218932 :             if (frozenxid_updated)
    1039             :             {
    1040       39704 :                 diff = (int32) (vacrel->NewRelfrozenXid -
    1041       39704 :                                 vacrel->cutoffs.relfrozenxid);
    1042       39704 :                 appendStringInfo(&buf,
    1043       39704 :                                  _("new relfrozenxid: %u, which is %d XIDs ahead of previous value\n"),
    1044             :                                  vacrel->NewRelfrozenXid, diff);
    1045             :             }
    1046      218932 :             if (minmulti_updated)
    1047             :             {
    1048           8 :                 diff = (int32) (vacrel->NewRelminMxid -
    1049           8 :                                 vacrel->cutoffs.relminmxid);
    1050           8 :                 appendStringInfo(&buf,
    1051           8 :                                  _("new relminmxid: %u, which is %d MXIDs ahead of previous value\n"),
    1052             :                                  vacrel->NewRelminMxid, diff);
    1053             :             }
    1054      305898 :             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       86966 :                              100.0 * vacrel->new_frozen_tuple_pages /
    1058             :                              orig_rel_pages,
    1059             :                              vacrel->tuples_frozen);
    1060             : 
    1061      218932 :             appendStringInfo(&buf,
    1062      218932 :                              _("visibility map: %u pages set all-visible, %u pages set all-frozen (%u were all-visible)\n"),
    1063             :                              vacrel->vm_new_visible_pages,
    1064      218932 :                              vacrel->vm_new_visible_frozen_pages +
    1065      218932 :                              vacrel->vm_new_frozen_pages,
    1066             :                              vacrel->vm_new_frozen_pages);
    1067      218932 :             if (vacrel->do_index_vacuuming)
    1068             :             {
    1069      151522 :                 if (vacrel->nindexes == 0 || vacrel->num_index_scans == 0)
    1070      151492 :                     appendStringInfoString(&buf, _("index scan not needed: "));
    1071             :                 else
    1072          30 :                     appendStringInfoString(&buf, _("index scan needed: "));
    1073             : 
    1074      151522 :                 msgfmt = _("%u pages from table (%.2f%% of total) had %" PRId64 " dead item identifiers removed\n");
    1075             :             }
    1076             :             else
    1077             :             {
    1078       67410 :                 if (!VacuumFailsafeActive)
    1079           0 :                     appendStringInfoString(&buf, _("index scan bypassed: "));
    1080             :                 else
    1081       67410 :                     appendStringInfoString(&buf, _("index scan bypassed by failsafe: "));
    1082             : 
    1083       67410 :                 msgfmt = _("%u pages from table (%.2f%% of total) have %" PRId64 " dead item identifiers\n");
    1084             :             }
    1085      305898 :             appendStringInfo(&buf, msgfmt,
    1086             :                              vacrel->lpdead_item_pages,
    1087             :                              orig_rel_pages == 0 ? 100.0 :
    1088       86966 :                              100.0 * vacrel->lpdead_item_pages / orig_rel_pages,
    1089             :                              vacrel->lpdead_items);
    1090      548896 :             for (int i = 0; i < vacrel->nindexes; i++)
    1091             :             {
    1092      329964 :                 IndexBulkDeleteResult *istat = vacrel->indstats[i];
    1093             : 
    1094      329964 :                 if (!istat)
    1095      329914 :                     continue;
    1096             : 
    1097          50 :                 appendStringInfo(&buf,
    1098          50 :                                  _("index \"%s\": pages: %u in total, %u newly deleted, %u currently deleted, %u reusable\n"),
    1099          50 :                                  indnames[i],
    1100             :                                  istat->num_pages,
    1101             :                                  istat->pages_newly_deleted,
    1102             :                                  istat->pages_deleted,
    1103             :                                  istat->pages_free);
    1104             :             }
    1105      218932 :             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      218932 :             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      218932 :             if (secs_dur > 0 || usecs_dur > 0)
    1125             :             {
    1126      218932 :                 read_rate = (double) BLCKSZ * total_blks_read /
    1127      218932 :                     (1024 * 1024) / (secs_dur + usecs_dur / 1000000.0);
    1128      218932 :                 write_rate = (double) BLCKSZ * total_blks_dirtied /
    1129      218932 :                     (1024 * 1024) / (secs_dur + usecs_dur / 1000000.0);
    1130             :             }
    1131      218932 :             appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
    1132             :                              read_rate, write_rate);
    1133      218932 :             appendStringInfo(&buf,
    1134      218932 :                              _("buffer usage: %" PRId64 " hits, %" PRId64 " reads, %" PRId64 " dirtied\n"),
    1135             :                              total_blks_hit,
    1136             :                              total_blks_read,
    1137             :                              total_blks_dirtied);
    1138      218932 :             appendStringInfo(&buf,
    1139      218932 :                              _("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      218932 :             appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
    1145             : 
    1146      218932 :             ereport(verbose ? INFO : LOG,
    1147             :                     (errmsg_internal("%s", buf.data)));
    1148      218930 :             pfree(buf.data);
    1149             :         }
    1150             :     }
    1151             : 
    1152             :     /* Cleanup index statistics and index names */
    1153      613382 :     for (int i = 0; i < vacrel->nindexes; i++)
    1154             :     {
    1155      368002 :         if (vacrel->indstats[i])
    1156        2826 :             pfree(vacrel->indstats[i]);
    1157             : 
    1158      368002 :         if (instrument)
    1159      330468 :             pfree(indnames[i]);
    1160             :     }
    1161      245380 : }
    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      245382 : lazy_scan_heap(LVRelState *vacrel)
    1201             : {
    1202             :     ReadStream *stream;
    1203      245382 :     BlockNumber rel_pages = vacrel->rel_pages,
    1204      245382 :                 blkno = 0,
    1205      245382 :                 next_fsm_block_to_vacuum = 0;
    1206      245382 :     BlockNumber orig_eager_scan_success_limit =
    1207             :         vacrel->eager_scan_remaining_successes; /* for logging */
    1208      245382 :     Buffer      vmbuffer = InvalidBuffer;
    1209      245382 :     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      245382 :     initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
    1218      245382 :     initprog_val[1] = rel_pages;
    1219      245382 :     initprog_val[2] = vacrel->dead_items_info->max_bytes;
    1220      245382 :     pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
    1221             : 
    1222             :     /* Initialize for the first heap_vac_scan_next_block() call */
    1223      245382 :     vacrel->current_block = InvalidBlockNumber;
    1224      245382 :     vacrel->next_unskippable_block = InvalidBlockNumber;
    1225      245382 :     vacrel->next_unskippable_allvis = false;
    1226      245382 :     vacrel->next_unskippable_eager_scanned = false;
    1227      245382 :     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      245382 :     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      881364 :     {
    1245             :         Buffer      buf;
    1246             :         Page        page;
    1247     1126746 :         uint8       blk_info = 0;
    1248     1126746 :         int         ndeleted = 0;
    1249             :         bool        has_lpdead_items;
    1250     1126746 :         void       *per_buffer_data = NULL;
    1251     1126746 :         bool        vm_page_frozen = false;
    1252     1126746 :         bool        got_cleanup_lock = false;
    1253             : 
    1254     1126746 :         vacuum_delay_point(false);
    1255             : 
    1256             :         /*
    1257             :          * Regularly check if wraparound failsafe should trigger.
    1258             :          *
    1259             :          * There is a similar check inside lazy_vacuum_all_indexes(), but
    1260             :          * relfrozenxid might start to look dangerously old before we reach
    1261             :          * that point.  This check also provides failsafe coverage for the
    1262             :          * one-pass strategy, and the two-pass strategy with the index_cleanup
    1263             :          * param set to 'off'.
    1264             :          */
    1265     1126746 :         if (vacrel->scanned_pages > 0 &&
    1266      881364 :             vacrel->scanned_pages % FAILSAFE_EVERY_PAGES == 0)
    1267           0 :             lazy_check_wraparound_failsafe(vacrel);
    1268             : 
    1269             :         /*
    1270             :          * Consider if we definitely have enough space to process TIDs on page
    1271             :          * already.  If we are close to overrunning the available space for
    1272             :          * dead_items TIDs, pause and do a cycle of vacuuming before we tackle
    1273             :          * this page. However, let's force at least one page-worth of tuples
    1274             :          * to be stored as to ensure we do at least some work when the memory
    1275             :          * configured is so low that we run out before storing anything.
    1276             :          */
    1277     1126746 :         if (vacrel->dead_items_info->num_items > 0 &&
    1278       51976 :             TidStoreMemoryUsage(vacrel->dead_items) > vacrel->dead_items_info->max_bytes)
    1279             :         {
    1280             :             /*
    1281             :              * Before beginning index vacuuming, we release any pin we may
    1282             :              * hold on the visibility map page.  This isn't necessary for
    1283             :              * correctness, but we do it anyway to avoid holding the pin
    1284             :              * across a lengthy, unrelated operation.
    1285             :              */
    1286           4 :             if (BufferIsValid(vmbuffer))
    1287             :             {
    1288           4 :                 ReleaseBuffer(vmbuffer);
    1289           4 :                 vmbuffer = InvalidBuffer;
    1290             :             }
    1291             : 
    1292             :             /* Perform a round of index and heap vacuuming */
    1293           4 :             vacrel->consider_bypass_optimization = false;
    1294           4 :             lazy_vacuum(vacrel);
    1295             : 
    1296             :             /*
    1297             :              * Vacuum the Free Space Map to make newly-freed space visible on
    1298             :              * upper-level FSM pages. Note that blkno is the previously
    1299             :              * processed block.
    1300             :              */
    1301           4 :             FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
    1302             :                                     blkno + 1);
    1303           4 :             next_fsm_block_to_vacuum = blkno;
    1304             : 
    1305             :             /* Report that we are once again scanning the heap */
    1306           4 :             pgstat_progress_update_param(PROGRESS_VACUUM_PHASE,
    1307             :                                          PROGRESS_VACUUM_PHASE_SCAN_HEAP);
    1308             :         }
    1309             : 
    1310     1126746 :         buf = read_stream_next_buffer(stream, &per_buffer_data);
    1311             : 
    1312             :         /* The relation is exhausted. */
    1313     1126746 :         if (!BufferIsValid(buf))
    1314      245382 :             break;
    1315             : 
    1316      881364 :         blk_info = *((uint8 *) per_buffer_data);
    1317      881364 :         CheckBufferIsPinnedOnce(buf);
    1318      881364 :         page = BufferGetPage(buf);
    1319      881364 :         blkno = BufferGetBlockNumber(buf);
    1320             : 
    1321      881364 :         vacrel->scanned_pages++;
    1322      881364 :         if (blk_info & VAC_BLK_WAS_EAGER_SCANNED)
    1323           0 :             vacrel->eager_scanned_pages++;
    1324             : 
    1325             :         /* Report as block scanned, update error traceback information */
    1326      881364 :         pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno);
    1327      881364 :         update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP,
    1328             :                                  blkno, InvalidOffsetNumber);
    1329             : 
    1330             :         /*
    1331             :          * Pin the visibility map page in case we need to mark the page
    1332             :          * all-visible.  In most cases this will be very cheap, because we'll
    1333             :          * already have the correct page pinned anyway.
    1334             :          */
    1335      881364 :         visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
    1336             : 
    1337             :         /*
    1338             :          * We need a buffer cleanup lock to prune HOT chains and defragment
    1339             :          * the page in lazy_scan_prune.  But when it's not possible to acquire
    1340             :          * a cleanup lock right away, we may be able to settle for reduced
    1341             :          * processing using lazy_scan_noprune.
    1342             :          */
    1343      881364 :         got_cleanup_lock = ConditionalLockBufferForCleanup(buf);
    1344             : 
    1345      881364 :         if (!got_cleanup_lock)
    1346         268 :             LockBuffer(buf, BUFFER_LOCK_SHARE);
    1347             : 
    1348             :         /* Check for new or empty pages before lazy_scan_[no]prune call */
    1349      881364 :         if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock,
    1350      881364 :                                    vmbuffer))
    1351             :         {
    1352             :             /* Processed as new/empty page (lock and pin released) */
    1353        1960 :             continue;
    1354             :         }
    1355             : 
    1356             :         /*
    1357             :          * If we didn't get the cleanup lock, we can still collect LP_DEAD
    1358             :          * items in the dead_items area for later vacuuming, count live and
    1359             :          * recently dead tuples for vacuum logging, and determine if this
    1360             :          * block could later be truncated. If we encounter any xid/mxids that
    1361             :          * require advancing the relfrozenxid/relminxid, we'll have to wait
    1362             :          * for a cleanup lock and call lazy_scan_prune().
    1363             :          */
    1364      879404 :         if (!got_cleanup_lock &&
    1365         268 :             !lazy_scan_noprune(vacrel, buf, blkno, page, &has_lpdead_items))
    1366             :         {
    1367             :             /*
    1368             :              * lazy_scan_noprune could not do all required processing.  Wait
    1369             :              * for a cleanup lock, and call lazy_scan_prune in the usual way.
    1370             :              */
    1371             :             Assert(vacrel->aggressive);
    1372          74 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
    1373          74 :             LockBufferForCleanup(buf);
    1374          74 :             got_cleanup_lock = true;
    1375             :         }
    1376             : 
    1377             :         /*
    1378             :          * If we have a cleanup lock, we must now prune, freeze, and count
    1379             :          * tuples. We may have acquired the cleanup lock originally, or we may
    1380             :          * have gone back and acquired it after lazy_scan_noprune() returned
    1381             :          * false. Either way, the page hasn't been processed yet.
    1382             :          *
    1383             :          * Like lazy_scan_noprune(), lazy_scan_prune() will count
    1384             :          * recently_dead_tuples and live tuples for vacuum logging, determine
    1385             :          * if the block can later be truncated, and accumulate the details of
    1386             :          * remaining LP_DEAD line pointers on the page into dead_items. These
    1387             :          * dead items include those pruned by lazy_scan_prune() as well as
    1388             :          * line pointers previously marked LP_DEAD.
    1389             :          */
    1390      879404 :         if (got_cleanup_lock)
    1391      879210 :             ndeleted = lazy_scan_prune(vacrel, buf, blkno, page,
    1392             :                                        vmbuffer,
    1393      879210 :                                        blk_info & VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM,
    1394             :                                        &has_lpdead_items, &vm_page_frozen);
    1395             : 
    1396             :         /*
    1397             :          * Count an eagerly scanned page as a failure or a success.
    1398             :          *
    1399             :          * Only lazy_scan_prune() freezes pages, so if we didn't get the
    1400             :          * cleanup lock, we won't have frozen the page. However, we only count
    1401             :          * pages that were too new to require freezing as eager freeze
    1402             :          * failures.
    1403             :          *
    1404             :          * We could gather more information from lazy_scan_noprune() about
    1405             :          * whether or not there were tuples with XIDs or MXIDs older than the
    1406             :          * FreezeLimit or MultiXactCutoff. However, for simplicity, we simply
    1407             :          * exclude pages skipped due to cleanup lock contention from eager
    1408             :          * freeze algorithm caps.
    1409             :          */
    1410      879404 :         if (got_cleanup_lock &&
    1411      879210 :             (blk_info & VAC_BLK_WAS_EAGER_SCANNED))
    1412             :         {
    1413             :             /* Aggressive vacuums do not eager scan. */
    1414             :             Assert(!vacrel->aggressive);
    1415             : 
    1416           0 :             if (vm_page_frozen)
    1417             :             {
    1418           0 :                 if (vacrel->eager_scan_remaining_successes > 0)
    1419           0 :                     vacrel->eager_scan_remaining_successes--;
    1420             : 
    1421           0 :                 if (vacrel->eager_scan_remaining_successes == 0)
    1422             :                 {
    1423             :                     /*
    1424             :                      * Report only once that we disabled eager scanning. We
    1425             :                      * may eagerly read ahead blocks in excess of the success
    1426             :                      * or failure caps before attempting to freeze them, so we
    1427             :                      * could reach here even after disabling additional eager
    1428             :                      * scanning.
    1429             :                      */
    1430           0 :                     if (vacrel->eager_scan_max_fails_per_region > 0)
    1431           0 :                         ereport(vacrel->verbose ? INFO : DEBUG2,
    1432             :                                 (errmsg("disabling eager scanning after freezing %u eagerly scanned blocks of relation \"%s.%s.%s\"",
    1433             :                                         orig_eager_scan_success_limit,
    1434             :                                         vacrel->dbname, vacrel->relnamespace,
    1435             :                                         vacrel->relname)));
    1436             : 
    1437             :                     /*
    1438             :                      * If we hit our success cap, permanently disable eager
    1439             :                      * scanning by setting the other eager scan management
    1440             :                      * fields to their disabled values.
    1441             :                      */
    1442           0 :                     vacrel->eager_scan_remaining_fails = 0;
    1443           0 :                     vacrel->next_eager_scan_region_start = InvalidBlockNumber;
    1444           0 :                     vacrel->eager_scan_max_fails_per_region = 0;
    1445             :                 }
    1446             :             }
    1447           0 :             else if (vacrel->eager_scan_remaining_fails > 0)
    1448           0 :                 vacrel->eager_scan_remaining_fails--;
    1449             :         }
    1450             : 
    1451             :         /*
    1452             :          * Now drop the buffer lock and, potentially, update the FSM.
    1453             :          *
    1454             :          * Our goal is to update the freespace map the last time we touch the
    1455             :          * page. If we'll process a block in the second pass, we may free up
    1456             :          * additional space on the page, so it is better to update the FSM
    1457             :          * after the second pass. If the relation has no indexes, or if index
    1458             :          * vacuuming is disabled, there will be no second heap pass; if this
    1459             :          * particular page has no dead items, the second heap pass will not
    1460             :          * touch this page. So, in those cases, update the FSM now.
    1461             :          *
    1462             :          * Note: In corner cases, it's possible to miss updating the FSM
    1463             :          * entirely. If index vacuuming is currently enabled, we'll skip the
    1464             :          * FSM update now. But if failsafe mode is later activated, or there
    1465             :          * are so few dead tuples that index vacuuming is bypassed, there will
    1466             :          * also be no opportunity to update the FSM later, because we'll never
    1467             :          * revisit this page. Since updating the FSM is desirable but not
    1468             :          * absolutely required, that's OK.
    1469             :          */
    1470      879404 :         if (vacrel->nindexes == 0
    1471      843816 :             || !vacrel->do_index_vacuuming
    1472      625568 :             || !has_lpdead_items)
    1473      851188 :         {
    1474      851188 :             Size        freespace = PageGetHeapFreeSpace(page);
    1475             : 
    1476      851188 :             UnlockReleaseBuffer(buf);
    1477      851188 :             RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
    1478             : 
    1479             :             /*
    1480             :              * Periodically perform FSM vacuuming to make newly-freed space
    1481             :              * visible on upper FSM pages. This is done after vacuuming if the
    1482             :              * table has indexes. There will only be newly-freed space if we
    1483             :              * held the cleanup lock and lazy_scan_prune() was called.
    1484             :              */
    1485      851188 :             if (got_cleanup_lock && vacrel->nindexes == 0 && ndeleted > 0 &&
    1486         904 :                 blkno - next_fsm_block_to_vacuum >= VACUUM_FSM_EVERY_PAGES)
    1487             :             {
    1488           0 :                 FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
    1489             :                                         blkno);
    1490           0 :                 next_fsm_block_to_vacuum = blkno;
    1491             :             }
    1492             :         }
    1493             :         else
    1494       28216 :             UnlockReleaseBuffer(buf);
    1495             :     }
    1496             : 
    1497      245382 :     vacrel->blkno = InvalidBlockNumber;
    1498      245382 :     if (BufferIsValid(vmbuffer))
    1499       98182 :         ReleaseBuffer(vmbuffer);
    1500             : 
    1501             :     /*
    1502             :      * Report that everything is now scanned. We never skip scanning the last
    1503             :      * block in the relation, so we can pass rel_pages here.
    1504             :      */
    1505      245382 :     pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED,
    1506             :                                  rel_pages);
    1507             : 
    1508             :     /* now we can compute the new value for pg_class.reltuples */
    1509      490764 :     vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
    1510             :                                                      vacrel->scanned_pages,
    1511      245382 :                                                      vacrel->live_tuples);
    1512             : 
    1513             :     /*
    1514             :      * Also compute the total number of surviving heap entries.  In the
    1515             :      * (unlikely) scenario that new_live_tuples is -1, take it as zero.
    1516             :      */
    1517      245382 :     vacrel->new_rel_tuples =
    1518      245382 :         Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
    1519      245382 :         vacrel->missed_dead_tuples;
    1520             : 
    1521      245382 :     read_stream_end(stream);
    1522             : 
    1523             :     /*
    1524             :      * Do index vacuuming (call each index's ambulkdelete routine), then do
    1525             :      * related heap vacuuming
    1526             :      */
    1527      245382 :     if (vacrel->dead_items_info->num_items > 0)
    1528        1336 :         lazy_vacuum(vacrel);
    1529             : 
    1530             :     /*
    1531             :      * Vacuum the remainder of the Free Space Map.  We must do this whether or
    1532             :      * not there were indexes, and whether or not we bypassed index vacuuming.
    1533             :      * We can pass rel_pages here because we never skip scanning the last
    1534             :      * block of the relation.
    1535             :      */
    1536      245382 :     if (rel_pages > next_fsm_block_to_vacuum)
    1537       98182 :         FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, rel_pages);
    1538             : 
    1539             :     /* report all blocks vacuumed */
    1540      245382 :     pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, rel_pages);
    1541             : 
    1542             :     /* Do final index cleanup (call each index's amvacuumcleanup routine) */
    1543      245382 :     if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
    1544      168810 :         lazy_cleanup_all_indexes(vacrel);
    1545      245382 : }
    1546             : 
    1547             : /*
    1548             :  *  heap_vac_scan_next_block() -- read stream callback to get the next block
    1549             :  *  for vacuum to process
    1550             :  *
    1551             :  * Every time lazy_scan_heap() needs a new block to process during its first
    1552             :  * phase, it invokes read_stream_next_buffer() with a stream set up to call
    1553             :  * heap_vac_scan_next_block() to get the next block.
    1554             :  *
    1555             :  * heap_vac_scan_next_block() uses the visibility map, vacuum options, and
    1556             :  * various thresholds to skip blocks which do not need to be processed and
    1557             :  * returns the next block to process or InvalidBlockNumber if there are no
    1558             :  * remaining blocks.
    1559             :  *
    1560             :  * The visibility status of the next block to process and whether or not it
    1561             :  * was eager scanned is set in the per_buffer_data.
    1562             :  *
    1563             :  * callback_private_data contains a reference to the LVRelState, passed to the
    1564             :  * read stream API during stream setup. The LVRelState is an in/out parameter
    1565             :  * here (locally named `vacrel`). Vacuum options and information about the
    1566             :  * relation are read from it. vacrel->skippedallvis is set if we skip a block
    1567             :  * that's all-visible but not all-frozen (to ensure that we don't update
    1568             :  * relfrozenxid in that case). vacrel also holds information about the next
    1569             :  * unskippable block -- as bookkeeping for this function.
    1570             :  */
    1571             : static BlockNumber
    1572     1126746 : heap_vac_scan_next_block(ReadStream *stream,
    1573             :                          void *callback_private_data,
    1574             :                          void *per_buffer_data)
    1575             : {
    1576             :     BlockNumber next_block;
    1577     1126746 :     LVRelState *vacrel = callback_private_data;
    1578     1126746 :     uint8       blk_info = 0;
    1579             : 
    1580             :     /* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
    1581     1126746 :     next_block = vacrel->current_block + 1;
    1582             : 
    1583             :     /* Have we reached the end of the relation? */
    1584     1126746 :     if (next_block >= vacrel->rel_pages)
    1585             :     {
    1586      245382 :         if (BufferIsValid(vacrel->next_unskippable_vmbuffer))
    1587             :         {
    1588       95240 :             ReleaseBuffer(vacrel->next_unskippable_vmbuffer);
    1589       95240 :             vacrel->next_unskippable_vmbuffer = InvalidBuffer;
    1590             :         }
    1591      245382 :         return InvalidBlockNumber;
    1592             :     }
    1593             : 
    1594             :     /*
    1595             :      * We must be in one of the three following states:
    1596             :      */
    1597      881364 :     if (next_block > vacrel->next_unskippable_block ||
    1598      393978 :         vacrel->next_unskippable_block == InvalidBlockNumber)
    1599             :     {
    1600             :         /*
    1601             :          * 1. We have just processed an unskippable block (or we're at the
    1602             :          * beginning of the scan).  Find the next unskippable block using the
    1603             :          * visibility map.
    1604             :          */
    1605             :         bool        skipsallvis;
    1606             : 
    1607      585568 :         find_next_unskippable_block(vacrel, &skipsallvis);
    1608             : 
    1609             :         /*
    1610             :          * We now know the next block that we must process.  It can be the
    1611             :          * next block after the one we just processed, or something further
    1612             :          * ahead.  If it's further ahead, we can jump to it, but we choose to
    1613             :          * do so only if we can skip at least SKIP_PAGES_THRESHOLD consecutive
    1614             :          * pages.  Since we're reading sequentially, the OS should be doing
    1615             :          * readahead for us, so there's no gain in skipping a page now and
    1616             :          * then.  Skipping such a range might even discourage sequential
    1617             :          * detection.
    1618             :          *
    1619             :          * This test also enables more frequent relfrozenxid advancement
    1620             :          * during non-aggressive VACUUMs.  If the range has any all-visible
    1621             :          * pages then skipping makes updating relfrozenxid unsafe, which is a
    1622             :          * real downside.
    1623             :          */
    1624      585568 :         if (vacrel->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
    1625             :         {
    1626        8770 :             next_block = vacrel->next_unskippable_block;
    1627        8770 :             if (skipsallvis)
    1628          76 :                 vacrel->skippedallvis = true;
    1629             :         }
    1630             :     }
    1631             : 
    1632             :     /* Now we must be in one of the two remaining states: */
    1633      881364 :     if (next_block < vacrel->next_unskippable_block)
    1634             :     {
    1635             :         /*
    1636             :          * 2. We are processing a range of blocks that we could have skipped
    1637             :          * but chose not to.  We know that they are all-visible in the VM,
    1638             :          * otherwise they would've been unskippable.
    1639             :          */
    1640      295796 :         vacrel->current_block = next_block;
    1641      295796 :         blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
    1642      295796 :         *((uint8 *) per_buffer_data) = blk_info;
    1643      295796 :         return vacrel->current_block;
    1644             :     }
    1645             :     else
    1646             :     {
    1647             :         /*
    1648             :          * 3. We reached the next unskippable block.  Process it.  On next
    1649             :          * iteration, we will be back in state 1.
    1650             :          */
    1651             :         Assert(next_block == vacrel->next_unskippable_block);
    1652             : 
    1653      585568 :         vacrel->current_block = next_block;
    1654      585568 :         if (vacrel->next_unskippable_allvis)
    1655       89866 :             blk_info |= VAC_BLK_ALL_VISIBLE_ACCORDING_TO_VM;
    1656      585568 :         if (vacrel->next_unskippable_eager_scanned)
    1657           0 :             blk_info |= VAC_BLK_WAS_EAGER_SCANNED;
    1658      585568 :         *((uint8 *) per_buffer_data) = blk_info;
    1659      585568 :         return vacrel->current_block;
    1660             :     }
    1661             : }
    1662             : 
    1663             : /*
    1664             :  * Find the next unskippable block in a vacuum scan using the visibility map.
    1665             :  * The next unskippable block and its visibility information is updated in
    1666             :  * vacrel.
    1667             :  *
    1668             :  * Note: our opinion of which blocks can be skipped can go stale immediately.
    1669             :  * It's okay if caller "misses" a page whose all-visible or all-frozen marking
    1670             :  * was concurrently cleared, though.  All that matters is that caller scan all
    1671             :  * pages whose tuples might contain XIDs < OldestXmin, or MXIDs < OldestMxact.
    1672             :  * (Actually, non-aggressive VACUUMs can choose to skip all-visible pages with
    1673             :  * older XIDs/MXIDs.  The *skippedallvis flag will be set here when the choice
    1674             :  * to skip such a range is actually made, making everything safe.)
    1675             :  */
    1676             : static void
    1677      585568 : find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis)
    1678             : {
    1679      585568 :     BlockNumber rel_pages = vacrel->rel_pages;
    1680      585568 :     BlockNumber next_unskippable_block = vacrel->next_unskippable_block + 1;
    1681      585568 :     Buffer      next_unskippable_vmbuffer = vacrel->next_unskippable_vmbuffer;
    1682      585568 :     bool        next_unskippable_eager_scanned = false;
    1683             :     bool        next_unskippable_allvis;
    1684             : 
    1685      585568 :     *skipsallvis = false;
    1686             : 
    1687      913434 :     for (;; next_unskippable_block++)
    1688      913434 :     {
    1689     1499002 :         uint8       mapbits = visibilitymap_get_status(vacrel->rel,
    1690             :                                                        next_unskippable_block,
    1691             :                                                        &next_unskippable_vmbuffer);
    1692             : 
    1693     1499002 :         next_unskippable_allvis = (mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0;
    1694             : 
    1695             :         /*
    1696             :          * At the start of each eager scan region, normal vacuums with eager
    1697             :          * scanning enabled reset the failure counter, allowing vacuum to
    1698             :          * resume eager scanning if it had been suspended in the previous
    1699             :          * region.
    1700             :          */
    1701     1499002 :         if (next_unskippable_block >= vacrel->next_eager_scan_region_start)
    1702             :         {
    1703           0 :             vacrel->eager_scan_remaining_fails =
    1704           0 :                 vacrel->eager_scan_max_fails_per_region;
    1705           0 :             vacrel->next_eager_scan_region_start += EAGER_SCAN_REGION_SIZE;
    1706             :         }
    1707             : 
    1708             :         /*
    1709             :          * A block is unskippable if it is not all visible according to the
    1710             :          * visibility map.
    1711             :          */
    1712     1499002 :         if (!next_unskippable_allvis)
    1713             :         {
    1714             :             Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
    1715      495702 :             break;
    1716             :         }
    1717             : 
    1718             :         /*
    1719             :          * Caller must scan the last page to determine whether it has tuples
    1720             :          * (caller must have the opportunity to set vacrel->nonempty_pages).
    1721             :          * This rule avoids having lazy_truncate_heap() take access-exclusive
    1722             :          * lock on rel to attempt a truncation that fails anyway, just because
    1723             :          * there are tuples on the last page (it is likely that there will be
    1724             :          * tuples on other nearby pages as well, but those can be skipped).
    1725             :          *
    1726             :          * Implement this by always treating the last block as unsafe to skip.
    1727             :          */
    1728     1003300 :         if (next_unskippable_block == rel_pages - 1)
    1729       89054 :             break;
    1730             : 
    1731             :         /* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
    1732      914246 :         if (!vacrel->skipwithvm)
    1733         812 :             break;
    1734             : 
    1735             :         /*
    1736             :          * All-frozen pages cannot contain XIDs < OldestXmin (XIDs that aren't
    1737             :          * already frozen by now), so this page can be skipped.
    1738             :          */
    1739      913434 :         if ((mapbits & VISIBILITYMAP_ALL_FROZEN) != 0)
    1740      907898 :             continue;
    1741             : 
    1742             :         /*
    1743             :          * Aggressive vacuums cannot skip any all-visible pages that are not
    1744             :          * also all-frozen.
    1745             :          */
    1746        5536 :         if (vacrel->aggressive)
    1747           0 :             break;
    1748             : 
    1749             :         /*
    1750             :          * Normal vacuums with eager scanning enabled only skip all-visible
    1751             :          * but not all-frozen pages if they have hit the failure limit for the
    1752             :          * current eager scan region.
    1753             :          */
    1754        5536 :         if (vacrel->eager_scan_remaining_fails > 0)
    1755             :         {
    1756           0 :             next_unskippable_eager_scanned = true;
    1757           0 :             break;
    1758             :         }
    1759             : 
    1760             :         /*
    1761             :          * All-visible blocks are safe to skip in a normal vacuum. But
    1762             :          * remember that the final range contains such a block for later.
    1763             :          */
    1764        5536 :         *skipsallvis = true;
    1765             :     }
    1766             : 
    1767             :     /* write the local variables back to vacrel */
    1768      585568 :     vacrel->next_unskippable_block = next_unskippable_block;
    1769      585568 :     vacrel->next_unskippable_allvis = next_unskippable_allvis;
    1770      585568 :     vacrel->next_unskippable_eager_scanned = next_unskippable_eager_scanned;
    1771      585568 :     vacrel->next_unskippable_vmbuffer = next_unskippable_vmbuffer;
    1772      585568 : }
    1773             : 
    1774             : /*
    1775             :  *  lazy_scan_new_or_empty() -- lazy_scan_heap() new/empty page handling.
    1776             :  *
    1777             :  * Must call here to handle both new and empty pages before calling
    1778             :  * lazy_scan_prune or lazy_scan_noprune, since they're not prepared to deal
    1779             :  * with new or empty pages.
    1780             :  *
    1781             :  * It's necessary to consider new pages as a special case, since the rules for
    1782             :  * maintaining the visibility map and FSM with empty pages are a little
    1783             :  * different (though new pages can be truncated away during rel truncation).
    1784             :  *
    1785             :  * Empty pages are not really a special case -- they're just heap pages that
    1786             :  * have no allocated tuples (including even LP_UNUSED items).  You might
    1787             :  * wonder why we need to handle them here all the same.  It's only necessary
    1788             :  * because of a corner-case involving a hard crash during heap relation
    1789             :  * extension.  If we ever make relation-extension crash safe, then it should
    1790             :  * no longer be necessary to deal with empty pages here (or new pages, for
    1791             :  * that matter).
    1792             :  *
    1793             :  * Caller must hold at least a shared lock.  We might need to escalate the
    1794             :  * lock in that case, so the type of lock caller holds needs to be specified
    1795             :  * using 'sharelock' argument.
    1796             :  *
    1797             :  * Returns false in common case where caller should go on to call
    1798             :  * lazy_scan_prune (or lazy_scan_noprune).  Otherwise returns true, indicating
    1799             :  * that lazy_scan_heap is done processing the page, releasing lock on caller's
    1800             :  * behalf.
    1801             :  *
    1802             :  * No vm_page_frozen output parameter (like that passed to lazy_scan_prune())
    1803             :  * is passed here because neither empty nor new pages can be eagerly frozen.
    1804             :  * New pages are never frozen. Empty pages are always set frozen in the VM at
    1805             :  * the same time that they are set all-visible, and we don't eagerly scan
    1806             :  * frozen pages.
    1807             :  */
    1808             : static bool
    1809      881364 : lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno,
    1810             :                        Page page, bool sharelock, Buffer vmbuffer)
    1811             : {
    1812             :     Size        freespace;
    1813             : 
    1814      881364 :     if (PageIsNew(page))
    1815             :     {
    1816             :         /*
    1817             :          * All-zeroes pages can be left over if either a backend extends the
    1818             :          * relation by a single page, but crashes before the newly initialized
    1819             :          * page has been written out, or when bulk-extending the relation
    1820             :          * (which creates a number of empty pages at the tail end of the
    1821             :          * relation), and then enters them into the FSM.
    1822             :          *
    1823             :          * Note we do not enter the page into the visibilitymap. That has the
    1824             :          * downside that we repeatedly visit this page in subsequent vacuums,
    1825             :          * but otherwise we'll never discover the space on a promoted standby.
    1826             :          * The harm of repeated checking ought to normally not be too bad. The
    1827             :          * space usually should be used at some point, otherwise there
    1828             :          * wouldn't be any regular vacuums.
    1829             :          *
    1830             :          * Make sure these pages are in the FSM, to ensure they can be reused.
    1831             :          * Do that by testing if there's any space recorded for the page. If
    1832             :          * not, enter it. We do so after releasing the lock on the heap page,
    1833             :          * the FSM is approximate, after all.
    1834             :          */
    1835        1906 :         UnlockReleaseBuffer(buf);
    1836             : 
    1837        1906 :         if (GetRecordedFreeSpace(vacrel->rel, blkno) == 0)
    1838             :         {
    1839         950 :             freespace = BLCKSZ - SizeOfPageHeaderData;
    1840             : 
    1841         950 :             RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
    1842             :         }
    1843             : 
    1844        1906 :         return true;
    1845             :     }
    1846             : 
    1847      879458 :     if (PageIsEmpty(page))
    1848             :     {
    1849             :         /*
    1850             :          * It seems likely that caller will always be able to get a cleanup
    1851             :          * lock on an empty page.  But don't take any chances -- escalate to
    1852             :          * an exclusive lock (still don't need a cleanup lock, though).
    1853             :          */
    1854          54 :         if (sharelock)
    1855             :         {
    1856           0 :             LockBuffer(buf, BUFFER_LOCK_UNLOCK);
    1857           0 :             LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    1858             : 
    1859           0 :             if (!PageIsEmpty(page))
    1860             :             {
    1861             :                 /* page isn't new or empty -- keep lock and pin for now */
    1862           0 :                 return false;
    1863             :             }
    1864             :         }
    1865             :         else
    1866             :         {
    1867             :             /* Already have a full cleanup lock (which is more than enough) */
    1868             :         }
    1869             : 
    1870             :         /*
    1871             :          * Unlike new pages, empty pages are always set all-visible and
    1872             :          * all-frozen.
    1873             :          */
    1874          54 :         if (!PageIsAllVisible(page))
    1875             :         {
    1876           0 :             START_CRIT_SECTION();
    1877             : 
    1878             :             /* mark buffer dirty before writing a WAL record */
    1879           0 :             MarkBufferDirty(buf);
    1880             : 
    1881             :             /*
    1882             :              * It's possible that another backend has extended the heap,
    1883             :              * initialized the page, and then failed to WAL-log the page due
    1884             :              * to an ERROR.  Since heap extension is not WAL-logged, recovery
    1885             :              * might try to replay our record setting the page all-visible and
    1886             :              * find that the page isn't initialized, which will cause a PANIC.
    1887             :              * To prevent that, check whether the page has been previously
    1888             :              * WAL-logged, and if not, do that now.
    1889             :              */
    1890           0 :             if (RelationNeedsWAL(vacrel->rel) &&
    1891           0 :                 PageGetLSN(page) == InvalidXLogRecPtr)
    1892           0 :                 log_newpage_buffer(buf, true);
    1893             : 
    1894           0 :             PageSetAllVisible(page);
    1895           0 :             visibilitymap_set(vacrel->rel, blkno, buf,
    1896             :                               InvalidXLogRecPtr,
    1897             :                               vmbuffer, InvalidTransactionId,
    1898             :                               VISIBILITYMAP_ALL_VISIBLE |
    1899             :                               VISIBILITYMAP_ALL_FROZEN);
    1900           0 :             END_CRIT_SECTION();
    1901             : 
    1902             :             /* Count the newly all-frozen pages for logging */
    1903           0 :             vacrel->vm_new_visible_pages++;
    1904           0 :             vacrel->vm_new_visible_frozen_pages++;
    1905             :         }
    1906             : 
    1907          54 :         freespace = PageGetHeapFreeSpace(page);
    1908          54 :         UnlockReleaseBuffer(buf);
    1909          54 :         RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
    1910          54 :         return true;
    1911             :     }
    1912             : 
    1913             :     /* page isn't new or empty -- keep lock and pin */
    1914      879404 :     return false;
    1915             : }
    1916             : 
    1917             : /* qsort comparator for sorting OffsetNumbers */
    1918             : static int
    1919     6261364 : cmpOffsetNumbers(const void *a, const void *b)
    1920             : {
    1921     6261364 :     return pg_cmp_u16(*(const OffsetNumber *) a, *(const OffsetNumber *) b);
    1922             : }
    1923             : 
    1924             : /*
    1925             :  *  lazy_scan_prune() -- lazy_scan_heap() pruning and freezing.
    1926             :  *
    1927             :  * Caller must hold pin and buffer cleanup lock on the buffer.
    1928             :  *
    1929             :  * vmbuffer is the buffer containing the VM block with visibility information
    1930             :  * for the heap block, blkno. all_visible_according_to_vm is the saved
    1931             :  * visibility status of the heap block looked up earlier by the caller. We
    1932             :  * won't rely entirely on this status, as it may be out of date.
    1933             :  *
    1934             :  * *has_lpdead_items is set to true or false depending on whether, upon return
    1935             :  * from this function, any LP_DEAD items are still present on the page.
    1936             :  *
    1937             :  * *vm_page_frozen is set to true if the page is newly set all-frozen in the
    1938             :  * VM. The caller currently only uses this for determining whether an eagerly
    1939             :  * scanned page was successfully set all-frozen.
    1940             :  *
    1941             :  * Returns the number of tuples deleted from the page during HOT pruning.
    1942             :  */
    1943             : static int
    1944      879210 : lazy_scan_prune(LVRelState *vacrel,
    1945             :                 Buffer buf,
    1946             :                 BlockNumber blkno,
    1947             :                 Page page,
    1948             :                 Buffer vmbuffer,
    1949             :                 bool all_visible_according_to_vm,
    1950             :                 bool *has_lpdead_items,
    1951             :                 bool *vm_page_frozen)
    1952             : {
    1953      879210 :     Relation    rel = vacrel->rel;
    1954             :     PruneFreezeResult presult;
    1955      879210 :     int         prune_options = 0;
    1956             : 
    1957             :     Assert(BufferGetBlockNumber(buf) == blkno);
    1958             : 
    1959             :     /*
    1960             :      * Prune all HOT-update chains and potentially freeze tuples on this page.
    1961             :      *
    1962             :      * If the relation has no indexes, we can immediately mark would-be dead
    1963             :      * items LP_UNUSED.
    1964             :      *
    1965             :      * The number of tuples removed from the page is returned in
    1966             :      * presult.ndeleted.  It should not be confused with presult.lpdead_items;
    1967             :      * presult.lpdead_items's final value can be thought of as the number of
    1968             :      * tuples that were deleted from indexes.
    1969             :      *
    1970             :      * We will update the VM after collecting LP_DEAD items and freezing
    1971             :      * tuples. Pruning will have determined whether or not the page is
    1972             :      * all-visible.
    1973             :      */
    1974      879210 :     prune_options = HEAP_PAGE_PRUNE_FREEZE;
    1975      879210 :     if (vacrel->nindexes == 0)
    1976       35588 :         prune_options |= HEAP_PAGE_PRUNE_MARK_UNUSED_NOW;
    1977             : 
    1978      879210 :     heap_page_prune_and_freeze(rel, buf, vacrel->vistest, prune_options,
    1979             :                                &vacrel->cutoffs, &presult, PRUNE_VACUUM_SCAN,
    1980             :                                &vacrel->offnum,
    1981             :                                &vacrel->NewRelfrozenXid, &vacrel->NewRelminMxid);
    1982             : 
    1983             :     Assert(MultiXactIdIsValid(vacrel->NewRelminMxid));
    1984             :     Assert(TransactionIdIsValid(vacrel->NewRelfrozenXid));
    1985             : 
    1986      879210 :     if (presult.nfrozen > 0)
    1987             :     {
    1988             :         /*
    1989             :          * We don't increment the new_frozen_tuple_pages instrumentation
    1990             :          * counter when nfrozen == 0, since it only counts pages with newly
    1991             :          * frozen tuples (don't confuse that with pages newly set all-frozen
    1992             :          * in VM).
    1993             :          */
    1994       46910 :         vacrel->new_frozen_tuple_pages++;
    1995             :     }
    1996             : 
    1997             :     /*
    1998             :      * VACUUM will call heap_page_is_all_visible() during the second pass over
    1999             :      * the heap to determine all_visible and all_frozen for the page -- this
    2000             :      * is a specialized version of the logic from this function.  Now that
    2001             :      * we've finished pruning and freezing, make sure that we're in total
    2002             :      * agreement with heap_page_is_all_visible() using an assertion.
    2003             :      */
    2004             : #ifdef USE_ASSERT_CHECKING
    2005             :     /* Note that all_frozen value does not matter when !all_visible */
    2006             :     if (presult.all_visible)
    2007             :     {
    2008             :         TransactionId debug_cutoff;
    2009             :         bool        debug_all_frozen;
    2010             : 
    2011             :         Assert(presult.lpdead_items == 0);
    2012             : 
    2013             :         if (!heap_page_is_all_visible(vacrel, buf,
    2014             :                                       &debug_cutoff, &debug_all_frozen))
    2015             :             Assert(false);
    2016             : 
    2017             :         Assert(presult.all_frozen == debug_all_frozen);
    2018             : 
    2019             :         Assert(!TransactionIdIsValid(debug_cutoff) ||
    2020             :                debug_cutoff == presult.vm_conflict_horizon);
    2021             :     }
    2022             : #endif
    2023             : 
    2024             :     /*
    2025             :      * Now save details of the LP_DEAD items from the page in vacrel
    2026             :      */
    2027      879210 :     if (presult.lpdead_items > 0)
    2028             :     {
    2029       32874 :         vacrel->lpdead_item_pages++;
    2030             : 
    2031             :         /*
    2032             :          * deadoffsets are collected incrementally in
    2033             :          * heap_page_prune_and_freeze() as each dead line pointer is recorded,
    2034             :          * with an indeterminate order, but dead_items_add requires them to be
    2035             :          * sorted.
    2036             :          */
    2037       32874 :         qsort(presult.deadoffsets, presult.lpdead_items, sizeof(OffsetNumber),
    2038             :               cmpOffsetNumbers);
    2039             : 
    2040       32874 :         dead_items_add(vacrel, blkno, presult.deadoffsets, presult.lpdead_items);
    2041             :     }
    2042             : 
    2043             :     /* Finally, add page-local counts to whole-VACUUM counts */
    2044      879210 :     vacrel->tuples_deleted += presult.ndeleted;
    2045      879210 :     vacrel->tuples_frozen += presult.nfrozen;
    2046      879210 :     vacrel->lpdead_items += presult.lpdead_items;
    2047      879210 :     vacrel->live_tuples += presult.live_tuples;
    2048      879210 :     vacrel->recently_dead_tuples += presult.recently_dead_tuples;
    2049             : 
    2050             :     /* Can't truncate this page */
    2051      879210 :     if (presult.hastup)
    2052      863598 :         vacrel->nonempty_pages = blkno + 1;
    2053             : 
    2054             :     /* Did we find LP_DEAD items? */
    2055      879210 :     *has_lpdead_items = (presult.lpdead_items > 0);
    2056             : 
    2057             :     Assert(!presult.all_visible || !(*has_lpdead_items));
    2058             : 
    2059             :     /*
    2060             :      * Handle setting visibility map bit based on information from the VM (as
    2061             :      * of last heap_vac_scan_next_block() call), and from all_visible and
    2062             :      * all_frozen variables
    2063             :      */
    2064      879210 :     if (!all_visible_according_to_vm && presult.all_visible)
    2065       73470 :     {
    2066             :         uint8       old_vmbits;
    2067       73470 :         uint8       flags = VISIBILITYMAP_ALL_VISIBLE;
    2068             : 
    2069       73470 :         if (presult.all_frozen)
    2070             :         {
    2071             :             Assert(!TransactionIdIsValid(presult.vm_conflict_horizon));
    2072       54200 :             flags |= VISIBILITYMAP_ALL_FROZEN;
    2073             :         }
    2074             : 
    2075             :         /*
    2076             :          * It should never be the case that the visibility map page is set
    2077             :          * while the page-level bit is clear, but the reverse is allowed (if
    2078             :          * checksums are not enabled).  Regardless, set both bits so that we
    2079             :          * get back in sync.
    2080             :          *
    2081             :          * NB: If the heap page is all-visible but the VM bit is not set, we
    2082             :          * don't need to dirty the heap page.  However, if checksums are
    2083             :          * enabled, we do need to make sure that the heap page is dirtied
    2084             :          * before passing it to visibilitymap_set(), because it may be logged.
    2085             :          * Given that this situation should only happen in rare cases after a
    2086             :          * crash, it is not worth optimizing.
    2087             :          */
    2088       73470 :         PageSetAllVisible(page);
    2089       73470 :         MarkBufferDirty(buf);
    2090       73470 :         old_vmbits = visibilitymap_set(vacrel->rel, blkno, buf,
    2091             :                                        InvalidXLogRecPtr,
    2092             :                                        vmbuffer, presult.vm_conflict_horizon,
    2093             :                                        flags);
    2094             : 
    2095             :         /*
    2096             :          * If the page wasn't already set all-visible and/or all-frozen in the
    2097             :          * VM, count it as newly set for logging.
    2098             :          */
    2099       73470 :         if ((old_vmbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
    2100             :         {
    2101       73470 :             vacrel->vm_new_visible_pages++;
    2102       73470 :             if (presult.all_frozen)
    2103             :             {
    2104       54200 :                 vacrel->vm_new_visible_frozen_pages++;
    2105       54200 :                 *vm_page_frozen = true;
    2106             :             }
    2107             :         }
    2108           0 :         else if ((old_vmbits & VISIBILITYMAP_ALL_FROZEN) == 0 &&
    2109           0 :                  presult.all_frozen)
    2110             :         {
    2111           0 :             vacrel->vm_new_frozen_pages++;
    2112           0 :             *vm_page_frozen = true;
    2113             :         }
    2114             :     }
    2115             : 
    2116             :     /*
    2117             :      * As of PostgreSQL 9.2, the visibility map bit should never be set if the
    2118             :      * page-level bit is clear.  However, it's possible that the bit got
    2119             :      * cleared after heap_vac_scan_next_block() was called, so we must recheck
    2120             :      * with buffer lock before concluding that the VM is corrupt.
    2121             :      */
    2122      805740 :     else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
    2123           0 :              visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
    2124             :     {
    2125           0 :         elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
    2126             :              vacrel->relname, blkno);
    2127           0 :         visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
    2128             :                             VISIBILITYMAP_VALID_BITS);
    2129             :     }
    2130             : 
    2131             :     /*
    2132             :      * It's possible for the value returned by
    2133             :      * GetOldestNonRemovableTransactionId() to move backwards, so it's not
    2134             :      * wrong for us to see tuples that appear to not be visible to everyone
    2135             :      * yet, while PD_ALL_VISIBLE is already set. The real safe xmin value
    2136             :      * never moves backwards, but GetOldestNonRemovableTransactionId() is
    2137             :      * conservative and sometimes returns a value that's unnecessarily small,
    2138             :      * so if we see that contradiction it just means that the tuples that we
    2139             :      * think are not visible to everyone yet actually are, and the
    2140             :      * PD_ALL_VISIBLE flag is correct.
    2141             :      *
    2142             :      * There should never be LP_DEAD items on a page with PD_ALL_VISIBLE set,
    2143             :      * however.
    2144             :      */
    2145      805740 :     else if (presult.lpdead_items > 0 && PageIsAllVisible(page))
    2146             :     {
    2147           0 :         elog(WARNING, "page containing LP_DEAD items is marked as all-visible in relation \"%s\" page %u",
    2148             :              vacrel->relname, blkno);
    2149           0 :         PageClearAllVisible(page);
    2150           0 :         MarkBufferDirty(buf);
    2151           0 :         visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
    2152             :                             VISIBILITYMAP_VALID_BITS);
    2153             :     }
    2154             : 
    2155             :     /*
    2156             :      * If the all-visible page is all-frozen but not marked as such yet, mark
    2157             :      * it as all-frozen.  Note that all_frozen is only valid if all_visible is
    2158             :      * true, so we must check both all_visible and all_frozen.
    2159             :      */
    2160      805740 :     else if (all_visible_according_to_vm && presult.all_visible &&
    2161      385428 :              presult.all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
    2162             :     {
    2163             :         uint8       old_vmbits;
    2164             : 
    2165             :         /*
    2166             :          * Avoid relying on all_visible_according_to_vm as a proxy for the
    2167             :          * page-level PD_ALL_VISIBLE bit being set, since it might have become
    2168             :          * stale -- even when all_visible is set
    2169             :          */
    2170          44 :         if (!PageIsAllVisible(page))
    2171             :         {
    2172           0 :             PageSetAllVisible(page);
    2173           0 :             MarkBufferDirty(buf);
    2174             :         }
    2175             : 
    2176             :         /*
    2177             :          * Set the page all-frozen (and all-visible) in the VM.
    2178             :          *
    2179             :          * We can pass InvalidTransactionId as our cutoff_xid, since a
    2180             :          * snapshotConflictHorizon sufficient to make everything safe for REDO
    2181             :          * was logged when the page's tuples were frozen.
    2182             :          */
    2183             :         Assert(!TransactionIdIsValid(presult.vm_conflict_horizon));
    2184          44 :         old_vmbits = visibilitymap_set(vacrel->rel, blkno, buf,
    2185             :                                        InvalidXLogRecPtr,
    2186             :                                        vmbuffer, InvalidTransactionId,
    2187             :                                        VISIBILITYMAP_ALL_VISIBLE |
    2188             :                                        VISIBILITYMAP_ALL_FROZEN);
    2189             : 
    2190             :         /*
    2191             :          * The page was likely already set all-visible in the VM. However,
    2192             :          * there is a small chance that it was modified sometime between
    2193             :          * setting all_visible_according_to_vm and checking the visibility
    2194             :          * during pruning. Check the return value of old_vmbits anyway to
    2195             :          * ensure the visibility map counters used for logging are accurate.
    2196             :          */
    2197          44 :         if ((old_vmbits & VISIBILITYMAP_ALL_VISIBLE) == 0)
    2198             :         {
    2199           0 :             vacrel->vm_new_visible_pages++;
    2200           0 :             vacrel->vm_new_visible_frozen_pages++;
    2201           0 :             *vm_page_frozen = true;
    2202             :         }
    2203             : 
    2204             :         /*
    2205             :          * We already checked that the page was not set all-frozen in the VM
    2206             :          * above, so we don't need to test the value of old_vmbits.
    2207             :          */
    2208             :         else
    2209             :         {
    2210          44 :             vacrel->vm_new_frozen_pages++;
    2211          44 :             *vm_page_frozen = true;
    2212             :         }
    2213             :     }
    2214             : 
    2215      879210 :     return presult.ndeleted;
    2216             : }
    2217             : 
    2218             : /*
    2219             :  *  lazy_scan_noprune() -- lazy_scan_prune() without pruning or freezing
    2220             :  *
    2221             :  * Caller need only hold a pin and share lock on the buffer, unlike
    2222             :  * lazy_scan_prune, which requires a full cleanup lock.  While pruning isn't
    2223             :  * performed here, it's quite possible that an earlier opportunistic pruning
    2224             :  * operation left LP_DEAD items behind.  We'll at least collect any such items
    2225             :  * in dead_items for removal from indexes.
    2226             :  *
    2227             :  * For aggressive VACUUM callers, we may return false to indicate that a full
    2228             :  * cleanup lock is required for processing by lazy_scan_prune.  This is only
    2229             :  * necessary when the aggressive VACUUM needs to freeze some tuple XIDs from
    2230             :  * one or more tuples on the page.  We always return true for non-aggressive
    2231             :  * callers.
    2232             :  *
    2233             :  * If this function returns true, *has_lpdead_items gets set to true or false
    2234             :  * depending on whether, upon return from this function, any LP_DEAD items are
    2235             :  * present on the page. If this function returns false, *has_lpdead_items
    2236             :  * is not updated.
    2237             :  */
    2238             : static bool
    2239         268 : lazy_scan_noprune(LVRelState *vacrel,
    2240             :                   Buffer buf,
    2241             :                   BlockNumber blkno,
    2242             :                   Page page,
    2243             :                   bool *has_lpdead_items)
    2244             : {
    2245             :     OffsetNumber offnum,
    2246             :                 maxoff;
    2247             :     int         lpdead_items,
    2248             :                 live_tuples,
    2249             :                 recently_dead_tuples,
    2250             :                 missed_dead_tuples;
    2251             :     bool        hastup;
    2252             :     HeapTupleHeader tupleheader;
    2253         268 :     TransactionId NoFreezePageRelfrozenXid = vacrel->NewRelfrozenXid;
    2254         268 :     MultiXactId NoFreezePageRelminMxid = vacrel->NewRelminMxid;
    2255             :     OffsetNumber deadoffsets[MaxHeapTuplesPerPage];
    2256             : 
    2257             :     Assert(BufferGetBlockNumber(buf) == blkno);
    2258             : 
    2259         268 :     hastup = false;             /* for now */
    2260             : 
    2261         268 :     lpdead_items = 0;
    2262         268 :     live_tuples = 0;
    2263         268 :     recently_dead_tuples = 0;
    2264         268 :     missed_dead_tuples = 0;
    2265             : 
    2266         268 :     maxoff = PageGetMaxOffsetNumber(page);
    2267         268 :     for (offnum = FirstOffsetNumber;
    2268        8594 :          offnum <= maxoff;
    2269        8326 :          offnum = OffsetNumberNext(offnum))
    2270             :     {
    2271             :         ItemId      itemid;
    2272             :         HeapTupleData tuple;
    2273             : 
    2274        8400 :         vacrel->offnum = offnum;
    2275        8400 :         itemid = PageGetItemId(page, offnum);
    2276             : 
    2277        8400 :         if (!ItemIdIsUsed(itemid))
    2278        2010 :             continue;
    2279             : 
    2280        6990 :         if (ItemIdIsRedirected(itemid))
    2281             :         {
    2282         600 :             hastup = true;
    2283         600 :             continue;
    2284             :         }
    2285             : 
    2286        6390 :         if (ItemIdIsDead(itemid))
    2287             :         {
    2288             :             /*
    2289             :              * Deliberately don't set hastup=true here.  See same point in
    2290             :              * lazy_scan_prune for an explanation.
    2291             :              */
    2292           0 :             deadoffsets[lpdead_items++] = offnum;
    2293           0 :             continue;
    2294             :         }
    2295             : 
    2296        6390 :         hastup = true;          /* page prevents rel truncation */
    2297        6390 :         tupleheader = (HeapTupleHeader) PageGetItem(page, itemid);
    2298        6390 :         if (heap_tuple_should_freeze(tupleheader, &vacrel->cutoffs,
    2299             :                                      &NoFreezePageRelfrozenXid,
    2300             :                                      &NoFreezePageRelminMxid))
    2301             :         {
    2302             :             /* Tuple with XID < FreezeLimit (or MXID < MultiXactCutoff) */
    2303         202 :             if (vacrel->aggressive)
    2304             :             {
    2305             :                 /*
    2306             :                  * Aggressive VACUUMs must always be able to advance rel's
    2307             :                  * relfrozenxid to a value >= FreezeLimit (and be able to
    2308             :                  * advance rel's relminmxid to a value >= MultiXactCutoff).
    2309             :                  * The ongoing aggressive VACUUM won't be able to do that
    2310             :                  * unless it can freeze an XID (or MXID) from this tuple now.
    2311             :                  *
    2312             :                  * The only safe option is to have caller perform processing
    2313             :                  * of this page using lazy_scan_prune.  Caller might have to
    2314             :                  * wait a while for a cleanup lock, but it can't be helped.
    2315             :                  */
    2316          74 :                 vacrel->offnum = InvalidOffsetNumber;
    2317          74 :                 return false;
    2318             :             }
    2319             : 
    2320             :             /*
    2321             :              * Non-aggressive VACUUMs are under no obligation to advance
    2322             :              * relfrozenxid (even by one XID).  We can be much laxer here.
    2323             :              *
    2324             :              * Currently we always just accept an older final relfrozenxid
    2325             :              * and/or relminmxid value.  We never make caller wait or work a
    2326             :              * little harder, even when it likely makes sense to do so.
    2327             :              */
    2328             :         }
    2329             : 
    2330        6316 :         ItemPointerSet(&(tuple.t_self), blkno, offnum);
    2331        6316 :         tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
    2332        6316 :         tuple.t_len = ItemIdGetLength(itemid);
    2333        6316 :         tuple.t_tableOid = RelationGetRelid(vacrel->rel);
    2334             : 
    2335        6316 :         switch (HeapTupleSatisfiesVacuum(&tuple, vacrel->cutoffs.OldestXmin,
    2336             :                                          buf))
    2337             :         {
    2338        6222 :             case HEAPTUPLE_DELETE_IN_PROGRESS:
    2339             :             case HEAPTUPLE_LIVE:
    2340             : 
    2341             :                 /*
    2342             :                  * Count both cases as live, just like lazy_scan_prune
    2343             :                  */
    2344        6222 :                 live_tuples++;
    2345             : 
    2346        6222 :                 break;
    2347          82 :             case HEAPTUPLE_DEAD:
    2348             : 
    2349             :                 /*
    2350             :                  * There is some useful work for pruning to do, that won't be
    2351             :                  * done due to failure to get a cleanup lock.
    2352             :                  */
    2353          82 :                 missed_dead_tuples++;
    2354          82 :                 break;
    2355           4 :             case HEAPTUPLE_RECENTLY_DEAD:
    2356             : 
    2357             :                 /*
    2358             :                  * Count in recently_dead_tuples, just like lazy_scan_prune
    2359             :                  */
    2360           4 :                 recently_dead_tuples++;
    2361           4 :                 break;
    2362           8 :             case HEAPTUPLE_INSERT_IN_PROGRESS:
    2363             : 
    2364             :                 /*
    2365             :                  * Do not count these rows as live, just like lazy_scan_prune
    2366             :                  */
    2367           8 :                 break;
    2368           0 :             default:
    2369           0 :                 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
    2370             :                 break;
    2371             :         }
    2372             :     }
    2373             : 
    2374         194 :     vacrel->offnum = InvalidOffsetNumber;
    2375             : 
    2376             :     /*
    2377             :      * By here we know for sure that caller can put off freezing and pruning
    2378             :      * this particular page until the next VACUUM.  Remember its details now.
    2379             :      * (lazy_scan_prune expects a clean slate, so we have to do this last.)
    2380             :      */
    2381         194 :     vacrel->NewRelfrozenXid = NoFreezePageRelfrozenXid;
    2382         194 :     vacrel->NewRelminMxid = NoFreezePageRelminMxid;
    2383             : 
    2384             :     /* Save any LP_DEAD items found on the page in dead_items */
    2385         194 :     if (vacrel->nindexes == 0)
    2386             :     {
    2387             :         /* Using one-pass strategy (since table has no indexes) */
    2388           0 :         if (lpdead_items > 0)
    2389             :         {
    2390             :             /*
    2391             :              * Perfunctory handling for the corner case where a single pass
    2392             :              * strategy VACUUM cannot get a cleanup lock, and it turns out
    2393             :              * that there is one or more LP_DEAD items: just count the LP_DEAD
    2394             :              * items as missed_dead_tuples instead. (This is a bit dishonest,
    2395             :              * but it beats having to maintain specialized heap vacuuming code
    2396             :              * forever, for vanishingly little benefit.)
    2397             :              */
    2398           0 :             hastup = true;
    2399           0 :             missed_dead_tuples += lpdead_items;
    2400             :         }
    2401             :     }
    2402         194 :     else if (lpdead_items > 0)
    2403             :     {
    2404             :         /*
    2405             :          * Page has LP_DEAD items, and so any references/TIDs that remain in
    2406             :          * indexes will be deleted during index vacuuming (and then marked
    2407             :          * LP_UNUSED in the heap)
    2408             :          */
    2409           0 :         vacrel->lpdead_item_pages++;
    2410             : 
    2411           0 :         dead_items_add(vacrel, blkno, deadoffsets, lpdead_items);
    2412             : 
    2413           0 :         vacrel->lpdead_items += lpdead_items;
    2414             :     }
    2415             : 
    2416             :     /*
    2417             :      * Finally, add relevant page-local counts to whole-VACUUM counts
    2418             :      */
    2419         194 :     vacrel->live_tuples += live_tuples;
    2420         194 :     vacrel->recently_dead_tuples += recently_dead_tuples;
    2421         194 :     vacrel->missed_dead_tuples += missed_dead_tuples;
    2422         194 :     if (missed_dead_tuples > 0)
    2423           6 :         vacrel->missed_dead_pages++;
    2424             : 
    2425             :     /* Can't truncate this page */
    2426         194 :     if (hastup)
    2427         194 :         vacrel->nonempty_pages = blkno + 1;
    2428             : 
    2429             :     /* Did we find LP_DEAD items? */
    2430         194 :     *has_lpdead_items = (lpdead_items > 0);
    2431             : 
    2432             :     /* Caller won't need to call lazy_scan_prune with same page */
    2433         194 :     return true;
    2434             : }
    2435             : 
    2436             : /*
    2437             :  * Main entry point for index vacuuming and heap vacuuming.
    2438             :  *
    2439             :  * Removes items collected in dead_items from table's indexes, then marks the
    2440             :  * same items LP_UNUSED in the heap.  See the comments above lazy_scan_heap
    2441             :  * for full details.
    2442             :  *
    2443             :  * Also empties dead_items, freeing up space for later TIDs.
    2444             :  *
    2445             :  * We may choose to bypass index vacuuming at this point, though only when the
    2446             :  * ongoing VACUUM operation will definitely only have one index scan/round of
    2447             :  * index vacuuming.
    2448             :  */
    2449             : static void
    2450        1340 : lazy_vacuum(LVRelState *vacrel)
    2451             : {
    2452             :     bool        bypass;
    2453             : 
    2454             :     /* Should not end up here with no indexes */
    2455             :     Assert(vacrel->nindexes > 0);
    2456             :     Assert(vacrel->lpdead_item_pages > 0);
    2457             : 
    2458        1340 :     if (!vacrel->do_index_vacuuming)
    2459             :     {
    2460             :         Assert(!vacrel->do_index_cleanup);
    2461          26 :         dead_items_reset(vacrel);
    2462          26 :         return;
    2463             :     }
    2464             : 
    2465             :     /*
    2466             :      * Consider bypassing index vacuuming (and heap vacuuming) entirely.
    2467             :      *
    2468             :      * We currently only do this in cases where the number of LP_DEAD items
    2469             :      * for the entire VACUUM operation is close to zero.  This avoids sharp
    2470             :      * discontinuities in the duration and overhead of successive VACUUM
    2471             :      * operations that run against the same table with a fixed workload.
    2472             :      * Ideally, successive VACUUM operations will behave as if there are
    2473             :      * exactly zero LP_DEAD items in cases where there are close to zero.
    2474             :      *
    2475             :      * This is likely to be helpful with a table that is continually affected
    2476             :      * by UPDATEs that can mostly apply the HOT optimization, but occasionally
    2477             :      * have small aberrations that lead to just a few heap pages retaining
    2478             :      * only one or two LP_DEAD items.  This is pretty common; even when the
    2479             :      * DBA goes out of their way to make UPDATEs use HOT, it is practically
    2480             :      * impossible to predict whether HOT will be applied in 100% of cases.
    2481             :      * It's far easier to ensure that 99%+ of all UPDATEs against a table use
    2482             :      * HOT through careful tuning.
    2483             :      */
    2484        1314 :     bypass = false;
    2485        1314 :     if (vacrel->consider_bypass_optimization && vacrel->rel_pages > 0)
    2486             :     {
    2487             :         BlockNumber threshold;
    2488             : 
    2489             :         Assert(vacrel->num_index_scans == 0);
    2490             :         Assert(vacrel->lpdead_items == vacrel->dead_items_info->num_items);
    2491             :         Assert(vacrel->do_index_vacuuming);
    2492             :         Assert(vacrel->do_index_cleanup);
    2493             : 
    2494             :         /*
    2495             :          * This crossover point at which we'll start to do index vacuuming is
    2496             :          * expressed as a percentage of the total number of heap pages in the
    2497             :          * table that are known to have at least one LP_DEAD item.  This is
    2498             :          * much more important than the total number of LP_DEAD items, since
    2499             :          * it's a proxy for the number of heap pages whose visibility map bits
    2500             :          * cannot be set on account of bypassing index and heap vacuuming.
    2501             :          *
    2502             :          * We apply one further precautionary test: the space currently used
    2503             :          * to store the TIDs (TIDs that now all point to LP_DEAD items) must
    2504             :          * not exceed 32MB.  This limits the risk that we will bypass index
    2505             :          * vacuuming again and again until eventually there is a VACUUM whose
    2506             :          * dead_items space is not CPU cache resident.
    2507             :          *
    2508             :          * We don't take any special steps to remember the LP_DEAD items (such
    2509             :          * as counting them in our final update to the stats system) when the
    2510             :          * optimization is applied.  Though the accounting used in analyze.c's
    2511             :          * acquire_sample_rows() will recognize the same LP_DEAD items as dead
    2512             :          * rows in its own stats report, that's okay. The discrepancy should
    2513             :          * be negligible.  If this optimization is ever expanded to cover more
    2514             :          * cases then this may need to be reconsidered.
    2515             :          */
    2516        1294 :         threshold = (double) vacrel->rel_pages * BYPASS_THRESHOLD_PAGES;
    2517        1298 :         bypass = (vacrel->lpdead_item_pages < threshold &&
    2518           4 :                   TidStoreMemoryUsage(vacrel->dead_items) < 32 * 1024 * 1024);
    2519             :     }
    2520             : 
    2521        1314 :     if (bypass)
    2522             :     {
    2523             :         /*
    2524             :          * There are almost zero TIDs.  Behave as if there were precisely
    2525             :          * zero: bypass index vacuuming, but do index cleanup.
    2526             :          *
    2527             :          * We expect that the ongoing VACUUM operation will finish very
    2528             :          * quickly, so there is no point in considering speeding up as a
    2529             :          * failsafe against wraparound failure. (Index cleanup is expected to
    2530             :          * finish very quickly in cases where there were no ambulkdelete()
    2531             :          * calls.)
    2532             :          */
    2533           4 :         vacrel->do_index_vacuuming = false;
    2534             :     }
    2535        1310 :     else if (lazy_vacuum_all_indexes(vacrel))
    2536             :     {
    2537             :         /*
    2538             :          * We successfully completed a round of index vacuuming.  Do related
    2539             :          * heap vacuuming now.
    2540             :          */
    2541        1310 :         lazy_vacuum_heap_rel(vacrel);
    2542             :     }
    2543             :     else
    2544             :     {
    2545             :         /*
    2546             :          * Failsafe case.
    2547             :          *
    2548             :          * We attempted index vacuuming, but didn't finish a full round/full
    2549             :          * index scan.  This happens when relfrozenxid or relminmxid is too
    2550             :          * far in the past.
    2551             :          *
    2552             :          * From this point on the VACUUM operation will do no further index
    2553             :          * vacuuming or heap vacuuming.  This VACUUM operation won't end up
    2554             :          * back here again.
    2555             :          */
    2556             :         Assert(VacuumFailsafeActive);
    2557             :     }
    2558             : 
    2559             :     /*
    2560             :      * Forget the LP_DEAD items that we just vacuumed (or just decided to not
    2561             :      * vacuum)
    2562             :      */
    2563        1314 :     dead_items_reset(vacrel);
    2564             : }
    2565             : 
    2566             : /*
    2567             :  *  lazy_vacuum_all_indexes() -- Main entry for index vacuuming
    2568             :  *
    2569             :  * Returns true in the common case when all indexes were successfully
    2570             :  * vacuumed.  Returns false in rare cases where we determined that the ongoing
    2571             :  * VACUUM operation is at risk of taking too long to finish, leading to
    2572             :  * wraparound failure.
    2573             :  */
    2574             : static bool
    2575        1310 : lazy_vacuum_all_indexes(LVRelState *vacrel)
    2576             : {
    2577        1310 :     bool        allindexes = true;
    2578        1310 :     double      old_live_tuples = vacrel->rel->rd_rel->reltuples;
    2579        1310 :     const int   progress_start_index[] = {
    2580             :         PROGRESS_VACUUM_PHASE,
    2581             :         PROGRESS_VACUUM_INDEXES_TOTAL
    2582             :     };
    2583        1310 :     const int   progress_end_index[] = {
    2584             :         PROGRESS_VACUUM_INDEXES_TOTAL,
    2585             :         PROGRESS_VACUUM_INDEXES_PROCESSED,
    2586             :         PROGRESS_VACUUM_NUM_INDEX_VACUUMS
    2587             :     };
    2588             :     int64       progress_start_val[2];
    2589             :     int64       progress_end_val[3];
    2590             : 
    2591             :     Assert(vacrel->nindexes > 0);
    2592             :     Assert(vacrel->do_index_vacuuming);
    2593             :     Assert(vacrel->do_index_cleanup);
    2594             : 
    2595             :     /* Precheck for XID wraparound emergencies */
    2596        1310 :     if (lazy_check_wraparound_failsafe(vacrel))
    2597             :     {
    2598             :         /* Wraparound emergency -- don't even start an index scan */
    2599           0 :         return false;
    2600             :     }
    2601             : 
    2602             :     /*
    2603             :      * Report that we are now vacuuming indexes and the number of indexes to
    2604             :      * vacuum.
    2605             :      */
    2606        1310 :     progress_start_val[0] = PROGRESS_VACUUM_PHASE_VACUUM_INDEX;
    2607        1310 :     progress_start_val[1] = vacrel->nindexes;
    2608        1310 :     pgstat_progress_update_multi_param(2, progress_start_index, progress_start_val);
    2609             : 
    2610        1310 :     if (!ParallelVacuumIsActive(vacrel))
    2611             :     {
    2612        3836 :         for (int idx = 0; idx < vacrel->nindexes; idx++)
    2613             :         {
    2614        2536 :             Relation    indrel = vacrel->indrels[idx];
    2615        2536 :             IndexBulkDeleteResult *istat = vacrel->indstats[idx];
    2616             : 
    2617        2536 :             vacrel->indstats[idx] = lazy_vacuum_one_index(indrel, istat,
    2618             :                                                           old_live_tuples,
    2619             :                                                           vacrel);
    2620             : 
    2621             :             /* Report the number of indexes vacuumed */
    2622        2536 :             pgstat_progress_update_param(PROGRESS_VACUUM_INDEXES_PROCESSED,
    2623        2536 :                                          idx + 1);
    2624             : 
    2625        2536 :             if (lazy_check_wraparound_failsafe(vacrel))
    2626             :             {
    2627             :                 /* Wraparound emergency -- end current index scan */
    2628           0 :                 allindexes = false;
    2629           0 :                 break;
    2630             :             }
    2631             :         }
    2632             :     }
    2633             :     else
    2634             :     {
    2635             :         /* Outsource everything to parallel variant */
    2636          10 :         parallel_vacuum_bulkdel_all_indexes(vacrel->pvs, old_live_tuples,
    2637             :                                             vacrel->num_index_scans);
    2638             : 
    2639             :         /*
    2640             :          * Do a postcheck to consider applying wraparound failsafe now.  Note
    2641             :          * that parallel VACUUM only gets the precheck and this postcheck.
    2642             :          */
    2643          10 :         if (lazy_check_wraparound_failsafe(vacrel))
    2644           0 :             allindexes = false;
    2645             :     }
    2646             : 
    2647             :     /*
    2648             :      * We delete all LP_DEAD items from the first heap pass in all indexes on
    2649             :      * each call here (except calls where we choose to do the failsafe). This
    2650             :      * makes the next call to lazy_vacuum_heap_rel() safe (except in the event
    2651             :      * of the failsafe triggering, which prevents the next call from taking
    2652             :      * place).
    2653             :      */
    2654             :     Assert(vacrel->num_index_scans > 0 ||
    2655             :            vacrel->dead_items_info->num_items == vacrel->lpdead_items);
    2656             :     Assert(allindexes || VacuumFailsafeActive);
    2657             : 
    2658             :     /*
    2659             :      * Increase and report the number of index scans.  Also, we reset
    2660             :      * PROGRESS_VACUUM_INDEXES_TOTAL and PROGRESS_VACUUM_INDEXES_PROCESSED.
    2661             :      *
    2662             :      * We deliberately include the case where we started a round of bulk
    2663             :      * deletes that we weren't able to finish due to the failsafe triggering.
    2664             :      */
    2665        1310 :     vacrel->num_index_scans++;
    2666        1310 :     progress_end_val[0] = 0;
    2667        1310 :     progress_end_val[1] = 0;
    2668        1310 :     progress_end_val[2] = vacrel->num_index_scans;
    2669        1310 :     pgstat_progress_update_multi_param(3, progress_end_index, progress_end_val);
    2670             : 
    2671        1310 :     return allindexes;
    2672             : }
    2673             : 
    2674             : /*
    2675             :  * Read stream callback for vacuum's third phase (second pass over the heap).
    2676             :  * Gets the next block from the TID store and returns it or InvalidBlockNumber
    2677             :  * if there are no further blocks to vacuum.
    2678             :  *
    2679             :  * NB: Assumed to be safe to use with READ_STREAM_USE_BATCHING.
    2680             :  */
    2681             : static BlockNumber
    2682       29522 : vacuum_reap_lp_read_stream_next(ReadStream *stream,
    2683             :                                 void *callback_private_data,
    2684             :                                 void *per_buffer_data)
    2685             : {
    2686       29522 :     TidStoreIter *iter = callback_private_data;
    2687             :     TidStoreIterResult *iter_result;
    2688             : 
    2689       29522 :     iter_result = TidStoreIterateNext(iter);
    2690       29522 :     if (iter_result == NULL)
    2691        1310 :         return InvalidBlockNumber;
    2692             : 
    2693             :     /*
    2694             :      * Save the TidStoreIterResult for later, so we can extract the offsets.
    2695             :      * It is safe to copy the result, according to TidStoreIterateNext().
    2696             :      */
    2697       28212 :     memcpy(per_buffer_data, iter_result, sizeof(*iter_result));
    2698             : 
    2699       28212 :     return iter_result->blkno;
    2700             : }
    2701             : 
    2702             : /*
    2703             :  *  lazy_vacuum_heap_rel() -- second pass over the heap for two pass strategy
    2704             :  *
    2705             :  * This routine marks LP_DEAD items in vacrel->dead_items as LP_UNUSED. Pages
    2706             :  * that never had lazy_scan_prune record LP_DEAD items are not visited at all.
    2707             :  *
    2708             :  * We may also be able to truncate the line pointer array of the heap pages we
    2709             :  * visit.  If there is a contiguous group of LP_UNUSED items at the end of the
    2710             :  * array, it can be reclaimed as free space.  These LP_UNUSED items usually
    2711             :  * start out as LP_DEAD items recorded by lazy_scan_prune (we set items from
    2712             :  * each page to LP_UNUSED, and then consider if it's possible to truncate the
    2713             :  * page's line pointer array).
    2714             :  *
    2715             :  * Note: the reason for doing this as a second pass is we cannot remove the
    2716             :  * tuples until we've removed their index entries, and we want to process
    2717             :  * index entry removal in batches as large as possible.
    2718             :  */
    2719             : static void
    2720        1310 : lazy_vacuum_heap_rel(LVRelState *vacrel)
    2721             : {
    2722             :     ReadStream *stream;
    2723        1310 :     BlockNumber vacuumed_pages = 0;
    2724        1310 :     Buffer      vmbuffer = InvalidBuffer;
    2725             :     LVSavedErrInfo saved_err_info;
    2726             :     TidStoreIter *iter;
    2727             : 
    2728             :     Assert(vacrel->do_index_vacuuming);
    2729             :     Assert(vacrel->do_index_cleanup);
    2730             :     Assert(vacrel->num_index_scans > 0);
    2731             : 
    2732             :     /* Report that we are now vacuuming the heap */
    2733        1310 :     pgstat_progress_update_param(PROGRESS_VACUUM_PHASE,
    2734             :                                  PROGRESS_VACUUM_PHASE_VACUUM_HEAP);
    2735             : 
    2736             :     /* Update error traceback information */
    2737        1310 :     update_vacuum_error_info(vacrel, &saved_err_info,
    2738             :                              VACUUM_ERRCB_PHASE_VACUUM_HEAP,
    2739             :                              InvalidBlockNumber, InvalidOffsetNumber);
    2740             : 
    2741        1310 :     iter = TidStoreBeginIterate(vacrel->dead_items);
    2742             : 
    2743             :     /*
    2744             :      * Set up the read stream for vacuum's second pass through the heap.
    2745             :      *
    2746             :      * It is safe to use batchmode, as vacuum_reap_lp_read_stream_next() does
    2747             :      * not need to wait for IO and does not perform locking. Once we support
    2748             :      * parallelism it should still be fine, as presumably the holder of locks
    2749             :      * would never be blocked by IO while holding the lock.
    2750             :      */
    2751        1310 :     stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE |
    2752             :                                         READ_STREAM_USE_BATCHING,
    2753             :                                         vacrel->bstrategy,
    2754             :                                         vacrel->rel,
    2755             :                                         MAIN_FORKNUM,
    2756             :                                         vacuum_reap_lp_read_stream_next,
    2757             :                                         iter,
    2758             :                                         sizeof(TidStoreIterResult));
    2759             : 
    2760             :     while (true)
    2761       28212 :     {
    2762             :         BlockNumber blkno;
    2763             :         Buffer      buf;
    2764             :         Page        page;
    2765             :         TidStoreIterResult *iter_result;
    2766             :         Size        freespace;
    2767             :         OffsetNumber offsets[MaxOffsetNumber];
    2768             :         int         num_offsets;
    2769             : 
    2770       29522 :         vacuum_delay_point(false);
    2771             : 
    2772       29522 :         buf = read_stream_next_buffer(stream, (void **) &iter_result);
    2773             : 
    2774             :         /* The relation is exhausted */
    2775       29522 :         if (!BufferIsValid(buf))
    2776        1310 :             break;
    2777             : 
    2778       28212 :         vacrel->blkno = blkno = BufferGetBlockNumber(buf);
    2779             : 
    2780             :         Assert(iter_result);
    2781       28212 :         num_offsets = TidStoreGetBlockOffsets(iter_result, offsets, lengthof(offsets));
    2782             :         Assert(num_offsets <= lengthof(offsets));
    2783             : 
    2784             :         /*
    2785             :          * Pin the visibility map page in case we need to mark the page
    2786             :          * all-visible.  In most cases this will be very cheap, because we'll
    2787             :          * already have the correct page pinned anyway.
    2788             :          */
    2789       28212 :         visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
    2790             : 
    2791             :         /* We need a non-cleanup exclusive lock to mark dead_items unused */
    2792       28212 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    2793       28212 :         lazy_vacuum_heap_page(vacrel, blkno, buf, offsets,
    2794             :                               num_offsets, vmbuffer);
    2795             : 
    2796             :         /* Now that we've vacuumed the page, record its available space */
    2797       28212 :         page = BufferGetPage(buf);
    2798       28212 :         freespace = PageGetHeapFreeSpace(page);
    2799             : 
    2800       28212 :         UnlockReleaseBuffer(buf);
    2801       28212 :         RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
    2802       28212 :         vacuumed_pages++;
    2803             :     }
    2804             : 
    2805        1310 :     read_stream_end(stream);
    2806        1310 :     TidStoreEndIterate(iter);
    2807             : 
    2808        1310 :     vacrel->blkno = InvalidBlockNumber;
    2809        1310 :     if (BufferIsValid(vmbuffer))
    2810        1310 :         ReleaseBuffer(vmbuffer);
    2811             : 
    2812             :     /*
    2813             :      * We set all LP_DEAD items from the first heap pass to LP_UNUSED during
    2814             :      * the second heap pass.  No more, no less.
    2815             :      */
    2816             :     Assert(vacrel->num_index_scans > 1 ||
    2817             :            (vacrel->dead_items_info->num_items == vacrel->lpdead_items &&
    2818             :             vacuumed_pages == vacrel->lpdead_item_pages));
    2819             : 
    2820        1310 :     ereport(DEBUG2,
    2821             :             (errmsg("table \"%s\": removed %" PRId64 " dead item identifiers in %u pages",
    2822             :                     vacrel->relname, vacrel->dead_items_info->num_items,
    2823             :                     vacuumed_pages)));
    2824             : 
    2825             :     /* Revert to the previous phase information for error traceback */
    2826        1310 :     restore_vacuum_error_info(vacrel, &saved_err_info);
    2827        1310 : }
    2828             : 
    2829             : /*
    2830             :  *  lazy_vacuum_heap_page() -- free page's LP_DEAD items listed in the
    2831             :  *                        vacrel->dead_items store.
    2832             :  *
    2833             :  * Caller must have an exclusive buffer lock on the buffer (though a full
    2834             :  * cleanup lock is also acceptable).  vmbuffer must be valid and already have
    2835             :  * a pin on blkno's visibility map page.
    2836             :  */
    2837             : static void
    2838       28212 : lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer,
    2839             :                       OffsetNumber *deadoffsets, int num_offsets,
    2840             :                       Buffer vmbuffer)
    2841             : {
    2842       28212 :     Page        page = BufferGetPage(buffer);
    2843             :     OffsetNumber unused[MaxHeapTuplesPerPage];
    2844       28212 :     int         nunused = 0;
    2845             :     TransactionId visibility_cutoff_xid;
    2846             :     bool        all_frozen;
    2847             :     LVSavedErrInfo saved_err_info;
    2848             : 
    2849             :     Assert(vacrel->do_index_vacuuming);
    2850             : 
    2851       28212 :     pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno);
    2852             : 
    2853             :     /* Update error traceback information */
    2854       28212 :     update_vacuum_error_info(vacrel, &saved_err_info,
    2855             :                              VACUUM_ERRCB_PHASE_VACUUM_HEAP, blkno,
    2856             :                              InvalidOffsetNumber);
    2857             : 
    2858       28212 :     START_CRIT_SECTION();
    2859             : 
    2860     1725764 :     for (int i = 0; i < num_offsets; i++)
    2861             :     {
    2862             :         ItemId      itemid;
    2863     1697552 :         OffsetNumber toff = deadoffsets[i];
    2864             : 
    2865     1697552 :         itemid = PageGetItemId(page, toff);
    2866             : 
    2867             :         Assert(ItemIdIsDead(itemid) && !ItemIdHasStorage(itemid));
    2868     1697552 :         ItemIdSetUnused(itemid);
    2869     1697552 :         unused[nunused++] = toff;
    2870             :     }
    2871             : 
    2872             :     Assert(nunused > 0);
    2873             : 
    2874             :     /* Attempt to truncate line pointer array now */
    2875       28212 :     PageTruncateLinePointerArray(page);
    2876             : 
    2877             :     /*
    2878             :      * Mark buffer dirty before we write WAL.
    2879             :      */
    2880       28212 :     MarkBufferDirty(buffer);
    2881             : 
    2882             :     /* XLOG stuff */
    2883       28212 :     if (RelationNeedsWAL(vacrel->rel))
    2884             :     {
    2885       26516 :         log_heap_prune_and_freeze(vacrel->rel, buffer,
    2886             :                                   InvalidTransactionId,
    2887             :                                   false,    /* no cleanup lock required */
    2888             :                                   PRUNE_VACUUM_CLEANUP,
    2889             :                                   NULL, 0,  /* frozen */
    2890             :                                   NULL, 0,  /* redirected */
    2891             :                                   NULL, 0,  /* dead */
    2892             :                                   unused, nunused);
    2893             :     }
    2894             : 
    2895             :     /*
    2896             :      * End critical section, so we safely can do visibility tests (which
    2897             :      * possibly need to perform IO and allocate memory!). If we crash now the
    2898             :      * page (including the corresponding vm bit) might not be marked all
    2899             :      * visible, but that's fine. A later vacuum will fix that.
    2900             :      */
    2901       28212 :     END_CRIT_SECTION();
    2902             : 
    2903             :     /*
    2904             :      * Now that we have removed the LP_DEAD items from the page, once again
    2905             :      * check if the page has become all-visible.  The page is already marked
    2906             :      * dirty, exclusively locked, and, if needed, a full page image has been
    2907             :      * emitted.
    2908             :      */
    2909             :     Assert(!PageIsAllVisible(page));
    2910       28212 :     if (heap_page_is_all_visible(vacrel, buffer, &visibility_cutoff_xid,
    2911             :                                  &all_frozen))
    2912             :     {
    2913       27554 :         uint8       flags = VISIBILITYMAP_ALL_VISIBLE;
    2914             : 
    2915       27554 :         if (all_frozen)
    2916             :         {
    2917             :             Assert(!TransactionIdIsValid(visibility_cutoff_xid));
    2918       21964 :             flags |= VISIBILITYMAP_ALL_FROZEN;
    2919             :         }
    2920             : 
    2921       27554 :         PageSetAllVisible(page);
    2922       27554 :         visibilitymap_set(vacrel->rel, blkno, buffer,
    2923             :                           InvalidXLogRecPtr,
    2924             :                           vmbuffer, visibility_cutoff_xid,
    2925             :                           flags);
    2926             : 
    2927             :         /* Count the newly set VM page for logging */
    2928       27554 :         vacrel->vm_new_visible_pages++;
    2929       27554 :         if (all_frozen)
    2930       21964 :             vacrel->vm_new_visible_frozen_pages++;
    2931             :     }
    2932             : 
    2933             :     /* Revert to the previous phase information for error traceback */
    2934       28212 :     restore_vacuum_error_info(vacrel, &saved_err_info);
    2935       28212 : }
    2936             : 
    2937             : /*
    2938             :  * Trigger the failsafe to avoid wraparound failure when vacrel table has a
    2939             :  * relfrozenxid and/or relminmxid that is dangerously far in the past.
    2940             :  * Triggering the failsafe makes the ongoing VACUUM bypass any further index
    2941             :  * vacuuming and heap vacuuming.  Truncating the heap is also bypassed.
    2942             :  *
    2943             :  * Any remaining work (work that VACUUM cannot just bypass) is typically sped
    2944             :  * up when the failsafe triggers.  VACUUM stops applying any cost-based delay
    2945             :  * that it started out with.
    2946             :  *
    2947             :  * Returns true when failsafe has been triggered.
    2948             :  */
    2949             : static bool
    2950      249238 : lazy_check_wraparound_failsafe(LVRelState *vacrel)
    2951             : {
    2952             :     /* Don't warn more than once per VACUUM */
    2953      249238 :     if (VacuumFailsafeActive)
    2954           0 :         return true;
    2955             : 
    2956      249238 :     if (unlikely(vacuum_xid_failsafe_check(&vacrel->cutoffs)))
    2957             :     {
    2958       67628 :         const int   progress_index[] = {
    2959             :             PROGRESS_VACUUM_INDEXES_TOTAL,
    2960             :             PROGRESS_VACUUM_INDEXES_PROCESSED
    2961             :         };
    2962       67628 :         int64       progress_val[2] = {0, 0};
    2963             : 
    2964       67628 :         VacuumFailsafeActive = true;
    2965             : 
    2966             :         /*
    2967             :          * Abandon use of a buffer access strategy to allow use of all of
    2968             :          * shared buffers.  We assume the caller who allocated the memory for
    2969             :          * the BufferAccessStrategy will free it.
    2970             :          */
    2971       67628 :         vacrel->bstrategy = NULL;
    2972             : 
    2973             :         /* Disable index vacuuming, index cleanup, and heap rel truncation */
    2974       67628 :         vacrel->do_index_vacuuming = false;
    2975       67628 :         vacrel->do_index_cleanup = false;
    2976       67628 :         vacrel->do_rel_truncate = false;
    2977             : 
    2978             :         /* Reset the progress counters */
    2979       67628 :         pgstat_progress_update_multi_param(2, progress_index, progress_val);
    2980             : 
    2981       67628 :         ereport(WARNING,
    2982             :                 (errmsg("bypassing nonessential maintenance of table \"%s.%s.%s\" as a failsafe after %d index scans",
    2983             :                         vacrel->dbname, vacrel->relnamespace, vacrel->relname,
    2984             :                         vacrel->num_index_scans),
    2985             :                  errdetail("The table's relfrozenxid or relminmxid is too far in the past."),
    2986             :                  errhint("Consider increasing configuration parameter \"maintenance_work_mem\" or \"autovacuum_work_mem\".\n"
    2987             :                          "You might also need to consider other ways for VACUUM to keep up with the allocation of transaction IDs.")));
    2988             : 
    2989             :         /* Stop applying cost limits from this point on */
    2990       67628 :         VacuumCostActive = false;
    2991       67628 :         VacuumCostBalance = 0;
    2992             : 
    2993       67628 :         return true;
    2994             :     }
    2995             : 
    2996      181610 :     return false;
    2997             : }
    2998             : 
    2999             : /*
    3000             :  *  lazy_cleanup_all_indexes() -- cleanup all indexes of relation.
    3001             :  */
    3002             : static void
    3003      168810 : lazy_cleanup_all_indexes(LVRelState *vacrel)
    3004             : {
    3005      168810 :     double      reltuples = vacrel->new_rel_tuples;
    3006      168810 :     bool        estimated_count = vacrel->scanned_pages < vacrel->rel_pages;
    3007      168810 :     const int   progress_start_index[] = {
    3008             :         PROGRESS_VACUUM_PHASE,
    3009             :         PROGRESS_VACUUM_INDEXES_TOTAL
    3010             :     };
    3011      168810 :     const int   progress_end_index[] = {
    3012             :         PROGRESS_VACUUM_INDEXES_TOTAL,
    3013             :         PROGRESS_VACUUM_INDEXES_PROCESSED
    3014             :     };
    3015             :     int64       progress_start_val[2];
    3016      168810 :     int64       progress_end_val[2] = {0, 0};
    3017             : 
    3018             :     Assert(vacrel->do_index_cleanup);
    3019             :     Assert(vacrel->nindexes > 0);
    3020             : 
    3021             :     /*
    3022             :      * Report that we are now cleaning up indexes and the number of indexes to
    3023             :      * cleanup.
    3024             :      */
    3025      168810 :     progress_start_val[0] = PROGRESS_VACUUM_PHASE_INDEX_CLEANUP;
    3026      168810 :     progress_start_val[1] = vacrel->nindexes;
    3027      168810 :     pgstat_progress_update_multi_param(2, progress_start_index, progress_start_val);
    3028             : 
    3029      168810 :     if (!ParallelVacuumIsActive(vacrel))
    3030             :     {
    3031      434648 :         for (int idx = 0; idx < vacrel->nindexes; idx++)
    3032             :         {
    3033      265872 :             Relation    indrel = vacrel->indrels[idx];
    3034      265872 :             IndexBulkDeleteResult *istat = vacrel->indstats[idx];
    3035             : 
    3036      531744 :             vacrel->indstats[idx] =
    3037      265872 :                 lazy_cleanup_one_index(indrel, istat, reltuples,
    3038             :                                        estimated_count, vacrel);
    3039             : 
    3040             :             /* Report the number of indexes cleaned up */
    3041      265872 :             pgstat_progress_update_param(PROGRESS_VACUUM_INDEXES_PROCESSED,
    3042      265872 :                                          idx + 1);
    3043             :         }
    3044             :     }
    3045             :     else
    3046             :     {
    3047             :         /* Outsource everything to parallel variant */
    3048          34 :         parallel_vacuum_cleanup_all_indexes(vacrel->pvs, reltuples,
    3049             :                                             vacrel->num_index_scans,
    3050             :                                             estimated_count);
    3051             :     }
    3052             : 
    3053             :     /* Reset the progress counters */
    3054      168810 :     pgstat_progress_update_multi_param(2, progress_end_index, progress_end_val);
    3055      168810 : }
    3056             : 
    3057             : /*
    3058             :  *  lazy_vacuum_one_index() -- vacuum index relation.
    3059             :  *
    3060             :  *      Delete all the index tuples containing a TID collected in
    3061             :  *      vacrel->dead_items.  Also update running statistics. Exact
    3062             :  *      details depend on index AM's ambulkdelete routine.
    3063             :  *
    3064             :  *      reltuples is the number of heap tuples to be passed to the
    3065             :  *      bulkdelete callback.  It's always assumed to be estimated.
    3066             :  *      See indexam.sgml for more info.
    3067             :  *
    3068             :  * Returns bulk delete stats derived from input stats
    3069             :  */
    3070             : static IndexBulkDeleteResult *
    3071        2536 : lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat,
    3072             :                       double reltuples, LVRelState *vacrel)
    3073             : {
    3074             :     IndexVacuumInfo ivinfo;
    3075             :     LVSavedErrInfo saved_err_info;
    3076             : 
    3077        2536 :     ivinfo.index = indrel;
    3078        2536 :     ivinfo.heaprel = vacrel->rel;
    3079        2536 :     ivinfo.analyze_only = false;
    3080        2536 :     ivinfo.report_progress = false;
    3081        2536 :     ivinfo.estimated_count = true;
    3082        2536 :     ivinfo.message_level = DEBUG2;
    3083        2536 :     ivinfo.num_heap_tuples = reltuples;
    3084        2536 :     ivinfo.strategy = vacrel->bstrategy;
    3085             : 
    3086             :     /*
    3087             :      * Update error traceback information.
    3088             :      *
    3089             :      * The index name is saved during this phase and restored immediately
    3090             :      * after this phase.  See vacuum_error_callback.
    3091             :      */
    3092             :     Assert(vacrel->indname == NULL);
    3093        2536 :     vacrel->indname = pstrdup(RelationGetRelationName(indrel));
    3094        2536 :     update_vacuum_error_info(vacrel, &saved_err_info,
    3095             :                              VACUUM_ERRCB_PHASE_VACUUM_INDEX,
    3096             :                              InvalidBlockNumber, InvalidOffsetNumber);
    3097             : 
    3098             :     /* Do bulk deletion */
    3099        2536 :     istat = vac_bulkdel_one_index(&ivinfo, istat, vacrel->dead_items,
    3100             :                                   vacrel->dead_items_info);
    3101             : 
    3102             :     /* Revert to the previous phase information for error traceback */
    3103        2536 :     restore_vacuum_error_info(vacrel, &saved_err_info);
    3104        2536 :     pfree(vacrel->indname);
    3105        2536 :     vacrel->indname = NULL;
    3106             : 
    3107        2536 :     return istat;
    3108             : }
    3109             : 
    3110             : /*
    3111             :  *  lazy_cleanup_one_index() -- do post-vacuum cleanup for index relation.
    3112             :  *
    3113             :  *      Calls index AM's amvacuumcleanup routine.  reltuples is the number
    3114             :  *      of heap tuples and estimated_count is true if reltuples is an
    3115             :  *      estimated value.  See indexam.sgml for more info.
    3116             :  *
    3117             :  * Returns bulk delete stats derived from input stats
    3118             :  */
    3119             : static IndexBulkDeleteResult *
    3120      265872 : lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat,
    3121             :                        double reltuples, bool estimated_count,
    3122             :                        LVRelState *vacrel)
    3123             : {
    3124             :     IndexVacuumInfo ivinfo;
    3125             :     LVSavedErrInfo saved_err_info;
    3126             : 
    3127      265872 :     ivinfo.index = indrel;
    3128      265872 :     ivinfo.heaprel = vacrel->rel;
    3129      265872 :     ivinfo.analyze_only = false;
    3130      265872 :     ivinfo.report_progress = false;
    3131      265872 :     ivinfo.estimated_count = estimated_count;
    3132      265872 :     ivinfo.message_level = DEBUG2;
    3133             : 
    3134      265872 :     ivinfo.num_heap_tuples = reltuples;
    3135      265872 :     ivinfo.strategy = vacrel->bstrategy;
    3136             : 
    3137             :     /*
    3138             :      * Update error traceback information.
    3139             :      *
    3140             :      * The index name is saved during this phase and restored immediately
    3141             :      * after this phase.  See vacuum_error_callback.
    3142             :      */
    3143             :     Assert(vacrel->indname == NULL);
    3144      265872 :     vacrel->indname = pstrdup(RelationGetRelationName(indrel));
    3145      265872 :     update_vacuum_error_info(vacrel, &saved_err_info,
    3146             :                              VACUUM_ERRCB_PHASE_INDEX_CLEANUP,
    3147             :                              InvalidBlockNumber, InvalidOffsetNumber);
    3148             : 
    3149      265872 :     istat = vac_cleanup_one_index(&ivinfo, istat);
    3150             : 
    3151             :     /* Revert to the previous phase information for error traceback */
    3152      265872 :     restore_vacuum_error_info(vacrel, &saved_err_info);
    3153      265872 :     pfree(vacrel->indname);
    3154      265872 :     vacrel->indname = NULL;
    3155             : 
    3156      265872 :     return istat;
    3157             : }
    3158             : 
    3159             : /*
    3160             :  * should_attempt_truncation - should we attempt to truncate the heap?
    3161             :  *
    3162             :  * Don't even think about it unless we have a shot at releasing a goodly
    3163             :  * number of pages.  Otherwise, the time taken isn't worth it, mainly because
    3164             :  * an AccessExclusive lock must be replayed on any hot standby, where it can
    3165             :  * be particularly disruptive.
    3166             :  *
    3167             :  * Also don't attempt it if wraparound failsafe is in effect.  The entire
    3168             :  * system might be refusing to allocate new XIDs at this point.  The system
    3169             :  * definitely won't return to normal unless and until VACUUM actually advances
    3170             :  * the oldest relfrozenxid -- which hasn't happened for target rel just yet.
    3171             :  * If lazy_truncate_heap attempted to acquire an AccessExclusiveLock to
    3172             :  * truncate the table under these circumstances, an XID exhaustion error might
    3173             :  * make it impossible for VACUUM to fix the underlying XID exhaustion problem.
    3174             :  * There is very little chance of truncation working out when the failsafe is
    3175             :  * in effect in any case.  lazy_scan_prune makes the optimistic assumption
    3176             :  * that any LP_DEAD items it encounters will always be LP_UNUSED by the time
    3177             :  * we're called.
    3178             :  */
    3179             : static bool
    3180      245382 : should_attempt_truncation(LVRelState *vacrel)
    3181             : {
    3182             :     BlockNumber possibly_freeable;
    3183             : 
    3184      245382 :     if (!vacrel->do_rel_truncate || VacuumFailsafeActive)
    3185       67918 :         return false;
    3186             : 
    3187      177464 :     possibly_freeable = vacrel->rel_pages - vacrel->nonempty_pages;
    3188      177464 :     if (possibly_freeable > 0 &&
    3189         358 :         (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
    3190         358 :          possibly_freeable >= vacrel->rel_pages / REL_TRUNCATE_FRACTION))
    3191         330 :         return true;
    3192             : 
    3193      177134 :     return false;
    3194             : }
    3195             : 
    3196             : /*
    3197             :  * lazy_truncate_heap - try to truncate off any empty pages at the end
    3198             :  */
    3199             : static void
    3200         330 : lazy_truncate_heap(LVRelState *vacrel)
    3201             : {
    3202         330 :     BlockNumber orig_rel_pages = vacrel->rel_pages;
    3203             :     BlockNumber new_rel_pages;
    3204             :     bool        lock_waiter_detected;
    3205             :     int         lock_retry;
    3206             : 
    3207             :     /* Report that we are now truncating */
    3208         330 :     pgstat_progress_update_param(PROGRESS_VACUUM_PHASE,
    3209             :                                  PROGRESS_VACUUM_PHASE_TRUNCATE);
    3210             : 
    3211             :     /* Update error traceback information one last time */
    3212         330 :     update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_TRUNCATE,
    3213             :                              vacrel->nonempty_pages, InvalidOffsetNumber);
    3214             : 
    3215             :     /*
    3216             :      * Loop until no more truncating can be done.
    3217             :      */
    3218             :     do
    3219             :     {
    3220             :         /*
    3221             :          * We need full exclusive lock on the relation in order to do
    3222             :          * truncation. If we can't get it, give up rather than waiting --- we
    3223             :          * don't want to block other backends, and we don't want to deadlock
    3224             :          * (which is quite possible considering we already hold a lower-grade
    3225             :          * lock).
    3226             :          */
    3227         330 :         lock_waiter_detected = false;
    3228         330 :         lock_retry = 0;
    3229             :         while (true)
    3230             :         {
    3231         734 :             if (ConditionalLockRelation(vacrel->rel, AccessExclusiveLock))
    3232         326 :                 break;
    3233             : 
    3234             :             /*
    3235             :              * Check for interrupts while trying to (re-)acquire the exclusive
    3236             :              * lock.
    3237             :              */
    3238         408 :             CHECK_FOR_INTERRUPTS();
    3239             : 
    3240         408 :             if (++lock_retry > (VACUUM_TRUNCATE_LOCK_TIMEOUT /
    3241             :                                 VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL))
    3242             :             {
    3243             :                 /*
    3244             :                  * We failed to establish the lock in the specified number of
    3245             :                  * retries. This means we give up truncating.
    3246             :                  */
    3247           4 :                 ereport(vacrel->verbose ? INFO : DEBUG2,
    3248             :                         (errmsg("\"%s\": stopping truncate due to conflicting lock request",
    3249             :                                 vacrel->relname)));
    3250           6 :                 return;
    3251             :             }
    3252             : 
    3253         404 :             (void) WaitLatch(MyLatch,
    3254             :                              WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
    3255             :                              VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL,
    3256             :                              WAIT_EVENT_VACUUM_TRUNCATE);
    3257         404 :             ResetLatch(MyLatch);
    3258             :         }
    3259             : 
    3260             :         /*
    3261             :          * Now that we have exclusive lock, look to see if the rel has grown
    3262             :          * whilst we were vacuuming with non-exclusive lock.  If so, give up;
    3263             :          * the newly added pages presumably contain non-deletable tuples.
    3264             :          */
    3265         326 :         new_rel_pages = RelationGetNumberOfBlocks(vacrel->rel);
    3266         326 :         if (new_rel_pages != orig_rel_pages)
    3267             :         {
    3268             :             /*
    3269             :              * Note: we intentionally don't update vacrel->rel_pages with the
    3270             :              * new rel size here.  If we did, it would amount to assuming that
    3271             :              * the new pages are empty, which is unlikely. Leaving the numbers
    3272             :              * alone amounts to assuming that the new pages have the same
    3273             :              * tuple density as existing ones, which is less unlikely.
    3274             :              */
    3275           0 :             UnlockRelation(vacrel->rel, AccessExclusiveLock);
    3276           0 :             return;
    3277             :         }
    3278             : 
    3279             :         /*
    3280             :          * Scan backwards from the end to verify that the end pages actually
    3281             :          * contain no tuples.  This is *necessary*, not optional, because
    3282             :          * other backends could have added tuples to these pages whilst we
    3283             :          * were vacuuming.
    3284             :          */
    3285         326 :         new_rel_pages = count_nondeletable_pages(vacrel, &lock_waiter_detected);
    3286         326 :         vacrel->blkno = new_rel_pages;
    3287             : 
    3288         326 :         if (new_rel_pages >= orig_rel_pages)
    3289             :         {
    3290             :             /* can't do anything after all */
    3291           2 :             UnlockRelation(vacrel->rel, AccessExclusiveLock);
    3292           2 :             return;
    3293             :         }
    3294             : 
    3295             :         /*
    3296             :          * Okay to truncate.
    3297             :          */
    3298         324 :         RelationTruncate(vacrel->rel, new_rel_pages);
    3299             : 
    3300             :         /*
    3301             :          * We can release the exclusive lock as soon as we have truncated.
    3302             :          * Other backends can't safely access the relation until they have
    3303             :          * processed the smgr invalidation that smgrtruncate sent out ... but
    3304             :          * that should happen as part of standard invalidation processing once
    3305             :          * they acquire lock on the relation.
    3306             :          */
    3307         324 :         UnlockRelation(vacrel->rel, AccessExclusiveLock);
    3308             : 
    3309             :         /*
    3310             :          * Update statistics.  Here, it *is* correct to adjust rel_pages
    3311             :          * without also touching reltuples, since the tuple count wasn't
    3312             :          * changed by the truncation.
    3313             :          */
    3314         324 :         vacrel->removed_pages += orig_rel_pages - new_rel_pages;
    3315         324 :         vacrel->rel_pages = new_rel_pages;
    3316             : 
    3317         324 :         ereport(vacrel->verbose ? INFO : DEBUG2,
    3318             :                 (errmsg("table \"%s\": truncated %u to %u pages",
    3319             :                         vacrel->relname,
    3320             :                         orig_rel_pages, new_rel_pages)));
    3321         324 :         orig_rel_pages = new_rel_pages;
    3322         324 :     } while (new_rel_pages > vacrel->nonempty_pages && lock_waiter_detected);
    3323             : }
    3324             : 
    3325             : /*
    3326             :  * Rescan end pages to verify that they are (still) empty of tuples.
    3327             :  *
    3328             :  * Returns number of nondeletable pages (last nonempty page + 1).
    3329             :  */
    3330             : static BlockNumber
    3331         326 : count_nondeletable_pages(LVRelState *vacrel, bool *lock_waiter_detected)
    3332             : {
    3333             :     BlockNumber blkno;
    3334             :     BlockNumber prefetchedUntil;
    3335             :     instr_time  starttime;
    3336             : 
    3337             :     /* Initialize the starttime if we check for conflicting lock requests */
    3338         326 :     INSTR_TIME_SET_CURRENT(starttime);
    3339             : 
    3340             :     /*
    3341             :      * Start checking blocks at what we believe relation end to be and move
    3342             :      * backwards.  (Strange coding of loop control is needed because blkno is
    3343             :      * unsigned.)  To make the scan faster, we prefetch a few blocks at a time
    3344             :      * in forward direction, so that OS-level readahead can kick in.
    3345             :      */
    3346         326 :     blkno = vacrel->rel_pages;
    3347             :     StaticAssertStmt((PREFETCH_SIZE & (PREFETCH_SIZE - 1)) == 0,
    3348             :                      "prefetch size must be power of 2");
    3349         326 :     prefetchedUntil = InvalidBlockNumber;
    3350        5356 :     while (blkno > vacrel->nonempty_pages)
    3351             :     {
    3352             :         Buffer      buf;
    3353             :         Page        page;
    3354             :         OffsetNumber offnum,
    3355             :                     maxoff;
    3356             :         bool        hastup;
    3357             : 
    3358             :         /*
    3359             :          * Check if another process requests a lock on our relation. We are
    3360             :          * holding an AccessExclusiveLock here, so they will be waiting. We
    3361             :          * only do this once per VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and we
    3362             :          * only check if that interval has elapsed once every 32 blocks to
    3363             :          * keep the number of system calls and actual shared lock table
    3364             :          * lookups to a minimum.
    3365             :          */
    3366        5040 :         if ((blkno % 32) == 0)
    3367             :         {
    3368             :             instr_time  currenttime;
    3369             :             instr_time  elapsed;
    3370             : 
    3371         164 :             INSTR_TIME_SET_CURRENT(currenttime);
    3372         164 :             elapsed = currenttime;
    3373         164 :             INSTR_TIME_SUBTRACT(elapsed, starttime);
    3374         164 :             if ((INSTR_TIME_GET_MICROSEC(elapsed) / 1000)
    3375             :                 >= VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL)
    3376             :             {
    3377           0 :                 if (LockHasWaitersRelation(vacrel->rel, AccessExclusiveLock))
    3378             :                 {
    3379           0 :                     ereport(vacrel->verbose ? INFO : DEBUG2,
    3380             :                             (errmsg("table \"%s\": suspending truncate due to conflicting lock request",
    3381             :                                     vacrel->relname)));
    3382             : 
    3383           0 :                     *lock_waiter_detected = true;
    3384           0 :                     return blkno;
    3385             :                 }
    3386           0 :                 starttime = currenttime;
    3387             :             }
    3388             :         }
    3389             : 
    3390             :         /*
    3391             :          * We don't insert a vacuum delay point here, because we have an
    3392             :          * exclusive lock on the table which we want to hold for as short a
    3393             :          * time as possible.  We still need to check for interrupts however.
    3394             :          */
    3395        5040 :         CHECK_FOR_INTERRUPTS();
    3396             : 
    3397        5040 :         blkno--;
    3398             : 
    3399             :         /* If we haven't prefetched this lot yet, do so now. */
    3400        5040 :         if (prefetchedUntil > blkno)
    3401             :         {
    3402             :             BlockNumber prefetchStart;
    3403             :             BlockNumber pblkno;
    3404             : 
    3405         442 :             prefetchStart = blkno & ~(PREFETCH_SIZE - 1);
    3406        7388 :             for (pblkno = prefetchStart; pblkno <= blkno; pblkno++)
    3407             :             {
    3408        6946 :                 PrefetchBuffer(vacrel->rel, MAIN_FORKNUM, pblkno);
    3409        6946 :                 CHECK_FOR_INTERRUPTS();
    3410             :             }
    3411         442 :             prefetchedUntil = prefetchStart;
    3412             :         }
    3413             : 
    3414        5040 :         buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
    3415             :                                  vacrel->bstrategy);
    3416             : 
    3417             :         /* In this phase we only need shared access to the buffer */
    3418        5040 :         LockBuffer(buf, BUFFER_LOCK_SHARE);
    3419             : 
    3420        5040 :         page = BufferGetPage(buf);
    3421             : 
    3422        5040 :         if (PageIsNew(page) || PageIsEmpty(page))
    3423             :         {
    3424        2384 :             UnlockReleaseBuffer(buf);
    3425        2384 :             continue;
    3426             :         }
    3427             : 
    3428        2656 :         hastup = false;
    3429        2656 :         maxoff = PageGetMaxOffsetNumber(page);
    3430        2656 :         for (offnum = FirstOffsetNumber;
    3431        5302 :              offnum <= maxoff;
    3432        2646 :              offnum = OffsetNumberNext(offnum))
    3433             :         {
    3434             :             ItemId      itemid;
    3435             : 
    3436        2656 :             itemid = PageGetItemId(page, offnum);
    3437             : 
    3438             :             /*
    3439             :              * Note: any non-unused item should be taken as a reason to keep
    3440             :              * this page.  Even an LP_DEAD item makes truncation unsafe, since
    3441             :              * we must not have cleaned out its index entries.
    3442             :              */
    3443        2656 :             if (ItemIdIsUsed(itemid))
    3444             :             {
    3445          10 :                 hastup = true;
    3446          10 :                 break;          /* can stop scanning */
    3447             :             }
    3448             :         }                       /* scan along page */
    3449             : 
    3450        2656 :         UnlockReleaseBuffer(buf);
    3451             : 
    3452             :         /* Done scanning if we found a tuple here */
    3453        2656 :         if (hastup)
    3454          10 :             return blkno + 1;
    3455             :     }
    3456             : 
    3457             :     /*
    3458             :      * If we fall out of the loop, all the previously-thought-to-be-empty
    3459             :      * pages still are; we need not bother to look at the last known-nonempty
    3460             :      * page.
    3461             :      */
    3462         316 :     return vacrel->nonempty_pages;
    3463             : }
    3464             : 
    3465             : /*
    3466             :  * Allocate dead_items and dead_items_info (either using palloc, or in dynamic
    3467             :  * shared memory). Sets both in vacrel for caller.
    3468             :  *
    3469             :  * Also handles parallel initialization as part of allocating dead_items in
    3470             :  * DSM when required.
    3471             :  */
    3472             : static void
    3473      245382 : dead_items_alloc(LVRelState *vacrel, int nworkers)
    3474             : {
    3475             :     VacDeadItemsInfo *dead_items_info;
    3476      709958 :     int         vac_work_mem = AmAutoVacuumWorkerProcess() &&
    3477      219194 :         autovacuum_work_mem != -1 ?
    3478      464576 :         autovacuum_work_mem : maintenance_work_mem;
    3479             : 
    3480             :     /*
    3481             :      * Initialize state for a parallel vacuum.  As of now, only one worker can
    3482             :      * be used for an index, so we invoke parallelism only if there are at
    3483             :      * least two indexes on a table.
    3484             :      */
    3485      245382 :     if (nworkers >= 0 && vacrel->nindexes > 1 && vacrel->do_index_vacuuming)
    3486             :     {
    3487             :         /*
    3488             :          * Since parallel workers cannot access data in temporary tables, we
    3489             :          * can't perform parallel vacuum on them.
    3490             :          */
    3491       10394 :         if (RelationUsesLocalBuffers(vacrel->rel))
    3492             :         {
    3493             :             /*
    3494             :              * Give warning only if the user explicitly tries to perform a
    3495             :              * parallel vacuum on the temporary table.
    3496             :              */
    3497           6 :             if (nworkers > 0)
    3498           6 :                 ereport(WARNING,
    3499             :                         (errmsg("disabling parallel option of vacuum on \"%s\" --- cannot vacuum temporary tables in parallel",
    3500             :                                 vacrel->relname)));
    3501             :         }
    3502             :         else
    3503       10388 :             vacrel->pvs = parallel_vacuum_init(vacrel->rel, vacrel->indrels,
    3504             :                                                vacrel->nindexes, nworkers,
    3505             :                                                vac_work_mem,
    3506       10388 :                                                vacrel->verbose ? INFO : DEBUG2,
    3507             :                                                vacrel->bstrategy);
    3508             : 
    3509             :         /*
    3510             :          * If parallel mode started, dead_items and dead_items_info spaces are
    3511             :          * allocated in DSM.
    3512             :          */
    3513       10394 :         if (ParallelVacuumIsActive(vacrel))
    3514             :         {
    3515          34 :             vacrel->dead_items = parallel_vacuum_get_dead_items(vacrel->pvs,
    3516             :                                                                 &vacrel->dead_items_info);
    3517          34 :             return;
    3518             :         }
    3519             :     }
    3520             : 
    3521             :     /*
    3522             :      * Serial VACUUM case. Allocate both dead_items and dead_items_info
    3523             :      * locally.
    3524             :      */
    3525             : 
    3526      245348 :     dead_items_info = (VacDeadItemsInfo *) palloc(sizeof(VacDeadItemsInfo));
    3527      245348 :     dead_items_info->max_bytes = vac_work_mem * (Size) 1024;
    3528      245348 :     dead_items_info->num_items = 0;
    3529      245348 :     vacrel->dead_items_info = dead_items_info;
    3530             : 
    3531      245348 :     vacrel->dead_items = TidStoreCreateLocal(dead_items_info->max_bytes, true);
    3532             : }
    3533             : 
    3534             : /*
    3535             :  * Add the given block number and offset numbers to dead_items.
    3536             :  */
    3537             : static void
    3538       32874 : dead_items_add(LVRelState *vacrel, BlockNumber blkno, OffsetNumber *offsets,
    3539             :                int num_offsets)
    3540             : {
    3541       32874 :     const int   prog_index[2] = {
    3542             :         PROGRESS_VACUUM_NUM_DEAD_ITEM_IDS,
    3543             :         PROGRESS_VACUUM_DEAD_TUPLE_BYTES
    3544             :     };
    3545             :     int64       prog_val[2];
    3546             : 
    3547       32874 :     TidStoreSetBlockOffsets(vacrel->dead_items, blkno, offsets, num_offsets);
    3548       32874 :     vacrel->dead_items_info->num_items += num_offsets;
    3549             : 
    3550             :     /* update the progress information */
    3551       32874 :     prog_val[0] = vacrel->dead_items_info->num_items;
    3552       32874 :     prog_val[1] = TidStoreMemoryUsage(vacrel->dead_items);
    3553       32874 :     pgstat_progress_update_multi_param(2, prog_index, prog_val);
    3554       32874 : }
    3555             : 
    3556             : /*
    3557             :  * Forget all collected dead items.
    3558             :  */
    3559             : static void
    3560        1340 : dead_items_reset(LVRelState *vacrel)
    3561             : {
    3562        1340 :     if (ParallelVacuumIsActive(vacrel))
    3563             :     {
    3564          10 :         parallel_vacuum_reset_dead_items(vacrel->pvs);
    3565          10 :         return;
    3566             :     }
    3567             : 
    3568             :     /* Recreate the tidstore with the same max_bytes limitation */
    3569        1330 :     TidStoreDestroy(vacrel->dead_items);
    3570        1330 :     vacrel->dead_items = TidStoreCreateLocal(vacrel->dead_items_info->max_bytes, true);
    3571             : 
    3572             :     /* Reset the counter */
    3573        1330 :     vacrel->dead_items_info->num_items = 0;
    3574             : }
    3575             : 
    3576             : /*
    3577             :  * Perform cleanup for resources allocated in dead_items_alloc
    3578             :  */
    3579             : static void
    3580      245382 : dead_items_cleanup(LVRelState *vacrel)
    3581             : {
    3582      245382 :     if (!ParallelVacuumIsActive(vacrel))
    3583             :     {
    3584             :         /* Don't bother with pfree here */
    3585      245348 :         return;
    3586             :     }
    3587             : 
    3588             :     /* End parallel mode */
    3589          34 :     parallel_vacuum_end(vacrel->pvs, vacrel->indstats);
    3590          34 :     vacrel->pvs = NULL;
    3591             : }
    3592             : 
    3593             : /*
    3594             :  * Check if every tuple in the given page is visible to all current and future
    3595             :  * transactions. Also return the visibility_cutoff_xid which is the highest
    3596             :  * xmin amongst the visible tuples.  Set *all_frozen to true if every tuple
    3597             :  * on this page is frozen.
    3598             :  *
    3599             :  * This is a stripped down version of lazy_scan_prune().  If you change
    3600             :  * anything here, make sure that everything stays in sync.  Note that an
    3601             :  * assertion calls us to verify that everybody still agrees.  Be sure to avoid
    3602             :  * introducing new side-effects here.
    3603             :  */
    3604             : static bool
    3605       28212 : heap_page_is_all_visible(LVRelState *vacrel, Buffer buf,
    3606             :                          TransactionId *visibility_cutoff_xid,
    3607             :                          bool *all_frozen)
    3608             : {
    3609       28212 :     Page        page = BufferGetPage(buf);
    3610       28212 :     BlockNumber blockno = BufferGetBlockNumber(buf);
    3611             :     OffsetNumber offnum,
    3612             :                 maxoff;
    3613       28212 :     bool        all_visible = true;
    3614             : 
    3615       28212 :     *visibility_cutoff_xid = InvalidTransactionId;
    3616       28212 :     *all_frozen = true;
    3617             : 
    3618       28212 :     maxoff = PageGetMaxOffsetNumber(page);
    3619       28212 :     for (offnum = FirstOffsetNumber;
    3620     1374904 :          offnum <= maxoff && all_visible;
    3621     1346692 :          offnum = OffsetNumberNext(offnum))
    3622             :     {
    3623             :         ItemId      itemid;
    3624             :         HeapTupleData tuple;
    3625             : 
    3626             :         /*
    3627             :          * Set the offset number so that we can display it along with any
    3628             :          * error that occurred while processing this tuple.
    3629             :          */
    3630     1346698 :         vacrel->offnum = offnum;
    3631     1346698 :         itemid = PageGetItemId(page, offnum);
    3632             : 
    3633             :         /* Unused or redirect line pointers are of no interest */
    3634     1346698 :         if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
    3635      403070 :             continue;
    3636             : 
    3637      943628 :         ItemPointerSet(&(tuple.t_self), blockno, offnum);
    3638             : 
    3639             :         /*
    3640             :          * Dead line pointers can have index pointers pointing to them. So
    3641             :          * they can't be treated as visible
    3642             :          */
    3643      943628 :         if (ItemIdIsDead(itemid))
    3644             :         {
    3645           6 :             all_visible = false;
    3646           6 :             *all_frozen = false;
    3647           6 :             break;
    3648             :         }
    3649             : 
    3650             :         Assert(ItemIdIsNormal(itemid));
    3651             : 
    3652      943622 :         tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
    3653      943622 :         tuple.t_len = ItemIdGetLength(itemid);
    3654      943622 :         tuple.t_tableOid = RelationGetRelid(vacrel->rel);
    3655             : 
    3656      943622 :         switch (HeapTupleSatisfiesVacuum(&tuple, vacrel->cutoffs.OldestXmin,
    3657             :                                          buf))
    3658             :         {
    3659      943162 :             case HEAPTUPLE_LIVE:
    3660             :                 {
    3661             :                     TransactionId xmin;
    3662             : 
    3663             :                     /* Check comments in lazy_scan_prune. */
    3664      943162 :                     if (!HeapTupleHeaderXminCommitted(tuple.t_data))
    3665             :                     {
    3666           0 :                         all_visible = false;
    3667           0 :                         *all_frozen = false;
    3668           0 :                         break;
    3669             :                     }
    3670             : 
    3671             :                     /*
    3672             :                      * The inserter definitely committed. But is it old enough
    3673             :                      * that everyone sees it as committed?
    3674             :                      */
    3675      943162 :                     xmin = HeapTupleHeaderGetXmin(tuple.t_data);
    3676      943162 :                     if (!TransactionIdPrecedes(xmin,
    3677             :                                                vacrel->cutoffs.OldestXmin))
    3678             :                     {
    3679         192 :                         all_visible = false;
    3680         192 :                         *all_frozen = false;
    3681         192 :                         break;
    3682             :                     }
    3683             : 
    3684             :                     /* Track newest xmin on page. */
    3685      942970 :                     if (TransactionIdFollows(xmin, *visibility_cutoff_xid) &&
    3686             :                         TransactionIdIsNormal(xmin))
    3687       21266 :                         *visibility_cutoff_xid = xmin;
    3688             : 
    3689             :                     /* Check whether this tuple is already frozen or not */
    3690     1249634 :                     if (all_visible && *all_frozen &&
    3691      306664 :                         heap_tuple_needs_eventual_freeze(tuple.t_data))
    3692        5746 :                         *all_frozen = false;
    3693             :                 }
    3694      942970 :                 break;
    3695             : 
    3696         460 :             case HEAPTUPLE_DEAD:
    3697             :             case HEAPTUPLE_RECENTLY_DEAD:
    3698             :             case HEAPTUPLE_INSERT_IN_PROGRESS:
    3699             :             case HEAPTUPLE_DELETE_IN_PROGRESS:
    3700             :                 {
    3701         460 :                     all_visible = false;
    3702         460 :                     *all_frozen = false;
    3703         460 :                     break;
    3704             :                 }
    3705           0 :             default:
    3706           0 :                 elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
    3707             :                 break;
    3708             :         }
    3709             :     }                           /* scan along page */
    3710             : 
    3711             :     /* Clear the offset information once we have processed the given page. */
    3712       28212 :     vacrel->offnum = InvalidOffsetNumber;
    3713             : 
    3714       28212 :     return all_visible;
    3715             : }
    3716             : 
    3717             : /*
    3718             :  * Update index statistics in pg_class if the statistics are accurate.
    3719             :  */
    3720             : static void
    3721      177494 : update_relstats_all_indexes(LVRelState *vacrel)
    3722             : {
    3723      177494 :     Relation   *indrels = vacrel->indrels;
    3724      177494 :     int         nindexes = vacrel->nindexes;
    3725      177494 :     IndexBulkDeleteResult **indstats = vacrel->indstats;
    3726             : 
    3727             :     Assert(vacrel->do_index_cleanup);
    3728             : 
    3729      443488 :     for (int idx = 0; idx < nindexes; idx++)
    3730             :     {
    3731      265994 :         Relation    indrel = indrels[idx];
    3732      265994 :         IndexBulkDeleteResult *istat = indstats[idx];
    3733             : 
    3734      265994 :         if (istat == NULL || istat->estimated_count)
    3735      263178 :             continue;
    3736             : 
    3737             :         /* Update index statistics */
    3738        2816 :         vac_update_relstats(indrel,
    3739             :                             istat->num_pages,
    3740             :                             istat->num_index_tuples,
    3741             :                             0, 0,
    3742             :                             false,
    3743             :                             InvalidTransactionId,
    3744             :                             InvalidMultiXactId,
    3745             :                             NULL, NULL, false);
    3746             :     }
    3747      177494 : }
    3748             : 
    3749             : /*
    3750             :  * Error context callback for errors occurring during vacuum.  The error
    3751             :  * context messages for index phases should match the messages set in parallel
    3752             :  * vacuum.  If you change this function for those phases, change
    3753             :  * parallel_vacuum_error_callback() as well.
    3754             :  */
    3755             : static void
    3756      247832 : vacuum_error_callback(void *arg)
    3757             : {
    3758      247832 :     LVRelState *errinfo = arg;
    3759             : 
    3760      247832 :     switch (errinfo->phase)
    3761             :     {
    3762           0 :         case VACUUM_ERRCB_PHASE_SCAN_HEAP:
    3763           0 :             if (BlockNumberIsValid(errinfo->blkno))
    3764             :             {
    3765           0 :                 if (OffsetNumberIsValid(errinfo->offnum))
    3766           0 :                     errcontext("while scanning block %u offset %u of relation \"%s.%s\"",
    3767           0 :                                errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
    3768             :                 else
    3769           0 :                     errcontext("while scanning block %u of relation \"%s.%s\"",
    3770             :                                errinfo->blkno, errinfo->relnamespace, errinfo->relname);
    3771             :             }
    3772             :             else
    3773           0 :                 errcontext("while scanning relation \"%s.%s\"",
    3774             :                            errinfo->relnamespace, errinfo->relname);
    3775           0 :             break;
    3776             : 
    3777           0 :         case VACUUM_ERRCB_PHASE_VACUUM_HEAP:
    3778           0 :             if (BlockNumberIsValid(errinfo->blkno))
    3779             :             {
    3780           0 :                 if (OffsetNumberIsValid(errinfo->offnum))
    3781           0 :                     errcontext("while vacuuming block %u offset %u of relation \"%s.%s\"",
    3782           0 :                                errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
    3783             :                 else
    3784           0 :                     errcontext("while vacuuming block %u of relation \"%s.%s\"",
    3785             :                                errinfo->blkno, errinfo->relnamespace, errinfo->relname);
    3786             :             }
    3787             :             else
    3788           0 :                 errcontext("while vacuuming relation \"%s.%s\"",
    3789             :                            errinfo->relnamespace, errinfo->relname);
    3790           0 :             break;
    3791             : 
    3792           0 :         case VACUUM_ERRCB_PHASE_VACUUM_INDEX:
    3793           0 :             errcontext("while vacuuming index \"%s\" of relation \"%s.%s\"",
    3794             :                        errinfo->indname, errinfo->relnamespace, errinfo->relname);
    3795           0 :             break;
    3796             : 
    3797           0 :         case VACUUM_ERRCB_PHASE_INDEX_CLEANUP:
    3798           0 :             errcontext("while cleaning up index \"%s\" of relation \"%s.%s\"",
    3799             :                        errinfo->indname, errinfo->relnamespace, errinfo->relname);
    3800           0 :             break;
    3801             : 
    3802           6 :         case VACUUM_ERRCB_PHASE_TRUNCATE:
    3803           6 :             if (BlockNumberIsValid(errinfo->blkno))
    3804           6 :                 errcontext("while truncating relation \"%s.%s\" to %u blocks",
    3805             :                            errinfo->relnamespace, errinfo->relname, errinfo->blkno);
    3806           6 :             break;
    3807             : 
    3808      247826 :         case VACUUM_ERRCB_PHASE_UNKNOWN:
    3809             :         default:
    3810      247826 :             return;             /* do nothing; the errinfo may not be
    3811             :                                  * initialized */
    3812             :     }
    3813             : }
    3814             : 
    3815             : /*
    3816             :  * Updates the information required for vacuum error callback.  This also saves
    3817             :  * the current information which can be later restored via restore_vacuum_error_info.
    3818             :  */
    3819             : static void
    3820     1179624 : update_vacuum_error_info(LVRelState *vacrel, LVSavedErrInfo *saved_vacrel,
    3821             :                          int phase, BlockNumber blkno, OffsetNumber offnum)
    3822             : {
    3823     1179624 :     if (saved_vacrel)
    3824             :     {
    3825      297930 :         saved_vacrel->offnum = vacrel->offnum;
    3826      297930 :         saved_vacrel->blkno = vacrel->blkno;
    3827      297930 :         saved_vacrel->phase = vacrel->phase;
    3828             :     }
    3829             : 
    3830     1179624 :     vacrel->blkno = blkno;
    3831     1179624 :     vacrel->offnum = offnum;
    3832     1179624 :     vacrel->phase = phase;
    3833     1179624 : }
    3834             : 
    3835             : /*
    3836             :  * Restores the vacuum information saved via a prior call to update_vacuum_error_info.
    3837             :  */
    3838             : static void
    3839      297930 : restore_vacuum_error_info(LVRelState *vacrel,
    3840             :                           const LVSavedErrInfo *saved_vacrel)
    3841             : {
    3842      297930 :     vacrel->blkno = saved_vacrel->blkno;
    3843      297930 :     vacrel->offnum = saved_vacrel->offnum;
    3844      297930 :     vacrel->phase = saved_vacrel->phase;
    3845      297930 : }

Generated by: LCOV version 1.16