LCOV - code coverage report
Current view: top level - src/backend/access/heap - vacuumlazy.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 815 967 84.3 %
Date: 2025-04-01 15:15:16 Functions: 30 30 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14