LCOV - differential code coverage report
Current view: top level - src/backend/access/heap - vacuumlazy.c (source / functions) Coverage Total Hit LBC UBC GBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 87.7 % 1048 919 2 127 2 13 904 4
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 31 31 3 28
Baseline: lcov-20261128-baseline Branches: 70.5 % 650 458 1 191 2 456
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 6 6 6
(30,360] days: 81.2 % 128 104 24 13 91
(360..) days: 88.5 % 914 809 2 103 2 807
Function coverage date bins:
(30,360] days: 100.0 % 2 2 1 1
(360..) days: 100.0 % 29 29 2 27
Branch coverage date bins:
(30,360] days: 68.8 % 93 64 29 64
(360..) days: 70.7 % 557 394 1 162 2 392

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

Generated by: LCOV version 2.0-1