PostgreSQL Source Code  git master
autovacuum.c File Reference
#include "postgres.h"
#include <signal.h>
#include <sys/time.h>
#include <unistd.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/reloptions.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/dependency.h"
#include "catalog/namespace.h"
#include "catalog/pg_database.h"
#include "catalog/pg_inherits.h"
#include "commands/dbcommands.h"
#include "commands/vacuum.h"
#include "lib/ilist.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/fork_process.h"
#include "postmaster/interrupt.h"
#include "postmaster/postmaster.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lmgr.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/sinvaladt.h"
#include "storage/smgr.h"
#include "tcop/tcopprot.h"
#include "utils/fmgroids.h"
#include "utils/fmgrprotos.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
Include dependency graph for autovacuum.c:

Go to the source code of this file.

Data Structures

struct  avl_dbase
 
struct  avw_dbase
 
struct  av_relation
 
struct  autovac_table
 
struct  WorkerInfoData
 
struct  AutoVacuumWorkItem
 
struct  AutoVacuumShmemStruct
 

Macros

#define STATS_READ_DELAY   1000
 
#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */
 
#define MAX_AUTOVAC_SLEEPTIME   300 /* seconds */
 
#define NUM_WORKITEMS   256
 
#define MAX_AUTOVAC_ACTIV_LEN   (NAMEDATALEN * 2 + 56)
 

Typedefs

typedef struct avl_dbase avl_dbase
 
typedef struct avw_dbase avw_dbase
 
typedef struct av_relation av_relation
 
typedef struct autovac_table autovac_table
 
typedef struct WorkerInfoData WorkerInfoData
 
typedef struct WorkerInfoDataWorkerInfo
 
typedef struct AutoVacuumWorkItem AutoVacuumWorkItem
 

Enumerations

enum  AutoVacuumSignal { AutoVacForkFailed, AutoVacRebalance, AutoVacNumSignals }
 

Functions

NON_EXEC_STATIC void AutoVacWorkerMain (int argc, char *argv[]) pg_attribute_noreturn()
 
NON_EXEC_STATIC void AutoVacLauncherMain (int argc, char *argv[]) pg_attribute_noreturn()
 
static Oid do_start_worker (void)
 
static void HandleAutoVacLauncherInterrupts (void)
 
static void AutoVacLauncherShutdown (void)
 
static void launcher_determine_sleep (bool canlaunch, bool recursing, struct timeval *nap)
 
static void rebuild_database_list (Oid newdb)
 
static int db_comparator (const void *a, const void *b)
 
static void launch_worker (TimestampTz now)
 
void AutoVacWorkerFailed (void)
 
static void avl_sigusr2_handler (SIGNAL_ARGS)
 
int StartAutoVacWorker (void)
 
static void FreeWorkerInfo (int code, Datum arg)
 
void AutoVacuumUpdateDelay (void)
 
static void autovac_balance_cost (void)
 
static Listget_database_list (void)
 
static void do_autovacuum (void)
 
static void perform_work_item (AutoVacuumWorkItem *workitem)
 
static AutoVacOptsextract_autovac_opts (HeapTuple tup, TupleDesc pg_class_desc)
 
static PgStat_StatTabEntryget_pgstat_tabentry_relid (Oid relid, bool isshared, PgStat_StatDBEntry *shared, PgStat_StatDBEntry *dbentry)
 
static autovac_tabletable_recheck_autovac (Oid relid, HTAB *table_toast_map, TupleDesc pg_class_desc, int effective_multixact_freeze_max_age)
 
static void recheck_relation_needs_vacanalyze (Oid relid, AutoVacOpts *avopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
 
static void relation_needs_vacanalyze (Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, PgStat_StatTabEntry *tabentry, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
 
static void autovacuum_do_vac_analyze (autovac_table *tab, BufferAccessStrategy bstrategy)
 
static void autovac_report_activity (autovac_table *tab)
 
static void autovac_report_workitem (AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
 
bool AutoVacuumingActive (void)
 
bool AutoVacuumRequestWork (AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
 
void autovac_init (void)
 
bool IsAutoVacuumLauncherProcess (void)
 
bool IsAutoVacuumWorkerProcess (void)
 
Size AutoVacuumShmemSize (void)
 
void AutoVacuumShmemInit (void)
 
static void autovac_refresh_stats (void)
 

Variables

bool autovacuum_start_daemon = false
 
int autovacuum_max_workers
 
int autovacuum_work_mem = -1
 
int autovacuum_naptime
 
int autovacuum_vac_thresh
 
double autovacuum_vac_scale
 
int autovacuum_vac_ins_thresh
 
double autovacuum_vac_ins_scale
 
int autovacuum_anl_thresh
 
double autovacuum_anl_scale
 
int autovacuum_freeze_max_age
 
int autovacuum_multixact_freeze_max_age
 
double autovacuum_vac_cost_delay
 
int autovacuum_vac_cost_limit
 
int Log_autovacuum_min_duration = -1
 
static bool am_autovacuum_launcher = false
 
static bool am_autovacuum_worker = false
 
static volatile sig_atomic_t got_SIGUSR2 = false
 
static TransactionId recentXid
 
static MultiXactId recentMulti
 
static int default_freeze_min_age
 
static int default_freeze_table_age
 
static int default_multixact_freeze_min_age
 
static int default_multixact_freeze_table_age
 
static MemoryContext AutovacMemCxt
 
static AutoVacuumShmemStructAutoVacuumShmem
 
static dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
 
static MemoryContext DatabaseListCxt = NULL
 
static WorkerInfo MyWorkerInfo = NULL
 
int AutovacuumLauncherPid = 0
 

Macro Definition Documentation

◆ MAX_AUTOVAC_ACTIV_LEN

#define MAX_AUTOVAC_ACTIV_LEN   (NAMEDATALEN * 2 + 56)

◆ MAX_AUTOVAC_SLEEPTIME

#define MAX_AUTOVAC_SLEEPTIME   300 /* seconds */

Definition at line 138 of file autovacuum.c.

Referenced by launcher_determine_sleep().

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 137 of file autovacuum.c.

Referenced by launcher_determine_sleep(), and rebuild_database_list().

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

Definition at line 265 of file autovacuum.c.

Referenced by AutoVacuumRequestWork(), AutoVacuumShmemInit(), and do_autovacuum().

◆ STATS_READ_DELAY

#define STATS_READ_DELAY   1000

Definition at line 134 of file autovacuum.c.

Referenced by autovac_refresh_stats().

Typedef Documentation

◆ autovac_table

typedef struct autovac_table autovac_table

◆ AutoVacuumWorkItem

◆ av_relation

typedef struct av_relation av_relation

◆ avl_dbase

typedef struct avl_dbase avl_dbase

◆ avw_dbase

typedef struct avw_dbase avw_dbase

◆ WorkerInfo

typedef struct WorkerInfoData* WorkerInfo

Definition at line 235 of file autovacuum.c.

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 
AutoVacNumSignals 

Definition at line 242 of file autovacuum.c.

243 {
244  AutoVacForkFailed, /* failed trying to start a worker */
245  AutoVacRebalance, /* rebalance the cost limits */
246  AutoVacNumSignals /* must be last */
AutoVacuumSignal
Definition: autovacuum.c:242

Function Documentation

◆ autovac_balance_cost()

static void autovac_balance_cost ( void  )
static

Definition at line 1796 of file autovacuum.c.

References autovacuum_vac_cost_delay, autovacuum_vac_cost_limit, AutoVacuumShmemStruct::av_runningWorkers, dlist_iter::cur, DEBUG2, dlist_container, dlist_foreach, elog, Max, Min, PGPROC::pid, VacuumCostDelay, VacuumCostLimit, WorkerInfoData::wi_cost_delay, WorkerInfoData::wi_cost_limit, WorkerInfoData::wi_cost_limit_base, WorkerInfoData::wi_dboid, WorkerInfoData::wi_dobalance, WorkerInfoData::wi_proc, and WorkerInfoData::wi_tableoid.

Referenced by AutoVacLauncherMain(), do_autovacuum(), and HandleAutoVacLauncherInterrupts().

1797 {
1798  /*
1799  * The idea here is that we ration out I/O equally. The amount of I/O
1800  * that a worker can consume is determined by cost_limit/cost_delay, so we
1801  * try to equalize those ratios rather than the raw limit settings.
1802  *
1803  * note: in cost_limit, zero also means use value from elsewhere, because
1804  * zero is not a valid value.
1805  */
1806  int vac_cost_limit = (autovacuum_vac_cost_limit > 0 ?
1808  double vac_cost_delay = (autovacuum_vac_cost_delay >= 0 ?
1810  double cost_total;
1811  double cost_avail;
1812  dlist_iter iter;
1813 
1814  /* not set? nothing to do */
1815  if (vac_cost_limit <= 0 || vac_cost_delay <= 0)
1816  return;
1817 
1818  /* calculate the total base cost limit of participating active workers */
1819  cost_total = 0.0;
1821  {
1822  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1823 
1824  if (worker->wi_proc != NULL &&
1825  worker->wi_dobalance &&
1826  worker->wi_cost_limit_base > 0 && worker->wi_cost_delay > 0)
1827  cost_total +=
1828  (double) worker->wi_cost_limit_base / worker->wi_cost_delay;
1829  }
1830 
1831  /* there are no cost limits -- nothing to do */
1832  if (cost_total <= 0)
1833  return;
1834 
1835  /*
1836  * Adjust cost limit of each active worker to balance the total of cost
1837  * limit to autovacuum_vacuum_cost_limit.
1838  */
1839  cost_avail = (double) vac_cost_limit / vac_cost_delay;
1841  {
1842  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1843 
1844  if (worker->wi_proc != NULL &&
1845  worker->wi_dobalance &&
1846  worker->wi_cost_limit_base > 0 && worker->wi_cost_delay > 0)
1847  {
1848  int limit = (int)
1849  (cost_avail * worker->wi_cost_limit_base / cost_total);
1850 
1851  /*
1852  * We put a lower bound of 1 on the cost_limit, to avoid division-
1853  * by-zero in the vacuum code. Also, in case of roundoff trouble
1854  * in these calculations, let's be sure we don't ever set
1855  * cost_limit to more than the base value.
1856  */
1857  worker->wi_cost_limit = Max(Min(limit,
1858  worker->wi_cost_limit_base),
1859  1);
1860  }
1861 
1862  if (worker->wi_proc != NULL)
1863  elog(DEBUG2, "autovac_balance_cost(pid=%d db=%u, rel=%u, dobalance=%s cost_limit=%d, cost_limit_base=%d, cost_delay=%g)",
1864  worker->wi_proc->pid, worker->wi_dboid, worker->wi_tableoid,
1865  worker->wi_dobalance ? "yes" : "no",
1866  worker->wi_cost_limit, worker->wi_cost_limit_base,
1867  worker->wi_cost_delay);
1868  }
1869 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
double wi_cost_delay
Definition: autovacuum.c:230
#define Min(x, y)
Definition: c.h:986
int autovacuum_vac_cost_limit
Definition: autovacuum.c:129
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
int VacuumCostLimit
Definition: globals.c:144
#define DEBUG2
Definition: elog.h:24
double autovacuum_vac_cost_delay
Definition: autovacuum.c:128
int wi_cost_limit_base
Definition: autovacuum.c:232
dlist_node * cur
Definition: ilist.h:161
#define Max(x, y)
Definition: c.h:980
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293
double VacuumCostDelay
Definition: globals.c:145
#define elog(elevel,...)
Definition: elog.h:232
PGPROC * wi_proc
Definition: autovacuum.c:226
dlist_head av_runningWorkers
Definition: autovacuum.c:288
int pid
Definition: proc.h:146

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3434 of file autovacuum.c.

References autovacuum_start_daemon, ereport, errhint(), errmsg(), pgstat_track_counts, and WARNING.

Referenced by PostmasterMain().

3435 {
3437  ereport(WARNING,
3438  (errmsg("autovacuum not started because of misconfiguration"),
3439  errhint("Enable the \"track_counts\" option.")));
3440 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
bool autovacuum_start_daemon
Definition: autovacuum.c:115
bool pgstat_track_counts
Definition: pgstat.c:115
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ autovac_refresh_stats()

static void autovac_refresh_stats ( void  )
static

Definition at line 3532 of file autovacuum.c.

References GetCurrentTimestamp(), IsAutoVacuumLauncherProcess(), pgstat_clear_snapshot(), STATS_READ_DELAY, and TimestampDifferenceExceeds().

Referenced by do_autovacuum(), do_start_worker(), rebuild_database_list(), and table_recheck_autovac().

3533 {
3535  {
3536  static TimestampTz last_read = 0;
3537  TimestampTz current_time;
3538 
3539  current_time = GetCurrentTimestamp();
3540 
3541  if (!TimestampDifferenceExceeds(last_read, current_time,
3543  return;
3544 
3545  last_read = current_time;
3546  }
3547 
3549 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
#define STATS_READ_DELAY
Definition: autovacuum.c:134
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3448
void pgstat_clear_snapshot(void)
Definition: pgstat.c:4709

◆ autovac_report_activity()

static void autovac_report_activity ( autovac_table tab)
static

Definition at line 3305 of file autovacuum.c.

References autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relname, VacuumParams::is_wraparound, MAX_AUTOVAC_ACTIV_LEN, VacuumParams::options, pgstat_report_activity(), SetCurrentStatementStartTimestamp(), snprintf, STATE_RUNNING, VACOPT_ANALYZE, and VACOPT_VACUUM.

Referenced by autovacuum_do_vac_analyze().

3306 {
3307 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3308  char activity[MAX_AUTOVAC_ACTIV_LEN];
3309  int len;
3310 
3311  /* Report the command and possible options */
3312  if (tab->at_params.options & VACOPT_VACUUM)
3313  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3314  "autovacuum: VACUUM%s",
3315  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3316  else
3317  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3318  "autovacuum: ANALYZE");
3319 
3320  /*
3321  * Report the qualified name of the relation.
3322  */
3323  len = strlen(activity);
3324 
3325  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3326  " %s.%s%s", tab->at_nspname, tab->at_relname,
3327  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3328 
3329  /* Set statement_timestamp() to current time for pg_stat_activity */
3331 
3333 }
#define VACOPT_ANALYZE
Definition: vacuum.h:179
char * at_relname
Definition: autovacuum.c:198
bits32 options
Definition: vacuum.h:211
bool is_wraparound
Definition: vacuum.h:218
char * at_nspname
Definition: autovacuum.c:199
#define MAX_AUTOVAC_ACTIV_LEN
VacuumParams at_params
Definition: autovacuum.c:193
#define VACOPT_VACUUM
Definition: vacuum.h:178
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833
void pgstat_report_activity(BackendState state, const char *cmd_str)
#define snprintf
Definition: port.h:216

◆ autovac_report_workitem()

static void autovac_report_workitem ( AutoVacuumWorkItem workitem,
const char *  nspname,
const char *  relname 
)
static

Definition at line 3340 of file autovacuum.c.

References AutoVacuumWorkItem::avw_blockNumber, AVW_BRINSummarizeRange, AutoVacuumWorkItem::avw_type, BlockNumberIsValid, MAX_AUTOVAC_ACTIV_LEN, pgstat_report_activity(), SetCurrentStatementStartTimestamp(), snprintf, and STATE_RUNNING.

Referenced by perform_work_item().

3342 {
3343  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3344  char blk[12 + 2];
3345  int len;
3346 
3347  switch (workitem->avw_type)
3348  {
3350  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3351  "autovacuum: BRIN summarize");
3352  break;
3353  }
3354 
3355  /*
3356  * Report the qualified name of the relation, and the block number if any
3357  */
3358  len = strlen(activity);
3359 
3360  if (BlockNumberIsValid(workitem->avw_blockNumber))
3361  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3362  else
3363  blk[0] = '\0';
3364 
3365  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3366  " %s.%s%s", nspname, relname, blk);
3367 
3368  /* Set statement_timestamp() to current time for pg_stat_activity */
3370 
3372 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:257
NameData relname
Definition: pg_class.h:38
#define MAX_AUTOVAC_ACTIV_LEN
BlockNumber avw_blockNumber
Definition: autovacuum.c:262
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833
void pgstat_report_activity(BackendState state, const char *cmd_str)
#define snprintf
Definition: port.h:216

◆ AutoVacLauncherMain()

NON_EXEC_STATIC void AutoVacLauncherMain ( int  argc,
char *  argv[] 
)

Definition at line 437 of file autovacuum.c.

References AbortBufferIO(), AbortCurrentTransaction(), avl_dbase::adl_next_worker, avl_dbase::adl_node, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_autovacuum_launcher, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), autovac_balance_cost(), AutoVacForkFailed, AutoVacLauncherShutdown(), AutoVacRebalance, autovacuum_naptime, AutoVacuumingActive(), AuxProcessResourceOwner, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_signal, AutoVacuumShmemStruct::av_startingWorker, avl_sigusr2_handler(), B_AUTOVAC_LAUNCHER, BaseInit(), DEBUG1, disable_all_timeouts(), dlist_init(), dlist_is_empty(), dlist_push_head(), dlist_tail_element, do_start_worker(), elog, EmitErrorReport(), ereport, errmsg_internal(), error_context_stack, FloatExceptionHandler(), FlushErrorState(), GetCurrentTimestamp(), got_SIGUSR2, HandleAutoVacLauncherInterrupts(), HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InvalidOid, launch_worker(), launcher_determine_sleep(), LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), LWLockReleaseAll(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, MyBackendType, MyLatch, MyProcPid, NormalProcessing, PG_exception_stack, PG_SETMASK, pg_usleep(), PGC_S_OVERRIDE, PGC_SUSET, pgstat_clear_snapshot(), pgstat_report_wait_end(), PMSIGNAL_START_AUTOVAC_WORKER, PostAuthDelay, pqsignal(), proc_exit(), procsignal_sigusr1_handler(), QueryCancelPending, rebuild_database_list(), ReleaseAuxProcessResources(), ResetLatch(), RESUME_INTERRUPTS, SendPostmasterSignal(), SetConfigOption(), SetProcessingMode, ShutdownRequestPending, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, StatementCancelHandler(), TimestampDifferenceExceeds(), TopMemoryContext, UnBlockSig, UnlockBuffers(), WAIT_EVENT_AUTOVACUUM_MAIN, WaitLatch(), WARNING, WorkerInfoData::wi_dboid, WorkerInfoData::wi_launchtime, WorkerInfoData::wi_links, WorkerInfoData::wi_proc, WorkerInfoData::wi_sharedrel, WorkerInfoData::wi_tableoid, WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by BackendRun().

438 {
439  sigjmp_buf local_sigjmp_buf;
440 
441  am_autovacuum_launcher = true;
442 
444  init_ps_display(NULL);
445 
446  ereport(DEBUG1,
447  (errmsg_internal("autovacuum launcher started")));
448 
449  if (PostAuthDelay)
450  pg_usleep(PostAuthDelay * 1000000L);
451 
453 
454  /*
455  * Set up signal handlers. We operate on databases much like a regular
456  * backend, so we use the same signal handling. See equivalent code in
457  * tcop/postgres.c.
458  */
462  /* SIGQUIT handler was already set up by InitPostmasterChild */
463 
464  InitializeTimeouts(); /* establishes SIGALRM handler */
465 
471 
472  /* Early initialization */
473  BaseInit();
474 
475  /*
476  * Create a per-backend PGPROC struct in shared memory, except in the
477  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
478  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
479  * had to do some stuff with LWLocks).
480  */
481 #ifndef EXEC_BACKEND
482  InitProcess();
483 #endif
484 
485  InitPostgres(NULL, InvalidOid, NULL, InvalidOid, NULL, false);
486 
488 
489  /*
490  * Create a memory context that we will do all our work in. We do this so
491  * that we can reset the context during error recovery and thereby avoid
492  * possible memory leaks.
493  */
495  "Autovacuum Launcher",
498 
499  /*
500  * If an exception is encountered, processing resumes here.
501  *
502  * This code is a stripped down version of PostgresMain error recovery.
503  *
504  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
505  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
506  * signals other than SIGQUIT will be blocked until we complete error
507  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
508  * call redundant, but it is not since InterruptPending might be set
509  * already.
510  */
511  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
512  {
513  /* since not using PG_TRY, must reset error stack by hand */
514  error_context_stack = NULL;
515 
516  /* Prevents interrupts while cleaning up */
517  HOLD_INTERRUPTS();
518 
519  /* Forget any pending QueryCancel or timeout request */
520  disable_all_timeouts(false);
521  QueryCancelPending = false; /* second to avoid race condition */
522 
523  /* Report the error to the server log */
524  EmitErrorReport();
525 
526  /* Abort the current transaction in order to recover */
528 
529  /*
530  * Release any other resources, for the case where we were not in a
531  * transaction.
532  */
535  AbortBufferIO();
536  UnlockBuffers();
537  /* this is probably dead code, but let's be safe: */
540  AtEOXact_Buffers(false);
541  AtEOXact_SMgr();
542  AtEOXact_Files(false);
543  AtEOXact_HashTables(false);
544 
545  /*
546  * Now return to normal top-level context and clear ErrorContext for
547  * next time.
548  */
550  FlushErrorState();
551 
552  /* Flush any leaked data in the top-level context */
554 
555  /* don't leave dangling pointers to freed memory */
556  DatabaseListCxt = NULL;
558 
559  /*
560  * Make sure pgstat also considers our stat data as gone. Note: we
561  * mustn't use autovac_refresh_stats here.
562  */
564 
565  /* Now we can allow interrupts again */
567 
568  /* if in shutdown mode, no need for anything further; just go away */
571 
572  /*
573  * Sleep at least 1 second after any error. We don't want to be
574  * filling the error logs as fast as we can.
575  */
576  pg_usleep(1000000L);
577  }
578 
579  /* We can now handle ereport(ERROR) */
580  PG_exception_stack = &local_sigjmp_buf;
581 
582  /* must unblock signals before calling rebuild_database_list */
584 
585  /*
586  * Set always-secure search path. Launcher doesn't connect to a database,
587  * so this has no effect.
588  */
589  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
590 
591  /*
592  * Force zero_damaged_pages OFF in the autovac process, even if it is set
593  * in postgresql.conf. We don't really want such a dangerous option being
594  * applied non-interactively.
595  */
596  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
597 
598  /*
599  * Force settable timeouts off to avoid letting these settings prevent
600  * regular maintenance from being executed.
601  */
602  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
603  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
604  SetConfigOption("idle_in_transaction_session_timeout", "0",
606 
607  /*
608  * Force default_transaction_isolation to READ COMMITTED. We don't want
609  * to pay the overhead of serializable mode, nor add any risk of causing
610  * deadlocks or delaying other transactions.
611  */
612  SetConfigOption("default_transaction_isolation", "read committed",
614 
615  /*
616  * In emergency mode, just start a worker (unless shutdown was requested)
617  * and go away.
618  */
619  if (!AutoVacuumingActive())
620  {
622  do_start_worker();
623  proc_exit(0); /* done */
624  }
625 
627 
628  /*
629  * Create the initial database list. The invariant we want this list to
630  * keep is that it's ordered by decreasing next_time. As soon as an entry
631  * is updated to a higher time, it will be moved to the front (which is
632  * correct because the only operation is to add autovacuum_naptime to the
633  * entry, and time always increases).
634  */
636 
637  /* loop until shutdown request */
638  while (!ShutdownRequestPending)
639  {
640  struct timeval nap;
641  TimestampTz current_time = 0;
642  bool can_launch;
643 
644  /*
645  * This loop is a bit different from the normal use of WaitLatch,
646  * because we'd like to sleep before the first launch of a child
647  * process. So it's WaitLatch, then ResetLatch, then check for
648  * wakening conditions.
649  */
650 
652  false, &nap);
653 
654  /*
655  * Wait until naptime expires or we get some type of signal (all the
656  * signal handlers will wake us by calling SetLatch).
657  */
658  (void) WaitLatch(MyLatch,
660  (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
662 
664 
666 
667  /*
668  * a worker finished, or postmaster signaled failure to start a worker
669  */
670  if (got_SIGUSR2)
671  {
672  got_SIGUSR2 = false;
673 
674  /* rebalance cost limits, if needed */
676  {
677  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
680  LWLockRelease(AutovacuumLock);
681  }
682 
684  {
685  /*
686  * If the postmaster failed to start a new worker, we sleep
687  * for a little while and resend the signal. The new worker's
688  * state is still in memory, so this is sufficient. After
689  * that, we restart the main loop.
690  *
691  * XXX should we put a limit to the number of times we retry?
692  * I don't think it makes much sense, because a future start
693  * of a worker will continue to fail in the same way.
694  */
696  pg_usleep(1000000L); /* 1s */
698  continue;
699  }
700  }
701 
702  /*
703  * There are some conditions that we need to check before trying to
704  * start a worker. First, we need to make sure that there is a worker
705  * slot available. Second, we need to make sure that no other worker
706  * failed while starting up.
707  */
708 
709  current_time = GetCurrentTimestamp();
710  LWLockAcquire(AutovacuumLock, LW_SHARED);
711 
713 
714  if (AutoVacuumShmem->av_startingWorker != NULL)
715  {
716  int waittime;
718 
719  /*
720  * We can't launch another worker when another one is still
721  * starting up (or failed while doing so), so just sleep for a bit
722  * more; that worker will wake us up again as soon as it's ready.
723  * We will only wait autovacuum_naptime seconds (up to a maximum
724  * of 60 seconds) for this to happen however. Note that failure
725  * to connect to a particular database is not a problem here,
726  * because the worker removes itself from the startingWorker
727  * pointer before trying to connect. Problems detected by the
728  * postmaster (like fork() failure) are also reported and handled
729  * differently. The only problems that may cause this code to
730  * fire are errors in the earlier sections of AutoVacWorkerMain,
731  * before the worker removes the WorkerInfo from the
732  * startingWorker pointer.
733  */
734  waittime = Min(autovacuum_naptime, 60) * 1000;
735  if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
736  waittime))
737  {
738  LWLockRelease(AutovacuumLock);
739  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
740 
741  /*
742  * No other process can put a worker in starting mode, so if
743  * startingWorker is still INVALID after exchanging our lock,
744  * we assume it's the same one we saw above (so we don't
745  * recheck the launch time).
746  */
747  if (AutoVacuumShmem->av_startingWorker != NULL)
748  {
750  worker->wi_dboid = InvalidOid;
751  worker->wi_tableoid = InvalidOid;
752  worker->wi_sharedrel = false;
753  worker->wi_proc = NULL;
754  worker->wi_launchtime = 0;
756  &worker->wi_links);
758  elog(WARNING, "worker took too long to start; canceled");
759  }
760  }
761  else
762  can_launch = false;
763  }
764  LWLockRelease(AutovacuumLock); /* either shared or exclusive */
765 
766  /* if we can't do anything, just go back to sleep */
767  if (!can_launch)
768  continue;
769 
770  /* We're OK to start a new worker */
771 
773  {
774  /*
775  * Special case when the list is empty: start a worker right away.
776  * This covers the initial case, when no database is in pgstats
777  * (thus the list is empty). Note that the constraints in
778  * launcher_determine_sleep keep us from starting workers too
779  * quickly (at most once every autovacuum_naptime when the list is
780  * empty).
781  */
782  launch_worker(current_time);
783  }
784  else
785  {
786  /*
787  * because rebuild_database_list constructs a list with most
788  * distant adl_next_worker first, we obtain our database from the
789  * tail of the list.
790  */
791  avl_dbase *avdb;
792 
793  avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
794 
795  /*
796  * launch a worker if next_worker is right now or it is in the
797  * past
798  */
800  current_time, 0))
801  launch_worker(current_time);
802  }
803  }
804 
806 }
void InitializeTimeouts(void)
Definition: timeout.c:435
int autovacuum_naptime
Definition: autovacuum.c:118
void AbortCurrentTransaction(void)
Definition: xact.c:3210
TimestampTz adl_next_worker
Definition: autovacuum.c:164
#define AllocSetContextCreate
Definition: memutils.h:173
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:43
WorkerInfo av_startingWorker
Definition: autovacuum.c:289
static void autovac_balance_cost(void)
Definition: autovacuum.c:1796
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:285
static bool am_autovacuum_launcher
Definition: autovacuum.c:141
#define WL_TIMEOUT
Definition: latch.h:128
dlist_head av_freeWorkers
Definition: autovacuum.c:287
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
#define SIGUSR1
Definition: win32_port.h:171
BackendType MyBackendType
Definition: miscinit.c:62
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
#define SIGCHLD
Definition: win32_port.h:169
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2570
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:908
TimestampTz wi_launchtime
Definition: autovacuum.c:227
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:158
#define Min(x, y)
Definition: c.h:986
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:104
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
void BaseInit(void)
Definition: postinit.c:537
dlist_node wi_links
Definition: autovacuum.c:223
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
void FlushErrorState(void)
Definition: elog.c:1654
void ResetLatch(Latch *latch)
Definition: latch.c:660
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
ResourceOwner AuxProcessResourceOwner
Definition: resowner.c:149
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2949
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2999
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:133
ErrorContextCallback * error_context_stack
Definition: elog.c:93
void pg_usleep(long microsec)
Definition: signal.c:53
static void HandleAutoVacLauncherInterrupts(void)
Definition: autovacuum.c:812
void AtEOXact_SMgr(void)
Definition: smgr.c:678
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:515
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:687
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3380
Definition: guc.h:75
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
void InitProcess(void)
Definition: proc.c:303
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8086
#define SIGHUP
Definition: win32_port.h:159
sigset_t UnBlockSig
Definition: pqsignal.c:22
static dlist_head DatabaseList
Definition: autovacuum.c:299
MemoryContext TopMemoryContext
Definition: mcxt.c:48
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:104
static void avl_sigusr2_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1424
#define SIG_IGN
Definition: win32_port.h:156
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition: autovacuum.c:865
#define WARNING
Definition: elog.h:40
void UnlockBuffers(void)
Definition: bufmgr.c:3983
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
int PostAuthDelay
Definition: postgres.c:103
void EmitErrorReport(void)
Definition: elog.c:1509
#define InvalidOid
Definition: postgres_ext.h:36
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define ereport(elevel,...)
Definition: elog.h:157
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:579
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:145
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define SIG_DFL
Definition: win32_port.h:154
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
void pgstat_clear_snapshot(void)
Definition: pgstat.c:4709
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
void AbortBufferIO(void)
Definition: bufmgr.c:4481
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:949
static void AutoVacLauncherShutdown(void)
Definition: autovacuum.c:317
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
#define elog(elevel,...)
Definition: elog.h:232
static MemoryContext DatabaseListCxt
Definition: autovacuum.c:300
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2970
struct Latch * MyLatch
Definition: globals.c:57
PGPROC * wi_proc
Definition: autovacuum.c:226
static void launch_worker(TimestampTz now)
Definition: autovacuum.c:1365
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:153
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
void LWLockReleaseAll(void)
Definition: lwlock.c:1902
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:642
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1883
#define WL_LATCH_SET
Definition: latch.h:125
static Oid do_start_worker(void)
Definition: autovacuum.c:1150
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130

◆ AutoVacLauncherShutdown()

static void AutoVacLauncherShutdown ( void  )
static

Definition at line 317 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and HandleAutoVacLauncherInterrupts().

370 {
371  char *av[10];
372  int ac = 0;
373 
374  av[ac++] = "postgres";
375  av[ac++] = "--forkavlauncher";
376  av[ac++] = NULL; /* filled in by postmaster_forkexec */
377  av[ac] = NULL;
378 
379  Assert(ac < lengthof(av));
380 
381  return postmaster_forkexec(ac, av);
382 }
383 
384 /*
385  * We need this set from the outside, before InitProcess is called
386  */
387 void
388 AutovacuumLauncherIAm(void)
389 {
390  am_autovacuum_launcher = true;
391 }
392 #endif
393 
394 /*
395  * Main entry point for autovacuum launcher process, to be called from the
396  * postmaster.
397  */
398 int
400 {
401  pid_t AutoVacPID;
402 
403 #ifdef EXEC_BACKEND
404  switch ((AutoVacPID = avlauncher_forkexec()))
405 #else
406  switch ((AutoVacPID = fork_process()))
407 #endif
408  {
409  case -1:
410  ereport(LOG,
411  (errmsg("could not fork autovacuum launcher process: %m")));
412  return 0;
413 
414 #ifndef EXEC_BACKEND
415  case 0:
416  /* in postmaster child ... */
418 
419  /* Close the postmaster's sockets */
420  ClosePostmasterPorts(false);
421 
422  AutoVacLauncherMain(0, NULL);
423  break;
424 #endif
425  default:
426  return (int) AutoVacPID;
427  }
428 
429  /* shouldn't get here */
430  return 0;
431 }
static bool am_autovacuum_launcher
Definition: autovacuum.c:141
void InitPostmasterChild(void)
Definition: miscinit.c:93
NON_EXEC_STATIC void AutoVacLauncherMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: autovacuum.c:437
pid_t fork_process(void)
Definition: fork_process.c:29
struct @11::@12 av[32]
#define lengthof(array)
Definition: c.h:734
#define LOG
Definition: elog.h:26
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2556
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
int StartAutoVacLauncher(void)
static pid_t AutoVacPID
Definition: postmaster.c:254
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3276 of file autovacuum.c.

References autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relid, autovac_table::at_relname, autovac_report_activity(), list_make1, makeRangeVar(), makeVacuumRelation(), NIL, and vacuum().

Referenced by do_autovacuum().

3277 {
3278  RangeVar *rangevar;
3279  VacuumRelation *rel;
3280  List *rel_list;
3281 
3282  /* Let pgstat know what we're doing */
3284 
3285  /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3286  rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3287  rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3288  rel_list = list_make1(rel);
3289 
3290  vacuum(rel_list, &tab->at_params, bstrategy, true);
3291 }
#define NIL
Definition: pg_list.h:65
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:291
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:809
#define list_make1(x1)
Definition: pg_list.h:206
char * at_relname
Definition: autovacuum.c:198
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3305
char * at_nspname
Definition: autovacuum.c:199
VacuumParams at_params
Definition: autovacuum.c:193
Definition: pg_list.h:50
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422

◆ AutoVacuumingActive()

bool AutoVacuumingActive ( void  )

Definition at line 3380 of file autovacuum.c.

References autovacuum_start_daemon, and pgstat_track_counts.

Referenced by AutoVacLauncherMain(), HandleAutoVacLauncherInterrupts(), reaper(), relation_needs_vacanalyze(), and ServerLoop().

3381 {
3383  return false;
3384  return true;
3385 }
bool autovacuum_start_daemon
Definition: autovacuum.c:115
bool pgstat_track_counts
Definition: pgstat.c:115

◆ AutoVacuumRequestWork()

bool AutoVacuumRequestWork ( AutoVacuumWorkItemType  type,
Oid  relationId,
BlockNumber  blkno 
)

Definition at line 3392 of file autovacuum.c.

References AutoVacuumShmemStruct::av_workItems, AutoVacuumWorkItem::avw_active, AutoVacuumWorkItem::avw_blockNumber, AutoVacuumWorkItem::avw_database, AutoVacuumWorkItem::avw_relation, AutoVacuumWorkItem::avw_type, AutoVacuumWorkItem::avw_used, i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyDatabaseId, NUM_WORKITEMS, and generate_unaccent_rules::type.

Referenced by brininsert().

3394 {
3395  int i;
3396  bool result = false;
3397 
3398  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3399 
3400  /*
3401  * Locate an unused work item and fill it with the given data.
3402  */
3403  for (i = 0; i < NUM_WORKITEMS; i++)
3404  {
3406 
3407  if (workitem->avw_used)
3408  continue;
3409 
3410  workitem->avw_used = true;
3411  workitem->avw_active = false;
3412  workitem->avw_type = type;
3413  workitem->avw_database = MyDatabaseId;
3414  workitem->avw_relation = relationId;
3415  workitem->avw_blockNumber = blkno;
3416  result = true;
3417 
3418  /* done */
3419  break;
3420  }
3421 
3422  LWLockRelease(AutovacuumLock);
3423 
3424  return result;
3425 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:257
#define NUM_WORKITEMS
Definition: autovacuum.c:265
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:290
Oid MyDatabaseId
Definition: globals.c:88
BlockNumber avw_blockNumber
Definition: autovacuum.c:262
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int i

◆ AutoVacuumShmemInit()

void AutoVacuumShmemInit ( void  )

Definition at line 3484 of file autovacuum.c.

References Assert, autovacuum_max_workers, AutoVacuumShmemSize(), AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_startingWorker, AutoVacuumShmemStruct::av_workItems, dlist_init(), dlist_push_head(), i, IsUnderPostmaster, MAXALIGN, NUM_WORKITEMS, ShmemInitStruct(), and WorkerInfoData::wi_links.

Referenced by CreateSharedMemoryAndSemaphores().

3485 {
3486  bool found;
3487 
3489  ShmemInitStruct("AutoVacuum Data",
3491  &found);
3492 
3493  if (!IsUnderPostmaster)
3494  {
3495  WorkerInfo worker;
3496  int i;
3497 
3498  Assert(!found);
3499 
3504  memset(AutoVacuumShmem->av_workItems, 0,
3505  sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3506 
3507  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3508  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3509 
3510  /* initialize the WorkerInfo free list */
3511  for (i = 0; i < autovacuum_max_workers; i++)
3513  &worker[i].wi_links);
3514  }
3515  else
3516  Assert(found);
3517 }
#define NUM_WORKITEMS
Definition: autovacuum.c:265
WorkerInfo av_startingWorker
Definition: autovacuum.c:289
dlist_head av_freeWorkers
Definition: autovacuum.c:287
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:235
dlist_node wi_links
Definition: autovacuum.c:223
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:290
bool IsUnderPostmaster
Definition: globals.c:112
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3465
int autovacuum_max_workers
Definition: autovacuum.c:116
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define Assert(condition)
Definition: c.h:804
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293
#define MAXALIGN(LEN)
Definition: c.h:757
int i
dlist_head av_runningWorkers
Definition: autovacuum.c:288

◆ AutoVacuumShmemSize()

Size AutoVacuumShmemSize ( void  )

Definition at line 3465 of file autovacuum.c.

References add_size(), autovacuum_max_workers, MAXALIGN, and mul_size().

Referenced by AutoVacuumShmemInit(), and CreateSharedMemoryAndSemaphores().

3466 {
3467  Size size;
3468 
3469  /*
3470  * Need the fixed struct and the array of WorkerInfoData.
3471  */
3472  size = sizeof(AutoVacuumShmemStruct);
3473  size = MAXALIGN(size);
3475  sizeof(WorkerInfoData)));
3476  return size;
3477 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
int autovacuum_max_workers
Definition: autovacuum.c:116
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757

◆ AutoVacuumUpdateDelay()

void AutoVacuumUpdateDelay ( void  )

Definition at line 1780 of file autovacuum.c.

References VacuumCostDelay, VacuumCostLimit, WorkerInfoData::wi_cost_delay, and WorkerInfoData::wi_cost_limit.

Referenced by do_autovacuum(), and vacuum_delay_point().

1781 {
1782  if (MyWorkerInfo)
1783  {
1786  }
1787 }
double wi_cost_delay
Definition: autovacuum.c:230
int VacuumCostLimit
Definition: globals.c:144
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:303
double VacuumCostDelay
Definition: globals.c:145

◆ AutoVacWorkerFailed()

void AutoVacWorkerFailed ( void  )

Definition at line 1417 of file autovacuum.c.

References AutoVacForkFailed, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

1418 {
1420 }
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:285
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293

◆ AutoVacWorkerMain()

NON_EXEC_STATIC void AutoVacWorkerMain ( int  argc,
char *  argv[] 
)

Definition at line 1515 of file autovacuum.c.

References am_autovacuum_worker, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_startingWorker, B_AUTOVAC_WORKER, BaseInit(), dbname, DEBUG1, die, dlist_push_head(), do_autovacuum(), elog, EmitErrorReport(), ereport, errmsg_internal(), error_context_stack, FloatExceptionHandler(), FreeWorkerInfo(), HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InvalidOid, kill, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyBackendType, MyProc, NAMEDATALEN, NormalProcessing, OidIsValid, on_shmem_exit(), PG_exception_stack, PG_SETMASK, pg_usleep(), PGC_S_OVERRIDE, PGC_SUSET, pgstat_report_autovac(), PostAuthDelay, pqsignal(), proc_exit(), procsignal_sigusr1_handler(), ReadNextMultiXactId(), ReadNextTransactionId(), recentMulti, recentXid, set_ps_display(), SetConfigOption(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGUSR1, SIGUSR2, StatementCancelHandler(), synchronous_commit, SYNCHRONOUS_COMMIT_LOCAL_FLUSH, UnBlockSig, WARNING, WorkerInfoData::wi_dboid, WorkerInfoData::wi_links, and WorkerInfoData::wi_proc.

Referenced by BackendRun(), and StartAutoVacWorker().

1516 {
1517  sigjmp_buf local_sigjmp_buf;
1518  Oid dbid;
1519 
1520  am_autovacuum_worker = true;
1521 
1523  init_ps_display(NULL);
1524 
1526 
1527  /*
1528  * Set up signal handlers. We operate on databases much like a regular
1529  * backend, so we use the same signal handling. See equivalent code in
1530  * tcop/postgres.c.
1531  */
1533 
1534  /*
1535  * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1536  * means abort and exit cleanly, and SIGQUIT means abandon ship.
1537  */
1539  pqsignal(SIGTERM, die);
1540  /* SIGQUIT handler was already set up by InitPostmasterChild */
1541 
1542  InitializeTimeouts(); /* establishes SIGALRM handler */
1543 
1549 
1550  /* Early initialization */
1551  BaseInit();
1552 
1553  /*
1554  * Create a per-backend PGPROC struct in shared memory, except in the
1555  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
1556  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
1557  * had to do some stuff with LWLocks).
1558  */
1559 #ifndef EXEC_BACKEND
1560  InitProcess();
1561 #endif
1562 
1563  /*
1564  * If an exception is encountered, processing resumes here.
1565  *
1566  * Unlike most auxiliary processes, we don't attempt to continue
1567  * processing after an error; we just clean up and exit. The autovac
1568  * launcher is responsible for spawning another worker later.
1569  *
1570  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
1571  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
1572  * signals other than SIGQUIT will be blocked until we exit. It might
1573  * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
1574  * it is not since InterruptPending might be set already.
1575  */
1576  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1577  {
1578  /* since not using PG_TRY, must reset error stack by hand */
1579  error_context_stack = NULL;
1580 
1581  /* Prevents interrupts while cleaning up */
1582  HOLD_INTERRUPTS();
1583 
1584  /* Report the error to the server log */
1585  EmitErrorReport();
1586 
1587  /*
1588  * We can now go away. Note that because we called InitProcess, a
1589  * callback was registered to do ProcKill, which will clean up
1590  * necessary state.
1591  */
1592  proc_exit(0);
1593  }
1594 
1595  /* We can now handle ereport(ERROR) */
1596  PG_exception_stack = &local_sigjmp_buf;
1597 
1599 
1600  /*
1601  * Set always-secure search path, so malicious users can't redirect user
1602  * code (e.g. pg_index.indexprs). (That code runs in a
1603  * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1604  * take control of the entire autovacuum worker in any case.)
1605  */
1606  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1607 
1608  /*
1609  * Force zero_damaged_pages OFF in the autovac process, even if it is set
1610  * in postgresql.conf. We don't really want such a dangerous option being
1611  * applied non-interactively.
1612  */
1613  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1614 
1615  /*
1616  * Force settable timeouts off to avoid letting these settings prevent
1617  * regular maintenance from being executed.
1618  */
1619  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1620  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1621  SetConfigOption("idle_in_transaction_session_timeout", "0",
1623 
1624  /*
1625  * Force default_transaction_isolation to READ COMMITTED. We don't want
1626  * to pay the overhead of serializable mode, nor add any risk of causing
1627  * deadlocks or delaying other transactions.
1628  */
1629  SetConfigOption("default_transaction_isolation", "read committed",
1631 
1632  /*
1633  * Force synchronous replication off to allow regular maintenance even if
1634  * we are waiting for standbys to connect. This is important to ensure we
1635  * aren't blocked from performing anti-wraparound tasks.
1636  */
1638  SetConfigOption("synchronous_commit", "local",
1640 
1641  /*
1642  * Get the info about the database we're going to work on.
1643  */
1644  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1645 
1646  /*
1647  * beware of startingWorker being INVALID; this should normally not
1648  * happen, but if a worker fails after forking and before this, the
1649  * launcher might have decided to remove it from the queue and start
1650  * again.
1651  */
1652  if (AutoVacuumShmem->av_startingWorker != NULL)
1653  {
1655  dbid = MyWorkerInfo->wi_dboid;
1657 
1658  /* insert into the running list */
1661 
1662  /*
1663  * remove from the "starting" pointer, so that the launcher can start
1664  * a new worker if required
1665  */
1667  LWLockRelease(AutovacuumLock);
1668 
1670 
1671  /* wake up the launcher */
1672  if (AutoVacuumShmem->av_launcherpid != 0)
1674  }
1675  else
1676  {
1677  /* no worker entry for me, go away */
1678  elog(WARNING, "autovacuum worker started without a worker entry");
1679  dbid = InvalidOid;
1680  LWLockRelease(AutovacuumLock);
1681  }
1682 
1683  if (OidIsValid(dbid))
1684  {
1685  char dbname[NAMEDATALEN];
1686 
1687  /*
1688  * Report autovac startup to the stats collector. We deliberately do
1689  * this before InitPostgres, so that the last_autovac_time will get
1690  * updated even if the connection attempt fails. This is to prevent
1691  * autovac from getting "stuck" repeatedly selecting an unopenable
1692  * database, rather than making any progress on stuff it can connect
1693  * to.
1694  */
1695  pgstat_report_autovac(dbid);
1696 
1697  /*
1698  * Connect to the selected database
1699  *
1700  * Note: if we have selected a just-deleted database (due to using
1701  * stale stats info), we'll fail and exit here.
1702  */
1703  InitPostgres(NULL, dbid, NULL, InvalidOid, dbname, false);
1705  set_ps_display(dbname);
1706  ereport(DEBUG1,
1707  (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1708 
1709  if (PostAuthDelay)
1710  pg_usleep(PostAuthDelay * 1000000L);
1711 
1712  /* And do an appropriate amount of work */
1715  do_autovacuum();
1716  }
1717 
1718  /*
1719  * The launcher will be notified of my death in ProcKill, *if* we managed
1720  * to get a worker slot at all
1721  */
1722 
1723  /* All done, go away */
1724  proc_exit(0);
1725 }
static bool am_autovacuum_worker
Definition: autovacuum.c:142
void InitializeTimeouts(void)
Definition: timeout.c:435
#define DEBUG1
Definition: elog.h:25
WorkerInfo av_startingWorker
Definition: autovacuum.c:289
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
#define SIGUSR1
Definition: win32_port.h:171
BackendType MyBackendType
Definition: miscinit.c:62
static void do_autovacuum(void)
Definition: autovacuum.c:1954
#define SIGCHLD
Definition: win32_port.h:169
PGPROC * MyProc
Definition: proc.c:68
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
static MultiXactId recentMulti
Definition: autovacuum.c:149
void proc_exit(int code)
Definition: ipc.c:104
#define SetProcessingMode(mode)
Definition: miscadmin.h:412
#define kill(pid, sig)
Definition: win32_port.h:454
void BaseInit(void)
Definition: postinit.c:537
dlist_node wi_links
Definition: autovacuum.c:223
#define SIGPIPE
Definition: win32_port.h:164
#define SIGUSR2
Definition: win32_port.h:172
static TransactionId ReadNextTransactionId(void)
Definition: transam.h:316
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2949
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define NAMEDATALEN
void set_ps_display(const char *activity)
Definition: ps_status.c:349
void pg_usleep(long microsec)
Definition: signal.c:53
Definition: guc.h:75
void InitProcess(void)
Definition: proc.c:303
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8086
#define SIGHUP
Definition: win32_port.h:159
sigset_t UnBlockSig
Definition: pqsignal.c:22
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:303
int synchronous_commit
Definition: xact.c:83
#define SIG_IGN
Definition: win32_port.h:156
#define WARNING
Definition: elog.h:40
int PostAuthDelay
Definition: postgres.c:103
static TransactionId recentXid
Definition: autovacuum.c:148
void EmitErrorReport(void)
Definition: elog.c:1509
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:579
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define SIG_DFL
Definition: win32_port.h:154
char * dbname
Definition: streamutil.c:51
static void FreeWorkerInfo(int code, Datum arg)
Definition: autovacuum.c:1731
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
sigjmp_buf * PG_exception_stack
Definition: elog.c:95
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
#define elog(elevel,...)
Definition: elog.h:232
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2970
PGPROC * wi_proc
Definition: autovacuum.c:226
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:642
dlist_head av_runningWorkers
Definition: autovacuum.c:288
void pgstat_report_autovac(Oid dboid)
Definition: pgstat.c:1555
#define die(msg)
Definition: pg_test_fsync.c:97
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1424 of file autovacuum.c.

References am_autovacuum_worker, Assert, got_SIGUSR2, lengthof, MyLatch, and SetLatch().

Referenced by AutoVacLauncherMain().

1425 {
1426  int save_errno = errno;
1427 
1428  got_SIGUSR2 = true;
1429  SetLatch(MyLatch);
1430 
1431  errno = save_errno;
1432 }
void SetLatch(Latch *latch)
Definition: latch.c:567
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:145
struct Latch * MyLatch
Definition: globals.c:57

◆ db_comparator()

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

Definition at line 1130 of file autovacuum.c.

References avl_dbase::adl_score.

Referenced by rebuild_database_list().

1131 {
1132  if (((const avl_dbase *) a)->adl_score == ((const avl_dbase *) b)->adl_score)
1133  return 0;
1134  else
1135  return (((const avl_dbase *) a)->adl_score < ((const avl_dbase *) b)->adl_score) ? 1 : -1;
1136 }

◆ do_autovacuum()

static void do_autovacuum ( void  )
static

Definition at line 1954 of file autovacuum.c.

References AbortOutOfAnyTransaction(), AccessExclusiveLock, AccessShareLock, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, av_relation::ar_hasrelopts, av_relation::ar_relid, av_relation::ar_reloptions, autovac_table::at_datname, autovac_table::at_dobalance, autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relid, autovac_table::at_relname, autovac_table::at_vacuum_cost_delay, autovac_table::at_vacuum_cost_limit, autovac_balance_cost(), autovac_refresh_stats(), autovacuum_do_vac_analyze(), AutoVacuumUpdateDelay(), AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_workItems, AutoVacuumWorkItem::avw_active, AutoVacuumWorkItem::avw_database, AutoVacuumWorkItem::avw_used, BAS_VACUUM, BTEqualStrategyNumber, PgStat_StatTabEntry::changes_since_analyze, PgStat_StatTabEntry::changes_since_analyze_reported, CharGetDatum, CHECK_FOR_INTERRUPTS, checkTempNamespaceStatus(), CommitTransactionCommand(), ConditionalLockRelationOid(), ConfigReloadPending, CreateTupleDescCopy(), dlist_iter::cur, DATABASEOID, default_freeze_min_age, default_freeze_table_age, default_multixact_freeze_min_age, default_multixact_freeze_table_age, dlist_container, dlist_foreach, DROP_CASCADE, elog, EmitErrorReport(), HASHCTL::entrysize, ereport, errcontext, errmsg(), ERROR, extract_autovac_opts(), FlushErrorState(), ForwardScanDirection, get_database_name(), get_namespace_name(), get_pgstat_tabentry_relid(), get_rel_name(), get_rel_namespace(), GetAccessStrategy(), GETSTRUCT, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, HASH_FIND, hash_search(), heap_getnext(), HeapTupleIsValid, HOLD_INTERRUPTS, i, InvalidOid, sort-test::key, HASHCTL::keysize, lappend_oid(), lfirst_oid, LOG, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MultiXactMemberFreezeThreshold(), MyDatabaseId, NameStr, NIL, NUM_WORKITEMS, ObjectIdGetDatum, OidIsValid, VacuumParams::options, PERFORM_DELETION_INTERNAL, PERFORM_DELETION_QUIETLY, PERFORM_DELETION_SKIP_EXTENSIONS, perform_work_item(), performDeletion(), pfree(), PG_CATCH, PG_END_TRY, PG_TRY, PGC_SIGHUP, pgstat_fetch_stat_dbentry(), pgstat_fetch_stat_tabentry(), pgstat_report_anl_ancestors(), pgstat_vacuum_stat(), PortalContext, ProcessConfigFile(), QueryCancelPending, relation_needs_vacanalyze(), RelationGetDescr, ReleaseSysCache(), RELOID, RESUME_INTERRUPTS, ScanKeyInit(), SearchSysCache1(), SearchSysCacheCopy1, StartTransactionCommand(), table_beginscan_catalog(), table_close(), table_endscan(), table_open(), table_recheck_autovac(), TEMP_NAMESPACE_IDLE, TopMemoryContext, UnlockRelationOid(), vac_update_datfrozenxid(), VACOPT_VACUUM, vacuum_freeze_min_age, vacuum_freeze_table_age, vacuum_multixact_freeze_min_age, vacuum_multixact_freeze_table_age, VacuumCostDelay, VacuumCostLimit, WorkerInfoData::wi_cost_delay, WorkerInfoData::wi_cost_limit, WorkerInfoData::wi_cost_limit_base, WorkerInfoData::wi_dboid, WorkerInfoData::wi_dobalance, WorkerInfoData::wi_sharedrel, and WorkerInfoData::wi_tableoid.

Referenced by AutoVacWorkerMain().

1955 {
1956  Relation classRel;
1957  HeapTuple tuple;
1958  TableScanDesc relScan;
1959  Form_pg_database dbForm;
1960  List *table_oids = NIL;
1961  List *orphan_oids = NIL;
1962  HASHCTL ctl;
1963  HTAB *table_toast_map;
1964  ListCell *volatile cell;
1965  PgStat_StatDBEntry *shared;
1966  PgStat_StatDBEntry *dbentry;
1967  BufferAccessStrategy bstrategy;
1968  ScanKeyData key;
1969  TupleDesc pg_class_desc;
1970  int effective_multixact_freeze_max_age;
1971  bool did_vacuum = false;
1972  bool found_concurrent_worker = false;
1973  bool updated = false;
1974  int i;
1975 
1976  /*
1977  * StartTransactionCommand and CommitTransactionCommand will automatically
1978  * switch to other contexts. We need this one to keep the list of
1979  * relations to vacuum/analyze across transactions.
1980  */
1982  "AV worker",
1985 
1986  /*
1987  * may be NULL if we couldn't find an entry (only happens if we are
1988  * forcing a vacuum for anti-wrap purposes).
1989  */
1991 
1992  /* Start a transaction so our commands have one to play into. */
1994 
1995  /*
1996  * Clean up any dead statistics collector entries for this DB. We always
1997  * want to do this exactly once per DB-processing cycle, even if we find
1998  * nothing worth vacuuming in the database.
1999  */
2001 
2002  /*
2003  * Compute the multixact age for which freezing is urgent. This is
2004  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
2005  * short of multixact member space.
2006  */
2007  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
2008 
2009  /*
2010  * Find the pg_database entry and select the default freeze ages. We use
2011  * zero in template and nonconnectable databases, else the system-wide
2012  * default.
2013  */
2015  if (!HeapTupleIsValid(tuple))
2016  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
2017  dbForm = (Form_pg_database) GETSTRUCT(tuple);
2018 
2019  if (dbForm->datistemplate || !dbForm->datallowconn)
2020  {
2025  }
2026  else
2027  {
2032  }
2033 
2034  ReleaseSysCache(tuple);
2035 
2036  /* StartTransactionCommand changed elsewhere */
2038 
2039  /* The database hash where pgstat keeps shared relations */
2041 
2042  classRel = table_open(RelationRelationId, AccessShareLock);
2043 
2044  /* create a copy so we can use it after closing pg_class */
2045  pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
2046 
2047  /* create hash table for toast <-> main relid mapping */
2048  ctl.keysize = sizeof(Oid);
2049  ctl.entrysize = sizeof(av_relation);
2050 
2051  table_toast_map = hash_create("TOAST to main relid map",
2052  100,
2053  &ctl,
2054  HASH_ELEM | HASH_BLOBS);
2055 
2056  /*
2057  * Scan pg_class to determine which tables to vacuum.
2058  *
2059  * We do this in three passes: First we let pgstat collector know about
2060  * the partitioned table ancestors of all partitions that have recently
2061  * acquired rows for analyze. This informs the second pass about the
2062  * total number of tuple count in partitioning hierarchies.
2063  *
2064  * On the second pass, we collect the list of plain relations,
2065  * materialized views and partitioned tables. On the third one we collect
2066  * TOAST tables.
2067  *
2068  * The reason for doing the third pass is that during it we want to use
2069  * the main relation's pg_class.reloptions entry if the TOAST table does
2070  * not have any, and we cannot obtain it unless we know beforehand what's
2071  * the main table OID.
2072  *
2073  * We need to check TOAST tables separately because in cases with short,
2074  * wide tables there might be proportionally much more activity in the
2075  * TOAST table than in its parent.
2076  */
2077  relScan = table_beginscan_catalog(classRel, 0, NULL);
2078 
2079  /*
2080  * First pass: before collecting the list of tables to vacuum, let stat
2081  * collector know about partitioned-table ancestors of each partition.
2082  */
2083  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2084  {
2085  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2086  Oid relid = classForm->oid;
2087  PgStat_StatTabEntry *tabentry;
2088 
2089  /* Only consider permanent leaf partitions */
2090  if (!classForm->relispartition ||
2091  classForm->relkind == RELKIND_PARTITIONED_TABLE ||
2092  classForm->relpersistence == RELPERSISTENCE_TEMP)
2093  continue;
2094 
2095  /*
2096  * No need to do this for partitions that haven't acquired any rows.
2097  */
2098  tabentry = pgstat_fetch_stat_tabentry(relid);
2099  if (tabentry &&
2100  tabentry->changes_since_analyze -
2101  tabentry->changes_since_analyze_reported > 0)
2102  {
2104  updated = true;
2105  }
2106  }
2107 
2108  /* Acquire fresh stats for the next passes, if needed */
2109  if (updated)
2110  {
2114  }
2115 
2116  /*
2117  * On the second pass, we collect main tables to vacuum, and also the main
2118  * table relid to TOAST relid mapping.
2119  */
2120  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2121  {
2122  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2123  PgStat_StatTabEntry *tabentry;
2124  AutoVacOpts *relopts;
2125  Oid relid;
2126  bool dovacuum;
2127  bool doanalyze;
2128  bool wraparound;
2129 
2130  if (classForm->relkind != RELKIND_RELATION &&
2131  classForm->relkind != RELKIND_MATVIEW &&
2132  classForm->relkind != RELKIND_PARTITIONED_TABLE)
2133  continue;
2134 
2135  relid = classForm->oid;
2136 
2137  /*
2138  * Check if it is a temp table (presumably, of some other backend's).
2139  * We cannot safely process other backends' temp tables.
2140  */
2141  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2142  {
2143  /*
2144  * We just ignore it if the owning backend is still active and
2145  * using the temporary schema. Also, for safety, ignore it if the
2146  * namespace doesn't exist or isn't a temp namespace after all.
2147  */
2148  if (checkTempNamespaceStatus(classForm->relnamespace) == TEMP_NAMESPACE_IDLE)
2149  {
2150  /*
2151  * The table seems to be orphaned -- although it might be that
2152  * the owning backend has already deleted it and exited; our
2153  * pg_class scan snapshot is not necessarily up-to-date
2154  * anymore, so we could be looking at a committed-dead entry.
2155  * Remember it so we can try to delete it later.
2156  */
2157  orphan_oids = lappend_oid(orphan_oids, relid);
2158  }
2159  continue;
2160  }
2161 
2162  /* Fetch reloptions and the pgstat entry for this table */
2163  relopts = extract_autovac_opts(tuple, pg_class_desc);
2164  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
2165  shared, dbentry);
2166 
2167  /* Check if it needs vacuum or analyze */
2168  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2169  effective_multixact_freeze_max_age,
2170  &dovacuum, &doanalyze, &wraparound);
2171 
2172  /* Relations that need work are added to table_oids */
2173  if (dovacuum || doanalyze)
2174  table_oids = lappend_oid(table_oids, relid);
2175 
2176  /*
2177  * Remember TOAST associations for the second pass. Note: we must do
2178  * this whether or not the table is going to be vacuumed, because we
2179  * don't automatically vacuum toast tables along the parent table.
2180  */
2181  if (OidIsValid(classForm->reltoastrelid))
2182  {
2183  av_relation *hentry;
2184  bool found;
2185 
2186  hentry = hash_search(table_toast_map,
2187  &classForm->reltoastrelid,
2188  HASH_ENTER, &found);
2189 
2190  if (!found)
2191  {
2192  /* hash_search already filled in the key */
2193  hentry->ar_relid = relid;
2194  hentry->ar_hasrelopts = false;
2195  if (relopts != NULL)
2196  {
2197  hentry->ar_hasrelopts = true;
2198  memcpy(&hentry->ar_reloptions, relopts,
2199  sizeof(AutoVacOpts));
2200  }
2201  }
2202  }
2203  }
2204 
2205  table_endscan(relScan);
2206 
2207  /* third pass: check TOAST tables */
2208  ScanKeyInit(&key,
2209  Anum_pg_class_relkind,
2210  BTEqualStrategyNumber, F_CHAREQ,
2211  CharGetDatum(RELKIND_TOASTVALUE));
2212 
2213  relScan = table_beginscan_catalog(classRel, 1, &key);
2214  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2215  {
2216  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2217  PgStat_StatTabEntry *tabentry;
2218  Oid relid;
2219  AutoVacOpts *relopts = NULL;
2220  bool dovacuum;
2221  bool doanalyze;
2222  bool wraparound;
2223 
2224  /*
2225  * We cannot safely process other backends' temp tables, so skip 'em.
2226  */
2227  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2228  continue;
2229 
2230  relid = classForm->oid;
2231 
2232  /*
2233  * fetch reloptions -- if this toast table does not have them, try the
2234  * main rel
2235  */
2236  relopts = extract_autovac_opts(tuple, pg_class_desc);
2237  if (relopts == NULL)
2238  {
2239  av_relation *hentry;
2240  bool found;
2241 
2242  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2243  if (found && hentry->ar_hasrelopts)
2244  relopts = &hentry->ar_reloptions;
2245  }
2246 
2247  /* Fetch the pgstat entry for this table */
2248  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
2249  shared, dbentry);
2250 
2251  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2252  effective_multixact_freeze_max_age,
2253  &dovacuum, &doanalyze, &wraparound);
2254 
2255  /* ignore analyze for toast tables */
2256  if (dovacuum)
2257  table_oids = lappend_oid(table_oids, relid);
2258  }
2259 
2260  table_endscan(relScan);
2261  table_close(classRel, AccessShareLock);
2262 
2263  /*
2264  * Recheck orphan temporary tables, and if they still seem orphaned, drop
2265  * them. We'll eat a transaction per dropped table, which might seem
2266  * excessive, but we should only need to do anything as a result of a
2267  * previous backend crash, so this should not happen often enough to
2268  * justify "optimizing". Using separate transactions ensures that we
2269  * don't bloat the lock table if there are many temp tables to be dropped,
2270  * and it ensures that we don't lose work if a deletion attempt fails.
2271  */
2272  foreach(cell, orphan_oids)
2273  {
2274  Oid relid = lfirst_oid(cell);
2275  Form_pg_class classForm;
2276  ObjectAddress object;
2277 
2278  /*
2279  * Check for user-requested abort.
2280  */
2282 
2283  /*
2284  * Try to lock the table. If we can't get the lock immediately,
2285  * somebody else is using (or dropping) the table, so it's not our
2286  * concern anymore. Having the lock prevents race conditions below.
2287  */
2289  continue;
2290 
2291  /*
2292  * Re-fetch the pg_class tuple and re-check whether it still seems to
2293  * be an orphaned temp table. If it's not there or no longer the same
2294  * relation, ignore it.
2295  */
2296  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2297  if (!HeapTupleIsValid(tuple))
2298  {
2299  /* be sure to drop useless lock so we don't bloat lock table */
2301  continue;
2302  }
2303  classForm = (Form_pg_class) GETSTRUCT(tuple);
2304 
2305  /*
2306  * Make all the same tests made in the loop above. In event of OID
2307  * counter wraparound, the pg_class entry we have now might be
2308  * completely unrelated to the one we saw before.
2309  */
2310  if (!((classForm->relkind == RELKIND_RELATION ||
2311  classForm->relkind == RELKIND_MATVIEW) &&
2312  classForm->relpersistence == RELPERSISTENCE_TEMP))
2313  {
2315  continue;
2316  }
2317 
2318  if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE)
2319  {
2321  continue;
2322  }
2323 
2324  /* OK, let's delete it */
2325  ereport(LOG,
2326  (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2328  get_namespace_name(classForm->relnamespace),
2329  NameStr(classForm->relname))));
2330 
2331  object.classId = RelationRelationId;
2332  object.objectId = relid;
2333  object.objectSubId = 0;
2334  performDeletion(&object, DROP_CASCADE,
2338 
2339  /*
2340  * To commit the deletion, end current transaction and start a new
2341  * one. Note this also releases the lock we took.
2342  */
2345 
2346  /* StartTransactionCommand changed current memory context */
2348  }
2349 
2350  /*
2351  * Create a buffer access strategy object for VACUUM to use. We want to
2352  * use the same one across all the vacuum operations we perform, since the
2353  * point is for VACUUM not to blow out the shared cache.
2354  */
2355  bstrategy = GetAccessStrategy(BAS_VACUUM);
2356 
2357  /*
2358  * create a memory context to act as fake PortalContext, so that the
2359  * contexts created in the vacuum code are cleaned up for each table.
2360  */
2362  "Autovacuum Portal",
2364 
2365  /*
2366  * Perform operations on collected tables.
2367  */
2368  foreach(cell, table_oids)
2369  {
2370  Oid relid = lfirst_oid(cell);
2371  HeapTuple classTup;
2372  autovac_table *tab;
2373  bool isshared;
2374  bool skipit;
2375  double stdVacuumCostDelay;
2376  int stdVacuumCostLimit;
2377  dlist_iter iter;
2378 
2380 
2381  /*
2382  * Check for config changes before processing each collected table.
2383  */
2384  if (ConfigReloadPending)
2385  {
2386  ConfigReloadPending = false;
2388 
2389  /*
2390  * You might be tempted to bail out if we see autovacuum is now
2391  * disabled. Must resist that temptation -- this might be a
2392  * for-wraparound emergency worker, in which case that would be
2393  * entirely inappropriate.
2394  */
2395  }
2396 
2397  /*
2398  * Find out whether the table is shared or not. (It's slightly
2399  * annoying to fetch the syscache entry just for this, but in typical
2400  * cases it adds little cost because table_recheck_autovac would
2401  * refetch the entry anyway. We could buy that back by copying the
2402  * tuple here and passing it to table_recheck_autovac, but that
2403  * increases the odds of that function working with stale data.)
2404  */
2405  classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2406  if (!HeapTupleIsValid(classTup))
2407  continue; /* somebody deleted the rel, forget it */
2408  isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared;
2409  ReleaseSysCache(classTup);
2410 
2411  /*
2412  * Hold schedule lock from here until we've claimed the table. We
2413  * also need the AutovacuumLock to walk the worker array, but that one
2414  * can just be a shared lock.
2415  */
2416  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2417  LWLockAcquire(AutovacuumLock, LW_SHARED);
2418 
2419  /*
2420  * Check whether the table is being vacuumed concurrently by another
2421  * worker.
2422  */
2423  skipit = false;
2425  {
2426  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2427 
2428  /* ignore myself */
2429  if (worker == MyWorkerInfo)
2430  continue;
2431 
2432  /* ignore workers in other databases (unless table is shared) */
2433  if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2434  continue;
2435 
2436  if (worker->wi_tableoid == relid)
2437  {
2438  skipit = true;
2439  found_concurrent_worker = true;
2440  break;
2441  }
2442  }
2443  LWLockRelease(AutovacuumLock);
2444  if (skipit)
2445  {
2446  LWLockRelease(AutovacuumScheduleLock);
2447  continue;
2448  }
2449 
2450  /*
2451  * Store the table's OID in shared memory before releasing the
2452  * schedule lock, so that other workers don't try to vacuum it
2453  * concurrently. (We claim it here so as not to hold
2454  * AutovacuumScheduleLock while rechecking the stats.)
2455  */
2456  MyWorkerInfo->wi_tableoid = relid;
2457  MyWorkerInfo->wi_sharedrel = isshared;
2458  LWLockRelease(AutovacuumScheduleLock);
2459 
2460  /*
2461  * Check whether pgstat data still says we need to vacuum this table.
2462  * It could have changed if something else processed the table while
2463  * we weren't looking.
2464  *
2465  * Note: we have a special case in pgstat code to ensure that the
2466  * stats we read are as up-to-date as possible, to avoid the problem
2467  * that somebody just finished vacuuming this table. The window to
2468  * the race condition is not closed but it is very small.
2469  */
2471  tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
2472  effective_multixact_freeze_max_age);
2473  if (tab == NULL)
2474  {
2475  /* someone else vacuumed the table, or it went away */
2476  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2478  MyWorkerInfo->wi_sharedrel = false;
2479  LWLockRelease(AutovacuumScheduleLock);
2480  continue;
2481  }
2482 
2483  /*
2484  * Remember the prevailing values of the vacuum cost GUCs. We have to
2485  * restore these at the bottom of the loop, else we'll compute wrong
2486  * values in the next iteration of autovac_balance_cost().
2487  */
2488  stdVacuumCostDelay = VacuumCostDelay;
2489  stdVacuumCostLimit = VacuumCostLimit;
2490 
2491  /* Must hold AutovacuumLock while mucking with cost balance info */
2492  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2493 
2494  /* advertise my cost delay parameters for the balancing algorithm */
2499 
2500  /* do a balance */
2502 
2503  /* set the active cost parameters from the result of that */
2505 
2506  /* done */
2507  LWLockRelease(AutovacuumLock);
2508 
2509  /* clean up memory before each iteration */
2511 
2512  /*
2513  * Save the relation name for a possible error message, to avoid a
2514  * catalog lookup in case of an error. If any of these return NULL,
2515  * then the relation has been dropped since last we checked; skip it.
2516  * Note: they must live in a long-lived memory context because we call
2517  * vacuum and analyze in different transactions.
2518  */
2519 
2520  tab->at_relname = get_rel_name(tab->at_relid);
2523  if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2524  goto deleted;
2525 
2526  /*
2527  * We will abort vacuuming the current table if something errors out,
2528  * and continue with the next one in schedule; in particular, this
2529  * happens if we are interrupted with SIGINT.
2530  */
2531  PG_TRY();
2532  {
2533  /* Use PortalContext for any per-table allocations */
2535 
2536  /* have at it */
2537  autovacuum_do_vac_analyze(tab, bstrategy);
2538 
2539  /*
2540  * Clear a possible query-cancel signal, to avoid a late reaction
2541  * to an automatically-sent signal because of vacuuming the
2542  * current table (we're done with it, so it would make no sense to
2543  * cancel at this point.)
2544  */
2545  QueryCancelPending = false;
2546  }
2547  PG_CATCH();
2548  {
2549  /*
2550  * Abort the transaction, start a new one, and proceed with the
2551  * next table in our list.
2552  */
2553  HOLD_INTERRUPTS();
2554  if (tab->at_params.options & VACOPT_VACUUM)
2555  errcontext("automatic vacuum of table \"%s.%s.%s\"",
2556  tab->at_datname, tab->at_nspname, tab->at_relname);
2557  else
2558  errcontext("automatic analyze of table \"%s.%s.%s\"",
2559  tab->at_datname, tab->at_nspname, tab->at_relname);
2560  EmitErrorReport();
2561 
2562  /* this resets ProcGlobal->statusFlags[i] too */
2564  FlushErrorState();
2566 
2567  /* restart our transaction for the following operations */
2570  }
2571  PG_END_TRY();
2572 
2573  /* Make sure we're back in AutovacMemCxt */
2575 
2576  did_vacuum = true;
2577 
2578  /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2579 
2580  /* be tidy */
2581 deleted:
2582  if (tab->at_datname != NULL)
2583  pfree(tab->at_datname);
2584  if (tab->at_nspname != NULL)
2585  pfree(tab->at_nspname);
2586  if (tab->at_relname != NULL)
2587  pfree(tab->at_relname);
2588  pfree(tab);
2589 
2590  /*
2591  * Remove my info from shared memory. We could, but intentionally
2592  * don't, clear wi_cost_limit and friends --- this is on the
2593  * assumption that we probably have more to do with similar cost
2594  * settings, so we don't want to give up our share of I/O for a very
2595  * short interval and thereby thrash the global balance.
2596  */
2597  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2599  MyWorkerInfo->wi_sharedrel = false;
2600  LWLockRelease(AutovacuumScheduleLock);
2601 
2602  /* restore vacuum cost GUCs for the next iteration */
2603  VacuumCostDelay = stdVacuumCostDelay;
2604  VacuumCostLimit = stdVacuumCostLimit;
2605  }
2606 
2607  /*
2608  * Perform additional work items, as requested by backends.
2609  */
2610  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2611  for (i = 0; i < NUM_WORKITEMS; i++)
2612  {
2614 
2615  if (!workitem->avw_used)
2616  continue;
2617  if (workitem->avw_active)
2618  continue;
2619  if (workitem->avw_database != MyDatabaseId)
2620  continue;
2621 
2622  /* claim this one, and release lock while performing it */
2623  workitem->avw_active = true;
2624  LWLockRelease(AutovacuumLock);
2625 
2626  perform_work_item(workitem);
2627 
2628  /*
2629  * Check for config changes before acquiring lock for further jobs.
2630  */
2632  if (ConfigReloadPending)
2633  {
2634  ConfigReloadPending = false;
2636  }
2637 
2638  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2639 
2640  /* and mark it done */
2641  workitem->avw_active = false;
2642  workitem->avw_used = false;
2643  }
2644  LWLockRelease(AutovacuumLock);
2645 
2646  /*
2647  * We leak table_toast_map here (among other things), but since we're
2648  * going away soon, it's not a problem.
2649  */
2650 
2651  /*
2652  * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2653  * only need to do this once, not after each table.
2654  *
2655  * Even if we didn't vacuum anything, it may still be important to do
2656  * this, because one indirect effect of vac_update_datfrozenxid() is to
2657  * update ShmemVariableCache->xidVacLimit. That might need to be done
2658  * even if we haven't vacuumed anything, because relations with older
2659  * relfrozenxid values or other databases with older datfrozenxid values
2660  * might have been dropped, allowing xidVacLimit to advance.
2661  *
2662  * However, it's also important not to do this blindly in all cases,
2663  * because when autovacuum=off this will restart the autovacuum launcher.
2664  * If we're not careful, an infinite loop can result, where workers find
2665  * no work to do and restart the launcher, which starts another worker in
2666  * the same database that finds no work to do. To prevent that, we skip
2667  * this if (1) we found no work to do and (2) we skipped at least one
2668  * table due to concurrent autovacuum activity. In that case, the other
2669  * worker has already done it, or will do so when it finishes.
2670  */
2671  if (did_vacuum || !found_concurrent_worker)
2673 
2674  /* Finally close out the last transaction. */
2676 }
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:542
#define NIL
Definition: pg_list.h:65
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:152
static int default_freeze_table_age
Definition: autovacuum.c:153
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:111
#define AllocSetContextCreate
Definition: memutils.h:173
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define NUM_WORKITEMS
Definition: autovacuum.c:265
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
static void autovac_balance_cost(void)
Definition: autovacuum.c:1796
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:64
#define HASH_ELEM
Definition: hsearch.h:95
void ProcessConfigFile(GucContext context)
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
Definition: autovacuum.c:2793
void vac_update_datfrozenxid(void)
Definition: vacuum.c:1433
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static int default_multixact_freeze_min_age
Definition: autovacuum.c:154
#define RelationGetDescr(relation)
Definition: rel.h:503
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:200
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
void CommitTransactionCommand(void)
Definition: xact.c:2939
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:158
double wi_cost_delay
Definition: autovacuum.c:230
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Size entrysize
Definition: hsearch.h:76
static void autovac_refresh_stats(void)
Definition: autovacuum.c:3532
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2713
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
char * at_datname
Definition: autovacuum.c:200
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4579
void FlushErrorState(void)
Definition: elog.c:1654
MemoryContext PortalContext
Definition: mcxt.c:57
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
TempNamespaceStatus checkTempNamespaceStatus(Oid namespaceId)
Definition: namespace.c:3282
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:133
int at_vacuum_cost_limit
Definition: autovacuum.c:195
Definition: dynahash.c:219
char * at_relname
Definition: autovacuum.c:198
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
bits32 options
Definition: vacuum.h:211
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
int VacuumCostLimit
Definition: globals.c:144
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:63
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2113
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:290
PgStat_StatTabEntry * pgstat_fetch_stat_tabentry(Oid relid)
Definition: pgstat.c:2740
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:313
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
static void perform_work_item(AutoVacuumWorkItem *workitem)
Definition: autovacuum.c:2682
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:303
static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, PgStat_StatTabEntry *tabentry, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
Definition: autovacuum.c:3106
void pgstat_vacuum_stat(void)
Definition: pgstat.c:1074
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2828
int wi_cost_limit_base
Definition: autovacuum.c:232
MemoryContext TopMemoryContext
Definition: mcxt.c:48
Definition: guc.h:72
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1127
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define HASH_BLOBS
Definition: hsearch.h:97
char * at_nspname
Definition: autovacuum.c:199
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Oid MyDatabaseId
Definition: globals.c:88
double at_vacuum_cost_delay
Definition: autovacuum.c:194
Size keysize
Definition: hsearch.h:75
dlist_node * cur
Definition: ilist.h:161
void EmitErrorReport(void)
Definition: elog.c:1509
PgStat_Counter changes_since_analyze
Definition: pgstat.h:795
#define InvalidOid
Definition: postgres_ext.h:36
static PgStat_StatTabEntry * get_pgstat_tabentry_relid(Oid relid, bool isshared, PgStat_StatDBEntry *shared, PgStat_StatDBEntry *dbentry)
Definition: autovacuum.c:2820
VacuumParams at_params
Definition: autovacuum.c:193
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_CATCH()
Definition: elog.h:323
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define VACOPT_VACUUM
Definition: vacuum.h:178
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:135
void StartTransactionCommand(void)
Definition: xact.c:2838
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int vacuum_freeze_min_age
Definition: vacuum.c:61
int vacuum_freeze_table_age
Definition: vacuum.c:62
#define CharGetDatum(X)
Definition: postgres.h:460
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
AutoVacOpts ar_reloptions
Definition: autovacuum.c:185
PgStat_Counter changes_since_analyze_reported
Definition: pgstat.h:796
#define AccessExclusiveLock
Definition: lockdefs.h:45
static void autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
Definition: autovacuum.c:3276
int errmsg(const char *fmt,...)
Definition: elog.c:909
double VacuumCostDelay
Definition: globals.c:145
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
#define elog(elevel,...)
Definition: elog.h:232
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
int i
#define errcontext
Definition: elog.h:204
#define NameStr(name)
Definition: c.h:681
struct av_relation av_relation
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void AutoVacuumUpdateDelay(void)
Definition: autovacuum.c:1780
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
static autovac_table * table_recheck_autovac(Oid relid, HTAB *table_toast_map, TupleDesc pg_class_desc, int effective_multixact_freeze_max_age)
Definition: autovacuum.c:2847
dlist_head av_runningWorkers
Definition: autovacuum.c:288
#define PG_TRY()
Definition: elog.h:313
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:137
bool ar_hasrelopts
Definition: autovacuum.c:184
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
static int default_multixact_freeze_table_age
Definition: autovacuum.c:155
static int default_freeze_min_age
Definition: autovacuum.c:152
#define PG_END_TRY()
Definition: elog.h:338
#define BTEqualStrategyNumber
Definition: stratnum.h:31
bool at_dobalance
Definition: autovacuum.c:196
#define lfirst_oid(lc)
Definition: pg_list.h:171
void pgstat_report_anl_ancestors(Oid relid)
Definition: pgstat.c:1674
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:133

◆ do_start_worker()

static Oid do_start_worker ( void  )
static

Definition at line 1150 of file autovacuum.c.

References avl_dbase::adl_datid, avl_dbase::adl_next_worker, avl_dbase::adl_node, avw_dbase::adw_datid, avw_dbase::adw_entry, avw_dbase::adw_frozenxid, avw_dbase::adw_minmulti, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, autovac_refresh_stats(), autovacuum_freeze_max_age, autovacuum_naptime, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_startingWorker, dlist_iter::cur, CurrentMemoryContext, dblist, dlist_container, dlist_is_empty(), dlist_pop_head_node(), dlist_reverse_foreach, FirstMultiXactId, FirstNormalTransactionId, get_database_list(), GetCurrentTimestamp(), InvalidOid, PgStat_StatDBEntry::last_autovac_time, lfirst, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextDelete(), MemoryContextSwitchTo(), MultiXactIdPrecedes(), MultiXactMemberFreezeThreshold(), pgstat_fetch_stat_dbentry(), PMSIGNAL_START_AUTOVAC_WORKER, ReadNextMultiXactId(), ReadNextTransactionId(), rebuild_database_list(), recentMulti, recentXid, SendPostmasterSignal(), TimestampDifferenceExceeds(), TransactionIdPrecedes(), WorkerInfoData::wi_dboid, WorkerInfoData::wi_launchtime, and WorkerInfoData::wi_proc.

Referenced by AutoVacLauncherMain(), and launch_worker().

1151 {
1152  List *dblist;
1153  ListCell *cell;
1154  TransactionId xidForceLimit;
1155  MultiXactId multiForceLimit;
1156  bool for_xid_wrap;
1157  bool for_multi_wrap;
1158  avw_dbase *avdb;
1159  TimestampTz current_time;
1160  bool skipit = false;
1161  Oid retval = InvalidOid;
1162  MemoryContext tmpcxt,
1163  oldcxt;
1164 
1165  /* return quickly when there are no free workers */
1166  LWLockAcquire(AutovacuumLock, LW_SHARED);
1168  {
1169  LWLockRelease(AutovacuumLock);
1170  return InvalidOid;
1171  }
1172  LWLockRelease(AutovacuumLock);
1173 
1174  /*
1175  * Create and switch to a temporary context to avoid leaking the memory
1176  * allocated for the database list.
1177  */
1179  "Start worker tmp cxt",
1181  oldcxt = MemoryContextSwitchTo(tmpcxt);
1182 
1183  /* use fresh stats */
1185 
1186  /* Get a list of databases */
1187  dblist = get_database_list();
1188 
1189  /*
1190  * Determine the oldest datfrozenxid/relfrozenxid that we will allow to
1191  * pass without forcing a vacuum. (This limit can be tightened for
1192  * particular tables, but not loosened.)
1193  */
1195  xidForceLimit = recentXid - autovacuum_freeze_max_age;
1196  /* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
1197  /* this can cause the limit to go backwards by 3, but that's OK */
1198  if (xidForceLimit < FirstNormalTransactionId)
1199  xidForceLimit -= FirstNormalTransactionId;
1200 
1201  /* Also determine the oldest datminmxid we will consider. */
1203  multiForceLimit = recentMulti - MultiXactMemberFreezeThreshold();
1204  if (multiForceLimit < FirstMultiXactId)
1205  multiForceLimit -= FirstMultiXactId;
1206 
1207  /*
1208  * Choose a database to connect to. We pick the database that was least
1209  * recently auto-vacuumed, or one that needs vacuuming to prevent Xid
1210  * wraparound-related data loss. If any db at risk of Xid wraparound is
1211  * found, we pick the one with oldest datfrozenxid, independently of
1212  * autovacuum times; similarly we pick the one with the oldest datminmxid
1213  * if any is in MultiXactId wraparound. Note that those in Xid wraparound
1214  * danger are given more priority than those in multi wraparound danger.
1215  *
1216  * Note that a database with no stats entry is not considered, except for
1217  * Xid wraparound purposes. The theory is that if no one has ever
1218  * connected to it since the stats were last initialized, it doesn't need
1219  * vacuuming.
1220  *
1221  * XXX This could be improved if we had more info about whether it needs
1222  * vacuuming before connecting to it. Perhaps look through the pgstats
1223  * data for the database's tables? One idea is to keep track of the
1224  * number of new and dead tuples per database in pgstats. However it
1225  * isn't clear how to construct a metric that measures that and not cause
1226  * starvation for less busy databases.
1227  */
1228  avdb = NULL;
1229  for_xid_wrap = false;
1230  for_multi_wrap = false;
1231  current_time = GetCurrentTimestamp();
1232  foreach(cell, dblist)
1233  {
1234  avw_dbase *tmp = lfirst(cell);
1235  dlist_iter iter;
1236 
1237  /* Check to see if this one is at risk of wraparound */
1238  if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit))
1239  {
1240  if (avdb == NULL ||
1242  avdb->adw_frozenxid))
1243  avdb = tmp;
1244  for_xid_wrap = true;
1245  continue;
1246  }
1247  else if (for_xid_wrap)
1248  continue; /* ignore not-at-risk DBs */
1249  else if (MultiXactIdPrecedes(tmp->adw_minmulti, multiForceLimit))
1250  {
1251  if (avdb == NULL ||
1253  avdb = tmp;
1254  for_multi_wrap = true;
1255  continue;
1256  }
1257  else if (for_multi_wrap)
1258  continue; /* ignore not-at-risk DBs */
1259 
1260  /* Find pgstat entry if any */
1262 
1263  /*
1264  * Skip a database with no pgstat entry; it means it hasn't seen any
1265  * activity.
1266  */
1267  if (!tmp->adw_entry)
1268  continue;
1269 
1270  /*
1271  * Also, skip a database that appears on the database list as having
1272  * been processed recently (less than autovacuum_naptime seconds ago).
1273  * We do this so that we don't select a database which we just
1274  * selected, but that pgstat hasn't gotten around to updating the last
1275  * autovacuum time yet.
1276  */
1277  skipit = false;
1278 
1280  {
1281  avl_dbase *dbp = dlist_container(avl_dbase, adl_node, iter.cur);
1282 
1283  if (dbp->adl_datid == tmp->adw_datid)
1284  {
1285  /*
1286  * Skip this database if its next_worker value falls between
1287  * the current time and the current time plus naptime.
1288  */
1290  current_time, 0) &&
1291  !TimestampDifferenceExceeds(current_time,
1292  dbp->adl_next_worker,
1293  autovacuum_naptime * 1000))
1294  skipit = true;
1295 
1296  break;
1297  }
1298  }
1299  if (skipit)
1300  continue;
1301 
1302  /*
1303  * Remember the db with oldest autovac time. (If we are here, both
1304  * tmp->entry and db->entry must be non-null.)
1305  */
1306  if (avdb == NULL ||
1308  avdb = tmp;
1309  }
1310 
1311  /* Found a database -- process it */
1312  if (avdb != NULL)
1313  {
1314  WorkerInfo worker;
1315  dlist_node *wptr;
1316 
1317  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1318 
1319  /*
1320  * Get a worker entry from the freelist. We checked above, so there
1321  * really should be a free slot.
1322  */
1324 
1325  worker = dlist_container(WorkerInfoData, wi_links, wptr);
1326  worker->wi_dboid = avdb->adw_datid;
1327  worker->wi_proc = NULL;
1328  worker->wi_launchtime = GetCurrentTimestamp();
1329 
1331 
1332  LWLockRelease(AutovacuumLock);
1333 
1335 
1336  retval = avdb->adw_datid;
1337  }
1338  else if (skipit)
1339  {
1340  /*
1341  * If we skipped all databases on the list, rebuild it, because it
1342  * probably contains a dropped database.
1343  */
1345  }
1346 
1347  MemoryContextSwitchTo(oldcxt);
1348  MemoryContextDelete(tmpcxt);
1349 
1350  return retval;
1351 }
int autovacuum_naptime
Definition: autovacuum.c:118
TimestampTz adl_next_worker
Definition: autovacuum.c:164
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
MultiXactId adw_minmulti
Definition: autovacuum.c:175
WorkerInfo av_startingWorker
Definition: autovacuum.c:289
dlist_head av_freeWorkers
Definition: autovacuum.c:287
uint32 TransactionId
Definition: c.h:587
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
TimestampTz wi_launchtime
Definition: autovacuum.c:227
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static MultiXactId recentMulti
Definition: autovacuum.c:149
static void autovac_refresh_stats(void)
Definition: autovacuum.c:3532
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2713
static TransactionId ReadNextTransactionId(void)
Definition: transam.h:316
unsigned int Oid
Definition: postgres_ext.h:31
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
#define FirstNormalTransactionId
Definition: transam.h:34
int autovacuum_freeze_max_age
Definition: autovacuum.c:125
Oid adl_datid
Definition: autovacuum.c:163
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
_stringlist * dblist
Definition: pg_regress.c:75
TimestampTz last_autovac_time
Definition: pgstat.h:742
#define FirstMultiXactId
Definition: multixact.h:25
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
static dlist_head DatabaseList
Definition: autovacuum.c:299
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2828
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
TransactionId adw_frozenxid
Definition: autovacuum.c:174
PgStat_StatDBEntry * adw_entry
Definition: autovacuum.c:176
Oid adw_datid
Definition: autovacuum.c:172
static TransactionId recentXid
Definition: autovacuum.c:148
dlist_node * cur
Definition: ilist.h:161
#define InvalidOid
Definition: postgres_ext.h:36
TransactionId MultiXactId
Definition: c.h:597
#define lfirst(lc)
Definition: pg_list.h:169
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3159
static List * get_database_list(void)
Definition: autovacuum.c:1884
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:949
static dlist_node * dlist_pop_head_node(dlist_head *head)
Definition: ilist.h:368
PGPROC * wi_proc
Definition: autovacuum.c:226
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:153
Definition: pg_list.h:50
#define dlist_reverse_foreach(iter, lhead)
Definition: ilist.h:557
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723

◆ extract_autovac_opts()

static AutoVacOpts* extract_autovac_opts ( HeapTuple  tup,
TupleDesc  pg_class_desc 
)
static

Definition at line 2793 of file autovacuum.c.

References Assert, av, extractRelOptions(), GETSTRUCT, palloc(), and pfree().

Referenced by do_autovacuum(), and table_recheck_autovac().

2794 {
2795  bytea *relopts;
2796  AutoVacOpts *av;
2797 
2798  Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2799  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2800  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_PARTITIONED_TABLE ||
2801  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2802 
2803  relopts = extractRelOptions(tup, pg_class_desc, NULL);
2804  if (relopts == NULL)
2805  return NULL;
2806 
2807  av = palloc(sizeof(AutoVacOpts));
2808  memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2809  pfree(relopts);
2810 
2811  return av;
2812 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
struct @11::@12 av[32]
void pfree(void *pointer)
Definition: mcxt.c:1169
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
Definition: reloptions.c:1374
#define Assert(condition)
Definition: c.h:804
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
void * palloc(Size size)
Definition: mcxt.c:1062
Definition: c.h:621

◆ FreeWorkerInfo()

static void FreeWorkerInfo ( int  code,
Datum  arg 
)
static

Definition at line 1731 of file autovacuum.c.

References AutoVacRebalance, AutovacuumLauncherPid, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_signal, dlist_delete(), dlist_push_head(), InvalidOid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), WorkerInfoData::wi_cost_delay, WorkerInfoData::wi_cost_limit, WorkerInfoData::wi_cost_limit_base, WorkerInfoData::wi_dboid, WorkerInfoData::wi_dobalance, WorkerInfoData::wi_launchtime, WorkerInfoData::wi_links, WorkerInfoData::wi_proc, WorkerInfoData::wi_sharedrel, and WorkerInfoData::wi_tableoid.

Referenced by AutoVacWorkerMain().

1732 {
1733  if (MyWorkerInfo != NULL)
1734  {
1735  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1736 
1737  /*
1738  * Wake the launcher up so that he can launch a new worker immediately
1739  * if required. We only save the launcher's PID in local memory here;
1740  * the actual signal will be sent when the PGPROC is recycled. Note
1741  * that we always do this, so that the launcher can rebalance the cost
1742  * limit setting of the remaining workers.
1743  *
1744  * We somewhat ignore the risk that the launcher changes its PID
1745  * between us reading it and the actual kill; we expect ProcKill to be
1746  * called shortly after us, and we assume that PIDs are not reused too
1747  * quickly after a process exits.
1748  */
1750 
1754  MyWorkerInfo->wi_sharedrel = false;
1755  MyWorkerInfo->wi_proc = NULL;
1757  MyWorkerInfo->wi_dobalance = false;
1763  /* not mine anymore */
1764  MyWorkerInfo = NULL;
1765 
1766  /*
1767  * now that we're inactive, cause a rebalancing of the surviving
1768  * workers
1769  */
1771  LWLockRelease(AutovacuumLock);
1772  }
1773 }
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:285
dlist_head av_freeWorkers
Definition: autovacuum.c:287
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz wi_launchtime
Definition: autovacuum.c:227
double wi_cost_delay
Definition: autovacuum.c:230
dlist_node wi_links
Definition: autovacuum.c:223
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
int AutovacuumLauncherPid
Definition: autovacuum.c:306
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:303
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
int wi_cost_limit_base
Definition: autovacuum.c:232
#define InvalidOid
Definition: postgres_ext.h:36
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:293
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
PGPROC * wi_proc
Definition: autovacuum.c:226

◆ get_database_list()

static List* get_database_list ( void  )
static

Definition at line 1884 of file autovacuum.c.

References AccessShareLock, avw_dbase::adw_datid, avw_dbase::adw_entry, avw_dbase::adw_frozenxid, avw_dbase::adw_minmulti, avw_dbase::adw_name, CommitTransactionCommand(), CurrentMemoryContext, dblist, ForwardScanDirection, GETSTRUCT, GetTransactionSnapshot(), heap_getnext(), HeapTupleIsValid, lappend(), MemoryContextSwitchTo(), NameStr, NIL, palloc(), pstrdup(), StartTransactionCommand(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by do_start_worker(), and rebuild_database_list().

1885 {
1886  List *dblist = NIL;
1887  Relation rel;
1888  TableScanDesc scan;
1889  HeapTuple tup;
1890  MemoryContext resultcxt;
1891 
1892  /* This is the context that we will allocate our output data in */
1893  resultcxt = CurrentMemoryContext;
1894 
1895  /*
1896  * Start a transaction so we can access pg_database, and get a snapshot.
1897  * We don't have a use for the snapshot itself, but we're interested in
1898  * the secondary effect that it sets RecentGlobalXmin. (This is critical
1899  * for anything that reads heap pages, because HOT may decide to prune
1900  * them even if the process doesn't attempt to modify any tuples.)
1901  *
1902  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
1903  * not pushed/active does not reliably prevent HOT pruning (->xmin could
1904  * e.g. be cleared when cache invalidations are processed).
1905  */
1907  (void) GetTransactionSnapshot();
1908 
1909  rel = table_open(DatabaseRelationId, AccessShareLock);
1910  scan = table_beginscan_catalog(rel, 0, NULL);
1911 
1912  while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1913  {
1914  Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1915  avw_dbase *avdb;
1916  MemoryContext oldcxt;
1917 
1918  /*
1919  * Allocate our results in the caller's context, not the
1920  * transaction's. We do this inside the loop, and restore the original
1921  * context at the end, so that leaky things like heap_getnext() are
1922  * not called in a potentially long-lived context.
1923  */
1924  oldcxt = MemoryContextSwitchTo(resultcxt);
1925 
1926  avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1927 
1928  avdb->adw_datid = pgdatabase->oid;
1929  avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1930  avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1931  avdb->adw_minmulti = pgdatabase->datminmxid;
1932  /* this gets set later: */
1933  avdb->adw_entry = NULL;
1934 
1935  dblist = lappend(dblist, avdb);
1936  MemoryContextSwitchTo(oldcxt);
1937  }
1938 
1939  table_endscan(scan);
1941 
1943 
1944  return dblist;
1945 }
#define NIL
Definition: pg_list.h:65
MultiXactId adw_minmulti
Definition: autovacuum.c:175
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void CommitTransactionCommand(void)
Definition: xact.c:2939
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
_stringlist * dblist
Definition: pg_regress.c:75
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
char * adw_name
Definition: autovacuum.c:173
List * lappend(List *list, void *datum)
Definition: list.c:336
TransactionId adw_frozenxid
Definition: autovacuum.c:174
PgStat_StatDBEntry * adw_entry
Definition: autovacuum.c:176
Oid adw_datid
Definition: autovacuum.c:172
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void StartTransactionCommand(void)
Definition: xact.c:2838
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
void * palloc(Size size)
Definition: mcxt.c:1062
#define NameStr(name)
Definition: c.h:681
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50

◆ get_pgstat_tabentry_relid()

static PgStat_StatTabEntry* get_pgstat_tabentry_relid ( Oid  relid,
bool  isshared,
PgStat_StatDBEntry shared,
PgStat_StatDBEntry dbentry 
)
static

Definition at line 2820 of file autovacuum.c.

References HASH_FIND, hash_search(), PointerIsValid, and PgStat_StatDBEntry::tables.

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

2822 {
2823  PgStat_StatTabEntry *tabentry = NULL;
2824 
2825  if (isshared)
2826  {
2827  if (PointerIsValid(shared))
2828  tabentry = hash_search(shared->tables, &relid,
2829  HASH_FIND, NULL);
2830  }
2831  else if (PointerIsValid(dbentry))
2832  tabentry = hash_search(dbentry->tables, &relid,
2833  HASH_FIND, NULL);
2834 
2835  return tabentry;
2836 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
#define PointerIsValid(pointer)
Definition: c.h:698

◆ HandleAutoVacLauncherInterrupts()

static void HandleAutoVacLauncherInterrupts ( void  )
static

Definition at line 812 of file autovacuum.c.

References autovac_balance_cost(), AutoVacLauncherShutdown(), AutoVacuumingActive(), AutoVacuumShmemStruct::av_launcherpid, ConfigReloadPending, DEBUG1, ereport, errmsg_internal(), InvalidOid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), PGC_SIGHUP, proc_exit(), ProcessCatchupInterrupt(), ProcessConfigFile(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, rebuild_database_list(), and ShutdownRequestPending.

Referenced by AutoVacLauncherMain().

813 {
814  /* the normal shutdown case */
817 
819  {
820  ConfigReloadPending = false;
822 
823  /* shutdown requested in config file? */
824  if (!AutoVacuumingActive())
826 
827  /* rebalance in case the default cost parameters changed */
828  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
830  LWLockRelease(AutovacuumLock);
831 
832  /* rebuild the list in case the naptime changed */
834  }
835 
836  /* Process barrier events */
839 
840  /* Process sinval catchup interrupts that happened while sleeping */
842 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
static void autovac_balance_cost(void)
Definition: autovacuum.c:1796
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3380
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:27
Definition: guc.h:72
#define InvalidOid
Definition: postgres_ext.h:36
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:949
static void AutoVacLauncherShutdown(void)
Definition: autovacuum.c:317
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26

◆ IsAutoVacuumLauncherProcess()

bool IsAutoVacuumLauncherProcess ( void  )

Definition at line 3448 of file autovacuum.c.

References am_autovacuum_launcher.

Referenced by autovac_refresh_stats(), backend_read_statsfile(), InitPostgres(), InitProcess(), and ProcKill().

3449 {
3450  return am_autovacuum_launcher;
3451 }
static bool am_autovacuum_launcher
Definition: autovacuum.c:141

◆ IsAutoVacuumWorkerProcess()

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1365 of file autovacuum.c.

References avl_dbase::adl_datid, avl_dbase::adl_next_worker, avl_dbase::adl_node, autovacuum_naptime, dlist_iter::cur, dlist_container, dlist_foreach, dlist_move_head(), do_start_worker(), OidIsValid, rebuild_database_list(), and TimestampTzPlusMilliseconds.

Referenced by AutoVacLauncherMain().

1366 {
1367  Oid dbid;
1368  dlist_iter iter;
1369 
1370  dbid = do_start_worker();
1371  if (OidIsValid(dbid))
1372  {
1373  bool found = false;
1374 
1375  /*
1376  * Walk the database list and update the corresponding entry. If the
1377  * database is not on the list, we'll recreate the list.
1378  */
1379  dlist_foreach(iter, &DatabaseList)
1380  {
1381  avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1382 
1383  if (avdb->adl_datid == dbid)
1384  {
1385  found = true;
1386 
1387  /*
1388  * add autovacuum_naptime seconds to the current time, and use
1389  * that as the new "next_worker" field for this database.
1390  */
1391  avdb->adl_next_worker =
1393 
1395  break;
1396  }
1397  }
1398 
1399  /*
1400  * If the database was not present in the database list, we rebuild
1401  * the list. It's possible that the database does not get into the
1402  * list anyway, for example if it's a database that doesn't have a
1403  * pgstat entry, but this is not a problem because we don't want to
1404  * schedule workers regularly into those in any case.
1405  */
1406  if (!found)
1407  rebuild_database_list(dbid);
1408  }
1409 }
int autovacuum_naptime
Definition: autovacuum.c:118
TimestampTz adl_next_worker
Definition: autovacuum.c:164
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
Oid adl_datid
Definition: autovacuum.c:163
static dlist_head DatabaseList
Definition: autovacuum.c:299
dlist_node * cur
Definition: ilist.h:161
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
static void dlist_move_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:385
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:949
static Oid do_start_worker(void)
Definition: autovacuum.c:1150
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544

◆ launcher_determine_sleep()

static void launcher_determine_sleep ( bool  canlaunch,
bool  recursing,
struct timeval *  nap 
)
static

Definition at line 865 of file autovacuum.c.

References avl_dbase::adl_next_worker, avl_dbase::adl_node, autovacuum_naptime, dlist_is_empty(), dlist_tail_element, GetCurrentTimestamp(), InvalidOid, MAX_AUTOVAC_SLEEPTIME, MIN_AUTOVAC_SLEEPTIME, rebuild_database_list(), and TimestampDifference().

Referenced by AutoVacLauncherMain().

866 {
867  /*
868  * We sleep until the next scheduled vacuum. We trust that when the
869  * database list was built, care was taken so that no entries have times
870  * in the past; if the first entry has too close a next_worker value, or a
871  * time in the past, we will sleep a small nominal time.
872  */
873  if (!canlaunch)
874  {
875  nap->tv_sec = autovacuum_naptime;
876  nap->tv_usec = 0;
877  }
878  else if (!dlist_is_empty(&DatabaseList))
879  {
880  TimestampTz current_time = GetCurrentTimestamp();
881  TimestampTz next_wakeup;
882  avl_dbase *avdb;
883  long secs;
884  int usecs;
885 
886  avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
887 
888  next_wakeup = avdb->adl_next_worker;
889  TimestampDifference(current_time, next_wakeup, &secs, &usecs);
890 
891  nap->tv_sec = secs;
892  nap->tv_usec = usecs;
893  }
894  else
895  {
896  /* list is empty, sleep for whole autovacuum_naptime seconds */
897  nap->tv_sec = autovacuum_naptime;
898  nap->tv_usec = 0;
899  }
900 
901  /*
902  * If the result is exactly zero, it means a database had an entry with
903  * time in the past. Rebuild the list so that the databases are evenly
904  * distributed again, and recalculate the time to sleep. This can happen
905  * if there are more tables needing vacuum than workers, and they all take
906  * longer to vacuum than autovacuum_naptime.
907  *
908  * We only recurse once. rebuild_database_list should always return times
909  * in the future, but it seems best not to trust too much on that.
910  */
911  if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
912  {
914  launcher_determine_sleep(canlaunch, true, nap);
915  return;
916  }
917 
918  /* The smallest time we'll allow the launcher to sleep. */
919  if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
920  {
921  nap->tv_sec = 0;
922  nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000;
923  }
924 
925  /*
926  * If the sleep time is too large, clamp it to an arbitrary maximum (plus
927  * any fractional seconds, for simplicity). This avoids an essentially
928  * infinite sleep in strange cases like the system clock going backwards a
929  * few years.
930  */
931  if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME)
932  nap->tv_sec = MAX_AUTOVAC_SLEEPTIME;
933 }
int autovacuum_naptime
Definition: autovacuum.c:118
TimestampTz adl_next_worker
Definition: autovacuum.c:164
#define MAX_AUTOVAC_SLEEPTIME
Definition: autovacuum.c:138
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
#define MIN_AUTOVAC_SLEEPTIME
Definition: autovacuum.c:137
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:515
static dlist_head DatabaseList
Definition: autovacuum.c:299
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition: autovacuum.c:865
#define InvalidOid
Definition: postgres_ext.h:36
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:949
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1656

◆ perform_work_item()

static void perform_work_item ( AutoVacuumWorkItem workitem)
static

Definition at line 2682 of file autovacuum.c.

References AbortOutOfAnyTransaction(), Assert, autovac_report_workitem(), AutoVacuumWorkItem::avw_blockNumber, AVW_BRINSummarizeRange, AutoVacuumWorkItem::avw_relation, AutoVacuumWorkItem::avw_type, brin_summarize_range(), CurrentMemoryContext, DirectFunctionCall2, elog, EmitErrorReport(), errcontext, FlushErrorState(), get_database_name(), get_namespace_name(), get_rel_name(), get_rel_namespace(), HOLD_INTERRUPTS, Int64GetDatum(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MyDatabaseId, ObjectIdGetDatum, pfree(), PG_CATCH, PG_END_TRY, PG_TRY, PortalContext, QueryCancelPending, RESUME_INTERRUPTS, StartTransactionCommand(), and WARNING.

Referenced by do_autovacuum().

2683 {
2684  char *cur_datname = NULL;
2685  char *cur_nspname = NULL;
2686  char *cur_relname = NULL;
2687 
2688  /*
2689  * Note we do not store table info in MyWorkerInfo, since this is not
2690  * vacuuming proper.
2691  */
2692 
2693  /*
2694  * Save the relation name for a possible error message, to avoid a catalog
2695  * lookup in case of an error. If any of these return NULL, then the
2696  * relation has been dropped since last we checked; skip it.
2697  */
2699 
2700  cur_relname = get_rel_name(workitem->avw_relation);
2701  cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2702  cur_datname = get_database_name(MyDatabaseId);
2703  if (!cur_relname || !cur_nspname || !cur_datname)
2704  goto deleted2;
2705 
2706  autovac_report_workitem(workitem, cur_nspname, cur_relname);
2707 
2708  /* clean up memory before each work item */
2710 
2711  /*
2712  * We will abort the current work item if something errors out, and
2713  * continue with the next one; in particular, this happens if we are
2714  * interrupted with SIGINT. Note that this means that the work item list
2715  * can be lossy.
2716  */
2717  PG_TRY();
2718  {
2719  /* Use PortalContext for any per-work-item allocations */
2721 
2722  /* have at it */
2723  switch (workitem->avw_type)
2724  {
2727  ObjectIdGetDatum(workitem->avw_relation),
2728  Int64GetDatum((int64) workitem->avw_blockNumber));
2729  break;
2730  default:
2731  elog(WARNING, "unrecognized work item found: type %d",
2732  workitem->avw_type);
2733  break;
2734  }
2735 
2736  /*
2737  * Clear a possible query-cancel signal, to avoid a late reaction to
2738  * an automatically-sent signal because of vacuuming the current table
2739  * (we're done with it, so it would make no sense to cancel at this
2740  * point.)
2741  */
2742  QueryCancelPending = false;
2743  }
2744  PG_CATCH();
2745  {
2746  /*
2747  * Abort the transaction, start a new one, and proceed with the next
2748  * table in our list.
2749  */
2750  HOLD_INTERRUPTS();
2751  errcontext("processing work entry for relation \"%s.%s.%s\"",
2752  cur_datname, cur_nspname, cur_relname);
2753  EmitErrorReport();
2754 
2755  /* this resets ProcGlobal->statusFlags[i] too */
2757  FlushErrorState();
2759 
2760  /* restart our transaction for the following operations */
2763  }
2764  PG_END_TRY();
2765 
2766  /* Make sure we're back in AutovacMemCxt */
2768 
2769  /* We intentionally do not set did_vacuum here */
2770 
2771  /* be tidy */
2772 deleted2:
2773  if (cur_datname)
2774  pfree(cur_datname);
2775  if (cur_nspname)
2776  pfree(cur_nspname);
2777  if (cur_relname)
2778  pfree(cur_relname);
2779 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:257
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:158
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4579
void FlushErrorState(void)
Definition: elog.c:1654
MemoryContext PortalContext
Definition: mcxt.c:57
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:1002
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:133
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2113
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
Definition: autovacuum.c:3340
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1697
#define WARNING
Definition: elog.h:40
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
Oid MyDatabaseId
Definition: globals.c:88
BlockNumber avw_blockNumber
Definition: autovacuum.c:262
void EmitErrorReport(void)
Definition: elog.c:1509
#define PG_CATCH()
Definition: elog.h:323
#define Assert(condition)
Definition: c.h:804
void StartTransactionCommand(void)
Definition: xact.c:2838
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:131
#define elog(elevel,...)
Definition: elog.h:232
#define errcontext
Definition: elog.h:204
#define PG_TRY()
Definition: elog.h:313
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:628
#define PG_END_TRY()
Definition: elog.h:338

◆ rebuild_database_list()

static void rebuild_database_list ( Oid  newdb)
static

Definition at line 949 of file autovacuum.c.

References avl_dbase::adl_datid, avl_dbase::adl_next_worker, avl_dbase::adl_node, avl_dbase::adl_score, avw_dbase::adw_datid, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, autovac_refresh_stats(), autovacuum_naptime, dlist_iter::cur, db_comparator(), dblist, dlist_container, dlist_foreach, dlist_init(), dlist_push_head(), HASHCTL::entrysize, get_database_list(), GetCurrentTimestamp(), HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), hash_seq_init(), hash_seq_search(), HASHCTL::hcxt, i, HASHCTL::keysize, lfirst, MemoryContextDelete(), MemoryContextSwitchTo(), MIN_AUTOVAC_SLEEPTIME, OidIsValid, palloc(), pgstat_fetch_stat_dbentry(), qsort, and TimestampTzPlusMilliseconds.

Referenced by AutoVacLauncherMain(), do_start_worker(), HandleAutoVacLauncherInterrupts(), launch_worker(), and launcher_determine_sleep().

950 {
951  List *dblist;
952  ListCell *cell;
953  MemoryContext newcxt;
954  MemoryContext oldcxt;
955  MemoryContext tmpcxt;
956  HASHCTL hctl;
957  int score;
958  int nelems;
959  HTAB *dbhash;
960  dlist_iter iter;
961 
962  /* use fresh stats */
964 
966  "AV dblist",
968  tmpcxt = AllocSetContextCreate(newcxt,
969  "tmp AV dblist",
971  oldcxt = MemoryContextSwitchTo(tmpcxt);
972 
973  /*
974  * Implementing this is not as simple as it sounds, because we need to put
975  * the new database at the end of the list; next the databases that were
976  * already on the list, and finally (at the tail of the list) all the
977  * other databases that are not on the existing list.
978  *
979  * To do this, we build an empty hash table of scored databases. We will
980  * start with the lowest score (zero) for the new database, then
981  * increasing scores for the databases in the existing list, in order, and
982  * lastly increasing scores for all databases gotten via
983  * get_database_list() that are not already on the hash.
984  *
985  * Then we will put all the hash elements into an array, sort the array by
986  * score, and finally put the array elements into the new doubly linked
987  * list.
988  */
989  hctl.keysize = sizeof(Oid);
990  hctl.entrysize = sizeof(avl_dbase);
991  hctl.hcxt = tmpcxt;
992  dbhash = hash_create("db hash", 20, &hctl, /* magic number here FIXME */
994 
995  /* start by inserting the new database */
996  score = 0;
997  if (OidIsValid(newdb))
998  {
999  avl_dbase *db;
1000  PgStat_StatDBEntry *entry;
1001 
1002  /* only consider this database if it has a pgstat entry */
1003  entry = pgstat_fetch_stat_dbentry(newdb);
1004  if (entry != NULL)
1005  {
1006  /* we assume it isn't found because the hash was just created */
1007  db = hash_search(dbhash, &newdb, HASH_ENTER, NULL);
1008 
1009  /* hash_search already filled in the key */
1010  db->adl_score = score++;
1011  /* next_worker is filled in later */
1012  }
1013  }
1014 
1015  /* Now insert the databases from the existing list */
1016  dlist_foreach(iter, &DatabaseList)
1017  {
1018  avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1019  avl_dbase *db;
1020  bool found;
1021  PgStat_StatDBEntry *entry;
1022 
1023  /*
1024  * skip databases with no stat entries -- in particular, this gets rid
1025  * of dropped databases
1026  */
1027  entry = pgstat_fetch_stat_dbentry(avdb->adl_datid);
1028  if (entry == NULL)
1029  continue;
1030 
1031  db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found);
1032 
1033  if (!found)
1034  {
1035  /* hash_search already filled in the key */
1036  db->adl_score = score++;
1037  /* next_worker is filled in later */
1038  }
1039  }
1040 
1041  /* finally, insert all qualifying databases not previously inserted */
1042  dblist = get_database_list();
1043  foreach(cell, dblist)
1044  {
1045  avw_dbase *avdb = lfirst(cell);
1046  avl_dbase *db;
1047  bool found;
1048  PgStat_StatDBEntry *entry;
1049 
1050  /* only consider databases with a pgstat entry */
1051  entry = pgstat_fetch_stat_dbentry(avdb->adw_datid);
1052  if (entry == NULL)
1053  continue;
1054 
1055  db = hash_search(dbhash, &(avdb->adw_datid), HASH_ENTER, &found);
1056  /* only update the score if the database was not already on the hash */
1057  if (!found)
1058  {
1059  /* hash_search already filled in the key */
1060  db->adl_score = score++;
1061  /* next_worker is filled in later */
1062  }
1063  }
1064  nelems = score;
1065 
1066  /* from here on, the allocated memory belongs to the new list */
1067  MemoryContextSwitchTo(newcxt);
1069 
1070  if (nelems > 0)
1071  {
1072  TimestampTz current_time;
1073  int millis_increment;
1074  avl_dbase *dbary;
1075  avl_dbase *db;
1076  HASH_SEQ_STATUS seq;
1077  int i;
1078 
1079  /* put all the hash elements into an array */
1080  dbary = palloc(nelems * sizeof(avl_dbase));
1081 
1082  i = 0;
1083  hash_seq_init(&seq, dbhash);
1084  while ((db = hash_seq_search(&seq)) != NULL)
1085  memcpy(&(dbary[i++]), db, sizeof(avl_dbase));
1086 
1087  /* sort the array */
1088  qsort(dbary, nelems, sizeof(avl_dbase), db_comparator);
1089 
1090  /*
1091  * Determine the time interval between databases in the schedule. If
1092  * we see that the configured naptime would take us to sleep times
1093  * lower than our min sleep time (which launcher_determine_sleep is
1094  * coded not to allow), silently use a larger naptime (but don't touch
1095  * the GUC variable).
1096  */
1097  millis_increment = 1000.0 * autovacuum_naptime / nelems;
1098  if (millis_increment <= MIN_AUTOVAC_SLEEPTIME)
1099  millis_increment = MIN_AUTOVAC_SLEEPTIME * 1.1;
1100 
1101  current_time = GetCurrentTimestamp();
1102 
1103  /*
1104  * move the elements from the array into the dlist, setting the
1105  * next_worker while walking the array
1106  */
1107  for (i = 0; i < nelems; i++)
1108  {
1109  avl_dbase *db = &(dbary[i]);
1110 
1111  current_time = TimestampTzPlusMilliseconds(current_time,
1112  millis_increment);
1113  db->adl_next_worker = current_time;
1114 
1115  /* later elements should go closer to the head of the list */
1117  }
1118  }
1119 
1120  /* all done, clean up memory */
1121  if (DatabaseListCxt != NULL)
1123  MemoryContextDelete(tmpcxt);
1124  DatabaseListCxt = newcxt;
1125  MemoryContextSwitchTo(oldcxt);
1126 }
int autovacuum_naptime
Definition: autovacuum.c:118
TimestampTz adl_next_worker
Definition: autovacuum.c:164
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
MemoryContext hcxt
Definition: hsearch.h:86
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
int adl_score
Definition: autovacuum.c:165
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:158
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Size entrysize
Definition: hsearch.h:76
struct avl_dbase avl_dbase
static void autovac_refresh_stats(void)
Definition: autovacuum.c:3532
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2713
#define MIN_AUTOVAC_SLEEPTIME
Definition: autovacuum.c:137
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
Definition: dynahash.c:219
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
Oid adl_datid
Definition: autovacuum.c:163
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
_stringlist * dblist
Definition: pg_regress.c:75
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
static dlist_head DatabaseList
Definition: autovacuum.c:299
static int db_comparator(const void *a, const void *b)
Definition: autovacuum.c:1130
#define HASH_BLOBS
Definition: hsearch.h:97
Oid adw_datid
Definition: autovacuum.c:172
Size keysize
Definition: hsearch.h:75
dlist_node * cur
Definition: ilist.h:161
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define lfirst(lc)
Definition: pg_list.h:169
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1436
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1426
static List * get_database_list(void)
Definition: autovacuum.c:1884
dlist_node adl_node
Definition: autovacuum.c:166
void * palloc(Size size)
Definition: mcxt.c:1062
static MemoryContext DatabaseListCxt
Definition: autovacuum.c:300
int i
#define qsort(a, b, c, d)
Definition: port.h:504
Definition: pg_list.h:50

◆ recheck_relation_needs_vacanalyze()

static void recheck_relation_needs_vacanalyze ( Oid  relid,
AutoVacOpts avopts,
Form_pg_class  classForm,
int  effective_multixact_freeze_max_age,
bool dovacuum,
bool doanalyze,
bool wraparound 
)
static

Definition at line 3038 of file autovacuum.c.

References get_pgstat_tabentry_relid(), InvalidOid, MyDatabaseId, pgstat_fetch_stat_dbentry(), and relation_needs_vacanalyze().

Referenced by table_recheck_autovac().

3045 {
3046  PgStat_StatTabEntry *tabentry;
3047  PgStat_StatDBEntry *shared = NULL;
3048  PgStat_StatDBEntry *dbentry = NULL;
3049 
3050  if (classForm->relisshared)
3052  else
3054 
3055  /* fetch the pgstat table entry */
3056  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
3057  shared, dbentry);
3058 
3059  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
3060  effective_multixact_freeze_max_age,
3061  dovacuum, doanalyze, wraparound);
3062 
3063  /* ignore ANALYZE for toast tables */
3064  if (classForm->relkind == RELKIND_TOASTVALUE)
3065  *doanalyze = false;
3066 }
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2713
static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, PgStat_StatTabEntry *tabentry, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
Definition: autovacuum.c:3106
Oid MyDatabaseId
Definition: globals.c:88
#define InvalidOid
Definition: postgres_ext.h:36
static PgStat_StatTabEntry * get_pgstat_tabentry_relid(Oid relid, bool isshared, PgStat_StatDBEntry *shared, PgStat_StatDBEntry *dbentry)
Definition: autovacuum.c:2820

◆ relation_needs_vacanalyze()

static void relation_needs_vacanalyze ( Oid  relid,
AutoVacOpts relopts,
Form_pg_class  classForm,
PgStat_StatTabEntry tabentry,
int  effective_multixact_freeze_max_age,
bool dovacuum,
bool doanalyze,
bool wraparound 
)
static

Definition at line 3106 of file autovacuum.c.

References AutoVacOpts::analyze_scale_factor, AutoVacOpts::analyze_threshold, AssertArg, autovacuum_anl_scale, autovacuum_anl_thresh, autovacuum_freeze_max_age, autovacuum_vac_ins_scale, autovacuum_vac_ins_thresh, autovacuum_vac_scale, autovacuum_vac_thresh, AutoVacuumingActive(), PgStat_StatTabEntry::changes_since_analyze, DEBUG3, elog, AutoVacOpts::enabled, FirstMultiXactId, FirstNormalTransactionId, AutoVacOpts::freeze_max_age, PgStat_StatTabEntry::inserts_since_vacuum, Min, AutoVacOpts::multixact_freeze_max_age, MultiXactIdIsValid, MultiXactIdPrecedes(), PgStat_StatTabEntry::n_dead_tuples, NameStr, OidIsValid, PointerIsValid, recentMulti, recentXid, TransactionIdIsNormal, TransactionIdPrecedes(), AutoVacOpts::vacuum_ins_scale_factor, AutoVacOpts::vacuum_ins_threshold, AutoVacOpts::vacuum_scale_factor, and AutoVacOpts::vacuum_threshold.

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

3115 {
3116  bool force_vacuum;
3117  bool av_enabled;
3118  float4 reltuples; /* pg_class.reltuples */
3119 
3120  /* constants from reloptions or GUC variables */
3121  int vac_base_thresh,
3122  vac_ins_base_thresh,
3123  anl_base_thresh;
3124  float4 vac_scale_factor,
3125  vac_ins_scale_factor,
3126  anl_scale_factor;
3127 
3128  /* thresholds calculated from above constants */
3129  float4 vacthresh,
3130  vacinsthresh,
3131  anlthresh;
3132 
3133  /* number of vacuum (resp. analyze) tuples at this time */
3134  float4 vactuples,
3135  instuples,
3136  anltuples;
3137 
3138  /* freeze parameters */
3139  int freeze_max_age;
3140  int multixact_freeze_max_age;
3141  TransactionId xidForceLimit;
3142  MultiXactId multiForceLimit;
3143 
3144  AssertArg(classForm != NULL);
3145  AssertArg(OidIsValid(relid));
3146 
3147  /*
3148  * Determine vacuum/analyze equation parameters. We have two possible
3149  * sources: the passed reloptions (which could be a main table or a toast
3150  * table), or the autovacuum GUC variables.
3151  */
3152 
3153  /* -1 in autovac setting means use plain vacuum_scale_factor */
3154  vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3155  ? relopts->vacuum_scale_factor
3157 
3158  vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3159  ? relopts->vacuum_threshold
3161 
3162  vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3163  ? relopts->vacuum_ins_scale_factor
3165 
3166  /* -1 is used to disable insert vacuums */
3167  vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3168  ? relopts->vacuum_ins_threshold
3170 
3171  anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3172  ? relopts->analyze_scale_factor
3174 
3175  anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3176  ? relopts->analyze_threshold
3178 
3179  freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3182 
3183  multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3184  ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3185  : effective_multixact_freeze_max_age;
3186 
3187  av_enabled = (relopts ? relopts->enabled : true);
3188 
3189  /* Force vacuum if table is at risk of wraparound */
3190  xidForceLimit = recentXid - freeze_max_age;
3191  if (xidForceLimit < FirstNormalTransactionId)
3192  xidForceLimit -= FirstNormalTransactionId;
3193  force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
3194  TransactionIdPrecedes(classForm->relfrozenxid,
3195  xidForceLimit));
3196  if (!force_vacuum)
3197  {
3198  multiForceLimit = recentMulti - multixact_freeze_max_age;
3199  if (multiForceLimit < FirstMultiXactId)
3200  multiForceLimit -= FirstMultiXactId;
3201  force_vacuum = MultiXactIdIsValid(classForm->relminmxid) &&
3202  MultiXactIdPrecedes(classForm->relminmxid, multiForceLimit);
3203  }
3204  *wraparound = force_vacuum;
3205 
3206  /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3207  if (!av_enabled && !force_vacuum)
3208  {
3209  *doanalyze = false;
3210  *dovacuum = false;
3211  return;
3212  }
3213 
3214  /*
3215  * If we found the table in the stats hash, and autovacuum is currently
3216  * enabled, make a threshold-based decision whether to vacuum and/or
3217  * analyze. If autovacuum is currently disabled, we must be here for
3218  * anti-wraparound vacuuming only, so don't vacuum (or analyze) anything
3219  * that's not being forced.
3220  */
3221  if (PointerIsValid(tabentry) && AutoVacuumingActive())
3222  {
3223  reltuples = classForm->reltuples;
3224  vactuples = tabentry->n_dead_tuples;
3225  instuples = tabentry->inserts_since_vacuum;
3226  anltuples = tabentry->changes_since_analyze;
3227 
3228  /* If the table hasn't yet been vacuumed, take reltuples as zero */
3229  if (reltuples < 0)
3230  reltuples = 0;
3231 
3232  vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3233  vacinsthresh = (float4) vac_ins_base_thresh + vac_ins_scale_factor * reltuples;
3234  anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3235 
3236  /*
3237  * Note that we don't need to take special consideration for stat
3238  * reset, because if that happens, the last vacuum and analyze counts
3239  * will be reset too.
3240  */
3241  if (vac_ins_base_thresh >= 0)
3242  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3243  NameStr(classForm->relname),
3244  vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3245  else
3246  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3247  NameStr(classForm->relname),
3248  vactuples, vacthresh, anltuples, anlthresh);
3249 
3250  /* Determine if this table needs vacuum or analyze. */
3251  *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3252  (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3253  *doanalyze = (anltuples > anlthresh);
3254  }
3255  else
3256  {
3257  /*
3258  * Skip a table not found in stat hash, unless we have to force vacuum
3259  * for anti-wrap purposes. If it's not acted upon, there's no need to
3260  * vacuum it.
3261  */
3262  *dovacuum = force_vacuum;
3263  *doanalyze = false;
3264  }
3265 
3266  /* ANALYZE refuses to work with pg_statistic */
3267  if (relid == StatisticRelationId)
3268  *doanalyze = false;
3269 }
double autovacuum_anl_scale
Definition: autovacuum.c:124
int autovacuum_vac_ins_thresh
Definition: autovacuum.c:121
uint32 TransactionId
Definition: c.h:587
#define DEBUG3
Definition: elog.h:23
float8 vacuum_scale_factor
Definition: rel.h:305
#define Min(x, y)
Definition: c.h:986
static MultiXactId recentMulti
Definition: autovacuum.c:149
#define OidIsValid(objectId)
Definition: c.h:710
double autovacuum_vac_ins_scale
Definition: autovacuum.c:122
PgStat_Counter inserts_since_vacuum
Definition: pgstat.h:797
#define FirstNormalTransactionId
Definition: transam.h:34
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3380
int autovacuum_freeze_max_age
Definition: autovacuum.c:125
PgStat_Counter n_dead_tuples
Definition: pgstat.h:794
int analyze_threshold
Definition: rel.h:295
int autovacuum_vac_thresh
Definition: autovacuum.c:119
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
#define FirstMultiXactId
Definition: multixact.h:25
#define AssertArg(condition)
Definition: c.h:806
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
float float4
Definition: c.h:564
int vacuum_threshold
Definition: rel.h:293
static TransactionId recentXid
Definition: autovacuum.c:148
PgStat_Counter changes_since_analyze
Definition: pgstat.h:795
double autovacuum_vac_scale
Definition: autovacuum.c:120
float8 analyze_scale_factor
Definition: rel.h:307
TransactionId MultiXactId
Definition: c.h:597
int freeze_max_age
Definition: rel.h:298
bool enabled
Definition: rel.h:292
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3159
int vacuum_ins_threshold
Definition: rel.h:294
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
int multixact_freeze_max_age
Definition: rel.h:301
float8 vacuum_ins_scale_factor
Definition: rel.h:306
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define PointerIsValid(pointer)
Definition: c.h:698
int autovacuum_anl_thresh
Definition: autovacuum.c:123

◆ StartAutoVacWorker()

int StartAutoVacWorker ( void  )

Definition at line 1477 of file autovacuum.c.

References AutoVacWorkerMain(), ClosePostmasterPorts(), ereport, errmsg(), fork_process(), InitPostmasterChild(), LOG, and NON_EXEC_STATIC.

Referenced by StartAutovacuumWorker().

1478 {
1479  pid_t worker_pid;
1480 
1481 #ifdef EXEC_BACKEND
1482  switch ((worker_pid = avworker_forkexec()))
1483 #else
1484  switch ((worker_pid = fork_process()))
1485 #endif
1486  {
1487  case -1:
1488  ereport(LOG,
1489  (errmsg("could not fork autovacuum worker process: %m")));
1490  return 0;
1491 
1492 #ifndef EXEC_BACKEND
1493  case 0:
1494  /* in postmaster child ... */
1496 
1497  /* Close the postmaster's sockets */
1498  ClosePostmasterPorts(false);
1499 
1500  AutoVacWorkerMain(0, NULL);
1501  break;
1502 #endif
1503  default:
1504  return (int) worker_pid;
1505  }
1506 
1507  /* shouldn't get here */
1508  return 0;
1509 }
void InitPostmasterChild(void)
Definition: miscinit.c:93
pid_t fork_process(void)
Definition: fork_process.c:29
#define LOG
Definition: elog.h:26
NON_EXEC_STATIC void AutoVacWorkerMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: autovacuum.c:1515
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2556
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ table_recheck_autovac()

static autovac_table* table_recheck_autovac ( Oid  relid,
HTAB table_toast_map,
TupleDesc  pg_class_desc,
int  effective_multixact_freeze_max_age 
)
static

Definition at line 2847 of file autovacuum.c.

References av_relation::ar_hasrelopts, av_relation::ar_reloptions, autovac_table::at_datname, autovac_table::at_dobalance, autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relid, autovac_table::at_relname, autovac_table::at_sharedrel, autovac_table::at_vacuum_cost_delay, autovac_table::at_vacuum_cost_limit, autovac_refresh_stats(), autovacuum_vac_cost_delay, autovacuum_vac_cost_limit, default_freeze_min_age, default_freeze_table_age, default_multixact_freeze_min_age, default_multixact_freeze_table_age, extract_autovac_opts(), VacuumParams::freeze_min_age, AutoVacOpts::freeze_min_age, VacuumParams::freeze_table_age, AutoVacOpts::freeze_table_age, GETSTRUCT, HASH_FIND, hash_search(), heap_freetuple(), HeapTupleIsValid, VacuumParams::index_cleanup, VacuumParams::is_wraparound, Log_autovacuum_min_duration, VacuumParams::log_min_duration, AutoVacOpts::log_min_duration, VacuumParams::multixact_freeze_min_age, AutoVacOpts::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, AutoVacOpts::multixact_freeze_table_age, VacuumParams::nworkers, ObjectIdGetDatum, VacuumParams::options, palloc(), recheck_relation_needs_vacanalyze(), RELOID, SearchSysCacheCopy1, VacuumParams::truncate, VACOPT_ANALYZE, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, VACOPTVALUE_UNSPECIFIED, AutoVacOpts::vacuum_cost_delay, AutoVacOpts::vacuum_cost_limit, VacuumCostDelay, and VacuumCostLimit.

Referenced by do_autovacuum().

2850 {
2851  Form_pg_class classForm;
2852  HeapTuple classTup;
2853  bool dovacuum;
2854  bool doanalyze;
2855  autovac_table *tab = NULL;
2856  bool wraparound;
2857  AutoVacOpts *avopts;
2858  static bool reuse_stats = false;
2859 
2860  /* fetch the relation's relcache entry */
2861  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2862  if (!HeapTupleIsValid(classTup))
2863  return NULL;
2864  classForm = (Form_pg_class) GETSTRUCT(classTup);
2865 
2866  /*
2867  * Get the applicable reloptions. If it is a TOAST table, try to get the
2868  * main table reloptions if the toast table itself doesn't have.
2869  */
2870  avopts = extract_autovac_opts(classTup, pg_class_desc);
2871  if (classForm->relkind == RELKIND_TOASTVALUE &&
2872  avopts == NULL && table_toast_map != NULL)
2873  {
2874  av_relation *hentry;
2875  bool found;
2876 
2877  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2878  if (found && hentry->ar_hasrelopts)
2879  avopts = &hentry->ar_reloptions;
2880  }
2881 
2882  /*
2883  * Reuse the stats to recheck whether a relation needs to be vacuumed or
2884  * analyzed if it was reloaded before and has not been cleared yet. This
2885  * is necessary to avoid frequent refresh of stats, especially when there
2886  * are very large number of relations and the refresh can cause lots of
2887  * overhead.
2888  *
2889  * If we determined that a relation needs to be vacuumed or analyzed,
2890  * based on the old stats, we refresh stats and recheck the necessity
2891  * again. Because a relation may have already been vacuumed or analyzed by
2892  * someone since the last reload of stats.
2893  */
2894  if (reuse_stats)
2895  {
2896  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2897  effective_multixact_freeze_max_age,
2898  &dovacuum, &doanalyze, &wraparound);
2899 
2900  /* Quick exit if a relation doesn't need to be vacuumed or analyzed */
2901  if (!doanalyze && !dovacuum)
2902  {
2903  heap_freetuple(classTup);
2904  return NULL;
2905  }
2906  }
2907 
2908  /* Use fresh stats and recheck again */
2910 
2911  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2912  effective_multixact_freeze_max_age,
2913  &dovacuum, &doanalyze, &wraparound);
2914 
2915  /* OK, it needs something done */
2916  if (doanalyze || dovacuum)
2917  {
2918  int freeze_min_age;
2919  int freeze_table_age;
2920  int multixact_freeze_min_age;
2921  int multixact_freeze_table_age;
2922  int vac_cost_limit;
2923  double vac_cost_delay;
2924  int log_min_duration;
2925 
2926  /*
2927  * Calculate the vacuum cost parameters and the freeze ages. If there
2928  * are options set in pg_class.reloptions, use them; in the case of a
2929  * toast table, try the main table too. Otherwise use the GUC
2930  * defaults, autovacuum's own first and plain vacuum second.
2931  */
2932 
2933  /* -1 in autovac setting means use plain vacuum_cost_delay */
2934  vac_cost_delay = (avopts && avopts->vacuum_cost_delay >= 0)
2935  ? avopts->vacuum_cost_delay
2936  : (autovacuum_vac_cost_delay >= 0)
2938  : VacuumCostDelay;
2939 
2940  /* 0 or -1 in autovac setting means use plain vacuum_cost_limit */
2941  vac_cost_limit = (avopts && avopts->vacuum_cost_limit > 0)
2942  ? avopts->vacuum_cost_limit
2945  : VacuumCostLimit;
2946 
2947  /* -1 in autovac setting means use log_autovacuum_min_duration */
2948  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2949  ? avopts->log_min_duration
2951 
2952  /* these do not have autovacuum-specific settings */
2953  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2954  ? avopts->freeze_min_age
2956 
2957  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2958  ? avopts->freeze_table_age
2960 
2961  multixact_freeze_min_age = (avopts &&
2962  avopts->multixact_freeze_min_age >= 0)
2963  ? avopts->multixact_freeze_min_age
2965 
2966  multixact_freeze_table_age = (avopts &&
2967  avopts->multixact_freeze_table_age >= 0)
2968  ? avopts->multixact_freeze_table_age
2970 
2971  tab = palloc(sizeof(autovac_table));
2972  tab->at_relid = relid;
2973  tab->at_sharedrel = classForm->relisshared;
2974 
2975  /* Note that this skips toast relations */
2976  tab->at_params.options = (dovacuum ? VACOPT_VACUUM : 0) |
2977  (doanalyze ? VACOPT_ANALYZE : 0) |
2978  (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2979 
2980  /*
2981  * index_cleanup and truncate are unspecified at first in autovacuum.
2982  * They will be filled in with usable values using their reloptions
2983  * (or reloption defaults) later.
2984  */
2987  /* As of now, we don't support parallel vacuum for autovacuum */
2988  tab->at_params.nworkers = -1;
2989  tab->at_params.freeze_min_age = freeze_min_age;
2990  tab->at_params.freeze_table_age = freeze_table_age;
2991  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2992  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2993  tab->at_params.is_wraparound = wraparound;
2994  tab->at_params.log_min_duration = log_min_duration;
2995  tab->at_vacuum_cost_limit = vac_cost_limit;
2996  tab->at_vacuum_cost_delay = vac_cost_delay;
2997  tab->at_relname = NULL;
2998  tab->at_nspname = NULL;
2999  tab->at_datname = NULL;
3000 
3001  /*
3002  * If any of the cost delay parameters has been set individually for
3003  * this table, disable the balancing algorithm.
3004  */
3005  tab->at_dobalance =
3006  !(avopts && (avopts->vacuum_cost_limit > 0 ||
3007  avopts->vacuum_cost_delay > 0));
3008 
3009  /*
3010  * When we decide to do vacuum or analyze, the existing stats cannot
3011  * be reused in the next cycle because it's cleared at the end of
3012  * vacuum or analyze (by AtEOXact_PgStat()).
3013  */
3014  reuse_stats = false;
3015  }
3016  else
3017  {
3018  /*
3019  * If neither vacuum nor analyze is necessary, the existing stats is
3020  * not cleared and can be reused in the next cycle.
3021  */
3022  reuse_stats = true;
3023  }
3024 
3025  heap_freetuple(classTup);
3026  return tab;
3027 }
int multixact_freeze_table_age
Definition: vacuum.h:216
static int default_freeze_table_age
Definition: autovacuum.c:153
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
Definition: autovacuum.c:2793
static int default_multixact_freeze_min_age
Definition: autovacuum.c:154
#define VACOPT_ANALYZE
Definition: vacuum.h:179
int freeze_min_age
Definition: rel.h:297
static void autovac_refresh_stats(void)
Definition: autovacuum.c:3532
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
VacOptValue truncate
Definition: vacuum.h:223
char * at_datname
Definition: autovacuum.c:200
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
int freeze_table_age
Definition: vacuum.h:213
int autovacuum_vac_cost_limit
Definition: autovacuum.c:129
bool at_sharedrel
Definition: autovacuum.c:197
static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
Definition: autovacuum.c:3038
int freeze_table_age
Definition: rel.h:299
int at_vacuum_cost_limit
Definition: autovacuum.c:195
char * at_relname
Definition: autovacuum.c:198
bits32 options
Definition: vacuum.h:211
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
int VacuumCostLimit
Definition: globals.c:144
int freeze_min_age
Definition: vacuum.h:212
float8 vacuum_cost_delay
Definition: rel.h:304
bool is_wraparound
Definition: vacuum.h:218
double autovacuum_vac_cost_delay
Definition: autovacuum.c:128
VacOptValue index_cleanup
Definition: vacuum.h:222
char * at_nspname
Definition: autovacuum.c:199
int multixact_freeze_table_age
Definition: rel.h:302
double at_vacuum_cost_delay
Definition: autovacuum.c:194
VacuumParams at_params
Definition: autovacuum.c:193
int vacuum_cost_limit
Definition: rel.h:296
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define VACOPT_VACUUM
Definition: vacuum.h:178
int multixact_freeze_min_age
Definition: rel.h:300
int nworkers
Definition: vacuum.h:230
int log_min_duration
Definition: vacuum.h:219
int log_min_duration
Definition: rel.h:303
int Log_autovacuum_min_duration
Definition: autovacuum.c:131
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
AutoVacOpts ar_reloptions
Definition: autovacuum.c:185
void * palloc(Size size)
Definition: mcxt.c:1062
double VacuumCostDelay
Definition: globals.c:145
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:183
bool ar_hasrelopts
Definition: autovacuum.c:184
static int default_multixact_freeze_table_age
Definition: autovacuum.c:155
int multixact_freeze_min_age
Definition: vacuum.h:214
static int default_freeze_min_age
Definition: autovacuum.c:152
bool at_dobalance
Definition: autovacuum.c:196

Variable Documentation

◆ am_autovacuum_launcher

bool am_autovacuum_launcher = false
static

Definition at line 141 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and IsAutoVacuumLauncherProcess().

◆ am_autovacuum_worker

bool am_autovacuum_worker = false
static

Definition at line 142 of file autovacuum.c.

Referenced by AutoVacWorkerMain(), avl_sigusr2_handler(), and IsAutoVacuumWorkerProcess().

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

Definition at line 158 of file autovacuum.c.

◆ autovacuum_anl_scale

double autovacuum_anl_scale

Definition at line 124 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

int autovacuum_freeze_max_age

◆ autovacuum_max_workers

◆ autovacuum_multixact_freeze_max_age

int autovacuum_multixact_freeze_max_age

◆ autovacuum_naptime

int autovacuum_naptime

◆ autovacuum_start_daemon

bool autovacuum_start_daemon = false

Definition at line 115 of file autovacuum.c.

Referenced by autovac_init(), and AutoVacuumingActive().

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 128 of file autovacuum.c.

Referenced by autovac_balance_cost(), and table_recheck_autovac().

◆ autovacuum_vac_cost_limit

int autovacuum_vac_cost_limit

Definition at line 129 of file autovacuum.c.

Referenced by autovac_balance_cost(), and table_recheck_autovac().

◆ autovacuum_vac_ins_scale

double autovacuum_vac_ins_scale

Definition at line 122 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 121 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 120 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 119 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 117 of file autovacuum.c.

Referenced by compute_max_dead_tuples(), and ginInsertCleanup().

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

Definition at line 306 of file autovacuum.c.

Referenced by FreeWorkerInfo(), and ProcKill().

◆ AutoVacuumShmem

AutoVacuumShmemStruct* AutoVacuumShmem
static

Definition at line 293 of file autovacuum.c.

◆ DatabaseList

dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
static

Definition at line 299 of file autovacuum.c.

◆ DatabaseListCxt

MemoryContext DatabaseListCxt = NULL
static

Definition at line 300 of file autovacuum.c.

◆ default_freeze_min_age

int default_freeze_min_age
static

Definition at line 152 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_freeze_table_age

int default_freeze_table_age
static

Definition at line 153 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_multixact_freeze_min_age

int default_multixact_freeze_min_age
static

Definition at line 154 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_multixact_freeze_table_age

int default_multixact_freeze_table_age
static

Definition at line 155 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ got_SIGUSR2

volatile sig_atomic_t got_SIGUSR2 = false
static

Definition at line 145 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and avl_sigusr2_handler().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = -1

Definition at line 131 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

WorkerInfo MyWorkerInfo = NULL
static

Definition at line 303 of file autovacuum.c.

◆ recentMulti

MultiXactId recentMulti
static

Definition at line 149 of file autovacuum.c.

Referenced by AutoVacWorkerMain(), do_start_worker(), and relation_needs_vacanalyze().

◆ recentXid

TransactionId recentXid
static

Definition at line 148 of file autovacuum.c.

Referenced by AutoVacWorkerMain(), do_start_worker(), and relation_needs_vacanalyze().