PostgreSQL Source Code  git master
vacuumlazy.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/amapi.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/parallel.h"
#include "access/transam.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/storage.h"
#include "commands/dbcommands.h"
#include "commands/progress.h"
#include "commands/vacuum.h"
#include "executor/instrument.h"
#include "miscadmin.h"
#include "optimizer/paths.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 "tcop/tcopprot.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  LVDeadTuples
 
struct  LVShared
 
struct  LVSharedIndStats
 
struct  LVParallelState
 
struct  LVRelStats
 
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 VACUUM_FSM_EVERY_PAGES   ((BlockNumber) (((uint64) 8 * 1024 * 1024 * 1024) / BLCKSZ))
 
#define LAZY_ALLOC_TUPLES   MaxHeapTuplesPerPage
 
#define SKIP_PAGES_THRESHOLD   ((BlockNumber) 32)
 
#define PREFETCH_SIZE   ((BlockNumber) 32)
 
#define PARALLEL_VACUUM_KEY_SHARED   1
 
#define PARALLEL_VACUUM_KEY_DEAD_TUPLES   2
 
#define PARALLEL_VACUUM_KEY_QUERY_TEXT   3
 
#define PARALLEL_VACUUM_KEY_BUFFER_USAGE   4
 
#define PARALLEL_VACUUM_KEY_WAL_USAGE   5
 
#define ParallelVacuumIsActive(lps)   PointerIsValid(lps)
 
#define SizeOfDeadTuples(cnt)
 
#define MAXDEADTUPLES(max_size)   (((max_size) - offsetof(LVDeadTuples, itemptrs)) / sizeof(ItemPointerData))
 
#define SizeOfLVShared   (offsetof(LVShared, bitmap) + sizeof(bits8))
 
#define GetSharedIndStats(s)   ((LVSharedIndStats *)((char *)(s) + ((LVShared *)(s))->offset))
 
#define IndStatsIsNull(s, i)   (!(((LVShared *)(s))->bitmap[(i) >> 3] & (1 << ((i) & 0x07))))
 
#define FORCE_CHECK_PAGE()   (blkno == nblocks - 1 && should_attempt_truncation(params, vacrelstats))
 

Typedefs

typedef struct LVDeadTuples LVDeadTuples
 
typedef struct LVShared LVShared
 
typedef struct LVSharedIndStats LVSharedIndStats
 
typedef struct LVParallelState LVParallelState
 
typedef struct LVRelStats LVRelStats
 
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 (Relation onerel, VacuumParams *params, LVRelStats *vacrelstats, Relation *Irel, int nindexes, bool aggressive)
 
static void lazy_vacuum_heap (Relation onerel, LVRelStats *vacrelstats)
 
static bool lazy_check_needs_freeze (Buffer buf, bool *hastup, LVRelStats *vacrelstats)
 
static void lazy_vacuum_all_indexes (Relation onerel, Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
 
static void lazy_vacuum_index (Relation indrel, IndexBulkDeleteResult **stats, LVDeadTuples *dead_tuples, double reltuples, LVRelStats *vacrelstats)
 
static void lazy_cleanup_index (Relation indrel, IndexBulkDeleteResult **stats, double reltuples, bool estimated_count, LVRelStats *vacrelstats)
 
static int lazy_vacuum_page (Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer)
 
static bool should_attempt_truncation (VacuumParams *params, LVRelStats *vacrelstats)
 
static void lazy_truncate_heap (Relation onerel, LVRelStats *vacrelstats)
 
static BlockNumber count_nondeletable_pages (Relation onerel, LVRelStats *vacrelstats)
 
static void lazy_space_alloc (LVRelStats *vacrelstats, BlockNumber relblocks)
 
static void lazy_record_dead_tuple (LVDeadTuples *dead_tuples, ItemPointer itemptr)
 
static bool lazy_tid_reaped (ItemPointer itemptr, void *state)
 
static int vac_cmp_itemptr (const void *left, const void *right)
 
static bool heap_page_is_all_visible (Relation rel, Buffer buf, LVRelStats *vacrelstats, TransactionId *visibility_cutoff_xid, bool *all_frozen)
 
static void lazy_parallel_vacuum_indexes (Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
 
static void parallel_vacuum_index (Relation *Irel, IndexBulkDeleteResult **stats, LVShared *lvshared, LVDeadTuples *dead_tuples, int nindexes, LVRelStats *vacrelstats)
 
static void vacuum_indexes_leader (Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
 
static void vacuum_one_index (Relation indrel, IndexBulkDeleteResult **stats, LVShared *lvshared, LVSharedIndStats *shared_indstats, LVDeadTuples *dead_tuples, LVRelStats *vacrelstats)
 
static void lazy_cleanup_all_indexes (Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
 
static long compute_max_dead_tuples (BlockNumber relblocks, bool hasindex)
 
static int compute_parallel_vacuum_workers (Relation *Irel, int nindexes, int nrequested, bool *can_parallel_vacuum)
 
static void prepare_index_statistics (LVShared *lvshared, bool *can_parallel_vacuum, int nindexes)
 
static void update_index_statistics (Relation *Irel, IndexBulkDeleteResult **stats, int nindexes)
 
static LVParallelStatebegin_parallel_vacuum (Oid relid, Relation *Irel, LVRelStats *vacrelstats, BlockNumber nblocks, int nindexes, int nrequested)
 
static void end_parallel_vacuum (IndexBulkDeleteResult **stats, LVParallelState *lps, int nindexes)
 
static LVSharedIndStatsget_indstats (LVShared *lvshared, int n)
 
static bool skip_parallel_vacuum_index (Relation indrel, LVShared *lvshared)
 
static void vacuum_error_callback (void *arg)
 
static void update_vacuum_error_info (LVRelStats *errinfo, LVSavedErrInfo *saved_err_info, int phase, BlockNumber blkno, OffsetNumber offnum)
 
static void restore_vacuum_error_info (LVRelStats *errinfo, const LVSavedErrInfo *saved_err_info)
 
void heap_vacuum_rel (Relation onerel, VacuumParams *params, BufferAccessStrategy bstrategy)
 
static void vacuum_log_cleanup_info (Relation rel, LVRelStats *vacrelstats)
 
void parallel_vacuum_main (dsm_segment *seg, shm_toc *toc)
 

Variables

static int elevel = -1
 
static TransactionId OldestXmin
 
static TransactionId FreezeLimit
 
static MultiXactId MultiXactCutoff
 
static BufferAccessStrategy vac_strategy
 

Macro Definition Documentation

◆ FORCE_CHECK_PAGE

#define FORCE_CHECK_PAGE ( )    (blkno == nblocks - 1 && should_attempt_truncation(params, vacrelstats))

Referenced by lazy_scan_heap().

◆ GetSharedIndStats

#define GetSharedIndStats (   s)    ((LVSharedIndStats *)((char *)(s) + ((LVShared *)(s))->offset))

Definition at line 254 of file vacuumlazy.c.

Referenced by get_indstats().

◆ IndStatsIsNull

#define IndStatsIsNull (   s,
  i 
)    (!(((LVShared *)(s))->bitmap[(i) >> 3] & (1 << ((i) & 0x07))))

Definition at line 256 of file vacuumlazy.c.

Referenced by get_indstats().

◆ LAZY_ALLOC_TUPLES

#define LAZY_ALLOC_TUPLES   MaxHeapTuplesPerPage

Definition at line 119 of file vacuumlazy.c.

Referenced by compute_max_dead_tuples().

◆ MAXDEADTUPLES

#define MAXDEADTUPLES (   max_size)    (((max_size) - offsetof(LVDeadTuples, itemptrs)) / sizeof(ItemPointerData))

Definition at line 180 of file vacuumlazy.c.

Referenced by compute_max_dead_tuples().

◆ PARALLEL_VACUUM_KEY_BUFFER_USAGE

#define PARALLEL_VACUUM_KEY_BUFFER_USAGE   4

Definition at line 141 of file vacuumlazy.c.

Referenced by begin_parallel_vacuum(), and parallel_vacuum_main().

◆ PARALLEL_VACUUM_KEY_DEAD_TUPLES

#define PARALLEL_VACUUM_KEY_DEAD_TUPLES   2

Definition at line 139 of file vacuumlazy.c.

Referenced by begin_parallel_vacuum(), and parallel_vacuum_main().

◆ PARALLEL_VACUUM_KEY_QUERY_TEXT

#define PARALLEL_VACUUM_KEY_QUERY_TEXT   3

Definition at line 140 of file vacuumlazy.c.

Referenced by begin_parallel_vacuum(), and parallel_vacuum_main().

◆ PARALLEL_VACUUM_KEY_SHARED

#define PARALLEL_VACUUM_KEY_SHARED   1

Definition at line 138 of file vacuumlazy.c.

Referenced by begin_parallel_vacuum(), and parallel_vacuum_main().

◆ PARALLEL_VACUUM_KEY_WAL_USAGE

#define PARALLEL_VACUUM_KEY_WAL_USAGE   5

Definition at line 142 of file vacuumlazy.c.

Referenced by begin_parallel_vacuum(), and parallel_vacuum_main().

◆ ParallelVacuumIsActive

#define ParallelVacuumIsActive (   lps)    PointerIsValid(lps)

◆ PREFETCH_SIZE

#define PREFETCH_SIZE   ((BlockNumber) 32)

Definition at line 131 of file vacuumlazy.c.

Referenced by count_nondeletable_pages().

◆ REL_TRUNCATE_FRACTION

#define REL_TRUNCATE_FRACTION   16

Definition at line 92 of file vacuumlazy.c.

Referenced by should_attempt_truncation().

◆ REL_TRUNCATE_MINIMUM

#define REL_TRUNCATE_MINIMUM   1000

Definition at line 91 of file vacuumlazy.c.

Referenced by should_attempt_truncation().

◆ SizeOfDeadTuples

#define SizeOfDeadTuples (   cnt)
Value:
mul_size(sizeof(ItemPointerData), cnt))
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
#define offsetof(type, field)
Definition: c.h:723

Definition at line 177 of file vacuumlazy.c.

Referenced by begin_parallel_vacuum(), and lazy_space_alloc().

◆ SizeOfLVShared

#define SizeOfLVShared   (offsetof(LVShared, bitmap) + sizeof(bits8))

Definition at line 253 of file vacuumlazy.c.

Referenced by begin_parallel_vacuum().

◆ SKIP_PAGES_THRESHOLD

#define SKIP_PAGES_THRESHOLD   ((BlockNumber) 32)

Definition at line 125 of file vacuumlazy.c.

Referenced by lazy_scan_heap().

◆ VACUUM_FSM_EVERY_PAGES

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

Definition at line 111 of file vacuumlazy.c.

Referenced by lazy_scan_heap().

◆ VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL

#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL   20 /* ms */

Definition at line 101 of file vacuumlazy.c.

Referenced by count_nondeletable_pages().

◆ VACUUM_TRUNCATE_LOCK_TIMEOUT

#define VACUUM_TRUNCATE_LOCK_TIMEOUT   5000 /* ms */

Definition at line 103 of file vacuumlazy.c.

Referenced by lazy_truncate_heap().

◆ VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL

#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL   50 /* ms */

Definition at line 102 of file vacuumlazy.c.

Referenced by lazy_truncate_heap().

Typedef Documentation

◆ LVDeadTuples

typedef struct LVDeadTuples LVDeadTuples

◆ LVParallelState

◆ LVRelStats

typedef struct LVRelStats LVRelStats

◆ LVSavedErrInfo

◆ LVShared

typedef struct LVShared LVShared

◆ LVSharedIndStats

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 151 of file vacuumlazy.c.

Function Documentation

◆ begin_parallel_vacuum()

static LVParallelState * begin_parallel_vacuum ( Oid  relid,
Relation Irel,
LVRelStats vacrelstats,
BlockNumber  nblocks,
int  nindexes,
int  nrequested 
)
static

Definition at line 3217 of file vacuumlazy.c.

References LVShared::active_nworkers, add_size(), IndexAmRoutine::amparallelvacuumoptions, Assert, BITMAPLEN, LVParallelState::buffer_usage, compute_max_dead_tuples(), compute_parallel_vacuum_workers(), LVShared::cost_balance, CreateParallelContext(), LVRelStats::dead_tuples, debug_query_string, LVShared::elevel, elevel, EnterParallelMode(), ParallelContext::estimator, i, LVShared::idx, InitializeParallelDSM(), LVDeadTuples::itemptrs, LVParallelState::lvshared, maintenance_work_mem, LVShared::maintenance_work_mem_worker, LVDeadTuples::max_tuples, MAXALIGN, MemSet, Min, mul_size(), LVParallelState::nindexes_parallel_bulkdel, LVParallelState::nindexes_parallel_cleanup, LVParallelState::nindexes_parallel_condcleanup, LVDeadTuples::num_tuples, ParallelContext::nworkers, LVShared::offset, palloc0(), PARALLEL_VACUUM_KEY_BUFFER_USAGE, PARALLEL_VACUUM_KEY_DEAD_TUPLES, PARALLEL_VACUUM_KEY_QUERY_TEXT, PARALLEL_VACUUM_KEY_SHARED, PARALLEL_VACUUM_KEY_WAL_USAGE, LVParallelState::pcxt, pfree(), pg_atomic_init_u32(), prepare_index_statistics(), RelationData::rd_indam, LVShared::relid, shm_toc_allocate(), shm_toc_estimate_chunk, shm_toc_estimate_keys, shm_toc_insert(), SizeOfDeadTuples, SizeOfLVShared, ParallelContext::toc, VACUUM_OPTION_MAX_VALID_VALUE, VACUUM_OPTION_PARALLEL_BULKDEL, VACUUM_OPTION_PARALLEL_CLEANUP, VACUUM_OPTION_PARALLEL_COND_CLEANUP, and LVParallelState::wal_usage.

Referenced by lazy_scan_heap().

3219 {
3220  LVParallelState *lps = NULL;
3221  ParallelContext *pcxt;
3222  LVShared *shared;
3223  LVDeadTuples *dead_tuples;
3224  BufferUsage *buffer_usage;
3225  WalUsage *wal_usage;
3226  bool *can_parallel_vacuum;
3227  long maxtuples;
3228  Size est_shared;
3229  Size est_deadtuples;
3230  int nindexes_mwm = 0;
3231  int parallel_workers = 0;
3232  int querylen;
3233  int i;
3234 
3235  /*
3236  * A parallel vacuum must be requested and there must be indexes on the
3237  * relation
3238  */
3239  Assert(nrequested >= 0);
3240  Assert(nindexes > 0);
3241 
3242  /*
3243  * Compute the number of parallel vacuum workers to launch
3244  */
3245  can_parallel_vacuum = (bool *) palloc0(sizeof(bool) * nindexes);
3246  parallel_workers = compute_parallel_vacuum_workers(Irel, nindexes,
3247  nrequested,
3248  can_parallel_vacuum);
3249 
3250  /* Can't perform vacuum in parallel */
3251  if (parallel_workers <= 0)
3252  {
3253  pfree(can_parallel_vacuum);
3254  return lps;
3255  }
3256 
3257  lps = (LVParallelState *) palloc0(sizeof(LVParallelState));
3258 
3260  pcxt = CreateParallelContext("postgres", "parallel_vacuum_main",
3261  parallel_workers);
3262  Assert(pcxt->nworkers > 0);
3263  lps->pcxt = pcxt;
3264 
3265  /* Estimate size for shared information -- PARALLEL_VACUUM_KEY_SHARED */
3266  est_shared = MAXALIGN(add_size(SizeOfLVShared, BITMAPLEN(nindexes)));
3267  for (i = 0; i < nindexes; i++)
3268  {
3269  uint8 vacoptions = Irel[i]->rd_indam->amparallelvacuumoptions;
3270 
3271  /*
3272  * Cleanup option should be either disabled, always performing in
3273  * parallel or conditionally performing in parallel.
3274  */
3275  Assert(((vacoptions & VACUUM_OPTION_PARALLEL_CLEANUP) == 0) ||
3276  ((vacoptions & VACUUM_OPTION_PARALLEL_COND_CLEANUP) == 0));
3277  Assert(vacoptions <= VACUUM_OPTION_MAX_VALID_VALUE);
3278 
3279  /* Skip indexes that don't participate in parallel vacuum */
3280  if (!can_parallel_vacuum[i])
3281  continue;
3282 
3283  if (Irel[i]->rd_indam->amusemaintenanceworkmem)
3284  nindexes_mwm++;
3285 
3286  est_shared = add_size(est_shared, sizeof(LVSharedIndStats));
3287 
3288  /*
3289  * Remember the number of indexes that support parallel operation for
3290  * each phase.
3291  */
3292  if ((vacoptions & VACUUM_OPTION_PARALLEL_BULKDEL) != 0)
3294  if ((vacoptions & VACUUM_OPTION_PARALLEL_CLEANUP) != 0)
3296  if ((vacoptions & VACUUM_OPTION_PARALLEL_COND_CLEANUP) != 0)
3298  }
3299  shm_toc_estimate_chunk(&pcxt->estimator, est_shared);
3300  shm_toc_estimate_keys(&pcxt->estimator, 1);
3301 
3302  /* Estimate size for dead tuples -- PARALLEL_VACUUM_KEY_DEAD_TUPLES */
3303  maxtuples = compute_max_dead_tuples(nblocks, true);
3304  est_deadtuples = MAXALIGN(SizeOfDeadTuples(maxtuples));
3305  shm_toc_estimate_chunk(&pcxt->estimator, est_deadtuples);
3306  shm_toc_estimate_keys(&pcxt->estimator, 1);
3307 
3308  /*
3309  * Estimate space for BufferUsage and WalUsage --
3310  * PARALLEL_VACUUM_KEY_BUFFER_USAGE and PARALLEL_VACUUM_KEY_WAL_USAGE.
3311  *
3312  * If there are no extensions loaded that care, we could skip this. We
3313  * have no way of knowing whether anyone's looking at pgBufferUsage or
3314  * pgWalUsage, so do it unconditionally.
3315  */
3317  mul_size(sizeof(BufferUsage), pcxt->nworkers));
3318  shm_toc_estimate_keys(&pcxt->estimator, 1);
3320  mul_size(sizeof(WalUsage), pcxt->nworkers));
3321  shm_toc_estimate_keys(&pcxt->estimator, 1);
3322 
3323  /* Finally, estimate PARALLEL_VACUUM_KEY_QUERY_TEXT space */
3324  if (debug_query_string)
3325  {
3326  querylen = strlen(debug_query_string);
3327  shm_toc_estimate_chunk(&pcxt->estimator, querylen + 1);
3328  shm_toc_estimate_keys(&pcxt->estimator, 1);
3329  }
3330  else
3331  querylen = 0; /* keep compiler quiet */
3332 
3333  InitializeParallelDSM(pcxt);
3334 
3335  /* Prepare shared information */
3336  shared = (LVShared *) shm_toc_allocate(pcxt->toc, est_shared);
3337  MemSet(shared, 0, est_shared);
3338  shared->relid = relid;
3339  shared->elevel = elevel;
3340  shared->maintenance_work_mem_worker =
3341  (nindexes_mwm > 0) ?
3342  maintenance_work_mem / Min(parallel_workers, nindexes_mwm) :
3344 
3345  pg_atomic_init_u32(&(shared->cost_balance), 0);
3346  pg_atomic_init_u32(&(shared->active_nworkers), 0);
3347  pg_atomic_init_u32(&(shared->idx), 0);
3348  shared->offset = MAXALIGN(add_size(SizeOfLVShared, BITMAPLEN(nindexes)));
3349  prepare_index_statistics(shared, can_parallel_vacuum, nindexes);
3350 
3352  lps->lvshared = shared;
3353 
3354  /* Prepare the dead tuple space */
3355  dead_tuples = (LVDeadTuples *) shm_toc_allocate(pcxt->toc, est_deadtuples);
3356  dead_tuples->max_tuples = maxtuples;
3357  dead_tuples->num_tuples = 0;
3358  MemSet(dead_tuples->itemptrs, 0, sizeof(ItemPointerData) * maxtuples);
3359  shm_toc_insert(pcxt->toc, PARALLEL_VACUUM_KEY_DEAD_TUPLES, dead_tuples);
3360  vacrelstats->dead_tuples = dead_tuples;
3361 
3362  /*
3363  * Allocate space for each worker's BufferUsage and WalUsage; no need to
3364  * initialize
3365  */
3366  buffer_usage = shm_toc_allocate(pcxt->toc,
3367  mul_size(sizeof(BufferUsage), pcxt->nworkers));
3368  shm_toc_insert(pcxt->toc, PARALLEL_VACUUM_KEY_BUFFER_USAGE, buffer_usage);
3369  lps->buffer_usage = buffer_usage;
3370  wal_usage = shm_toc_allocate(pcxt->toc,
3371  mul_size(sizeof(WalUsage), pcxt->nworkers));
3373  lps->wal_usage = wal_usage;
3374 
3375  /* Store query string for workers */
3376  if (debug_query_string)
3377  {
3378  char *sharedquery;
3379 
3380  sharedquery = (char *) shm_toc_allocate(pcxt->toc, querylen + 1);
3381  memcpy(sharedquery, debug_query_string, querylen + 1);
3382  sharedquery[querylen] = '\0';
3383  shm_toc_insert(pcxt->toc,
3384  PARALLEL_VACUUM_KEY_QUERY_TEXT, sharedquery);
3385  }
3386 
3387  pfree(can_parallel_vacuum);
3388  return lps;
3389 }
uint8 amparallelvacuumoptions
Definition: amapi.h:247
struct IndexAmRoutine * rd_indam
Definition: rel.h:189
WalUsage * wal_usage
Definition: vacuumlazy.c:281
static int compute_parallel_vacuum_workers(Relation *Irel, int nindexes, int nrequested, bool *can_parallel_vacuum)
Definition: vacuumlazy.c:3100
ItemPointerData itemptrs[FLEXIBLE_ARRAY_MEMBER]
Definition: vacuumlazy.c:172
ParallelContext * CreateParallelContext(const char *library_name, const char *function_name, int nworkers)
Definition: parallel.c:164
LVDeadTuples * dead_tuples
Definition: vacuumlazy.c:312
#define PARALLEL_VACUUM_KEY_DEAD_TUPLES
Definition: vacuumlazy.c:139
Oid relid
Definition: vacuumlazy.c:193
#define SizeOfDeadTuples(cnt)
Definition: vacuumlazy.c:177
BufferUsage * buffer_usage
Definition: vacuumlazy.c:278
shm_toc_estimator estimator
Definition: parallel.h:42
#define Min(x, y)
Definition: c.h:982
unsigned char uint8
Definition: c.h:427
#define VACUUM_OPTION_MAX_VALID_VALUE
Definition: vacuum.h:63
#define MemSet(start, val, len)
Definition: c.h:1004
static long compute_max_dead_tuples(BlockNumber relblocks, bool hasindex)
Definition: vacuumlazy.c:2847
#define BITMAPLEN(NATTS)
Definition: htup_details.h:547
int nindexes_parallel_bulkdel
Definition: vacuumlazy.c:287
int maintenance_work_mem_worker
Definition: vacuumlazy.c:225
#define shm_toc_estimate_chunk(e, sz)
Definition: shm_toc.h:51
int nindexes_parallel_condcleanup
Definition: vacuumlazy.c:289
#define PARALLEL_VACUUM_KEY_QUERY_TEXT
Definition: vacuumlazy.c:140
ParallelContext * pcxt
Definition: vacuumlazy.c:272
#define SizeOfLVShared
Definition: vacuumlazy.c:253
pg_atomic_uint32 cost_balance
Definition: vacuumlazy.c:232
void pfree(void *pointer)
Definition: mcxt.c:1057
int elevel
Definition: vacuumlazy.c:194
pg_atomic_uint32 idx
Definition: vacuumlazy.c:246
const char * debug_query_string
Definition: postgres.c:88
static void prepare_index_statistics(LVShared *lvshared, bool *can_parallel_vacuum, int nindexes)
Definition: vacuumlazy.c:3161
void InitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:202
static int elevel
Definition: vacuumlazy.c:333
int nindexes_parallel_cleanup
Definition: vacuumlazy.c:288
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
void * palloc0(Size size)
Definition: mcxt.c:981
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
#define PARALLEL_VACUUM_KEY_SHARED
Definition: vacuumlazy.c:138
pg_atomic_uint32 active_nworkers
Definition: vacuumlazy.c:239
int maintenance_work_mem
Definition: globals.c:123
#define PARALLEL_VACUUM_KEY_BUFFER_USAGE
Definition: vacuumlazy.c:141
#define Assert(condition)
Definition: c.h:800
#define VACUUM_OPTION_PARALLEL_COND_CLEANUP
Definition: vacuum.h:52
#define PARALLEL_VACUUM_KEY_WAL_USAGE
Definition: vacuumlazy.c:142
size_t Size
Definition: c.h:528
#define shm_toc_estimate_keys(e, cnt)
Definition: shm_toc.h:53
#define MAXALIGN(LEN)
Definition: c.h:753
void EnterParallelMode(void)
Definition: xact.c:979
LVShared * lvshared
Definition: vacuumlazy.c:275
#define VACUUM_OPTION_PARALLEL_BULKDEL
Definition: vacuum.h:45
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition: shm_toc.c:88
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition: shm_toc.c:171
int i
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:223
uint32 offset
Definition: vacuumlazy.c:247
#define VACUUM_OPTION_PARALLEL_CLEANUP
Definition: vacuum.h:60
shm_toc * toc
Definition: parallel.h:45

◆ compute_max_dead_tuples()

static long compute_max_dead_tuples ( BlockNumber  relblocks,
bool  hasindex 
)
static

Definition at line 2847 of file vacuumlazy.c.

References autovacuum_work_mem, IsAutoVacuumWorkerProcess(), LAZY_ALLOC_TUPLES, maintenance_work_mem, Max, MaxAllocSize, MAXDEADTUPLES, MaxHeapTuplesPerPage, and Min.

Referenced by begin_parallel_vacuum(), and lazy_space_alloc().

2848 {
2849  long maxtuples;
2850  int vac_work_mem = IsAutoVacuumWorkerProcess() &&
2851  autovacuum_work_mem != -1 ?
2853 
2854  if (useindex)
2855  {
2856  maxtuples = MAXDEADTUPLES(vac_work_mem * 1024L);
2857  maxtuples = Min(maxtuples, INT_MAX);
2858  maxtuples = Min(maxtuples, MAXDEADTUPLES(MaxAllocSize));
2859 
2860  /* curious coding here to ensure the multiplication can't overflow */
2861  if ((BlockNumber) (maxtuples / LAZY_ALLOC_TUPLES) > relblocks)
2862  maxtuples = relblocks * LAZY_ALLOC_TUPLES;
2863 
2864  /* stay sane if small maintenance_work_mem */
2865  maxtuples = Max(maxtuples, MaxHeapTuplesPerPage);
2866  }
2867  else
2868  maxtuples = MaxHeapTuplesPerPage;
2869 
2870  return maxtuples;
2871 }
int autovacuum_work_mem
Definition: autovacuum.c:116
#define Min(x, y)
Definition: c.h:982
#define MaxHeapTuplesPerPage
Definition: htup_details.h:574
uint32 BlockNumber
Definition: block.h:31
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3325
#define MaxAllocSize
Definition: memutils.h:40
int maintenance_work_mem
Definition: globals.c:123
#define Max(x, y)
Definition: c.h:976
#define MAXDEADTUPLES(max_size)
Definition: vacuumlazy.c:180
#define LAZY_ALLOC_TUPLES
Definition: vacuumlazy.c:119

◆ compute_parallel_vacuum_workers()

static int compute_parallel_vacuum_workers ( Relation Irel,
int  nindexes,
int  nrequested,
bool can_parallel_vacuum 
)
static

Definition at line 3100 of file vacuumlazy.c.

References IndexAmRoutine::amparallelvacuumoptions, i, IsUnderPostmaster, Max, max_parallel_maintenance_workers, Min, min_parallel_index_scan_size, RelationData::rd_indam, RelationGetNumberOfBlocks, VACUUM_OPTION_NO_PARALLEL, VACUUM_OPTION_PARALLEL_BULKDEL, VACUUM_OPTION_PARALLEL_CLEANUP, and VACUUM_OPTION_PARALLEL_COND_CLEANUP.

Referenced by begin_parallel_vacuum().

3102 {
3103  int nindexes_parallel = 0;
3104  int nindexes_parallel_bulkdel = 0;
3105  int nindexes_parallel_cleanup = 0;
3106  int parallel_workers;
3107  int i;
3108 
3109  /*
3110  * We don't allow performing parallel operation in standalone backend or
3111  * when parallelism is disabled.
3112  */
3114  return 0;
3115 
3116  /*
3117  * Compute the number of indexes that can participate in parallel vacuum.
3118  */
3119  for (i = 0; i < nindexes; i++)
3120  {
3121  uint8 vacoptions = Irel[i]->rd_indam->amparallelvacuumoptions;
3122 
3123  if (vacoptions == VACUUM_OPTION_NO_PARALLEL ||
3125  continue;
3126 
3127  can_parallel_vacuum[i] = true;
3128 
3129  if ((vacoptions & VACUUM_OPTION_PARALLEL_BULKDEL) != 0)
3130  nindexes_parallel_bulkdel++;
3131  if (((vacoptions & VACUUM_OPTION_PARALLEL_CLEANUP) != 0) ||
3132  ((vacoptions & VACUUM_OPTION_PARALLEL_COND_CLEANUP) != 0))
3133  nindexes_parallel_cleanup++;
3134  }
3135 
3136  nindexes_parallel = Max(nindexes_parallel_bulkdel,
3137  nindexes_parallel_cleanup);
3138 
3139  /* The leader process takes one index */
3140  nindexes_parallel--;
3141 
3142  /* No index supports parallel vacuum */
3143  if (nindexes_parallel <= 0)
3144  return 0;
3145 
3146  /* Compute the parallel degree */
3147  parallel_workers = (nrequested > 0) ?
3148  Min(nrequested, nindexes_parallel) : nindexes_parallel;
3149 
3150  /* Cap by max_parallel_maintenance_workers */
3151  parallel_workers = Min(parallel_workers, max_parallel_maintenance_workers);
3152 
3153  return parallel_workers;
3154 }
uint8 amparallelvacuumoptions
Definition: amapi.h:247
struct IndexAmRoutine * rd_indam
Definition: rel.h:189
#define Min(x, y)
Definition: c.h:982
unsigned char uint8
Definition: c.h:427
bool IsUnderPostmaster
Definition: globals.c:109
int min_parallel_index_scan_size
Definition: allpaths.c:65
#define VACUUM_OPTION_NO_PARALLEL
Definition: vacuum.h:39
int max_parallel_maintenance_workers
Definition: globals.c:124
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define Max(x, y)
Definition: c.h:976
#define VACUUM_OPTION_PARALLEL_COND_CLEANUP
Definition: vacuum.h:52
#define VACUUM_OPTION_PARALLEL_BULKDEL
Definition: vacuum.h:45
int i
#define VACUUM_OPTION_PARALLEL_CLEANUP
Definition: vacuum.h:60

◆ count_nondeletable_pages()

static BlockNumber count_nondeletable_pages ( Relation  onerel,
LVRelStats vacrelstats 
)
static

Definition at line 2708 of file vacuumlazy.c.

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

Referenced by lazy_truncate_heap().

2709 {
2710  BlockNumber blkno;
2711  BlockNumber prefetchedUntil;
2712  instr_time starttime;
2713 
2714  /* Initialize the starttime if we check for conflicting lock requests */
2715  INSTR_TIME_SET_CURRENT(starttime);
2716 
2717  /*
2718  * Start checking blocks at what we believe relation end to be and move
2719  * backwards. (Strange coding of loop control is needed because blkno is
2720  * unsigned.) To make the scan faster, we prefetch a few blocks at a time
2721  * in forward direction, so that OS-level readahead can kick in.
2722  */
2723  blkno = vacrelstats->rel_pages;
2725  "prefetch size must be power of 2");
2726  prefetchedUntil = InvalidBlockNumber;
2727  while (blkno > vacrelstats->nonempty_pages)
2728  {
2729  Buffer buf;
2730  Page page;
2731  OffsetNumber offnum,
2732  maxoff;
2733  bool hastup;
2734 
2735  /*
2736  * Check if another process requests a lock on our relation. We are
2737  * holding an AccessExclusiveLock here, so they will be waiting. We
2738  * only do this once per VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and we
2739  * only check if that interval has elapsed once every 32 blocks to
2740  * keep the number of system calls and actual shared lock table
2741  * lookups to a minimum.
2742  */
2743  if ((blkno % 32) == 0)
2744  {
2745  instr_time currenttime;
2746  instr_time elapsed;
2747 
2748  INSTR_TIME_SET_CURRENT(currenttime);
2749  elapsed = currenttime;
2750  INSTR_TIME_SUBTRACT(elapsed, starttime);
2751  if ((INSTR_TIME_GET_MICROSEC(elapsed) / 1000)
2753  {
2755  {
2756  ereport(elevel,
2757  (errmsg("\"%s\": suspending truncate due to conflicting lock request",
2758  vacrelstats->relname)));
2759 
2760  vacrelstats->lock_waiter_detected = true;
2761  return blkno;
2762  }
2763  starttime = currenttime;
2764  }
2765  }
2766 
2767  /*
2768  * We don't insert a vacuum delay point here, because we have an
2769  * exclusive lock on the table which we want to hold for as short a
2770  * time as possible. We still need to check for interrupts however.
2771  */
2773 
2774  blkno--;
2775 
2776  /* If we haven't prefetched this lot yet, do so now. */
2777  if (prefetchedUntil > blkno)
2778  {
2779  BlockNumber prefetchStart;
2780  BlockNumber pblkno;
2781 
2782  prefetchStart = blkno & ~(PREFETCH_SIZE - 1);
2783  for (pblkno = prefetchStart; pblkno <= blkno; pblkno++)
2784  {
2785  PrefetchBuffer(onerel, MAIN_FORKNUM, pblkno);
2787  }
2788  prefetchedUntil = prefetchStart;
2789  }
2790 
2791  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, blkno,
2793 
2794  /* In this phase we only need shared access to the buffer */
2796 
2797  page = BufferGetPage(buf);
2798 
2799  if (PageIsNew(page) || PageIsEmpty(page))
2800  {
2801  UnlockReleaseBuffer(buf);
2802  continue;
2803  }
2804 
2805  hastup = false;
2806  maxoff = PageGetMaxOffsetNumber(page);
2807  for (offnum = FirstOffsetNumber;
2808  offnum <= maxoff;
2809  offnum = OffsetNumberNext(offnum))
2810  {
2811  ItemId itemid;
2812 
2813  itemid = PageGetItemId(page, offnum);
2814 
2815  /*
2816  * Note: any non-unused item should be taken as a reason to keep
2817  * this page. We formerly thought that DEAD tuples could be
2818  * thrown away, but that's not so, because we'd not have cleaned
2819  * out their index entries.
2820  */
2821  if (ItemIdIsUsed(itemid))
2822  {
2823  hastup = true;
2824  break; /* can stop scanning */
2825  }
2826  } /* scan along page */
2827 
2828  UnlockReleaseBuffer(buf);
2829 
2830  /* Done scanning if we found a tuple here */
2831  if (hastup)
2832  return blkno + 1;
2833  }
2834 
2835  /*
2836  * If we fall out of the loop, all the previously-thought-to-be-empty
2837  * pages still are; we need not bother to look at the last known-nonempty
2838  * page.
2839  */
2840  return vacrelstats->nonempty_pages;
2841 }
#define PageIsEmpty(page)
Definition: bufpage.h:222
BlockNumber rel_pages
Definition: vacuumlazy.c:300
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:654
struct timeval instr_time
Definition: instr_time.h:150
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
uint32 BlockNumber
Definition: block.h:31
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
uint16 OffsetNumber
Definition: off.h:24
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:914
#define PREFETCH_SIZE
Definition: vacuumlazy.c:131
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3536
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
static char * buf
Definition: pg_test_fsync.c:68
#define FirstOffsetNumber
Definition: off.h:27
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
static int elevel
Definition: vacuumlazy.c:333
#define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL
Definition: vacuumlazy.c:101
char * relname
Definition: vacuumlazy.c:295
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3752
#define ereport(elevel,...)
Definition: elog.h:155
bool LockHasWaitersRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:345
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:339
#define INSTR_TIME_GET_MICROSEC(t)
Definition: instr_time.h:205
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define InvalidBlockNumber
Definition: block.h:33
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
#define AccessExclusiveLock
Definition: lockdefs.h:45
BlockNumber nonempty_pages
Definition: vacuumlazy.c:311
#define PageIsNew(page)
Definition: bufpage.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:902
PrefetchBufferResult PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition: bufmgr.c:575
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:78
bool lock_waiter_detected
Definition: vacuumlazy.c:315

◆ end_parallel_vacuum()

static void end_parallel_vacuum ( IndexBulkDeleteResult **  stats,
LVParallelState lps,
int  nindexes 
)
static

Definition at line 3401 of file vacuumlazy.c.

References Assert, DestroyParallelContext(), ExitParallelMode(), get_indstats(), i, IsParallelWorker, LVParallelState::lvshared, palloc0(), LVParallelState::pcxt, pfree(), LVSharedIndStats::stats, and LVSharedIndStats::updated.

Referenced by lazy_scan_heap().

3403 {
3404  int i;
3405 
3407 
3408  /* Copy the updated statistics */
3409  for (i = 0; i < nindexes; i++)
3410  {
3411  LVSharedIndStats *indstats = get_indstats(lps->lvshared, i);
3412 
3413  /*
3414  * Skip unused slot. The statistics of this index are already stored
3415  * in local memory.
3416  */
3417  if (indstats == NULL)
3418  continue;
3419 
3420  if (indstats->updated)
3421  {
3422  stats[i] = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult));
3423  memcpy(stats[i], &(indstats->stats), sizeof(IndexBulkDeleteResult));
3424  }
3425  else
3426  stats[i] = NULL;
3427  }
3428 
3430  ExitParallelMode();
3431 
3432  /* Deactivate parallel vacuum */
3433  pfree(lps);
3434  lps = NULL;
3435 }
static LVSharedIndStats * get_indstats(LVShared *lvshared, int n)
Definition: vacuumlazy.c:3439
ParallelContext * pcxt
Definition: vacuumlazy.c:272
void DestroyParallelContext(ParallelContext *pcxt)
Definition: parallel.c:904
void pfree(void *pointer)
Definition: mcxt.c:1057
void ExitParallelMode(void)
Definition: xact.c:992
IndexBulkDeleteResult stats
Definition: vacuumlazy.c:266
#define IsParallelWorker()
Definition: parallel.h:61
void * palloc0(Size size)
Definition: mcxt.c:981
#define Assert(condition)
Definition: c.h:800
LVShared * lvshared
Definition: vacuumlazy.c:275
int i

◆ get_indstats()

static LVSharedIndStats * get_indstats ( LVShared lvshared,
int  n 
)
static

Definition at line 3439 of file vacuumlazy.c.

References GetSharedIndStats, i, and IndStatsIsNull.

Referenced by end_parallel_vacuum(), parallel_vacuum_index(), and vacuum_indexes_leader().

3440 {
3441  int i;
3442  char *p;
3443 
3444  if (IndStatsIsNull(lvshared, n))
3445  return NULL;
3446 
3447  p = (char *) GetSharedIndStats(lvshared);
3448  for (i = 0; i < n; i++)
3449  {
3450  if (IndStatsIsNull(lvshared, i))
3451  continue;
3452 
3453  p += sizeof(LVSharedIndStats);
3454  }
3455 
3456  return (LVSharedIndStats *) p;
3457 }
#define GetSharedIndStats(s)
Definition: vacuumlazy.c:254
#define IndStatsIsNull(s, i)
Definition: vacuumlazy.c:256
struct LVSharedIndStats LVSharedIndStats
int i

◆ heap_page_is_all_visible()

static bool heap_page_is_all_visible ( Relation  rel,
Buffer  buf,
LVRelStats vacrelstats,
TransactionId visibility_cutoff_xid,
bool all_frozen 
)
static

Definition at line 2972 of file vacuumlazy.c.

References Assert, BufferGetBlockNumber(), BufferGetPage, 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, LVRelStats::offnum, OffsetNumberNext, OldestXmin, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, RelationGetRelid, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdFollows(), and TransactionIdPrecedes().

Referenced by lazy_vacuum_page().

2976 {
2977  Page page = BufferGetPage(buf);
2979  OffsetNumber offnum,
2980  maxoff;
2981  bool all_visible = true;
2982 
2983  *visibility_cutoff_xid = InvalidTransactionId;
2984  *all_frozen = true;
2985 
2986  /*
2987  * This is a stripped down version of the line pointer scan in
2988  * lazy_scan_heap(). So if you change anything here, also check that code.
2989  */
2990  maxoff = PageGetMaxOffsetNumber(page);
2991  for (offnum = FirstOffsetNumber;
2992  offnum <= maxoff && all_visible;
2993  offnum = OffsetNumberNext(offnum))
2994  {
2995  ItemId itemid;
2996  HeapTupleData tuple;
2997 
2998  /*
2999  * Set the offset number so that we can display it along with any
3000  * error that occurred while processing this tuple.
3001  */
3002  vacrelstats->offnum = offnum;
3003  itemid = PageGetItemId(page, offnum);
3004 
3005  /* Unused or redirect line pointers are of no interest */
3006  if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid))
3007  continue;
3008 
3009  ItemPointerSet(&(tuple.t_self), blockno, offnum);
3010 
3011  /*
3012  * Dead line pointers can have index pointers pointing to them. So
3013  * they can't be treated as visible
3014  */
3015  if (ItemIdIsDead(itemid))
3016  {
3017  all_visible = false;
3018  *all_frozen = false;
3019  break;
3020  }
3021 
3022  Assert(ItemIdIsNormal(itemid));
3023 
3024  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
3025  tuple.t_len = ItemIdGetLength(itemid);
3026  tuple.t_tableOid = RelationGetRelid(rel);
3027 
3028  switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf))
3029  {
3030  case HEAPTUPLE_LIVE:
3031  {
3032  TransactionId xmin;
3033 
3034  /* Check comments in lazy_scan_heap. */
3036  {
3037  all_visible = false;
3038  *all_frozen = false;
3039  break;
3040  }
3041 
3042  /*
3043  * The inserter definitely committed. But is it old enough
3044  * that everyone sees it as committed?
3045  */
3046  xmin = HeapTupleHeaderGetXmin(tuple.t_data);
3047  if (!TransactionIdPrecedes(xmin, OldestXmin))
3048  {
3049  all_visible = false;
3050  *all_frozen = false;
3051  break;
3052  }
3053 
3054  /* Track newest xmin on page. */
3055  if (TransactionIdFollows(xmin, *visibility_cutoff_xid))
3056  *visibility_cutoff_xid = xmin;
3057 
3058  /* Check whether this tuple is already frozen or not */
3059  if (all_visible && *all_frozen &&
3061  *all_frozen = false;
3062  }
3063  break;
3064 
3065  case HEAPTUPLE_DEAD:
3069  {
3070  all_visible = false;
3071  *all_frozen = false;
3072  break;
3073  }
3074  default:
3075  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
3076  break;
3077  }
3078  } /* scan along page */
3079 
3080  /* Clear the offset information once we have processed the given page. */
3081  vacrelstats->offnum = InvalidOffsetNumber;
3082 
3083  return all_visible;
3084 }
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:575
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
uint32 BlockNumber
Definition: block.h:31
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:68
bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple)
Definition: heapam.c:6771
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
#define HeapTupleHeaderXminCommitted(tup)
Definition: htup_details.h:324
uint32 t_len
Definition: htup.h:64
static char * buf
Definition: pg_test_fsync.c:68
#define FirstOffsetNumber
Definition: off.h:27
#define InvalidTransactionId
Definition: transam.h:31
static TransactionId OldestXmin
Definition: vacuumlazy.c:335
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
#define InvalidOffsetNumber
Definition: off.h:26
OffsetNumber offnum
Definition: vacuumlazy.c:320
#define Assert(condition)
Definition: c.h:800
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2663
#define elog(elevel,...)
Definition: elog.h:228
#define RelationGetRelid(relation)
Definition: rel.h:457
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127

◆ heap_vacuum_rel()

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

Definition at line 419 of file vacuumlazy.c.

References _, appendStringInfo(), ErrorContextCallback::arg, Assert, buf, ErrorContextCallback::callback, StringInfoData::data, DEBUG2, elevel, ereport, errmsg_internal(), error_context_stack, VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, FreezeLimit, LVRelStats::frozenskipped_pages, get_database_name(), get_namespace_name(), GetCurrentTimestamp(), VacuumParams::index_cleanup, LVRelStats::indname, INFO, initStringInfo(), InvalidMultiXactId, InvalidOffsetNumber, InvalidTransactionId, VacuumParams::is_wraparound, IsAutoVacuumWorkerProcess(), lazy_scan_heap(), lazy_truncate_heap(), LVRelStats::lock_waiter_detected, LOG, VacuumParams::log_min_duration, Max, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, MultiXactCutoff, MultiXactIdIsValid, MultiXactIdPrecedesOrEquals(), MyDatabaseId, LVRelStats::new_dead_tuples, LVRelStats::new_live_tuples, LVRelStats::new_rel_tuples, NoLock, LVRelStats::nonempty_pages, LVRelStats::num_index_scans, LVRelStats::old_live_tuples, LVRelStats::old_rel_pages, OldestXmin, VacuumParams::options, LVRelStats::pages_removed, palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), pgstat_report_vacuum(), pgWalUsage, LVRelStats::phase, LVRelStats::pinskipped_pages, ErrorContextCallback::previous, PROGRESS_COMMAND_VACUUM, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_FINAL_CLEANUP, pstrdup(), RelationData::rd_rel, LVRelStats::rel_pages, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, LVRelStats::relname, LVRelStats::relnamespace, RowExclusiveLock, LVRelStats::scanned_pages, should_attempt_truncation(), TimestampDifference(), TimestampDifferenceExceeds(), TransactionIdIsNormal, TransactionIdPrecedesOrEquals(), VacuumParams::truncate, LVRelStats::tuples_deleted, update_vacuum_error_info(), LVRelStats::useindex, vac_close_indexes(), vac_open_indexes(), vac_update_relstats(), VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_TERNARY_DEFAULT, VACOPT_TERNARY_ENABLED, VACOPT_VERBOSE, VACUUM_ERRCB_PHASE_TRUNCATE, VACUUM_ERRCB_PHASE_UNKNOWN, vacuum_error_callback(), vacuum_set_xid_limits(), VacuumPageDirty, VacuumPageHit, VacuumPageMiss, visibilitymap_count(), WalUsage::wal_bytes, WalUsage::wal_fpi, WalUsage::wal_records, and WalUsageAccumDiff().

Referenced by SampleHeapTupleVisible().

421 {
422  LVRelStats *vacrelstats;
423  Relation *Irel;
424  int nindexes;
425  PGRUsage ru0;
426  TimestampTz starttime = 0;
427  WalUsage walusage_start = pgWalUsage;
428  WalUsage walusage = {0, 0, 0};
429  long secs;
430  int usecs;
431  double read_rate,
432  write_rate;
433  bool aggressive; /* should we scan all unfrozen pages? */
434  bool scanned_all_unfrozen; /* actually scanned all such pages? */
435  TransactionId xidFullScanLimit;
436  MultiXactId mxactFullScanLimit;
437  BlockNumber new_rel_pages;
438  BlockNumber new_rel_allvisible;
439  double new_live_tuples;
440  TransactionId new_frozen_xid;
441  MultiXactId new_min_multi;
442  ErrorContextCallback errcallback;
443 
444  Assert(params != NULL);
447 
448  /* not every AM requires these to be valid, but heap does */
449  Assert(TransactionIdIsNormal(onerel->rd_rel->relfrozenxid));
450  Assert(MultiXactIdIsValid(onerel->rd_rel->relminmxid));
451 
452  /* measure elapsed time iff autovacuum logging requires it */
453  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
454  {
455  pg_rusage_init(&ru0);
456  starttime = GetCurrentTimestamp();
457  }
458 
459  if (params->options & VACOPT_VERBOSE)
460  elevel = INFO;
461  else
462  elevel = DEBUG2;
463 
465  RelationGetRelid(onerel));
466 
467  vac_strategy = bstrategy;
468 
469  vacuum_set_xid_limits(onerel,
470  params->freeze_min_age,
471  params->freeze_table_age,
472  params->multixact_freeze_min_age,
474  &OldestXmin, &FreezeLimit, &xidFullScanLimit,
475  &MultiXactCutoff, &mxactFullScanLimit);
476 
477  /*
478  * We request an aggressive scan if the table's frozen Xid is now older
479  * than or equal to the requested Xid full-table scan limit; or if the
480  * table's minimum MultiXactId is older than or equal to the requested
481  * mxid full-table scan limit; or if DISABLE_PAGE_SKIPPING was specified.
482  */
483  aggressive = TransactionIdPrecedesOrEquals(onerel->rd_rel->relfrozenxid,
484  xidFullScanLimit);
485  aggressive |= MultiXactIdPrecedesOrEquals(onerel->rd_rel->relminmxid,
486  mxactFullScanLimit);
488  aggressive = true;
489 
490  vacrelstats = (LVRelStats *) palloc0(sizeof(LVRelStats));
491 
492  vacrelstats->relnamespace = get_namespace_name(RelationGetNamespace(onerel));
493  vacrelstats->relname = pstrdup(RelationGetRelationName(onerel));
494  vacrelstats->indname = NULL;
495  vacrelstats->phase = VACUUM_ERRCB_PHASE_UNKNOWN;
496  vacrelstats->old_rel_pages = onerel->rd_rel->relpages;
497  vacrelstats->old_live_tuples = onerel->rd_rel->reltuples;
498  vacrelstats->num_index_scans = 0;
499  vacrelstats->pages_removed = 0;
500  vacrelstats->lock_waiter_detected = false;
501 
502  /* Open all indexes of the relation */
503  vac_open_indexes(onerel, RowExclusiveLock, &nindexes, &Irel);
504  vacrelstats->useindex = (nindexes > 0 &&
506 
507  /*
508  * Setup error traceback support for ereport(). The idea is to set up an
509  * error context callback to display additional information on any error
510  * during a vacuum. During different phases of vacuum (heap scan, heap
511  * vacuum, index vacuum, index clean up, heap truncate), we update the
512  * error context callback to display appropriate information.
513  *
514  * Note that the index vacuum and heap vacuum phases may be called
515  * multiple times in the middle of the heap scan phase. So the old phase
516  * information is restored at the end of those phases.
517  */
518  errcallback.callback = vacuum_error_callback;
519  errcallback.arg = vacrelstats;
520  errcallback.previous = error_context_stack;
521  error_context_stack = &errcallback;
522 
523  /* Do the vacuuming */
524  lazy_scan_heap(onerel, params, vacrelstats, Irel, nindexes, aggressive);
525 
526  /* Done with indexes */
527  vac_close_indexes(nindexes, Irel, NoLock);
528 
529  /*
530  * Compute whether we actually scanned the all unfrozen pages. If we did,
531  * we can adjust relfrozenxid and relminmxid.
532  *
533  * NB: We need to check this before truncating the relation, because that
534  * will change ->rel_pages.
535  */
536  if ((vacrelstats->scanned_pages + vacrelstats->frozenskipped_pages)
537  < vacrelstats->rel_pages)
538  {
539  Assert(!aggressive);
540  scanned_all_unfrozen = false;
541  }
542  else
543  scanned_all_unfrozen = true;
544 
545  /*
546  * Optionally truncate the relation.
547  */
548  if (should_attempt_truncation(params, vacrelstats))
549  {
550  /*
551  * Update error traceback information. This is the last phase during
552  * which we add context information to errors, so we don't need to
553  * revert to the previous phase.
554  */
556  vacrelstats->nonempty_pages,
558  lazy_truncate_heap(onerel, vacrelstats);
559  }
560 
561  /* Pop the error context stack */
562  error_context_stack = errcallback.previous;
563 
564  /* Report that we are now doing final cleanup */
567 
568  /*
569  * Update statistics in pg_class.
570  *
571  * In principle new_live_tuples could be -1 indicating that we (still)
572  * don't know the tuple count. In practice that probably can't happen,
573  * since we'd surely have scanned some pages if the table is new and
574  * nonempty.
575  *
576  * For safety, clamp relallvisible to be not more than what we're setting
577  * relpages to.
578  *
579  * Also, don't change relfrozenxid/relminmxid if we skipped any pages,
580  * since then we don't know for certain that all tuples have a newer xmin.
581  */
582  new_rel_pages = vacrelstats->rel_pages;
583  new_live_tuples = vacrelstats->new_live_tuples;
584 
585  visibilitymap_count(onerel, &new_rel_allvisible, NULL);
586  if (new_rel_allvisible > new_rel_pages)
587  new_rel_allvisible = new_rel_pages;
588 
589  new_frozen_xid = scanned_all_unfrozen ? FreezeLimit : InvalidTransactionId;
590  new_min_multi = scanned_all_unfrozen ? MultiXactCutoff : InvalidMultiXactId;
591 
592  vac_update_relstats(onerel,
593  new_rel_pages,
594  new_live_tuples,
595  new_rel_allvisible,
596  nindexes > 0,
597  new_frozen_xid,
598  new_min_multi,
599  false);
600 
601  /* report results to the stats collector, too */
603  onerel->rd_rel->relisshared,
604  Max(new_live_tuples, 0),
605  vacrelstats->new_dead_tuples);
607 
608  /* and log the action if appropriate */
609  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
610  {
611  TimestampTz endtime = GetCurrentTimestamp();
612 
613  if (params->log_min_duration == 0 ||
614  TimestampDifferenceExceeds(starttime, endtime,
615  params->log_min_duration))
616  {
618  char *msgfmt;
619 
620  TimestampDifference(starttime, endtime, &secs, &usecs);
621 
622  memset(&walusage, 0, sizeof(WalUsage));
623  WalUsageAccumDiff(&walusage, &pgWalUsage, &walusage_start);
624 
625  read_rate = 0;
626  write_rate = 0;
627  if ((secs > 0) || (usecs > 0))
628  {
629  read_rate = (double) BLCKSZ * VacuumPageMiss / (1024 * 1024) /
630  (secs + usecs / 1000000.0);
631  write_rate = (double) BLCKSZ * VacuumPageDirty / (1024 * 1024) /
632  (secs + usecs / 1000000.0);
633  }
634 
635  /*
636  * This is pretty messy, but we split it up so that we can skip
637  * emitting individual parts of the message when not applicable.
638  */
639  initStringInfo(&buf);
640  if (params->is_wraparound)
641  {
642  if (aggressive)
643  msgfmt = _("automatic aggressive vacuum to prevent wraparound of table \"%s.%s.%s\": index scans: %d\n");
644  else
645  msgfmt = _("automatic vacuum to prevent wraparound of table \"%s.%s.%s\": index scans: %d\n");
646  }
647  else
648  {
649  if (aggressive)
650  msgfmt = _("automatic aggressive vacuum of table \"%s.%s.%s\": index scans: %d\n");
651  else
652  msgfmt = _("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n");
653  }
654  appendStringInfo(&buf, msgfmt,
656  vacrelstats->relnamespace,
657  vacrelstats->relname,
658  vacrelstats->num_index_scans);
659  appendStringInfo(&buf, _("pages: %u removed, %u remain, %u skipped due to pins, %u skipped frozen\n"),
660  vacrelstats->pages_removed,
661  vacrelstats->rel_pages,
662  vacrelstats->pinskipped_pages,
663  vacrelstats->frozenskipped_pages);
664  appendStringInfo(&buf,
665  _("tuples: %.0f removed, %.0f remain, %.0f are dead but not yet removable, oldest xmin: %u\n"),
666  vacrelstats->tuples_deleted,
667  vacrelstats->new_rel_tuples,
668  vacrelstats->new_dead_tuples,
669  OldestXmin);
670  appendStringInfo(&buf,
671  _("buffer usage: %lld hits, %lld misses, %lld dirtied\n"),
672  (long long) VacuumPageHit,
673  (long long) VacuumPageMiss,
674  (long long) VacuumPageDirty);
675  appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
676  read_rate, write_rate);
677  appendStringInfo(&buf, _("system usage: %s\n"), pg_rusage_show(&ru0));
678  appendStringInfo(&buf,
679  _("WAL usage: %ld records, %ld full page images, %llu bytes"),
680  walusage.wal_records,
681  walusage.wal_fpi,
682  (unsigned long long) walusage.wal_bytes);
683 
684  ereport(LOG,
685  (errmsg_internal("%s", buf.data)));
686  pfree(buf.data);
687  }
688  }
689 }
double new_rel_tuples
Definition: vacuumlazy.c:306
static void vacuum_error_callback(void *arg)
Definition: vacuumlazy.c:3607
int multixact_freeze_table_age
Definition: vacuum.h:215
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:2010
int64 VacuumPageMiss
Definition: globals.c:145
BlockNumber rel_pages
Definition: vacuumlazy.c:300
uint32 TransactionId
Definition: c.h:575
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3356
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
double tuples_deleted
Definition: vacuumlazy.c:310
int64 TimestampTz
Definition: timestamp.h:39
WalUsage pgWalUsage
Definition: instrument.c:22
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bool useindex
Definition: vacuumlazy.c:297
int64 VacuumPageHit
Definition: globals.c:144
void WalUsageAccumDiff(WalUsage *dst, const WalUsage *add, const WalUsage *sub)
Definition: instrument.c:255
char * relnamespace
Definition: vacuumlazy.c:294
BlockNumber scanned_pages
Definition: vacuumlazy.c:301
VacErrPhase phase
Definition: vacuumlazy.c:321
#define INFO
Definition: elog.h:33
void vacuum_set_xid_limits(Relation rel, int freeze_min_age, int freeze_table_age, int multixact_freeze_min_age, int multixact_freeze_table_age, TransactionId *oldestXmin, TransactionId *freezeLimit, TransactionId *xidFullScanLimit, MultiXactId *multiXactCutoff, MultiXactId *mxactFullScanLimit)
Definition: vacuum.c:931
int64 VacuumPageDirty
Definition: globals.c:146
uint32 BlockNumber
Definition: block.h:31
BlockNumber pinskipped_pages
Definition: vacuumlazy.c:302
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:110
void(* callback)(void *arg)
Definition: elog.h:243
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1709
struct ErrorContextCallback * previous
Definition: elog.h:242
int freeze_table_age
Definition: vacuum.h:212
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
ErrorContextCallback * error_context_stack
Definition: elog.c:92
BlockNumber old_rel_pages
Definition: vacuumlazy.c:299
void pfree(void *pointer)
Definition: mcxt.c:1057
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
int freeze_min_age
Definition: vacuum.h:211
bool is_wraparound
Definition: vacuum.h:217
long wal_records
Definition: instrument.h:37
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
#define DEBUG2
Definition: elog.h:24
static TransactionId FreezeLimit
Definition: vacuumlazy.c:336
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3196
#define NoLock
Definition: lockdefs.h:34
static char * buf
Definition: pg_test_fsync.c:68
#define RowExclusiveLock
Definition: lockdefs.h:38
static MultiXactId MultiXactCutoff
Definition: vacuumlazy.c:337
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:491
static TransactionId OldestXmin
Definition: vacuumlazy.c:335
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3325
double new_live_tuples
Definition: vacuumlazy.c:307
VacOptTernaryValue index_cleanup
Definition: vacuum.h:221
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:1967
static int elevel
Definition: vacuumlazy.c:333
void * palloc0(Size size)
Definition: mcxt.c:981
char * indname
Definition: vacuumlazy.c:318
void pgstat_progress_end_command(void)
Definition: pgstat.c:3428
char * relname
Definition: vacuumlazy.c:295
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidMultiXactId
Definition: multixact.h:24
static bool should_attempt_truncation(VacuumParams *params, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2557
#define InvalidOffsetNumber
Definition: off.h:26
VacOptTernaryValue truncate
Definition: vacuum.h:223
#define PROGRESS_VACUUM_PHASE_FINAL_CLEANUP
Definition: progress.h:35
#define ereport(elevel,...)
Definition: elog.h:155
int num_index_scans
Definition: vacuumlazy.c:313
double old_live_tuples
Definition: vacuumlazy.c:305
static void update_vacuum_error_info(LVRelStats *errinfo, LVSavedErrInfo *saved_err_info, int phase, BlockNumber blkno, OffsetNumber offnum)
Definition: vacuumlazy.c:3671
TransactionId MultiXactId
Definition: c.h:585
int errmsg_internal(const char *fmt,...)
Definition: elog.c:989
#define Max(x, y)
Definition: c.h:976
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:339
#define Assert(condition)
Definition: c.h:800
double new_dead_tuples
Definition: vacuumlazy.c:308
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
long wal_fpi
Definition: instrument.h:38
int log_min_duration
Definition: vacuum.h:218
void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples)
Definition: pgstat.c:1534
BlockNumber pages_removed
Definition: vacuumlazy.c:309
BlockNumber nonempty_pages
Definition: vacuumlazy.c:311
static void lazy_scan_heap(Relation onerel, VacuumParams *params, LVRelStats *vacrelstats, Relation *Irel, int nindexes, bool aggressive)
Definition: vacuumlazy.c:753
BlockNumber frozenskipped_pages
Definition: vacuumlazy.c:303
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3160
int options
Definition: vacuum.h:210
uint64 wal_bytes
Definition: instrument.h:39
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1654
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool in_outer_xact)
Definition: vacuum.c:1224
#define _(x)
Definition: elog.c:88
#define RelationGetRelid(relation)
Definition: rel.h:457
int multixact_freeze_min_age
Definition: vacuum.h:213
static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2578
#define RelationGetNamespace(relation)
Definition: rel.h:498
bool lock_waiter_detected
Definition: vacuumlazy.c:315

◆ lazy_check_needs_freeze()

static bool lazy_check_needs_freeze ( Buffer  buf,
bool hastup,
LVRelStats vacrelstats 
)
static

Definition at line 2031 of file vacuumlazy.c.

References BufferGetPage, FirstOffsetNumber, FreezeLimit, heap_tuple_needs_freeze(), InvalidOffsetNumber, ItemIdIsNormal, ItemIdIsUsed, MultiXactCutoff, LVRelStats::offnum, OffsetNumberNext, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageIsEmpty, and PageIsNew.

Referenced by lazy_scan_heap().

2032 {
2033  Page page = BufferGetPage(buf);
2034  OffsetNumber offnum,
2035  maxoff;
2036  HeapTupleHeader tupleheader;
2037 
2038  *hastup = false;
2039 
2040  /*
2041  * New and empty pages, obviously, don't contain tuples. We could make
2042  * sure that the page is registered in the FSM, but it doesn't seem worth
2043  * waiting for a cleanup lock just for that, especially because it's
2044  * likely that the pin holder will do so.
2045  */
2046  if (PageIsNew(page) || PageIsEmpty(page))
2047  return false;
2048 
2049  maxoff = PageGetMaxOffsetNumber(page);
2050  for (offnum = FirstOffsetNumber;
2051  offnum <= maxoff;
2052  offnum = OffsetNumberNext(offnum))
2053  {
2054  ItemId itemid;
2055 
2056  /*
2057  * Set the offset number so that we can display it along with any
2058  * error that occurred while processing this tuple.
2059  */
2060  vacrelstats->offnum = offnum;
2061  itemid = PageGetItemId(page, offnum);
2062 
2063  /* this should match hastup test in count_nondeletable_pages() */
2064  if (ItemIdIsUsed(itemid))
2065  *hastup = true;
2066 
2067  /* dead and redirect items never need freezing */
2068  if (!ItemIdIsNormal(itemid))
2069  continue;
2070 
2071  tupleheader = (HeapTupleHeader) PageGetItem(page, itemid);
2072 
2073  if (heap_tuple_needs_freeze(tupleheader, FreezeLimit,
2074  MultiXactCutoff, buf))
2075  break;
2076  } /* scan along page */
2077 
2078  /* Clear the offset information once we have processed the given page. */
2079  vacrelstats->offnum = InvalidOffsetNumber;
2080 
2081  return (offnum <= maxoff);
2082 }
#define PageIsEmpty(page)
Definition: bufpage.h:222
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
uint16 OffsetNumber
Definition: off.h:24
static TransactionId FreezeLimit
Definition: vacuumlazy.c:336
static char * buf
Definition: pg_test_fsync.c:68
#define FirstOffsetNumber
Definition: off.h:27
static MultiXactId MultiXactCutoff
Definition: vacuumlazy.c:337
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
bool heap_tuple_needs_freeze(HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, Buffer buf)
Definition: heapam.c:6824
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
#define InvalidOffsetNumber
Definition: off.h:26
OffsetNumber offnum
Definition: vacuumlazy.c:320
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
#define PageIsNew(page)
Definition: bufpage.h:229
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78

◆ lazy_cleanup_all_indexes()

static void lazy_cleanup_all_indexes ( Relation Irel,
IndexBulkDeleteResult **  stats,
LVRelStats vacrelstats,
LVParallelState lps,
int  nindexes 
)
static

Definition at line 2376 of file vacuumlazy.c.

References Assert, LVShared::estimated_count, LVShared::first_time, LVShared::for_cleanup, idx(), IsParallelWorker, lazy_cleanup_index(), lazy_parallel_vacuum_indexes(), LVParallelState::lvshared, LVRelStats::new_rel_tuples, LVRelStats::num_index_scans, ParallelVacuumIsActive, pgstat_progress_update_param(), PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_INDEX_CLEANUP, LVRelStats::rel_pages, LVShared::reltuples, and LVRelStats::tupcount_pages.

Referenced by lazy_scan_heap().

2379 {
2380  int idx;
2381 
2383  Assert(nindexes > 0);
2384 
2385  /* Report that we are now cleaning up indexes */
2388 
2389  /*
2390  * If parallel vacuum is active we perform index cleanup with parallel
2391  * workers.
2392  */
2393  if (ParallelVacuumIsActive(lps))
2394  {
2395  /* Tell parallel workers to do index cleanup */
2396  lps->lvshared->for_cleanup = true;
2397  lps->lvshared->first_time =
2398  (vacrelstats->num_index_scans == 0);
2399 
2400  /*
2401  * Now we can provide a better estimate of total number of surviving
2402  * tuples (we assume indexes are more interested in that than in the
2403  * number of nominally live tuples).
2404  */
2405  lps->lvshared->reltuples = vacrelstats->new_rel_tuples;
2406  lps->lvshared->estimated_count =
2407  (vacrelstats->tupcount_pages < vacrelstats->rel_pages);
2408 
2409  lazy_parallel_vacuum_indexes(Irel, stats, vacrelstats, lps, nindexes);
2410  }
2411  else
2412  {
2413  for (idx = 0; idx < nindexes; idx++)
2414  lazy_cleanup_index(Irel[idx], &stats[idx],
2415  vacrelstats->new_rel_tuples,
2416  vacrelstats->tupcount_pages < vacrelstats->rel_pages,
2417  vacrelstats);
2418  }
2419 }
double new_rel_tuples
Definition: vacuumlazy.c:306
BlockNumber rel_pages
Definition: vacuumlazy.c:300
bool estimated_count
Definition: vacuumlazy.c:215
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
BlockNumber tupcount_pages
Definition: vacuumlazy.c:304
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
#define IsParallelWorker()
Definition: parallel.h:61
bool first_time
Definition: vacuumlazy.c:202
double reltuples
Definition: vacuumlazy.c:214
static void lazy_cleanup_index(Relation indrel, IndexBulkDeleteResult **stats, double reltuples, bool estimated_count, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2483
static void lazy_parallel_vacuum_indexes(Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
Definition: vacuumlazy.c:2091
#define ParallelVacuumIsActive(lps)
Definition: vacuumlazy.c:148
int num_index_scans
Definition: vacuumlazy.c:313
#define Assert(condition)
Definition: c.h:800
#define PROGRESS_VACUUM_PHASE_INDEX_CLEANUP
Definition: progress.h:33
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
LVShared * lvshared
Definition: vacuumlazy.c:275
bool for_cleanup
Definition: vacuumlazy.c:201

◆ lazy_cleanup_index()

static void lazy_cleanup_index ( Relation  indrel,
IndexBulkDeleteResult **  stats,
double  reltuples,
bool  estimated_count,
LVRelStats vacrelstats 
)
static

Definition at line 2483 of file vacuumlazy.c.

References IndexVacuumInfo::analyze_only, Assert, elevel, ereport, errdetail(), errmsg(), IndexVacuumInfo::estimated_count, IndexVacuumInfo::index, index_vacuum_cleanup(), LVRelStats::indname, InvalidBlockNumber, InvalidOffsetNumber, IndexVacuumInfo::message_level, IndexVacuumInfo::num_heap_tuples, pfree(), pg_rusage_init(), pg_rusage_show(), pstrdup(), RelationGetRelationName, IndexVacuumInfo::report_progress, restore_vacuum_error_info(), IndexVacuumInfo::strategy, update_vacuum_error_info(), vac_strategy, and VACUUM_ERRCB_PHASE_INDEX_CLEANUP.

Referenced by lazy_cleanup_all_indexes(), and vacuum_one_index().

2486 {
2487  IndexVacuumInfo ivinfo;
2488  PGRUsage ru0;
2489  LVSavedErrInfo saved_err_info;
2490 
2491  pg_rusage_init(&ru0);
2492 
2493  ivinfo.index = indrel;
2494  ivinfo.analyze_only = false;
2495  ivinfo.report_progress = false;
2496  ivinfo.estimated_count = estimated_count;
2497  ivinfo.message_level = elevel;
2498 
2499  ivinfo.num_heap_tuples = reltuples;
2500  ivinfo.strategy = vac_strategy;
2501 
2502  /*
2503  * Update error traceback information.
2504  *
2505  * The index name is saved during this phase and restored immediately
2506  * after this phase. See vacuum_error_callback.
2507  */
2508  Assert(vacrelstats->indname == NULL);
2509  vacrelstats->indname = pstrdup(RelationGetRelationName(indrel));
2510  update_vacuum_error_info(vacrelstats, &saved_err_info,
2513 
2514  *stats = index_vacuum_cleanup(&ivinfo, *stats);
2515 
2516  if (*stats)
2517  {
2518  ereport(elevel,
2519  (errmsg("index \"%s\" now contains %.0f row versions in %u pages",
2520  RelationGetRelationName(indrel),
2521  (*stats)->num_index_tuples,
2522  (*stats)->num_pages),
2523  errdetail("%.0f index row versions were removed.\n"
2524  "%u index pages have been deleted, %u are currently reusable.\n"
2525  "%s.",
2526  (*stats)->tuples_removed,
2527  (*stats)->pages_deleted, (*stats)->pages_free,
2528  pg_rusage_show(&ru0))));
2529  }
2530 
2531  /* Revert to the previous phase information for error traceback */
2532  restore_vacuum_error_info(vacrelstats, &saved_err_info);
2533  pfree(vacrelstats->indname);
2534  vacrelstats->indname = NULL;
2535 }
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bool analyze_only
Definition: genam.h:47
bool report_progress
Definition: genam.h:48
BufferAccessStrategy strategy
Definition: genam.h:52
Relation index
Definition: genam.h:46
static void restore_vacuum_error_info(LVRelStats *errinfo, const LVSavedErrInfo *saved_err_info)
Definition: vacuumlazy.c:3690
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void pfree(void *pointer)
Definition: mcxt.c:1057
int errdetail(const char *fmt,...)
Definition: elog.c:1035
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define RelationGetRelationName(relation)
Definition: rel.h:491
static int elevel
Definition: vacuumlazy.c:333
char * indname
Definition: vacuumlazy.c:318
#define InvalidOffsetNumber
Definition: off.h:26
#define ereport(elevel,...)
Definition: elog.h:155
static void update_vacuum_error_info(LVRelStats *errinfo, LVSavedErrInfo *saved_err_info, int phase, BlockNumber blkno, OffsetNumber offnum)
Definition: vacuumlazy.c:3671
int message_level
Definition: genam.h:50
double num_heap_tuples
Definition: genam.h:51
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:339
#define Assert(condition)
Definition: c.h:800
#define InvalidBlockNumber
Definition: block.h:33
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
Definition: indexam.c:710
int errmsg(const char *fmt,...)
Definition: elog.c:902
bool estimated_count
Definition: genam.h:49

◆ lazy_parallel_vacuum_indexes()

static void lazy_parallel_vacuum_indexes ( Relation Irel,
IndexBulkDeleteResult **  stats,
LVRelStats vacrelstats,
LVParallelState lps,
int  nindexes 
)
static

Definition at line 2091 of file vacuumlazy.c.

References LVShared::active_nworkers, Assert, LVParallelState::buffer_usage, LVShared::cost_balance, LVRelStats::dead_tuples, elevel, ereport, errmsg(), LVShared::first_time, LVShared::for_cleanup, i, LVShared::idx, InstrAccumParallelQuery(), IsParallelWorker, LaunchParallelWorkers(), LVParallelState::lvshared, Min, ngettext, LVParallelState::nindexes_parallel_bulkdel, LVParallelState::nindexes_parallel_cleanup, LVParallelState::nindexes_parallel_condcleanup, LVRelStats::num_index_scans, ParallelContext::nworkers, ParallelContext::nworkers_launched, parallel_vacuum_index(), ParallelVacuumIsActive, LVParallelState::pcxt, pg_atomic_read_u32(), pg_atomic_write_u32(), ReinitializeParallelDSM(), ReinitializeParallelWorkers(), vacuum_indexes_leader(), VacuumActiveNWorkers, VacuumCostBalance, VacuumCostBalanceLocal, VacuumSharedCostBalance, WaitForParallelWorkersToFinish(), and LVParallelState::wal_usage.

Referenced by lazy_cleanup_all_indexes(), and lazy_vacuum_all_indexes().

2094 {
2095  int nworkers;
2096 
2099  Assert(nindexes > 0);
2100 
2101  /* Determine the number of parallel workers to launch */
2102  if (lps->lvshared->for_cleanup)
2103  {
2104  if (lps->lvshared->first_time)
2105  nworkers = lps->nindexes_parallel_cleanup +
2107  else
2108  nworkers = lps->nindexes_parallel_cleanup;
2109  }
2110  else
2111  nworkers = lps->nindexes_parallel_bulkdel;
2112 
2113  /* The leader process will participate */
2114  nworkers--;
2115 
2116  /*
2117  * It is possible that parallel context is initialized with fewer workers
2118  * than the number of indexes that need a separate worker in the current
2119  * phase, so we need to consider it. See compute_parallel_vacuum_workers.
2120  */
2121  nworkers = Min(nworkers, lps->pcxt->nworkers);
2122 
2123  /* Setup the shared cost-based vacuum delay and launch workers */
2124  if (nworkers > 0)
2125  {
2126  if (vacrelstats->num_index_scans > 0)
2127  {
2128  /* Reset the parallel index processing counter */
2129  pg_atomic_write_u32(&(lps->lvshared->idx), 0);
2130 
2131  /* Reinitialize the parallel context to relaunch parallel workers */
2133  }
2134 
2135  /*
2136  * Set up shared cost balance and the number of active workers for
2137  * vacuum delay. We need to do this before launching workers as
2138  * otherwise, they might not see the updated values for these
2139  * parameters.
2140  */
2143 
2144  /*
2145  * The number of workers can vary between bulkdelete and cleanup
2146  * phase.
2147  */
2148  ReinitializeParallelWorkers(lps->pcxt, nworkers);
2149 
2151 
2152  if (lps->pcxt->nworkers_launched > 0)
2153  {
2154  /*
2155  * Reset the local cost values for leader backend as we have
2156  * already accumulated the remaining balance of heap.
2157  */
2158  VacuumCostBalance = 0;
2160 
2161  /* Enable shared cost balance for leader backend */
2164  }
2165 
2166  if (lps->lvshared->for_cleanup)
2167  ereport(elevel,
2168  (errmsg(ngettext("launched %d parallel vacuum worker for index cleanup (planned: %d)",
2169  "launched %d parallel vacuum workers for index cleanup (planned: %d)",
2170  lps->pcxt->nworkers_launched),
2171  lps->pcxt->nworkers_launched, nworkers)));
2172  else
2173  ereport(elevel,
2174  (errmsg(ngettext("launched %d parallel vacuum worker for index vacuuming (planned: %d)",
2175  "launched %d parallel vacuum workers for index vacuuming (planned: %d)",
2176  lps->pcxt->nworkers_launched),
2177  lps->pcxt->nworkers_launched, nworkers)));
2178  }
2179 
2180  /* Process the indexes that can be processed by only leader process */
2181  vacuum_indexes_leader(Irel, stats, vacrelstats, lps, nindexes);
2182 
2183  /*
2184  * Join as a parallel worker. The leader process alone processes all the
2185  * indexes in the case where no workers are launched.
2186  */
2187  parallel_vacuum_index(Irel, stats, lps->lvshared,
2188  vacrelstats->dead_tuples, nindexes, vacrelstats);
2189 
2190  /*
2191  * Next, accumulate buffer and WAL usage. (This must wait for the workers
2192  * to finish, or we might get incomplete data.)
2193  */
2194  if (nworkers > 0)
2195  {
2196  int i;
2197 
2198  /* Wait for all vacuum workers to finish */
2200 
2201  for (i = 0; i < lps->pcxt->nworkers_launched; i++)
2202  InstrAccumParallelQuery(&lps->buffer_usage[i], &lps->wal_usage[i]);
2203  }
2204 
2205  /*
2206  * Carry the shared balance value to heap scan and disable shared costing
2207  */
2209  {
2211  VacuumSharedCostBalance = NULL;
2212  VacuumActiveNWorkers = NULL;
2213  }
2214 }
WalUsage * wal_usage
Definition: vacuumlazy.c:281
pg_atomic_uint32 * VacuumActiveNWorkers
Definition: vacuum.c:77
int VacuumCostBalance
Definition: globals.c:148
LVDeadTuples * dead_tuples
Definition: vacuumlazy.c:312
BufferUsage * buffer_usage
Definition: vacuumlazy.c:278
#define Min(x, y)
Definition: c.h:982
int nindexes_parallel_bulkdel
Definition: vacuumlazy.c:287
int nindexes_parallel_condcleanup
Definition: vacuumlazy.c:289
void ReinitializeParallelWorkers(ParallelContext *pcxt, int nworkers_to_launch)
Definition: parallel.c:513
ParallelContext * pcxt
Definition: vacuumlazy.c:272
pg_atomic_uint32 cost_balance
Definition: vacuumlazy.c:232
void WaitForParallelWorkersToFinish(ParallelContext *pcxt)
Definition: parallel.c:750
pg_atomic_uint32 idx
Definition: vacuumlazy.c:246
int nworkers_launched
Definition: parallel.h:38
void LaunchParallelWorkers(ParallelContext *pcxt)
Definition: parallel.c:527
void InstrAccumParallelQuery(BufferUsage *bufusage, WalUsage *walusage)
Definition: instrument.c:199
static void vacuum_indexes_leader(Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
Definition: vacuumlazy.c:2273
#define IsParallelWorker()
Definition: parallel.h:61
bool first_time
Definition: vacuumlazy.c:202
int VacuumCostBalanceLocal
Definition: vacuum.c:78
pg_atomic_uint32 * VacuumSharedCostBalance
Definition: vacuum.c:76
static int elevel
Definition: vacuumlazy.c:333
#define ngettext(s, p, n)
Definition: c.h:1178
int nindexes_parallel_cleanup
Definition: vacuumlazy.c:288
#define ParallelVacuumIsActive(lps)
Definition: vacuumlazy.c:148
void ReinitializeParallelDSM(ParallelContext *pcxt)
Definition: parallel.c:463
pg_atomic_uint32 active_nworkers
Definition: vacuumlazy.c:239
#define ereport(elevel,...)
Definition: elog.h:155
int num_index_scans
Definition: vacuumlazy.c:313
#define Assert(condition)
Definition: c.h:800
LVShared * lvshared
Definition: vacuumlazy.c:275
bool for_cleanup
Definition: vacuumlazy.c:201
int errmsg(const char *fmt,...)
Definition: elog.c:902
int i
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:258
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241
static void parallel_vacuum_index(Relation *Irel, IndexBulkDeleteResult **stats, LVShared *lvshared, LVDeadTuples *dead_tuples, int nindexes, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2221

◆ lazy_record_dead_tuple()

static void lazy_record_dead_tuple ( LVDeadTuples dead_tuples,
ItemPointer  itemptr 
)
static

Definition at line 2897 of file vacuumlazy.c.

References LVDeadTuples::itemptrs, LVDeadTuples::max_tuples, LVDeadTuples::num_tuples, pgstat_progress_update_param(), and PROGRESS_VACUUM_NUM_DEAD_TUPLES.

Referenced by lazy_scan_heap().

2898 {
2899  /*
2900  * The array shouldn't overflow under normal behavior, but perhaps it
2901  * could if we are given a really small maintenance_work_mem. In that
2902  * case, just forget the last few tuples (we'll get 'em next time).
2903  */
2904  if (dead_tuples->num_tuples < dead_tuples->max_tuples)
2905  {
2906  dead_tuples->itemptrs[dead_tuples->num_tuples] = *itemptr;
2907  dead_tuples->num_tuples++;
2909  dead_tuples->num_tuples);
2910  }
2911 }
ItemPointerData itemptrs[FLEXIBLE_ARRAY_MEMBER]
Definition: vacuumlazy.c:172
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
#define PROGRESS_VACUUM_NUM_DEAD_TUPLES
Definition: progress.h:27

◆ lazy_scan_heap()

static void lazy_scan_heap ( Relation  onerel,
VacuumParams params,
LVRelStats vacrelstats,
Relation Irel,
int  nindexes,
bool  aggressive 
)
static

Definition at line 753 of file vacuumlazy.c.

References _, appendStringInfo(), Assert, begin_parallel_vacuum(), LVRelStats::blkno, buf, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, BufferGetPageSize, BufferIsValid, ConditionalLockBufferForCleanup(), StringInfoData::data, LVRelStats::dead_tuples, elevel, elog, END_CRIT_SECTION, end_parallel_vacuum(), ereport, errdetail_internal(), errmsg(), ERROR, FirstOffsetNumber, FORCE_CHECK_PAGE, FreeSpaceMapVacuumRange(), FreezeLimit, LVRelStats::frozenskipped_pages, GetRecordedFreeSpace(), GlobalVisTestFor(), heap_execute_freeze_tuple(), heap_page_prune(), heap_prepare_freeze_tuple(), HEAPTUPLE_DEAD, HEAPTUPLE_DELETE_IN_PROGRESS, HEAPTUPLE_INSERT_IN_PROGRESS, HEAPTUPLE_LIVE, HEAPTUPLE_RECENTLY_DEAD, HeapTupleHeaderAdvanceLatestRemovedXid(), HeapTupleHeaderGetXmin, HeapTupleHeaderXminCommitted, HeapTupleIsHeapOnly, HeapTupleIsHotUpdated, HeapTupleSatisfiesVacuum(), i, VacuumParams::index_cleanup, initStringInfo(), InvalidBlockNumber, InvalidBuffer, InvalidOffsetNumber, InvalidTransactionId, InvalidXLogRecPtr, ItemIdGetLength, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerSet, LVRelStats::latestRemovedXid, lazy_check_needs_freeze(), lazy_cleanup_all_indexes(), lazy_record_dead_tuple(), lazy_space_alloc(), lazy_vacuum_all_indexes(), lazy_vacuum_heap(), lazy_vacuum_page(), LockBuffer(), LockBufferForCleanup(), log_heap_freeze(), log_newpage_buffer(), MAIN_FORKNUM, MarkBufferDirty(), Max, LVDeadTuples::max_tuples, MaxHeapTuplesPerPage, MultiXactCutoff, LVRelStats::new_dead_tuples, LVRelStats::new_live_tuples, LVRelStats::new_rel_tuples, ngettext, LVRelStats::nonempty_pages, LVDeadTuples::num_tuples, VacuumParams::nworkers, LVRelStats::offnum, xl_heap_freeze_tuple::offset, OffsetNumberNext, OldestXmin, VacuumParams::options, PageClearAllVisible, PageGetHeapFreeSpace(), PageGetItem, PageGetItemId, PageGetLSN, PageGetMaxOffsetNumber, PageIsAllVisible, PageIsEmpty, PageIsNew, PageSetAllVisible, PageSetLSN, palloc(), palloc0(), ParallelVacuumIsActive, pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_update_multi_param(), pgstat_progress_update_param(), LVRelStats::pinskipped_pages, PROGRESS_VACUUM_HEAP_BLKS_SCANNED, PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, PROGRESS_VACUUM_MAX_DEAD_TUPLES, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_SCAN_HEAP, PROGRESS_VACUUM_TOTAL_HEAP_BLKS, RBM_NORMAL, RelationData::rd_rel, ReadBufferExtended(), RecordPageWithFreeSpace(), LVRelStats::rel_pages, RelationGetNumberOfBlocks, RelationGetRelid, RelationNeedsWAL, RelationUsesLocalBuffers, ReleaseBuffer(), LVRelStats::relname, LVRelStats::relnamespace, LVRelStats::scanned_pages, SizeOfPageHeaderData, SKIP_PAGES_THRESHOLD, START_CRIT_SECTION, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdFollows(), TransactionIdPrecedes(), LVRelStats::tupcount_pages, LVRelStats::tuples_deleted, UnlockReleaseBuffer(), update_index_statistics(), update_vacuum_error_info(), LVRelStats::useindex, vac_estimate_reltuples(), VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_TERNARY_DISABLED, vacuum_delay_point(), VACUUM_ERRCB_PHASE_SCAN_HEAP, VACUUM_FSM_EVERY_PAGES, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, visibilitymap_clear(), visibilitymap_get_status(), visibilitymap_pin(), visibilitymap_set(), VISIBILITYMAP_VALID_BITS, VM_ALL_FROZEN, VM_ALL_VISIBLE, and WARNING.

Referenced by heap_vacuum_rel().

755 {
756  LVParallelState *lps = NULL;
757  LVDeadTuples *dead_tuples;
758  BlockNumber nblocks,
759  blkno;
760  HeapTupleData tuple;
761  TransactionId relfrozenxid = onerel->rd_rel->relfrozenxid;
762  TransactionId relminmxid = onerel->rd_rel->relminmxid;
763  BlockNumber empty_pages,
764  vacuumed_pages,
765  next_fsm_block_to_vacuum;
766  double num_tuples, /* total number of nonremovable tuples */
767  live_tuples, /* live tuples (reltuples estimate) */
768  tups_vacuumed, /* tuples cleaned up by vacuum */
769  nkeep, /* dead-but-not-removable tuples */
770  nunused; /* unused line pointers */
771  IndexBulkDeleteResult **indstats;
772  int i;
773  PGRUsage ru0;
774  Buffer vmbuffer = InvalidBuffer;
775  BlockNumber next_unskippable_block;
776  bool skipping_blocks;
777  xl_heap_freeze_tuple *frozen;
779  const int initprog_index[] = {
783  };
784  int64 initprog_val[3];
785  GlobalVisState *vistest;
786 
787  pg_rusage_init(&ru0);
788 
789  if (aggressive)
790  ereport(elevel,
791  (errmsg("aggressively vacuuming \"%s.%s\"",
792  vacrelstats->relnamespace,
793  vacrelstats->relname)));
794  else
795  ereport(elevel,
796  (errmsg("vacuuming \"%s.%s\"",
797  vacrelstats->relnamespace,
798  vacrelstats->relname)));
799 
800  empty_pages = vacuumed_pages = 0;
801  next_fsm_block_to_vacuum = (BlockNumber) 0;
802  num_tuples = live_tuples = tups_vacuumed = nkeep = nunused = 0;
803 
804  indstats = (IndexBulkDeleteResult **)
805  palloc0(nindexes * sizeof(IndexBulkDeleteResult *));
806 
807  nblocks = RelationGetNumberOfBlocks(onerel);
808  vacrelstats->rel_pages = nblocks;
809  vacrelstats->scanned_pages = 0;
810  vacrelstats->tupcount_pages = 0;
811  vacrelstats->nonempty_pages = 0;
812  vacrelstats->latestRemovedXid = InvalidTransactionId;
813 
814  vistest = GlobalVisTestFor(onerel);
815 
816  /*
817  * Initialize state for a parallel vacuum. As of now, only one worker can
818  * be used for an index, so we invoke parallelism only if there are at
819  * least two indexes on a table.
820  */
821  if (params->nworkers >= 0 && vacrelstats->useindex && nindexes > 1)
822  {
823  /*
824  * Since parallel workers cannot access data in temporary tables, we
825  * can't perform parallel vacuum on them.
826  */
827  if (RelationUsesLocalBuffers(onerel))
828  {
829  /*
830  * Give warning only if the user explicitly tries to perform a
831  * parallel vacuum on the temporary table.
832  */
833  if (params->nworkers > 0)
835  (errmsg("disabling parallel option of vacuum on \"%s\" --- cannot vacuum temporary tables in parallel",
836  vacrelstats->relname)));
837  }
838  else
839  lps = begin_parallel_vacuum(RelationGetRelid(onerel), Irel,
840  vacrelstats, nblocks, nindexes,
841  params->nworkers);
842  }
843 
844  /*
845  * Allocate the space for dead tuples in case parallel vacuum is not
846  * initialized.
847  */
848  if (!ParallelVacuumIsActive(lps))
849  lazy_space_alloc(vacrelstats, nblocks);
850 
851  dead_tuples = vacrelstats->dead_tuples;
853 
854  /* Report that we're scanning the heap, advertising total # of blocks */
855  initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP;
856  initprog_val[1] = nblocks;
857  initprog_val[2] = dead_tuples->max_tuples;
858  pgstat_progress_update_multi_param(3, initprog_index, initprog_val);
859 
860  /*
861  * Except when aggressive is set, we want to skip pages that are
862  * all-visible according to the visibility map, but only when we can skip
863  * at least SKIP_PAGES_THRESHOLD consecutive pages. Since we're reading
864  * sequentially, the OS should be doing readahead for us, so there's no
865  * gain in skipping a page now and then; that's likely to disable
866  * readahead and so be counterproductive. Also, skipping even a single
867  * page means that we can't update relfrozenxid, so we only want to do it
868  * if we can skip a goodly number of pages.
869  *
870  * When aggressive is set, we can't skip pages just because they are
871  * all-visible, but we can still skip pages that are all-frozen, since
872  * such pages do not need freezing and do not affect the value that we can
873  * safely set for relfrozenxid or relminmxid.
874  *
875  * Before entering the main loop, establish the invariant that
876  * next_unskippable_block is the next block number >= blkno that we can't
877  * skip based on the visibility map, either all-visible for a regular scan
878  * or all-frozen for an aggressive scan. We set it to nblocks if there's
879  * no such block. We also set up the skipping_blocks flag correctly at
880  * this stage.
881  *
882  * Note: The value returned by visibilitymap_get_status could be slightly
883  * out-of-date, since we make this test before reading the corresponding
884  * heap page or locking the buffer. This is OK. If we mistakenly think
885  * that the page is all-visible or all-frozen when in fact the flag's just
886  * been cleared, we might fail to vacuum the page. It's easy to see that
887  * skipping a page when aggressive is not set is not a very big deal; we
888  * might leave some dead tuples lying around, but the next vacuum will
889  * find them. But even when aggressive *is* set, it's still OK if we miss
890  * a page whose all-frozen marking has just been cleared. Any new XIDs
891  * just added to that page are necessarily newer than the GlobalXmin we
892  * computed, so they'll have no effect on the value to which we can safely
893  * set relfrozenxid. A similar argument applies for MXIDs and relminmxid.
894  *
895  * We will scan the table's last page, at least to the extent of
896  * determining whether it has tuples or not, even if it should be skipped
897  * according to the above rules; except when we've already determined that
898  * it's not worth trying to truncate the table. This avoids having
899  * lazy_truncate_heap() take access-exclusive lock on the table to attempt
900  * a truncation that just fails immediately because there are tuples in
901  * the last page. This is worth avoiding mainly because such a lock must
902  * be replayed on any hot standby, where it can be disruptive.
903  */
904  next_unskippable_block = 0;
905  if ((params->options & VACOPT_DISABLE_PAGE_SKIPPING) == 0)
906  {
907  while (next_unskippable_block < nblocks)
908  {
909  uint8 vmstatus;
910 
911  vmstatus = visibilitymap_get_status(onerel, next_unskippable_block,
912  &vmbuffer);
913  if (aggressive)
914  {
915  if ((vmstatus & VISIBILITYMAP_ALL_FROZEN) == 0)
916  break;
917  }
918  else
919  {
920  if ((vmstatus & VISIBILITYMAP_ALL_VISIBLE) == 0)
921  break;
922  }
924  next_unskippable_block++;
925  }
926  }
927 
928  if (next_unskippable_block >= SKIP_PAGES_THRESHOLD)
929  skipping_blocks = true;
930  else
931  skipping_blocks = false;
932 
933  for (blkno = 0; blkno < nblocks; blkno++)
934  {
935  Buffer buf;
936  Page page;
937  OffsetNumber offnum,
938  maxoff;
939  bool tupgone,
940  hastup;
941  int prev_dead_count;
942  int nfrozen;
943  Size freespace;
944  bool all_visible_according_to_vm = false;
945  bool all_visible;
946  bool all_frozen = true; /* provided all_visible is also true */
947  bool has_dead_tuples;
948  TransactionId visibility_cutoff_xid = InvalidTransactionId;
949 
950  /* see note above about forcing scanning of last page */
951 #define FORCE_CHECK_PAGE() \
952  (blkno == nblocks - 1 && should_attempt_truncation(params, vacrelstats))
953 
955 
957  blkno, InvalidOffsetNumber);
958 
959  if (blkno == next_unskippable_block)
960  {
961  /* Time to advance next_unskippable_block */
962  next_unskippable_block++;
963  if ((params->options & VACOPT_DISABLE_PAGE_SKIPPING) == 0)
964  {
965  while (next_unskippable_block < nblocks)
966  {
967  uint8 vmskipflags;
968 
969  vmskipflags = visibilitymap_get_status(onerel,
970  next_unskippable_block,
971  &vmbuffer);
972  if (aggressive)
973  {
974  if ((vmskipflags & VISIBILITYMAP_ALL_FROZEN) == 0)
975  break;
976  }
977  else
978  {
979  if ((vmskipflags & VISIBILITYMAP_ALL_VISIBLE) == 0)
980  break;
981  }
983  next_unskippable_block++;
984  }
985  }
986 
987  /*
988  * We know we can't skip the current block. But set up
989  * skipping_blocks to do the right thing at the following blocks.
990  */
991  if (next_unskippable_block - blkno > SKIP_PAGES_THRESHOLD)
992  skipping_blocks = true;
993  else
994  skipping_blocks = false;
995 
996  /*
997  * Normally, the fact that we can't skip this block must mean that
998  * it's not all-visible. But in an aggressive vacuum we know only
999  * that it's not all-frozen, so it might still be all-visible.
1000  */
1001  if (aggressive && VM_ALL_VISIBLE(onerel, blkno, &vmbuffer))
1002  all_visible_according_to_vm = true;
1003  }
1004  else
1005  {
1006  /*
1007  * The current block is potentially skippable; if we've seen a
1008  * long enough run of skippable blocks to justify skipping it, and
1009  * we're not forced to check it, then go ahead and skip.
1010  * Otherwise, the page must be at least all-visible if not
1011  * all-frozen, so we can set all_visible_according_to_vm = true.
1012  */
1013  if (skipping_blocks && !FORCE_CHECK_PAGE())
1014  {
1015  /*
1016  * Tricky, tricky. If this is in aggressive vacuum, the page
1017  * must have been all-frozen at the time we checked whether it
1018  * was skippable, but it might not be any more. We must be
1019  * careful to count it as a skipped all-frozen page in that
1020  * case, or else we'll think we can't update relfrozenxid and
1021  * relminmxid. If it's not an aggressive vacuum, we don't
1022  * know whether it was all-frozen, so we have to recheck; but
1023  * in this case an approximate answer is OK.
1024  */
1025  if (aggressive || VM_ALL_FROZEN(onerel, blkno, &vmbuffer))
1026  vacrelstats->frozenskipped_pages++;
1027  continue;
1028  }
1029  all_visible_according_to_vm = true;
1030  }
1031 
1033 
1034  /*
1035  * If we are close to overrunning the available space for dead-tuple
1036  * TIDs, pause and do a cycle of vacuuming before we tackle this page.
1037  */
1038  if ((dead_tuples->max_tuples - dead_tuples->num_tuples) < MaxHeapTuplesPerPage &&
1039  dead_tuples->num_tuples > 0)
1040  {
1041  /*
1042  * Before beginning index vacuuming, we release any pin we may
1043  * hold on the visibility map page. This isn't necessary for
1044  * correctness, but we do it anyway to avoid holding the pin
1045  * across a lengthy, unrelated operation.
1046  */
1047  if (BufferIsValid(vmbuffer))
1048  {
1049  ReleaseBuffer(vmbuffer);
1050  vmbuffer = InvalidBuffer;
1051  }
1052 
1053  /* Work on all the indexes, then the heap */
1054  lazy_vacuum_all_indexes(onerel, Irel, indstats,
1055  vacrelstats, lps, nindexes);
1056 
1057  /* Remove tuples from heap */
1058  lazy_vacuum_heap(onerel, vacrelstats);
1059 
1060  /*
1061  * Forget the now-vacuumed tuples, and press on, but be careful
1062  * not to reset latestRemovedXid since we want that value to be
1063  * valid.
1064  */
1065  dead_tuples->num_tuples = 0;
1066 
1067  /*
1068  * Vacuum the Free Space Map to make newly-freed space visible on
1069  * upper-level FSM pages. Note we have not yet processed blkno.
1070  */
1071  FreeSpaceMapVacuumRange(onerel, next_fsm_block_to_vacuum, blkno);
1072  next_fsm_block_to_vacuum = blkno;
1073 
1074  /* Report that we are once again scanning the heap */
1077  }
1078 
1079  /*
1080  * Pin the visibility map page in case we need to mark the page
1081  * all-visible. In most cases this will be very cheap, because we'll
1082  * already have the correct page pinned anyway. However, it's
1083  * possible that (a) next_unskippable_block is covered by a different
1084  * VM page than the current block or (b) we released our pin and did a
1085  * cycle of index vacuuming.
1086  *
1087  */
1088  visibilitymap_pin(onerel, blkno, &vmbuffer);
1089 
1090  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, blkno,
1092 
1093  /* We need buffer cleanup lock so that we can prune HOT chains. */
1095  {
1096  /*
1097  * If we're not performing an aggressive scan to guard against XID
1098  * wraparound, and we don't want to forcibly check the page, then
1099  * it's OK to skip vacuuming pages we get a lock conflict on. They
1100  * will be dealt with in some future vacuum.
1101  */
1102  if (!aggressive && !FORCE_CHECK_PAGE())
1103  {
1104  ReleaseBuffer(buf);
1105  vacrelstats->pinskipped_pages++;
1106  continue;
1107  }
1108 
1109  /*
1110  * Read the page with share lock to see if any xids on it need to
1111  * be frozen. If not we just skip the page, after updating our
1112  * scan statistics. If there are some, we wait for cleanup lock.
1113  *
1114  * We could defer the lock request further by remembering the page
1115  * and coming back to it later, or we could even register
1116  * ourselves for multiple buffers and then service whichever one
1117  * is received first. For now, this seems good enough.
1118  *
1119  * If we get here with aggressive false, then we're just forcibly
1120  * checking the page, and so we don't want to insist on getting
1121  * the lock; we only need to know if the page contains tuples, so
1122  * that we can update nonempty_pages correctly. It's convenient
1123  * to use lazy_check_needs_freeze() for both situations, though.
1124  */
1126  if (!lazy_check_needs_freeze(buf, &hastup, vacrelstats))
1127  {
1128  UnlockReleaseBuffer(buf);
1129  vacrelstats->scanned_pages++;
1130  vacrelstats->pinskipped_pages++;
1131  if (hastup)
1132  vacrelstats->nonempty_pages = blkno + 1;
1133  continue;
1134  }
1135  if (!aggressive)
1136  {
1137  /*
1138  * Here, we must not advance scanned_pages; that would amount
1139  * to claiming that the page contains no freezable tuples.
1140  */
1141  UnlockReleaseBuffer(buf);
1142  vacrelstats->pinskipped_pages++;
1143  if (hastup)
1144  vacrelstats->nonempty_pages = blkno + 1;
1145  continue;
1146  }
1148  LockBufferForCleanup(buf);
1149  /* drop through to normal processing */
1150  }
1151 
1152  vacrelstats->scanned_pages++;
1153  vacrelstats->tupcount_pages++;
1154 
1155  page = BufferGetPage(buf);
1156 
1157  if (PageIsNew(page))
1158  {
1159  /*
1160  * All-zeroes pages can be left over if either a backend extends
1161  * the relation by a single page, but crashes before the newly
1162  * initialized page has been written out, or when bulk-extending
1163  * the relation (which creates a number of empty pages at the tail
1164  * end of the relation, but enters them into the FSM).
1165  *
1166  * Note we do not enter the page into the visibilitymap. That has
1167  * the downside that we repeatedly visit this page in subsequent
1168  * vacuums, but otherwise we'll never not discover the space on a
1169  * promoted standby. The harm of repeated checking ought to
1170  * normally not be too bad - the space usually should be used at
1171  * some point, otherwise there wouldn't be any regular vacuums.
1172  *
1173  * Make sure these pages are in the FSM, to ensure they can be
1174  * reused. Do that by testing if there's any space recorded for
1175  * the page. If not, enter it. We do so after releasing the lock
1176  * on the heap page, the FSM is approximate, after all.
1177  */
1178  UnlockReleaseBuffer(buf);
1179 
1180  empty_pages++;
1181 
1182  if (GetRecordedFreeSpace(onerel, blkno) == 0)
1183  {
1184  Size freespace;
1185 
1186  freespace = BufferGetPageSize(buf) - SizeOfPageHeaderData;
1187  RecordPageWithFreeSpace(onerel, blkno, freespace);
1188  }
1189  continue;
1190  }
1191 
1192  if (PageIsEmpty(page))
1193  {
1194  empty_pages++;
1195  freespace = PageGetHeapFreeSpace(page);
1196 
1197  /*
1198  * Empty pages are always all-visible and all-frozen (note that
1199  * the same is currently not true for new pages, see above).
1200  */
1201  if (!PageIsAllVisible(page))
1202  {
1204 
1205  /* mark buffer dirty before writing a WAL record */
1206  MarkBufferDirty(buf);
1207 
1208  /*
1209  * It's possible that another backend has extended the heap,
1210  * initialized the page, and then failed to WAL-log the page
1211  * due to an ERROR. Since heap extension is not WAL-logged,
1212  * recovery might try to replay our record setting the page
1213  * all-visible and find that the page isn't initialized, which
1214  * will cause a PANIC. To prevent that, check whether the
1215  * page has been previously WAL-logged, and if not, do that
1216  * now.
1217  */
1218  if (RelationNeedsWAL(onerel) &&
1219  PageGetLSN(page) == InvalidXLogRecPtr)
1220  log_newpage_buffer(buf, true);
1221 
1222  PageSetAllVisible(page);
1223  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
1224  vmbuffer, InvalidTransactionId,
1226  END_CRIT_SECTION();
1227  }
1228 
1229  UnlockReleaseBuffer(buf);
1230  RecordPageWithFreeSpace(onerel, blkno, freespace);
1231  continue;
1232  }
1233 
1234  /*
1235  * Prune all HOT-update chains in this page.
1236  *
1237  * We count tuples removed by the pruning step as removed by VACUUM.
1238  */
1239  tups_vacuumed += heap_page_prune(onerel, buf, vistest, false,
1241  &vacrelstats->latestRemovedXid,
1242  &vacrelstats->offnum);
1243 
1244  /*
1245  * Now scan the page to collect vacuumable items and check for tuples
1246  * requiring freezing.
1247  */
1248  all_visible = true;
1249  has_dead_tuples = false;
1250  nfrozen = 0;
1251  hastup = false;
1252  prev_dead_count = dead_tuples->num_tuples;
1253  maxoff = PageGetMaxOffsetNumber(page);
1254 
1255  /*
1256  * Note: If you change anything in the loop below, also look at
1257  * heap_page_is_all_visible to see if that needs to be changed.
1258  */
1259  for (offnum = FirstOffsetNumber;
1260  offnum <= maxoff;
1261  offnum = OffsetNumberNext(offnum))
1262  {
1263  ItemId itemid;
1264 
1265  /*
1266  * Set the offset number so that we can display it along with any
1267  * error that occurred while processing this tuple.
1268  */
1269  vacrelstats->offnum = offnum;
1270  itemid = PageGetItemId(page, offnum);
1271 
1272  /* Unused items require no processing, but we count 'em */
1273  if (!ItemIdIsUsed(itemid))
1274  {
1275  nunused += 1;
1276  continue;
1277  }
1278 
1279  /* Redirect items mustn't be touched */
1280  if (ItemIdIsRedirected(itemid))
1281  {
1282  hastup = true; /* this page won't be truncatable */
1283  continue;
1284  }
1285 
1286  ItemPointerSet(&(tuple.t_self), blkno, offnum);
1287 
1288  /*
1289  * DEAD line pointers are to be vacuumed normally; but we don't
1290  * count them in tups_vacuumed, else we'd be double-counting (at
1291  * least in the common case where heap_page_prune() just freed up
1292  * a non-HOT tuple).
1293  */
1294  if (ItemIdIsDead(itemid))
1295  {
1296  lazy_record_dead_tuple(dead_tuples, &(tuple.t_self));
1297  all_visible = false;
1298  continue;
1299  }
1300 
1301  Assert(ItemIdIsNormal(itemid));
1302 
1303  tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
1304  tuple.t_len = ItemIdGetLength(itemid);
1305  tuple.t_tableOid = RelationGetRelid(onerel);
1306 
1307  tupgone = false;
1308 
1309  /*
1310  * The criteria for counting a tuple as live in this block need to
1311  * match what analyze.c's acquire_sample_rows() does, otherwise
1312  * VACUUM and ANALYZE may produce wildly different reltuples
1313  * values, e.g. when there are many recently-dead tuples.
1314  *
1315  * The logic here is a bit simpler than acquire_sample_rows(), as
1316  * VACUUM can't run inside a transaction block, which makes some
1317  * cases impossible (e.g. in-progress insert from the same
1318  * transaction).
1319  */
1320  switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf))
1321  {
1322  case HEAPTUPLE_DEAD:
1323 
1324  /*
1325  * Ordinarily, DEAD tuples would have been removed by
1326  * heap_page_prune(), but it's possible that the tuple
1327  * state changed since heap_page_prune() looked. In
1328  * particular an INSERT_IN_PROGRESS tuple could have
1329  * changed to DEAD if the inserter aborted. So this
1330  * cannot be considered an error condition.
1331  *
1332  * If the tuple is HOT-updated then it must only be
1333  * removed by a prune operation; so we keep it just as if
1334  * it were RECENTLY_DEAD. Also, if it's a heap-only
1335  * tuple, we choose to keep it, because it'll be a lot
1336  * cheaper to get rid of it in the next pruning pass than
1337  * to treat it like an indexed tuple. Finally, if index
1338  * cleanup is disabled, the second heap pass will not
1339  * execute, and the tuple will not get removed, so we must
1340  * treat it like any other dead tuple that we choose to
1341  * keep.
1342  *
1343  * If this were to happen for a tuple that actually needed
1344  * to be deleted, we'd be in trouble, because it'd
1345  * possibly leave a tuple below the relation's xmin
1346  * horizon alive. heap_prepare_freeze_tuple() is prepared
1347  * to detect that case and abort the transaction,
1348  * preventing corruption.
1349  */
1350  if (HeapTupleIsHotUpdated(&tuple) ||
1351  HeapTupleIsHeapOnly(&tuple) ||
1353  nkeep += 1;
1354  else
1355  tupgone = true; /* we can delete the tuple */
1356  all_visible = false;
1357  break;
1358  case HEAPTUPLE_LIVE:
1359 
1360  /*
1361  * Count it as live. Not only is this natural, but it's
1362  * also what acquire_sample_rows() does.
1363  */
1364  live_tuples += 1;
1365 
1366  /*
1367  * Is the tuple definitely visible to all transactions?
1368  *
1369  * NB: Like with per-tuple hint bits, we can't set the
1370  * PD_ALL_VISIBLE flag if the inserter committed
1371  * asynchronously. See SetHintBits for more info. Check
1372  * that the tuple is hinted xmin-committed because of
1373  * that.
1374  */
1375  if (all_visible)
1376  {
1377  TransactionId xmin;
1378 
1380  {
1381  all_visible = false;
1382  break;
1383  }
1384 
1385  /*
1386  * The inserter definitely committed. But is it old
1387  * enough that everyone sees it as committed?
1388  */
1389  xmin = HeapTupleHeaderGetXmin(tuple.t_data);
1390  if (!TransactionIdPrecedes(xmin, OldestXmin))
1391  {
1392  all_visible = false;
1393  break;
1394  }
1395 
1396  /* Track newest xmin on page. */
1397  if (TransactionIdFollows(xmin, visibility_cutoff_xid))
1398  visibility_cutoff_xid = xmin;
1399  }
1400  break;
1402 
1403  /*
1404  * If tuple is recently deleted then we must not remove it
1405  * from relation.
1406  */
1407  nkeep += 1;
1408  all_visible = false;
1409  break;
1411 
1412  /*
1413  * This is an expected case during concurrent vacuum.
1414  *
1415  * We do not count these rows as live, because we expect
1416  * the inserting transaction to update the counters at
1417  * commit, and we assume that will happen only after we
1418  * report our results. This assumption is a bit shaky,
1419  * but it is what acquire_sample_rows() does, so be
1420  * consistent.
1421  */
1422  all_visible = false;
1423  break;
1425  /* This is an expected case during concurrent vacuum */
1426  all_visible = false;
1427 
1428  /*
1429  * Count such rows as live. As above, we assume the
1430  * deleting transaction will commit and update the
1431  * counters after we report.
1432  */
1433  live_tuples += 1;
1434  break;
1435  default:
1436  elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
1437  break;
1438  }
1439 
1440  if (tupgone)
1441  {
1442  lazy_record_dead_tuple(dead_tuples, &(tuple.t_self));
1444  &vacrelstats->latestRemovedXid);
1445  tups_vacuumed += 1;
1446  has_dead_tuples = true;
1447  }
1448  else
1449  {
1450  bool tuple_totally_frozen;
1451 
1452  num_tuples += 1;
1453  hastup = true;
1454 
1455  /*
1456  * Each non-removable tuple must be checked to see if it needs
1457  * freezing. Note we already have exclusive buffer lock.
1458  */
1460  relfrozenxid, relminmxid,
1462  &frozen[nfrozen],
1463  &tuple_totally_frozen))
1464  frozen[nfrozen++].offset = offnum;
1465 
1466  if (!tuple_totally_frozen)
1467  all_frozen = false;
1468  }
1469  } /* scan along page */
1470 
1471  /*
1472  * Clear the offset information once we have processed all the tuples
1473  * on the page.
1474  */
1475  vacrelstats->offnum = InvalidOffsetNumber;
1476 
1477  /*
1478  * If we froze any tuples, mark the buffer dirty, and write a WAL
1479  * record recording the changes. We must log the changes to be
1480  * crash-safe against future truncation of CLOG.
1481  */
1482  if (nfrozen > 0)
1483  {
1485 
1486  MarkBufferDirty(buf);
1487 
1488  /* execute collected freezes */
1489  for (i = 0; i < nfrozen; i++)
1490  {
1491  ItemId itemid;
1492  HeapTupleHeader htup;
1493 
1494  itemid = PageGetItemId(page, frozen[i].offset);
1495  htup = (HeapTupleHeader) PageGetItem(page, itemid);
1496 
1497  heap_execute_freeze_tuple(htup, &frozen[i]);
1498  }
1499 
1500  /* Now WAL-log freezing if necessary */
1501  if (RelationNeedsWAL(onerel))
1502  {
1503  XLogRecPtr recptr;
1504 
1505  recptr = log_heap_freeze(onerel, buf, FreezeLimit,
1506  frozen, nfrozen);
1507  PageSetLSN(page, recptr);
1508  }
1509 
1510  END_CRIT_SECTION();
1511  }
1512 
1513  /*
1514  * If there are no indexes we can vacuum the page right now instead of
1515  * doing a second scan. Also we don't do that but forget dead tuples
1516  * when index cleanup is disabled.
1517  */
1518  if (!vacrelstats->useindex && dead_tuples->num_tuples > 0)
1519  {
1520  if (nindexes == 0)
1521  {
1522  /* Remove tuples from heap if the table has no index */
1523  lazy_vacuum_page(onerel, blkno, buf, 0, vacrelstats, &vmbuffer);
1524  vacuumed_pages++;
1525  has_dead_tuples = false;
1526  }
1527  else
1528  {
1529  /*
1530  * Here, we have indexes but index cleanup is disabled.
1531  * Instead of vacuuming the dead tuples on the heap, we just
1532  * forget them.
1533  *
1534  * Note that vacrelstats->dead_tuples could have tuples which
1535  * became dead after HOT-pruning but are not marked dead yet.
1536  * We do not process them because it's a very rare condition,
1537  * and the next vacuum will process them anyway.
1538  */
1540  }
1541 
1542  /*
1543  * Forget the now-vacuumed tuples, and press on, but be careful
1544  * not to reset latestRemovedXid since we want that value to be
1545  * valid.
1546  */
1547  dead_tuples->num_tuples = 0;
1548 
1549  /*
1550  * Periodically do incremental FSM vacuuming to make newly-freed
1551  * space visible on upper FSM pages. Note: although we've cleaned
1552  * the current block, we haven't yet updated its FSM entry (that
1553  * happens further down), so passing end == blkno is correct.
1554  */
1555  if (blkno - next_fsm_block_to_vacuum >= VACUUM_FSM_EVERY_PAGES)
1556  {
1557  FreeSpaceMapVacuumRange(onerel, next_fsm_block_to_vacuum,
1558  blkno);
1559  next_fsm_block_to_vacuum = blkno;
1560  }
1561  }
1562 
1563  freespace = PageGetHeapFreeSpace(page);
1564 
1565  /* mark page all-visible, if appropriate */
1566  if (all_visible && !all_visible_according_to_vm)
1567  {
1569 
1570  if (all_frozen)
1571  flags |= VISIBILITYMAP_ALL_FROZEN;
1572 
1573  /*
1574  * It should never be the case that the visibility map page is set
1575  * while the page-level bit is clear, but the reverse is allowed
1576  * (if checksums are not enabled). Regardless, set both bits so
1577  * that we get back in sync.
1578  *
1579  * NB: If the heap page is all-visible but the VM bit is not set,
1580  * we don't need to dirty the heap page. However, if checksums
1581  * are enabled, we do need to make sure that the heap page is
1582  * dirtied before passing it to visibilitymap_set(), because it
1583  * may be logged. Given that this situation should only happen in
1584  * rare cases after a crash, it is not worth optimizing.
1585  */
1586  PageSetAllVisible(page);
1587  MarkBufferDirty(buf);
1588  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
1589  vmbuffer, visibility_cutoff_xid, flags);
1590  }
1591 
1592  /*
1593  * As of PostgreSQL 9.2, the visibility map bit should never be set if
1594  * the page-level bit is clear. However, it's possible that the bit
1595  * got cleared after we checked it and before we took the buffer
1596  * content lock, so we must recheck before jumping to the conclusion
1597  * that something bad has happened.
1598  */
1599  else if (all_visible_according_to_vm && !PageIsAllVisible(page)
1600  && VM_ALL_VISIBLE(onerel, blkno, &vmbuffer))
1601  {
1602  elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u",
1603  vacrelstats->relname, blkno);
1604  visibilitymap_clear(onerel, blkno, vmbuffer,
1606  }
1607 
1608  /*
1609  * It's possible for the value returned by
1610  * GetOldestNonRemovableTransactionId() to move backwards, so it's not
1611  * wrong for us to see tuples that appear to not be visible to
1612  * everyone yet, while PD_ALL_VISIBLE is already set. The real safe
1613  * xmin value never moves backwards, but
1614  * GetOldestNonRemovableTransactionId() is conservative and sometimes
1615  * returns a value that's unnecessarily small, so if we see that
1616  * contradiction it just means that the tuples that we think are not
1617  * visible to everyone yet actually are, and the PD_ALL_VISIBLE flag
1618  * is correct.
1619  *
1620  * There should never be dead tuples on a page with PD_ALL_VISIBLE
1621  * set, however.
1622  */
1623  else if (PageIsAllVisible(page) && has_dead_tuples)
1624  {
1625  elog(WARNING, "page containing dead tuples is marked as all-visible in relation \"%s\" page %u",
1626  vacrelstats->relname, blkno);
1627  PageClearAllVisible(page);
1628  MarkBufferDirty(buf);
1629  visibilitymap_clear(onerel, blkno, vmbuffer,
1631  }
1632 
1633  /*
1634  * If the all-visible page is all-frozen but not marked as such yet,
1635  * mark it as all-frozen. Note that all_frozen is only valid if
1636  * all_visible is true, so we must check both.
1637  */
1638  else if (all_visible_according_to_vm && all_visible && all_frozen &&
1639  !VM_ALL_FROZEN(onerel, blkno, &vmbuffer))
1640  {
1641  /*
1642  * We can pass InvalidTransactionId as the cutoff XID here,
1643  * because setting the all-frozen bit doesn't cause recovery
1644  * conflicts.
1645  */
1646  visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr,
1647  vmbuffer, InvalidTransactionId,
1649  }
1650 
1651  UnlockReleaseBuffer(buf);
1652 
1653  /* Remember the location of the last page with nonremovable tuples */
1654  if (hastup)
1655  vacrelstats->nonempty_pages = blkno + 1;
1656 
1657  /*
1658  * If we remembered any tuples for deletion, then the page will be
1659  * visited again by lazy_vacuum_heap, which will compute and record
1660  * its post-compaction free space. If not, then we're done with this
1661  * page, so remember its free space as-is. (This path will always be
1662  * taken if there are no indexes.)
1663  */
1664  if (dead_tuples->num_tuples == prev_dead_count)
1665  RecordPageWithFreeSpace(onerel, blkno, freespace);
1666  }
1667 
1668  /* report that everything is scanned and vacuumed */
1670 
1671  /* Clear the block number information */
1672  vacrelstats->blkno = InvalidBlockNumber;
1673 
1674  pfree(frozen);
1675 
1676  /* save stats for use later */
1677  vacrelstats->tuples_deleted = tups_vacuumed;
1678  vacrelstats->new_dead_tuples = nkeep;
1679 
1680  /* now we can compute the new value for pg_class.reltuples */
1681  vacrelstats->new_live_tuples = vac_estimate_reltuples(onerel,
1682  nblocks,
1683  vacrelstats->tupcount_pages,
1684  live_tuples);
1685 
1686  /*
1687  * Also compute the total number of surviving heap entries. In the
1688  * (unlikely) scenario that new_live_tuples is -1, take it as zero.
1689  */
1690  vacrelstats->new_rel_tuples =
1691  Max(vacrelstats->new_live_tuples, 0) + vacrelstats->new_dead_tuples;
1692 
1693  /*
1694  * Release any remaining pin on visibility map page.
1695  */
1696  if (BufferIsValid(vmbuffer))
1697  {
1698  ReleaseBuffer(vmbuffer);
1699  vmbuffer = InvalidBuffer;
1700  }
1701 
1702  /* If any tuples need to be deleted, perform final vacuum cycle */
1703  /* XXX put a threshold on min number of tuples here? */
1704  if (dead_tuples->num_tuples > 0)
1705  {
1706  /* Work on all the indexes, and then the heap */
1707  lazy_vacuum_all_indexes(onerel, Irel, indstats, vacrelstats,
1708  lps, nindexes);
1709 
1710  /* Remove tuples from heap */
1711  lazy_vacuum_heap(onerel, vacrelstats);
1712  }
1713 
1714  /*
1715  * Vacuum the remainder of the Free Space Map. We must do this whether or
1716  * not there were indexes.
1717  */
1718  if (blkno > next_fsm_block_to_vacuum)
1719  FreeSpaceMapVacuumRange(onerel, next_fsm_block_to_vacuum, blkno);
1720 
1721  /* report all blocks vacuumed */
1723 
1724  /* Do post-vacuum cleanup */
1725  if (vacrelstats->useindex)
1726  lazy_cleanup_all_indexes(Irel, indstats, vacrelstats, lps, nindexes);
1727 
1728  /*
1729  * End parallel mode before updating index statistics as we cannot write
1730  * during parallel mode.
1731  */
1732  if (ParallelVacuumIsActive(lps))
1733  end_parallel_vacuum(indstats, lps, nindexes);
1734 
1735  /* Update index statistics */
1736  update_index_statistics(Irel, indstats, nindexes);
1737 
1738  /* If no indexes, make log report that lazy_vacuum_heap would've made */
1739  if (vacuumed_pages)
1740  ereport(elevel,
1741  (errmsg("\"%s\": removed %.0f row versions in %u pages",
1742  vacrelstats->relname,
1743  tups_vacuumed, vacuumed_pages)));
1744 
1745  /*
1746  * This is pretty messy, but we split it up so that we can skip emitting
1747  * individual parts of the message when not applicable.
1748  */
1749  initStringInfo(&buf);
1750  appendStringInfo(&buf,
1751  _("%.0f dead row versions cannot be removed yet, oldest xmin: %u\n"),
1752  nkeep, OldestXmin);
1753  appendStringInfo(&buf, _("There were %.0f unused item identifiers.\n"),
1754  nunused);
1755  appendStringInfo(&buf, ngettext("Skipped %u page due to buffer pins, ",
1756  "Skipped %u pages due to buffer pins, ",
1757  vacrelstats->pinskipped_pages),
1758  vacrelstats->pinskipped_pages);
1759  appendStringInfo(&buf, ngettext("%u frozen page.\n",
1760  "%u frozen pages.\n",
1761  vacrelstats->frozenskipped_pages),
1762  vacrelstats->frozenskipped_pages);
1763  appendStringInfo(&buf, ngettext("%u page is entirely empty.\n",
1764  "%u pages are entirely empty.\n",
1765  empty_pages),
1766  empty_pages);
1767  appendStringInfo(&buf, _("%s."), pg_rusage_show(&ru0));
1768 
1769  ereport(elevel,
1770  (errmsg("\"%s\": found %.0f removable, %.0f nonremovable row versions in %u out of %u pages",
1771  vacrelstats->relname,
1772  tups_vacuumed, num_tuples,
1773  vacrelstats->scanned_pages, nblocks),
1774  errdetail_internal("%s", buf.data)));
1775  pfree(buf.data);
1776 }
double new_rel_tuples
Definition: vacuumlazy.c:306
void HeapTupleHeaderAdvanceLatestRemovedXid(HeapTupleHeader tuple, TransactionId *latestRemovedXid)
Definition: heapam.c:6903
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer)
Definition: vacuumlazy.c:1924
void LockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:3809
XLogRecPtr log_heap_freeze(Relation reln, Buffer buffer, TransactionId cutoff_xid, xl_heap_freeze_tuple *tuples, int ntuples)
Definition: heapam.c:7223
#define PROGRESS_VACUUM_HEAP_BLKS_VACUUMED
Definition: progress.h:24
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define PageIsEmpty(page)
Definition: bufpage.h:222
int heap_page_prune(Relation relation, Buffer buffer, GlobalVisState *vistest, TransactionId old_snap_xmin, TimestampTz old_snap_ts, bool report_stats, TransactionId *latestRemovedXid, OffsetNumber *off_loc)
Definition: pruneheap.c:223
XLogRecPtr log_newpage_buffer(Buffer buffer, bool page_std)
Definition: xloginsert.c:1090
BlockNumber rel_pages
Definition: vacuumlazy.c:300
double vac_estimate_reltuples(Relation relation, BlockNumber total_pages, BlockNumber scanned_pages, double scanned_tuples)
Definition: vacuum.c:1141
OffsetNumber offset
Definition: heapam_xlog.h:320
static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1843
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:106
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
LVDeadTuples * dead_tuples
Definition: vacuumlazy.c:312
#define PageIsAllVisible(page)
Definition: bufpage.h:385
uint32 TransactionId
Definition: c.h:575
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:181
#define PROGRESS_VACUUM_MAX_DEAD_TUPLES
Definition: progress.h:26
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *buf)
double tuples_deleted
Definition: vacuumlazy.c:310
void visibilitymap_set(Relation rel, BlockNumber heapBlk, Buffer heapBuf, XLogRecPtr recptr, Buffer vmBuf, TransactionId cutoff_xid, uint8 flags)
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1471
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
#define VISIBILITYMAP_ALL_FROZEN
Definition: visibilitymap.h:27
static void lazy_record_dead_tuple(LVDeadTuples *dead_tuples, ItemPointer itemptr)
Definition: vacuumlazy.c:2897
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:654
bool useindex
Definition: vacuumlazy.c:297
BlockNumber tupcount_pages
Definition: vacuumlazy.c:304
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define ItemIdIsUsed(itemId)
Definition: itemid.h:92
#define MaxHeapTuplesPerPage
Definition: htup_details.h:574
#define VM_ALL_FROZEN(r, b, v)
Definition: visibilitymap.h:34
unsigned char uint8
Definition: c.h:427
#define PROGRESS_VACUUM_HEAP_BLKS_SCANNED
Definition: progress.h:23
#define InvalidBuffer
Definition: buf.h:25
char * relnamespace
Definition: vacuumlazy.c:294
#define PROGRESS_VACUUM_TOTAL_HEAP_BLKS
Definition: progress.h:22
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
BlockNumber scanned_pages
Definition: vacuumlazy.c:301
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3513
BlockNumber pinskipped_pages
Definition: vacuumlazy.c:302
#define SizeOfPageHeaderData
Definition: bufpage.h:216
Form_pg_class rd_rel
Definition: rel.h:110
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:357
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1062
uint16 OffsetNumber
Definition: off.h:24
#define VISIBILITYMAP_VALID_BITS
Definition: visibilitymap.h:28
HeapTupleHeader t_data
Definition: htup.h:68
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId relfrozenxid, TransactionId relminmxid, TransactionId cutoff_xid, TransactionId cutoff_multi, xl_heap_freeze_tuple *frz, bool *totally_frozen_p)
Definition: heapam.c:6126
#define FORCE_CHECK_PAGE()
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:676
GlobalVisState * GlobalVisTestFor(Relation rel)
Definition: procarray.c:3922
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ItemIdGetLength(itemId)
Definition: itemid.h:59
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer buf, uint8 flags)
#define VACUUM_FSM_EVERY_PAGES
Definition: vacuumlazy.c:111
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3536
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:3946
#define ERROR
Definition: elog.h:43
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:874
ItemPointerData t_self
Definition: htup.h:65
#define HeapTupleHeaderXminCommitted(tup)
Definition: htup_details.h:324
static TransactionId FreezeLimit
Definition: vacuumlazy.c:336
static void lazy_vacuum_all_indexes(Relation onerel, Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
Definition: vacuumlazy.c:1784
uint32 t_len
Definition: htup.h:64
void heap_execute_freeze_tuple(HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
Definition: heapam.c:6355
static char * buf
Definition: pg_test_fsync.c:68
#define PageSetAllVisible(page)
Definition: bufpage.h:387
#define FirstOffsetNumber
Definition: off.h:27
static MultiXactId MultiXactCutoff
Definition: vacuumlazy.c:337
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
static TransactionId OldestXmin
Definition: vacuumlazy.c:335
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple htup, TransactionId OldestXmin, Buffer buffer)
static bool lazy_check_needs_freeze(Buffer buf, bool *hastup, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2031
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
double new_live_tuples
Definition: vacuumlazy.c:307
VacOptTernaryValue index_cleanup
Definition: vacuum.h:221
#define SKIP_PAGES_THRESHOLD
Definition: vacuumlazy.c:125
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define WARNING
Definition: elog.h:40
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
static int elevel
Definition: vacuumlazy.c:333
#define ngettext(s, p, n)
Definition: c.h:1178
Size GetRecordedFreeSpace(Relation rel, BlockNumber heapBlk)
Definition: freespace.c:230
#define ParallelVacuumIsActive(lps)
Definition: vacuumlazy.c:148
void * palloc0(Size size)
Definition: mcxt.c:981
char * relname
Definition: vacuumlazy.c:295
#define BufferGetPageSize(buffer)
Definition: bufmgr.h:156
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3752
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
static void update_index_statistics(Relation *Irel, IndexBulkDeleteResult **stats, int nindexes)
Definition: vacuumlazy.c:3186
static void lazy_cleanup_all_indexes(Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
Definition: vacuumlazy.c:2376
#define InvalidOffsetNumber
Definition: off.h:26
static LVParallelState * begin_parallel_vacuum(Oid relid, Relation *Irel, LVRelStats *vacrelstats, BlockNumber nblocks, int nindexes, int nrequested)
Definition: vacuumlazy.c:3217
#define ereport(elevel,...)
Definition: elog.h:155
static void update_vacuum_error_info(LVRelStats *errinfo, LVSavedErrInfo *saved_err_info, int phase, BlockNumber blkno, OffsetNumber offnum)
Definition: vacuumlazy.c:3671
OffsetNumber offnum
Definition: vacuumlazy.c:320
#define Max(x, y)
Definition: c.h:976
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:339
#define PageClearAllVisible(page)
Definition: bufpage.h:389
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:685
#define Assert(condition)
Definition: c.h:800
double new_dead_tuples
Definition: vacuumlazy.c:308
TransactionId latestRemovedXid
Definition: vacuumlazy.c:314
#define ItemIdIsNormal(itemId)
Definition: itemid.h:99
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:313
#define VM_ALL_VISIBLE(r, b, v)
Definition: visibilitymap.h:32
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
Definition: pgstat.c:3399
#define OffsetNumberNext(offsetNumber)
Definition: off.h:52
size_t Size
Definition: c.h:528
#define PROGRESS_VACUUM_PHASE_SCAN_HEAP
Definition: progress.h:30
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
int nworkers
Definition: vacuum.h:231
#define InvalidBlockNumber
Definition: block.h:33
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
#define RelationNeedsWAL(relation)
Definition: rel.h:563
#define VISIBILITYMAP_ALL_VISIBLE
Definition: visibilitymap.h:26
#define RelationUsesLocalBuffers(relation)
Definition: rel.h:573
#define PageGetLSN(page)
Definition: bufpage.h:366
static void end_parallel_vacuum(IndexBulkDeleteResult **stats, LVParallelState *lps, int nindexes)
Definition: vacuumlazy.c:3401
BlockNumber nonempty_pages
Definition: vacuumlazy.c:311
#define PageIsNew(page)
Definition: bufpage.h:229
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:902
uint8 visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *buf)
BlockNumber frozenskipped_pages
Definition: vacuumlazy.c:303
#define elog(elevel,...)
Definition: elog.h:228
int i
int options
Definition: vacuum.h:210
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
void vacuum_delay_point(void)
Definition: vacuum.c:2031
BlockNumber blkno
Definition: vacuumlazy.c:319
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
int Buffer
Definition: buf.h:23
#define _(x)
Definition: elog.c:88
#define RelationGetRelid(relation)
Definition: rel.h:457
void FreeSpaceMapVacuumRange(Relation rel, BlockNumber start, BlockNumber end)
Definition: freespace.c:354
#define PageGetItem(page, itemId)
Definition: bufpage.h:340
Pointer Page
Definition: bufpage.h:78
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:127
static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks)
Definition: vacuumlazy.c:2879

◆ lazy_space_alloc()

static void lazy_space_alloc ( LVRelStats vacrelstats,
BlockNumber  relblocks 
)
static

Definition at line 2879 of file vacuumlazy.c.

References compute_max_dead_tuples(), LVRelStats::dead_tuples, LVDeadTuples::max_tuples, LVDeadTuples::num_tuples, palloc(), SizeOfDeadTuples, and LVRelStats::useindex.

Referenced by lazy_scan_heap().

2880 {
2881  LVDeadTuples *dead_tuples = NULL;
2882  long maxtuples;
2883 
2884  maxtuples = compute_max_dead_tuples(relblocks, vacrelstats->useindex);
2885 
2886  dead_tuples = (LVDeadTuples *) palloc(SizeOfDeadTuples(maxtuples));
2887  dead_tuples->num_tuples = 0;
2888  dead_tuples->max_tuples = (int) maxtuples;
2889 
2890  vacrelstats->dead_tuples = dead_tuples;
2891 }
LVDeadTuples * dead_tuples
Definition: vacuumlazy.c:312
#define SizeOfDeadTuples(cnt)
Definition: vacuumlazy.c:177
bool useindex
Definition: vacuumlazy.c:297
static long compute_max_dead_tuples(BlockNumber relblocks, bool hasindex)
Definition: vacuumlazy.c:2847
void * palloc(Size size)
Definition: mcxt.c:950

◆ lazy_tid_reaped()

static bool lazy_tid_reaped ( ItemPointer  itemptr,
void *  state 
)
static

Definition at line 2921 of file vacuumlazy.c.

References LVDeadTuples::itemptrs, LVDeadTuples::num_tuples, and vac_cmp_itemptr().

Referenced by lazy_vacuum_index().

2922 {
2923  LVDeadTuples *dead_tuples = (LVDeadTuples *) state;
2924  ItemPointer res;
2925 
2926  res = (ItemPointer) bsearch((void *) itemptr,
2927  (void *) dead_tuples->itemptrs,
2928  dead_tuples->num_tuples,
2929  sizeof(ItemPointerData),
2930  vac_cmp_itemptr);
2931 
2932  return (res != NULL);
2933 }
ItemPointerData itemptrs[FLEXIBLE_ARRAY_MEMBER]
Definition: vacuumlazy.c:172
ItemPointerData * ItemPointer
Definition: itemptr.h:49
Definition: regguts.h:298
static int vac_cmp_itemptr(const void *left, const void *right)
Definition: vacuumlazy.c:2939

◆ lazy_truncate_heap()

static void lazy_truncate_heap ( Relation  onerel,
LVRelStats vacrelstats 
)
static

Definition at line 2578 of file vacuumlazy.c.

References AccessExclusiveLock, LVRelStats::blkno, CHECK_FOR_INTERRUPTS, ConditionalLockRelation(), count_nondeletable_pages(), elevel, ereport, errdetail_internal(), errmsg(), LVRelStats::lock_waiter_detected, LVRelStats::nonempty_pages, LVRelStats::pages_removed, pg_rusage_init(), pg_rusage_show(), pg_usleep(), pgstat_progress_update_param(), PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_TRUNCATE, LVRelStats::rel_pages, RelationGetNumberOfBlocks, RelationTruncate(), LVRelStats::relname, UnlockRelation(), VACUUM_TRUNCATE_LOCK_TIMEOUT, and VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL.

Referenced by heap_vacuum_rel().

2579 {
2580  BlockNumber old_rel_pages = vacrelstats->rel_pages;
2581  BlockNumber new_rel_pages;
2582  int lock_retry;
2583 
2584  /* Report that we are now truncating */
2587 
2588  /*
2589  * Loop until no more truncating can be done.
2590  */
2591  do
2592  {
2593  PGRUsage ru0;
2594 
2595  pg_rusage_init(&ru0);
2596 
2597  /*
2598  * We need full exclusive lock on the relation in order to do
2599  * truncation. If we can't get it, give up rather than waiting --- we
2600  * don't want to block other backends, and we don't want to deadlock
2601  * (which is quite possible considering we already hold a lower-grade
2602  * lock).
2603  */
2604  vacrelstats->lock_waiter_detected = false;
2605  lock_retry = 0;
2606  while (true)
2607  {
2609  break;
2610 
2611  /*
2612  * Check for interrupts while trying to (re-)acquire the exclusive
2613  * lock.
2614  */
2616 
2617  if (++lock_retry > (VACUUM_TRUNCATE_LOCK_TIMEOUT /
2619  {
2620  /*
2621  * We failed to establish the lock in the specified number of
2622  * retries. This means we give up truncating.
2623  */
2624  vacrelstats->lock_waiter_detected = true;
2625  ereport(elevel,
2626  (errmsg("\"%s\": stopping truncate due to conflicting lock request",
2627  vacrelstats->relname)));
2628  return;
2629  }
2630 
2632  }
2633 
2634  /*
2635  * Now that we have exclusive lock, look to see if the rel has grown
2636  * whilst we were vacuuming with non-exclusive lock. If so, give up;
2637  * the newly added pages presumably contain non-deletable tuples.
2638  */
2639  new_rel_pages = RelationGetNumberOfBlocks(onerel);
2640  if (new_rel_pages != old_rel_pages)
2641  {
2642  /*
2643  * Note: we intentionally don't update vacrelstats->rel_pages with
2644  * the new rel size here. If we did, it would amount to assuming
2645  * that the new pages are empty, which is unlikely. Leaving the
2646  * numbers alone amounts to assuming that the new pages have the
2647  * same tuple density as existing ones, which is less unlikely.
2648  */
2650  return;
2651  }
2652 
2653  /*
2654  * Scan backwards from the end to verify that the end pages actually
2655  * contain no tuples. This is *necessary*, not optional, because
2656  * other backends could have added tuples to these pages whilst we
2657  * were vacuuming.
2658  */
2659  new_rel_pages = count_nondeletable_pages(onerel, vacrelstats);
2660  vacrelstats->blkno = new_rel_pages;
2661 
2662  if (new_rel_pages >= old_rel_pages)
2663  {
2664  /* can't do anything after all */
2666  return;
2667  }
2668 
2669  /*
2670  * Okay to truncate.
2671  */
2672  RelationTruncate(onerel, new_rel_pages);
2673 
2674  /*
2675  * We can release the exclusive lock as soon as we have truncated.
2676  * Other backends can't safely access the relation until they have
2677  * processed the smgr invalidation that smgrtruncate sent out ... but
2678  * that should happen as part of standard invalidation processing once
2679  * they acquire lock on the relation.
2680  */
2682 
2683  /*
2684  * Update statistics. Here, it *is* correct to adjust rel_pages
2685  * without also touching reltuples, since the tuple count wasn't
2686  * changed by the truncation.
2687  */
2688  vacrelstats->pages_removed += old_rel_pages - new_rel_pages;
2689  vacrelstats->rel_pages = new_rel_pages;
2690 
2691  ereport(elevel,
2692  (errmsg("\"%s\": truncated %u to %u pages",
2693  vacrelstats->relname,
2694  old_rel_pages, new_rel_pages),
2695  errdetail_internal("%s",
2696  pg_rusage_show(&ru0))));
2697  old_rel_pages = new_rel_pages;
2698  } while (new_rel_pages > vacrelstats->nonempty_pages &&
2699  vacrelstats->lock_waiter_detected);
2700 }
static BlockNumber count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2708
BlockNumber rel_pages
Definition: vacuumlazy.c:300
void UnlockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:282
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
#define VACUUM_TRUNCATE_LOCK_TIMEOUT
Definition: vacuumlazy.c:103
uint32 BlockNumber
Definition: block.h:31
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1062
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
#define PROGRESS_VACUUM_PHASE_TRUNCATE
Definition: progress.h:34
void pg_usleep(long microsec)
Definition: signal.c:53
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
bool ConditionalLockRelation(Relation relation, LOCKMODE lockmode)
Definition: lmgr.c:247
#define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL
Definition: vacuumlazy.c:102
static int elevel
Definition: vacuumlazy.c:333
char * relname
Definition: vacuumlazy.c:295
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:211
#define ereport(elevel,...)
Definition: elog.h:155
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
#define AccessExclusiveLock
Definition: lockdefs.h:45
BlockNumber pages_removed
Definition: vacuumlazy.c:309
BlockNumber nonempty_pages
Definition: vacuumlazy.c:311
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
BlockNumber blkno
Definition: vacuumlazy.c:319
void RelationTruncate(Relation rel, BlockNumber nblocks)
Definition: storage.c:277
bool lock_waiter_detected
Definition: vacuumlazy.c:315

◆ lazy_vacuum_all_indexes()

static void lazy_vacuum_all_indexes ( Relation  onerel,
Relation Irel,
IndexBulkDeleteResult **  stats,
LVRelStats vacrelstats,
LVParallelState lps,
int  nindexes 
)
static

Definition at line 1784 of file vacuumlazy.c.

References Assert, LVRelStats::dead_tuples, LVShared::estimated_count, LVShared::first_time, LVShared::for_cleanup, idx(), IsParallelWorker, lazy_parallel_vacuum_indexes(), lazy_vacuum_index(), LVParallelState::lvshared, LVRelStats::num_index_scans, LVRelStats::old_live_tuples, ParallelVacuumIsActive, pgstat_progress_update_param(), PROGRESS_VACUUM_NUM_INDEX_VACUUMS, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_VACUUM_INDEX, LVShared::reltuples, and vacuum_log_cleanup_info().

Referenced by lazy_scan_heap().

1788 {
1790  Assert(nindexes > 0);
1791 
1792  /* Log cleanup info before we touch indexes */
1793  vacuum_log_cleanup_info(onerel, vacrelstats);
1794 
1795  /* Report that we are now vacuuming indexes */
1798 
1799  /* Perform index vacuuming with parallel workers for parallel vacuum. */
1800  if (ParallelVacuumIsActive(lps))
1801  {
1802  /* Tell parallel workers to do index vacuuming */
1803  lps->lvshared->for_cleanup = false;
1804  lps->lvshared->first_time = false;
1805 
1806  /*
1807  * We can only provide an approximate value of num_heap_tuples in
1808  * vacuum cases.
1809  */
1810  lps->lvshared->reltuples = vacrelstats->old_live_tuples;
1811  lps->lvshared->estimated_count = true;
1812 
1813  lazy_parallel_vacuum_indexes(Irel, stats, vacrelstats, lps, nindexes);
1814  }
1815  else
1816  {
1817  int idx;
1818 
1819  for (idx = 0; idx < nindexes; idx++)
1820  lazy_vacuum_index(Irel[idx], &stats[idx], vacrelstats->dead_tuples,
1821  vacrelstats->old_live_tuples, vacrelstats);
1822  }
1823 
1824  /* Increase and report the number of index scans */
1825  vacrelstats->num_index_scans++;
1827  vacrelstats->num_index_scans);
1828 }
bool estimated_count
Definition: vacuumlazy.c:215
LVDeadTuples * dead_tuples
Definition: vacuumlazy.c:312
#define PROGRESS_VACUUM_PHASE_VACUUM_INDEX
Definition: progress.h:31
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
static void lazy_vacuum_index(Relation indrel, IndexBulkDeleteResult **stats, LVDeadTuples *dead_tuples, double reltuples, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2431
#define IsParallelWorker()
Definition: parallel.h:61
bool first_time
Definition: vacuumlazy.c:202
double reltuples
Definition: vacuumlazy.c:214
static void lazy_parallel_vacuum_indexes(Relation *Irel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats, LVParallelState *lps, int nindexes)
Definition: vacuumlazy.c:2091
#define ParallelVacuumIsActive(lps)
Definition: vacuumlazy.c:148
int num_index_scans
Definition: vacuumlazy.c:313
double old_live_tuples
Definition: vacuumlazy.c:305
static void vacuum_log_cleanup_info(Relation rel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:708
#define Assert(condition)
Definition: c.h:800
#define PROGRESS_VACUUM_NUM_INDEX_VACUUMS
Definition: progress.h:25
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
LVShared * lvshared
Definition: vacuumlazy.c:275
bool for_cleanup
Definition: vacuumlazy.c:201

◆ lazy_vacuum_heap()

static void lazy_vacuum_heap ( Relation  onerel,
LVRelStats vacrelstats 
)
static

Definition at line 1843 of file vacuumlazy.c.

References LVRelStats::blkno, buf, BufferGetPage, BufferIsValid, ConditionalLockBufferForCleanup(), LVRelStats::dead_tuples, elevel, ereport, errdetail_internal(), errmsg(), InvalidBlockNumber, InvalidBuffer, InvalidOffsetNumber, ItemPointerGetBlockNumber, LVDeadTuples::itemptrs, lazy_vacuum_page(), MAIN_FORKNUM, PageGetHeapFreeSpace(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_update_param(), PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_VACUUM_HEAP, RBM_NORMAL, ReadBufferExtended(), RecordPageWithFreeSpace(), ReleaseBuffer(), LVRelStats::relname, restore_vacuum_error_info(), UnlockReleaseBuffer(), update_vacuum_error_info(), vacuum_delay_point(), and VACUUM_ERRCB_PHASE_VACUUM_HEAP.

Referenced by lazy_scan_heap().

1844 {
1845  int tupindex;
1846  int npages;
1847  PGRUsage ru0;
1848  Buffer vmbuffer = InvalidBuffer;
1849  LVSavedErrInfo saved_err_info;
1850 
1851  /* Report that we are now vacuuming the heap */
1854 
1855  /* Update error traceback information */
1856  update_vacuum_error_info(vacrelstats, &saved_err_info, VACUUM_ERRCB_PHASE_VACUUM_HEAP,
1858 
1859  pg_rusage_init(&ru0);
1860  npages = 0;
1861 
1862  tupindex = 0;
1863  while (tupindex < vacrelstats->dead_tuples->num_tuples)
1864  {
1865  BlockNumber tblk;
1866  Buffer buf;
1867  Page page;
1868  Size freespace;
1869 
1871 
1872  tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples->itemptrs[tupindex]);
1873  vacrelstats->blkno = tblk;
1874  buf = ReadBufferExtended(onerel, MAIN_FORKNUM, tblk, RBM_NORMAL,
1875  vac_strategy);
1877  {
1878  ReleaseBuffer(buf);
1879  ++tupindex;
1880  continue;
1881  }
1882  tupindex = lazy_vacuum_page(onerel, tblk, buf, tupindex, vacrelstats,
1883  &vmbuffer);
1884 
1885  /* Now that we've compacted the page, record its available space */
1886  page = BufferGetPage(buf);
1887  freespace = PageGetHeapFreeSpace(page);
1888 
1889  UnlockReleaseBuffer(buf);
1890  RecordPageWithFreeSpace(onerel, tblk, freespace);
1891  npages++;
1892  }
1893 
1894  /* Clear the block number information */
1895  vacrelstats->blkno = InvalidBlockNumber;
1896 
1897  if (BufferIsValid(vmbuffer))
1898  {
1899  ReleaseBuffer(vmbuffer);
1900  vmbuffer = InvalidBuffer;
1901  }
1902 
1903  ereport(elevel,
1904  (errmsg("\"%s\": removed %d row versions in %d pages",
1905  vacrelstats->relname,
1906  tupindex, npages),
1907  errdetail_internal("%s", pg_rusage_show(&ru0))));
1908 
1909  /* Revert to the previous phase information for error traceback */
1910  restore_vacuum_error_info(vacrelstats, &saved_err_info);
1911 }
static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer)
Definition: vacuumlazy.c:1924
ItemPointerData itemptrs[FLEXIBLE_ARRAY_MEMBER]
Definition: vacuumlazy.c:172
LVDeadTuples * dead_tuples
Definition: vacuumlazy.c:312
void RecordPageWithFreeSpace(Relation rel, BlockNumber heapBlk, Size spaceAvail)
Definition: freespace.c:181
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:654
#define InvalidBuffer
Definition: buf.h:25
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3513
static void restore_vacuum_error_info(LVRelStats *errinfo, const LVSavedErrInfo *saved_err_info)
Definition: vacuumlazy.c:3690
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1062
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3536
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:3946
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:874
static char * buf
Definition: pg_test_fsync.c:68
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
static int elevel
Definition: vacuumlazy.c:333
char * relname
Definition: vacuumlazy.c:295
#define InvalidOffsetNumber
Definition: off.h:26
#define ereport(elevel,...)
Definition: elog.h:155
static void update_vacuum_error_info(LVRelStats *errinfo, LVSavedErrInfo *saved_err_info, int phase, BlockNumber blkno, OffsetNumber offnum)
Definition: vacuumlazy.c:3671
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:339
size_t Size
Definition: c.h:528
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
#define InvalidBlockNumber
Definition: block.h:33
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
int errmsg(const char *fmt,...)
Definition: elog.c:902
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
void vacuum_delay_point(void)
Definition: vacuum.c:2031
BlockNumber blkno
Definition: vacuumlazy.c:319
int Buffer
Definition: buf.h:23
#define PROGRESS_VACUUM_PHASE_VACUUM_HEAP
Definition: progress.h:32
Pointer Page
Definition: bufpage.h:78

◆ lazy_vacuum_index()

static void lazy_vacuum_index ( Relation  indrel,
IndexBulkDeleteResult **  stats,
LVDeadTuples dead_tuples,
double  reltuples,
LVRelStats vacrelstats 
)
static

Definition at line 2431 of file vacuumlazy.c.

References IndexVacuumInfo::analyze_only, Assert, elevel, ereport, errdetail_internal(), errmsg(), IndexVacuumInfo::estimated_count, IndexVacuumInfo::index, index_bulk_delete(), LVRelStats::indname, InvalidBlockNumber, InvalidOffsetNumber, lazy_tid_reaped(), IndexVacuumInfo::message_level, IndexVacuumInfo::num_heap_tuples, pfree(), pg_rusage_init(), pg_rusage_show(), pstrdup(), RelationGetRelationName, IndexVacuumInfo::report_progress, restore_vacuum_error_info(), IndexVacuumInfo::strategy, update_vacuum_error_info(), vac_strategy, and VACUUM_ERRCB_PHASE_VACUUM_INDEX.

Referenced by lazy_vacuum_all_indexes(), and vacuum_one_index().

2433 {
2434  IndexVacuumInfo ivinfo;
2435  PGRUsage ru0;
2436  LVSavedErrInfo saved_err_info;
2437 
2438  pg_rusage_init(&ru0);
2439 
2440  ivinfo.index = indrel;
2441  ivinfo.analyze_only = false;
2442  ivinfo.report_progress = false;
2443  ivinfo.estimated_count = true;
2444  ivinfo.message_level = elevel;
2445  ivinfo.num_heap_tuples = reltuples;
2446  ivinfo.strategy = vac_strategy;
2447 
2448  /*
2449  * Update error traceback information.
2450  *
2451  * The index name is saved during this phase and restored immediately
2452  * after this phase. See vacuum_error_callback.
2453  */
2454  Assert(vacrelstats->indname == NULL);
2455  vacrelstats->indname = pstrdup(RelationGetRelationName(indrel));
2456  update_vacuum_error_info(vacrelstats, &saved_err_info,
2459 
2460  /* Do bulk deletion */
2461  *stats = index_bulk_delete(&ivinfo, *stats,
2462  lazy_tid_reaped, (void *) dead_tuples);
2463 
2464  ereport(elevel,
2465  (errmsg("scanned index \"%s\" to remove %d row versions",
2466  vacrelstats->indname,
2467  dead_tuples->num_tuples),
2468  errdetail_internal("%s", pg_rusage_show(&ru0))));
2469 
2470  /* Revert to the previous phase information for error traceback */
2471  restore_vacuum_error_info(vacrelstats, &saved_err_info);
2472  pfree(vacrelstats->indname);
2473  vacrelstats->indname = NULL;
2474 }
static bool lazy_tid_reaped(ItemPointer itemptr, void *state)
Definition: vacuumlazy.c:2921
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bool analyze_only
Definition: genam.h:47
bool report_progress
Definition: genam.h:48
BufferAccessStrategy strategy
Definition: genam.h:52
Relation index
Definition: genam.h:46
static void restore_vacuum_error_info(LVRelStats *errinfo, const LVSavedErrInfo *saved_err_info)
Definition: vacuumlazy.c:3690
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1062
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
void pfree(void *pointer)
Definition: mcxt.c:1057
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define RelationGetRelationName(relation)
Definition: rel.h:491
static int elevel
Definition: vacuumlazy.c:333
char * indname
Definition: vacuumlazy.c:318
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:689
#define InvalidOffsetNumber
Definition: off.h:26
#define ereport(elevel,...)
Definition: elog.h:155
static void update_vacuum_error_info(LVRelStats *errinfo, LVSavedErrInfo *saved_err_info, int phase, BlockNumber blkno, OffsetNumber offnum)
Definition: vacuumlazy.c:3671
int message_level
Definition: genam.h:50
double num_heap_tuples
Definition: genam.h:51
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:339
#define Assert(condition)
Definition: c.h:800
#define InvalidBlockNumber
Definition: block.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:902
bool estimated_count
Definition: genam.h:49

◆ lazy_vacuum_page()

static int lazy_vacuum_page ( Relation  onerel,
BlockNumber  blkno,
Buffer  buffer,
int  tupindex,
LVRelStats vacrelstats,
Buffer vmbuffer 
)
static

Definition at line 1924 of file vacuumlazy.c.

References Assert, BufferGetPage, BufferIsValid, LVRelStats::dead_tuples, END_CRIT_SECTION, heap_page_is_all_visible(), InvalidOffsetNumber, InvalidXLogRecPtr, ItemIdSetUnused, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LVDeadTuples::itemptrs, LVRelStats::latestRemovedXid, log_heap_clean(), MarkBufferDirty(), MaxOffsetNumber, LVDeadTuples::num_tuples, PageGetItemId, PageIsAllVisible, PageRepairFragmentation(), PageSetAllVisible, PageSetLSN, pgstat_progress_update_param(), PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, RelationNeedsWAL, restore_vacuum_error_info(), START_CRIT_SECTION, update_vacuum_error_info(), VACUUM_ERRCB_PHASE_VACUUM_HEAP, VISIBILITYMAP_ALL_FROZEN, VISIBILITYMAP_ALL_VISIBLE, visibilitymap_get_status(), and visibilitymap_set().

Referenced by lazy_scan_heap(), and lazy_vacuum_heap().

1926 {
1927  LVDeadTuples *dead_tuples = vacrelstats->dead_tuples;
1928  Page page = BufferGetPage(buffer);
1929  OffsetNumber unused[MaxOffsetNumber];
1930  int uncnt = 0;
1931  TransactionId visibility_cutoff_xid;
1932  bool all_frozen;
1933  LVSavedErrInfo saved_err_info;
1934 
1936 
1937  /* Update error traceback information */
1938  update_vacuum_error_info(vacrelstats, &saved_err_info, VACUUM_ERRCB_PHASE_VACUUM_HEAP,
1939  blkno, InvalidOffsetNumber);
1940 
1942 
1943  for (; tupindex < dead_tuples->num_tuples; tupindex++)
1944  {
1945  BlockNumber tblk;
1946  OffsetNumber toff;
1947  ItemId itemid;
1948 
1949  tblk = ItemPointerGetBlockNumber(&dead_tuples->itemptrs[tupindex]);
1950  if (tblk != blkno)
1951  break; /* past end of tuples for this block */
1952  toff = ItemPointerGetOffsetNumber(&dead_tuples->itemptrs[tupindex]);
1953  itemid = PageGetItemId(page, toff);
1954  ItemIdSetUnused(itemid);
1955  unused[uncnt++] = toff;
1956  }
1957 
1959 
1960  /*
1961  * Mark buffer dirty before we write WAL.
1962  */
1963  MarkBufferDirty(buffer);
1964 
1965  /* XLOG stuff */
1966  if (RelationNeedsWAL(onerel))
1967  {
1968  XLogRecPtr recptr;
1969 
1970  recptr = log_heap_clean(onerel, buffer,
1971  NULL, 0, NULL, 0,
1972  unused, uncnt,
1973  vacrelstats->latestRemovedXid);
1974  PageSetLSN(page, recptr);
1975  }
1976 
1977  /*
1978  * End critical section, so we safely can do visibility tests (which
1979  * possibly need to perform IO and allocate memory!). If we crash now the
1980  * page (including the corresponding vm bit) might not be marked all
1981  * visible, but that's fine. A later vacuum will fix that.
1982  */
1983  END_CRIT_SECTION();
1984 
1985  /*
1986  * Now that we have removed the dead tuples from the page, once again
1987  * check if the page has become all-visible. The page is already marked
1988  * dirty, exclusively locked, and, if needed, a full page image has been
1989  * emitted in the log_heap_clean() above.
1990  */
1991  if (heap_page_is_all_visible(onerel, buffer, vacrelstats,
1992  &visibility_cutoff_xid,
1993  &all_frozen))
1994  PageSetAllVisible(page);
1995 
1996  /*
1997  * All the changes to the heap page have been done. If the all-visible
1998  * flag is now set, also set the VM all-visible bit (and, if possible, the
1999  * all-frozen bit) unless this has already been done previously.
2000  */
2001  if (PageIsAllVisible(page))
2002  {
2003  uint8 vm_status = visibilitymap_get_status(onerel, blkno, vmbuffer);
2004  uint8 flags = 0;
2005 
2006  /* Set the VM all-frozen bit to flag, if needed */
2007  if ((vm_status & VISIBILITYMAP_ALL_VISIBLE) == 0)
2008  flags |= VISIBILITYMAP_ALL_VISIBLE;
2009  if ((vm_status & VISIBILITYMAP_ALL_FROZEN) == 0 && all_frozen)
2010  flags |= VISIBILITYMAP_ALL_FROZEN;
2011 
2012  Assert(BufferIsValid(*vmbuffer));
2013  if (flags != 0)
2014  visibilitymap_set(onerel, blkno, buffer, InvalidXLogRecPtr,
2015  *vmbuffer, visibility_cutoff_xid, flags);
2016  }
2017 
2018  /* Revert to the previous phase information for error traceback */
2019  restore_vacuum_error_info(vacrelstats, &saved_err_info);
2020  return tupindex;
2021 }
#define PROGRESS_VACUUM_HEAP_BLKS_VACUUMED
Definition: progress.h:24
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
ItemPointerData itemptrs[FLEXIBLE_ARRAY_MEMBER]
Definition: vacuumlazy.c:172
LVDeadTuples * dead_tuples
Definition: vacuumlazy.c:312
#define PageIsAllVisible(page)
Definition: bufpage.h:385
uint32 TransactionId
Definition: c.h:575
void visibilitymap_set(Relation rel, BlockNumber heapBlk, Buffer heapBuf, XLogRecPtr recptr, Buffer vmBuf, TransactionId cutoff_xid, uint8 flags)
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1471
#define MaxOffsetNumber
Definition: off.h:28
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3377
#define VISIBILITYMAP_ALL_FROZEN
Definition: visibilitymap.h:27
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
unsigned char uint8
Definition: c.h:427
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
uint32 BlockNumber
Definition: block.h:31
static void restore_vacuum_error_info(LVRelStats *errinfo, const LVSavedErrInfo *saved_err_info)
Definition: vacuumlazy.c:3690
uint16 OffsetNumber
Definition: off.h:24
#define PageSetAllVisible(page)
Definition: bufpage.h:387
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:235
#define InvalidOffsetNumber
Definition: off.h:26
static void update_vacuum_error_info(LVRelStats *errinfo, LVSavedErrInfo *saved_err_info, int phase, BlockNumber blkno, OffsetNumber offnum)
Definition: vacuumlazy.c:3671
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:800
TransactionId latestRemovedXid
Definition: vacuumlazy.c:314
XLogRecPtr log_heap_clean(Relation reln, Buffer buffer, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused, TransactionId latestRemovedXid)
Definition: heapam.c:7172
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define RelationNeedsWAL(relation)
Definition: rel.h:563
#define VISIBILITYMAP_ALL_VISIBLE
Definition: visibilitymap.h:26
void PageRepairFragmentation(Page page)
Definition: bufpage.c:682
uint8 visibilitymap_get_status(Relation rel, BlockNumber heapBlk, Buffer *buf)
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98
#define ItemIdSetUnused(itemId)
Definition: itemid.h:128
static bool heap_page_is_all_visible(Relation rel, Buffer buf, LVRelStats *vacrelstats, TransactionId *visibility_cutoff_xid, bool *all_frozen)
Definition: vacuumlazy.c:2972
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
Pointer Page
Definition: bufpage.h:78

◆ parallel_vacuum_index()

static void parallel_vacuum_index ( Relation Irel,
IndexBulkDeleteResult **  stats,
LVShared lvshared,
LVDeadTuples dead_tuples,
int  nindexes,
LVRelStats vacrelstats 
)
static

Definition at line 2221 of file vacuumlazy.c.

References get_indstats(), LVShared::idx, idx(), pg_atomic_add_fetch_u32(), pg_atomic_fetch_add_u32(), pg_atomic_sub_fetch_u32(), skip_parallel_vacuum_index(), vacuum_one_index(), and VacuumActiveNWorkers.

Referenced by lazy_parallel_vacuum_indexes(), and parallel_vacuum_main().

2224 {
2225  /*
2226  * Increment the active worker count if we are able to launch any worker.
2227  */
2230 
2231  /* Loop until all indexes are vacuumed */
2232  for (;;)
2233  {
2234  int idx;
2235  LVSharedIndStats *shared_indstats;
2236 
2237  /* Get an index number to process */
2238  idx = pg_atomic_fetch_add_u32(&(lvshared->idx), 1);
2239 
2240  /* Done for all indexes? */
2241  if (idx >= nindexes)
2242  break;
2243 
2244  /* Get the index statistics of this index from DSM */
2245  shared_indstats = get_indstats(lvshared, idx);
2246 
2247  /*
2248  * Skip processing indexes that don't participate in parallel
2249  * operation
2250  */
2251  if (shared_indstats == NULL ||
2252  skip_parallel_vacuum_index(Irel[idx], lvshared))
2253  continue;
2254 
2255  /* Do vacuum or cleanup of the index */
2256  vacuum_one_index(Irel[idx], &(stats[idx]), lvshared, shared_indstats,
2257  dead_tuples, vacrelstats);
2258  }
2259 
2260  /*
2261  * We have completed the index vacuum so decrement the active worker
2262  * count.
2263  */
2266 }
pg_atomic_uint32 * VacuumActiveNWorkers
Definition: vacuum.c:77
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:401
static uint32 pg_atomic_add_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:386
Datum idx(PG_FUNCTION_ARGS)
Definition: _int_op.c:259
static bool skip_parallel_vacuum_index(Relation indrel, LVShared *lvshared)
Definition: vacuumlazy.c:3464
static LVSharedIndStats * get_indstats(LVShared *lvshared, int n)
Definition: vacuumlazy.c:3439
pg_atomic_uint32 idx
Definition: vacuumlazy.c:246
static uint32 pg_atomic_fetch_add_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:328
static void vacuum_one_index(Relation indrel, IndexBulkDeleteResult **stats, LVShared *lvshared, LVSharedIndStats *shared_indstats, LVDeadTuples *dead_tuples, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2316

◆ parallel_vacuum_main()

void parallel_vacuum_main ( dsm_segment seg,
shm_toc toc 
)

Definition at line 3504 of file vacuumlazy.c.

References LVShared::active_nworkers, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, LVShared::cost_balance, DEBUG1, debug_query_string, LVShared::elevel, elevel, elog, error_context_stack, LVShared::for_cleanup, get_namespace_name(), LVRelStats::indname, InstrEndParallelQuery(), InstrStartParallelQuery(), maintenance_work_mem, LVShared::maintenance_work_mem_worker, palloc0(), parallel_vacuum_index(), PARALLEL_VACUUM_KEY_BUFFER_USAGE, PARALLEL_VACUUM_KEY_DEAD_TUPLES, PARALLEL_VACUUM_KEY_QUERY_TEXT, PARALLEL_VACUUM_KEY_SHARED, PARALLEL_VACUUM_KEY_WAL_USAGE, ParallelWorkerNumber, pfree(), pgstat_report_activity(), LVRelStats::phase, ErrorContextCallback::previous, pstrdup(), RelationGetNamespace, RelationGetRelationName, LVShared::relid, LVRelStats::relname, LVRelStats::relnamespace, RowExclusiveLock, ShareUpdateExclusiveLock, shm_toc_lookup(), STATE_RUNNING, table_close(), table_open(), vac_close_indexes(), vac_open_indexes(), VACUUM_ERRCB_PHASE_UNKNOWN, vacuum_error_callback(), VacuumActiveNWorkers, VacuumCostActive, VacuumCostBalance, VacuumCostBalanceLocal, VacuumCostDelay, VacuumPageDirty, VacuumPageHit, VacuumPageMiss, and VacuumSharedCostBalance.

3505 {
3506  Relation onerel;
3507  Relation *indrels;
3508  LVShared *lvshared;
3509  LVDeadTuples *dead_tuples;
3510  BufferUsage *buffer_usage;
3511  WalUsage *wal_usage;
3512  int nindexes;
3513  char *sharedquery;
3514  IndexBulkDeleteResult **stats;
3515  LVRelStats vacrelstats;
3516  ErrorContextCallback errcallback;
3517 
3519  false);
3520  elevel = lvshared->elevel;
3521 
3522  if (lvshared->for_cleanup)
3523  elog(DEBUG1, "starting parallel vacuum worker for cleanup");
3524  else
3525  elog(DEBUG1, "starting parallel vacuum worker for bulk delete");
3526 
3527  /* Set debug_query_string for individual workers */
3528  sharedquery = shm_toc_lookup(toc, PARALLEL_VACUUM_KEY_QUERY_TEXT, true);
3529  debug_query_string = sharedquery;
3531 
3532  /*
3533  * Open table. The lock mode is the same as the leader process. It's
3534  * okay because the lock mode does not conflict among the parallel
3535  * workers.
3536  */
3537  onerel = table_open(lvshared->relid, ShareUpdateExclusiveLock);
3538 
3539  /*
3540  * Open all indexes. indrels are sorted in order by OID, which should be
3541  * matched to the leader's one.
3542  */
3543  vac_open_indexes(onerel, RowExclusiveLock, &nindexes, &indrels);
3544  Assert(nindexes > 0);
3545 
3546  /* Set dead tuple space */
3547  dead_tuples = (LVDeadTuples *) shm_toc_lookup(toc,
3549  false);
3550 
3551  /* Set cost-based vacuum delay */
3553  VacuumCostBalance = 0;
3554  VacuumPageHit = 0;
3555  VacuumPageMiss = 0;
3556  VacuumPageDirty = 0;
3558  VacuumSharedCostBalance = &(lvshared->cost_balance);
3559  VacuumActiveNWorkers = &(lvshared->active_nworkers);
3560 
3561  stats = (IndexBulkDeleteResult **)
3562  palloc0(nindexes * sizeof(IndexBulkDeleteResult *));
3563 
3564  if (lvshared->maintenance_work_mem_worker > 0)
3566 
3567  /*
3568  * Initialize vacrelstats for use as error callback arg by parallel
3569  * worker.
3570  */
3571  vacrelstats.relnamespace = get_namespace_name(RelationGetNamespace(onerel));
3572  vacrelstats.relname = pstrdup(RelationGetRelationName(onerel));
3573  vacrelstats.indname = NULL;
3574  vacrelstats.phase = VACUUM_ERRCB_PHASE_UNKNOWN; /* Not yet processing */
3575 
3576  /* Setup error traceback support for ereport() */
3577  errcallback.callback = vacuum_error_callback;
3578  errcallback.arg = &vacrelstats;
3579  errcallback.previous = error_context_stack;
3580  error_context_stack = &errcallback;
3581 
3582  /* Prepare to track buffer usage during parallel execution */
3584 
3585  /* Process indexes to perform vacuum/cleanup */
3586  parallel_vacuum_index(indrels, stats, lvshared, dead_tuples, nindexes,
3587  &vacrelstats);
3588 
3589  /* Report buffer/WAL usage during parallel execution */
3590  buffer_usage = shm_toc_lookup(toc, PARALLEL_VACUUM_KEY_BUFFER_USAGE, false);
3591  wal_usage = shm_toc_lookup(toc, PARALLEL_VACUUM_KEY_WAL_USAGE, false);
3593  &wal_usage[ParallelWorkerNumber]);
3594 
3595  /* Pop the error context stack */
3596  error_context_stack = errcallback.previous;
3597 
3598  vac_close_indexes(nindexes, indrels, RowExclusiveLock);
3600  pfree(stats);
3601 }
static void vacuum_error_callback(void *arg)
Definition: vacuumlazy.c:3607
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:2010
int64 VacuumPageMiss
Definition: globals.c:145
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
pg_atomic_uint32 * VacuumActiveNWorkers
Definition: vacuum.c:77
int VacuumCostBalance
Definition: globals.c:148
#define PARALLEL_VACUUM_KEY_DEAD_TUPLES
Definition: vacuumlazy.c:139
Oid relid
Definition: vacuumlazy.c:193
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3278
char * pstrdup(const char *in)
Definition: mcxt.c:1187
int64 VacuumPageHit
Definition: globals.c:144
char * relnamespace
Definition: vacuumlazy.c:294
VacErrPhase phase
Definition: vacuumlazy.c:321
int64 VacuumPageDirty
Definition: globals.c:146
int maintenance_work_mem_worker
Definition: vacuumlazy.c:225
void InstrEndParallelQuery(BufferUsage *bufusage, WalUsage *walusage)
Definition: instrument.c:189
void(* callback)(void *arg)
Definition: elog.h:243
struct ErrorContextCallback * previous
Definition: elog.h:242
#define PARALLEL_VACUUM_KEY_QUERY_TEXT
Definition: vacuumlazy.c:140
ErrorContextCallback * error_context_stack
Definition: elog.c:92
pg_atomic_uint32 cost_balance
Definition: vacuumlazy.c:232
void pfree(void *pointer)
Definition: mcxt.c:1057
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3196
#define RowExclusiveLock
Definition: lockdefs.h:38
int elevel
Definition: vacuumlazy.c:194
int ParallelWorkerNumber
Definition: parallel.c:112
#define RelationGetRelationName(relation)
Definition: rel.h:491
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:1967
const char * debug_query_string
Definition: postgres.c:88
int VacuumCostBalanceLocal
Definition: vacuum.c:78
pg_atomic_uint32 * VacuumSharedCostBalance
Definition: vacuum.c:76
void InstrStartParallelQuery(void)
Definition: instrument.c:181
static int elevel
Definition: vacuumlazy.c:333
void * palloc0(Size size)
Definition: mcxt.c:981
char * indname
Definition: vacuumlazy.c:318
char * relname
Definition: vacuumlazy.c:295
#define PARALLEL_VACUUM_KEY_SHARED
Definition: vacuumlazy.c:138
pg_atomic_uint32 active_nworkers
Definition: vacuumlazy.c:239
int maintenance_work_mem
Definition: globals.c:123
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define PARALLEL_VACUUM_KEY_BUFFER_USAGE
Definition: vacuumlazy.c:141
#define Assert(condition)
Definition: c.h:800
#define PARALLEL_VACUUM_KEY_WAL_USAGE
Definition: vacuumlazy.c:142
bool for_cleanup
Definition: vacuumlazy.c:201
double VacuumCostDelay
Definition: globals.c:142
#define elog(elevel,...)
Definition: elog.h:228
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition: shm_toc.c:232
bool VacuumCostActive
Definition: globals.c:149
#define RelationGetNamespace(relation)
Definition: rel.h:498
static void parallel_vacuum_index(Relation *Irel, IndexBulkDeleteResult **stats, LVShared *lvshared, LVDeadTuples *dead_tuples, int nindexes, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2221

◆ prepare_index_statistics()

static void prepare_index_statistics ( LVShared lvshared,
bool can_parallel_vacuum,
int  nindexes 
)
static

Definition at line 3161 of file vacuumlazy.c.

References Assert, LVShared::bitmap, BITMAPLEN, i, and IsAutoVacuumWorkerProcess().

Referenced by begin_parallel_vacuum().

3163 {
3164  int i;
3165 
3166  /* Currently, we don't support parallel vacuum for autovacuum */
3168 
3169  /* Set NULL for all indexes */
3170  memset(lvshared->bitmap, 0x00, BITMAPLEN(nindexes));
3171 
3172  for (i = 0; i < nindexes; i++)
3173  {
3174  if (!can_parallel_vacuum[i])
3175  continue;
3176 
3177  /* Set NOT NULL as this index does support parallelism */
3178  lvshared->bitmap[i >> 3] |= 1 << (i & 0x07);
3179  }
3180 }
#define BITMAPLEN(NATTS)
Definition: htup_details.h:547
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3325
#define Assert(condition)
Definition: c.h:800
bits8 bitmap[FLEXIBLE_ARRAY_MEMBER]
Definition: vacuumlazy.c:248
int i

◆ restore_vacuum_error_info()

static void restore_vacuum_error_info ( LVRelStats errinfo,
const LVSavedErrInfo saved_err_info 
)
static

Definition at line 3690 of file vacuumlazy.c.

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

Referenced by lazy_cleanup_index(), lazy_vacuum_heap(), lazy_vacuum_index(), and lazy_vacuum_page().

3691 {
3692  errinfo->blkno = saved_err_info->blkno;
3693  errinfo->offnum = saved_err_info->offnum;
3694  errinfo->phase = saved_err_info->phase;
3695 }
VacErrPhase phase
Definition: vacuumlazy.c:321
OffsetNumber offnum
Definition: vacuumlazy.c:328
BlockNumber blkno
Definition: vacuumlazy.c:327
VacErrPhase phase
Definition: vacuumlazy.c:329
OffsetNumber offnum
Definition: vacuumlazy.c:320
BlockNumber blkno
Definition: vacuumlazy.c:319

◆ should_attempt_truncation()

static bool should_attempt_truncation ( VacuumParams params,
LVRelStats vacrelstats 
)
static

Definition at line 2557 of file vacuumlazy.c.

References LVRelStats::nonempty_pages, old_snapshot_threshold, LVRelStats::rel_pages, REL_TRUNCATE_FRACTION, REL_TRUNCATE_MINIMUM, VacuumParams::truncate, and VACOPT_TERNARY_DISABLED.

Referenced by heap_vacuum_rel().

2558 {
2559  BlockNumber possibly_freeable;
2560 
2561  if (params->truncate == VACOPT_TERNARY_DISABLED)
2562  return false;
2563 
2564  possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages;
2565  if (possibly_freeable > 0 &&
2566  (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
2567  possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION) &&
2569  return true;
2570  else
2571  return false;
2572 }
BlockNumber rel_pages
Definition: vacuumlazy.c:300
uint32 BlockNumber
Definition: block.h:31
#define REL_TRUNCATE_MINIMUM
Definition: vacuumlazy.c:91
VacOptTernaryValue truncate
Definition: vacuum.h:223
BlockNumber nonempty_pages
Definition: vacuumlazy.c:311
int old_snapshot_threshold
Definition: snapmgr.c:78
#define REL_TRUNCATE_FRACTION
Definition: vacuumlazy.c:92

◆ skip_parallel_vacuum_index()

static bool skip_parallel_vacuum_index ( Relation  indrel,
LVShared lvshared 
)
static

Definition at line 3464 of file vacuumlazy.c.

References IndexAmRoutine::amparallelvacuumoptions, Assert, LVShared::first_time, LVShared::for_cleanup, RelationData::rd_indam, VACUUM_OPTION_PARALLEL_BULKDEL, VACUUM_OPTION_PARALLEL_CLEANUP, and VACUUM_OPTION_PARALLEL_COND_CLEANUP.

Referenced by parallel_vacuum_index(), and vacuum_indexes_leader().

3465 {
3466  uint8 vacoptions = indrel->rd_indam->amparallelvacuumoptions;
3467 
3468  /* first_time must be true only if for_cleanup is true */
3469  Assert(lvshared->for_cleanup || !lvshared->first_time);
3470 
3471  if (lvshared->for_cleanup)
3472  {
3473  /* Skip, if the index does not support parallel cleanup */
3474  if (((vacoptions & VACUUM_OPTION_PARALLEL_CLEANUP) == 0) &&
3475  ((vacoptions & VACUUM_OPTION_PARALLEL_COND_CLEANUP) == 0))
3476  return true;
3477 
3478  /*
3479  * Skip, if the index supports parallel cleanup conditionally, but we
3480  * have already processed the index (for bulkdelete). See the
3481  * comments for option VACUUM_OPTION_PARALLEL_COND_CLEANUP to know
3482  * when indexes support parallel cleanup conditionally.
3483  */
3484  if (!lvshared->first_time &&
3485  ((vacoptions & VACUUM_OPTION_PARALLEL_COND_CLEANUP) != 0))
3486  return true;
3487  }
3488  else if ((vacoptions & VACUUM_OPTION_PARALLEL_BULKDEL) == 0)
3489  {
3490  /* Skip if the index does not support parallel bulk deletion */
3491  return true;
3492  }
3493 
3494  return false;
3495 }
uint8 amparallelvacuumoptions
Definition: amapi.h:247
struct IndexAmRoutine * rd_indam
Definition: rel.h:189
unsigned char uint8
Definition: c.h:427
bool first_time
Definition: vacuumlazy.c:202
#define Assert(condition)
Definition: c.h:800
#define VACUUM_OPTION_PARALLEL_COND_CLEANUP
Definition: vacuum.h:52
#define VACUUM_OPTION_PARALLEL_BULKDEL
Definition: vacuum.h:45
bool for_cleanup
Definition: vacuumlazy.c:201
#define VACUUM_OPTION_PARALLEL_CLEANUP
Definition: vacuum.h:60

◆ update_index_statistics()

static void update_index_statistics ( Relation Irel,
IndexBulkDeleteResult **  stats,
int  nindexes 
)
static

Definition at line 3186 of file vacuumlazy.c.

References Assert, i, InvalidMultiXactId, InvalidTransactionId, IsInParallelMode(), pfree(), and vac_update_relstats().

Referenced by lazy_scan_heap().

3188 {
3189  int i;
3190 
3192 
3193  for (i = 0; i < nindexes; i++)
3194  {
3195  if (stats[i] == NULL || stats[i]->estimated_count)
3196  continue;
3197 
3198  /* Update index statistics */
3199  vac_update_relstats(Irel[i],
3200  stats[i]->num_pages,
3201  stats[i]->num_index_tuples,
3202  0,
3203  false,
3206  false);
3207  pfree(stats[i]);
3208  }
3209 }
void pfree(void *pointer)
Definition: mcxt.c:1057
bool IsInParallelMode(void)
Definition: xact.c:1012
#define InvalidTransactionId
Definition: transam.h:31
#define InvalidMultiXactId
Definition: multixact.h:24
#define Assert(condition)
Definition: c.h:800
int i
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool in_outer_xact)
Definition: vacuum.c:1224

◆ update_vacuum_error_info()

static void update_vacuum_error_info ( LVRelStats errinfo,
LVSavedErrInfo saved_err_info,
int  phase,
BlockNumber  blkno,
OffsetNumber  offnum 
)
static

Definition at line 3671 of file vacuumlazy.c.

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

Referenced by heap_vacuum_rel(), lazy_cleanup_index(), lazy_scan_heap(), lazy_vacuum_heap(), lazy_vacuum_index(), and lazy_vacuum_page().

3673 {
3674  if (saved_err_info)
3675  {
3676  saved_err_info->offnum = errinfo->offnum;
3677  saved_err_info->blkno = errinfo->blkno;
3678  saved_err_info->phase = errinfo->phase;
3679  }
3680 
3681  errinfo->blkno = blkno;
3682  errinfo->offnum = offnum;
3683  errinfo->phase = phase;
3684 }
VacErrPhase phase
Definition: vacuumlazy.c:321
OffsetNumber offnum
Definition: vacuumlazy.c:328
BlockNumber blkno
Definition: vacuumlazy.c:327
VacErrPhase phase
Definition: vacuumlazy.c:329
OffsetNumber offnum
Definition: vacuumlazy.c:320
BlockNumber blkno
Definition: vacuumlazy.c:319

◆ vac_cmp_itemptr()

static int vac_cmp_itemptr ( const void *  left,
const void *  right 
)
static

Definition at line 2939 of file vacuumlazy.c.

References ItemPointerGetBlockNumber, and ItemPointerGetOffsetNumber.

Referenced by lazy_tid_reaped().

2940 {
2941  BlockNumber lblk,
2942  rblk;
2943  OffsetNumber loff,
2944  roff;
2945 
2946  lblk = ItemPointerGetBlockNumber((ItemPointer) left);
2947  rblk = ItemPointerGetBlockNumber((ItemPointer) right);
2948 
2949  if (lblk < rblk)
2950  return -1;
2951  if (lblk > rblk)
2952  return 1;
2953 
2954  loff = ItemPointerGetOffsetNumber((ItemPointer) left);
2955  roff = ItemPointerGetOffsetNumber((ItemPointer) right);
2956 
2957  if (loff < roff)
2958  return -1;
2959  if (loff > roff)
2960  return 1;
2961 
2962  return 0;
2963 }
uint32 BlockNumber
Definition: block.h:31
uint16 OffsetNumber
Definition: off.h:24
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:117
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:98

◆ vacuum_error_callback()

static void vacuum_error_callback ( void *  arg)
static

Definition at line 3607 of file vacuumlazy.c.

References arg, LVRelStats::blkno, BlockNumberIsValid, errcontext, LVRelStats::indname, LVRelStats::offnum, OffsetNumberIsValid, LVRelStats::phase, LVRelStats::relname, LVRelStats::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(), and parallel_vacuum_main().

3608 {
3609  LVRelStats *errinfo = arg;
3610 
3611  switch (errinfo->phase)
3612  {
3614  if (BlockNumberIsValid(errinfo->blkno))
3615  {
3616  if (OffsetNumberIsValid(errinfo->offnum))
3617  errcontext("while scanning block %u and offset %u of relation \"%s.%s\"",
3618  errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
3619  else
3620  errcontext("while scanning block %u of relation \"%s.%s\"",
3621  errinfo->blkno, errinfo->relnamespace, errinfo->relname);
3622  }
3623  else
3624  errcontext("while scanning relation \"%s.%s\"",
3625  errinfo->relnamespace, errinfo->relname);
3626  break;
3627 
3629  if (BlockNumberIsValid(errinfo->blkno))
3630  {
3631  if (OffsetNumberIsValid(errinfo->offnum))
3632  errcontext("while vacuuming block %u and offset %u of relation \"%s.%s\"",
3633  errinfo->blkno, errinfo->offnum, errinfo->relnamespace, errinfo->relname);
3634  else
3635  errcontext("while vacuuming block %u of relation \"%s.%s\"",
3636  errinfo->blkno, errinfo->relnamespace, errinfo->relname);
3637  }
3638  else
3639  errcontext("while vacuuming relation \"%s.%s\"",
3640  errinfo->relnamespace, errinfo->relname);
3641  break;
3642 
3644  errcontext("while vacuuming index \"%s\" of relation \"%s.%s\"",
3645  errinfo->indname, errinfo->relnamespace, errinfo->relname);
3646  break;
3647 
3649  errcontext("while cleaning up index \"%s\" of relation \"%s.%s\"",
3650  errinfo->indname, errinfo->relnamespace, errinfo->relname);
3651  break;
3652 
3654  if (BlockNumberIsValid(errinfo->blkno))
3655  errcontext("while truncating relation \"%s.%s\" to %u blocks",
3656  errinfo->relnamespace, errinfo->relname, errinfo->blkno);
3657  break;
3658 
3660  default:
3661  return; /* do nothing; the errinfo may not be
3662  * initialized */
3663  }
3664 }
char * relnamespace
Definition: vacuumlazy.c:294
VacErrPhase phase
Definition: vacuumlazy.c:321
char * indname
Definition: vacuumlazy.c:318
char * relname
Definition: vacuumlazy.c:295
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
OffsetNumber offnum
Definition: vacuumlazy.c:320
#define OffsetNumberIsValid(offsetNumber)
Definition: off.h:39
#define errcontext
Definition: elog.h:199
void * arg
BlockNumber blkno
Definition: vacuumlazy.c:319

◆ vacuum_indexes_leader()

static void vacuum_indexes_leader ( Relation Irel,
IndexBulkDeleteResult **  stats,
LVRelStats vacrelstats,
LVParallelState lps,
int  nindexes 
)
static

Definition at line 2273 of file vacuumlazy.c.

References Assert, LVRelStats::dead_tuples, get_indstats(), i, IsParallelWorker, LVParallelState::lvshared, pg_atomic_add_fetch_u32(), pg_atomic_sub_fetch_u32(), skip_parallel_vacuum_index(), vacuum_one_index(), and VacuumActiveNWorkers.

Referenced by lazy_parallel_vacuum_indexes().

2276 {
2277  int i;
2278 
2280 
2281  /*
2282  * Increment the active worker count if we are able to launch any worker.
2283  */
2286 
2287  for (i = 0; i < nindexes; i++)
2288  {
2289  LVSharedIndStats *shared_indstats;
2290 
2291  shared_indstats = get_indstats(lps->lvshared, i);
2292 
2293  /* Process the indexes skipped by parallel workers */
2294  if (shared_indstats == NULL ||
2295  skip_parallel_vacuum_index(Irel[i], lps->lvshared))
2296  vacuum_one_index(Irel[i], &(stats[i]), lps->lvshared,
2297  shared_indstats, vacrelstats->dead_tuples,
2298  vacrelstats);
2299  }
2300 
2301  /*
2302  * We have completed the index vacuum so decrement the active worker
2303  * count.
2304  */
2307 }
pg_atomic_uint32 * VacuumActiveNWorkers
Definition: vacuum.c:77
LVDeadTuples * dead_tuples
Definition: vacuumlazy.c:312
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:401
static uint32 pg_atomic_add_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:386
static bool skip_parallel_vacuum_index(Relation indrel, LVShared *lvshared)
Definition: vacuumlazy.c:3464
static LVSharedIndStats * get_indstats(LVShared *lvshared, int n)
Definition: vacuumlazy.c:3439
#define IsParallelWorker()
Definition: parallel.h:61
#define Assert(condition)
Definition: c.h:800
LVShared * lvshared
Definition: vacuumlazy.c:275
int i
static void vacuum_one_index(Relation indrel, IndexBulkDeleteResult **stats, LVShared *lvshared, LVSharedIndStats *shared_indstats, LVDeadTuples *dead_tuples, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:2316

◆ vacuum_log_cleanup_info()

static void vacuum_log_cleanup_info ( Relation  rel,
LVRelStats vacrelstats 
)
static

Definition at line 708 of file vacuumlazy.c.

References LVRelStats::latestRemovedXid, log_heap_cleanup_info(), RelationData::rd_node, RelationNeedsWAL, TransactionIdIsValid, and XLogIsNeeded.

Referenced by lazy_vacuum_all_indexes().

709 {
710  /*
711  * Skip this for relations for which no WAL is to be written, or if we're
712  * not trying to support archive recovery.
713  */
714  if (!RelationNeedsWAL(rel) || !XLogIsNeeded())
715  return;
716 
717  /*
718  * No need to write the record at all unless it contains a valid value
719  */
720  if (TransactionIdIsValid(vacrelstats->latestRemovedXid))
721  (void) log_heap_cleanup_info(rel->rd_node, vacrelstats->latestRemovedXid);
722 }
XLogRecPtr log_heap_cleanup_info(RelFileNode rnode, TransactionId latestRemovedXid)
Definition: heapam.c:7143
#define XLogIsNeeded()
Definition: xlog.h:191
RelFileNode rd_node
Definition: rel.h:55
TransactionId latestRemovedXid
Definition: vacuumlazy.c:314
#define RelationNeedsWAL(relation)
Definition: rel.h:563
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ vacuum_one_index()

static void vacuum_one_index ( Relation  indrel,
IndexBulkDeleteResult **  stats,
LVShared lvshared,
LVSharedIndStats shared_indstats,
LVDeadTuples dead_tuples,
LVRelStats vacrelstats 
)
static

Definition at line 2316 of file vacuumlazy.c.

References LVShared::estimated_count, LVShared::for_cleanup, lazy_cleanup_index(), lazy_vacuum_index(), pfree(), LVShared::reltuples, LVSharedIndStats::stats, and LVSharedIndStats::updated.

Referenced by parallel_vacuum_index(), and vacuum_indexes_leader().

2319 {
2320  IndexBulkDeleteResult *bulkdelete_res = NULL;
2321 
2322  if (shared_indstats)
2323  {