PostgreSQL Source Code  git master
vacuumlazy.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/genam.h"
#include "access/heapam.h"
#include "access/heapam_xlog.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/tidstore.h"
#include "access/transam.h"
#include "access/visibilitymap.h"
#include "access/xloginsert.h"
#include "catalog/storage.h"
#include "commands/dbcommands.h"
#include "commands/progress.h"
#include "commands/vacuum.h"
#include "common/int.h"
#include "executor/instrument.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "portability/instr_time.h"
#include "postmaster/autovacuum.h"
#include "storage/bufmgr.h"
#include "storage/freespace.h"
#include "storage/lmgr.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.h"
#include "utils/timestamp.h"
Include dependency graph for vacuumlazy.c:

Go to the source code of this file.

Data Structures

struct  LVRelState
 
struct  LVSavedErrInfo
 

Macros

#define REL_TRUNCATE_MINIMUM   1000
 
#define REL_TRUNCATE_FRACTION   16
 
#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL   20 /* ms */
 
#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL   50 /* ms */
 
#define VACUUM_TRUNCATE_LOCK_TIMEOUT   5000 /* ms */
 
#define BYPASS_THRESHOLD_PAGES   0.02 /* i.e. 2% of rel_pages */
 
#define FAILSAFE_EVERY_PAGES    ((BlockNumber) (((uint64) 4 * 1024 * 1024 * 1024) / BLCKSZ))
 
#define VACUUM_FSM_EVERY_PAGES    ((BlockNumber) (((uint64) 8 * 1024 * 1024 * 1024) / BLCKSZ))
 
#define SKIP_PAGES_THRESHOLD   ((BlockNumber) 32)
 
#define PREFETCH_SIZE   ((BlockNumber) 32)
 
#define ParallelVacuumIsActive(vacrel)   ((vacrel)->pvs != NULL)
 

Typedefs

typedef struct LVRelState LVRelState
 
typedef struct LVSavedErrInfo LVSavedErrInfo
 

Enumerations

enum  VacErrPhase {
  VACUUM_ERRCB_PHASE_UNKNOWN , VACUUM_ERRCB_PHASE_SCAN_HEAP , VACUUM_ERRCB_PHASE_VACUUM_INDEX , VACUUM_ERRCB_PHASE_VACUUM_HEAP ,
  VACUUM_ERRCB_PHASE_INDEX_CLEANUP , VACUUM_ERRCB_PHASE_TRUNCATE
}
 

Functions

static void lazy_scan_heap (LVRelState *vacrel)
 
static bool heap_vac_scan_next_block (LVRelState *vacrel, BlockNumber *blkno, bool *all_visible_according_to_vm)
 
static void find_next_unskippable_block (LVRelState *vacrel, bool *skipsallvis)
 
static bool lazy_scan_new_or_empty (LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, bool sharelock, Buffer vmbuffer)
 
static void lazy_scan_prune (LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, Buffer vmbuffer, bool all_visible_according_to_vm, bool *has_lpdead_items)
 
static bool lazy_scan_noprune (LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, bool *has_lpdead_items)
 
static void lazy_vacuum (LVRelState *vacrel)
 
static bool lazy_vacuum_all_indexes (LVRelState *vacrel)
 
static void lazy_vacuum_heap_rel (LVRelState *vacrel)
 
static void lazy_vacuum_heap_page (LVRelState *vacrel, BlockNumber blkno, Buffer buffer, OffsetNumber *offsets, int num_offsets, Buffer vmbuffer)
 
static bool lazy_check_wraparound_failsafe (LVRelState *vacrel)
 
static void lazy_cleanup_all_indexes (LVRelState *vacrel)
 
static IndexBulkDeleteResultlazy_vacuum_one_index (Relation indrel, IndexBulkDeleteResult *istat, double reltuples, LVRelState *vacrel)
 
static IndexBulkDeleteResultlazy_cleanup_one_index (Relation indrel, IndexBulkDeleteResult *istat, double reltuples, bool estimated_count, LVRelState *vacrel)
 
static bool should_attempt_truncation (LVRelState *vacrel)
 
static void lazy_truncate_heap (LVRelState *vacrel)
 
static BlockNumber count_nondeletable_pages (LVRelState *vacrel, bool *lock_waiter_detected)
 
static void dead_items_alloc (LVRelState *vacrel, int nworkers)
 
static void dead_items_add (LVRelState *vacrel, BlockNumber blkno, OffsetNumber *offsets, int num_offsets)
 
static void dead_items_reset (LVRelState *vacrel)
 
static void dead_items_cleanup (LVRelState *vacrel)
 
static bool heap_page_is_all_visible (LVRelState *vacrel, Buffer buf, TransactionId *visibility_cutoff_xid, bool *all_frozen)
 
static void update_relstats_all_indexes (LVRelState *vacrel)
 
static void vacuum_error_callback (void *arg)
 
static void update_vacuum_error_info (LVRelState *vacrel, LVSavedErrInfo *saved_vacrel, int phase, BlockNumber blkno, OffsetNumber offnum)
 
static void restore_vacuum_error_info (LVRelState *vacrel, const LVSavedErrInfo *saved_vacrel)
 
void heap_vacuum_rel (Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy)
 
static int cmpOffsetNumbers (const void *a, const void *b)
 

Macro Definition Documentation

◆ BYPASS_THRESHOLD_PAGES

#define BYPASS_THRESHOLD_PAGES   0.02 /* i.e. 2% of rel_pages */

Definition at line 89 of file vacuumlazy.c.

◆ FAILSAFE_EVERY_PAGES

#define FAILSAFE_EVERY_PAGES    ((BlockNumber) (((uint64) 4 * 1024 * 1024 * 1024) / BLCKSZ))

Definition at line 95 of file vacuumlazy.c.

◆ ParallelVacuumIsActive

#define ParallelVacuumIsActive (   vacrel)    ((vacrel)->pvs != NULL)

Definition at line 123 of file vacuumlazy.c.

◆ PREFETCH_SIZE

#define PREFETCH_SIZE   ((BlockNumber) 32)

Definition at line 117 of file vacuumlazy.c.

◆ REL_TRUNCATE_FRACTION

#define REL_TRUNCATE_FRACTION   16

Definition at line 72 of file vacuumlazy.c.

◆ REL_TRUNCATE_MINIMUM

#define REL_TRUNCATE_MINIMUM   1000

Definition at line 71 of file vacuumlazy.c.

◆ SKIP_PAGES_THRESHOLD

#define SKIP_PAGES_THRESHOLD   ((BlockNumber) 32)

Definition at line 111 of file vacuumlazy.c.

◆ VACUUM_FSM_EVERY_PAGES

#define VACUUM_FSM_EVERY_PAGES    ((BlockNumber) (((uint64) 8 * 1024 * 1024 * 1024) / BLCKSZ))

Definition at line 104 of file vacuumlazy.c.

◆ VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL

#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL   20 /* ms */

Definition at line 81 of file vacuumlazy.c.

◆ VACUUM_TRUNCATE_LOCK_TIMEOUT

#define VACUUM_TRUNCATE_LOCK_TIMEOUT   5000 /* ms */

Definition at line 83 of file vacuumlazy.c.

◆ VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL

#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL   50 /* ms */

Definition at line 82 of file vacuumlazy.c.

Typedef Documentation

◆ LVRelState

typedef struct LVRelState LVRelState

◆ LVSavedErrInfo

Enumeration Type Documentation

◆ VacErrPhase

Enumerator
VACUUM_ERRCB_PHASE_UNKNOWN 
VACUUM_ERRCB_PHASE_SCAN_HEAP 
VACUUM_ERRCB_PHASE_VACUUM_INDEX 
VACUUM_ERRCB_PHASE_VACUUM_HEAP 
VACUUM_ERRCB_PHASE_INDEX_CLEANUP 
VACUUM_ERRCB_PHASE_TRUNCATE 

Definition at line 126 of file vacuumlazy.c.

127 {
134 } VacErrPhase;
VacErrPhase
Definition: vacuumlazy.c:127
@ VACUUM_ERRCB_PHASE_SCAN_HEAP
Definition: vacuumlazy.c:129
@ VACUUM_ERRCB_PHASE_VACUUM_INDEX
Definition: vacuumlazy.c:130
@ VACUUM_ERRCB_PHASE_TRUNCATE
Definition: vacuumlazy.c:133
@ VACUUM_ERRCB_PHASE_INDEX_CLEANUP
Definition: vacuumlazy.c:132
@ VACUUM_ERRCB_PHASE_VACUUM_HEAP
Definition: vacuumlazy.c:131
@ VACUUM_ERRCB_PHASE_UNKNOWN
Definition: vacuumlazy.c:128

Function Documentation

◆ cmpOffsetNumbers()

static int cmpOffsetNumbers ( const void *  a,
const void *  b 
)
static

Definition at line 1389 of file vacuumlazy.c.

1390 {
1391  return pg_cmp_u16(*(const OffsetNumber *) a, *(const OffsetNumber *) b);
1392 }
static int pg_cmp_u16(uint16 a, uint16 b)
Definition: int.h:477
int b
Definition: isn.c:70
int a
Definition: isn.c:69
uint16 OffsetNumber
Definition: off.h:24

References a, b, and pg_cmp_u16().

Referenced by lazy_scan_prune().

◆ count_nondeletable_pages()

static BlockNumber count_nondeletable_pages ( LVRelState vacrel,
bool lock_waiter_detected 
)
static

Definition at line 2677 of file vacuumlazy.c.

2678 {
2679  BlockNumber blkno;
2680  BlockNumber prefetchedUntil;
2681  instr_time starttime;
2682 
2683  /* Initialize the starttime if we check for conflicting lock requests */
2684  INSTR_TIME_SET_CURRENT(starttime);
2685 
2686  /*
2687  * Start checking blocks at what we believe relation end to be and move
2688  * backwards. (Strange coding of loop control is needed because blkno is
2689  * unsigned.) To make the scan faster, we prefetch a few blocks at a time
2690  * in forward direction, so that OS-level readahead can kick in.
2691  */
2692  blkno = vacrel->rel_pages;
2694  "prefetch size must be power of 2");
2695  prefetchedUntil = InvalidBlockNumber;
2696  while (blkno > vacrel->nonempty_pages)
2697  {
2698  Buffer buf;
2699  Page page;
2700  OffsetNumber offnum,
2701  maxoff;
2702  bool hastup;
2703 
2704  /*
2705  * Check if another process requests a lock on our relation. We are
2706  * holding an AccessExclusiveLock here, so they will be waiting. We
2707  * only do this once per VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and we
2708  * only check if that interval has elapsed once every 32 blocks to
2709  * keep the number of system calls and actual shared lock table
2710  * lookups to a minimum.
2711  */
2712  if ((blkno % 32) == 0)
2713  {
2714  instr_time currenttime;
2715  instr_time elapsed;
2716 
2717  INSTR_TIME_SET_CURRENT(currenttime);
2718  elapsed = currenttime;
2719  INSTR_TIME_SUBTRACT(elapsed, starttime);
2720  if ((INSTR_TIME_GET_MICROSEC(elapsed) / 1000)
2722  {
2724  {
2725  ereport(vacrel->verbose ? INFO : DEBUG2,
2726  (errmsg("table \"%s\": suspending truncate due to conflicting lock request",
2727  vacrel->relname)));
2728 
2729  *lock_waiter_detected = true;
2730  return blkno;
2731  }
2732  starttime = currenttime;
2733  }
2734  }
2735 
2736  /*
2737  * We don't insert a vacuum delay point here, because we have an
2738  * exclusive lock on the table which we want to hold for as short a
2739  * time as possible. We still need to check for interrupts however.
2740  */
2742 
2743  blkno--;
2744 
2745  /* If we haven't prefetched this lot yet, do so now. */
2746  if (prefetchedUntil > blkno)
2747  {
2748  BlockNumber prefetchStart;
2749  BlockNumber pblkno;
2750 
2751  prefetchStart = blkno & ~(PREFETCH_SIZE - 1);
2752  for (pblkno = prefetchStart; pblkno <= blkno; pblkno++)
2753  {
2754  PrefetchBuffer(vacrel->rel, MAIN_FORKNUM, pblkno);
2756  }
2757  prefetchedUntil = prefetchStart;
2758  }
2759 
2760  buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
2761  vacrel->bstrategy);
2762 
2763  /* In this phase we only need shared access to the buffer */
2765 
2766  page = BufferGetPage(buf);
2767 
2768  if (PageIsNew(page) || PageIsEmpty(page))
2769  {
2771  continue;
2772  }
2773 
2774  hastup = false;
2775  maxoff = PageGetMaxOffsetNumber(page);
2776  for (offnum = FirstOffsetNumber;
2777  offnum <= maxoff;
2778  offnum = OffsetNumberNext(offnum))
2779  {
2780  ItemId itemid;
2781 
2782  itemid = PageGetItemId(page, offnum);
2783 
2784  /*
2785  * Note: any non-unused item should be taken as a reason to keep
2786  * this page. Even an LP_DEAD item makes truncation unsafe, since
2787  * we must not have cleaned out its index entries.
2788  */
2789  if (ItemIdIsUsed(itemid))
2790  {
2791  hastup = true;
2792  break; /* can stop scanning */
2793  }
2794  } /* scan along page */
2795 
2797 
2798  /* Done scanning if we found a tuple here */
2799  if (hastup)
2800  return blkno + 1;
2801  }
2802 
2803  /*
2804  * If we fall out of the loop, all the previously-thought-to-be-empty
2805  * pages still are; we need not bother to look at the last known-nonempty
2806  * page.
2807  */
2808  return vacrel->nonempty_pages;
2809 }
uint32 BlockNumber
Definition: block.h:31
#define InvalidBlockNumber
Definition: block.h:33
int Buffer
Definition: buf.h:23
PrefetchBufferResult PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition: bufmgr.c:638
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4867
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:5085
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:792
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:198
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:408
@ RBM_NORMAL
Definition: bufmgr.h:45
static bool PageIsEmpty(Page page)
Definition: bufpage.h:220
Pointer Page
Definition: bufpage.h:78
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:240
static bool PageIsNew(Page page)
Definition: bufpage.h:230
static OffsetNumber PageGetMaxOffsetNumber(Page page)
Definition: bufpage.h:369
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:938
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define DEBUG2
Definition: elog.h:29
#define INFO
Definition: elog.h:34
#define ereport(elevel,...)
Definition: elog.h:149
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:122
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:181
#define INSTR_TIME_GET_MICROSEC(t)
Definition: instr_time.h:194
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
bool LockHasWaitersRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:373
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define FirstOffsetNumber
Definition: off.h:27
static char * buf
Definition: pg_test_fsync.c:73
@ MAIN_FORKNUM
Definition: relpath.h:50
bool verbose
Definition: vacuumlazy.c:175
BlockNumber nonempty_pages
Definition: vacuumlazy.c:196
Relation rel
Definition: vacuumlazy.c:139
BlockNumber rel_pages
Definition: vacuumlazy.c:190
BufferAccessStrategy bstrategy
Definition: vacuumlazy.c:144
char * relname
Definition: vacuumlazy.c:170
#define PREFETCH_SIZE
Definition: vacuumlazy.c:117
#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL
Definition: vacuumlazy.c:81

References AccessExclusiveLock, LVRelState::bstrategy, buf, BUFFER_LOCK_SHARE, BufferGetPage(), CHECK_FOR_INTERRUPTS, DEBUG2, ereport, errmsg(), FirstOffsetNumber, INFO, INSTR_TIME_GET_MICROSEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, InvalidBlockNumber, ItemIdIsUsed, LockBuffer(), LockHasWaitersRelation(), MAIN_FORKNUM, LVRelState::nonempty_pages, OffsetNumberNext, PageGetItemId(), PageGetMaxOffsetNumber(), PageIsEmpty(), PageIsNew(), PREFETCH_SIZE, PrefetchBuffer(), RBM_NORMAL, ReadBufferExtended(), LVRelState::rel, LVRelState::rel_pages, LVRelState::relname, StaticAssertStmt, UnlockReleaseBuffer(), VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and LVRelState::verbose.

Referenced by lazy_truncate_heap().

◆ dead_items_add()

static void dead_items_add ( LVRelState vacrel,
BlockNumber  blkno,
OffsetNumber offsets,
int  num_offsets 
)
static

Definition at line 2884 of file vacuumlazy.c.

2886 {
2887  TidStore *dead_items = vacrel->dead_items;
2888 
2889  TidStoreSetBlockOffsets(dead_items, blkno, offsets, num_offsets);
2890  vacrel->dead_items_info->num_items += num_offsets;
2891 
2892  /* update the memory usage report */
2894  TidStoreMemoryUsage(dead_items));
2895 }
void pgstat_progress_update_param(int index, int64 val)
#define PROGRESS_VACUUM_DEAD_TUPLE_BYTES
Definition: progress.h:27
VacDeadItemsInfo * dead_items_info
Definition: vacuumlazy.c:188
TidStore * dead_items
Definition: vacuumlazy.c:187
int64 num_items
Definition: vacuum.h:288
void TidStoreSetBlockOffsets(TidStore *ts, BlockNumber blkno, OffsetNumber *offsets, int num_offsets)
Definition: tidstore.c:356
size_t TidStoreMemoryUsage(TidStore *ts)
Definition: tidstore.c:551

References LVRelState::dead_items, LVRelState::dead_items_info, VacDeadItemsInfo::num_items, pgstat_progress_update_param(), PROGRESS_VACUUM_DEAD_TUPLE_BYTES, TidStoreMemoryUsage(), and TidStoreSetBlockOffsets().

Referenced by lazy_scan_noprune(), and lazy_scan_prune().

◆ dead_items_alloc()

static void dead_items_alloc ( LVRelState vacrel,
int  nworkers 
)
static

Definition at line 2819 of file vacuumlazy.c.

2820 {
2821  VacDeadItemsInfo *dead_items_info;
2822  int vac_work_mem = AmAutoVacuumWorkerProcess() &&
2823  autovacuum_work_mem != -1 ?
2825 
2826  /*
2827  * Initialize state for a parallel vacuum. As of now, only one worker can
2828  * be used for an index, so we invoke parallelism only if there are at
2829  * least two indexes on a table.
2830  */
2831  if (nworkers >= 0 && vacrel->nindexes > 1 && vacrel->do_index_vacuuming)
2832  {
2833  /*
2834  * Since parallel workers cannot access data in temporary tables, we
2835  * can't perform parallel vacuum on them.
2836  */
2837  if (RelationUsesLocalBuffers(vacrel->rel))
2838  {
2839  /*
2840  * Give warning only if the user explicitly tries to perform a
2841  * parallel vacuum on the temporary table.
2842  */
2843  if (nworkers > 0)
2844  ereport(WARNING,
2845  (errmsg("disabling parallel option of vacuum on \"%s\" --- cannot vacuum temporary tables in parallel",
2846  vacrel->relname)));
2847  }
2848  else
2849  vacrel->pvs = parallel_vacuum_init(vacrel->rel, vacrel->indrels,
2850  vacrel->nindexes, nworkers,
2851  vac_work_mem,
2852  vacrel->verbose ? INFO : DEBUG2,
2853  vacrel->bstrategy);
2854 
2855  /*
2856  * If parallel mode started, dead_items and dead_items_info spaces are
2857  * allocated in DSM.
2858  */
2859  if (ParallelVacuumIsActive(vacrel))
2860  {
2861  vacrel->dead_items = parallel_vacuum_get_dead_items(vacrel->pvs,
2862  &vacrel->dead_items_info);
2863  return;
2864  }
2865  }
2866 
2867  /*
2868  * Serial VACUUM case. Allocate both dead_items and dead_items_info
2869  * locally.
2870  */
2871 
2872  dead_items_info = (VacDeadItemsInfo *) palloc(sizeof(VacDeadItemsInfo));
2873  dead_items_info->max_bytes = vac_work_mem * 1024L;
2874  dead_items_info->num_items = 0;
2875  vacrel->dead_items_info = dead_items_info;
2876 
2877  vacrel->dead_items = TidStoreCreateLocal(dead_items_info->max_bytes, true);
2878 }
int autovacuum_work_mem
Definition: autovacuum.c:118
#define WARNING
Definition: elog.h:36
int maintenance_work_mem
Definition: globals.c:130
void * palloc(Size size)
Definition: mcxt.c:1316
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:375
#define RelationUsesLocalBuffers(relation)
Definition: rel.h:637
ParallelVacuumState * pvs
Definition: vacuumlazy.c:145
int nindexes
Definition: vacuumlazy.c:141
Relation * indrels
Definition: vacuumlazy.c:140
bool do_index_vacuuming
Definition: vacuumlazy.c:155
size_t max_bytes
Definition: vacuum.h:287
TidStore * TidStoreCreateLocal(size_t max_bytes, bool insert_only)
Definition: tidstore.c:165
#define ParallelVacuumIsActive(vacrel)
Definition: vacuumlazy.c:123
ParallelVacuumState * parallel_vacuum_init(Relation rel, Relation *indrels, int nindexes, int nrequested_workers, int vac_work_mem, int elevel, BufferAccessStrategy bstrategy)
TidStore * parallel_vacuum_get_dead_items(ParallelVacuumState *pvs, VacDeadItemsInfo **dead_items_info_p)

References AmAutoVacuumWorkerProcess, autovacuum_work_mem, LVRelState::bstrategy, LVRelState::dead_items, LVRelState::dead_items_info, DEBUG2, LVRelState::do_index_vacuuming, ereport, errmsg(), LVRelState::indrels, INFO, maintenance_work_mem, VacDeadItemsInfo::max_bytes, LVRelState::nindexes, VacDeadItemsInfo::num_items, palloc(), parallel_vacuum_get_dead_items(), parallel_vacuum_init(), ParallelVacuumIsActive, LVRelState::pvs, LVRelState::rel, RelationUsesLocalBuffers, LVRelState::relname, TidStoreCreateLocal(), LVRelState::verbose, and WARNING.

Referenced by heap_vacuum_rel().

◆ dead_items_cleanup()

static void dead_items_cleanup ( LVRelState vacrel)
static

Definition at line 2923 of file vacuumlazy.c.

2924 {
2925  if (!ParallelVacuumIsActive(vacrel))
2926  {
2927  /* Don't bother with pfree here */
2928  return;
2929  }
2930 
2931  /* End parallel mode */
2932  parallel_vacuum_end(vacrel->pvs, vacrel->indstats);
2933  vacrel->pvs = NULL;
2934 }
IndexBulkDeleteResult ** indstats
Definition: vacuumlazy.c:202
void parallel_vacuum_end(ParallelVacuumState *pvs, IndexBulkDeleteResult **istats)

References LVRelState::indstats, parallel_vacuum_end(), ParallelVacuumIsActive, and LVRelState::pvs.

Referenced by heap_vacuum_rel().

◆ dead_items_reset()

static void dead_items_reset ( LVRelState vacrel)
static

Definition at line 2901 of file vacuumlazy.c.

2902 {
2903  TidStore *dead_items = vacrel->dead_items;
2904 
2905  if (ParallelVacuumIsActive(vacrel))
2906  {
2908  return;
2909  }
2910 
2911  /* Recreate the tidstore with the same max_bytes limitation */
2912  TidStoreDestroy(dead_items);
2913  vacrel->dead_items = TidStoreCreateLocal(vacrel->dead_items_info->max_bytes, true);
2914 
2915  /* Reset the counter */
2916  vacrel->dead_items_info->num_items = 0;
2917 }
void TidStoreDestroy(TidStore *ts)
Definition: tidstore.c:328
void parallel_vacuum_reset_dead_items(ParallelVacuumState *pvs)

References LVRelState::dead_items, LVRelState::dead_items_info, VacDeadItemsInfo::max_bytes, VacDeadItemsInfo::num_items, parallel_vacuum_reset_dead_items(), ParallelVacuumIsActive, LVRelState::pvs, TidStoreCreateLocal(), and TidStoreDestroy().

Referenced by lazy_vacuum().

◆ find_next_unskippable_block()

static void find_next_unskippable_block ( LVRelState vacrel,
bool skipsallvis 
)
static

Definition at line 1186 of file vacuumlazy.c.

1187 {
1188  BlockNumber rel_pages = vacrel->rel_pages;
1189  BlockNumber next_unskippable_block = vacrel->next_unskippable_block + 1;
1190  Buffer next_unskippable_vmbuffer = vacrel->next_unskippable_vmbuffer;
1191  bool next_unskippable_allvis;
1192 
1193  *skipsallvis = false;
1194 
1195  for (;;)
1196  {
1197  uint8 mapbits = visibilitymap_get_status(vacrel->rel,
1198  next_unskippable_block,
1199  &next_unskippable_vmbuffer);
1200 
1201  next_unskippable_allvis = (mapbits & VISIBILITYMAP_ALL_VISIBLE) != 0;
1202 
1203  /*
1204  * A block is unskippable if it is not all visible according to the
1205  * visibility map.
1206  */
1207  if (!next_unskippable_allvis)
1208  {
1209  Assert((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0);
1210  break;
1211  }
1212 
1213  /*
1214  * Caller must scan the last page to determine whether it has tuples
1215  * (caller must have the opportunity to set vacrel->nonempty_pages).
1216  * This rule avoids having lazy_truncate_heap() take access-exclusive
1217  * lock on rel to attempt a truncation that fails anyway, just because
1218  * there are tuples on the last page (it is likely that there will be
1219  * tuples on other nearby pages as well, but those can be skipped).
1220  *
1221  * Implement this by always treating the last block as unsafe to skip.
1222  */
1223  if (next_unskippable_block == rel_pages - 1)
1224  break;
1225 
1226  /* DISABLE_PAGE_SKIPPING makes all skipping unsafe */
1227  if (!vacrel->skipwithvm)
1228  break;
1229 
1230  /*
1231  * Aggressive VACUUM caller can't skip pages just because they are
1232  * all-visible. They may still skip all-frozen pages, which can't
1233  * contain XIDs < OldestXmin (XIDs that aren't already frozen by now).
1234  */
1235  if ((mapbits & VISIBILITYMAP_ALL_FROZEN) == 0)
1236  {
1237  if (vacrel->aggressive)
1238  break;
1239 
1240  /*
1241  * All-visible block is safe to skip in non-aggressive case. But
1242  * remember that the final range contains such a block for later.
1243  */
1244  *skipsallvis = true;
1245  }
1246 
1247  next_unskippable_block++;
1248  }
1249 
1250  /* write the local variables back to vacrel */
1251  vacrel->next_unskippable_block = next_unskippable_block;
1252  vacrel->next_unskippable_allvis = next_unskippable_allvis;
1253  vacrel->next_unskippable_vmbuffer = next_unskippable_vmbuffer;
1254 }
#define Assert(condition)
Definition: c.h:858
unsigned char uint8
Definition: c.h:504
Buffer next_unskippable_vmbuffer
Definition: vacuumlazy.c:218
bool aggressive
Definition: vacuumlazy.c:148
BlockNumber next_unskippable_block
Definition: vacuumlazy.c:216
bool skipwithvm
Definition: vacuumlazy.c:150
bool next_unskippable_allvis
Definition: vacuumlazy.c:217
uint8 visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)
#define VISIBILITYMAP_ALL_FROZEN
#define VISIBILITYMAP_ALL_VISIBLE

References LVRelState::aggressive, Assert, LVRelState::next_unskippable_allvis, LVRelState::next_unskippable_block, LVRelState::next_unskippable_vmbuffer, LVRelState::rel, LVRelState::rel_pages, LVRelState::skipwithvm, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, and visibilitymap_get_status().

Referenced by heap_vac_scan_next_block().

◆ heap_page_is_all_visible()

static bool heap_page_is_all_visible ( LVRelState vacrel,
Buffer  buf,
TransactionId visibility_cutoff_xid,
bool all_frozen 
)
static

Definition at line 2948 of file vacuumlazy.c.

2951 {
2952  Page page = BufferGetPage(buf);
2954  OffsetNumber offnum,
2955  maxoff;
2956  bool all_visible = true;
2957 
2958  *visibility_cutoff_xid = InvalidTransactionId;
2959  *all_frozen = true;
2960 
2961  maxoff = PageGetMaxOffsetNumber(page);
2962  for (offnum = FirstOffsetNumber;
2963  offnum <= maxoff && all_visible;
2964  offnum = OffsetNumberNext(offnum))
2965  {
2966  ItemId itemid;
2967  HeapTupleData tuple;
2968 
2969  /*
2970  * Set the offset number so that we can display it along with any
2971  * error that occurred while processing this tuple.
2972  */
2973  vacrel->offnum = offnum;
2974  itemid = PageGetItemId(page, offnum);
2975 
2976  /* Unused or redirect line pointers are of no interest */
2977  if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
2978  continue;
2979 
2980  ItemPointerSet(&(tuple.t_self), blockno, offnum);
2981 
2982  /*
2983  * Dead line pointers can have index pointers pointing to them. So
2984  * they can't be treated as visible
2985  */
2986  if (ItemIdIsDead(itemid))
2987  {
2988  all_visible = false;
2989  *all_frozen = false;
2990  break;
2991  }
2992 
2993  Assert(ItemIdIsNormal(itemid));
2994 
2995  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
2996  tuple.t_len = ItemIdGetLength(itemid);
2997  tuple.t_tableOid = RelationGetRelid(vacrel->rel);
2998 
2999  switch (HeapTupleSatisfiesVacuum(&tuple, vacrel->cutoffs.OldestXmin,
3000  buf))
3001  {
3002  case HEAPTUPLE_LIVE:
3003  {
3004  TransactionId xmin;
3005 
3006  /* Check comments in lazy_scan_prune. */
3008  {
3009  all_visible = false;
3010  *all_frozen = false;
3011  break;
3012  }
3013 
3014  /*
3015  * The inserter definitely committed. But is it old enough
3016  * that everyone sees it as committed?
3017  */
3018  xmin = HeapTupleHeaderGetXmin(tuple.t_data);
3019  if (!TransactionIdPrecedes(xmin,
3020  vacrel->cutoffs.OldestXmin))
3021  {
3022  all_visible = false;
3023  *all_frozen = false;
3024  break;
3025  }
3026 
3027  /* Track newest xmin on page. */
3028  if (TransactionIdFollows(xmin, *visibility_cutoff_xid) &&
3029  TransactionIdIsNormal(xmin))
3030  *visibility_cutoff_xid = xmin;
3031 
3032  /* Check whether this tuple is already frozen or not */
3033  if (all_visible && *all_frozen &&
3035  *all_frozen = false;
3036  }
3037  break;
3038 
3039  case HEAPTUPLE_DEAD:
3043  {
3044  all_visible = false;
3045  *all_frozen = false;
3046  break;
3047  }
3048  default:
3049  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
3050  break;
3051  }
3052  } /* scan along page */
3053 
3054  /* Clear the offset information once we have processed the given page. */
3055  vacrel->offnum = InvalidOffsetNumber;
3056 
3057  return all_visible;
3058 }
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:3667
static Item PageGetItem(Page page, ItemId itemId)
Definition: bufpage.h:351
uint32 TransactionId
Definition: c.h:652
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
Definition: heapam.c:7319
@ HEAPTUPLE_RECENTLY_DEAD
Definition: heapam.h:127
@ HEAPTUPLE_INSERT_IN_PROGRESS
Definition: heapam.h:128
@ HEAPTUPLE_LIVE
Definition: heapam.h:126
@ HEAPTUPLE_DELETE_IN_PROGRESS
Definition: heapam.h:129
@ HEAPTUPLE_DEAD
Definition: heapam.h:125
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:309
#define HeapTupleHeaderXminCommitted(tup)
Definition: htup_details.h:320
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
static void ItemPointerSet(ItemPointerData *pointer, BlockNumber blockNumber, OffsetNumber offNum)
Definition: itemptr.h:135
#define InvalidOffsetNumber
Definition: off.h:26
#define RelationGetRelid(relation)
Definition: rel.h:505
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
HeapTupleHeader t_data
Definition: htup.h:68
Oid t_tableOid
Definition: htup.h:66
OffsetNumber offnum
Definition: vacuumlazy.c:173
struct VacuumCutoffs cutoffs
Definition: vacuumlazy.c:160
TransactionId OldestXmin
Definition: vacuum.h:267
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:314
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

References Assert, buf, BufferGetBlockNumber(), BufferGetPage(), LVRelState::cutoffs, elog, ERROR, FirstOffsetNumber, heap_tuple_needs_eventual_freeze(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderGetXmin, HeapTupleHeaderXminCommitted, HeapTupleSatisfiesVacuum(), InvalidOffsetNumber, InvalidTransactionId, ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet(), LVRelState::offnum, OffsetNumberNext, VacuumCutoffs::OldestXmin, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), LVRelState::rel, RelationGetRelid, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdFollows(), TransactionIdIsNormal, and TransactionIdPrecedes().

Referenced by lazy_scan_prune(), and lazy_vacuum_heap_page().

◆ heap_vac_scan_next_block()

static bool heap_vac_scan_next_block ( LVRelState vacrel,
BlockNumber blkno,
bool all_visible_according_to_vm 
)
static

Definition at line 1088 of file vacuumlazy.c.

1090 {
1091  BlockNumber next_block;
1092 
1093  /* relies on InvalidBlockNumber + 1 overflowing to 0 on first call */
1094  next_block = vacrel->current_block + 1;
1095 
1096  /* Have we reached the end of the relation? */
1097  if (next_block >= vacrel->rel_pages)
1098  {
1100  {
1103  }
1104  *blkno = vacrel->rel_pages;
1105  return false;
1106  }
1107 
1108  /*
1109  * We must be in one of the three following states:
1110  */
1111  if (next_block > vacrel->next_unskippable_block ||
1113  {
1114  /*
1115  * 1. We have just processed an unskippable block (or we're at the
1116  * beginning of the scan). Find the next unskippable block using the
1117  * visibility map.
1118  */
1119  bool skipsallvis;
1120 
1121  find_next_unskippable_block(vacrel, &skipsallvis);
1122 
1123  /*
1124  * We now know the next block that we must process. It can be the
1125  * next block after the one we just processed, or something further
1126  * ahead. If it's further ahead, we can jump to it, but we choose to
1127  * do so only if we can skip at least SKIP_PAGES_THRESHOLD consecutive
1128  * pages. Since we're reading sequentially, the OS should be doing
1129  * readahead for us, so there's no gain in skipping a page now and
1130  * then. Skipping such a range might even discourage sequential
1131  * detection.
1132  *
1133  * This test also enables more frequent relfrozenxid advancement
1134  * during non-aggressive VACUUMs. If the range has any all-visible
1135  * pages then skipping makes updating relfrozenxid unsafe, which is a
1136  * real downside.
1137  */
1138  if (vacrel->next_unskippable_block - next_block >= SKIP_PAGES_THRESHOLD)
1139  {
1140  next_block = vacrel->next_unskippable_block;
1141  if (skipsallvis)
1142  vacrel->skippedallvis = true;
1143  }
1144  }
1145 
1146  /* Now we must be in one of the two remaining states: */
1147  if (next_block < vacrel->next_unskippable_block)
1148  {
1149  /*
1150  * 2. We are processing a range of blocks that we could have skipped
1151  * but chose not to. We know that they are all-visible in the VM,
1152  * otherwise they would've been unskippable.
1153  */
1154  *blkno = vacrel->current_block = next_block;
1155  *all_visible_according_to_vm = true;
1156  return true;
1157  }
1158  else
1159  {
1160  /*
1161  * 3. We reached the next unskippable block. Process it. On next
1162  * iteration, we will be back in state 1.
1163  */
1164  Assert(next_block == vacrel->next_unskippable_block);
1165 
1166  *blkno = vacrel->current_block = next_block;
1167  *all_visible_according_to_vm = vacrel->next_unskippable_allvis;
1168  return true;
1169  }
1170 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4850
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:359
BlockNumber current_block
Definition: vacuumlazy.c:215
bool skippedallvis
Definition: vacuumlazy.c:165
static void find_next_unskippable_block(LVRelState *vacrel, bool *skipsallvis)
Definition: vacuumlazy.c:1186
#define SKIP_PAGES_THRESHOLD
Definition: vacuumlazy.c:111

References Assert, BufferIsValid(), LVRelState::current_block, find_next_unskippable_block(), InvalidBlockNumber, InvalidBuffer, LVRelState::next_unskippable_allvis, LVRelState::next_unskippable_block, LVRelState::next_unskippable_vmbuffer, LVRelState::rel_pages, ReleaseBuffer(), SKIP_PAGES_THRESHOLD, and LVRelState::skippedallvis.

Referenced by lazy_scan_heap().

◆ heap_vacuum_rel()

void heap_vacuum_rel ( Relation  rel,
VacuumParams params,
BufferAccessStrategy  bstrategy 
)

Definition at line 295 of file vacuumlazy.c.

297 {
298  LVRelState *vacrel;
299  bool verbose,
300  instrument,
301  skipwithvm,
302  frozenxid_updated,
303  minmulti_updated;
304  BlockNumber orig_rel_pages,
305  new_rel_pages,
306  new_rel_allvisible;
307  PGRUsage ru0;
308  TimestampTz starttime = 0;
309  PgStat_Counter startreadtime = 0,
310  startwritetime = 0;
311  WalUsage startwalusage = pgWalUsage;
312  int64 StartPageHit = VacuumPageHit,
313  StartPageMiss = VacuumPageMiss,
314  StartPageDirty = VacuumPageDirty;
315  ErrorContextCallback errcallback;
316  char **indnames = NULL;
317 
318  verbose = (params->options & VACOPT_VERBOSE) != 0;
319  instrument = (verbose || (AmAutoVacuumWorkerProcess() &&
320  params->log_min_duration >= 0));
321  if (instrument)
322  {
323  pg_rusage_init(&ru0);
324  starttime = GetCurrentTimestamp();
325  if (track_io_timing)
326  {
327  startreadtime = pgStatBlockReadTime;
328  startwritetime = pgStatBlockWriteTime;
329  }
330  }
331 
333  RelationGetRelid(rel));
334 
335  /*
336  * Setup error traceback support for ereport() first. The idea is to set
337  * up an error context callback to display additional information on any
338  * error during a vacuum. During different phases of vacuum, we update
339  * the state so that the error context callback always display current
340  * information.
341  *
342  * Copy the names of heap rel into local memory for error reporting
343  * purposes, too. It isn't always safe to assume that we can get the name
344  * of each rel. It's convenient for code in lazy_scan_heap to always use
345  * these temp copies.
346  */
347  vacrel = (LVRelState *) palloc0(sizeof(LVRelState));
350  vacrel->relname = pstrdup(RelationGetRelationName(rel));
351  vacrel->indname = NULL;
353  vacrel->verbose = verbose;
354  errcallback.callback = vacuum_error_callback;
355  errcallback.arg = vacrel;
356  errcallback.previous = error_context_stack;
357  error_context_stack = &errcallback;
358 
359  /* Set up high level stuff about rel and its indexes */
360  vacrel->rel = rel;
361  vac_open_indexes(vacrel->rel, RowExclusiveLock, &vacrel->nindexes,
362  &vacrel->indrels);
363  vacrel->bstrategy = bstrategy;
364  if (instrument && vacrel->nindexes > 0)
365  {
366  /* Copy index names used by instrumentation (not error reporting) */
367  indnames = palloc(sizeof(char *) * vacrel->nindexes);
368  for (int i = 0; i < vacrel->nindexes; i++)
369  indnames[i] = pstrdup(RelationGetRelationName(vacrel->indrels[i]));
370  }
371 
372  /*
373  * The index_cleanup param either disables index vacuuming and cleanup or
374  * forces it to go ahead when we would otherwise apply the index bypass
375  * optimization. The default is 'auto', which leaves the final decision
376  * up to lazy_vacuum().
377  *
378  * The truncate param allows user to avoid attempting relation truncation,
379  * though it can't force truncation to happen.
380  */
383  params->truncate != VACOPTVALUE_AUTO);
384 
385  /*
386  * While VacuumFailSafeActive is reset to false before calling this, we
387  * still need to reset it here due to recursive calls.
388  */
389  VacuumFailsafeActive = false;
390  vacrel->consider_bypass_optimization = true;
391  vacrel->do_index_vacuuming = true;
392  vacrel->do_index_cleanup = true;
393  vacrel->do_rel_truncate = (params->truncate != VACOPTVALUE_DISABLED);
394  if (params->index_cleanup == VACOPTVALUE_DISABLED)
395  {
396  /* Force disable index vacuuming up-front */
397  vacrel->do_index_vacuuming = false;
398  vacrel->do_index_cleanup = false;
399  }
400  else if (params->index_cleanup == VACOPTVALUE_ENABLED)
401  {
402  /* Force index vacuuming. Note that failsafe can still bypass. */
403  vacrel->consider_bypass_optimization = false;
404  }
405  else
406  {
407  /* Default/auto, make all decisions dynamically */
409  }
410 
411  /* Initialize page counters explicitly (be tidy) */
412  vacrel->scanned_pages = 0;
413  vacrel->removed_pages = 0;
414  vacrel->frozen_pages = 0;
415  vacrel->lpdead_item_pages = 0;
416  vacrel->missed_dead_pages = 0;
417  vacrel->nonempty_pages = 0;
418  /* dead_items_alloc allocates vacrel->dead_items later on */
419 
420  /* Allocate/initialize output statistics state */
421  vacrel->new_rel_tuples = 0;
422  vacrel->new_live_tuples = 0;
423  vacrel->indstats = (IndexBulkDeleteResult **)
424  palloc0(vacrel->nindexes * sizeof(IndexBulkDeleteResult *));
425 
426  /* Initialize remaining counters (be tidy) */
427  vacrel->num_index_scans = 0;
428  vacrel->tuples_deleted = 0;
429  vacrel->tuples_frozen = 0;
430  vacrel->lpdead_items = 0;
431  vacrel->live_tuples = 0;
432  vacrel->recently_dead_tuples = 0;
433  vacrel->missed_dead_tuples = 0;
434 
435  /*
436  * Get cutoffs that determine which deleted tuples are considered DEAD,
437  * not just RECENTLY_DEAD, and which XIDs/MXIDs to freeze. Then determine
438  * the extent of the blocks that we'll scan in lazy_scan_heap. It has to
439  * happen in this order to ensure that the OldestXmin cutoff field works
440  * as an upper bound on the XIDs stored in the pages we'll actually scan
441  * (NewRelfrozenXid tracking must never be allowed to miss unfrozen XIDs).
442  *
443  * Next acquire vistest, a related cutoff that's used in pruning. We
444  * expect vistest will always make heap_page_prune_and_freeze() remove any
445  * deleted tuple whose xmax is < OldestXmin. lazy_scan_prune must never
446  * become confused about whether a tuple should be frozen or removed. (In
447  * the future we might want to teach lazy_scan_prune to recompute vistest
448  * from time to time, to increase the number of dead tuples it can prune
449  * away.)
450  */
451  vacrel->aggressive = vacuum_get_cutoffs(rel, params, &vacrel->cutoffs);
452  vacrel->rel_pages = orig_rel_pages = RelationGetNumberOfBlocks(rel);
453  vacrel->vistest = GlobalVisTestFor(rel);
454  /* Initialize state used to track oldest extant XID/MXID */
455  vacrel->NewRelfrozenXid = vacrel->cutoffs.OldestXmin;
456  vacrel->NewRelminMxid = vacrel->cutoffs.OldestMxact;
457  vacrel->skippedallvis = false;
458  skipwithvm = true;
460  {
461  /*
462  * Force aggressive mode, and disable skipping blocks using the
463  * visibility map (even those set all-frozen)
464  */
465  vacrel->aggressive = true;
466  skipwithvm = false;
467  }
468 
469  vacrel->skipwithvm = skipwithvm;
470 
471  if (verbose)
472  {
473  if (vacrel->aggressive)
474  ereport(INFO,
475  (errmsg("aggressively vacuuming \"%s.%s.%s\"",
476  vacrel->dbname, vacrel->relnamespace,
477  vacrel->relname)));
478  else
479  ereport(INFO,
480  (errmsg("vacuuming \"%s.%s.%s\"",
481  vacrel->dbname, vacrel->relnamespace,
482  vacrel->relname)));
483  }
484 
485  /*
486  * Allocate dead_items memory using dead_items_alloc. This handles
487  * parallel VACUUM initialization as part of allocating shared memory
488  * space used for dead_items. (But do a failsafe precheck first, to
489  * ensure that parallel VACUUM won't be attempted at all when relfrozenxid
490  * is already dangerously old.)
491  */
493  dead_items_alloc(vacrel, params->nworkers);
494 
495  /*
496  * Call lazy_scan_heap to perform all required heap pruning, index
497  * vacuuming, and heap vacuuming (plus related processing)
498  */
499  lazy_scan_heap(vacrel);
500 
501  /*
502  * Free resources managed by dead_items_alloc. This ends parallel mode in
503  * passing when necessary.
504  */
505  dead_items_cleanup(vacrel);
507 
508  /*
509  * Update pg_class entries for each of rel's indexes where appropriate.
510  *
511  * Unlike the later update to rel's pg_class entry, this is not critical.
512  * Maintains relpages/reltuples statistics used by the planner only.
513  */
514  if (vacrel->do_index_cleanup)
516 
517  /* Done with rel's indexes */
518  vac_close_indexes(vacrel->nindexes, vacrel->indrels, NoLock);
519 
520  /* Optionally truncate rel */
521  if (should_attempt_truncation(vacrel))
522  lazy_truncate_heap(vacrel);
523 
524  /* Pop the error context stack */
525  error_context_stack = errcallback.previous;
526 
527  /* Report that we are now doing final cleanup */
530 
531  /*
532  * Prepare to update rel's pg_class entry.
533  *
534  * Aggressive VACUUMs must always be able to advance relfrozenxid to a
535  * value >= FreezeLimit, and relminmxid to a value >= MultiXactCutoff.
536  * Non-aggressive VACUUMs may advance them by any amount, or not at all.
537  */
538  Assert(vacrel->NewRelfrozenXid == vacrel->cutoffs.OldestXmin ||
540  vacrel->cutoffs.relfrozenxid,
541  vacrel->NewRelfrozenXid));
542  Assert(vacrel->NewRelminMxid == vacrel->cutoffs.OldestMxact ||
544  vacrel->cutoffs.relminmxid,
545  vacrel->NewRelminMxid));
546  if (vacrel->skippedallvis)
547  {
548  /*
549  * Must keep original relfrozenxid in a non-aggressive VACUUM that
550  * chose to skip an all-visible page range. The state that tracks new
551  * values will have missed unfrozen XIDs from the pages we skipped.
552  */
553  Assert(!vacrel->aggressive);
556  }
557 
558  /*
559  * For safety, clamp relallvisible to be not more than what we're setting
560  * pg_class.relpages to
561  */
562  new_rel_pages = vacrel->rel_pages; /* After possible rel truncation */
563  visibilitymap_count(rel, &new_rel_allvisible, NULL);
564  if (new_rel_allvisible > new_rel_pages)
565  new_rel_allvisible = new_rel_pages;
566 
567  /*
568  * Now actually update rel's pg_class entry.
569  *
570  * In principle new_live_tuples could be -1 indicating that we (still)
571  * don't know the tuple count. In practice that can't happen, since we
572  * scan every page that isn't skipped using the visibility map.
573  */
574  vac_update_relstats(rel, new_rel_pages, vacrel->new_live_tuples,
575  new_rel_allvisible, vacrel->nindexes > 0,
576  vacrel->NewRelfrozenXid, vacrel->NewRelminMxid,
577  &frozenxid_updated, &minmulti_updated, false);
578 
579  /*
580  * Report results to the cumulative stats system, too.
581  *
582  * Deliberately avoid telling the stats system about LP_DEAD items that
583  * remain in the table due to VACUUM bypassing index and heap vacuuming.
584  * ANALYZE will consider the remaining LP_DEAD items to be dead "tuples".
585  * It seems like a good idea to err on the side of not vacuuming again too
586  * soon in cases where the failsafe prevented significant amounts of heap
587  * vacuuming.
588  */
590  rel->rd_rel->relisshared,
591  Max(vacrel->new_live_tuples, 0),
592  vacrel->recently_dead_tuples +
593  vacrel->missed_dead_tuples);
595 
596  if (instrument)
597  {
598  TimestampTz endtime = GetCurrentTimestamp();
599 
600  if (verbose || params->log_min_duration == 0 ||
601  TimestampDifferenceExceeds(starttime, endtime,
602  params->log_min_duration))
603  {
604  long secs_dur;
605  int usecs_dur;
606  WalUsage walusage;
608  char *msgfmt;
609  int32 diff;
610  int64 PageHitOp = VacuumPageHit - StartPageHit,
611  PageMissOp = VacuumPageMiss - StartPageMiss,
612  PageDirtyOp = VacuumPageDirty - StartPageDirty;
613  double read_rate = 0,
614  write_rate = 0;
615 
616  TimestampDifference(starttime, endtime, &secs_dur, &usecs_dur);
617  memset(&walusage, 0, sizeof(WalUsage));
618  WalUsageAccumDiff(&walusage, &pgWalUsage, &startwalusage);
619 
621  if (verbose)
622  {
623  /*
624  * Aggressiveness already reported earlier, in dedicated
625  * VACUUM VERBOSE ereport
626  */
627  Assert(!params->is_wraparound);
628  msgfmt = _("finished vacuuming \"%s.%s.%s\": index scans: %d\n");
629  }
630  else if (params->is_wraparound)
631  {
632  /*
633  * While it's possible for a VACUUM to be both is_wraparound
634  * and !aggressive, that's just a corner-case -- is_wraparound
635  * implies aggressive. Produce distinct output for the corner
636  * case all the same, just in case.
637  */
638  if (vacrel->aggressive)
639  msgfmt = _("automatic aggressive vacuum to prevent wraparound of table \"%s.%s.%s\": index scans: %d\n");
640  else
641  msgfmt = _("automatic vacuum to prevent wraparound of table \"%s.%s.%s\": index scans: %d\n");
642  }
643  else
644  {
645  if (vacrel->aggressive)
646  msgfmt = _("automatic aggressive vacuum of table \"%s.%s.%s\": index scans: %d\n");
647  else
648  msgfmt = _("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n");
649  }
650  appendStringInfo(&buf, msgfmt,
651  vacrel->dbname,
652  vacrel->relnamespace,
653  vacrel->relname,
654  vacrel->num_index_scans);
655  appendStringInfo(&buf, _("pages: %u removed, %u remain, %u scanned (%.2f%% of total)\n"),
656  vacrel->removed_pages,
657  new_rel_pages,
658  vacrel->scanned_pages,
659  orig_rel_pages == 0 ? 100.0 :
660  100.0 * vacrel->scanned_pages / orig_rel_pages);
662  _("tuples: %lld removed, %lld remain, %lld are dead but not yet removable\n"),
663  (long long) vacrel->tuples_deleted,
664  (long long) vacrel->new_rel_tuples,
665  (long long) vacrel->recently_dead_tuples);
666  if (vacrel->missed_dead_tuples > 0)
668  _("tuples missed: %lld dead from %u pages not removed due to cleanup lock contention\n"),
669  (long long) vacrel->missed_dead_tuples,
670  vacrel->missed_dead_pages);
671  diff = (int32) (ReadNextTransactionId() -
672  vacrel->cutoffs.OldestXmin);
674  _("removable cutoff: %u, which was %d XIDs old when operation ended\n"),
675  vacrel->cutoffs.OldestXmin, diff);
676  if (frozenxid_updated)
677  {
678  diff = (int32) (vacrel->NewRelfrozenXid -
679  vacrel->cutoffs.relfrozenxid);
681  _("new relfrozenxid: %u, which is %d XIDs ahead of previous value\n"),
682  vacrel->NewRelfrozenXid, diff);
683  }
684  if (minmulti_updated)
685  {
686  diff = (int32) (vacrel->NewRelminMxid -
687  vacrel->cutoffs.relminmxid);
689  _("new relminmxid: %u, which is %d MXIDs ahead of previous value\n"),
690  vacrel->NewRelminMxid, diff);
691  }
692  appendStringInfo(&buf, _("frozen: %u pages from table (%.2f%% of total) had %lld tuples frozen\n"),
693  vacrel->frozen_pages,
694  orig_rel_pages == 0 ? 100.0 :
695  100.0 * vacrel->frozen_pages / orig_rel_pages,
696  (long long) vacrel->tuples_frozen);
697  if (vacrel->do_index_vacuuming)
698  {
699  if (vacrel->nindexes == 0 || vacrel->num_index_scans == 0)
700  appendStringInfoString(&buf, _("index scan not needed: "));
701  else
702  appendStringInfoString(&buf, _("index scan needed: "));
703 
704  msgfmt = _("%u pages from table (%.2f%% of total) had %lld dead item identifiers removed\n");
705  }
706  else
707  {
709  appendStringInfoString(&buf, _("index scan bypassed: "));
710  else
711  appendStringInfoString(&buf, _("index scan bypassed by failsafe: "));
712 
713  msgfmt = _("%u pages from table (%.2f%% of total) have %lld dead item identifiers\n");
714  }
715  appendStringInfo(&buf, msgfmt,
716  vacrel->lpdead_item_pages,
717  orig_rel_pages == 0 ? 100.0 :
718  100.0 * vacrel->lpdead_item_pages / orig_rel_pages,
719  (long long) vacrel->lpdead_items);
720  for (int i = 0; i < vacrel->nindexes; i++)
721  {
722  IndexBulkDeleteResult *istat = vacrel->indstats[i];
723 
724  if (!istat)
725  continue;
726 
728  _("index \"%s\": pages: %u in total, %u newly deleted, %u currently deleted, %u reusable\n"),
729  indnames[i],
730  istat->num_pages,
731  istat->pages_newly_deleted,
732  istat->pages_deleted,
733  istat->pages_free);
734  }
735  if (track_io_timing)
736  {
737  double read_ms = (double) (pgStatBlockReadTime - startreadtime) / 1000;
738  double write_ms = (double) (pgStatBlockWriteTime - startwritetime) / 1000;
739 
740  appendStringInfo(&buf, _("I/O timings: read: %.3f ms, write: %.3f ms\n"),
741  read_ms, write_ms);
742  }
743  if (secs_dur > 0 || usecs_dur > 0)
744  {
745  read_rate = (double) BLCKSZ * PageMissOp / (1024 * 1024) /
746  (secs_dur + usecs_dur / 1000000.0);
747  write_rate = (double) BLCKSZ * PageDirtyOp / (1024 * 1024) /
748  (secs_dur + usecs_dur / 1000000.0);
749  }
750  appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
751  read_rate, write_rate);
753  _("buffer usage: %lld hits, %lld misses, %lld dirtied\n"),
754  (long long) PageHitOp,
755  (long long) PageMissOp,
756  (long long) PageDirtyOp);
758  _("WAL usage: %lld records, %lld full page images, %llu bytes\n"),
759  (long long) walusage.wal_records,
760  (long long) walusage.wal_fpi,
761  (unsigned long long) walusage.wal_bytes);
762  appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
763 
764  ereport(verbose ? INFO : LOG,
765  (errmsg_internal("%s", buf.data)));
766  pfree(buf.data);
767  }
768  }
769 
770  /* Cleanup index statistics and index names */
771  for (int i = 0; i < vacrel->nindexes; i++)
772  {
773  if (vacrel->indstats[i])
774  pfree(vacrel->indstats[i]);
775 
776  if (instrument)
777  pfree(indnames[i]);
778  }
779 }
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1730
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1790
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
void pgstat_progress_end_command(void)
@ PROGRESS_COMMAND_VACUUM
bool track_io_timing
Definition: bufmgr.c:142
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:281
signed int int32
Definition: c.h:494
#define Max(x, y)
Definition: c.h:998
int64 TimestampTz
Definition: timestamp.h:39
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3153
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
ErrorContextCallback * error_context_stack
Definition: elog.c:94
#define _(x)
Definition: elog.c:90
#define LOG
Definition: elog.h:31
int64 VacuumPageHit
Definition: globals.c:154
int64 VacuumPageMiss
Definition: globals.c:155
int64 VacuumPageDirty
Definition: globals.c:156
Oid MyDatabaseId
Definition: globals.c:91
int verbose
WalUsage pgWalUsage
Definition: instrument.c:22
void WalUsageAccumDiff(WalUsage *dst, const WalUsage *add, const WalUsage *sub)
Definition: instrument.c:286
int i
Definition: isn.c:73
#define NoLock
Definition: lockdefs.h:34
#define RowExclusiveLock
Definition: lockdefs.h:38
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
char * pstrdup(const char *in)
Definition: mcxt.c:1695
void pfree(void *pointer)
Definition: mcxt.c:1520
void * palloc0(Size size)
Definition: mcxt.c:1346
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3274
#define InvalidMultiXactId
Definition: multixact.h:24
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
int64 PgStat_Counter
Definition: pgstat.h:89
PgStat_Counter pgStatBlockReadTime
PgStat_Counter pgStatBlockWriteTime
void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples)
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition: procarray.c:4091
#define PROGRESS_VACUUM_PHASE_FINAL_CLEANUP
Definition: progress.h:37
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationGetNamespace(relation)
Definition: rel.h:546
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296
BlockNumber pages_deleted
Definition: genam.h:82
BlockNumber pages_newly_deleted
Definition: genam.h:81
BlockNumber pages_free
Definition: genam.h:83
BlockNumber num_pages
Definition: genam.h:77
int64 tuples_deleted
Definition: vacuumlazy.c:207
bool do_rel_truncate
Definition: vacuumlazy.c:157
BlockNumber scanned_pages
Definition: vacuumlazy.c:191
GlobalVisState * vistest
Definition: vacuumlazy.c:161
BlockNumber removed_pages
Definition: vacuumlazy.c:192
int num_index_scans
Definition: vacuumlazy.c:205
double new_live_tuples
Definition: vacuumlazy.c:200
double new_rel_tuples
Definition: vacuumlazy.c:199
TransactionId NewRelfrozenXid
Definition: vacuumlazy.c:163
bool consider_bypass_optimization
Definition: vacuumlazy.c:152
int64 recently_dead_tuples
Definition: vacuumlazy.c:211
int64 tuples_frozen
Definition: vacuumlazy.c:208
BlockNumber frozen_pages
Definition: vacuumlazy.c:193
char * dbname
Definition: vacuumlazy.c:168
BlockNumber missed_dead_pages
Definition: vacuumlazy.c:195
char * relnamespace
Definition: vacuumlazy.c:169
int64 live_tuples
Definition: vacuumlazy.c:210
int64 lpdead_items
Definition: vacuumlazy.c:209
BlockNumber lpdead_item_pages
Definition: vacuumlazy.c:194
bool do_index_cleanup
Definition: vacuumlazy.c:156
MultiXactId NewRelminMxid
Definition: vacuumlazy.c:164
int64 missed_dead_tuples
Definition: vacuumlazy.c:212
VacErrPhase phase
Definition: vacuumlazy.c:174
char * indname
Definition: vacuumlazy.c:171
Form_pg_class rd_rel
Definition: rel.h:111
TransactionId FreezeLimit
Definition: vacuum.h:277
TransactionId relfrozenxid
Definition: vacuum.h:251
MultiXactId relminmxid
Definition: vacuum.h:252
MultiXactId MultiXactCutoff
Definition: vacuum.h:278
MultiXactId OldestMxact
Definition: vacuum.h:268
int nworkers
Definition: vacuum.h:239
VacOptValue truncate
Definition: vacuum.h:231
bits32 options
Definition: vacuum.h:219
bool is_wraparound
Definition: vacuum.h:226
int log_min_duration
Definition: vacuum.h:227
VacOptValue index_cleanup
Definition: vacuum.h:230
uint64 wal_bytes
Definition: instrument.h:55
int64 wal_fpi
Definition: instrument.h:54
int64 wal_records
Definition: instrument.h:53
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:299
static TransactionId ReadNextTransactionId(void)
Definition: transam.h:315
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:2272
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool *frozenxid_updated, bool *minmulti_updated, bool in_outer_xact)
Definition: vacuum.c:1398
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:2315
bool vacuum_get_cutoffs(Relation rel, const VacuumParams *params, struct VacuumCutoffs *cutoffs)
Definition: vacuum.c:1072
bool VacuumFailsafeActive
Definition: vacuum.c:96
#define VACOPT_VERBOSE
Definition: vacuum.h:182
@ VACOPTVALUE_AUTO
Definition: vacuum.h:203
@ VACOPTVALUE_ENABLED
Definition: vacuum.h:205
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:202
@ VACOPTVALUE_DISABLED
Definition: vacuum.h:204
#define VACOPT_DISABLE_PAGE_SKIPPING
Definition: vacuum.h:188
static void dead_items_cleanup(LVRelState *vacrel)
Definition: vacuumlazy.c:2923
static void update_relstats_all_indexes(LVRelState *vacrel)
Definition: vacuumlazy.c:3064
static void vacuum_error_callback(void *arg)
Definition: vacuumlazy.c:3099
static void lazy_truncate_heap(LVRelState *vacrel)
Definition: vacuumlazy.c:2546
static bool should_attempt_truncation(LVRelState *vacrel)
Definition: vacuumlazy.c:2526
static void lazy_scan_heap(LVRelState *vacrel)
Definition: vacuumlazy.c:818
static bool lazy_check_wraparound_failsafe(LVRelState *vacrel)
Definition: vacuumlazy.c:2296
static void dead_items_alloc(LVRelState *vacrel, int nworkers)
Definition: vacuumlazy.c:2819
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
bool IsInParallelMode(void)
Definition: xact.c:1086

References _, LVRelState::aggressive, AmAutoVacuumWorkerProcess, appendStringInfo(), appendStringInfoString(), ErrorContextCallback::arg, Assert, LVRelState::bstrategy, buf, ErrorContextCallback::callback, LVRelState::consider_bypass_optimization, LVRelState::cutoffs, LVRelState::dbname, dead_items_alloc(), dead_items_cleanup(), LVRelState::do_index_cleanup, LVRelState::do_index_vacuuming, LVRelState::do_rel_truncate, ereport, errmsg(), errmsg_internal(), error_context_stack, VacuumCutoffs::FreezeLimit, LVRelState::frozen_pages, get_database_name(), get_namespace_name(), GetCurrentTimestamp(), GlobalVisTestFor(), i, VacuumParams::index_cleanup, LVRelState::indname, LVRelState::indrels, LVRelState::indstats, INFO, initStringInfo(), InvalidMultiXactId, InvalidTransactionId, VacuumParams::is_wraparound, IsInParallelMode(), lazy_check_wraparound_failsafe(), lazy_scan_heap(), lazy_truncate_heap(), LVRelState::live_tuples, LOG, VacuumParams::log_min_duration, LVRelState::lpdead_item_pages, LVRelState::lpdead_items, Max, LVRelState::missed_dead_pages, LVRelState::missed_dead_tuples, VacuumCutoffs::MultiXactCutoff, MultiXactIdPrecedesOrEquals(), MyDatabaseId, LVRelState::new_live_tuples, LVRelState::new_rel_tuples, LVRelState::NewRelfrozenXid, LVRelState::NewRelminMxid, LVRelState::nindexes, NoLock, LVRelState::nonempty_pages, LVRelState::num_index_scans, IndexBulkDeleteResult::num_pages, VacuumParams::nworkers, VacuumCutoffs::OldestMxact, VacuumCutoffs::OldestXmin, VacuumParams::options, IndexBulkDeleteResult::pages_deleted, IndexBulkDeleteResult::pages_free, IndexBulkDeleteResult::pages_newly_deleted, palloc(), palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), pgstat_report_vacuum(), pgStatBlockReadTime, pgStatBlockWriteTime, pgWalUsage, LVRelState::phase, ErrorContextCallback::previous, PROGRESS_COMMAND_VACUUM, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_FINAL_CLEANUP, pstrdup(), RelationData::rd_rel, ReadNextTransactionId(), LVRelState::recently_dead_tuples, LVRelState::rel, LVRelState::rel_pages, RelationGetNamespace, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, VacuumCutoffs::relfrozenxid, VacuumCutoffs::relminmxid, LVRelState::relname, LVRelState::relnamespace, LVRelState::removed_pages, RowExclusiveLock, LVRelState::scanned_pages, should_attempt_truncation(), LVRelState::skippedallvis, LVRelState::skipwithvm, TimestampDifference(), TimestampDifferenceExceeds(), track_io_timing, TransactionIdPrecedesOrEquals(), VacuumParams::truncate, LVRelState::tuples_deleted, LVRelState::tuples_frozen, update_relstats_all_indexes(), vac_close_indexes(), vac_open_indexes(), vac_update_relstats(), VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_VERBOSE, VACOPTVALUE_AUTO, VACOPTVALUE_DISABLED, VACOPTVALUE_ENABLED, VACOPTVALUE_UNSPECIFIED, VACUUM_ERRCB_PHASE_UNKNOWN, vacuum_error_callback(), vacuum_get_cutoffs(), VacuumFailsafeActive, VacuumPageDirty, VacuumPageHit, VacuumPageMiss, LVRelState::verbose, verbose, visibilitymap_count(), LVRelState::vistest, WalUsage::wal_bytes, WalUsage::wal_fpi, WalUsage::wal_records, and WalUsageAccumDiff().

◆ lazy_check_wraparound_failsafe()

static bool lazy_check_wraparound_failsafe ( LVRelState vacrel)
static

Definition at line 2296 of file vacuumlazy.c.

2297 {
2298  /* Don't warn more than once per VACUUM */
2300  return true;
2301 
2303  {
2304  const int progress_index[] = {
2307  };
2308  int64 progress_val[2] = {0, 0};
2309 
2310  VacuumFailsafeActive = true;
2311 
2312  /*
2313  * Abandon use of a buffer access strategy to allow use of all of
2314  * shared buffers. We assume the caller who allocated the memory for
2315  * the BufferAccessStrategy will free it.
2316  */
2317  vacrel->bstrategy = NULL;
2318 
2319  /* Disable index vacuuming, index cleanup, and heap rel truncation */
2320  vacrel->do_index_vacuuming = false;
2321  vacrel->do_index_cleanup = false;
2322  vacrel->do_rel_truncate = false;
2323 
2324  /* Reset the progress counters */
2325  pgstat_progress_update_multi_param(2, progress_index, progress_val);
2326 
2327  ereport(WARNING,
2328  (errmsg("bypassing nonessential maintenance of table \"%s.%s.%s\" as a failsafe after %d index scans",
2329  vacrel->dbname, vacrel->relnamespace, vacrel->relname,
2330  vacrel->num_index_scans),
2331  errdetail("The table's relfrozenxid or relminmxid is too far in the past."),
2332  errhint("Consider increasing configuration parameter maintenance_work_mem or autovacuum_work_mem.\n"
2333  "You might also need to consider other ways for VACUUM to keep up with the allocation of transaction IDs.")));
2334 
2335  /* Stop applying cost limits from this point on */
2336  VacuumCostActive = false;
2337  VacuumCostBalance = 0;
2338 
2339  return true;
2340  }
2341 
2342  return false;
2343 }
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
#define unlikely(x)
Definition: c.h:311
int errdetail(const char *fmt,...)
Definition: elog.c:1205
int errhint(const char *fmt,...)
Definition: elog.c:1319
bool VacuumCostActive
Definition: globals.c:159
int VacuumCostBalance
Definition: globals.c:158
#define PROGRESS_VACUUM_INDEXES_PROCESSED
Definition: progress.h:29
#define PROGRESS_VACUUM_INDEXES_TOTAL
Definition: progress.h:28
bool vacuum_xid_failsafe_check(const struct VacuumCutoffs *cutoffs)
Definition: vacuum.c:1240

References LVRelState::bstrategy, LVRelState::cutoffs, LVRelState::dbname, LVRelState::do_index_cleanup, LVRelState::do_index_vacuuming, LVRelState::do_rel_truncate, ereport, errdetail(), errhint(), errmsg(), LVRelState::num_index_scans, pgstat_progress_update_multi_param(), PROGRESS_VACUUM_INDEXES_PROCESSED, PROGRESS_VACUUM_INDEXES_TOTAL, LVRelState::relname, LVRelState::relnamespace, unlikely, vacuum_xid_failsafe_check(), VacuumCostActive, VacuumCostBalance, VacuumFailsafeActive, and WARNING.

Referenced by heap_vacuum_rel(), lazy_scan_heap(), and lazy_vacuum_all_indexes().

◆ lazy_cleanup_all_indexes()

static void lazy_cleanup_all_indexes ( LVRelState vacrel)
static

Definition at line 2349 of file vacuumlazy.c.

2350 {
2351  double reltuples = vacrel->new_rel_tuples;
2352  bool estimated_count = vacrel->scanned_pages < vacrel->rel_pages;
2353  const int progress_start_index[] = {
2356  };
2357  const int progress_end_index[] = {
2360  };
2361  int64 progress_start_val[2];
2362  int64 progress_end_val[2] = {0, 0};
2363 
2364  Assert(vacrel->do_index_cleanup);
2365  Assert(vacrel->nindexes > 0);
2366 
2367  /*
2368  * Report that we are now cleaning up indexes and the number of indexes to
2369  * cleanup.
2370  */
2371  progress_start_val[0] = PROGRESS_VACUUM_PHASE_INDEX_CLEANUP;
2372  progress_start_val[1] = vacrel->nindexes;
2373  pgstat_progress_update_multi_param(2, progress_start_index, progress_start_val);
2374 
2375  if (!ParallelVacuumIsActive(vacrel))
2376  {
2377  for (int idx = 0; idx < vacrel->nindexes; idx++)
2378  {
2379  Relation indrel = vacrel->indrels[idx];
2380  IndexBulkDeleteResult *istat = vacrel->indstats[idx];
2381 
2382  vacrel->indstats[idx] =
2383  lazy_cleanup_one_index(indrel, istat, reltuples,
2384  estimated_count, vacrel);
2385 
2386  /* Report the number of indexes cleaned up */
2388  idx + 1);
2389  }
2390  }
2391  else
2392  {
2393  /* Outsource everything to parallel variant */
2394  parallel_vacuum_cleanup_all_indexes(vacrel->pvs, reltuples,
2395  vacrel->num_index_scans,
2396  estimated_count);
2397  }
2398 
2399  /* Reset the progress counters */
2400  pgstat_progress_update_multi_param(2, progress_end_index, progress_end_val);
2401 }
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
#define PROGRESS_VACUUM_PHASE_INDEX_CLEANUP
Definition: progress.h:35
static IndexBulkDeleteResult * lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat, double reltuples, bool estimated_count, LVRelState *vacrel)
Definition: vacuumlazy.c:2466
void parallel_vacuum_cleanup_all_indexes(ParallelVacuumState *pvs, long num_table_tuples, int num_index_scans, bool estimated_count)

References Assert, LVRelState::do_index_cleanup, idx(), LVRelState::indrels, LVRelState::indstats, lazy_cleanup_one_index(), LVRelState::new_rel_tuples, LVRelState::nindexes, LVRelState::num_index_scans, parallel_vacuum_cleanup_all_indexes(), ParallelVacuumIsActive, pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_VACUUM_INDEXES_PROCESSED, PROGRESS_VACUUM_INDEXES_TOTAL, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_INDEX_CLEANUP, LVRelState::pvs, LVRelState::rel_pages, and LVRelState::scanned_pages.

Referenced by lazy_scan_heap().

◆ lazy_cleanup_one_index()

static IndexBulkDeleteResult * lazy_cleanup_one_index ( Relation  indrel,
IndexBulkDeleteResult istat,
double  reltuples,
bool  estimated_count,
LVRelState vacrel 
)
static

Definition at line 2466 of file vacuumlazy.c.

2469 {
2470  IndexVacuumInfo ivinfo;
2471  LVSavedErrInfo saved_err_info;
2472 
2473  ivinfo.index = indrel;
2474  ivinfo.heaprel = vacrel->rel;
2475  ivinfo.analyze_only = false;
2476  ivinfo.report_progress = false;
2477  ivinfo.estimated_count = estimated_count;
2478  ivinfo.message_level = DEBUG2;
2479 
2480  ivinfo.num_heap_tuples = reltuples;
2481  ivinfo.strategy = vacrel->bstrategy;
2482 
2483  /*
2484  * Update error traceback information.
2485  *
2486  * The index name is saved during this phase and restored immediately
2487  * after this phase. See vacuum_error_callback.
2488  */
2489  Assert(vacrel->indname == NULL);
2490  vacrel->indname = pstrdup(RelationGetRelationName(indrel));
2491  update_vacuum_error_info(vacrel, &saved_err_info,
2494 
2495  istat = vac_cleanup_one_index(&ivinfo, istat);
2496 
2497  /* Revert to the previous phase information for error traceback */
2498  restore_vacuum_error_info(vacrel, &saved_err_info);
2499  pfree(vacrel->indname);
2500  vacrel->indname = NULL;
2501 
2502  return istat;
2503 }
Relation index
Definition: genam.h:46
double num_heap_tuples
Definition: genam.h:52
bool analyze_only
Definition: genam.h:48
BufferAccessStrategy strategy
Definition: genam.h:53
Relation heaprel
Definition: genam.h:47
bool report_progress
Definition: genam.h:49
int message_level
Definition: genam.h:51
bool estimated_count
Definition: genam.h:50
IndexBulkDeleteResult * vac_cleanup_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat)
Definition: vacuum.c:2511
static void restore_vacuum_error_info(LVRelState *vacrel, const LVSavedErrInfo *saved_vacrel)
Definition: vacuumlazy.c:3182
static void update_vacuum_error_info(LVRelState *vacrel, LVSavedErrInfo *saved_vacrel, int phase, BlockNumber blkno, OffsetNumber offnum)
Definition: vacuumlazy.c:3163

References IndexVacuumInfo::analyze_only, Assert, LVRelState::bstrategy, DEBUG2, IndexVacuumInfo::estimated_count, IndexVacuumInfo::heaprel, IndexVacuumInfo::index, LVRelState::indname, InvalidBlockNumber, InvalidOffsetNumber, IndexVacuumInfo::message_level, IndexVacuumInfo::num_heap_tuples, pfree(), pstrdup(), LVRelState::rel, RelationGetRelationName, IndexVacuumInfo::report_progress, restore_vacuum_error_info(), IndexVacuumInfo::strategy, update_vacuum_error_info(), vac_cleanup_one_index(), and VACUUM_ERRCB_PHASE_INDEX_CLEANUP.

Referenced by lazy_cleanup_all_indexes().

◆ lazy_scan_heap()

static void lazy_scan_heap ( LVRelState vacrel)
static

Definition at line 818 of file vacuumlazy.c.

819 {
820  BlockNumber rel_pages = vacrel->rel_pages,
821  blkno,
822  next_fsm_block_to_vacuum = 0;
823  bool all_visible_according_to_vm;
824 
825  TidStore *dead_items = vacrel->dead_items;
826  VacDeadItemsInfo *dead_items_info = vacrel->dead_items_info;
827  Buffer vmbuffer = InvalidBuffer;
828  const int initprog_index[] = {
832  };
833  int64 initprog_val[3];
834 
835  /* Report that we're scanning the heap, advertising total # of blocks */
836  initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
837  initprog_val[1] = rel_pages;
838  initprog_val[2] = dead_items_info->max_bytes;
839  pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
840 
841  /* Initialize for the first heap_vac_scan_next_block() call */
844  vacrel->next_unskippable_allvis = false;
846 
847  while (heap_vac_scan_next_block(vacrel, &blkno, &all_visible_according_to_vm))
848  {
849  Buffer buf;
850  Page page;
851  bool has_lpdead_items;
852  bool got_cleanup_lock = false;
853 
854  vacrel->scanned_pages++;
855 
856  /* Report as block scanned, update error traceback information */
859  blkno, InvalidOffsetNumber);
860 
862 
863  /*
864  * Regularly check if wraparound failsafe should trigger.
865  *
866  * There is a similar check inside lazy_vacuum_all_indexes(), but
867  * relfrozenxid might start to look dangerously old before we reach
868  * that point. This check also provides failsafe coverage for the
869  * one-pass strategy, and the two-pass strategy with the index_cleanup
870  * param set to 'off'.
871  */
872  if (vacrel->scanned_pages % FAILSAFE_EVERY_PAGES == 0)
874 
875  /*
876  * Consider if we definitely have enough space to process TIDs on page
877  * already. If we are close to overrunning the available space for
878  * dead_items TIDs, pause and do a cycle of vacuuming before we tackle
879  * this page.
880  */
881  if (TidStoreMemoryUsage(dead_items) > dead_items_info->max_bytes)
882  {
883  /*
884  * Before beginning index vacuuming, we release any pin we may
885  * hold on the visibility map page. This isn't necessary for
886  * correctness, but we do it anyway to avoid holding the pin
887  * across a lengthy, unrelated operation.
888  */
889  if (BufferIsValid(vmbuffer))
890  {
891  ReleaseBuffer(vmbuffer);
892  vmbuffer = InvalidBuffer;
893  }
894 
895  /* Perform a round of index and heap vacuuming */
896  vacrel->consider_bypass_optimization = false;
897  lazy_vacuum(vacrel);
898 
899  /*
900  * Vacuum the Free Space Map to make newly-freed space visible on
901  * upper-level FSM pages. Note we have not yet processed blkno.
902  */
903  FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
904  blkno);
905  next_fsm_block_to_vacuum = blkno;
906 
907  /* Report that we are once again scanning the heap */
910  }
911 
912  /*
913  * Pin the visibility map page in case we need to mark the page
914  * all-visible. In most cases this will be very cheap, because we'll
915  * already have the correct page pinned anyway.
916  */
917  visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
918 
919  buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
920  vacrel->bstrategy);
921  page = BufferGetPage(buf);
922 
923  /*
924  * We need a buffer cleanup lock to prune HOT chains and defragment
925  * the page in lazy_scan_prune. But when it's not possible to acquire
926  * a cleanup lock right away, we may be able to settle for reduced
927  * processing using lazy_scan_noprune.
928  */
929  got_cleanup_lock = ConditionalLockBufferForCleanup(buf);
930 
931  if (!got_cleanup_lock)
933 
934  /* Check for new or empty pages before lazy_scan_[no]prune call */
935  if (lazy_scan_new_or_empty(vacrel, buf, blkno, page, !got_cleanup_lock,
936  vmbuffer))
937  {
938  /* Processed as new/empty page (lock and pin released) */
939  continue;
940  }
941 
942  /*
943  * If we didn't get the cleanup lock, we can still collect LP_DEAD
944  * items in the dead_items area for later vacuuming, count live and
945  * recently dead tuples for vacuum logging, and determine if this
946  * block could later be truncated. If we encounter any xid/mxids that
947  * require advancing the relfrozenxid/relminxid, we'll have to wait
948  * for a cleanup lock and call lazy_scan_prune().
949  */
950  if (!got_cleanup_lock &&
951  !lazy_scan_noprune(vacrel, buf, blkno, page, &has_lpdead_items))
952  {
953  /*
954  * lazy_scan_noprune could not do all required processing. Wait
955  * for a cleanup lock, and call lazy_scan_prune in the usual way.
956  */
957  Assert(vacrel->aggressive);
960  got_cleanup_lock = true;
961  }
962 
963  /*
964  * If we have a cleanup lock, we must now prune, freeze, and count
965  * tuples. We may have acquired the cleanup lock originally, or we may
966  * have gone back and acquired it after lazy_scan_noprune() returned
967  * false. Either way, the page hasn't been processed yet.
968  *
969  * Like lazy_scan_noprune(), lazy_scan_prune() will count
970  * recently_dead_tuples and live tuples for vacuum logging, determine
971  * if the block can later be truncated, and accumulate the details of
972  * remaining LP_DEAD line pointers on the page into dead_items. These
973  * dead items include those pruned by lazy_scan_prune() as well as
974  * line pointers previously marked LP_DEAD.
975  */
976  if (got_cleanup_lock)
977  lazy_scan_prune(vacrel, buf, blkno, page,
978  vmbuffer, all_visible_according_to_vm,
979  &has_lpdead_items);
980 
981  /*
982  * Now drop the buffer lock and, potentially, update the FSM.
983  *
984  * Our goal is to update the freespace map the last time we touch the
985  * page. If we'll process a block in the second pass, we may free up
986  * additional space on the page, so it is better to update the FSM
987  * after the second pass. If the relation has no indexes, or if index
988  * vacuuming is disabled, there will be no second heap pass; if this
989  * particular page has no dead items, the second heap pass will not
990  * touch this page. So, in those cases, update the FSM now.
991  *
992  * Note: In corner cases, it's possible to miss updating the FSM
993  * entirely. If index vacuuming is currently enabled, we'll skip the
994  * FSM update now. But if failsafe mode is later activated, or there
995  * are so few dead tuples that index vacuuming is bypassed, there will
996  * also be no opportunity to update the FSM later, because we'll never
997  * revisit this page. Since updating the FSM is desirable but not
998  * absolutely required, that's OK.
999  */
1000  if (vacrel->nindexes == 0
1001  || !vacrel->do_index_vacuuming
1002  || !has_lpdead_items)
1003  {
1004  Size freespace = PageGetHeapFreeSpace(page);
1005 
1007  RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
1008 
1009  /*
1010  * Periodically perform FSM vacuuming to make newly-freed space
1011  * visible on upper FSM pages. This is done after vacuuming if the
1012  * table has indexes. There will only be newly-freed space if we
1013  * held the cleanup lock and lazy_scan_prune() was called.
1014  */
1015  if (got_cleanup_lock && vacrel->nindexes == 0 && has_lpdead_items &&
1016  blkno - next_fsm_block_to_vacuum >= VACUUM_FSM_EVERY_PAGES)
1017  {
1018  FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum,
1019  blkno);
1020  next_fsm_block_to_vacuum = blkno;
1021  }
1022  }
1023  else
1025  }
1026 
1027  vacrel->blkno = InvalidBlockNumber;
1028  if (BufferIsValid(vmbuffer))
1029  ReleaseBuffer(vmbuffer);
1030 
1031  /* report that everything is now scanned */
1033 
1034  /* now we can compute the new value for pg_class.reltuples */
1035  vacrel->new_live_tuples = vac_estimate_reltuples(vacrel->rel, rel_pages,
1036  vacrel->scanned_pages,
1037  vacrel->live_tuples);
1038 
1039  /*
1040  * Also compute the total number of surviving heap entries. In the
1041  * (unlikely) scenario that new_live_tuples is -1, take it as zero.
1042  */
1043  vacrel->new_rel_tuples =
1044  Max(vacrel->new_live_tuples, 0) + vacrel->recently_dead_tuples +
1045  vacrel->missed_dead_tuples;
1046 
1047  /*
1048  * Do index vacuuming (call each index's ambulkdelete routine), then do
1049  * related heap vacuuming
1050  */
1051  if (dead_items_info->num_items > 0)
1052  lazy_vacuum(vacrel);
1053 
1054  /*
1055  * Vacuum the remainder of the Free Space Map. We must do this whether or
1056  * not there were indexes, and whether or not we bypassed index vacuuming.
1057  */
1058  if (blkno > next_fsm_block_to_vacuum)
1059  FreeSpaceMapVacuumRange(vacrel->rel, next_fsm_block_to_vacuum, blkno);
1060 
1061  /* report all blocks vacuumed */
1063 
1064  /* Do final index cleanup (call each index's amvacuumcleanup routine) */
1065  if (vacrel->nindexes > 0 && vacrel->do_index_cleanup)
1066  lazy_cleanup_all_indexes(vacrel);
1067 }
void LockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:5165
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:5326
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:197
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:991
size_t Size
Definition: c.h:605
void FreeSpaceMapVacuumRange(Relation rel, BlockNumber start, BlockNumber end)
Definition: freespace.c:377
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:194
#define PROGRESS_VACUUM_PHASE_SCAN_HEAP
Definition: progress.h:32
#define PROGRESS_VACUUM_TOTAL_HEAP_BLKS
Definition: progress.h:22
#define PROGRESS_VACUUM_MAX_DEAD_TUPLE_BYTES
Definition: progress.h:26
#define PROGRESS_VACUUM_HEAP_BLKS_SCANNED
Definition: progress.h:23
#define PROGRESS_VACUUM_HEAP_BLKS_VACUUMED
Definition: progress.h:24
BlockNumber blkno
Definition: vacuumlazy.c:172
void vacuum_delay_point(void)
Definition: vacuum.c:2336
double vac_estimate_reltuples(Relation relation, BlockNumber total_pages, BlockNumber scanned_pages, double scanned_tuples)
Definition: vacuum.c:1302
static void lazy_vacuum(LVRelState *vacrel)
Definition: vacuumlazy.c:1861
static void lazy_cleanup_all_indexes(LVRelState *vacrel)
Definition: vacuumlazy.c:2349
static bool lazy_scan_noprune(LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, bool *has_lpdead_items)
Definition: vacuumlazy.c:1650
static bool lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, bool sharelock, Buffer vmbuffer)
Definition: vacuumlazy.c:1285
static bool heap_vac_scan_next_block(LVRelState *vacrel, BlockNumber *blkno, bool *all_visible_according_to_vm)
Definition: vacuumlazy.c:1088
static void lazy_scan_prune(LVRelState *vacrel, Buffer buf, BlockNumber blkno, Page page, Buffer vmbuffer, bool all_visible_according_to_vm, bool *has_lpdead_items)
Definition: vacuumlazy.c:1408
#define FAILSAFE_EVERY_PAGES
Definition: vacuumlazy.c:95
#define VACUUM_FSM_EVERY_PAGES
Definition: vacuumlazy.c:104
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *vmbuf)

References LVRelState::aggressive, Assert, LVRelState::blkno, LVRelState::bstrategy, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage(), BufferIsValid(), ConditionalLockBufferForCleanup(), LVRelState::consider_bypass_optimization, LVRelState::current_block, LVRelState::dead_items, LVRelState::dead_items_info, LVRelState::do_index_cleanup, LVRelState::do_index_vacuuming, FAILSAFE_EVERY_PAGES, FreeSpaceMapVacuumRange(), heap_vac_scan_next_block(), InvalidBlockNumber, InvalidBuffer, InvalidOffsetNumber, lazy_check_wraparound_failsafe(), lazy_cleanup_all_indexes(), lazy_scan_new_or_empty(), lazy_scan_noprune(), lazy_scan_prune(), lazy_vacuum(), LVRelState::live_tuples, LockBuffer(), LockBufferForCleanup(), MAIN_FORKNUM, Max, VacDeadItemsInfo::max_bytes, LVRelState::missed_dead_tuples, LVRelState::new_live_tuples, LVRelState::new_rel_tuples, LVRelState::next_unskippable_allvis, LVRelState::next_unskippable_block, LVRelState::next_unskippable_vmbuffer, LVRelState::nindexes, VacDeadItemsInfo::num_items, PageGetHeapFreeSpace(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_VACUUM_HEAP_BLKS_SCANNED, PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, PROGRESS_VACUUM_MAX_DEAD_TUPLE_BYTES, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_SCAN_HEAP, PROGRESS_VACUUM_TOTAL_HEAP_BLKS, RBM_NORMAL, ReadBufferExtended(), LVRelState::recently_dead_tuples, RecordPageWithFreeSpace(), LVRelState::rel, LVRelState::rel_pages, ReleaseBuffer(), LVRelState::scanned_pages, TidStoreMemoryUsage(), UnlockReleaseBuffer(), update_vacuum_error_info(), vac_estimate_reltuples(), vacuum_delay_point(), VACUUM_ERRCB_PHASE_SCAN_HEAP, VACUUM_FSM_EVERY_PAGES, and visibilitymap_pin().

Referenced by heap_vacuum_rel().

◆ lazy_scan_new_or_empty()

static bool lazy_scan_new_or_empty ( LVRelState vacrel,
Buffer  buf,
BlockNumber  blkno,
Page  page,
bool  sharelock,
Buffer  vmbuffer 
)
static

Definition at line 1285 of file vacuumlazy.c.

1287 {
1288  Size freespace;
1289 
1290  if (PageIsNew(page))
1291  {
1292  /*
1293  * All-zeroes pages can be left over if either a backend extends the
1294  * relation by a single page, but crashes before the newly initialized
1295  * page has been written out, or when bulk-extending the relation
1296  * (which creates a number of empty pages at the tail end of the
1297  * relation), and then enters them into the FSM.
1298  *
1299  * Note we do not enter the page into the visibilitymap. That has the
1300  * downside that we repeatedly visit this page in subsequent vacuums,
1301  * but otherwise we'll never discover the space on a promoted standby.
1302  * The harm of repeated checking ought to normally not be too bad. The
1303  * space usually should be used at some point, otherwise there
1304  * wouldn't be any regular vacuums.
1305  *
1306  * Make sure these pages are in the FSM, to ensure they can be reused.
1307  * Do that by testing if there's any space recorded for the page. If
1308  * not, enter it. We do so after releasing the lock on the heap page,
1309  * the FSM is approximate, after all.
1310  */
1312 
1313  if (GetRecordedFreeSpace(vacrel->rel, blkno) == 0)
1314  {
1315  freespace = BLCKSZ - SizeOfPageHeaderData;
1316 
1317  RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
1318  }
1319 
1320  return true;
1321  }
1322 
1323  if (PageIsEmpty(page))
1324  {
1325  /*
1326  * It seems likely that caller will always be able to get a cleanup
1327  * lock on an empty page. But don't take any chances -- escalate to
1328  * an exclusive lock (still don't need a cleanup lock, though).
1329  */
1330  if (sharelock)
1331  {
1334 
1335  if (!PageIsEmpty(page))
1336  {
1337  /* page isn't new or empty -- keep lock and pin for now */
1338  return false;
1339  }
1340  }
1341  else
1342  {
1343  /* Already have a full cleanup lock (which is more than enough) */
1344  }
1345 
1346  /*
1347  * Unlike new pages, empty pages are always set all-visible and
1348  * all-frozen.
1349  */
1350  if (!PageIsAllVisible(page))
1351  {
1353 
1354  /* mark buffer dirty before writing a WAL record */
1356 
1357  /*
1358  * It's possible that another backend has extended the heap,
1359  * initialized the page, and then failed to WAL-log the page due
1360  * to an ERROR. Since heap extension is not WAL-logged, recovery
1361  * might try to replay our record setting the page all-visible and
1362  * find that the page isn't initialized, which will cause a PANIC.
1363  * To prevent that, check whether the page has been previously
1364  * WAL-logged, and if not, do that now.
1365  */
1366  if (RelationNeedsWAL(vacrel->rel) &&
1367  PageGetLSN(page) == InvalidXLogRecPtr)
1368  log_newpage_buffer(buf, true);
1369 
1370  PageSetAllVisible(page);
1371  visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
1372  vmbuffer, InvalidTransactionId,
1374  END_CRIT_SECTION();
1375  }
1376 
1377  freespace = PageGetHeapFreeSpace(page);
1379  RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
1380  return true;
1381  }
1382 
1383  /* page isn't new or empty -- keep lock and pin */
1384  return false;
1385 }
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:2474
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:199
#define SizeOfPageHeaderData
Definition: bufpage.h:213
static void PageSetAllVisible(Page page)
Definition: bufpage.h:431
static bool PageIsAllVisible(Page page)
Definition: bufpage.h:426
static XLogRecPtr PageGetLSN(Page page)
Definition: bufpage.h:383
Size GetRecordedFreeSpace(Relation rel, BlockNumber heapBlk)
Definition: freespace.c:244
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
#define RelationNeedsWAL(relation)
Definition: rel.h:628
void visibilitymap_set(Relation rel, BlockNumber heapBlk, Buffer heapBuf, XLogRecPtr recptr, Buffer vmBuf, TransactionId cutoff_xid, uint8 flags)
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1237

References buf, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, END_CRIT_SECTION, GetRecordedFreeSpace(), InvalidTransactionId, InvalidXLogRecPtr, LockBuffer(), log_newpage_buffer(), MarkBufferDirty(), PageGetHeapFreeSpace(), PageGetLSN(), PageIsAllVisible(), PageIsEmpty(), PageIsNew(), PageSetAllVisible(), RecordPageWithFreeSpace(), LVRelState::rel, RelationNeedsWAL, SizeOfPageHeaderData, START_CRIT_SECTION, UnlockReleaseBuffer(), VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, and visibilitymap_set().

Referenced by lazy_scan_heap().

◆ lazy_scan_noprune()

static bool lazy_scan_noprune ( LVRelState vacrel,
Buffer  buf,
BlockNumber  blkno,
Page  page,
bool has_lpdead_items 
)
static

Definition at line 1650 of file vacuumlazy.c.

1655 {
1656  OffsetNumber offnum,
1657  maxoff;
1658  int lpdead_items,
1659  live_tuples,
1660  recently_dead_tuples,
1661  missed_dead_tuples;
1662  bool hastup;
1663  HeapTupleHeader tupleheader;
1664  TransactionId NoFreezePageRelfrozenXid = vacrel->NewRelfrozenXid;
1665  MultiXactId NoFreezePageRelminMxid = vacrel->NewRelminMxid;
1666  OffsetNumber deadoffsets[MaxHeapTuplesPerPage];
1667 
1668  Assert(BufferGetBlockNumber(buf) == blkno);
1669 
1670  hastup = false; /* for now */
1671 
1672  lpdead_items = 0;
1673  live_tuples = 0;
1674  recently_dead_tuples = 0;
1675  missed_dead_tuples = 0;
1676 
1677  maxoff = PageGetMaxOffsetNumber(page);
1678  for (offnum = FirstOffsetNumber;
1679  offnum <= maxoff;
1680  offnum = OffsetNumberNext(offnum))
1681  {
1682  ItemId itemid;
1683  HeapTupleData tuple;
1684 
1685  vacrel->offnum = offnum;
1686  itemid = PageGetItemId(page, offnum);
1687 
1688  if (!ItemIdIsUsed(itemid))
1689  continue;
1690 
1691  if (ItemIdIsRedirected(itemid))
1692  {
1693  hastup = true;
1694  continue;
1695  }
1696 
1697  if (ItemIdIsDead(itemid))
1698  {
1699  /*
1700  * Deliberately don't set hastup=true here. See same point in
1701  * lazy_scan_prune for an explanation.
1702  */
1703  deadoffsets[lpdead_items++] = offnum;
1704  continue;
1705  }
1706 
1707  hastup = true; /* page prevents rel truncation */
1708  tupleheader = (HeapTupleHeader) PageGetItem(page, itemid);
1709  if (heap_tuple_should_freeze(tupleheader, &vacrel->cutoffs,
1710  &NoFreezePageRelfrozenXid,
1711  &NoFreezePageRelminMxid))
1712  {
1713  /* Tuple with XID < FreezeLimit (or MXID < MultiXactCutoff) */
1714  if (vacrel->aggressive)
1715  {
1716  /*
1717  * Aggressive VACUUMs must always be able to advance rel's
1718  * relfrozenxid to a value >= FreezeLimit (and be able to
1719  * advance rel's relminmxid to a value >= MultiXactCutoff).
1720  * The ongoing aggressive VACUUM won't be able to do that
1721  * unless it can freeze an XID (or MXID) from this tuple now.
1722  *
1723  * The only safe option is to have caller perform processing
1724  * of this page using lazy_scan_prune. Caller might have to
1725  * wait a while for a cleanup lock, but it can't be helped.
1726  */
1727  vacrel->offnum = InvalidOffsetNumber;
1728  return false;
1729  }
1730 
1731  /*
1732  * Non-aggressive VACUUMs are under no obligation to advance
1733  * relfrozenxid (even by one XID). We can be much laxer here.
1734  *
1735  * Currently we always just accept an older final relfrozenxid
1736  * and/or relminmxid value. We never make caller wait or work a
1737  * little harder, even when it likely makes sense to do so.
1738  */
1739  }
1740 
1741  ItemPointerSet(&(tuple.t_self), blkno, offnum);
1742  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
1743  tuple.t_len = ItemIdGetLength(itemid);
1744  tuple.t_tableOid = RelationGetRelid(vacrel->rel);
1745 
1746  switch (HeapTupleSatisfiesVacuum(&tuple, vacrel->cutoffs.OldestXmin,
1747  buf))
1748  {
1750  case HEAPTUPLE_LIVE:
1751 
1752  /*
1753  * Count both cases as live, just like lazy_scan_prune
1754  */
1755  live_tuples++;
1756 
1757  break;
1758  case HEAPTUPLE_DEAD:
1759 
1760  /*
1761  * There is some useful work for pruning to do, that won't be
1762  * done due to failure to get a cleanup lock.
1763  */
1764  missed_dead_tuples++;
1765  break;
1767 
1768  /*
1769  * Count in recently_dead_tuples, just like lazy_scan_prune
1770  */
1771  recently_dead_tuples++;
1772  break;
1774 
1775  /*
1776  * Do not count these rows as live, just like lazy_scan_prune
1777  */
1778  break;
1779  default:
1780  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1781  break;
1782  }
1783  }
1784 
1785  vacrel->offnum = InvalidOffsetNumber;
1786 
1787  /*
1788  * By here we know for sure that caller can put off freezing and pruning
1789  * this particular page until the next VACUUM. Remember its details now.
1790  * (lazy_scan_prune expects a clean slate, so we have to do this last.)
1791  */
1792  vacrel->NewRelfrozenXid = NoFreezePageRelfrozenXid;
1793  vacrel->NewRelminMxid = NoFreezePageRelminMxid;
1794 
1795  /* Save any LP_DEAD items found on the page in dead_items */
1796  if (vacrel->nindexes == 0)
1797  {
1798  /* Using one-pass strategy (since table has no indexes) */
1799  if (lpdead_items > 0)
1800  {
1801  /*
1802  * Perfunctory handling for the corner case where a single pass
1803  * strategy VACUUM cannot get a cleanup lock, and it turns out
1804  * that there is one or more LP_DEAD items: just count the LP_DEAD
1805  * items as missed_dead_tuples instead. (This is a bit dishonest,
1806  * but it beats having to maintain specialized heap vacuuming code
1807  * forever, for vanishingly little benefit.)
1808  */
1809  hastup = true;
1810  missed_dead_tuples += lpdead_items;
1811  }
1812  }
1813  else if (lpdead_items > 0)
1814  {
1815  /*
1816  * Page has LP_DEAD items, and so any references/TIDs that remain in
1817  * indexes will be deleted during index vacuuming (and then marked
1818  * LP_UNUSED in the heap)
1819  */
1820  vacrel->lpdead_item_pages++;
1821 
1822  dead_items_add(vacrel, blkno, deadoffsets, lpdead_items);
1823 
1824  vacrel->lpdead_items += lpdead_items;
1825  }
1826 
1827  /*
1828  * Finally, add relevant page-local counts to whole-VACUUM counts
1829  */
1830  vacrel->live_tuples += live_tuples;
1831  vacrel->recently_dead_tuples += recently_dead_tuples;
1832  vacrel->missed_dead_tuples += missed_dead_tuples;
1833  if (missed_dead_tuples > 0)
1834  vacrel->missed_dead_pages++;
1835 
1836  /* Can't truncate this page */
1837  if (hastup)
1838  vacrel->nonempty_pages = blkno + 1;
1839 
1840  /* Did we find LP_DEAD items? */
1841  *has_lpdead_items = (lpdead_items > 0);
1842 
1843  /* Caller won't need to call lazy_scan_prune with same page */
1844  return true;
1845 }
TransactionId MultiXactId
Definition: c.h:662
bool heap_tuple_should_freeze(HeapTupleHeader tuple, const struct VacuumCutoffs *cutoffs, TransactionId *NoFreezePageRelfrozenXid, MultiXactId *NoFreezePageRelminMxid)
Definition: heapam.c:7374
#define MaxHeapTuplesPerPage
Definition: htup_details.h:572
static void dead_items_add(LVRelState *vacrel, BlockNumber blkno, OffsetNumber *offsets, int num_offsets)
Definition: vacuumlazy.c:2884

References LVRelState::aggressive, Assert, buf, BufferGetBlockNumber(), LVRelState::cutoffs, dead_items_add(), elog, ERROR, FirstOffsetNumber, heap_tuple_should_freeze(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleSatisfiesVacuum(), InvalidOffsetNumber, ItemIdGetLength, ItemIdIsDead, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet(), LVRelState::live_tuples, LVRelState::lpdead_item_pages, LVRelState::lpdead_items, MaxHeapTuplesPerPage, LVRelState::missed_dead_pages, LVRelState::missed_dead_tuples, LVRelState::NewRelfrozenXid, LVRelState::NewRelminMxid, LVRelState::nindexes, LVRelState::nonempty_pages, LVRelState::offnum, OffsetNumberNext, VacuumCutoffs::OldestXmin, PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), LVRelState::recently_dead_tuples, LVRelState::rel, RelationGetRelid, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, and HeapTupleData::t_tableOid.

Referenced by lazy_scan_heap().

◆ lazy_scan_prune()

static void lazy_scan_prune ( LVRelState vacrel,
Buffer  buf,
BlockNumber  blkno,
Page  page,
Buffer  vmbuffer,
bool  all_visible_according_to_vm,
bool has_lpdead_items 
)
static

Definition at line 1408 of file vacuumlazy.c.

1415 {
1416  Relation rel = vacrel->rel;
1417  PruneFreezeResult presult;
1418  int prune_options = 0;
1419 
1420  Assert(BufferGetBlockNumber(buf) == blkno);
1421 
1422  /*
1423  * Prune all HOT-update chains and potentially freeze tuples on this page.
1424  *
1425  * If the relation has no indexes, we can immediately mark would-be dead
1426  * items LP_UNUSED.
1427  *
1428  * The number of tuples removed from the page is returned in
1429  * presult.ndeleted. It should not be confused with presult.lpdead_items;
1430  * presult.lpdead_items's final value can be thought of as the number of
1431  * tuples that were deleted from indexes.
1432  *
1433  * We will update the VM after collecting LP_DEAD items and freezing
1434  * tuples. Pruning will have determined whether or not the page is
1435  * all-visible.
1436  */
1437  prune_options = HEAP_PAGE_PRUNE_FREEZE;
1438  if (vacrel->nindexes == 0)
1439  prune_options |= HEAP_PAGE_PRUNE_MARK_UNUSED_NOW;
1440 
1441  heap_page_prune_and_freeze(rel, buf, vacrel->vistest, prune_options,
1442  &vacrel->cutoffs, &presult, PRUNE_VACUUM_SCAN,
1443  &vacrel->offnum,
1444  &vacrel->NewRelfrozenXid, &vacrel->NewRelminMxid);
1445 
1448 
1449  if (presult.nfrozen > 0)
1450  {
1451  /*
1452  * We don't increment the frozen_pages instrumentation counter when
1453  * nfrozen == 0, since it only counts pages with newly frozen tuples
1454  * (don't confuse that with pages newly set all-frozen in VM).
1455  */
1456  vacrel->frozen_pages++;
1457  }
1458 
1459  /*
1460  * VACUUM will call heap_page_is_all_visible() during the second pass over
1461  * the heap to determine all_visible and all_frozen for the page -- this
1462  * is a specialized version of the logic from this function. Now that
1463  * we've finished pruning and freezing, make sure that we're in total
1464  * agreement with heap_page_is_all_visible() using an assertion.
1465  */
1466 #ifdef USE_ASSERT_CHECKING
1467  /* Note that all_frozen value does not matter when !all_visible */
1468  if (presult.all_visible)
1469  {
1470  TransactionId debug_cutoff;
1471  bool debug_all_frozen;
1472 
1473  Assert(presult.lpdead_items == 0);
1474 
1475  if (!heap_page_is_all_visible(vacrel, buf,
1476  &debug_cutoff, &debug_all_frozen))
1477  Assert(false);
1478 
1479  Assert(presult.all_frozen == debug_all_frozen);
1480 
1481  Assert(!TransactionIdIsValid(debug_cutoff) ||
1482  debug_cutoff == presult.vm_conflict_horizon);
1483  }
1484 #endif
1485 
1486  /*
1487  * Now save details of the LP_DEAD items from the page in vacrel
1488  */
1489  if (presult.lpdead_items > 0)
1490  {
1491  vacrel->lpdead_item_pages++;
1492 
1493  /*
1494  * deadoffsets are collected incrementally in
1495  * heap_page_prune_and_freeze() as each dead line pointer is recorded,
1496  * with an indeterminate order, but dead_items_add requires them to be
1497  * sorted.
1498  */
1499  qsort(presult.deadoffsets, presult.lpdead_items, sizeof(OffsetNumber),
1501 
1502  dead_items_add(vacrel, blkno, presult.deadoffsets, presult.lpdead_items);
1503  }
1504 
1505  /* Finally, add page-local counts to whole-VACUUM counts */
1506  vacrel->tuples_deleted += presult.ndeleted;
1507  vacrel->tuples_frozen += presult.nfrozen;
1508  vacrel->lpdead_items += presult.lpdead_items;
1509  vacrel->live_tuples += presult.live_tuples;
1510  vacrel->recently_dead_tuples += presult.recently_dead_tuples;
1511 
1512  /* Can't truncate this page */
1513  if (presult.hastup)
1514  vacrel->nonempty_pages = blkno + 1;
1515 
1516  /* Did we find LP_DEAD items? */
1517  *has_lpdead_items = (presult.lpdead_items > 0);
1518 
1519  Assert(!presult.all_visible || !(*has_lpdead_items));
1520 
1521  /*
1522  * Handle setting visibility map bit based on information from the VM (as
1523  * of last heap_vac_scan_next_block() call), and from all_visible and
1524  * all_frozen variables
1525  */
1526  if (!all_visible_according_to_vm && presult.all_visible)
1527  {
1529 
1530  if (presult.all_frozen)
1531  {
1533  flags |= VISIBILITYMAP_ALL_FROZEN;
1534  }
1535 
1536  /*
1537  * It should never be the case that the visibility map page is set
1538  * while the page-level bit is clear, but the reverse is allowed (if
1539  * checksums are not enabled). Regardless, set both bits so that we
1540  * get back in sync.
1541  *
1542  * NB: If the heap page is all-visible but the VM bit is not set, we
1543  * don't need to dirty the heap page. However, if checksums are
1544  * enabled, we do need to make sure that the heap page is dirtied
1545  * before passing it to visibilitymap_set(), because it may be logged.
1546  * Given that this situation should only happen in rare cases after a
1547  * crash, it is not worth optimizing.
1548  */
1549  PageSetAllVisible(page);
1551  visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
1552  vmbuffer, presult.vm_conflict_horizon,
1553  flags);
1554  }
1555 
1556  /*
1557  * As of PostgreSQL 9.2, the visibility map bit should never be set if the
1558  * page-level bit is clear. However, it's possible that the bit got
1559  * cleared after heap_vac_scan_next_block() was called, so we must recheck
1560  * with buffer lock before concluding that the VM is corrupt.
1561  */
1562  else if (all_visible_according_to_vm && !PageIsAllVisible(page) &&
1563  visibilitymap_get_status(vacrel->rel, blkno, &vmbuffer) != 0)
1564  {
1565  elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
1566  vacrel->relname, blkno);
1567  visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
1569  }
1570 
1571  /*
1572  * It's possible for the value returned by
1573  * GetOldestNonRemovableTransactionId() to move backwards, so it's not
1574  * wrong for us to see tuples that appear to not be visible to everyone
1575  * yet, while PD_ALL_VISIBLE is already set. The real safe xmin value
1576  * never moves backwards, but GetOldestNonRemovableTransactionId() is
1577  * conservative and sometimes returns a value that's unnecessarily small,
1578  * so if we see that contradiction it just means that the tuples that we
1579  * think are not visible to everyone yet actually are, and the
1580  * PD_ALL_VISIBLE flag is correct.
1581  *
1582  * There should never be LP_DEAD items on a page with PD_ALL_VISIBLE set,
1583  * however.
1584  */
1585  else if (presult.lpdead_items > 0 && PageIsAllVisible(page))
1586  {
1587  elog(WARNING, "page containing LP_DEAD items is marked as all-visible in relation \"%s\" page %u",
1588  vacrel->relname, blkno);
1589  PageClearAllVisible(page);
1591  visibilitymap_clear(vacrel->rel, blkno, vmbuffer,
1593  }
1594 
1595  /*
1596  * If the all-visible page is all-frozen but not marked as such yet, mark
1597  * it as all-frozen. Note that all_frozen is only valid if all_visible is
1598  * true, so we must check both all_visible and all_frozen.
1599  */
1600  else if (all_visible_according_to_vm && presult.all_visible &&
1601  presult.all_frozen && !VM_ALL_FROZEN(vacrel->rel, blkno, &vmbuffer))
1602  {
1603  /*
1604  * Avoid relying on all_visible_according_to_vm as a proxy for the
1605  * page-level PD_ALL_VISIBLE bit being set, since it might have become
1606  * stale -- even when all_visible is set
1607  */
1608  if (!PageIsAllVisible(page))
1609  {
1610  PageSetAllVisible(page);
1612  }
1613 
1614  /*
1615  * Set the page all-frozen (and all-visible) in the VM.
1616  *
1617  * We can pass InvalidTransactionId as our cutoff_xid, since a
1618  * snapshotConflictHorizon sufficient to make everything safe for REDO
1619  * was logged when the page's tuples were frozen.
1620  */
1622  visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr,
1623  vmbuffer, InvalidTransactionId,
1626  }
1627 }
static void PageClearAllVisible(Page page)
Definition: bufpage.h:436
#define HEAP_PAGE_PRUNE_FREEZE
Definition: heapam.h:42
@ PRUNE_VACUUM_SCAN
Definition: heapam.h:270
#define HEAP_PAGE_PRUNE_MARK_UNUSED_NOW
Definition: heapam.h:41
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
#define qsort(a, b, c, d)
Definition: port.h:449
void heap_page_prune_and_freeze(Relation relation, Buffer buffer, GlobalVisState *vistest, int options, struct VacuumCutoffs *cutoffs, PruneFreezeResult *presult, PruneReason reason, OffsetNumber *off_loc, TransactionId *new_relfrozen_xid, MultiXactId *new_relmin_mxid)
Definition: pruneheap.c:348
int recently_dead_tuples
Definition: heapam.h:234
TransactionId vm_conflict_horizon
Definition: heapam.h:249
OffsetNumber deadoffsets[MaxHeapTuplesPerPage]
Definition: heapam.h:263
bool all_visible
Definition: heapam.h:247
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static bool heap_page_is_all_visible(LVRelState *vacrel, Buffer buf, TransactionId *visibility_cutoff_xid, bool *all_frozen)
Definition: vacuumlazy.c:2948
static int cmpOffsetNumbers(const void *a, const void *b)
Definition: vacuumlazy.c:1389
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer vmbuf, uint8 flags)
#define VM_ALL_FROZEN(r, b, v)
Definition: visibilitymap.h:26
#define VISIBILITYMAP_VALID_BITS

References PruneFreezeResult::all_frozen, PruneFreezeResult::all_visible, Assert, buf, BufferGetBlockNumber(), cmpOffsetNumbers(), LVRelState::cutoffs, dead_items_add(), PruneFreezeResult::deadoffsets, elog, LVRelState::frozen_pages, PruneFreezeResult::hastup, heap_page_is_all_visible(), heap_page_prune_and_freeze(), HEAP_PAGE_PRUNE_FREEZE, HEAP_PAGE_PRUNE_MARK_UNUSED_NOW, InvalidTransactionId, InvalidXLogRecPtr, LVRelState::live_tuples, PruneFreezeResult::live_tuples, LVRelState::lpdead_item_pages, LVRelState::lpdead_items, PruneFreezeResult::lpdead_items, MarkBufferDirty(), MultiXactIdIsValid, PruneFreezeResult::ndeleted, LVRelState::NewRelfrozenXid, LVRelState::NewRelminMxid, PruneFreezeResult::nfrozen, LVRelState::nindexes, LVRelState::nonempty_pages, LVRelState::offnum, PageClearAllVisible(), PageIsAllVisible(), PageSetAllVisible(), PRUNE_VACUUM_SCAN, qsort, LVRelState::recently_dead_tuples, PruneFreezeResult::recently_dead_tuples, LVRelState::rel, LVRelState::relname, TransactionIdIsValid, LVRelState::tuples_deleted, LVRelState::tuples_frozen, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, visibilitymap_clear(), visibilitymap_get_status(), visibilitymap_set(), VISIBILITYMAP_VALID_BITS, LVRelState::vistest, VM_ALL_FROZEN, PruneFreezeResult::vm_conflict_horizon, and WARNING.

Referenced by lazy_scan_heap().

◆ lazy_truncate_heap()

static void lazy_truncate_heap ( LVRelState vacrel)
static

Definition at line 2546 of file vacuumlazy.c.

2547 {
2548  BlockNumber orig_rel_pages = vacrel->rel_pages;
2549  BlockNumber new_rel_pages;
2550  bool lock_waiter_detected;
2551  int lock_retry;
2552 
2553  /* Report that we are now truncating */
2556 
2557  /* Update error traceback information one last time */
2560 
2561  /*
2562  * Loop until no more truncating can be done.
2563  */
2564  do
2565  {
2566  /*
2567  * We need full exclusive lock on the relation in order to do
2568  * truncation. If we can't get it, give up rather than waiting --- we
2569  * don't want to block other backends, and we don't want to deadlock
2570  * (which is quite possible considering we already hold a lower-grade
2571  * lock).
2572  */
2573  lock_waiter_detected = false;
2574  lock_retry = 0;
2575  while (true)
2576  {
2578  break;
2579 
2580  /*
2581  * Check for interrupts while trying to (re-)acquire the exclusive
2582  * lock.
2583  */
2585 
2586  if (++lock_retry > (VACUUM_TRUNCATE_LOCK_TIMEOUT /
2588  {
2589  /*
2590  * We failed to establish the lock in the specified number of
2591  * retries. This means we give up truncating.
2592  */
2593  ereport(vacrel->verbose ? INFO : DEBUG2,
2594  (errmsg("\"%s\": stopping truncate due to conflicting lock request",
2595  vacrel->relname)));
2596  return;
2597  }
2598 
2599  (void) WaitLatch(MyLatch,
2602  WAIT_EVENT_VACUUM_TRUNCATE);
2604  }
2605 
2606  /*
2607  * Now that we have exclusive lock, look to see if the rel has grown
2608  * whilst we were vacuuming with non-exclusive lock. If so, give up;
2609  * the newly added pages presumably contain non-deletable tuples.
2610  */
2611  new_rel_pages = RelationGetNumberOfBlocks(vacrel->rel);
2612  if (new_rel_pages != orig_rel_pages)
2613  {
2614  /*
2615  * Note: we intentionally don't update vacrel->rel_pages with the
2616  * new rel size here. If we did, it would amount to assuming that
2617  * the new pages are empty, which is unlikely. Leaving the numbers
2618  * alone amounts to assuming that the new pages have the same
2619  * tuple density as existing ones, which is less unlikely.
2620  */
2622  return;
2623  }
2624 
2625  /*
2626  * Scan backwards from the end to verify that the end pages actually
2627  * contain no tuples. This is *necessary*, not optional, because
2628  * other backends could have added tuples to these pages whilst we
2629  * were vacuuming.
2630  */
2631  new_rel_pages = count_nondeletable_pages(vacrel, &lock_waiter_detected);
2632  vacrel->blkno = new_rel_pages;
2633 
2634  if (new_rel_pages >= orig_rel_pages)
2635  {
2636  /* can't do anything after all */
2638  return;
2639  }
2640 
2641  /*
2642  * Okay to truncate.
2643  */
2644  RelationTruncate(vacrel->rel, new_rel_pages);
2645 
2646  /*
2647  * We can release the exclusive lock as soon as we have truncated.
2648  * Other backends can't safely access the relation until they have
2649  * processed the smgr invalidation that smgrtruncate sent out ... but
2650  * that should happen as part of standard invalidation processing once
2651  * they acquire lock on the relation.
2652  */
2654 
2655  /*
2656  * Update statistics. Here, it *is* correct to adjust rel_pages
2657  * without also touching reltuples, since the tuple count wasn't
2658  * changed by the truncation.
2659  */
2660  vacrel->removed_pages += orig_rel_pages - new_rel_pages;
2661  vacrel->rel_pages = new_rel_pages;
2662 
2663  ereport(vacrel->verbose ? INFO : DEBUG2,
2664  (errmsg("table \"%s\": truncated %u to %u pages",
2665  vacrel->relname,
2666  orig_rel_pages, new_rel_pages)));
2667  orig_rel_pages = new_rel_pages;
2668  } while (new_rel_pages > vacrel->nonempty_pages && lock_waiter_detected);
2669 }
struct Latch * MyLatch
Definition: globals.c:60
void ResetLatch(Latch *latch)
Definition: latch.c:724
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:517
#define WL_TIMEOUT
Definition: latch.h:130
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_LATCH_SET
Definition: latch.h:127
void UnlockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:310
bool ConditionalLockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:275
#define PROGRESS_VACUUM_PHASE_TRUNCATE
Definition: progress.h:36
void RelationTruncate(Relation rel, BlockNumber nblocks)
Definition: storage.c:288
#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL
Definition: vacuumlazy.c:82
#define VACUUM_TRUNCATE_LOCK_TIMEOUT
Definition: vacuumlazy.c:83
static BlockNumber count_nondeletable_pages(LVRelState *vacrel, bool *lock_waiter_detected)
Definition: vacuumlazy.c:2677

References AccessExclusiveLock, LVRelState::blkno, CHECK_FOR_INTERRUPTS, ConditionalLockRelation(), count_nondeletable_pages(), DEBUG2, ereport, errmsg(), INFO, InvalidOffsetNumber, MyLatch, LVRelState::nonempty_pages, pgstat_progress_update_param(), PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_TRUNCATE, LVRelState::rel, LVRelState::rel_pages, RelationGetNumberOfBlocks, RelationTruncate(), LVRelState::relname, LVRelState::removed_pages, ResetLatch(), UnlockRelation(), update_vacuum_error_info(), VACUUM_ERRCB_PHASE_TRUNCATE, VACUUM_TRUNCATE_LOCK_TIMEOUT, VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL, LVRelState::verbose, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by heap_vacuum_rel().

◆ lazy_vacuum()

static void lazy_vacuum ( LVRelState vacrel)
static

Definition at line 1861 of file vacuumlazy.c.

1862 {
1863  bool bypass;
1864 
1865  /* Should not end up here with no indexes */
1866  Assert(vacrel->nindexes > 0);
1867  Assert(vacrel->lpdead_item_pages > 0);
1868 
1869  if (!vacrel->do_index_vacuuming)
1870  {
1871  Assert(!vacrel->do_index_cleanup);
1872  dead_items_reset(vacrel);
1873  return;
1874  }
1875 
1876  /*
1877  * Consider bypassing index vacuuming (and heap vacuuming) entirely.
1878  *
1879  * We currently only do this in cases where the number of LP_DEAD items
1880  * for the entire VACUUM operation is close to zero. This avoids sharp
1881  * discontinuities in the duration and overhead of successive VACUUM
1882  * operations that run against the same table with a fixed workload.
1883  * Ideally, successive VACUUM operations will behave as if there are
1884  * exactly zero LP_DEAD items in cases where there are close to zero.
1885  *
1886  * This is likely to be helpful with a table that is continually affected
1887  * by UPDATEs that can mostly apply the HOT optimization, but occasionally
1888  * have small aberrations that lead to just a few heap pages retaining
1889  * only one or two LP_DEAD items. This is pretty common; even when the
1890  * DBA goes out of their way to make UPDATEs use HOT, it is practically
1891  * impossible to predict whether HOT will be applied in 100% of cases.
1892  * It's far easier to ensure that 99%+ of all UPDATEs against a table use
1893  * HOT through careful tuning.
1894  */
1895  bypass = false;
1896  if (vacrel->consider_bypass_optimization && vacrel->rel_pages > 0)
1897  {
1898  BlockNumber threshold;
1899 
1900  Assert(vacrel->num_index_scans == 0);
1901  Assert(vacrel->lpdead_items == vacrel->dead_items_info->num_items);
1902  Assert(vacrel->do_index_vacuuming);
1903  Assert(vacrel->do_index_cleanup);
1904 
1905  /*
1906  * This crossover point at which we'll start to do index vacuuming is
1907  * expressed as a percentage of the total number of heap pages in the
1908  * table that are known to have at least one LP_DEAD item. This is
1909  * much more important than the total number of LP_DEAD items, since
1910  * it's a proxy for the number of heap pages whose visibility map bits
1911  * cannot be set on account of bypassing index and heap vacuuming.
1912  *
1913  * We apply one further precautionary test: the space currently used
1914  * to store the TIDs (TIDs that now all point to LP_DEAD items) must
1915  * not exceed 32MB. This limits the risk that we will bypass index
1916  * vacuuming again and again until eventually there is a VACUUM whose
1917  * dead_items space is not CPU cache resident.
1918  *
1919  * We don't take any special steps to remember the LP_DEAD items (such
1920  * as counting them in our final update to the stats system) when the
1921  * optimization is applied. Though the accounting used in analyze.c's
1922  * acquire_sample_rows() will recognize the same LP_DEAD items as dead
1923  * rows in its own stats report, that's okay. The discrepancy should
1924  * be negligible. If this optimization is ever expanded to cover more
1925  * cases then this may need to be reconsidered.
1926  */
1927  threshold = (double) vacrel->rel_pages * BYPASS_THRESHOLD_PAGES;
1928  bypass = (vacrel->lpdead_item_pages < threshold &&
1929  (TidStoreMemoryUsage(vacrel->dead_items) < (32L * 1024L * 1024L)));
1930  }
1931 
1932  if (bypass)
1933  {
1934  /*
1935  * There are almost zero TIDs. Behave as if there were precisely
1936  * zero: bypass index vacuuming, but do index cleanup.
1937  *
1938  * We expect that the ongoing VACUUM operation will finish very
1939  * quickly, so there is no point in considering speeding up as a
1940  * failsafe against wraparound failure. (Index cleanup is expected to
1941  * finish very quickly in cases where there were no ambulkdelete()
1942  * calls.)
1943  */
1944  vacrel->do_index_vacuuming = false;
1945  }
1946  else if (lazy_vacuum_all_indexes(vacrel))
1947  {
1948  /*
1949  * We successfully completed a round of index vacuuming. Do related
1950  * heap vacuuming now.
1951  */
1952  lazy_vacuum_heap_rel(vacrel);
1953  }
1954  else
1955  {
1956  /*
1957  * Failsafe case.
1958  *
1959  * We attempted index vacuuming, but didn't finish a full round/full
1960  * index scan. This happens when relfrozenxid or relminmxid is too
1961  * far in the past.
1962  *
1963  * From this point on the VACUUM operation will do no further index
1964  * vacuuming or heap vacuuming. This VACUUM operation won't end up
1965  * back here again.
1966  */
1968  }
1969 
1970  /*
1971  * Forget the LP_DEAD items that we just vacuumed (or just decided to not
1972  * vacuum)
1973  */
1974  dead_items_reset(vacrel);
1975 }
static void dead_items_reset(LVRelState *vacrel)
Definition: vacuumlazy.c:2901
#define BYPASS_THRESHOLD_PAGES
Definition: vacuumlazy.c:89
static bool lazy_vacuum_all_indexes(LVRelState *vacrel)
Definition: vacuumlazy.c:1986
static void lazy_vacuum_heap_rel(LVRelState *vacrel)
Definition: vacuumlazy.c:2103

References Assert, BYPASS_THRESHOLD_PAGES, LVRelState::consider_bypass_optimization, LVRelState::dead_items, LVRelState::dead_items_info, dead_items_reset(), LVRelState::do_index_cleanup, LVRelState::do_index_vacuuming, lazy_vacuum_all_indexes(), lazy_vacuum_heap_rel(), LVRelState::lpdead_item_pages, LVRelState::lpdead_items, LVRelState::nindexes, LVRelState::num_index_scans, VacDeadItemsInfo::num_items, LVRelState::rel_pages, TidStoreMemoryUsage(), and VacuumFailsafeActive.

Referenced by lazy_scan_heap().

◆ lazy_vacuum_all_indexes()

static bool lazy_vacuum_all_indexes ( LVRelState vacrel)
static

Definition at line 1986 of file vacuumlazy.c.

1987 {
1988  bool allindexes = true;
1989  double old_live_tuples = vacrel->rel->rd_rel->reltuples;
1990  const int progress_start_index[] = {
1993  };
1994  const int progress_end_index[] = {
1998  };
1999  int64 progress_start_val[2];
2000  int64 progress_end_val[3];
2001 
2002  Assert(vacrel->nindexes > 0);
2003  Assert(vacrel->do_index_vacuuming);
2004  Assert(vacrel->do_index_cleanup);
2005 
2006  /* Precheck for XID wraparound emergencies */
2007  if (lazy_check_wraparound_failsafe(vacrel))
2008  {
2009  /* Wraparound emergency -- don't even start an index scan */
2010  return false;
2011  }
2012 
2013  /*
2014  * Report that we are now vacuuming indexes and the number of indexes to
2015  * vacuum.
2016  */
2017  progress_start_val[0] = PROGRESS_VACUUM_PHASE_VACUUM_INDEX;
2018  progress_start_val[1] = vacrel->nindexes;
2019  pgstat_progress_update_multi_param(2, progress_start_index, progress_start_val);
2020 
2021  if (!ParallelVacuumIsActive(vacrel))
2022  {
2023  for (int idx = 0; idx < vacrel->nindexes; idx++)
2024  {
2025  Relation indrel = vacrel->indrels[idx];
2026  IndexBulkDeleteResult *istat = vacrel->indstats[idx];
2027 
2028  vacrel->indstats[idx] = lazy_vacuum_one_index(indrel, istat,
2029  old_live_tuples,
2030  vacrel);
2031 
2032  /* Report the number of indexes vacuumed */
2034  idx + 1);
2035 
2036  if (lazy_check_wraparound_failsafe(vacrel))
2037  {
2038  /* Wraparound emergency -- end current index scan */
2039  allindexes = false;
2040  break;
2041  }
2042  }
2043  }
2044  else
2045  {
2046  /* Outsource everything to parallel variant */
2047  parallel_vacuum_bulkdel_all_indexes(vacrel->pvs, old_live_tuples,
2048  vacrel->num_index_scans);
2049 
2050  /*
2051  * Do a postcheck to consider applying wraparound failsafe now. Note
2052  * that parallel VACUUM only gets the precheck and this postcheck.
2053  */
2054  if (lazy_check_wraparound_failsafe(vacrel))
2055  allindexes = false;
2056  }
2057 
2058  /*
2059  * We delete all LP_DEAD items from the first heap pass in all indexes on
2060  * each call here (except calls where we choose to do the failsafe). This
2061  * makes the next call to lazy_vacuum_heap_rel() safe (except in the event
2062  * of the failsafe triggering, which prevents the next call from taking
2063  * place).
2064  */
2065  Assert(vacrel->num_index_scans > 0 ||
2066  vacrel->dead_items_info->num_items == vacrel->lpdead_items);
2067  Assert(allindexes || VacuumFailsafeActive);
2068 
2069  /*
2070  * Increase and report the number of index scans. Also, we reset
2071  * PROGRESS_VACUUM_INDEXES_TOTAL and PROGRESS_VACUUM_INDEXES_PROCESSED.
2072  *
2073  * We deliberately include the case where we started a round of bulk
2074  * deletes that we weren't able to finish due to the failsafe triggering.
2075  */
2076  vacrel->num_index_scans++;
2077  progress_end_val[0] = 0;
2078  progress_end_val[1] = 0;
2079  progress_end_val[2] = vacrel->num_index_scans;
2080  pgstat_progress_update_multi_param(3, progress_end_index, progress_end_val);
2081 
2082  return allindexes;
2083 }
#define PROGRESS_VACUUM_NUM_INDEX_VACUUMS
Definition: progress.h:25
#define PROGRESS_VACUUM_PHASE_VACUUM_INDEX
Definition: progress.h:33
static IndexBulkDeleteResult * lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat, double reltuples, LVRelState *vacrel)
Definition: vacuumlazy.c:2417
void parallel_vacuum_bulkdel_all_indexes(ParallelVacuumState *pvs, long num_table_tuples, int num_index_scans)

References Assert, LVRelState::dead_items_info, LVRelState::do_index_cleanup, LVRelState::do_index_vacuuming, idx(), LVRelState::indrels, LVRelState::indstats, lazy_check_wraparound_failsafe(), lazy_vacuum_one_index(), LVRelState::lpdead_items, LVRelState::nindexes, LVRelState::num_index_scans, VacDeadItemsInfo::num_items, parallel_vacuum_bulkdel_all_indexes(), ParallelVacuumIsActive, pgstat_progress_update_multi_param(), pgstat_progress_update_param(), PROGRESS_VACUUM_INDEXES_PROCESSED, PROGRESS_VACUUM_INDEXES_TOTAL, PROGRESS_VACUUM_NUM_INDEX_VACUUMS, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_VACUUM_INDEX, LVRelState::pvs, RelationData::rd_rel, LVRelState::rel, and VacuumFailsafeActive.

Referenced by lazy_vacuum().

◆ lazy_vacuum_heap_page()

static void lazy_vacuum_heap_page ( LVRelState vacrel,
BlockNumber  blkno,
Buffer  buffer,
OffsetNumber offsets,
int  num_offsets,
Buffer  vmbuffer 
)
static

Definition at line 2191 of file vacuumlazy.c.

2194 {
2195  Page page = BufferGetPage(buffer);
2197  int nunused = 0;
2198  TransactionId visibility_cutoff_xid;
2199  bool all_frozen;
2200  LVSavedErrInfo saved_err_info;
2201 
2202  Assert(vacrel->do_index_vacuuming);
2203 
2205 
2206  /* Update error traceback information */
2207  update_vacuum_error_info(vacrel, &saved_err_info,
2210 
2212 
2213  for (int i = 0; i < num_offsets; i++)
2214  {
2215  ItemId itemid;
2216  OffsetNumber toff = deadoffsets[i];
2217 
2218  itemid = PageGetItemId(page, toff);
2219 
2220  Assert(ItemIdIsDead(itemid) && !ItemIdHasStorage(itemid));
2221  ItemIdSetUnused(itemid);
2222  unused[nunused++] = toff;
2223  }
2224 
2225  Assert(nunused > 0);
2226 
2227  /* Attempt to truncate line pointer array now */
2229 
2230  /*
2231  * Mark buffer dirty before we write WAL.
2232  */
2233  MarkBufferDirty(buffer);
2234 
2235  /* XLOG stuff */
2236  if (RelationNeedsWAL(vacrel->rel))
2237  {
2238  log_heap_prune_and_freeze(vacrel->rel, buffer,
2240  false, /* no cleanup lock required */
2242  NULL, 0, /* frozen */
2243  NULL, 0, /* redirected */
2244  NULL, 0, /* dead */
2245  unused, nunused);
2246  }
2247 
2248  /*
2249  * End critical section, so we safely can do visibility tests (which
2250  * possibly need to perform IO and allocate memory!). If we crash now the
2251  * page (including the corresponding vm bit) might not be marked all
2252  * visible, but that's fine. A later vacuum will fix that.
2253  */
2254  END_CRIT_SECTION();
2255 
2256  /*
2257  * Now that we have removed the LP_DEAD items from the page, once again
2258  * check if the page has become all-visible. The page is already marked
2259  * dirty, exclusively locked, and, if needed, a full page image has been
2260  * emitted.
2261  */
2262  Assert(!PageIsAllVisible(page));
2263  if (heap_page_is_all_visible(vacrel, buffer, &visibility_cutoff_xid,
2264  &all_frozen))
2265  {
2267 
2268  if (all_frozen)
2269  {
2270  Assert(!TransactionIdIsValid(visibility_cutoff_xid));
2271  flags |= VISIBILITYMAP_ALL_FROZEN;
2272  }
2273 
2274  PageSetAllVisible(page);
2275  visibilitymap_set(vacrel->rel, blkno, buffer, InvalidXLogRecPtr,
2276  vmbuffer, visibility_cutoff_xid, flags);
2277  }
2278 
2279  /* Revert to the previous phase information for error traceback */
2280  restore_vacuum_error_info(vacrel, &saved_err_info);
2281 }
void PageTruncateLinePointerArray(Page page)
Definition: bufpage.c:835
@ PRUNE_VACUUM_CLEANUP
Definition: heapam.h:271
#define ItemIdSetUnused(itemId)
Definition: itemid.h:128
#define ItemIdHasStorage(itemId)
Definition: itemid.h:120
void log_heap_prune_and_freeze(Relation relation, Buffer buffer, TransactionId conflict_xid, bool cleanup_lock, PruneReason reason, HeapTupleFreeze *frozen, int nfrozen, OffsetNumber *redirected, int nredirected, OffsetNumber *dead, int ndead, OffsetNumber *unused, int nunused)
Definition: pruneheap.c:2032

References Assert, BufferGetPage(), LVRelState::do_index_vacuuming, END_CRIT_SECTION, heap_page_is_all_visible(), i, InvalidOffsetNumber, InvalidTransactionId, InvalidXLogRecPtr, ItemIdHasStorage, ItemIdIsDead, ItemIdSetUnused, log_heap_prune_and_freeze(), MarkBufferDirty(), MaxHeapTuplesPerPage, PageGetItemId(), PageIsAllVisible(), PageSetAllVisible(), PageTruncateLinePointerArray(), pgstat_progress_update_param(), PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, PRUNE_VACUUM_CLEANUP, LVRelState::rel, RelationNeedsWAL, restore_vacuum_error_info(), START_CRIT_SECTION, TransactionIdIsValid, update_vacuum_error_info(), VACUUM_ERRCB_PHASE_VACUUM_HEAP, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, and visibilitymap_set().

Referenced by lazy_vacuum_heap_rel().

◆ lazy_vacuum_heap_rel()

static void lazy_vacuum_heap_rel ( LVRelState vacrel)
static

Definition at line 2103 of file vacuumlazy.c.

2104 {
2105  BlockNumber vacuumed_pages = 0;
2106  Buffer vmbuffer = InvalidBuffer;
2107  LVSavedErrInfo saved_err_info;
2108  TidStoreIter *iter;
2109  TidStoreIterResult *iter_result;
2110 
2111  Assert(vacrel->do_index_vacuuming);
2112  Assert(vacrel->do_index_cleanup);
2113  Assert(vacrel->num_index_scans > 0);
2114 
2115  /* Report that we are now vacuuming the heap */
2118 
2119  /* Update error traceback information */
2120  update_vacuum_error_info(vacrel, &saved_err_info,
2123 
2124  iter = TidStoreBeginIterate(vacrel->dead_items);
2125  while ((iter_result = TidStoreIterateNext(iter)) != NULL)
2126  {
2127  BlockNumber blkno;
2128  Buffer buf;
2129  Page page;
2130  Size freespace;
2131 
2133 
2134  blkno = iter_result->blkno;
2135  vacrel->blkno = blkno;
2136 
2137  /*
2138  * Pin the visibility map page in case we need to mark the page
2139  * all-visible. In most cases this will be very cheap, because we'll
2140  * already have the correct page pinned anyway.
2141  */
2142  visibilitymap_pin(vacrel->rel, blkno, &vmbuffer);
2143 
2144  /* We need a non-cleanup exclusive lock to mark dead_items unused */
2145  buf = ReadBufferExtended(vacrel->rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
2146  vacrel->bstrategy);
2148  lazy_vacuum_heap_page(vacrel, blkno, buf, iter_result->offsets,
2149  iter_result->num_offsets, vmbuffer);
2150 
2151  /* Now that we've vacuumed the page, record its available space */
2152  page = BufferGetPage(buf);
2153  freespace = PageGetHeapFreeSpace(page);
2154 
2156  RecordPageWithFreeSpace(vacrel->rel, blkno, freespace);
2157  vacuumed_pages++;
2158  }
2159  TidStoreEndIterate(iter);
2160 
2161  vacrel->blkno = InvalidBlockNumber;
2162  if (BufferIsValid(vmbuffer))
2163  ReleaseBuffer(vmbuffer);
2164 
2165  /*
2166  * We set all LP_DEAD items from the first heap pass to LP_UNUSED during
2167  * the second heap pass. No more, no less.
2168  */
2169  Assert(vacrel->num_index_scans > 1 ||
2170  (vacrel->dead_items_info->num_items == vacrel->lpdead_items &&
2171  vacuumed_pages == vacrel->lpdead_item_pages));
2172 
2173  ereport(DEBUG2,
2174  (errmsg("table \"%s\": removed %lld dead item identifiers in %u pages",
2175  vacrel->relname, (long long) vacrel->dead_items_info->num_items,
2176  vacuumed_pages)));
2177 
2178  /* Revert to the previous phase information for error traceback */
2179  restore_vacuum_error_info(vacrel, &saved_err_info);
2180 }
#define PROGRESS_VACUUM_PHASE_VACUUM_HEAP
Definition: progress.h:34
BlockNumber blkno
Definition: tidstore.h:26
OffsetNumber * offsets
Definition: tidstore.h:29
void TidStoreEndIterate(TidStoreIter *iter)
Definition: tidstore.c:536
TidStoreIterResult * TidStoreIterateNext(TidStoreIter *iter)
Definition: tidstore.c:511
TidStoreIter * TidStoreBeginIterate(TidStore *ts)
Definition: tidstore.c:482
static void lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer, OffsetNumber *offsets, int num_offsets, Buffer vmbuffer)
Definition: vacuumlazy.c:2191

References Assert, LVRelState::blkno, TidStoreIterResult::blkno, LVRelState::bstrategy, buf, BUFFER_LOCK_EXCLUSIVE, BufferGetPage(), BufferIsValid(), LVRelState::dead_items, LVRelState::dead_items_info, DEBUG2, LVRelState::do_index_cleanup, LVRelState::do_index_vacuuming, ereport, errmsg(), InvalidBlockNumber, InvalidBuffer, InvalidOffsetNumber, lazy_vacuum_heap_page(), LockBuffer(), LVRelState::lpdead_item_pages, LVRelState::lpdead_items, MAIN_FORKNUM, LVRelState::num_index_scans, VacDeadItemsInfo::num_items, TidStoreIterResult::num_offsets, TidStoreIterResult::offsets, PageGetHeapFreeSpace(), pgstat_progress_update_param(), PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_VACUUM_HEAP, RBM_NORMAL, ReadBufferExtended(), RecordPageWithFreeSpace(), LVRelState::rel, ReleaseBuffer(), LVRelState::relname, restore_vacuum_error_info(), TidStoreBeginIterate(), TidStoreEndIterate(), TidStoreIterateNext(), UnlockReleaseBuffer(), update_vacuum_error_info(), vacuum_delay_point(), VACUUM_ERRCB_PHASE_VACUUM_HEAP, and visibilitymap_pin().

Referenced by lazy_vacuum().

◆ lazy_vacuum_one_index()

static IndexBulkDeleteResult * lazy_vacuum_one_index ( Relation  indrel,
IndexBulkDeleteResult istat,
double  reltuples,
LVRelState vacrel 
)
static

Definition at line 2417 of file vacuumlazy.c.

2419 {
2420  IndexVacuumInfo ivinfo;
2421  LVSavedErrInfo saved_err_info;
2422 
2423  ivinfo.index = indrel;
2424  ivinfo.heaprel = vacrel->rel;
2425  ivinfo.analyze_only = false;
2426  ivinfo.report_progress = false;
2427  ivinfo.estimated_count = true;
2428  ivinfo.message_level = DEBUG2;
2429  ivinfo.num_heap_tuples = reltuples;
2430  ivinfo.strategy = vacrel->bstrategy;
2431 
2432  /*
2433  * Update error traceback information.
2434  *
2435  * The index name is saved during this phase and restored immediately
2436  * after this phase. See vacuum_error_callback.
2437  */
2438  Assert(vacrel->indname == NULL);
2439  vacrel->indname = pstrdup(RelationGetRelationName(indrel));
2440  update_vacuum_error_info(vacrel, &saved_err_info,
2443 
2444  /* Do bulk deletion */
2445  istat = vac_bulkdel_one_index(&ivinfo, istat, (void *) vacrel->dead_items,
2446  vacrel->dead_items_info);
2447 
2448  /* Revert to the previous phase information for error traceback */
2449  restore_vacuum_error_info(vacrel, &saved_err_info);
2450  pfree(vacrel->indname);
2451  vacrel->indname = NULL;
2452 
2453  return istat;
2454 }
IndexBulkDeleteResult * vac_bulkdel_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat, TidStore *dead_items, VacDeadItemsInfo *dead_items_info)
Definition: vacuum.c:2490

References IndexVacuumInfo::analyze_only, Assert, LVRelState::bstrategy, LVRelState::dead_items, LVRelState::dead_items_info, DEBUG2, IndexVacuumInfo::estimated_count, IndexVacuumInfo::heaprel, IndexVacuumInfo::index, LVRelState::indname, InvalidBlockNumber, InvalidOffsetNumber, IndexVacuumInfo::message_level, IndexVacuumInfo::num_heap_tuples, pfree(), pstrdup(), LVRelState::rel, RelationGetRelationName, IndexVacuumInfo::report_progress, restore_vacuum_error_info(), IndexVacuumInfo::strategy, update_vacuum_error_info(), vac_bulkdel_one_index(), and VACUUM_ERRCB_PHASE_VACUUM_INDEX.

Referenced by lazy_vacuum_all_indexes().

◆ restore_vacuum_error_info()

static void restore_vacuum_error_info ( LVRelState vacrel,
const LVSavedErrInfo saved_vacrel 
)
static

Definition at line 3182 of file vacuumlazy.c.

3184 {
3185  vacrel->blkno = saved_vacrel->blkno;
3186  vacrel->offnum = saved_vacrel->offnum;
3187  vacrel->phase = saved_vacrel->phase;
3188 }
BlockNumber blkno
Definition: vacuumlazy.c:224
VacErrPhase phase
Definition: vacuumlazy.c:226
OffsetNumber offnum
Definition: vacuumlazy.c:225

References LVRelState::blkno, LVSavedErrInfo::blkno, LVRelState::offnum, LVSavedErrInfo::offnum, LVRelState::phase, and LVSavedErrInfo::phase.

Referenced by lazy_cleanup_one_index(), lazy_vacuum_heap_page(), lazy_vacuum_heap_rel(), and lazy_vacuum_one_index().

◆ should_attempt_truncation()

static bool should_attempt_truncation ( LVRelState vacrel)
static

Definition at line 2526 of file vacuumlazy.c.

2527 {
2528  BlockNumber possibly_freeable;
2529 
2530  if (!vacrel->do_rel_truncate || VacuumFailsafeActive)
2531  return false;
2532 
2533  possibly_freeable = vacrel->rel_pages - vacrel->nonempty_pages;
2534  if (possibly_freeable > 0 &&
2535  (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
2536  possibly_freeable >= vacrel->rel_pages / REL_TRUNCATE_FRACTION))
2537  return true;
2538 
2539  return false;
2540 }
#define REL_TRUNCATE_MINIMUM
Definition: vacuumlazy.c:71
#define REL_TRUNCATE_FRACTION
Definition: vacuumlazy.c:72

References LVRelState::do_rel_truncate, LVRelState::nonempty_pages, LVRelState::rel_pages, REL_TRUNCATE_FRACTION, REL_TRUNCATE_MINIMUM, and VacuumFailsafeActive.

Referenced by heap_vacuum_rel().

◆ update_relstats_all_indexes()

static void update_relstats_all_indexes ( LVRelState vacrel)
static

Definition at line 3064 of file vacuumlazy.c.

3065 {
3066  Relation *indrels = vacrel->indrels;
3067  int nindexes = vacrel->nindexes;
3068  IndexBulkDeleteResult **indstats = vacrel->indstats;
3069 
3070  Assert(vacrel->do_index_cleanup);
3071 
3072  for (int idx = 0; idx < nindexes; idx++)
3073  {
3074  Relation indrel = indrels[idx];
3075  IndexBulkDeleteResult *istat = indstats[idx];
3076 
3077  if (istat == NULL || istat->estimated_count)
3078  continue;
3079 
3080  /* Update index statistics */
3081  vac_update_relstats(indrel,
3082  istat->num_pages,
3083  istat->num_index_tuples,
3084  0,
3085  false,
3088  NULL, NULL, false);
3089  }
3090 }
bool estimated_count
Definition: genam.h:78
double num_index_tuples
Definition: genam.h:79

References Assert, LVRelState::do_index_cleanup, IndexBulkDeleteResult::estimated_count, idx(), LVRelState::indrels, LVRelState::indstats, InvalidMultiXactId, InvalidTransactionId, LVRelState::nindexes, IndexBulkDeleteResult::num_index_tuples, IndexBulkDeleteResult::num_pages, and vac_update_relstats().

Referenced by heap_vacuum_rel().

◆ update_vacuum_error_info()

static void update_vacuum_error_info ( LVRelState vacrel,
LVSavedErrInfo saved_vacrel,
int  phase,
BlockNumber  blkno,
OffsetNumber  offnum 
)
static

Definition at line 3163 of file vacuumlazy.c.

3165 {
3166  if (saved_vacrel)
3167  {
3168  saved_vacrel->offnum = vacrel->offnum;
3169  saved_vacrel->blkno = vacrel->blkno;
3170  saved_vacrel->phase = vacrel->phase;
3171  }
3172 
3173  vacrel->blkno = blkno;
3174  vacrel->offnum = offnum;
3175  vacrel->phase = phase;
3176 }

References LVRelState::blkno, LVSavedErrInfo::blkno, LVRelState::offnum, LVSavedErrInfo::offnum, LVRelState::phase, and LVSavedErrInfo::phase.

Referenced by lazy_cleanup_one_index(), lazy_scan_heap(), lazy_truncate_heap(), lazy_vacuum_heap_page(), lazy_vacuum_heap_rel(), and lazy_vacuum_one_index().

◆ vacuum_error_callback()

static void vacuum_error_callback ( void *  arg)
static

Definition at line 3099 of file vacuumlazy.c.

3100 {
3101  LVRelState *errinfo = arg;
3102 
3103  switch (errinfo->phase)
3104  {
3106  if (BlockNumberIsValid(errinfo->blkno))
3107  {
3108  if (OffsetNumberIsValid(errinfo->offnum))
3109  errcontext("while scanning block %u offset %u of relation \"%s.%s\"",
3110  errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
3111  else
3112  errcontext("while scanning block %u of relation \"%s.%s\"",
3113  errinfo->blkno, errinfo->relnamespace, errinfo->relname);
3114  }
3115  else
3116  errcontext("while scanning relation \"%s.%s\"",
3117  errinfo->relnamespace, errinfo->relname);
3118  break;
3119 
3121  if (BlockNumberIsValid(errinfo->blkno))
3122  {
3123  if (OffsetNumberIsValid(errinfo->offnum))
3124  errcontext("while vacuuming block %u offset %u of relation \"%s.%s\"",
3125  errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
3126  else
3127  errcontext("while vacuuming block %u of relation \"%s.%s\"",
3128  errinfo->blkno, errinfo->relnamespace, errinfo->relname);
3129  }
3130  else
3131  errcontext("while vacuuming relation \"%s.%s\"",
3132  errinfo->relnamespace, errinfo->relname);
3133  break;
3134 
3136  errcontext("while vacuuming index \"%s\" of relation \"%s.%s\"",
3137  errinfo->indname, errinfo->relnamespace, errinfo->relname);
3138  break;
3139 
3141  errcontext("while cleaning up index \"%s\" of relation \"%s.%s\"",
3142  errinfo->indname, errinfo->relnamespace, errinfo->relname);
3143  break;
3144 
3146  if (BlockNumberIsValid(errinfo->blkno))
3147  errcontext("while truncating relation \"%s.%s\" to %u blocks",
3148  errinfo->relnamespace, errinfo->relname, errinfo->blkno);
3149  break;
3150 
3152  default:
3153  return; /* do nothing; the errinfo may not be
3154  * initialized */
3155  }
3156 }
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
#define errcontext
Definition: elog.h:196
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
void * arg

References arg, LVRelState::blkno, BlockNumberIsValid(), errcontext, LVRelState::indname, LVRelState::offnum, OffsetNumberIsValid, LVRelState::phase, LVRelState::relname, LVRelState::relnamespace, VACUUM_ERRCB_PHASE_INDEX_CLEANUP, VACUUM_ERRCB_PHASE_SCAN_HEAP, VACUUM_ERRCB_PHASE_TRUNCATE, VACUUM_ERRCB_PHASE_UNKNOWN, VACUUM_ERRCB_PHASE_VACUUM_HEAP, and VACUUM_ERRCB_PHASE_VACUUM_INDEX.

Referenced by heap_vacuum_rel().