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

Generated by: LCOV version 1.16