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 recheck_relation_needs_vacanalyze (Oid relid, AutoVacOpts *avopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
 
static void relation_needs_vacanalyze (Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, PgStat_StatTabEntry *tabentry, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
 
static void autovacuum_do_vac_analyze (autovac_table *tab, BufferAccessStrategy bstrategy)
 
static void autovac_report_activity (autovac_table *tab)
 
static void autovac_report_workitem (AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
 
bool AutoVacuumingActive (void)
 
bool AutoVacuumRequestWork (AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
 
void autovac_init (void)
 
bool IsAutoVacuumLauncherProcess (void)
 
bool IsAutoVacuumWorkerProcess (void)
 
Size AutoVacuumShmemSize (void)
 
void AutoVacuumShmemInit (void)
 
static void autovac_refresh_stats (void)
 

Variables

bool autovacuum_start_daemon = false
 
int autovacuum_max_workers
 
int autovacuum_work_mem = -1
 
int autovacuum_naptime
 
int autovacuum_vac_thresh
 
double autovacuum_vac_scale
 
int autovacuum_vac_ins_thresh
 
double autovacuum_vac_ins_scale
 
int autovacuum_anl_thresh
 
double autovacuum_anl_scale
 
int autovacuum_freeze_max_age
 
int autovacuum_multixact_freeze_max_age
 
double autovacuum_vac_cost_delay
 
int autovacuum_vac_cost_limit
 
int Log_autovacuum_min_duration = 600000
 
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.

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 136 of file autovacuum.c.

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

Definition at line 264 of file autovacuum.c.

◆ STATS_READ_DELAY

#define STATS_READ_DELAY   1000

Definition at line 133 of file autovacuum.c.

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:242
@ AutoVacRebalance
Definition: autovacuum.c:244
@ AutoVacForkFailed
Definition: autovacuum.c:243
@ AutoVacNumSignals
Definition: autovacuum.c:245

Function Documentation

◆ autovac_balance_cost()

static void autovac_balance_cost ( void  )
static

Definition at line 1800 of file autovacuum.c.

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

References autovacuum_vac_cost_delay, autovacuum_vac_cost_limit, AutoVacuumShmem, 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().

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3391 of file autovacuum.c.

3392 {
3394  ereport(WARNING,
3395  (errmsg("autovacuum not started because of misconfiguration"),
3396  errhint("Enable the \"track_counts\" option.")));
3397 }
bool autovacuum_start_daemon
Definition: autovacuum.c:114
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define WARNING
Definition: elog.h:30
#define ereport(elevel,...)
Definition: elog.h:143
bool pgstat_track_counts
Definition: pgstat.c:111

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

Referenced by PostmasterMain().

◆ autovac_refresh_stats()

static void autovac_refresh_stats ( void  )
static

Definition at line 3489 of file autovacuum.c.

3490 {
3492  {
3493  static TimestampTz last_read = 0;
3494  TimestampTz current_time;
3495 
3496  current_time = GetCurrentTimestamp();
3497 
3498  if (!TimestampDifferenceExceeds(last_read, current_time,
3500  return;
3501 
3502  last_read = current_time;
3503  }
3504 
3506 }
#define STATS_READ_DELAY
Definition: autovacuum.c:133
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3405
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5149

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

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

◆ autovac_report_activity()

static void autovac_report_activity ( autovac_table tab)
static

Definition at line 3262 of file autovacuum.c.

3263 {
3264 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3265  char activity[MAX_AUTOVAC_ACTIV_LEN];
3266  int len;
3267 
3268  /* Report the command and possible options */
3269  if (tab->at_params.options & VACOPT_VACUUM)
3270  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3271  "autovacuum: VACUUM%s",
3272  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3273  else
3274  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3275  "autovacuum: ANALYZE");
3276 
3277  /*
3278  * Report the qualified name of the relation.
3279  */
3280  len = strlen(activity);
3281 
3282  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3283  " %s.%s%s", tab->at_nspname, tab->at_relname,
3284  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3285 
3286  /* Set statement_timestamp() to current time for pg_stat_activity */
3288 
3290 }
#define MAX_AUTOVAC_ACTIV_LEN
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
const void size_t len
#define snprintf
Definition: port.h:225
bits32 options
Definition: vacuum.h:216
bool is_wraparound
Definition: vacuum.h:223
char * at_nspname
Definition: autovacuum.c:198
char * at_relname
Definition: autovacuum.c:197
VacuumParams at_params
Definition: autovacuum.c:192
#define VACOPT_VACUUM
Definition: vacuum.h:183
#define VACOPT_ANALYZE
Definition: vacuum.h:184
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:885

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

Referenced by autovacuum_do_vac_analyze().

◆ autovac_report_workitem()

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

Definition at line 3297 of file autovacuum.c.

3299 {
3300  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3301  char blk[12 + 2];
3302  int len;
3303 
3304  switch (workitem->avw_type)
3305  {
3307  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3308  "autovacuum: BRIN summarize");
3309  break;
3310  }
3311 
3312  /*
3313  * Report the qualified name of the relation, and the block number if any
3314  */
3315  len = strlen(activity);
3316 
3317  if (BlockNumberIsValid(workitem->avw_blockNumber))
3318  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3319  else
3320  blk[0] = '\0';
3321 
3322  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3323  " %s.%s%s", nspname, relname, blk);
3324 
3325  /* Set statement_timestamp() to current time for pg_stat_activity */
3327 
3329 }
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
NameData relname
Definition: pg_class.h:38
BlockNumber avw_blockNumber
Definition: autovacuum.c:261
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:256

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

Referenced by perform_work_item().

◆ AutoVacLauncherMain()

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

Definition at line 436 of file autovacuum.c.

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

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

◆ AutoVacLauncherShutdown()

static void AutoVacLauncherShutdown ( void  )
static

Definition at line 316 of file autovacuum.c.

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

Referenced by AutoVacLauncherMain(), and HandleAutoVacLauncherInterrupts().

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3233 of file autovacuum.c.

3234 {
3235  RangeVar *rangevar;
3236  VacuumRelation *rel;
3237  List *rel_list;
3238 
3239  /* Let pgstat know what we're doing */
3241 
3242  /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3243  rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3244  rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3245  rel_list = list_make1(rel);
3246 
3247  vacuum(rel_list, &tab->at_params, bstrategy, true);
3248 }
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3262
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:811
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
#define NIL
Definition: pg_list.h:65
#define list_make1(x1)
Definition: pg_list.h:206
Definition: pg_list.h:51
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:298

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().

◆ AutoVacuumingActive()

bool AutoVacuumingActive ( void  )

Definition at line 3337 of file autovacuum.c.

3338 {
3340  return false;
3341  return true;
3342 }

References autovacuum_start_daemon, and pgstat_track_counts.

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

◆ AutoVacuumRequestWork()

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

Definition at line 3349 of file autovacuum.c.

3351 {
3352  int i;
3353  bool result = false;
3354 
3355  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3356 
3357  /*
3358  * Locate an unused work item and fill it with the given data.
3359  */
3360  for (i = 0; i < NUM_WORKITEMS; i++)
3361  {
3363 
3364  if (workitem->avw_used)
3365  continue;
3366 
3367  workitem->avw_used = true;
3368  workitem->avw_active = false;
3369  workitem->avw_type = type;
3370  workitem->avw_database = MyDatabaseId;
3371  workitem->avw_relation = relationId;
3372  workitem->avw_blockNumber = blkno;
3373  result = true;
3374 
3375  /* done */
3376  break;
3377  }
3378 
3379  LWLockRelease(AutovacuumLock);
3380 
3381  return result;
3382 }
#define NUM_WORKITEMS
Definition: autovacuum.c:264
Oid MyDatabaseId
Definition: globals.c:88
int i
Definition: isn.c:73
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:289

References AutoVacuumShmem, 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().

◆ AutoVacuumShmemInit()

void AutoVacuumShmemInit ( void  )

Definition at line 3441 of file autovacuum.c.

3442 {
3443  bool found;
3444 
3446  ShmemInitStruct("AutoVacuum Data",
3448  &found);
3449 
3450  if (!IsUnderPostmaster)
3451  {
3452  WorkerInfo worker;
3453  int i;
3454 
3455  Assert(!found);
3456 
3461  memset(AutoVacuumShmem->av_workItems, 0,
3462  sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3463 
3464  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3465  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3466 
3467  /* initialize the WorkerInfo free list */
3468  for (i = 0; i < autovacuum_max_workers; i++)
3470  &worker[i].wi_links);
3471  }
3472  else
3473  Assert(found);
3474 }
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3422
int autovacuum_max_workers
Definition: autovacuum.c:115
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:234
#define MAXALIGN(LEN)
Definition: c.h:757
bool IsUnderPostmaster
Definition: globals.c:112
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396

References Assert(), autovacuum_max_workers, AutoVacuumShmem, 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().

◆ AutoVacuumShmemSize()

Size AutoVacuumShmemSize ( void  )

Definition at line 3422 of file autovacuum.c.

3423 {
3424  Size size;
3425 
3426  /*
3427  * Need the fixed struct and the array of WorkerInfoData.
3428  */
3429  size = sizeof(AutoVacuumShmemStruct);
3430  size = MAXALIGN(size);
3432  sizeof(WorkerInfoData)));
3433  return size;
3434 }
size_t Size
Definition: c.h:540
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

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

Referenced by AutoVacuumShmemInit(), and CalculateShmemSize().

◆ AutoVacuumUpdateDelay()

void AutoVacuumUpdateDelay ( void  )

Definition at line 1784 of file autovacuum.c.

1785 {
1786  if (MyWorkerInfo)
1787  {
1790  }
1791 }
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:302

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

Referenced by do_autovacuum(), and vacuum_delay_point().

◆ AutoVacWorkerFailed()

void AutoVacWorkerFailed ( void  )

Definition at line 1421 of file autovacuum.c.

1422 {
1424 }

References AutoVacForkFailed, AutoVacuumShmem, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

◆ AutoVacWorkerMain()

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

Definition at line 1519 of file autovacuum.c.

1520 {
1521  sigjmp_buf local_sigjmp_buf;
1522  Oid dbid;
1523 
1524  am_autovacuum_worker = true;
1525 
1527  init_ps_display(NULL);
1528 
1530 
1531  /*
1532  * Set up signal handlers. We operate on databases much like a regular
1533  * backend, so we use the same signal handling. See equivalent code in
1534  * tcop/postgres.c.
1535  */
1537 
1538  /*
1539  * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1540  * means abort and exit cleanly, and SIGQUIT means abandon ship.
1541  */
1543  pqsignal(SIGTERM, die);
1544  /* SIGQUIT handler was already set up by InitPostmasterChild */
1545 
1546  InitializeTimeouts(); /* establishes SIGALRM handler */
1547 
1553 
1554  /*
1555  * Create a per-backend PGPROC struct in shared memory, except in the
1556  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
1557  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
1558  * had to do some stuff with LWLocks).
1559  */
1560 #ifndef EXEC_BACKEND
1561  InitProcess();
1562 #endif
1563 
1564  /* Early initialization */
1565  BaseInit();
1566 
1567  /*
1568  * If an exception is encountered, processing resumes here.
1569  *
1570  * Unlike most auxiliary processes, we don't attempt to continue
1571  * processing after an error; we just clean up and exit. The autovac
1572  * launcher is responsible for spawning another worker later.
1573  *
1574  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
1575  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
1576  * signals other than SIGQUIT will be blocked until we exit. It might
1577  * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
1578  * it is not since InterruptPending might be set already.
1579  */
1580  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1581  {
1582  /* since not using PG_TRY, must reset error stack by hand */
1583  error_context_stack = NULL;
1584 
1585  /* Prevents interrupts while cleaning up */
1586  HOLD_INTERRUPTS();
1587 
1588  /* Report the error to the server log */
1589  EmitErrorReport();
1590 
1591  /*
1592  * We can now go away. Note that because we called InitProcess, a
1593  * callback was registered to do ProcKill, which will clean up
1594  * necessary state.
1595  */
1596  proc_exit(0);
1597  }
1598 
1599  /* We can now handle ereport(ERROR) */
1600  PG_exception_stack = &local_sigjmp_buf;
1601 
1603 
1604  /*
1605  * Set always-secure search path, so malicious users can't redirect user
1606  * code (e.g. pg_index.indexprs). (That code runs in a
1607  * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1608  * take control of the entire autovacuum worker in any case.)
1609  */
1610  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1611 
1612  /*
1613  * Force zero_damaged_pages OFF in the autovac process, even if it is set
1614  * in postgresql.conf. We don't really want such a dangerous option being
1615  * applied non-interactively.
1616  */
1617  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1618 
1619  /*
1620  * Force settable timeouts off to avoid letting these settings prevent
1621  * regular maintenance from being executed.
1622  */
1623  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1624  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1625  SetConfigOption("idle_in_transaction_session_timeout", "0",
1627 
1628  /*
1629  * Force default_transaction_isolation to READ COMMITTED. We don't want
1630  * to pay the overhead of serializable mode, nor add any risk of causing
1631  * deadlocks or delaying other transactions.
1632  */
1633  SetConfigOption("default_transaction_isolation", "read committed",
1635 
1636  /*
1637  * Force synchronous replication off to allow regular maintenance even if
1638  * we are waiting for standbys to connect. This is important to ensure we
1639  * aren't blocked from performing anti-wraparound tasks.
1640  */
1642  SetConfigOption("synchronous_commit", "local",
1644 
1645  /*
1646  * Get the info about the database we're going to work on.
1647  */
1648  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1649 
1650  /*
1651  * beware of startingWorker being INVALID; this should normally not
1652  * happen, but if a worker fails after forking and before this, the
1653  * launcher might have decided to remove it from the queue and start
1654  * again.
1655  */
1656  if (AutoVacuumShmem->av_startingWorker != NULL)
1657  {
1659  dbid = MyWorkerInfo->wi_dboid;
1661 
1662  /* insert into the running list */
1665 
1666  /*
1667  * remove from the "starting" pointer, so that the launcher can start
1668  * a new worker if required
1669  */
1671  LWLockRelease(AutovacuumLock);
1672 
1674 
1675  /* wake up the launcher */
1676  if (AutoVacuumShmem->av_launcherpid != 0)
1678  }
1679  else
1680  {
1681  /* no worker entry for me, go away */
1682  elog(WARNING, "autovacuum worker started without a worker entry");
1683  dbid = InvalidOid;
1684  LWLockRelease(AutovacuumLock);
1685  }
1686 
1687  if (OidIsValid(dbid))
1688  {
1689  char dbname[NAMEDATALEN];
1690 
1691  /*
1692  * Report autovac startup to the stats collector. We deliberately do
1693  * this before InitPostgres, so that the last_autovac_time will get
1694  * updated even if the connection attempt fails. This is to prevent
1695  * autovac from getting "stuck" repeatedly selecting an unopenable
1696  * database, rather than making any progress on stuff it can connect
1697  * to.
1698  */
1699  pgstat_report_autovac(dbid);
1700 
1701  /*
1702  * Connect to the selected database
1703  *
1704  * Note: if we have selected a just-deleted database (due to using
1705  * stale stats info), we'll fail and exit here.
1706  */
1707  InitPostgres(NULL, dbid, NULL, InvalidOid, dbname, false);
1710  ereport(DEBUG1,
1711  (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1712 
1713  if (PostAuthDelay)
1714  pg_usleep(PostAuthDelay * 1000000L);
1715 
1716  /* And do an appropriate amount of work */
1719  do_autovacuum();
1720  }
1721 
1722  /*
1723  * The launcher will be notified of my death in ProcKill, *if* we managed
1724  * to get a worker slot at all
1725  */
1726 
1727  /* All done, go away */
1728  proc_exit(0);
1729 }
static void FreeWorkerInfo(int code, Datum arg)
Definition: autovacuum.c:1735
static TransactionId recentXid
Definition: autovacuum.c:147
static void do_autovacuum(void)
Definition: autovacuum.c:1958
static MultiXactId recentMulti
Definition: autovacuum.c:148
static bool am_autovacuum_worker
Definition: autovacuum.c:141
#define OidIsValid(objectId)
Definition: c.h:710
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:327
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:723
#define NAMEDATALEN
#define die(msg)
Definition: pg_test_fsync.c:98
void pgstat_report_autovac(Oid dboid)
Definition: pgstat.c:1629
unsigned int Oid
Definition: postgres_ext.h:31
void set_ps_display(const char *activity)
Definition: ps_status.c:349
PGPROC * MyProc
Definition: proc.c:68
char * dbname
Definition: streamutil.c:51
static TransactionId ReadNextTransactionId(void)
Definition: transam.h:316
#define kill(pid, sig)
Definition: win32_port.h:464
int synchronous_commit
Definition: xact.c:85
@ SYNCHRONOUS_COMMIT_LOCAL_FLUSH
Definition: xact.h:71

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

Referenced by StartAutoVacWorker().

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1428 of file autovacuum.c.

1429 {
1430  int save_errno = errno;
1431 
1432  got_SIGUSR2 = true;
1433  SetLatch(MyLatch);
1434 
1435  errno = save_errno;
1436 }
void SetLatch(Latch *latch)
Definition: latch.c:567

References got_SIGUSR2, MyLatch, and SetLatch().

Referenced by AutoVacLauncherMain().

◆ db_comparator()

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

Definition at line 1134 of file autovacuum.c.

1135 {
1136  if (((const avl_dbase *) a)->adl_score == ((const avl_dbase *) b)->adl_score)
1137  return 0;
1138  else
1139  return (((const avl_dbase *) a)->adl_score < ((const avl_dbase *) b)->adl_score) ? 1 : -1;
1140 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69

References a, and b.

Referenced by rebuild_database_list().

◆ do_autovacuum()

static void do_autovacuum ( void  )
static

Definition at line 1958 of file autovacuum.c.

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

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(), AutovacMemCxt, autovacuum_do_vac_analyze(), AutoVacuumShmem, 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(), MultiXactMemberFreezeThreshold(), MyDatabaseId, MyWorkerInfo, 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().

◆ do_start_worker()

static Oid do_start_worker ( void  )
static

Definition at line 1154 of file autovacuum.c.

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

References avl_dbase::adl_datid, avl_dbase::adl_next_worker, 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, AutoVacuumShmem, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_startingWorker, dlist_iter::cur, CurrentMemoryContext, DatabaseList, dblist, dlist_container, dlist_is_empty(), dlist_pop_head_node(), dlist_reverse_foreach, FirstMultiXactId, FirstNormalTransactionId, get_database_list(), GetCurrentTimestamp(), InvalidOid, PgStat_StatDBEntry::last_autovac_time, lfirst, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextDelete(), MemoryContextSwitchTo(), MultiXactIdPrecedes(), MultiXactMemberFreezeThreshold(), pgstat_fetch_stat_dbentry(), PMSIGNAL_START_AUTOVAC_WORKER, ReadNextMultiXactId(), ReadNextTransactionId(), rebuild_database_list(), recentMulti, recentXid, SendPostmasterSignal(), TimestampDifferenceExceeds(), TransactionIdPrecedes(), WorkerInfoData::wi_dboid, WorkerInfoData::wi_launchtime, and WorkerInfoData::wi_proc.

Referenced by AutoVacLauncherMain(), and launch_worker().

◆ extract_autovac_opts()

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

Definition at line 2751 of file autovacuum.c.

2752 {
2753  bytea *relopts;
2754  AutoVacOpts *av;
2755 
2756  Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2757  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2758  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2759 
2760  relopts = extractRelOptions(tup, pg_class_desc, NULL);
2761  if (relopts == NULL)
2762  return NULL;
2763 
2764  av = palloc(sizeof(AutoVacOpts));
2765  memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2766  pfree(relopts);
2767 
2768  return av;
2769 }
void * palloc(Size size)
Definition: mcxt.c:1062
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
Definition: reloptions.c:1374
Definition: c.h:622

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

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ FreeWorkerInfo()

static void FreeWorkerInfo ( int  code,
Datum  arg 
)
static

Definition at line 1735 of file autovacuum.c.

1736 {
1737  if (MyWorkerInfo != NULL)
1738  {
1739  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1740 
1741  /*
1742  * Wake the launcher up so that he can launch a new worker immediately
1743  * if required. We only save the launcher's PID in local memory here;
1744  * the actual signal will be sent when the PGPROC is recycled. Note
1745  * that we always do this, so that the launcher can rebalance the cost
1746  * limit setting of the remaining workers.
1747  *
1748  * We somewhat ignore the risk that the launcher changes its PID
1749  * between us reading it and the actual kill; we expect ProcKill to be
1750  * called shortly after us, and we assume that PIDs are not reused too
1751  * quickly after a process exits.
1752  */
1754 
1758  MyWorkerInfo->wi_sharedrel = false;
1759  MyWorkerInfo->wi_proc = NULL;
1761  MyWorkerInfo->wi_dobalance = false;
1767  /* not mine anymore */
1768  MyWorkerInfo = NULL;
1769 
1770  /*
1771  * now that we're inactive, cause a rebalancing of the surviving
1772  * workers
1773  */
1775  LWLockRelease(AutovacuumLock);
1776  }
1777 }
int AutovacuumLauncherPid
Definition: autovacuum.c:305
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358

References AutoVacRebalance, AutovacuumLauncherPid, AutoVacuumShmem, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_signal, dlist_delete(), dlist_push_head(), InvalidOid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyWorkerInfo, 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().

◆ get_database_list()

static List* get_database_list ( void  )
static

Definition at line 1888 of file autovacuum.c.

1889 {
1890  List *dblist = NIL;
1891  Relation rel;
1892  TableScanDesc scan;
1893  HeapTuple tup;
1894  MemoryContext resultcxt;
1895 
1896  /* This is the context that we will allocate our output data in */
1897  resultcxt = CurrentMemoryContext;
1898 
1899  /*
1900  * Start a transaction so we can access pg_database, and get a snapshot.
1901  * We don't have a use for the snapshot itself, but we're interested in
1902  * the secondary effect that it sets RecentGlobalXmin. (This is critical
1903  * for anything that reads heap pages, because HOT may decide to prune
1904  * them even if the process doesn't attempt to modify any tuples.)
1905  *
1906  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
1907  * not pushed/active does not reliably prevent HOT pruning (->xmin could
1908  * e.g. be cleared when cache invalidations are processed).
1909  */
1911  (void) GetTransactionSnapshot();
1912 
1913  rel = table_open(DatabaseRelationId, AccessShareLock);
1914  scan = table_beginscan_catalog(rel, 0, NULL);
1915 
1916  while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1917  {
1918  Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1919  avw_dbase *avdb;
1920  MemoryContext oldcxt;
1921 
1922  /*
1923  * Allocate our results in the caller's context, not the
1924  * transaction's. We do this inside the loop, and restore the original
1925  * context at the end, so that leaky things like heap_getnext() are
1926  * not called in a potentially long-lived context.
1927  */
1928  oldcxt = MemoryContextSwitchTo(resultcxt);
1929 
1930  avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1931 
1932  avdb->adw_datid = pgdatabase->oid;
1933  avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1934  avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1935  avdb->adw_minmulti = pgdatabase->datminmxid;
1936  /* this gets set later: */
1937  avdb->adw_entry = NULL;
1938 
1939  dblist = lappend(dblist, avdb);
1940  MemoryContextSwitchTo(oldcxt);
1941  }
1942 
1943  table_endscan(scan);
1945 
1947 
1948  return dblist;
1949 }
List * lappend(List *list, void *datum)
Definition: list.c:336
char * pstrdup(const char *in)
Definition: mcxt.c:1299
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
char * adw_name
Definition: autovacuum.c:172

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().

◆ 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 2777 of file autovacuum.c.

2779 {
2780  PgStat_StatTabEntry *tabentry = NULL;
2781 
2782  if (isshared)
2783  {
2784  if (PointerIsValid(shared))
2785  tabentry = hash_search(shared->tables, &relid,
2786  HASH_FIND, NULL);
2787  }
2788  else if (PointerIsValid(dbentry))
2789  tabentry = hash_search(dbentry->tables, &relid,
2790  HASH_FIND, NULL);
2791 
2792  return tabentry;
2793 }
#define PointerIsValid(pointer)
Definition: c.h:698

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

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

◆ HandleAutoVacLauncherInterrupts()

static void HandleAutoVacLauncherInterrupts ( void  )
static

Definition at line 812 of file autovacuum.c.

813 {
814  /* the normal shutdown case */
817 
819  {
820  ConfigReloadPending = false;
822 
823  /* shutdown requested in config file? */
824  if (!AutoVacuumingActive())
826 
827  /* rebalance in case the default cost parameters changed */
828  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
830  LWLockRelease(AutovacuumLock);
831 
832  /* rebuild the list in case the naptime changed */
834  }
835 
836  /* Process barrier events */
839 
840  /* Perform logging of memory contexts of this process */
843 
844  /* Process sinval catchup interrupts that happened while sleeping */
846 }
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1041
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176

References autovac_balance_cost(), AutoVacLauncherShutdown(), AutoVacuumingActive(), ConfigReloadPending, InvalidOid, LogMemoryContextPending, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), PGC_SIGHUP, ProcessCatchupInterrupt(), ProcessConfigFile(), ProcessLogMemoryContextInterrupt(), ProcessProcSignalBarrier(), ProcSignalBarrierPending, rebuild_database_list(), and ShutdownRequestPending.

Referenced by AutoVacLauncherMain().

◆ IsAutoVacuumLauncherProcess()

bool IsAutoVacuumLauncherProcess ( void  )

Definition at line 3405 of file autovacuum.c.

3406 {
3407  return am_autovacuum_launcher;
3408 }

References am_autovacuum_launcher.

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

◆ IsAutoVacuumWorkerProcess()

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1369 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain().

◆ launcher_determine_sleep()

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

Definition at line 869 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain().

◆ perform_work_item()

static void perform_work_item ( AutoVacuumWorkItem workitem)
static

Definition at line 2640 of file autovacuum.c.

2641 {
2642  char *cur_datname = NULL;
2643  char *cur_nspname = NULL;
2644  char *cur_relname = NULL;
2645 
2646  /*
2647  * Note we do not store table info in MyWorkerInfo, since this is not
2648  * vacuuming proper.
2649  */
2650 
2651  /*
2652  * Save the relation name for a possible error message, to avoid a catalog
2653  * lookup in case of an error. If any of these return NULL, then the
2654  * relation has been dropped since last we checked; skip it.
2655  */
2657 
2658  cur_relname = get_rel_name(workitem->avw_relation);
2659  cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2660  cur_datname = get_database_name(MyDatabaseId);
2661  if (!cur_relname || !cur_nspname || !cur_datname)
2662  goto deleted2;
2663 
2664  autovac_report_workitem(workitem, cur_nspname, cur_relname);
2665 
2666  /* clean up memory before each work item */
2668 
2669  /*
2670  * We will abort the current work item if something errors out, and
2671  * continue with the next one; in particular, this happens if we are
2672  * interrupted with SIGINT. Note that this means that the work item list
2673  * can be lossy.
2674  */
2675  PG_TRY();
2676  {
2677  /* Use PortalContext for any per-work-item allocations */
2679 
2680  /* have at it */
2681  switch (workitem->avw_type)
2682  {
2685  ObjectIdGetDatum(workitem->avw_relation),
2686  Int64GetDatum((int64) workitem->avw_blockNumber));
2687  break;
2688  default:
2689  elog(WARNING, "unrecognized work item found: type %d",
2690  workitem->avw_type);
2691  break;
2692  }
2693 
2694  /*
2695  * Clear a possible query-cancel signal, to avoid a late reaction to
2696  * an automatically-sent signal because of vacuuming the current table
2697  * (we're done with it, so it would make no sense to cancel at this
2698  * point.)
2699  */
2700  QueryCancelPending = false;
2701  }
2702  PG_CATCH();
2703  {
2704  /*
2705  * Abort the transaction, start a new one, and proceed with the next
2706  * table in our list.
2707  */
2708  HOLD_INTERRUPTS();
2709  errcontext("processing work entry for relation \"%s.%s.%s\"",
2710  cur_datname, cur_nspname, cur_relname);
2711  EmitErrorReport();
2712 
2713  /* this resets ProcGlobal->statusFlags[i] too */
2715  FlushErrorState();
2717 
2718  /* restart our transaction for the following operations */
2721  }
2722  PG_END_TRY();
2723 
2724  /* Make sure we're back in AutovacMemCxt */
2726 
2727  /* We intentionally do not set did_vacuum here */
2728 
2729  /* be tidy */
2730 deleted2:
2731  if (cur_datname)
2732  pfree(cur_datname);
2733  if (cur_nspname)
2734  pfree(cur_nspname);
2735  if (cur_relname)
2736  pfree(cur_relname);
2737 }
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
Definition: autovacuum.c:3297
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:1003
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1697
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:633

References AbortOutOfAnyTransaction(), Assert(), autovac_report_workitem(), AutovacMemCxt, 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().

◆ rebuild_database_list()

static void rebuild_database_list ( Oid  newdb)
static

Definition at line 953 of file autovacuum.c.

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

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(), AutovacMemCxt, autovacuum_naptime, dlist_iter::cur, DatabaseList, DatabaseListCxt, 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().

◆ recheck_relation_needs_vacanalyze()

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

Definition at line 2995 of file autovacuum.c.

3002 {
3003  PgStat_StatTabEntry *tabentry;
3004  PgStat_StatDBEntry *shared = NULL;
3005  PgStat_StatDBEntry *dbentry = NULL;
3006 
3007  if (classForm->relisshared)
3009  else
3011 
3012  /* fetch the pgstat table entry */
3013  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
3014  shared, dbentry);
3015 
3016  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
3017  effective_multixact_freeze_max_age,
3018  dovacuum, doanalyze, wraparound);
3019 
3020  /* ignore ANALYZE for toast tables */
3021  if (classForm->relkind == RELKIND_TOASTVALUE)
3022  *doanalyze = false;
3023 }

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

Referenced by table_recheck_autovac().

◆ 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 3063 of file autovacuum.c.

3072 {
3073  bool force_vacuum;
3074  bool av_enabled;
3075  float4 reltuples; /* pg_class.reltuples */
3076 
3077  /* constants from reloptions or GUC variables */
3078  int vac_base_thresh,
3079  vac_ins_base_thresh,
3080  anl_base_thresh;
3081  float4 vac_scale_factor,
3082  vac_ins_scale_factor,
3083  anl_scale_factor;
3084 
3085  /* thresholds calculated from above constants */
3086  float4 vacthresh,
3087  vacinsthresh,
3088  anlthresh;
3089 
3090  /* number of vacuum (resp. analyze) tuples at this time */
3091  float4 vactuples,
3092  instuples,
3093  anltuples;
3094 
3095  /* freeze parameters */
3096  int freeze_max_age;
3097  int multixact_freeze_max_age;
3098  TransactionId xidForceLimit;
3099  MultiXactId multiForceLimit;
3100 
3101  AssertArg(classForm != NULL);
3102  AssertArg(OidIsValid(relid));
3103 
3104  /*
3105  * Determine vacuum/analyze equation parameters. We have two possible
3106  * sources: the passed reloptions (which could be a main table or a toast
3107  * table), or the autovacuum GUC variables.
3108  */
3109 
3110  /* -1 in autovac setting means use plain vacuum_scale_factor */
3111  vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3112  ? relopts->vacuum_scale_factor
3114 
3115  vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3116  ? relopts->vacuum_threshold
3118 
3119  vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3120  ? relopts->vacuum_ins_scale_factor
3122 
3123  /* -1 is used to disable insert vacuums */
3124  vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3125  ? relopts->vacuum_ins_threshold
3127 
3128  anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3129  ? relopts->analyze_scale_factor
3131 
3132  anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3133  ? relopts->analyze_threshold
3135 
3136  freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3139 
3140  multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3141  ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3142  : effective_multixact_freeze_max_age;
3143 
3144  av_enabled = (relopts ? relopts->enabled : true);
3145 
3146  /* Force vacuum if table is at risk of wraparound */
3147  xidForceLimit = recentXid - freeze_max_age;
3148  if (xidForceLimit < FirstNormalTransactionId)
3149  xidForceLimit -= FirstNormalTransactionId;
3150  force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
3151  TransactionIdPrecedes(classForm->relfrozenxid,
3152  xidForceLimit));
3153  if (!force_vacuum)
3154  {
3155  multiForceLimit = recentMulti - multixact_freeze_max_age;
3156  if (multiForceLimit < FirstMultiXactId)
3157  multiForceLimit -= FirstMultiXactId;
3158  force_vacuum = MultiXactIdIsValid(classForm->relminmxid) &&
3159  MultiXactIdPrecedes(classForm->relminmxid, multiForceLimit);
3160  }
3161  *wraparound = force_vacuum;
3162 
3163  /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3164  if (!av_enabled && !force_vacuum)
3165  {
3166  *doanalyze = false;
3167  *dovacuum = false;
3168  return;
3169  }
3170 
3171  /*
3172  * If we found the table in the stats hash, and autovacuum is currently
3173  * enabled, make a threshold-based decision whether to vacuum and/or
3174  * analyze. If autovacuum is currently disabled, we must be here for
3175  * anti-wraparound vacuuming only, so don't vacuum (or analyze) anything
3176  * that's not being forced.
3177  */
3178  if (PointerIsValid(tabentry) && AutoVacuumingActive())
3179  {
3180  reltuples = classForm->reltuples;
3181  vactuples = tabentry->n_dead_tuples;
3182  instuples = tabentry->inserts_since_vacuum;
3183  anltuples = tabentry->changes_since_analyze;
3184 
3185  /* If the table hasn't yet been vacuumed, take reltuples as zero */
3186  if (reltuples < 0)
3187  reltuples = 0;
3188 
3189  vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3190  vacinsthresh = (float4) vac_ins_base_thresh + vac_ins_scale_factor * reltuples;
3191  anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3192 
3193  /*
3194  * Note that we don't need to take special consideration for stat
3195  * reset, because if that happens, the last vacuum and analyze counts
3196  * will be reset too.
3197  */
3198  if (vac_ins_base_thresh >= 0)
3199  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3200  NameStr(classForm->relname),
3201  vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3202  else
3203  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3204  NameStr(classForm->relname),
3205  vactuples, vacthresh, anltuples, anlthresh);
3206 
3207  /* Determine if this table needs vacuum or analyze. */
3208  *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3209  (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3210  *doanalyze = (anltuples > anlthresh);
3211  }
3212  else
3213  {
3214  /*
3215  * Skip a table not found in stat hash, unless we have to force vacuum
3216  * for anti-wrap purposes. If it's not acted upon, there's no need to
3217  * vacuum it.
3218  */
3219  *dovacuum = force_vacuum;
3220  *doanalyze = false;
3221  }
3222 
3223  /* ANALYZE refuses to work with pg_statistic */
3224  if (relid == StatisticRelationId)
3225  *doanalyze = false;
3226 }
double autovacuum_vac_scale
Definition: autovacuum.c:119
int autovacuum_anl_thresh
Definition: autovacuum.c:122
int autovacuum_vac_thresh
Definition: autovacuum.c:118
double autovacuum_anl_scale
Definition: autovacuum.c:123
int autovacuum_vac_ins_thresh
Definition: autovacuum.c:120
double autovacuum_vac_ins_scale
Definition: autovacuum.c:121
float float4
Definition: c.h:564
#define AssertArg(condition)
Definition: c.h:806
#define DEBUG3
Definition: elog.h:22
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
int vacuum_ins_threshold
Definition: rel.h:295
int multixact_freeze_max_age
Definition: rel.h:302
float8 vacuum_scale_factor
Definition: rel.h:306
int analyze_threshold
Definition: rel.h:296
float8 vacuum_ins_scale_factor
Definition: rel.h:307
bool enabled
Definition: rel.h:293
int freeze_max_age
Definition: rel.h:299
int vacuum_threshold
Definition: rel.h:294
float8 analyze_scale_factor
Definition: rel.h:308
PgStat_Counter changes_since_analyze
Definition: pgstat.h:859
PgStat_Counter inserts_since_vacuum
Definition: pgstat.h:860
PgStat_Counter n_dead_tuples
Definition: pgstat.h:858
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

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

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

◆ StartAutoVacWorker()

int StartAutoVacWorker ( void  )

Definition at line 1481 of file autovacuum.c.

1482 {
1483  pid_t worker_pid;
1484 
1485 #ifdef EXEC_BACKEND
1486  switch ((worker_pid = avworker_forkexec()))
1487 #else
1488  switch ((worker_pid = fork_process()))
1489 #endif
1490  {
1491  case -1:
1492  ereport(LOG,
1493  (errmsg("could not fork autovacuum worker process: %m")));
1494  return 0;
1495 
1496 #ifndef EXEC_BACKEND
1497  case 0:
1498  /* in postmaster child ... */
1500 
1501  /* Close the postmaster's sockets */
1502  ClosePostmasterPorts(false);
1503 
1504  AutoVacWorkerMain(0, NULL);
1505  break;
1506 #endif
1507  default:
1508  return (int) worker_pid;
1509  }
1510 
1511  /* shouldn't get here */
1512  return 0;
1513 }
NON_EXEC_STATIC void AutoVacWorkerMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: autovacuum.c:1519

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

Referenced by StartAutovacuumWorker().

◆ 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 2804 of file autovacuum.c.

2807 {
2808  Form_pg_class classForm;
2809  HeapTuple classTup;
2810  bool dovacuum;
2811  bool doanalyze;
2812  autovac_table *tab = NULL;
2813  bool wraparound;
2814  AutoVacOpts *avopts;
2815  static bool reuse_stats = false;
2816 
2817  /* fetch the relation's relcache entry */
2818  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2819  if (!HeapTupleIsValid(classTup))
2820  return NULL;
2821  classForm = (Form_pg_class) GETSTRUCT(classTup);
2822 
2823  /*
2824  * Get the applicable reloptions. If it is a TOAST table, try to get the
2825  * main table reloptions if the toast table itself doesn't have.
2826  */
2827  avopts = extract_autovac_opts(classTup, pg_class_desc);
2828  if (classForm->relkind == RELKIND_TOASTVALUE &&
2829  avopts == NULL && table_toast_map != NULL)
2830  {
2831  av_relation *hentry;
2832  bool found;
2833 
2834  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2835  if (found && hentry->ar_hasrelopts)
2836  avopts = &hentry->ar_reloptions;
2837  }
2838 
2839  /*
2840  * Reuse the stats to recheck whether a relation needs to be vacuumed or
2841  * analyzed if it was reloaded before and has not been cleared yet. This
2842  * is necessary to avoid frequent refresh of stats, especially when there
2843  * are very large number of relations and the refresh can cause lots of
2844  * overhead.
2845  *
2846  * If we determined that a relation needs to be vacuumed or analyzed,
2847  * based on the old stats, we refresh stats and recheck the necessity
2848  * again. Because a relation may have already been vacuumed or analyzed by
2849  * someone since the last reload of stats.
2850  */
2851  if (reuse_stats)
2852  {
2853  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2854  effective_multixact_freeze_max_age,
2855  &dovacuum, &doanalyze, &wraparound);
2856 
2857  /* Quick exit if a relation doesn't need to be vacuumed or analyzed */
2858  if (!doanalyze && !dovacuum)
2859  {
2860  heap_freetuple(classTup);
2861  return NULL;
2862  }
2863  }
2864 
2865  /* Use fresh stats and recheck again */
2867 
2868  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2869  effective_multixact_freeze_max_age,
2870  &dovacuum, &doanalyze, &wraparound);
2871 
2872  /* OK, it needs something done */
2873  if (doanalyze || dovacuum)
2874  {
2875  int freeze_min_age;
2876  int freeze_table_age;
2877  int multixact_freeze_min_age;
2878  int multixact_freeze_table_age;
2879  int vac_cost_limit;
2880  double vac_cost_delay;
2881  int log_min_duration;
2882 
2883  /*
2884  * Calculate the vacuum cost parameters and the freeze ages. If there
2885  * are options set in pg_class.reloptions, use them; in the case of a
2886  * toast table, try the main table too. Otherwise use the GUC
2887  * defaults, autovacuum's own first and plain vacuum second.
2888  */
2889 
2890  /* -1 in autovac setting means use plain vacuum_cost_delay */
2891  vac_cost_delay = (avopts && avopts->vacuum_cost_delay >= 0)
2892  ? avopts->vacuum_cost_delay
2893  : (autovacuum_vac_cost_delay >= 0)
2895  : VacuumCostDelay;
2896 
2897  /* 0 or -1 in autovac setting means use plain vacuum_cost_limit */
2898  vac_cost_limit = (avopts && avopts->vacuum_cost_limit > 0)
2899  ? avopts->vacuum_cost_limit
2902  : VacuumCostLimit;
2903 
2904  /* -1 in autovac setting means use log_autovacuum_min_duration */
2905  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2906  ? avopts->log_min_duration
2908 
2909  /* these do not have autovacuum-specific settings */
2910  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2911  ? avopts->freeze_min_age
2913 
2914  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2915  ? avopts->freeze_table_age
2917 
2918  multixact_freeze_min_age = (avopts &&
2919  avopts->multixact_freeze_min_age >= 0)
2920  ? avopts->multixact_freeze_min_age
2922 
2923  multixact_freeze_table_age = (avopts &&
2924  avopts->multixact_freeze_table_age >= 0)
2925  ? avopts->multixact_freeze_table_age
2927 
2928  tab = palloc(sizeof(autovac_table));
2929  tab->at_relid = relid;
2930  tab->at_sharedrel = classForm->relisshared;
2931 
2932  /* Note that this skips toast relations */
2933  tab->at_params.options = (dovacuum ? VACOPT_VACUUM : 0) |
2934  (doanalyze ? VACOPT_ANALYZE : 0) |
2935  (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2936 
2937  /*
2938  * index_cleanup and truncate are unspecified at first in autovacuum.
2939  * They will be filled in with usable values using their reloptions
2940  * (or reloption defaults) later.
2941  */
2944  /* As of now, we don't support parallel vacuum for autovacuum */
2945  tab->at_params.nworkers = -1;
2946  tab->at_params.freeze_min_age = freeze_min_age;
2947  tab->at_params.freeze_table_age = freeze_table_age;
2948  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2949  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2950  tab->at_params.is_wraparound = wraparound;
2951  tab->at_params.log_min_duration = log_min_duration;
2952  tab->at_vacuum_cost_limit = vac_cost_limit;
2953  tab->at_vacuum_cost_delay = vac_cost_delay;
2954  tab->at_relname = NULL;
2955  tab->at_nspname = NULL;
2956  tab->at_datname = NULL;
2957 
2958  /*
2959  * If any of the cost delay parameters has been set individually for
2960  * this table, disable the balancing algorithm.
2961  */
2962  tab->at_dobalance =
2963  !(avopts && (avopts->vacuum_cost_limit > 0 ||
2964  avopts->vacuum_cost_delay > 0));
2965 
2966  /*
2967  * When we decide to do vacuum or analyze, the existing stats cannot
2968  * be reused in the next cycle because it's cleared at the end of
2969  * vacuum or analyze (by AtEOXact_PgStat()).
2970  */
2971  reuse_stats = false;
2972  }
2973  else
2974  {
2975  /*
2976  * If neither vacuum nor analyze is necessary, the existing stats is
2977  * not cleared and can be reused in the next cycle.
2978  */
2979  reuse_stats = true;
2980  }
2981 
2982  heap_freetuple(classTup);
2983  return tab;
2984 }
int Log_autovacuum_min_duration
Definition: autovacuum.c:130
static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
Definition: autovacuum.c:2995
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
int log_min_duration
Definition: rel.h:304
float8 vacuum_cost_delay
Definition: rel.h:305
int vacuum_cost_limit
Definition: rel.h:297
int multixact_freeze_table_age
Definition: rel.h:303
int freeze_min_age
Definition: rel.h:298
int freeze_table_age
Definition: rel.h:300
int multixact_freeze_min_age
Definition: rel.h:301
int nworkers
Definition: vacuum.h:235
int freeze_table_age
Definition: vacuum.h:218
VacOptValue truncate
Definition: vacuum.h:228
int freeze_min_age
Definition: vacuum.h:217
int multixact_freeze_min_age
Definition: vacuum.h:219
int multixact_freeze_table_age
Definition: vacuum.h:221
int log_min_duration
Definition: vacuum.h:224
VacOptValue index_cleanup
Definition: vacuum.h:227
bool at_sharedrel
Definition: autovacuum.c:196
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:188
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:202

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

Referenced by do_autovacuum().

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(), and IsAutoVacuumWorkerProcess().

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

◆ 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

◆ 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 dead_items_max_items(), and ginInsertCleanup().

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

Definition at line 305 of file autovacuum.c.

Referenced by FreeWorkerInfo(), and ProcKill().

◆ AutoVacuumShmem

◆ DatabaseList

dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
static

◆ DatabaseListCxt

MemoryContext DatabaseListCxt = NULL
static

Definition at line 299 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and rebuild_database_list().

◆ 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 = 600000

Definition at line 130 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

WorkerInfo MyWorkerInfo = NULL
static

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