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 "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 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 137 of file autovacuum.c.

Referenced by launcher_determine_sleep().

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 136 of file autovacuum.c.

Referenced by launcher_determine_sleep(), and rebuild_database_list().

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

Definition at line 264 of file autovacuum.c.

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

◆ STATS_READ_DELAY

#define STATS_READ_DELAY   1000

Definition at line 133 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 234 of file autovacuum.c.

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 
AutoVacNumSignals 

Definition at line 241 of file autovacuum.c.

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

Function Documentation

◆ autovac_balance_cost()

static void autovac_balance_cost ( void  )
static

Definition at line 1775 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().

1776 {
1777  /*
1778  * The idea here is that we ration out I/O equally. The amount of I/O
1779  * that a worker can consume is determined by cost_limit/cost_delay, so we
1780  * try to equalize those ratios rather than the raw limit settings.
1781  *
1782  * note: in cost_limit, zero also means use value from elsewhere, because
1783  * zero is not a valid value.
1784  */
1785  int vac_cost_limit = (autovacuum_vac_cost_limit > 0 ?
1787  double vac_cost_delay = (autovacuum_vac_cost_delay >= 0 ?
1789  double cost_total;
1790  double cost_avail;
1791  dlist_iter iter;
1792 
1793  /* not set? nothing to do */
1794  if (vac_cost_limit <= 0 || vac_cost_delay <= 0)
1795  return;
1796 
1797  /* calculate the total base cost limit of participating active workers */
1798  cost_total = 0.0;
1800  {
1801  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1802 
1803  if (worker->wi_proc != NULL &&
1804  worker->wi_dobalance &&
1805  worker->wi_cost_limit_base > 0 && worker->wi_cost_delay > 0)
1806  cost_total +=
1807  (double) worker->wi_cost_limit_base / worker->wi_cost_delay;
1808  }
1809 
1810  /* there are no cost limits -- nothing to do */
1811  if (cost_total <= 0)
1812  return;
1813 
1814  /*
1815  * Adjust cost limit of each active worker to balance the total of cost
1816  * limit to autovacuum_vacuum_cost_limit.
1817  */
1818  cost_avail = (double) vac_cost_limit / vac_cost_delay;
1820  {
1821  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1822 
1823  if (worker->wi_proc != NULL &&
1824  worker->wi_dobalance &&
1825  worker->wi_cost_limit_base > 0 && worker->wi_cost_delay > 0)
1826  {
1827  int limit = (int)
1828  (cost_avail * worker->wi_cost_limit_base / cost_total);
1829 
1830  /*
1831  * We put a lower bound of 1 on the cost_limit, to avoid division-
1832  * by-zero in the vacuum code. Also, in case of roundoff trouble
1833  * in these calculations, let's be sure we don't ever set
1834  * cost_limit to more than the base value.
1835  */
1836  worker->wi_cost_limit = Max(Min(limit,
1837  worker->wi_cost_limit_base),
1838  1);
1839  }
1840 
1841  if (worker->wi_proc != NULL)
1842  elog(DEBUG2, "autovac_balance_cost(pid=%u db=%u, rel=%u, dobalance=%s cost_limit=%d, cost_limit_base=%d, cost_delay=%g)",
1843  worker->wi_proc->pid, worker->wi_dboid, worker->wi_tableoid,
1844  worker->wi_dobalance ? "yes" : "no",
1845  worker->wi_cost_limit, worker->wi_cost_limit_base,
1846  worker->wi_cost_delay);
1847  }
1848 }
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
double wi_cost_delay
Definition: autovacuum.c:229
#define Min(x, y)
Definition: c.h:927
int autovacuum_vac_cost_limit
Definition: autovacuum.c:128
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
int VacuumCostLimit
Definition: globals.c:141
#define DEBUG2
Definition: elog.h:24
double autovacuum_vac_cost_delay
Definition: autovacuum.c:127
int wi_cost_limit_base
Definition: autovacuum.c:231
dlist_node * cur
Definition: ilist.h:161
#define Max(x, y)
Definition: c.h:921
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:292
double VacuumCostDelay
Definition: globals.c:142
#define elog(elevel,...)
Definition: elog.h:214
PGPROC * wi_proc
Definition: autovacuum.c:225
dlist_head av_runningWorkers
Definition: autovacuum.c:287
int pid
Definition: proc.h:115

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3281 of file autovacuum.c.

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

Referenced by PostmasterMain().

3282 {
3284  ereport(WARNING,
3285  (errmsg("autovacuum not started because of misconfiguration"),
3286  errhint("Enable the \"track_counts\" option.")));
3287 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
bool autovacuum_start_daemon
Definition: autovacuum.c:114
bool pgstat_track_counts
Definition: pgstat.c:125
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ autovac_refresh_stats()

static void autovac_refresh_stats ( void  )
static

Definition at line 3379 of file autovacuum.c.

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

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

3380 {
3382  {
3383  static TimestampTz last_read = 0;
3384  TimestampTz current_time;
3385 
3386  current_time = GetCurrentTimestamp();
3387 
3388  if (!TimestampDifferenceExceeds(last_read, current_time,
3390  return;
3391 
3392  last_read = current_time;
3393  }
3394 
3396 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
int64 TimestampTz
Definition: timestamp.h:39
#define STATS_READ_DELAY
Definition: autovacuum.c:133
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1673
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3295
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5844

◆ autovac_report_activity()

static void autovac_report_activity ( autovac_table tab)
static

Definition at line 3152 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().

3153 {
3154 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3155  char activity[MAX_AUTOVAC_ACTIV_LEN];
3156  int len;
3157 
3158  /* Report the command and possible options */
3159  if (tab->at_params.options & VACOPT_VACUUM)
3160  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3161  "autovacuum: VACUUM%s",
3162  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3163  else
3164  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3165  "autovacuum: ANALYZE");
3166 
3167  /*
3168  * Report the qualified name of the relation.
3169  */
3170  len = strlen(activity);
3171 
3172  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3173  " %s.%s%s", tab->at_nspname, tab->at_relname,
3174  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3175 
3176  /* Set statement_timestamp() to current time for pg_stat_activity */
3178 
3180 }
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3132
char * at_relname
Definition: autovacuum.c:197
bool is_wraparound
Definition: vacuum.h:217
char * at_nspname
Definition: autovacuum.c:198
#define MAX_AUTOVAC_ACTIV_LEN
VacuumParams at_params
Definition: autovacuum.c:192
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833
int options
Definition: vacuum.h:210
#define snprintf
Definition: port.h:193

◆ autovac_report_workitem()

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

Definition at line 3187 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().

3189 {
3190  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3191  char blk[12 + 2];
3192  int len;
3193 
3194  switch (workitem->avw_type)
3195  {
3197  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3198  "autovacuum: BRIN summarize");
3199  break;
3200  }
3201 
3202  /*
3203  * Report the qualified name of the relation, and the block number if any
3204  */
3205  len = strlen(activity);
3206 
3207  if (BlockNumberIsValid(workitem->avw_blockNumber))
3208  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3209  else
3210  blk[0] = '\0';
3211 
3212  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3213  " %s.%s%s", nspname, relname, blk);
3214 
3215  /* Set statement_timestamp() to current time for pg_stat_activity */
3217 
3219 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:256
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:3132
NameData relname
Definition: pg_class.h:38
#define MAX_AUTOVAC_ACTIV_LEN
BlockNumber avw_blockNumber
Definition: autovacuum.c:261
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:833
#define snprintf
Definition: port.h:193

◆ AutoVacLauncherMain()

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

Definition at line 432 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(), 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, quickdie(), rebuild_database_list(), ReleaseAuxProcessResources(), ResetLatch(), RESUME_INTERRUPTS, SendPostmasterSignal(), SetConfigOption(), SetProcessingMode, ShutdownRequestPending, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, StatementCancelHandler(), TimestampDifferenceExceeds(), TopMemoryContext, UnBlockSig, UnlockBuffers(), WAIT_EVENT_AUTOVACUUM_MAIN, WaitLatch(), waittime, 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().

433 {
434  sigjmp_buf local_sigjmp_buf;
435 
436  am_autovacuum_launcher = true;
437 
439  init_ps_display(NULL);
440 
441  ereport(DEBUG1,
442  (errmsg("autovacuum launcher started")));
443 
444  if (PostAuthDelay)
445  pg_usleep(PostAuthDelay * 1000000L);
446 
448 
449  /*
450  * Set up signal handlers. We operate on databases much like a regular
451  * backend, so we use the same signal handling. See equivalent code in
452  * tcop/postgres.c.
453  */
457 
459  InitializeTimeouts(); /* establishes SIGALRM handler */
460 
466 
467  /* Early initialization */
468  BaseInit();
469 
470  /*
471  * Create a per-backend PGPROC struct in shared memory, except in the
472  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
473  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
474  * had to do some stuff with LWLocks).
475  */
476 #ifndef EXEC_BACKEND
477  InitProcess();
478 #endif
479 
480  InitPostgres(NULL, InvalidOid, NULL, InvalidOid, NULL, false);
481 
483 
484  /*
485  * Create a memory context that we will do all our work in. We do this so
486  * that we can reset the context during error recovery and thereby avoid
487  * possible memory leaks.
488  */
490  "Autovacuum Launcher",
493 
494  /*
495  * If an exception is encountered, processing resumes here.
496  *
497  * This code is a stripped down version of PostgresMain error recovery.
498  */
499  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
500  {
501  /* since not using PG_TRY, must reset error stack by hand */
502  error_context_stack = NULL;
503 
504  /* Prevents interrupts while cleaning up */
505  HOLD_INTERRUPTS();
506 
507  /* Forget any pending QueryCancel or timeout request */
508  disable_all_timeouts(false);
509  QueryCancelPending = false; /* second to avoid race condition */
510 
511  /* Report the error to the server log */
512  EmitErrorReport();
513 
514  /* Abort the current transaction in order to recover */
516 
517  /*
518  * Release any other resources, for the case where we were not in a
519  * transaction.
520  */
523  AbortBufferIO();
524  UnlockBuffers();
525  /* this is probably dead code, but let's be safe: */
528  AtEOXact_Buffers(false);
529  AtEOXact_SMgr();
530  AtEOXact_Files(false);
531  AtEOXact_HashTables(false);
532 
533  /*
534  * Now return to normal top-level context and clear ErrorContext for
535  * next time.
536  */
538  FlushErrorState();
539 
540  /* Flush any leaked data in the top-level context */
542 
543  /* don't leave dangling pointers to freed memory */
544  DatabaseListCxt = NULL;
546 
547  /*
548  * Make sure pgstat also considers our stat data as gone. Note: we
549  * mustn't use autovac_refresh_stats here.
550  */
552 
553  /* Now we can allow interrupts again */
555 
556  /* if in shutdown mode, no need for anything further; just go away */
559 
560  /*
561  * Sleep at least 1 second after any error. We don't want to be
562  * filling the error logs as fast as we can.
563  */
564  pg_usleep(1000000L);
565  }
566 
567  /* We can now handle ereport(ERROR) */
568  PG_exception_stack = &local_sigjmp_buf;
569 
570  /* must unblock signals before calling rebuild_database_list */
572 
573  /*
574  * Set always-secure search path. Launcher doesn't connect to a database,
575  * so this has no effect.
576  */
577  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
578 
579  /*
580  * Force zero_damaged_pages OFF in the autovac process, even if it is set
581  * in postgresql.conf. We don't really want such a dangerous option being
582  * applied non-interactively.
583  */
584  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
585 
586  /*
587  * Force settable timeouts off to avoid letting these settings prevent
588  * regular maintenance from being executed.
589  */
590  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
591  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
592  SetConfigOption("idle_in_transaction_session_timeout", "0",
594 
595  /*
596  * Force default_transaction_isolation to READ COMMITTED. We don't want
597  * to pay the overhead of serializable mode, nor add any risk of causing
598  * deadlocks or delaying other transactions.
599  */
600  SetConfigOption("default_transaction_isolation", "read committed",
602 
603  /*
604  * In emergency mode, just start a worker (unless shutdown was requested)
605  * and go away.
606  */
607  if (!AutoVacuumingActive())
608  {
610  do_start_worker();
611  proc_exit(0); /* done */
612  }
613 
615 
616  /*
617  * Create the initial database list. The invariant we want this list to
618  * keep is that it's ordered by decreasing next_time. As soon as an entry
619  * is updated to a higher time, it will be moved to the front (which is
620  * correct because the only operation is to add autovacuum_naptime to the
621  * entry, and time always increases).
622  */
624 
625  /* loop until shutdown request */
626  while (!ShutdownRequestPending)
627  {
628  struct timeval nap;
629  TimestampTz current_time = 0;
630  bool can_launch;
631 
632  /*
633  * This loop is a bit different from the normal use of WaitLatch,
634  * because we'd like to sleep before the first launch of a child
635  * process. So it's WaitLatch, then ResetLatch, then check for
636  * wakening conditions.
637  */
638 
640  false, &nap);
641 
642  /*
643  * Wait until naptime expires or we get some type of signal (all the
644  * signal handlers will wake us by calling SetLatch).
645  */
646  (void) WaitLatch(MyLatch,
648  (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
650 
652 
654 
655  /*
656  * a worker finished, or postmaster signaled failure to start a worker
657  */
658  if (got_SIGUSR2)
659  {
660  got_SIGUSR2 = false;
661 
662  /* rebalance cost limits, if needed */
664  {
665  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
668  LWLockRelease(AutovacuumLock);
669  }
670 
672  {
673  /*
674  * If the postmaster failed to start a new worker, we sleep
675  * for a little while and resend the signal. The new worker's
676  * state is still in memory, so this is sufficient. After
677  * that, we restart the main loop.
678  *
679  * XXX should we put a limit to the number of times we retry?
680  * I don't think it makes much sense, because a future start
681  * of a worker will continue to fail in the same way.
682  */
684  pg_usleep(1000000L); /* 1s */
686  continue;
687  }
688  }
689 
690  /*
691  * There are some conditions that we need to check before trying to
692  * start a worker. First, we need to make sure that there is a worker
693  * slot available. Second, we need to make sure that no other worker
694  * failed while starting up.
695  */
696 
697  current_time = GetCurrentTimestamp();
698  LWLockAcquire(AutovacuumLock, LW_SHARED);
699 
701 
702  if (AutoVacuumShmem->av_startingWorker != NULL)
703  {
704  int waittime;
706 
707  /*
708  * We can't launch another worker when another one is still
709  * starting up (or failed while doing so), so just sleep for a bit
710  * more; that worker will wake us up again as soon as it's ready.
711  * We will only wait autovacuum_naptime seconds (up to a maximum
712  * of 60 seconds) for this to happen however. Note that failure
713  * to connect to a particular database is not a problem here,
714  * because the worker removes itself from the startingWorker
715  * pointer before trying to connect. Problems detected by the
716  * postmaster (like fork() failure) are also reported and handled
717  * differently. The only problems that may cause this code to
718  * fire are errors in the earlier sections of AutoVacWorkerMain,
719  * before the worker removes the WorkerInfo from the
720  * startingWorker pointer.
721  */
722  waittime = Min(autovacuum_naptime, 60) * 1000;
723  if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
724  waittime))
725  {
726  LWLockRelease(AutovacuumLock);
727  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
728 
729  /*
730  * No other process can put a worker in starting mode, so if
731  * startingWorker is still INVALID after exchanging our lock,
732  * we assume it's the same one we saw above (so we don't
733  * recheck the launch time).
734  */
735  if (AutoVacuumShmem->av_startingWorker != NULL)
736  {
738  worker->wi_dboid = InvalidOid;
739  worker->wi_tableoid = InvalidOid;
740  worker->wi_sharedrel = false;
741  worker->wi_proc = NULL;
742  worker->wi_launchtime = 0;
744  &worker->wi_links);
746  elog(WARNING, "worker took too long to start; canceled");
747  }
748  }
749  else
750  can_launch = false;
751  }
752  LWLockRelease(AutovacuumLock); /* either shared or exclusive */
753 
754  /* if we can't do anything, just go back to sleep */
755  if (!can_launch)
756  continue;
757 
758  /* We're OK to start a new worker */
759 
761  {
762  /*
763  * Special case when the list is empty: start a worker right away.
764  * This covers the initial case, when no database is in pgstats
765  * (thus the list is empty). Note that the constraints in
766  * launcher_determine_sleep keep us from starting workers too
767  * quickly (at most once every autovacuum_naptime when the list is
768  * empty).
769  */
770  launch_worker(current_time);
771  }
772  else
773  {
774  /*
775  * because rebuild_database_list constructs a list with most
776  * distant adl_next_worker first, we obtain our database from the
777  * tail of the list.
778  */
779  avl_dbase *avdb;
780 
781  avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
782 
783  /*
784  * launch a worker if next_worker is right now or it is in the
785  * past
786  */
788  current_time, 0))
789  launch_worker(current_time);
790  }
791  }
792 
794 }
void InitializeTimeouts(void)
Definition: timeout.c:346
int autovacuum_naptime
Definition: autovacuum.c:117
void AbortCurrentTransaction(void)
Definition: xact.c:3211
#define SIGQUIT
Definition: win32_port.h:154
TimestampTz adl_next_worker
Definition: autovacuum.c:163
#define AllocSetContextCreate
Definition: memutils.h:170
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:40
WorkerInfo av_startingWorker
Definition: autovacuum.c:288
static void autovac_balance_cost(void)
Definition: autovacuum.c:1775
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:284
static bool am_autovacuum_launcher
Definition: autovacuum.c:140
#define WL_TIMEOUT
Definition: latch.h:127
dlist_head av_freeWorkers
Definition: autovacuum.c:286
int waittime
Definition: pg_standby.c:42
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
#define SIGUSR1
Definition: win32_port.h:165
BackendType MyBackendType
Definition: miscinit.c:60
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
#define SIGCHLD
Definition: win32_port.h:163
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2478
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:879
TimestampTz wi_launchtime
Definition: autovacuum.c:226
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:157
#define Min(x, y)
Definition: c.h:927
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:104
#define SetProcessingMode(mode)
Definition: miscadmin.h:399
void BaseInit(void)
Definition: postinit.c:548
dlist_node wi_links
Definition: autovacuum.c:222
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1673
void FlushErrorState(void)
Definition: elog.c:1568
void ResetLatch(Latch *latch)
Definition: latch.c:588
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
ResourceOwner AuxProcessResourceOwner
Definition: resowner.c:145
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2857
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2904
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:390
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
ErrorContextCallback * error_context_stack
Definition: elog.c:92
void pg_usleep(long microsec)
Definition: signal.c:53
static void HandleAutoVacLauncherInterrupts(void)
Definition: autovacuum.c:800
void AtEOXact_SMgr(void)
Definition: smgr.c:661
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:496
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:598
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3227
Definition: guc.h:75
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
void InitProcess(void)
Definition: proc.c:304
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7714
#define SIGHUP
Definition: win32_port.h:153
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1381
static dlist_head DatabaseList
Definition: autovacuum.c:298
MemoryContext TopMemoryContext
Definition: mcxt.c:44
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:1412
#define SIG_IGN
Definition: win32_port.h:150
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition: autovacuum.c:853
#define WARNING
Definition: elog.h:40
void UnlockBuffers(void)
Definition: bufmgr.c:3729
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
int PostAuthDelay
Definition: postgres.c:102
void EmitErrorReport(void)
Definition: elog.c:1423
#define InvalidOid
Definition: postgres_ext.h:36
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define ereport(elevel,...)
Definition: elog.h:144
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:590
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:144
#define SIG_DFL
Definition: win32_port.h:148
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5844
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:292
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
void AbortBufferIO(void)
Definition: bufmgr.c:4207
sigjmp_buf * PG_exception_stack
Definition: elog.c:94
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:937
static void AutoVacLauncherShutdown(void)
Definition: autovacuum.c:316
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:214
static MemoryContext DatabaseListCxt
Definition: autovacuum.c:299
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2878
struct Latch * MyLatch
Definition: globals.c:54
PGPROC * wi_proc
Definition: autovacuum.c:225
static void launch_worker(TimestampTz now)
Definition: autovacuum.c:1353
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:146
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
void LWLockReleaseAll(void)
Definition: lwlock.c:1911
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:551
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1857
#define WL_LATCH_SET
Definition: latch.h:124
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2759
static Oid do_start_worker(void)
Definition: autovacuum.c:1138
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ AutoVacLauncherShutdown()

static void AutoVacLauncherShutdown ( void  )
static

Definition at line 316 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and HandleAutoVacLauncherInterrupts().

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

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3123 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().

3124 {
3125  RangeVar *rangevar;
3126  VacuumRelation *rel;
3127  List *rel_list;
3128 
3129  /* Let pgstat know what we're doing */
3131 
3132  /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3133  rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3134  rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3135  rel_list = list_make1(rel);
3136 
3137  vacuum(rel_list, &tab->at_params, bstrategy, true);
3138 }
#define NIL
Definition: pg_list.h:65
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:272
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:808
#define list_make1(x1)
Definition: pg_list.h:227
char * at_relname
Definition: autovacuum.c:197
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3152
char * at_nspname
Definition: autovacuum.c:198
VacuumParams at_params
Definition: autovacuum.c:192
Definition: pg_list.h:50
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422

◆ AutoVacuumingActive()

bool AutoVacuumingActive ( void  )

Definition at line 3227 of file autovacuum.c.

References autovacuum_start_daemon, and pgstat_track_counts.

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

3228 {
3230  return false;
3231  return true;
3232 }
bool autovacuum_start_daemon
Definition: autovacuum.c:114
bool pgstat_track_counts
Definition: pgstat.c:125

◆ AutoVacuumRequestWork()

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

Definition at line 3239 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().

3241 {
3242  int i;
3243  bool result = false;
3244 
3245  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3246 
3247  /*
3248  * Locate an unused work item and fill it with the given data.
3249  */
3250  for (i = 0; i < NUM_WORKITEMS; i++)
3251  {
3253 
3254  if (workitem->avw_used)
3255  continue;
3256 
3257  workitem->avw_used = true;
3258  workitem->avw_active = false;
3259  workitem->avw_type = type;
3260  workitem->avw_database = MyDatabaseId;
3261  workitem->avw_relation = relationId;
3262  workitem->avw_blockNumber = blkno;
3263  result = true;
3264 
3265  /* done */
3266  break;
3267  }
3268 
3269  LWLockRelease(AutovacuumLock);
3270 
3271  return result;
3272 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:256
#define NUM_WORKITEMS
Definition: autovacuum.c:264
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:289
Oid MyDatabaseId
Definition: globals.c:85
BlockNumber avw_blockNumber
Definition: autovacuum.c:261
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:292
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
int i

◆ AutoVacuumShmemInit()

void AutoVacuumShmemInit ( void  )

Definition at line 3331 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().

3332 {
3333  bool found;
3334 
3336  ShmemInitStruct("AutoVacuum Data",
3338  &found);
3339 
3340  if (!IsUnderPostmaster)
3341  {
3342  WorkerInfo worker;
3343  int i;
3344 
3345  Assert(!found);
3346 
3351  memset(AutoVacuumShmem->av_workItems, 0,
3352  sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3353 
3354  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3355  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3356 
3357  /* initialize the WorkerInfo free list */
3358  for (i = 0; i < autovacuum_max_workers; i++)
3360  &worker[i].wi_links);
3361  }
3362  else
3363  Assert(found);
3364 }
#define NUM_WORKITEMS
Definition: autovacuum.c:264
WorkerInfo av_startingWorker
Definition: autovacuum.c:288
dlist_head av_freeWorkers
Definition: autovacuum.c:286
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:234
dlist_node wi_links
Definition: autovacuum.c:222
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:392
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:289
bool IsUnderPostmaster
Definition: globals.c:109
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3312
int autovacuum_max_workers
Definition: autovacuum.c:115
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define Assert(condition)
Definition: c.h:745
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:292
#define MAXALIGN(LEN)
Definition: c.h:698
int i
dlist_head av_runningWorkers
Definition: autovacuum.c:287

◆ AutoVacuumShmemSize()

Size AutoVacuumShmemSize ( void  )

Definition at line 3312 of file autovacuum.c.

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

Referenced by AutoVacuumShmemInit(), and CreateSharedMemoryAndSemaphores().

3313 {
3314  Size size;
3315 
3316  /*
3317  * Need the fixed struct and the array of WorkerInfoData.
3318  */
3319  size = sizeof(AutoVacuumShmemStruct);
3320  size = MAXALIGN(size);
3322  sizeof(WorkerInfoData)));
3323  return size;
3324 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
int autovacuum_max_workers
Definition: autovacuum.c:115
size_t Size
Definition: c.h:473
#define MAXALIGN(LEN)
Definition: c.h:698

◆ AutoVacuumUpdateDelay()

void AutoVacuumUpdateDelay ( void  )

Definition at line 1759 of file autovacuum.c.

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

Referenced by do_autovacuum(), and vacuum_delay_point().

1760 {
1761  if (MyWorkerInfo)
1762  {
1765  }
1766 }
double wi_cost_delay
Definition: autovacuum.c:229
int VacuumCostLimit
Definition: globals.c:141
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:302
double VacuumCostDelay
Definition: globals.c:142

◆ AutoVacWorkerFailed()

void AutoVacWorkerFailed ( void  )

Definition at line 1405 of file autovacuum.c.

References AutoVacForkFailed, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

1406 {
1408 }
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:284
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:292

◆ AutoVacWorkerMain()

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

Definition at line 1503 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(), 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(), quickdie(), ReadNewTransactionId(), ReadNextMultiXactId(), recentMulti, recentXid, set_ps_display(), SetConfigOption(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGQUIT, 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().

1504 {
1505  sigjmp_buf local_sigjmp_buf;
1506  Oid dbid;
1507 
1508  am_autovacuum_worker = true;
1509 
1511  init_ps_display(NULL);
1512 
1514 
1515  /*
1516  * Set up signal handlers. We operate on databases much like a regular
1517  * backend, so we use the same signal handling. See equivalent code in
1518  * tcop/postgres.c.
1519  */
1521 
1522  /*
1523  * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1524  * means abort and exit cleanly, and SIGQUIT means abandon ship.
1525  */
1527  pqsignal(SIGTERM, die);
1529  InitializeTimeouts(); /* establishes SIGALRM handler */
1530 
1536 
1537  /* Early initialization */
1538  BaseInit();
1539 
1540  /*
1541  * Create a per-backend PGPROC struct in shared memory, except in the
1542  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
1543  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
1544  * had to do some stuff with LWLocks).
1545  */
1546 #ifndef EXEC_BACKEND
1547  InitProcess();
1548 #endif
1549 
1550  /*
1551  * If an exception is encountered, processing resumes here.
1552  *
1553  * See notes in postgres.c about the design of this coding.
1554  */
1555  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1556  {
1557  /* since not using PG_TRY, must reset error stack by hand */
1558  error_context_stack = NULL;
1559 
1560  /* Prevents interrupts while cleaning up */
1561  HOLD_INTERRUPTS();
1562 
1563  /* Report the error to the server log */
1564  EmitErrorReport();
1565 
1566  /*
1567  * We can now go away. Note that because we called InitProcess, a
1568  * callback was registered to do ProcKill, which will clean up
1569  * necessary state.
1570  */
1571  proc_exit(0);
1572  }
1573 
1574  /* We can now handle ereport(ERROR) */
1575  PG_exception_stack = &local_sigjmp_buf;
1576 
1578 
1579  /*
1580  * Set always-secure search path, so malicious users can't redirect user
1581  * code (e.g. pg_index.indexprs). (That code runs in a
1582  * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1583  * take control of the entire autovacuum worker in any case.)
1584  */
1585  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1586 
1587  /*
1588  * Force zero_damaged_pages OFF in the autovac process, even if it is set
1589  * in postgresql.conf. We don't really want such a dangerous option being
1590  * applied non-interactively.
1591  */
1592  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1593 
1594  /*
1595  * Force settable timeouts off to avoid letting these settings prevent
1596  * regular maintenance from being executed.
1597  */
1598  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1599  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1600  SetConfigOption("idle_in_transaction_session_timeout", "0",
1602 
1603  /*
1604  * Force default_transaction_isolation to READ COMMITTED. We don't want
1605  * to pay the overhead of serializable mode, nor add any risk of causing
1606  * deadlocks or delaying other transactions.
1607  */
1608  SetConfigOption("default_transaction_isolation", "read committed",
1610 
1611  /*
1612  * Force synchronous replication off to allow regular maintenance even if
1613  * we are waiting for standbys to connect. This is important to ensure we
1614  * aren't blocked from performing anti-wraparound tasks.
1615  */
1617  SetConfigOption("synchronous_commit", "local",
1619 
1620  /*
1621  * Get the info about the database we're going to work on.
1622  */
1623  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1624 
1625  /*
1626  * beware of startingWorker being INVALID; this should normally not
1627  * happen, but if a worker fails after forking and before this, the
1628  * launcher might have decided to remove it from the queue and start
1629  * again.
1630  */
1631  if (AutoVacuumShmem->av_startingWorker != NULL)
1632  {
1634  dbid = MyWorkerInfo->wi_dboid;
1636 
1637  /* insert into the running list */
1640 
1641  /*
1642  * remove from the "starting" pointer, so that the launcher can start
1643  * a new worker if required
1644  */
1646  LWLockRelease(AutovacuumLock);
1647 
1649 
1650  /* wake up the launcher */
1651  if (AutoVacuumShmem->av_launcherpid != 0)
1653  }
1654  else
1655  {
1656  /* no worker entry for me, go away */
1657  elog(WARNING, "autovacuum worker started without a worker entry");
1658  dbid = InvalidOid;
1659  LWLockRelease(AutovacuumLock);
1660  }
1661 
1662  if (OidIsValid(dbid))
1663  {
1664  char dbname[NAMEDATALEN];
1665 
1666  /*
1667  * Report autovac startup to the stats collector. We deliberately do
1668  * this before InitPostgres, so that the last_autovac_time will get
1669  * updated even if the connection attempt fails. This is to prevent
1670  * autovac from getting "stuck" repeatedly selecting an unopenable
1671  * database, rather than making any progress on stuff it can connect
1672  * to.
1673  */
1674  pgstat_report_autovac(dbid);
1675 
1676  /*
1677  * Connect to the selected database
1678  *
1679  * Note: if we have selected a just-deleted database (due to using
1680  * stale stats info), we'll fail and exit here.
1681  */
1682  InitPostgres(NULL, dbid, NULL, InvalidOid, dbname, false);
1684  set_ps_display(dbname);
1685  ereport(DEBUG1,
1686  (errmsg("autovacuum: processing database \"%s\"", dbname)));
1687 
1688  if (PostAuthDelay)
1689  pg_usleep(PostAuthDelay * 1000000L);
1690 
1691  /* And do an appropriate amount of work */
1694  do_autovacuum();
1695  }
1696 
1697  /*
1698  * The launcher will be notified of my death in ProcKill, *if* we managed
1699  * to get a worker slot at all
1700  */
1701 
1702  /* All done, go away */
1703  proc_exit(0);
1704 }
static bool am_autovacuum_worker
Definition: autovacuum.c:141
void InitializeTimeouts(void)
Definition: timeout.c:346
#define SIGQUIT
Definition: win32_port.h:154
#define DEBUG1
Definition: elog.h:25
WorkerInfo av_startingWorker
Definition: autovacuum.c:288
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
#define SIGUSR1
Definition: win32_port.h:165
BackendType MyBackendType
Definition: miscinit.c:60
static void do_autovacuum(void)
Definition: autovacuum.c:1929
#define SIGCHLD
Definition: win32_port.h:163
PGPROC * MyProc
Definition: proc.c:67
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
static MultiXactId recentMulti
Definition: autovacuum.c:148
void proc_exit(int code)
Definition: ipc.c:104
#define SetProcessingMode(mode)
Definition: miscadmin.h:399
#define kill(pid, sig)
Definition: win32_port.h:426
void BaseInit(void)
Definition: postinit.c:548
dlist_node wi_links
Definition: autovacuum.c:222
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2857
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#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:304
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:7714
#define SIGHUP
Definition: win32_port.h:153
sigset_t UnBlockSig
Definition: pqsignal.c:22
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:302
int synchronous_commit
Definition: xact.c:83
#define SIG_IGN
Definition: win32_port.h:150
#define WARNING
Definition: elog.h:40
int PostAuthDelay
Definition: postgres.c:102
static TransactionId recentXid
Definition: autovacuum.c:147
void EmitErrorReport(void)
Definition: elog.c:1423
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname, bool override_allow_connections)
Definition: postinit.c:590
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
#define SIG_DFL
Definition: win32_port.h:148
char * dbname
Definition: streamutil.c:50
static void FreeWorkerInfo(int code, Datum arg)
Definition: autovacuum.c:1710
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:292
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
sigjmp_buf * PG_exception_stack
Definition: elog.c:94
static TransactionId ReadNewTransactionId(void)
Definition: transam.h:291
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:214
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2878
PGPROC * wi_proc
Definition: autovacuum.c:225
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:258
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:551
dlist_head av_runningWorkers
Definition: autovacuum.c:287
void pgstat_report_autovac(Oid dboid)
Definition: pgstat.c:1441
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2759
#define die(msg)
Definition: pg_test_fsync.c:96
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1412 of file autovacuum.c.

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

Referenced by AutoVacLauncherMain().

1413 {
1414  int save_errno = errno;
1415 
1416  got_SIGUSR2 = true;
1417  SetLatch(MyLatch);
1418 
1419  errno = save_errno;
1420 }
void SetLatch(Latch *latch)
Definition: latch.c:505
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:144
struct Latch * MyLatch
Definition: globals.c:54

◆ db_comparator()

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

Definition at line 1118 of file autovacuum.c.

References avl_dbase::adl_score.

Referenced by rebuild_database_list().

1119 {
1120  if (((const avl_dbase *) a)->adl_score == ((const avl_dbase *) b)->adl_score)
1121  return 0;
1122  else
1123  return (((const avl_dbase *) a)->adl_score < ((const avl_dbase *) b)->adl_score) ? 1 : -1;
1124 }

◆ do_autovacuum()

static void do_autovacuum ( void  )
static

Definition at line 1929 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(), autovacuum_do_vac_analyze(), AutoVacuumUpdateDelay(), AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_workItems, AutoVacuumWorkItem::avw_active, AutoVacuumWorkItem::avw_database, AutoVacuumWorkItem::avw_used, BAS_VACUUM, BTEqualStrategyNumber, 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(), MemSet, 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_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().

1930 {
1931  Relation classRel;
1932  HeapTuple tuple;
1933  TableScanDesc relScan;
1934  Form_pg_database dbForm;
1935  List *table_oids = NIL;
1936  List *orphan_oids = NIL;
1937  HASHCTL ctl;
1938  HTAB *table_toast_map;
1939  ListCell *volatile cell;
1940  PgStat_StatDBEntry *shared;
1941  PgStat_StatDBEntry *dbentry;
1942  BufferAccessStrategy bstrategy;
1943  ScanKeyData key;
1944  TupleDesc pg_class_desc;
1945  int effective_multixact_freeze_max_age;
1946  bool did_vacuum = false;
1947  bool found_concurrent_worker = false;
1948  int i;
1949 
1950  /*
1951  * StartTransactionCommand and CommitTransactionCommand will automatically
1952  * switch to other contexts. We need this one to keep the list of
1953  * relations to vacuum/analyze across transactions.
1954  */
1956  "AV worker",
1959 
1960  /*
1961  * may be NULL if we couldn't find an entry (only happens if we are
1962  * forcing a vacuum for anti-wrap purposes).
1963  */
1965 
1966  /* Start a transaction so our commands have one to play into. */
1968 
1969  /*
1970  * Clean up any dead statistics collector entries for this DB. We always
1971  * want to do this exactly once per DB-processing cycle, even if we find
1972  * nothing worth vacuuming in the database.
1973  */
1975 
1976  /*
1977  * Compute the multixact age for which freezing is urgent. This is
1978  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
1979  * short of multixact member space.
1980  */
1981  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
1982 
1983  /*
1984  * Find the pg_database entry and select the default freeze ages. We use
1985  * zero in template and nonconnectable databases, else the system-wide
1986  * default.
1987  */
1989  if (!HeapTupleIsValid(tuple))
1990  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1991  dbForm = (Form_pg_database) GETSTRUCT(tuple);
1992 
1993  if (dbForm->datistemplate || !dbForm->datallowconn)
1994  {
1999  }
2000  else
2001  {
2006  }
2007 
2008  ReleaseSysCache(tuple);
2009 
2010  /* StartTransactionCommand changed elsewhere */
2012 
2013  /* The database hash where pgstat keeps shared relations */
2015 
2016  classRel = table_open(RelationRelationId, AccessShareLock);
2017 
2018  /* create a copy so we can use it after closing pg_class */
2019  pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
2020 
2021  /* create hash table for toast <-> main relid mapping */
2022  MemSet(&ctl, 0, sizeof(ctl));
2023  ctl.keysize = sizeof(Oid);
2024  ctl.entrysize = sizeof(av_relation);
2025 
2026  table_toast_map = hash_create("TOAST to main relid map",
2027  100,
2028  &ctl,
2029  HASH_ELEM | HASH_BLOBS);
2030 
2031  /*
2032  * Scan pg_class to determine which tables to vacuum.
2033  *
2034  * We do this in two passes: on the first one we collect the list of plain
2035  * relations and materialized views, and on the second one we collect
2036  * TOAST tables. The reason for doing the second pass is that during it we
2037  * want to use the main relation's pg_class.reloptions entry if the TOAST
2038  * table does not have any, and we cannot obtain it unless we know
2039  * beforehand what's the main table OID.
2040  *
2041  * We need to check TOAST tables separately because in cases with short,
2042  * wide tables there might be proportionally much more activity in the
2043  * TOAST table than in its parent.
2044  */
2045  relScan = table_beginscan_catalog(classRel, 0, NULL);
2046 
2047  /*
2048  * On the first pass, we collect main tables to vacuum, and also the main
2049  * table relid to TOAST relid mapping.
2050  */
2051  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2052  {
2053  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2054  PgStat_StatTabEntry *tabentry;
2055  AutoVacOpts *relopts;
2056  Oid relid;
2057  bool dovacuum;
2058  bool doanalyze;
2059  bool wraparound;
2060 
2061  if (classForm->relkind != RELKIND_RELATION &&
2062  classForm->relkind != RELKIND_MATVIEW)
2063  continue;
2064 
2065  relid = classForm->oid;
2066 
2067  /*
2068  * Check if it is a temp table (presumably, of some other backend's).
2069  * We cannot safely process other backends' temp tables.
2070  */
2071  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2072  {
2073  /*
2074  * We just ignore it if the owning backend is still active and
2075  * using the temporary schema. Also, for safety, ignore it if the
2076  * namespace doesn't exist or isn't a temp namespace after all.
2077  */
2078  if (checkTempNamespaceStatus(classForm->relnamespace) == TEMP_NAMESPACE_IDLE)
2079  {
2080  /*
2081  * The table seems to be orphaned -- although it might be that
2082  * the owning backend has already deleted it and exited; our
2083  * pg_class scan snapshot is not necessarily up-to-date
2084  * anymore, so we could be looking at a committed-dead entry.
2085  * Remember it so we can try to delete it later.
2086  */
2087  orphan_oids = lappend_oid(orphan_oids, relid);
2088  }
2089  continue;
2090  }
2091 
2092  /* Fetch reloptions and the pgstat entry for this table */
2093  relopts = extract_autovac_opts(tuple, pg_class_desc);
2094  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
2095  shared, dbentry);
2096 
2097  /* Check if it needs vacuum or analyze */
2098  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2099  effective_multixact_freeze_max_age,
2100  &dovacuum, &doanalyze, &wraparound);
2101 
2102  /* Relations that need work are added to table_oids */
2103  if (dovacuum || doanalyze)
2104  table_oids = lappend_oid(table_oids, relid);
2105 
2106  /*
2107  * Remember TOAST associations for the second pass. Note: we must do
2108  * this whether or not the table is going to be vacuumed, because we
2109  * don't automatically vacuum toast tables along the parent table.
2110  */
2111  if (OidIsValid(classForm->reltoastrelid))
2112  {
2113  av_relation *hentry;
2114  bool found;
2115 
2116  hentry = hash_search(table_toast_map,
2117  &classForm->reltoastrelid,
2118  HASH_ENTER, &found);
2119 
2120  if (!found)
2121  {
2122  /* hash_search already filled in the key */
2123  hentry->ar_relid = relid;
2124  hentry->ar_hasrelopts = false;
2125  if (relopts != NULL)
2126  {
2127  hentry->ar_hasrelopts = true;
2128  memcpy(&hentry->ar_reloptions, relopts,
2129  sizeof(AutoVacOpts));
2130  }
2131  }
2132  }
2133  }
2134 
2135  table_endscan(relScan);
2136 
2137  /* second pass: check TOAST tables */
2138  ScanKeyInit(&key,
2139  Anum_pg_class_relkind,
2140  BTEqualStrategyNumber, F_CHAREQ,
2141  CharGetDatum(RELKIND_TOASTVALUE));
2142 
2143  relScan = table_beginscan_catalog(classRel, 1, &key);
2144  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2145  {
2146  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2147  PgStat_StatTabEntry *tabentry;
2148  Oid relid;
2149  AutoVacOpts *relopts = NULL;
2150  bool dovacuum;
2151  bool doanalyze;
2152  bool wraparound;
2153 
2154  /*
2155  * We cannot safely process other backends' temp tables, so skip 'em.
2156  */
2157  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2158  continue;
2159 
2160  relid = classForm->oid;
2161 
2162  /*
2163  * fetch reloptions -- if this toast table does not have them, try the
2164  * main rel
2165  */
2166  relopts = extract_autovac_opts(tuple, pg_class_desc);
2167  if (relopts == NULL)
2168  {
2169  av_relation *hentry;
2170  bool found;
2171 
2172  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2173  if (found && hentry->ar_hasrelopts)
2174  relopts = &hentry->ar_reloptions;
2175  }
2176 
2177  /* Fetch the pgstat entry for this table */
2178  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
2179  shared, dbentry);
2180 
2181  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2182  effective_multixact_freeze_max_age,
2183  &dovacuum, &doanalyze, &wraparound);
2184 
2185  /* ignore analyze for toast tables */
2186  if (dovacuum)
2187  table_oids = lappend_oid(table_oids, relid);
2188  }
2189 
2190  table_endscan(relScan);
2191  table_close(classRel, AccessShareLock);
2192 
2193  /*
2194  * Recheck orphan temporary tables, and if they still seem orphaned, drop
2195  * them. We'll eat a transaction per dropped table, which might seem
2196  * excessive, but we should only need to do anything as a result of a
2197  * previous backend crash, so this should not happen often enough to
2198  * justify "optimizing". Using separate transactions ensures that we
2199  * don't bloat the lock table if there are many temp tables to be dropped,
2200  * and it ensures that we don't lose work if a deletion attempt fails.
2201  */
2202  foreach(cell, orphan_oids)
2203  {
2204  Oid relid = lfirst_oid(cell);
2205  Form_pg_class classForm;
2206  ObjectAddress object;
2207 
2208  /*
2209  * Check for user-requested abort.
2210  */
2212 
2213  /*
2214  * Try to lock the table. If we can't get the lock immediately,
2215  * somebody else is using (or dropping) the table, so it's not our
2216  * concern anymore. Having the lock prevents race conditions below.
2217  */
2219  continue;
2220 
2221  /*
2222  * Re-fetch the pg_class tuple and re-check whether it still seems to
2223  * be an orphaned temp table. If it's not there or no longer the same
2224  * relation, ignore it.
2225  */
2226  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2227  if (!HeapTupleIsValid(tuple))
2228  {
2229  /* be sure to drop useless lock so we don't bloat lock table */
2231  continue;
2232  }
2233  classForm = (Form_pg_class) GETSTRUCT(tuple);
2234 
2235  /*
2236  * Make all the same tests made in the loop above. In event of OID
2237  * counter wraparound, the pg_class entry we have now might be
2238  * completely unrelated to the one we saw before.
2239  */
2240  if (!((classForm->relkind == RELKIND_RELATION ||
2241  classForm->relkind == RELKIND_MATVIEW) &&
2242  classForm->relpersistence == RELPERSISTENCE_TEMP))
2243  {
2245  continue;
2246  }
2247 
2248  if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE)
2249  {
2251  continue;
2252  }
2253 
2254  /* OK, let's delete it */
2255  ereport(LOG,
2256  (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2258  get_namespace_name(classForm->relnamespace),
2259  NameStr(classForm->relname))));
2260 
2261  object.classId = RelationRelationId;
2262  object.objectId = relid;
2263  object.objectSubId = 0;
2264  performDeletion(&object, DROP_CASCADE,
2268 
2269  /*
2270  * To commit the deletion, end current transaction and start a new
2271  * one. Note this also releases the lock we took.
2272  */
2275 
2276  /* StartTransactionCommand changed current memory context */
2278  }
2279 
2280  /*
2281  * Create a buffer access strategy object for VACUUM to use. We want to
2282  * use the same one across all the vacuum operations we perform, since the
2283  * point is for VACUUM not to blow out the shared cache.
2284  */
2285  bstrategy = GetAccessStrategy(BAS_VACUUM);
2286 
2287  /*
2288  * create a memory context to act as fake PortalContext, so that the
2289  * contexts created in the vacuum code are cleaned up for each table.
2290  */
2292  "Autovacuum Portal",
2294 
2295  /*
2296  * Perform operations on collected tables.
2297  */
2298  foreach(cell, table_oids)
2299  {
2300  Oid relid = lfirst_oid(cell);
2301  HeapTuple classTup;
2302  autovac_table *tab;
2303  bool isshared;
2304  bool skipit;
2305  double stdVacuumCostDelay;
2306  int stdVacuumCostLimit;
2307  dlist_iter iter;
2308 
2310 
2311  /*
2312  * Check for config changes before processing each collected table.
2313  */
2314  if (ConfigReloadPending)
2315  {
2316  ConfigReloadPending = false;
2318 
2319  /*
2320  * You might be tempted to bail out if we see autovacuum is now
2321  * disabled. Must resist that temptation -- this might be a
2322  * for-wraparound emergency worker, in which case that would be
2323  * entirely inappropriate.
2324  */
2325  }
2326 
2327  /*
2328  * Find out whether the table is shared or not. (It's slightly
2329  * annoying to fetch the syscache entry just for this, but in typical
2330  * cases it adds little cost because table_recheck_autovac would
2331  * refetch the entry anyway. We could buy that back by copying the
2332  * tuple here and passing it to table_recheck_autovac, but that
2333  * increases the odds of that function working with stale data.)
2334  */
2335  classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2336  if (!HeapTupleIsValid(classTup))
2337  continue; /* somebody deleted the rel, forget it */
2338  isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared;
2339  ReleaseSysCache(classTup);
2340 
2341  /*
2342  * Hold schedule lock from here until we've claimed the table. We
2343  * also need the AutovacuumLock to walk the worker array, but that one
2344  * can just be a shared lock.
2345  */
2346  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2347  LWLockAcquire(AutovacuumLock, LW_SHARED);
2348 
2349  /*
2350  * Check whether the table is being vacuumed concurrently by another
2351  * worker.
2352  */
2353  skipit = false;
2355  {
2356  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2357 
2358  /* ignore myself */
2359  if (worker == MyWorkerInfo)
2360  continue;
2361 
2362  /* ignore workers in other databases (unless table is shared) */
2363  if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2364  continue;
2365 
2366  if (worker->wi_tableoid == relid)
2367  {
2368  skipit = true;
2369  found_concurrent_worker = true;
2370  break;
2371  }
2372  }
2373  LWLockRelease(AutovacuumLock);
2374  if (skipit)
2375  {
2376  LWLockRelease(AutovacuumScheduleLock);
2377  continue;
2378  }
2379 
2380  /*
2381  * Store the table's OID in shared memory before releasing the
2382  * schedule lock, so that other workers don't try to vacuum it
2383  * concurrently. (We claim it here so as not to hold
2384  * AutovacuumScheduleLock while rechecking the stats.)
2385  */
2386  MyWorkerInfo->wi_tableoid = relid;
2387  MyWorkerInfo->wi_sharedrel = isshared;
2388  LWLockRelease(AutovacuumScheduleLock);
2389 
2390  /*
2391  * Check whether pgstat data still says we need to vacuum this table.
2392  * It could have changed if something else processed the table while
2393  * we weren't looking.
2394  *
2395  * Note: we have a special case in pgstat code to ensure that the
2396  * stats we read are as up-to-date as possible, to avoid the problem
2397  * that somebody just finished vacuuming this table. The window to
2398  * the race condition is not closed but it is very small.
2399  */
2401  tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
2402  effective_multixact_freeze_max_age);
2403  if (tab == NULL)
2404  {
2405  /* someone else vacuumed the table, or it went away */
2406  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2408  MyWorkerInfo->wi_sharedrel = false;
2409  LWLockRelease(AutovacuumScheduleLock);
2410  continue;
2411  }
2412 
2413  /*
2414  * Remember the prevailing values of the vacuum cost GUCs. We have to
2415  * restore these at the bottom of the loop, else we'll compute wrong
2416  * values in the next iteration of autovac_balance_cost().
2417  */
2418  stdVacuumCostDelay = VacuumCostDelay;
2419  stdVacuumCostLimit = VacuumCostLimit;
2420 
2421  /* Must hold AutovacuumLock while mucking with cost balance info */
2422  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2423 
2424  /* advertise my cost delay parameters for the balancing algorithm */
2429 
2430  /* do a balance */
2432 
2433  /* set the active cost parameters from the result of that */
2435 
2436  /* done */
2437  LWLockRelease(AutovacuumLock);
2438 
2439  /* clean up memory before each iteration */
2441 
2442  /*
2443  * Save the relation name for a possible error message, to avoid a
2444  * catalog lookup in case of an error. If any of these return NULL,
2445  * then the relation has been dropped since last we checked; skip it.
2446  * Note: they must live in a long-lived memory context because we call
2447  * vacuum and analyze in different transactions.
2448  */
2449 
2450  tab->at_relname = get_rel_name(tab->at_relid);
2453  if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2454  goto deleted;
2455 
2456  /*
2457  * We will abort vacuuming the current table if something errors out,
2458  * and continue with the next one in schedule; in particular, this
2459  * happens if we are interrupted with SIGINT.
2460  */
2461  PG_TRY();
2462  {
2463  /* Use PortalContext for any per-table allocations */
2465 
2466  /* have at it */
2467  autovacuum_do_vac_analyze(tab, bstrategy);
2468 
2469  /*
2470  * Clear a possible query-cancel signal, to avoid a late reaction
2471  * to an automatically-sent signal because of vacuuming the
2472  * current table (we're done with it, so it would make no sense to
2473  * cancel at this point.)
2474  */
2475  QueryCancelPending = false;
2476  }
2477  PG_CATCH();
2478  {
2479  /*
2480  * Abort the transaction, start a new one, and proceed with the
2481  * next table in our list.
2482  */
2483  HOLD_INTERRUPTS();
2484  if (tab->at_params.options & VACOPT_VACUUM)
2485  errcontext("automatic vacuum of table \"%s.%s.%s\"",
2486  tab->at_datname, tab->at_nspname, tab->at_relname);
2487  else
2488  errcontext("automatic analyze of table \"%s.%s.%s\"",
2489  tab->at_datname, tab->at_nspname, tab->at_relname);
2490  EmitErrorReport();
2491 
2492  /* this resets the PGXACT flags too */
2494  FlushErrorState();
2496 
2497  /* restart our transaction for the following operations */
2500  }
2501  PG_END_TRY();
2502 
2503  /* Make sure we're back in AutovacMemCxt */
2505 
2506  did_vacuum = true;
2507 
2508  /* the PGXACT flags are reset at the next end of transaction */
2509 
2510  /* be tidy */
2511 deleted:
2512  if (tab->at_datname != NULL)
2513  pfree(tab->at_datname);
2514  if (tab->at_nspname != NULL)
2515  pfree(tab->at_nspname);
2516  if (tab->at_relname != NULL)
2517  pfree(tab->at_relname);
2518  pfree(tab);
2519 
2520  /*
2521  * Remove my info from shared memory. We could, but intentionally
2522  * don't, clear wi_cost_limit and friends --- this is on the
2523  * assumption that we probably have more to do with similar cost
2524  * settings, so we don't want to give up our share of I/O for a very
2525  * short interval and thereby thrash the global balance.
2526  */
2527  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2529  MyWorkerInfo->wi_sharedrel = false;
2530  LWLockRelease(AutovacuumScheduleLock);
2531 
2532  /* restore vacuum cost GUCs for the next iteration */
2533  VacuumCostDelay = stdVacuumCostDelay;
2534  VacuumCostLimit = stdVacuumCostLimit;
2535  }
2536 
2537  /*
2538  * Perform additional work items, as requested by backends.
2539  */
2540  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2541  for (i = 0; i < NUM_WORKITEMS; i++)
2542  {
2544 
2545  if (!workitem->avw_used)
2546  continue;
2547  if (workitem->avw_active)
2548  continue;
2549  if (workitem->avw_database != MyDatabaseId)
2550  continue;
2551 
2552  /* claim this one, and release lock while performing it */
2553  workitem->avw_active = true;
2554  LWLockRelease(AutovacuumLock);
2555 
2556  perform_work_item(workitem);
2557 
2558  /*
2559  * Check for config changes before acquiring lock for further jobs.
2560  */
2562  if (ConfigReloadPending)
2563  {
2564  ConfigReloadPending = false;
2566  }
2567 
2568  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2569 
2570  /* and mark it done */
2571  workitem->avw_active = false;
2572  workitem->avw_used = false;
2573  }
2574  LWLockRelease(AutovacuumLock);
2575 
2576  /*
2577  * We leak table_toast_map here (among other things), but since we're
2578  * going away soon, it's not a problem.
2579  */
2580 
2581  /*
2582  * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2583  * only need to do this once, not after each table.
2584  *
2585  * Even if we didn't vacuum anything, it may still be important to do
2586  * this, because one indirect effect of vac_update_datfrozenxid() is to
2587  * update ShmemVariableCache->xidVacLimit. That might need to be done
2588  * even if we haven't vacuumed anything, because relations with older
2589  * relfrozenxid values or other databases with older datfrozenxid values
2590  * might have been dropped, allowing xidVacLimit to advance.
2591  *
2592  * However, it's also important not to do this blindly in all cases,
2593  * because when autovacuum=off this will restart the autovacuum launcher.
2594  * If we're not careful, an infinite loop can result, where workers find
2595  * no work to do and restart the launcher, which starts another worker in
2596  * the same database that finds no work to do. To prevent that, we skip
2597  * this if (1) we found no work to do and (2) we skipped at least one
2598  * table due to concurrent autovacuum activity. In that case, the other
2599  * worker has already done it, or will do so when it finishes.
2600  */
2601  if (did_vacuum || !found_concurrent_worker)
2603 
2604  /* Finally close out the last transaction. */
2606 }
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:542
#define NIL
Definition: pg_list.h:65
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
static int default_freeze_table_age
Definition: autovacuum.c:152
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
#define AllocSetContextCreate
Definition: memutils.h:170
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define NUM_WORKITEMS
Definition: autovacuum.c:264
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
static void autovac_balance_cost(void)
Definition: autovacuum.c:1775
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:64
#define HASH_ELEM
Definition: hsearch.h:87
void ProcessConfigFile(GucContext context)
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
Definition: autovacuum.c:2718
void vac_update_datfrozenxid(void)
Definition: vacuum.c:1333
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:153
#define RelationGetDescr(relation)
Definition: rel.h:482
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:199
FormData_pg_database * Form_pg_database
Definition: pg_database.h:81
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
void CommitTransactionCommand(void)
Definition: xact.c:2947
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:157
double wi_cost_delay
Definition: autovacuum.c:229
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:949
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2481
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:927
char * at_datname
Definition: autovacuum.c:199
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:651
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4580
void FlushErrorState(void)
Definition: elog.c:1568
MemoryContext PortalContext
Definition: mcxt.c:53
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
TempNamespaceStatus checkTempNamespaceStatus(Oid namespaceId)
Definition: namespace.c:3237
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
int at_vacuum_cost_limit
Definition: autovacuum.c:194
Definition: dynahash.c:220
char * at_relname
Definition: autovacuum.c:197
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
int VacuumCostLimit
Definition: globals.c:141
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:63
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:289
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1286
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:312
static void perform_work_item(AutoVacuumWorkItem *workitem)
Definition: autovacuum.c:2612
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:302
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:2957
void pgstat_vacuum_stat(void)
Definition: pgstat.c:1052
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2815
int wi_cost_limit_base
Definition: autovacuum.c:231
MemoryContext TopMemoryContext
Definition: mcxt.c:44
Definition: guc.h:72
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define HASH_BLOBS
Definition: hsearch.h:88
char * at_nspname
Definition: autovacuum.c:198
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:328
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
Oid MyDatabaseId
Definition: globals.c:85
double at_vacuum_cost_delay
Definition: autovacuum.c:193
Size keysize
Definition: hsearch.h:72
dlist_node * cur
Definition: ilist.h:161
void EmitErrorReport(void)
Definition: elog.c:1423
#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:2744
VacuumParams at_params
Definition: autovacuum.c:192
#define ereport(elevel,...)
Definition: elog.h:144
#define PG_CATCH()
Definition: elog.h:305
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:136
void StartTransactionCommand(void)
Definition: xact.c:2846
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:292
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
int vacuum_freeze_min_age
Definition: vacuum.c:61
int vacuum_freeze_table_age
Definition: vacuum.c:62
#define CharGetDatum(X)
Definition: postgres.h:416
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
AutoVacOpts ar_reloptions
Definition: autovacuum.c:184
#define AccessExclusiveLock
Definition: lockdefs.h:45
static void autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
Definition: autovacuum.c:3123
int errmsg(const char *fmt,...)
Definition: elog.c:824
double VacuumCostDelay
Definition: globals.c:142
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:214
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
int i
int options
Definition: vacuum.h:210
#define errcontext
Definition: elog.h:185
#define NameStr(name)
Definition: c.h:622
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:1759
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
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:2771
dlist_head av_runningWorkers
Definition: autovacuum.c:287
#define PG_TRY()
Definition: elog.h:295
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:138
bool ar_hasrelopts
Definition: autovacuum.c:183
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
static int default_multixact_freeze_table_age
Definition: autovacuum.c:154
static int default_freeze_min_age
Definition: autovacuum.c:151
#define PG_END_TRY()
Definition: elog.h:320
#define BTEqualStrategyNumber
Definition: stratnum.h:31
bool at_dobalance
Definition: autovacuum.c:195
#define lfirst_oid(lc)
Definition: pg_list.h:192
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:134

◆ do_start_worker()

static Oid do_start_worker ( void  )
static

Definition at line 1138 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, ReadNewTransactionId(), ReadNextMultiXactId(), rebuild_database_list(), recentMulti, recentXid, SendPostmasterSignal(), TimestampDifferenceExceeds(), TransactionIdPrecedes(), WorkerInfoData::wi_dboid, WorkerInfoData::wi_launchtime, and WorkerInfoData::wi_proc.

Referenced by AutoVacLauncherMain(), and launch_worker().

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

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

Referenced by do_autovacuum(), and table_recheck_autovac().

2719 {
2720  bytea *relopts;
2721  AutoVacOpts *av;
2722 
2723  Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2724  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2725  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2726 
2727  relopts = extractRelOptions(tup, pg_class_desc, NULL);
2728  if (relopts == NULL)
2729  return NULL;
2730 
2731  av = palloc(sizeof(AutoVacOpts));
2732  memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2733  pfree(relopts);
2734 
2735  return av;
2736 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
void pfree(void *pointer)
Definition: mcxt.c:1056
struct @17::@18 av[32]
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
Definition: reloptions.c:1357
#define Assert(condition)
Definition: c.h:745
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
void * palloc(Size size)
Definition: mcxt.c:949
Definition: c.h:562

◆ FreeWorkerInfo()

static void FreeWorkerInfo ( int  code,
Datum  arg 
)
static

Definition at line 1710 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().

1711 {
1712  if (MyWorkerInfo != NULL)
1713  {
1714  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1715 
1716  /*
1717  * Wake the launcher up so that he can launch a new worker immediately
1718  * if required. We only save the launcher's PID in local memory here;
1719  * the actual signal will be sent when the PGPROC is recycled. Note
1720  * that we always do this, so that the launcher can rebalance the cost
1721  * limit setting of the remaining workers.
1722  *
1723  * We somewhat ignore the risk that the launcher changes its PID
1724  * between us reading it and the actual kill; we expect ProcKill to be
1725  * called shortly after us, and we assume that PIDs are not reused too
1726  * quickly after a process exits.
1727  */
1729 
1733  MyWorkerInfo->wi_sharedrel = false;
1734  MyWorkerInfo->wi_proc = NULL;
1736  MyWorkerInfo->wi_dobalance = false;
1742  /* not mine anymore */
1743  MyWorkerInfo = NULL;
1744 
1745  /*
1746  * now that we're inactive, cause a rebalancing of the surviving
1747  * workers
1748  */
1750  LWLockRelease(AutovacuumLock);
1751  }
1752 }
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:284
dlist_head av_freeWorkers
Definition: autovacuum.c:286
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz wi_launchtime
Definition: autovacuum.c:226
double wi_cost_delay
Definition: autovacuum.c:229
dlist_node wi_links
Definition: autovacuum.c:222
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
int AutovacuumLauncherPid
Definition: autovacuum.c:305
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:302
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
int wi_cost_limit_base
Definition: autovacuum.c:231
#define InvalidOid
Definition: postgres_ext.h:36
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:292
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
PGPROC * wi_proc
Definition: autovacuum.c:225

◆ get_database_list()

static List* get_database_list ( void  )
static

Definition at line 1863 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().

1864 {
1865  List *dblist = NIL;
1866  Relation rel;
1867  TableScanDesc scan;
1868  HeapTuple tup;
1869  MemoryContext resultcxt;
1870 
1871  /* This is the context that we will allocate our output data in */
1872  resultcxt = CurrentMemoryContext;
1873 
1874  /*
1875  * Start a transaction so we can access pg_database, and get a snapshot.
1876  * We don't have a use for the snapshot itself, but we're interested in
1877  * the secondary effect that it sets RecentGlobalXmin. (This is critical
1878  * for anything that reads heap pages, because HOT may decide to prune
1879  * them even if the process doesn't attempt to modify any tuples.)
1880  */
1882  (void) GetTransactionSnapshot();
1883 
1884  rel = table_open(DatabaseRelationId, AccessShareLock);
1885  scan = table_beginscan_catalog(rel, 0, NULL);
1886 
1887  while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1888  {
1889  Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1890  avw_dbase *avdb;
1891  MemoryContext oldcxt;
1892 
1893  /*
1894  * Allocate our results in the caller's context, not the
1895  * transaction's. We do this inside the loop, and restore the original
1896  * context at the end, so that leaky things like heap_getnext() are
1897  * not called in a potentially long-lived context.
1898  */
1899  oldcxt = MemoryContextSwitchTo(resultcxt);
1900 
1901  avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1902 
1903  avdb->adw_datid = pgdatabase->oid;
1904  avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1905  avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1906  avdb->adw_minmulti = pgdatabase->datminmxid;
1907  /* this gets set later: */
1908  avdb->adw_entry = NULL;
1909 
1910  dblist = lappend(dblist, avdb);
1911  MemoryContextSwitchTo(oldcxt);
1912  }
1913 
1914  table_endscan(scan);
1916 
1918 
1919  return dblist;
1920 }
#define NIL
Definition: pg_list.h:65
MultiXactId adw_minmulti
Definition: autovacuum.c:174
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
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:1186
void CommitTransactionCommand(void)
Definition: xact.c:2947
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
_stringlist * dblist
Definition: pg_regress.c:73
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1286
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
char * adw_name
Definition: autovacuum.c:172
List * lappend(List *list, void *datum)
Definition: list.c:321
TransactionId adw_frozenxid
Definition: autovacuum.c:173
PgStat_StatDBEntry * adw_entry
Definition: autovacuum.c:175
Oid adw_datid
Definition: autovacuum.c:171
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void StartTransactionCommand(void)
Definition: xact.c:2846
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:863
void * palloc(Size size)
Definition: mcxt.c:949
#define NameStr(name)
Definition: c.h:622
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 2744 of file autovacuum.c.

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

Referenced by do_autovacuum(), and table_recheck_autovac().

2746 {
2747  PgStat_StatTabEntry *tabentry = NULL;
2748 
2749  if (isshared)
2750  {
2751  if (PointerIsValid(shared))
2752  tabentry = hash_search(shared->tables, &relid,
2753  HASH_FIND, NULL);
2754  }
2755  else if (PointerIsValid(dbentry))
2756  tabentry = hash_search(dbentry->tables, &relid,
2757  HASH_FIND, NULL);
2758 
2759  return tabentry;
2760 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:927
#define PointerIsValid(pointer)
Definition: c.h:639

◆ HandleAutoVacLauncherInterrupts()

static void HandleAutoVacLauncherInterrupts ( void  )
static

Definition at line 800 of file autovacuum.c.

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

Referenced by AutoVacLauncherMain().

801 {
802  /* the normal shutdown case */
805 
807  {
808  ConfigReloadPending = false;
810 
811  /* shutdown requested in config file? */
812  if (!AutoVacuumingActive())
814 
815  /* rebalance in case the default cost parameters changed */
816  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
818  LWLockRelease(AutovacuumLock);
819 
820  /* rebuild the list in case the naptime changed */
822  }
823 
824  /* Process barrier events */
827 
828  /* Process sinval catchup interrupts that happened while sleeping */
830 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176
static void autovac_balance_cost(void)
Definition: autovacuum.c:1775
void ProcessConfigFile(GucContext context)
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:452
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3227
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:35
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:937
static void AutoVacLauncherShutdown(void)
Definition: autovacuum.c:316
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26

◆ IsAutoVacuumLauncherProcess()

bool IsAutoVacuumLauncherProcess ( void  )

Definition at line 3295 of file autovacuum.c.

References am_autovacuum_launcher.

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

3296 {
3297  return am_autovacuum_launcher;
3298 }
static bool am_autovacuum_launcher
Definition: autovacuum.c:140

◆ IsAutoVacuumWorkerProcess()

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1353 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().

1354 {
1355  Oid dbid;
1356  dlist_iter iter;
1357 
1358  dbid = do_start_worker();
1359  if (OidIsValid(dbid))
1360  {
1361  bool found = false;
1362 
1363  /*
1364  * Walk the database list and update the corresponding entry. If the
1365  * database is not on the list, we'll recreate the list.
1366  */
1367  dlist_foreach(iter, &DatabaseList)
1368  {
1369  avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1370 
1371  if (avdb->adl_datid == dbid)
1372  {
1373  found = true;
1374 
1375  /*
1376  * add autovacuum_naptime seconds to the current time, and use
1377  * that as the new "next_worker" field for this database.
1378  */
1379  avdb->adl_next_worker =
1381 
1383  break;
1384  }
1385  }
1386 
1387  /*
1388  * If the database was not present in the database list, we rebuild
1389  * the list. It's possible that the database does not get into the
1390  * list anyway, for example if it's a database that doesn't have a
1391  * pgstat entry, but this is not a problem because we don't want to
1392  * schedule workers regularly into those in any case.
1393  */
1394  if (!found)
1395  rebuild_database_list(dbid);
1396  }
1397 }
int autovacuum_naptime
Definition: autovacuum.c:117
TimestampTz adl_next_worker
Definition: autovacuum.c:163
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:651
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
Oid adl_datid
Definition: autovacuum.c:162
static dlist_head DatabaseList
Definition: autovacuum.c:298
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:937
static Oid do_start_worker(void)
Definition: autovacuum.c:1138
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538

◆ launcher_determine_sleep()

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

Definition at line 853 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().

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

◆ perform_work_item()

static void perform_work_item ( AutoVacuumWorkItem workitem)
static

Definition at line 2612 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().

2613 {
2614  char *cur_datname = NULL;
2615  char *cur_nspname = NULL;
2616  char *cur_relname = NULL;
2617 
2618  /*
2619  * Note we do not store table info in MyWorkerInfo, since this is not
2620  * vacuuming proper.
2621  */
2622 
2623  /*
2624  * Save the relation name for a possible error message, to avoid a catalog
2625  * lookup in case of an error. If any of these return NULL, then the
2626  * relation has been dropped since last we checked; skip it.
2627  */
2629 
2630  cur_relname = get_rel_name(workitem->avw_relation);
2631  cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2632  cur_datname = get_database_name(MyDatabaseId);
2633  if (!cur_relname || !cur_nspname || !cur_datname)
2634  goto deleted2;
2635 
2636  autovac_report_workitem(workitem, cur_nspname, cur_relname);
2637 
2638  /* clean up memory before each work item */
2640 
2641  /*
2642  * We will abort the current work item if something errors out, and
2643  * continue with the next one; in particular, this happens if we are
2644  * interrupted with SIGINT. Note that this means that the work item list
2645  * can be lossy.
2646  */
2647  PG_TRY();
2648  {
2649  /* Use PortalContext for any per-work-item allocations */
2651 
2652  /* have at it */
2653  switch (workitem->avw_type)
2654  {
2657  ObjectIdGetDatum(workitem->avw_relation),
2658  Int64GetDatum((int64) workitem->avw_blockNumber));
2659  break;
2660  default:
2661  elog(WARNING, "unrecognized work item found: type %d",
2662  workitem->avw_type);
2663  break;
2664  }
2665 
2666  /*
2667  * Clear a possible query-cancel signal, to avoid a late reaction to
2668  * an automatically-sent signal because of vacuuming the current table
2669  * (we're done with it, so it would make no sense to cancel at this
2670  * point.)
2671  */
2672  QueryCancelPending = false;
2673  }
2674  PG_CATCH();
2675  {
2676  /*
2677  * Abort the transaction, start a new one, and proceed with the next
2678  * table in our list.
2679  */
2680  HOLD_INTERRUPTS();
2681  errcontext("processing work entry for relation \"%s.%s.%s\"",
2682  cur_datname, cur_nspname, cur_relname);
2683  EmitErrorReport();
2684 
2685  /* this resets the PGXACT flags too */
2687  FlushErrorState();
2689 
2690  /* restart our transaction for the following operations */
2693  }
2694  PG_END_TRY();
2695 
2696  /* Make sure we're back in AutovacMemCxt */
2698 
2699  /* We intentionally do not set did_vacuum here */
2700 
2701  /* be tidy */
2702 deleted2:
2703  if (cur_datname)
2704  pfree(cur_datname);
2705  if (cur_nspname)
2706  pfree(cur_nspname);
2707  if (cur_relname)
2708  pfree(cur_relname);
2709 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:256
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:157
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1864
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4580
void FlushErrorState(void)
Definition: elog.c:1568
MemoryContext PortalContext
Definition: mcxt.c:53
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:861
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
void pfree(void *pointer)
Definition: mcxt.c:1056
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2155
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3191
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
Definition: autovacuum.c:3187
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1701
#define WARNING
Definition: elog.h:40
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
Oid MyDatabaseId
Definition: globals.c:85
BlockNumber avw_blockNumber
Definition: autovacuum.c:261
void EmitErrorReport(void)
Definition: elog.c:1423
#define PG_CATCH()
Definition: elog.h:305
#define Assert(condition)
Definition: c.h:745
void StartTransactionCommand(void)
Definition: xact.c:2846
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
#define elog(elevel,...)
Definition: elog.h:214
#define errcontext
Definition: elog.h:185
#define PG_TRY()
Definition: elog.h:295
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1840
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:626
#define PG_END_TRY()
Definition: elog.h:320

◆ rebuild_database_list()

static void rebuild_database_list ( Oid  newdb)
static

Definition at line 937 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().

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

◆ 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 2957 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 table_recheck_autovac().

2966 {
2967  bool force_vacuum;
2968  bool av_enabled;
2969  float4 reltuples; /* pg_class.reltuples */
2970 
2971  /* constants from reloptions or GUC variables */
2972  int vac_base_thresh,
2973  vac_ins_base_thresh,
2974  anl_base_thresh;
2975  float4 vac_scale_factor,
2976  vac_ins_scale_factor,
2977  anl_scale_factor;
2978 
2979  /* thresholds calculated from above constants */
2980  float4 vacthresh,
2981  vacinsthresh,
2982  anlthresh;
2983 
2984  /* number of vacuum (resp. analyze) tuples at this time */
2985  float4 vactuples,
2986  instuples,
2987  anltuples;
2988 
2989  /* freeze parameters */
2990  int freeze_max_age;
2991  int multixact_freeze_max_age;
2992  TransactionId xidForceLimit;
2993  MultiXactId multiForceLimit;
2994 
2995  AssertArg(classForm != NULL);
2996  AssertArg(OidIsValid(relid));
2997 
2998  /*
2999  * Determine vacuum/analyze equation parameters. We have two possible
3000  * sources: the passed reloptions (which could be a main table or a toast
3001  * table), or the autovacuum GUC variables.
3002  */
3003 
3004  /* -1 in autovac setting means use plain vacuum_scale_factor */
3005  vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3006  ? relopts->vacuum_scale_factor
3008 
3009  vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3010  ? relopts->vacuum_threshold
3012 
3013  vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3014  ? relopts->vacuum_ins_scale_factor
3016 
3017  /* -1 is used to disable insert vacuums */
3018  vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3019  ? relopts->vacuum_ins_threshold
3021 
3022  anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3023  ? relopts->analyze_scale_factor
3025 
3026  anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3027  ? relopts->analyze_threshold
3029 
3030  freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3033 
3034  multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3035  ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3036  : effective_multixact_freeze_max_age;
3037 
3038  av_enabled = (relopts ? relopts->enabled : true);
3039 
3040  /* Force vacuum if table is at risk of wraparound */
3041  xidForceLimit = recentXid - freeze_max_age;
3042  if (xidForceLimit < FirstNormalTransactionId)
3043  xidForceLimit -= FirstNormalTransactionId;
3044  force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
3045  TransactionIdPrecedes(classForm->relfrozenxid,
3046  xidForceLimit));
3047  if (!force_vacuum)
3048  {
3049  multiForceLimit = recentMulti - multixact_freeze_max_age;
3050  if (multiForceLimit < FirstMultiXactId)
3051  multiForceLimit -= FirstMultiXactId;
3052  force_vacuum = MultiXactIdIsValid(classForm->relminmxid) &&
3053  MultiXactIdPrecedes(classForm->relminmxid, multiForceLimit);
3054  }
3055  *wraparound = force_vacuum;
3056 
3057  /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3058  if (!av_enabled && !force_vacuum)
3059  {
3060  *doanalyze = false;
3061  *dovacuum = false;
3062  return;
3063  }
3064 
3065  /*
3066  * If we found the table in the stats hash, and autovacuum is currently
3067  * enabled, make a threshold-based decision whether to vacuum and/or
3068  * analyze. If autovacuum is currently disabled, we must be here for
3069  * anti-wraparound vacuuming only, so don't vacuum (or analyze) anything
3070  * that's not being forced.
3071  */
3072  if (PointerIsValid(tabentry) && AutoVacuumingActive())
3073  {
3074  reltuples = classForm->reltuples;
3075  vactuples = tabentry->n_dead_tuples;
3076  instuples = tabentry->inserts_since_vacuum;
3077  anltuples = tabentry->changes_since_analyze;
3078 
3079  vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3080  vacinsthresh = (float4) vac_ins_base_thresh + vac_ins_scale_factor * reltuples;
3081  anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3082 
3083  /*
3084  * Note that we don't need to take special consideration for stat
3085  * reset, because if that happens, the last vacuum and analyze counts
3086  * will be reset too.
3087  */
3088  if (vac_ins_base_thresh >= 0)
3089  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3090  NameStr(classForm->relname),
3091  vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3092  else
3093  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3094  NameStr(classForm->relname),
3095  vactuples, vacthresh, anltuples, anlthresh);
3096 
3097  /* Determine if this table needs vacuum or analyze. */
3098  *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3099  (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3100  *doanalyze = (anltuples > anlthresh);
3101  }
3102  else
3103  {
3104  /*
3105  * Skip a table not found in stat hash, unless we have to force vacuum
3106  * for anti-wrap purposes. If it's not acted upon, there's no need to
3107  * vacuum it.
3108  */
3109  *dovacuum = force_vacuum;
3110  *doanalyze = false;
3111  }
3112 
3113  /* ANALYZE refuses to work with pg_statistic */
3114  if (relid == StatisticRelationId)
3115  *doanalyze = false;
3116 }
double autovacuum_anl_scale
Definition: autovacuum.c:123
int autovacuum_vac_ins_thresh
Definition: autovacuum.c:120
uint32 TransactionId
Definition: c.h:520
#define DEBUG3
Definition: elog.h:23
float8 vacuum_scale_factor
Definition: rel.h:292
#define Min(x, y)
Definition: c.h:927
static MultiXactId recentMulti
Definition: autovacuum.c:148
#define OidIsValid(objectId)
Definition: c.h:651
double autovacuum_vac_ins_scale
Definition: autovacuum.c:121
PgStat_Counter inserts_since_vacuum
Definition: pgstat.h:682
#define FirstNormalTransactionId
Definition: transam.h:34
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3227
int autovacuum_freeze_max_age
Definition: autovacuum.c:124
PgStat_Counter n_dead_tuples
Definition: pgstat.h:680
int analyze_threshold
Definition: rel.h:282
int autovacuum_vac_thresh
Definition: autovacuum.c:118
#define MultiXactIdIsValid(multi)
Definition: multixact.h:27
#define FirstMultiXactId
Definition: multixact.h:24
#define AssertArg(condition)
Definition: c.h:747
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
float float4
Definition: c.h:497
int vacuum_threshold
Definition: rel.h:280
static TransactionId recentXid
Definition: autovacuum.c:147
PgStat_Counter changes_since_analyze
Definition: pgstat.h:681
double autovacuum_vac_scale
Definition: autovacuum.c:119
float8 analyze_scale_factor
Definition: rel.h:294
TransactionId MultiXactId
Definition: c.h:530
int freeze_max_age
Definition: rel.h:285
bool enabled
Definition: rel.h:279
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3138
int vacuum_ins_threshold
Definition: rel.h:281
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:622
int multixact_freeze_max_age
Definition: rel.h:288
float8 vacuum_ins_scale_factor
Definition: rel.h:293
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define PointerIsValid(pointer)
Definition: c.h:639
int autovacuum_anl_thresh
Definition: autovacuum.c:122

◆ StartAutoVacWorker()

int StartAutoVacWorker ( void  )

Definition at line 1465 of file autovacuum.c.

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

Referenced by StartAutovacuumWorker().

1466 {
1467  pid_t worker_pid;
1468 
1469 #ifdef EXEC_BACKEND
1470  switch ((worker_pid = avworker_forkexec()))
1471 #else
1472  switch ((worker_pid = fork_process()))
1473 #endif
1474  {
1475  case -1:
1476  ereport(LOG,
1477  (errmsg("could not fork autovacuum worker process: %m")));
1478  return 0;
1479 
1480 #ifndef EXEC_BACKEND
1481  case 0:
1482  /* in postmaster child ... */
1484 
1485  /* Close the postmaster's sockets */
1486  ClosePostmasterPorts(false);
1487 
1488  AutoVacWorkerMain(0, NULL);
1489  break;
1490 #endif
1491  default:
1492  return (int) worker_pid;
1493  }
1494 
1495  /* shouldn't get here */
1496  return 0;
1497 }
void InitPostmasterChild(void)
Definition: miscinit.c:91
pid_t fork_process(void)
Definition: fork_process.c:32
#define LOG
Definition: elog.h:26
NON_EXEC_STATIC void AutoVacWorkerMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: autovacuum.c:1503
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2559
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ 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 2771 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, get_pgstat_tabentry_relid(), GETSTRUCT, HASH_FIND, hash_search(), heap_freetuple(), HeapTupleIsValid, VacuumParams::index_cleanup, InvalidOid, 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, MyDatabaseId, VacuumParams::nworkers, ObjectIdGetDatum, VacuumParams::options, palloc(), pgstat_fetch_stat_dbentry(), relation_needs_vacanalyze(), RELOID, SearchSysCacheCopy1, VacuumParams::truncate, VACOPT_ANALYZE, VACOPT_SKIP_LOCKED, VACOPT_SKIPTOAST, VACOPT_TERNARY_DEFAULT, VACOPT_VACUUM, AutoVacOpts::vacuum_cost_delay, AutoVacOpts::vacuum_cost_limit, VacuumCostDelay, and VacuumCostLimit.

Referenced by do_autovacuum().

2774 {
2775  Form_pg_class classForm;
2776  HeapTuple classTup;
2777  bool dovacuum;
2778  bool doanalyze;
2779  autovac_table *tab = NULL;
2780  PgStat_StatTabEntry *tabentry;
2781  PgStat_StatDBEntry *shared;
2782  PgStat_StatDBEntry *dbentry;
2783  bool wraparound;
2784  AutoVacOpts *avopts;
2785 
2786  /* use fresh stats */
2788 
2791 
2792  /* fetch the relation's relcache entry */
2793  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2794  if (!HeapTupleIsValid(classTup))
2795  return NULL;
2796  classForm = (Form_pg_class) GETSTRUCT(classTup);
2797 
2798  /*
2799  * Get the applicable reloptions. If it is a TOAST table, try to get the
2800  * main table reloptions if the toast table itself doesn't have.
2801  */
2802  avopts = extract_autovac_opts(classTup, pg_class_desc);
2803  if (classForm->relkind == RELKIND_TOASTVALUE &&
2804  avopts == NULL && table_toast_map != NULL)
2805  {
2806  av_relation *hentry;
2807  bool found;
2808 
2809  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2810  if (found && hentry->ar_hasrelopts)
2811  avopts = &hentry->ar_reloptions;
2812  }
2813 
2814  /* fetch the pgstat table entry */
2815  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
2816  shared, dbentry);
2817 
2818  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2819  effective_multixact_freeze_max_age,
2820  &dovacuum, &doanalyze, &wraparound);
2821 
2822  /* ignore ANALYZE for toast tables */
2823  if (classForm->relkind == RELKIND_TOASTVALUE)
2824  doanalyze = false;
2825 
2826  /* OK, it needs something done */
2827  if (doanalyze || dovacuum)
2828  {
2829  int freeze_min_age;
2830  int freeze_table_age;
2831  int multixact_freeze_min_age;
2832  int multixact_freeze_table_age;
2833  int vac_cost_limit;
2834  double vac_cost_delay;
2835  int log_min_duration;
2836 
2837  /*
2838  * Calculate the vacuum cost parameters and the freeze ages. If there
2839  * are options set in pg_class.reloptions, use them; in the case of a
2840  * toast table, try the main table too. Otherwise use the GUC
2841  * defaults, autovacuum's own first and plain vacuum second.
2842  */
2843 
2844  /* -1 in autovac setting means use plain vacuum_cost_delay */
2845  vac_cost_delay = (avopts && avopts->vacuum_cost_delay >= 0)
2846  ? avopts->vacuum_cost_delay
2847  : (autovacuum_vac_cost_delay >= 0)
2849  : VacuumCostDelay;
2850 
2851  /* 0 or -1 in autovac setting means use plain vacuum_cost_limit */
2852  vac_cost_limit = (avopts && avopts->vacuum_cost_limit > 0)
2853  ? avopts->vacuum_cost_limit
2856  : VacuumCostLimit;
2857 
2858  /* -1 in autovac setting means use log_autovacuum_min_duration */
2859  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2860  ? avopts->log_min_duration
2862 
2863  /* these do not have autovacuum-specific settings */
2864  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2865  ? avopts->freeze_min_age
2867 
2868  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2869  ? avopts->freeze_table_age
2871 
2872  multixact_freeze_min_age = (avopts &&
2873  avopts->multixact_freeze_min_age >= 0)
2874  ? avopts->multixact_freeze_min_age
2876 
2877  multixact_freeze_table_age = (avopts &&
2878  avopts->multixact_freeze_table_age >= 0)
2879  ? avopts->multixact_freeze_table_age
2881 
2882  tab = palloc(sizeof(autovac_table));
2883  tab->at_relid = relid;
2884  tab->at_sharedrel = classForm->relisshared;
2886  (dovacuum ? VACOPT_VACUUM : 0) |
2887  (doanalyze ? VACOPT_ANALYZE : 0) |
2888  (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2891  /* As of now, we don't support parallel vacuum for autovacuum */
2892  tab->at_params.nworkers = -1;
2893  tab->at_params.freeze_min_age = freeze_min_age;
2894  tab->at_params.freeze_table_age = freeze_table_age;
2895  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2896  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2897  tab->at_params.is_wraparound = wraparound;
2898  tab->at_params.log_min_duration = log_min_duration;
2899  tab->at_vacuum_cost_limit = vac_cost_limit;
2900  tab->at_vacuum_cost_delay = vac_cost_delay;
2901  tab->at_relname = NULL;
2902  tab->at_nspname = NULL;
2903  tab->at_datname = NULL;
2904 
2905  /*
2906  * If any of the cost delay parameters has been set individually for
2907  * this table, disable the balancing algorithm.
2908  */
2909  tab->at_dobalance =
2910  !(avopts && (avopts->vacuum_cost_limit > 0 ||
2911  avopts->vacuum_cost_delay > 0));
2912  }
2913 
2914  heap_freetuple(classTup);
2915 
2916  return tab;
2917 }
int multixact_freeze_table_age
Definition: vacuum.h:215
static int default_freeze_table_age
Definition: autovacuum.c:152
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
Definition: autovacuum.c:2718
static int default_multixact_freeze_min_age
Definition: autovacuum.c:153
int freeze_min_age
Definition: rel.h:284
static void autovac_refresh_stats(void)
Definition: autovacuum.c:3379
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2481
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:927
char * at_datname
Definition: autovacuum.c:199
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
int freeze_table_age
Definition: vacuum.h:212
int autovacuum_vac_cost_limit
Definition: autovacuum.c:128
bool at_sharedrel
Definition: autovacuum.c:196
int freeze_table_age
Definition: rel.h:286
int at_vacuum_cost_limit
Definition: autovacuum.c:194
char * at_relname
Definition: autovacuum.c:197
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
int VacuumCostLimit
Definition: globals.c:141
int freeze_min_age
Definition: vacuum.h:211
float8 vacuum_cost_delay
Definition: rel.h:291
bool is_wraparound
Definition: vacuum.h:217
double autovacuum_vac_cost_delay
Definition: autovacuum.c:127
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:2957
VacOptTernaryValue index_cleanup
Definition: vacuum.h:221
char * at_nspname
Definition: autovacuum.c:198
int multixact_freeze_table_age
Definition: rel.h:289
Oid MyDatabaseId
Definition: globals.c:85
double at_vacuum_cost_delay
Definition: autovacuum.c:193
#define InvalidOid
Definition: postgres_ext.h:36
VacOptTernaryValue truncate
Definition: vacuum.h:223
static PgStat_StatTabEntry * get_pgstat_tabentry_relid(Oid relid, bool isshared, PgStat_StatDBEntry *shared, PgStat_StatDBEntry *dbentry)
Definition: autovacuum.c:2744
VacuumParams at_params
Definition: autovacuum.c:192
int vacuum_cost_limit
Definition: rel.h:283
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int multixact_freeze_min_age
Definition: rel.h:287
int nworkers
Definition: vacuum.h:231
int log_min_duration
Definition: vacuum.h:218
int log_min_duration
Definition: rel.h:290
int Log_autovacuum_min_duration
Definition: autovacuum.c:130
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:174
AutoVacOpts ar_reloptions
Definition: autovacuum.c:184
void * palloc(Size size)
Definition: mcxt.c:949
double VacuumCostDelay
Definition: globals.c:142
int options
Definition: vacuum.h:210
bool ar_hasrelopts
Definition: autovacuum.c:183
static int default_multixact_freeze_table_age
Definition: autovacuum.c:154
int multixact_freeze_min_age
Definition: vacuum.h:213
static int default_freeze_min_age
Definition: autovacuum.c:151
bool at_dobalance
Definition: autovacuum.c:195

Variable Documentation

◆ am_autovacuum_launcher

bool am_autovacuum_launcher = false
static

Definition at line 140 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and IsAutoVacuumLauncherProcess().

◆ am_autovacuum_worker

bool am_autovacuum_worker = false
static

Definition at line 141 of file autovacuum.c.

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

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

Definition at line 157 of file autovacuum.c.

◆ autovacuum_anl_scale

double autovacuum_anl_scale

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 122 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

Definition at line 125 of file autovacuum.c.

Referenced by MultiXactMemberFreezeThreshold(), and SetMultiXactIdLimit().

◆ autovacuum_naptime

int autovacuum_naptime

◆ autovacuum_start_daemon

bool autovacuum_start_daemon = false

Definition at line 114 of file autovacuum.c.

Referenced by autovac_init(), and AutoVacuumingActive().

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 127 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 128 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 121 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 120 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 119 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 118 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 116 of file autovacuum.c.

Referenced by compute_max_dead_tuples(), and ginInsertCleanup().

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

Definition at line 305 of file autovacuum.c.

Referenced by FreeWorkerInfo(), and ProcKill().

◆ AutoVacuumShmem

AutoVacuumShmemStruct* AutoVacuumShmem
static

Definition at line 292 of file autovacuum.c.

◆ DatabaseList

dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
static

Definition at line 298 of file autovacuum.c.

◆ DatabaseListCxt

MemoryContext DatabaseListCxt = NULL
static

Definition at line 299 of file autovacuum.c.

◆ default_freeze_min_age

int default_freeze_min_age
static

Definition at line 151 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 152 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 153 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 154 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 144 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and avl_sigusr2_handler().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = -1

Definition at line 130 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

WorkerInfo MyWorkerInfo = NULL
static

Definition at line 302 of file autovacuum.c.

◆ recentMulti

MultiXactId recentMulti
static

Definition at line 148 of file autovacuum.c.

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

◆ recentXid

TransactionId recentXid
static

Definition at line 147 of file autovacuum.c.

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