PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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/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 "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/fork_process.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 "tcop/tcopprot.h"
#include "utils/dsa.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 "utils/tqual.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  AutoVacuumShmemStruct
 
struct  AutoVacuumWorkItem
 
struct  AutovacWorkItems
 

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 launcher_determine_sleep (bool canlaunch, bool recursing, struct timeval *nap)
 
static void launch_worker (TimestampTz now)
 
static Listget_database_list (void)
 
static void rebuild_database_list (Oid newdb)
 
static int db_comparator (const void *a, const void *b)
 
static void autovac_balance_cost (void)
 
static void do_autovacuum (void)
 
static void FreeWorkerInfo (int code, Datum arg)
 
static autovac_tabletable_recheck_autovac (Oid relid, HTAB *table_toast_map, TupleDesc pg_class_desc, int effective_multixact_freeze_max_age)
 
static void relation_needs_vacanalyze (Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, PgStat_StatTabEntry *tabentry, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
 
static void autovacuum_do_vac_analyze (autovac_table *tab, BufferAccessStrategy bstrategy)
 
static 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 void perform_work_item (AutoVacuumWorkItem *workitem)
 
static void autovac_report_activity (autovac_table *tab)
 
static void autovac_report_workitem (AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
 
static void av_sighup_handler (SIGNAL_ARGS)
 
static void avl_sigusr2_handler (SIGNAL_ARGS)
 
static void avl_sigterm_handler (SIGNAL_ARGS)
 
static void autovac_refresh_stats (void)
 
static void remove_wi_from_list (dsa_pointer *list, dsa_pointer wi_ptr)
 
static void add_wi_to_list (dsa_pointer *list, dsa_pointer wi_ptr)
 
int StartAutoVacLauncher (void)
 
void AutoVacWorkerFailed (void)
 
int StartAutoVacWorker (void)
 
void AutoVacuumUpdateDelay (void)
 
bool AutoVacuumingActive (void)
 
void AutoVacuumRequestWork (AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
 
void autovac_init (void)
 
bool IsAutoVacuumLauncherProcess (void)
 
bool IsAutoVacuumWorkerProcess (void)
 
Size AutoVacuumShmemSize (void)
 
void AutoVacuumShmemInit (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_anl_thresh
 
double autovacuum_anl_scale
 
int autovacuum_freeze_max_age
 
int autovacuum_multixact_freeze_max_age
 
int autovacuum_vac_cost_delay
 
int autovacuum_vac_cost_limit
 
int Log_autovacuum_min_duration = -1
 
static bool am_autovacuum_launcher = false
 
static bool am_autovacuum_worker = false
 
static volatile sig_atomic_t got_SIGHUP = false
 
static volatile sig_atomic_t got_SIGUSR2 = false
 
static volatile sig_atomic_t got_SIGTERM = 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
 
static dsa_areaAutoVacuumDSA = NULL
 
int AutovacuumLauncherPid = 0
 

Macro Definition Documentation

#define MAX_AUTOVAC_ACTIV_LEN   (NAMEDATALEN * 2 + 56)
#define MAX_AUTOVAC_SLEEPTIME   300 /* seconds */

Definition at line 133 of file autovacuum.c.

Referenced by launcher_determine_sleep().

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 132 of file autovacuum.c.

Referenced by launcher_determine_sleep(), and rebuild_database_list().

#define NUM_WORKITEMS   256

Definition at line 303 of file autovacuum.c.

Referenced by AutoVacuumRequestWork().

#define STATS_READ_DELAY   1000

Definition at line 129 of file autovacuum.c.

Referenced by autovac_refresh_stats().

Typedef Documentation

Definition at line 233 of file autovacuum.c.

Enumeration Type Documentation

Enumerator
AutoVacForkFailed 
AutoVacRebalance 
AutoVacNumSignals 

Definition at line 240 of file autovacuum.c.

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

Function Documentation

static void add_wi_to_list ( dsa_pointer list,
dsa_pointer  wi_ptr 
)
static

Definition at line 3492 of file autovacuum.c.

References AutoVacuumWorkItem::avw_next, AutoVacuumWorkItem::avw_prev, dsa_get_address(), InvalidDsaPointer, and sort-test::list.

Referenced by AutoVacuumRequestWork(), and do_autovacuum().

3493 {
3494  if (*list == InvalidDsaPointer)
3495  {
3496  /* list is empty; item is now singleton */
3497  *list = wi_ptr;
3498  }
3499  else
3500  {
3501  AutoVacuumWorkItem *workitem = dsa_get_address(AutoVacuumDSA, wi_ptr);
3503 
3504  /* Put item at head of list */
3505  workitem->avw_next = *list;
3506  old->avw_prev = wi_ptr;
3507  *list = wi_ptr;
3508  }
3509 }
#define InvalidDsaPointer
Definition: dsa.h:78
dsa_pointer avw_prev
Definition: autovacuum.c:300
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:924
dsa_pointer avw_next
Definition: autovacuum.c:299
tuple list
Definition: sort-test.py:11
static dsa_area * AutoVacuumDSA
Definition: autovacuum.c:310
static void autovac_balance_cost ( void  )
static

Definition at line 1795 of file autovacuum.c.

References autovacuum_vac_cost_delay, autovacuum_vac_cost_limit, AutoVacuumShmemStruct::av_runningWorkers, dlist_iter::cur, DEBUG2, dlist_container, dlist_foreach, elog, Max, Min, NULL, 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(), and do_autovacuum().

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

Definition at line 3340 of file autovacuum.c.

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

Referenced by PostmasterMain().

3341 {
3343  ereport(WARNING,
3344  (errmsg("autovacuum not started because of misconfiguration"),
3345  errhint("Enable the \"track_counts\" option.")));
3346 }
int errhint(const char *fmt,...)
Definition: elog.c:987
bool autovacuum_start_daemon
Definition: autovacuum.c:112
bool pgstat_track_counts
Definition: pgstat.c:126
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void autovac_refresh_stats ( void  )
static

Definition at line 3436 of file autovacuum.c.

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

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

3437 {
3439  {
3440  static TimestampTz last_read = 0;
3441  TimestampTz current_time;
3442 
3443  current_time = GetCurrentTimestamp();
3444 
3445  if (!TimestampDifferenceExceeds(last_read, current_time,
3447  return;
3448 
3449  last_read = current_time;
3450  }
3451 
3453 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
WalTimeSample last_read[NUM_SYNC_REP_WAIT_MODE]
Definition: walsender.c:214
#define STATS_READ_DELAY
Definition: autovacuum.c:129
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
bool IsAutoVacuumLauncherProcess(void)
Definition: autovacuum.c:3354
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5519
static void autovac_report_activity ( autovac_table tab)
static

Definition at line 3144 of file autovacuum.c.

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

Referenced by autovacuum_do_vac_analyze().

3145 {
3146 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3147  char activity[MAX_AUTOVAC_ACTIV_LEN];
3148  int len;
3149 
3150  /* Report the command and possible options */
3151  if (tab->at_vacoptions & VACOPT_VACUUM)
3152  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3153  "autovacuum: VACUUM%s",
3154  tab->at_vacoptions & VACOPT_ANALYZE ? " ANALYZE" : "");
3155  else
3156  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3157  "autovacuum: ANALYZE");
3158 
3159  /*
3160  * Report the qualified name of the relation.
3161  */
3162  len = strlen(activity);
3163 
3164  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3165  " %s.%s%s", tab->at_nspname, tab->at_relname,
3166  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3167 
3168  /* Set statement_timestamp() to current time for pg_stat_activity */
3170 
3172 }
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
char * at_relname
Definition: autovacuum.c:196
bool is_wraparound
Definition: vacuum.h:144
char * at_nspname
Definition: autovacuum.c:197
#define MAX_AUTOVAC_ACTIV_LEN
VacuumParams at_params
Definition: autovacuum.c:191
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:740
static void autovac_report_workitem ( AutoVacuumWorkItem workitem,
const char *  nspname,
const char *  relname 
)
static

Definition at line 3179 of file autovacuum.c.

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

Referenced by perform_work_item().

3181 {
3182  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3183  char blk[12 + 2];
3184  int len;
3185 
3186  switch (workitem->avw_type)
3187  {
3189  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3190  "autovacuum: BRIN summarize");
3191  break;
3192  }
3193 
3194  /*
3195  * Report the qualified name of the relation, and the block number if any
3196  */
3197  len = strlen(activity);
3198 
3199  if (BlockNumberIsValid(workitem->avw_blockNumber))
3200  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3201  else
3202  blk[0] = '\0';
3203 
3204  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3205  " %s.%s%s", nspname, relname, blk);
3206 
3207  /* Set statement_timestamp() to current time for pg_stat_activity */
3209 
3211 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:294
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2994
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define MAX_AUTOVAC_ACTIV_LEN
BlockNumber avw_blockNumber
Definition: autovacuum.c:297
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:740
NON_EXEC_STATIC void AutoVacLauncherMain ( int  argc,
char *  argv[] 
)

Definition at line 442 of file autovacuum.c.

References AbortCurrentTransaction(), avl_dbase::adl_next_worker, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), am_autovacuum_launcher, autovac_balance_cost(), AutoVacForkFailed, AutoVacRebalance, autovacuum_naptime, AutoVacuumingActive(), AutoVacuumShmemStruct::av_dsa_handle, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, av_sighup_handler(), AutoVacuumShmemStruct::av_signal, AutoVacuumShmemStruct::av_startingWorker, AutoVacuumShmemStruct::av_workitems, avl_sigterm_handler(), avl_sigusr2_handler(), BaseInit(), DEBUG1, disable_all_timeouts(), dlist_init(), dlist_is_empty(), dlist_push_head(), dlist_tail_element, do_start_worker(), dsa_attach(), dsa_create(), dsa_get_handle(), dsa_pin(), dsa_pin_mapping(), elog, EmitErrorReport(), ereport, errmsg(), error_context_stack, FloatExceptionHandler(), FlushErrorState(), GetCurrentTimestamp(), got_SIGHUP, got_SIGTERM, got_SIGUSR2, HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InvalidDsaPointer, InvalidOid, launch_worker(), launcher_determine_sleep(), LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, MyLatch, MyProcPid, NormalProcessing, NULL, PG_exception_stack, PG_SETMASK, pg_usleep(), PGC_S_OVERRIDE, PGC_SIGHUP, PGC_SUSET, pgstat_clear_snapshot(), PMSIGNAL_START_AUTOVAC_WORKER, PostAuthDelay, pqsignal(), proc_exit(), ProcessCatchupInterrupt(), ProcessConfigFile(), procsignal_sigusr1_handler(), QueryCancelPending, quickdie(), rebuild_database_list(), ResetLatch(), RESUME_INTERRUPTS, SendPostmasterSignal(), SetConfigOption(), SetProcessingMode, SIG_DFL, SIG_IGN, SIGCHLD, SIGHUP, SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, StatementCancelHandler(), TimestampDifferenceExceeds(), TopMemoryContext, UnBlockSig, WAIT_EVENT_AUTOVACUUM_MAIN, WaitLatch(), waittime, WARNING, WorkerInfoData::wi_dboid, WorkerInfoData::wi_launchtime, WorkerInfoData::wi_links, WorkerInfoData::wi_proc, WorkerInfoData::wi_sharedrel, WorkerInfoData::wi_tableoid, WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_TIMEOUT.

Referenced by StartAutoVacLauncher().

443 {
444  sigjmp_buf local_sigjmp_buf;
445 
446  am_autovacuum_launcher = true;
447 
448  /* Identify myself via ps */
449  init_ps_display("autovacuum launcher process", "", "", "");
450 
451  ereport(DEBUG1,
452  (errmsg("autovacuum launcher started")));
453 
454  if (PostAuthDelay)
455  pg_usleep(PostAuthDelay * 1000000L);
456 
458 
459  /*
460  * Set up signal handlers. We operate on databases much like a regular
461  * backend, so we use the same signal handling. See equivalent code in
462  * tcop/postgres.c.
463  */
466  pqsignal(SIGTERM, avl_sigterm_handler);
467 
469  InitializeTimeouts(); /* establishes SIGALRM handler */
470 
476 
477  /* Early initialization */
478  BaseInit();
479 
480  /*
481  * Create a per-backend PGPROC struct in shared memory, except in the
482  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
483  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
484  * had to do some stuff with LWLocks).
485  */
486 #ifndef EXEC_BACKEND
487  InitProcess();
488 #endif
489 
491 
493 
494  /*
495  * Create a memory context that we will do all our work in. We do this so
496  * that we can reset the context during error recovery and thereby avoid
497  * possible memory leaks.
498  */
500  "Autovacuum Launcher",
503 
504  /*
505  * If an exception is encountered, processing resumes here.
506  *
507  * This code is a stripped down version of PostgresMain error recovery.
508  */
509  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
510  {
511  /* since not using PG_TRY, must reset error stack by hand */
513 
514  /* Prevents interrupts while cleaning up */
515  HOLD_INTERRUPTS();
516 
517  /* Forget any pending QueryCancel or timeout request */
518  disable_all_timeouts(false);
519  QueryCancelPending = false; /* second to avoid race condition */
520 
521  /* Report the error to the server log */
522  EmitErrorReport();
523 
524  /* Abort the current transaction in order to recover */
526 
527  /*
528  * Now return to normal top-level context and clear ErrorContext for
529  * next time.
530  */
532  FlushErrorState();
533 
534  /* Flush any leaked data in the top-level context */
536 
537  /* don't leave dangling pointers to freed memory */
540 
541  /*
542  * Make sure pgstat also considers our stat data as gone. Note: we
543  * mustn't use autovac_refresh_stats here.
544  */
546 
547  /* Now we can allow interrupts again */
549 
550  /* if in shutdown mode, no need for anything further; just go away */
551  if (got_SIGTERM)
552  goto shutdown;
553 
554  /*
555  * Sleep at least 1 second after any error. We don't want to be
556  * filling the error logs as fast as we can.
557  */
558  pg_usleep(1000000L);
559  }
560 
561  /* We can now handle ereport(ERROR) */
562  PG_exception_stack = &local_sigjmp_buf;
563 
564  /* must unblock signals before calling rebuild_database_list */
566 
567  /*
568  * Force zero_damaged_pages OFF in the autovac process, even if it is set
569  * in postgresql.conf. We don't really want such a dangerous option being
570  * applied non-interactively.
571  */
572  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
573 
574  /*
575  * Force settable timeouts off to avoid letting these settings prevent
576  * regular maintenance from being executed.
577  */
578  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
579  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
580  SetConfigOption("idle_in_transaction_session_timeout", "0",
582 
583  /*
584  * Force default_transaction_isolation to READ COMMITTED. We don't want
585  * to pay the overhead of serializable mode, nor add any risk of causing
586  * deadlocks or delaying other transactions.
587  */
588  SetConfigOption("default_transaction_isolation", "read committed",
590 
591  /*
592  * In emergency mode, just start a worker (unless shutdown was requested)
593  * and go away.
594  */
595  if (!AutoVacuumingActive())
596  {
597  if (!got_SIGTERM)
598  do_start_worker();
599  proc_exit(0); /* done */
600  }
601 
603 
604  /*
605  * Create the initial database list. The invariant we want this list to
606  * keep is that it's ordered by decreasing next_time. As soon as an entry
607  * is updated to a higher time, it will be moved to the front (which is
608  * correct because the only operation is to add autovacuum_naptime to the
609  * entry, and time always increases).
610  */
612 
613  /*
614  * Set up our DSA so that backends can install work-item requests. It may
615  * already exist as created by a previous launcher.
616  */
618  {
619  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
620  AutoVacuumDSA = dsa_create(AutovacuumLock->tranche);
621  /* make sure it doesn't go away even if we do */
625  /* delay array allocation until first request */
627  LWLockRelease(AutovacuumLock);
628  }
629  else
630  {
633  }
634 
635  /* loop until shutdown request */
636  while (!got_SIGTERM)
637  {
638  struct timeval nap;
639  TimestampTz current_time = 0;
640  bool can_launch;
641  int rc;
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  rc = WaitLatch(MyLatch,
659  (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
661 
663 
664  /* Process sinval catchup interrupts that happened while sleeping */
666 
667  /*
668  * Emergency bailout if postmaster has died. This is to avoid the
669  * necessity for manual cleanup of all postmaster children.
670  */
671  if (rc & WL_POSTMASTER_DEATH)
672  proc_exit(1);
673 
674  /* the normal shutdown case */
675  if (got_SIGTERM)
676  break;
677 
678  if (got_SIGHUP)
679  {
680  got_SIGHUP = false;
682 
683  /* shutdown requested in config file? */
684  if (!AutoVacuumingActive())
685  break;
686 
687  /* rebalance in case the default cost parameters changed */
688  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
690  LWLockRelease(AutovacuumLock);
691 
692  /* rebuild the list in case the naptime changed */
694  }
695 
696  /*
697  * a worker finished, or postmaster signalled failure to start a
698  * worker
699  */
700  if (got_SIGUSR2)
701  {
702  got_SIGUSR2 = false;
703 
704  /* rebalance cost limits, if needed */
706  {
707  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
710  LWLockRelease(AutovacuumLock);
711  }
712 
714  {
715  /*
716  * If the postmaster failed to start a new worker, we sleep
717  * for a little while and resend the signal. The new worker's
718  * state is still in memory, so this is sufficient. After
719  * that, we restart the main loop.
720  *
721  * XXX should we put a limit to the number of times we retry?
722  * I don't think it makes much sense, because a future start
723  * of a worker will continue to fail in the same way.
724  */
726  pg_usleep(1000000L); /* 1s */
728  continue;
729  }
730  }
731 
732  /*
733  * There are some conditions that we need to check before trying to
734  * start a worker. First, we need to make sure that there is a worker
735  * slot available. Second, we need to make sure that no other worker
736  * failed while starting up.
737  */
738 
739  current_time = GetCurrentTimestamp();
740  LWLockAcquire(AutovacuumLock, LW_SHARED);
741 
743 
745  {
746  int waittime;
748 
749  /*
750  * We can't launch another worker when another one is still
751  * starting up (or failed while doing so), so just sleep for a bit
752  * more; that worker will wake us up again as soon as it's ready.
753  * We will only wait autovacuum_naptime seconds (up to a maximum
754  * of 60 seconds) for this to happen however. Note that failure
755  * to connect to a particular database is not a problem here,
756  * because the worker removes itself from the startingWorker
757  * pointer before trying to connect. Problems detected by the
758  * postmaster (like fork() failure) are also reported and handled
759  * differently. The only problems that may cause this code to
760  * fire are errors in the earlier sections of AutoVacWorkerMain,
761  * before the worker removes the WorkerInfo from the
762  * startingWorker pointer.
763  */
764  waittime = Min(autovacuum_naptime, 60) * 1000;
765  if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
766  waittime))
767  {
768  LWLockRelease(AutovacuumLock);
769  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
770 
771  /*
772  * No other process can put a worker in starting mode, so if
773  * startingWorker is still INVALID after exchanging our lock,
774  * we assume it's the same one we saw above (so we don't
775  * recheck the launch time).
776  */
778  {
780  worker->wi_dboid = InvalidOid;
781  worker->wi_tableoid = InvalidOid;
782  worker->wi_sharedrel = false;
783  worker->wi_proc = NULL;
784  worker->wi_launchtime = 0;
786  &worker->wi_links);
788  elog(WARNING, "worker took too long to start; canceled");
789  }
790  }
791  else
792  can_launch = false;
793  }
794  LWLockRelease(AutovacuumLock); /* either shared or exclusive */
795 
796  /* if we can't do anything, just go back to sleep */
797  if (!can_launch)
798  continue;
799 
800  /* We're OK to start a new worker */
801 
803  {
804  /*
805  * Special case when the list is empty: start a worker right away.
806  * This covers the initial case, when no database is in pgstats
807  * (thus the list is empty). Note that the constraints in
808  * launcher_determine_sleep keep us from starting workers too
809  * quickly (at most once every autovacuum_naptime when the list is
810  * empty).
811  */
812  launch_worker(current_time);
813  }
814  else
815  {
816  /*
817  * because rebuild_database_list constructs a list with most
818  * distant adl_next_worker first, we obtain our database from the
819  * tail of the list.
820  */
821  avl_dbase *avdb;
822 
823  avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
824 
825  /*
826  * launch a worker if next_worker is right now or it is in the
827  * past
828  */
830  current_time, 0))
831  launch_worker(current_time);
832  }
833  }
834 
835  /* Normal exit from the autovac launcher is here */
836 shutdown:
837  ereport(DEBUG1,
838  (errmsg("autovacuum launcher shutting down")));
840 
841  proc_exit(0); /* done */
842 }
void ProcessCatchupInterrupt(void)
Definition: sinval.c:177
void InitializeTimeouts(void)
Definition: timeout.c:340
int autovacuum_naptime
Definition: autovacuum.c:115
void AbortCurrentTransaction(void)
Definition: xact.c:2988
#define SIGUSR1
Definition: win32.h:202
TimestampTz adl_next_worker
Definition: autovacuum.c:161
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:38
WorkerInfo av_startingWorker
Definition: autovacuum.c:269
static void autovac_balance_cost(void)
Definition: autovacuum.c:1795
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:265
static bool am_autovacuum_launcher
Definition: autovacuum.c:136
#define InvalidDsaPointer
Definition: dsa.h:78
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
dlist_head av_freeWorkers
Definition: autovacuum.c:267
int waittime
Definition: pg_standby.c:41
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
TimestampTz wi_launchtime
Definition: autovacuum.c:225
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:155
#define Min(x, y)
Definition: c.h:806
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:99
static volatile sig_atomic_t got_SIGHUP
Definition: autovacuum.c:140
#define SetProcessingMode(mode)
Definition: miscadmin.h:371
void BaseInit(void)
Definition: postinit.c:517
dlist_node wi_links
Definition: autovacuum.c:221
void ResetLatch(volatile Latch *latch)
Definition: latch.c:498
volatile bool QueryCancelPending
Definition: globals.c:30
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
#define SIGQUIT
Definition: win32.h:189
void FlushErrorState(void)
Definition: elog.c:1587
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2654
dsa_area * dsa_create(int tranche_id)
Definition: dsa.c:419
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:116
ErrorContextCallback * error_context_stack
Definition: elog.c:88
dsa_handle dsa_get_handle(dsa_area *area)
Definition: dsa.c:493
void pg_usleep(long microsec)
Definition: signal.c:53
dsa_handle av_dsa_handle
Definition: autovacuum.c:270
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
#define SIG_IGN
Definition: win32.h:185
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:496
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:596
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3219
Definition: guc.h:75
static volatile sig_atomic_t got_SIGTERM
Definition: autovacuum.c:142
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
void InitProcess(void)
Definition: proc.c:287
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6672
void dsa_pin_mapping(dsa_area *area)
Definition: dsa.c:630
sigset_t UnBlockSig
Definition: pqsignal.c:22
static dlist_head DatabaseList
Definition: autovacuum.c:280
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
static void avl_sigusr2_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1423
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition: autovacuum.c:852
#define WARNING
Definition: elog.h:40
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
dsa_pointer av_workitems
Definition: autovacuum.c:271
int PostAuthDelay
Definition: postgres.c:97
dsa_area * dsa_attach(dsa_handle handle)
Definition: dsa.c:505
void EmitErrorReport(void)
Definition: elog.c:1446
#define SIGPIPE
Definition: win32.h:193
#define SIGHUP
Definition: win32.h:188
#define InvalidOid
Definition: postgres_ext.h:36
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define SIG_DFL
Definition: win32.h:183
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:141
#define NULL
Definition: c.h:229
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
void pgstat_clear_snapshot(void)
Definition: pgstat.c:5519
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:274
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
static void av_sighup_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1411
sigjmp_buf * PG_exception_stack
Definition: elog.c:90
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:936
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:558
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
static MemoryContext DatabaseListCxt
Definition: autovacuum.c:281
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2675
static dsa_area * AutoVacuumDSA
Definition: autovacuum.c:310
struct Latch * MyLatch
Definition: globals.c:51
PGPROC * wi_proc
Definition: autovacuum.c:224
static void launch_worker(TimestampTz now)
Definition: autovacuum.c:1352
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:113
#define elog
Definition: elog.h:219
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:260
void dsa_pin(dsa_area *area)
Definition: dsa.c:957
#define SIGCHLD
Definition: win32.h:198
#define WL_LATCH_SET
Definition: latch.h:124
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2562
static Oid do_start_worker(void)
Definition: autovacuum.c:1137
#define SIGUSR2
Definition: win32.h:203
static void avl_sigterm_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1435
void init_ps_display(const char *username, const char *dbname, const char *host_info, const char *initial_str)
Definition: ps_status.c:244
static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3114 of file autovacuum.c.

References autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relid, autovac_table::at_relname, autovac_table::at_vacoptions, autovac_report_activity(), RangeVar::location, MemSet, NIL, RangeVar::relname, RangeVar::schemaname, and vacuum().

Referenced by do_autovacuum().

3115 {
3116  RangeVar rangevar;
3117 
3118  /* Set up command parameters --- use local variables instead of palloc */
3119  MemSet(&rangevar, 0, sizeof(rangevar));
3120 
3121  rangevar.schemaname = tab->at_nspname;
3122  rangevar.relname = tab->at_relname;
3123  rangevar.location = -1;
3124 
3125  /* Let pgstat know what we're doing */
3127 
3128  vacuum(tab->at_vacoptions, &rangevar, tab->at_relid, &tab->at_params, NIL,
3129  bstrategy, true);
3130 }
#define NIL
Definition: pg_list.h:69
#define MemSet(start, val, len)
Definition: c.h:857
char * schemaname
Definition: primnodes.h:67
int location
Definition: primnodes.h:73
char * relname
Definition: primnodes.h:68
char * at_relname
Definition: autovacuum.c:196
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3144
char * at_nspname
Definition: autovacuum.c:197
void vacuum(int options, RangeVar *relation, Oid relid, VacuumParams *params, List *va_cols, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:149
VacuumParams at_params
Definition: autovacuum.c:191
bool AutoVacuumingActive ( void  )

Definition at line 3219 of file autovacuum.c.

References autovacuum_start_daemon, and pgstat_track_counts.

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

3220 {
3222  return false;
3223  return true;
3224 }
bool autovacuum_start_daemon
Definition: autovacuum.c:112
bool pgstat_track_counts
Definition: pgstat.c:126
void AutoVacuumRequestWork ( AutoVacuumWorkItemType  type,
Oid  relationId,
BlockNumber  blkno 
)

Definition at line 3230 of file autovacuum.c.

References add_wi_to_list(), AutoVacuumShmemStruct::av_dsa_handle, AutoVacuumShmemStruct::av_workitems, AutovacWorkItems::avs_freeItems, AutovacWorkItems::avs_usedItems, AutoVacuumWorkItem::avw_active, AutoVacuumWorkItem::avw_blockNumber, AutoVacuumWorkItem::avw_database, AutoVacuumWorkItem::avw_next, AutoVacuumWorkItem::avw_relation, AutoVacuumWorkItem::avw_type, DSA_ALLOC_NO_OOM, dsa_allocate_extended(), dsa_attach(), dsa_detach(), dsa_get_address(), dsa_pin_mapping(), i, InvalidDsaPointer, InvalidOid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyDatabaseId, NULL, NUM_WORKITEMS, and remove_wi_from_list().

Referenced by brininsert().

3232 {
3233  AutovacWorkItems *workitems;
3234  dsa_pointer wi_ptr;
3235  AutoVacuumWorkItem *workitem;
3236 
3237  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3238 
3239  /*
3240  * It may be useful to de-duplicate the list upon insertion. For the only
3241  * currently existing caller, this is not necessary.
3242  */
3243 
3244  /* First use in this process? Set up DSA */
3245  if (!AutoVacuumDSA)
3246  {
3248  {
3249  /* autovacuum launcher not started; nothing can be done */
3250  LWLockRelease(AutovacuumLock);
3251  return;
3252  }
3255  }
3256 
3257  /* First use overall? Allocate work items array */
3259  {
3260  int i;
3261  AutovacWorkItems *workitems;
3262 
3265  sizeof(AutovacWorkItems) +
3268  /* if out of memory, silently disregard the request */
3270  {
3271  LWLockRelease(AutovacuumLock);
3273  AutoVacuumDSA = NULL;
3274  return;
3275  }
3276 
3277  /* Initialize each array entry as a member of the free list */
3279 
3280  workitems->avs_usedItems = InvalidDsaPointer;
3281  workitems->avs_freeItems = InvalidDsaPointer;
3282  for (i = 0; i < NUM_WORKITEMS; i++)
3283  {
3284  /* XXX surely there is a simpler way to do this */
3285  wi_ptr = AutoVacuumShmem->av_workitems + sizeof(AutovacWorkItems) +
3286  sizeof(AutoVacuumWorkItem) * i;
3287  workitem = (AutoVacuumWorkItem *) dsa_get_address(AutoVacuumDSA, wi_ptr);
3288 
3289  workitem->avw_type = 0;
3290  workitem->avw_database = InvalidOid;
3291  workitem->avw_relation = InvalidOid;
3292  workitem->avw_active = false;
3293 
3294  /* put this item in the free list */
3295  workitem->avw_next = workitems->avs_freeItems;
3296  workitems->avs_freeItems = wi_ptr;
3297  }
3298  }
3299 
3300  workitems = (AutovacWorkItems *)
3302 
3303  /* If array is full, disregard the request */
3304  if (workitems->avs_freeItems == InvalidDsaPointer)
3305  {
3306  LWLockRelease(AutovacuumLock);
3308  AutoVacuumDSA = NULL;
3309  return;
3310  }
3311 
3312  /* remove workitem struct from free list ... */
3313  wi_ptr = workitems->avs_freeItems;
3314  remove_wi_from_list(&workitems->avs_freeItems, wi_ptr);
3315 
3316  /* ... initialize it ... */
3317  workitem = dsa_get_address(AutoVacuumDSA, wi_ptr);
3318  workitem->avw_type = type;
3319  workitem->avw_database = MyDatabaseId;
3320  workitem->avw_relation = relationId;
3321  workitem->avw_blockNumber = blkno;
3322  workitem->avw_active = false;
3323 
3324  /* ... and put it on autovacuum's to-do list */
3325  add_wi_to_list(&workitems->avs_usedItems, wi_ptr);
3326 
3327  LWLockRelease(AutovacuumLock);
3328 
3330  AutoVacuumDSA = NULL;
3331 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:294
static void remove_wi_from_list(dsa_pointer *list, dsa_pointer wi_ptr)
Definition: autovacuum.c:3465
#define NUM_WORKITEMS
Definition: autovacuum.c:303
#define DSA_ALLOC_NO_OOM
Definition: dsa.h:74
#define InvalidDsaPointer
Definition: dsa.h:78
dsa_pointer dsa_allocate_extended(dsa_area *area, Size size, int flags)
Definition: dsa.c:664
uint64 dsa_pointer
Definition: dsa.h:62
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:924
dsa_handle av_dsa_handle
Definition: autovacuum.c:270
dsa_pointer avw_next
Definition: autovacuum.c:299
static void add_wi_to_list(dsa_pointer *list, dsa_pointer wi_ptr)
Definition: autovacuum.c:3492
dsa_pointer avs_freeItems
Definition: autovacuum.c:307
void dsa_detach(dsa_area *area)
Definition: dsa.c:1884
void dsa_pin_mapping(dsa_area *area)
Definition: dsa.c:630
dsa_pointer av_workitems
Definition: autovacuum.c:271
Oid MyDatabaseId
Definition: globals.c:76
BlockNumber avw_blockNumber
Definition: autovacuum.c:297
dsa_area * dsa_attach(dsa_handle handle)
Definition: dsa.c:505
dsa_pointer avs_usedItems
Definition: autovacuum.c:306
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:274
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
int i
static dsa_area * AutoVacuumDSA
Definition: autovacuum.c:310
void AutoVacuumShmemInit ( void  )

Definition at line 3390 of file autovacuum.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

3391 {
3392  bool found;
3393 
3395  ShmemInitStruct("AutoVacuum Data",
3397  &found);
3398 
3399  if (!IsUnderPostmaster)
3400  {
3401  WorkerInfo worker;
3402  int i;
3403 
3404  Assert(!found);
3405 
3410 
3411  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3412  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3413 
3414  /* initialize the WorkerInfo free list */
3415  for (i = 0; i < autovacuum_max_workers; i++)
3417  &worker[i].wi_links);
3418  }
3419  else
3420  Assert(found);
3421 }
WorkerInfo av_startingWorker
Definition: autovacuum.c:269
dlist_head av_freeWorkers
Definition: autovacuum.c:267
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:233
dlist_node wi_links
Definition: autovacuum.c:221
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
bool IsUnderPostmaster
Definition: globals.c:100
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3371
int autovacuum_max_workers
Definition: autovacuum.c:113
static void dlist_init(dlist_head *head)
Definition: ilist.h:278
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:274
#define MAXALIGN(LEN)
Definition: c.h:588
int i
dlist_head av_runningWorkers
Definition: autovacuum.c:268
Size AutoVacuumShmemSize ( void  )

Definition at line 3371 of file autovacuum.c.

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

Referenced by AutoVacuumShmemInit(), and CreateSharedMemoryAndSemaphores().

3372 {
3373  Size size;
3374 
3375  /*
3376  * Need the fixed struct and the array of WorkerInfoData.
3377  */
3378  size = sizeof(AutoVacuumShmemStruct);
3379  size = MAXALIGN(size);
3381  sizeof(WorkerInfoData)));
3382  return size;
3383 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
int autovacuum_max_workers
Definition: autovacuum.c:113
size_t Size
Definition: c.h:356
#define MAXALIGN(LEN)
Definition: c.h:588
void AutoVacuumUpdateDelay ( void  )

Definition at line 1779 of file autovacuum.c.

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

Referenced by do_autovacuum(), and vacuum_delay_point().

1780 {
1781  if (MyWorkerInfo)
1782  {
1785  }
1786 }
int VacuumCostLimit
Definition: globals.c:131
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:284
int VacuumCostDelay
Definition: globals.c:132
void AutoVacWorkerFailed ( void  )

Definition at line 1404 of file autovacuum.c.

References AutoVacForkFailed, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

1405 {
1407 }
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:265
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:274
NON_EXEC_STATIC void AutoVacWorkerMain ( int  argc,
char *  argv[] 
)

Definition at line 1526 of file autovacuum.c.

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

Referenced by StartAutoVacWorker().

1527 {
1528  sigjmp_buf local_sigjmp_buf;
1529  Oid dbid;
1530 
1531  am_autovacuum_worker = true;
1532 
1533  /* Identify myself via ps */
1534  init_ps_display("autovacuum worker process", "", "", "");
1535 
1537 
1538  /*
1539  * Set up signal handlers. We operate on databases much like a regular
1540  * backend, so we use the same signal handling. See equivalent code in
1541  * tcop/postgres.c.
1542  */
1544 
1545  /*
1546  * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1547  * means abort and exit cleanly, and SIGQUIT means abandon ship.
1548  */
1550  pqsignal(SIGTERM, die);
1552  InitializeTimeouts(); /* establishes SIGALRM handler */
1553 
1559 
1560  /* Early initialization */
1561  BaseInit();
1562 
1563  /*
1564  * Create a per-backend PGPROC struct in shared memory, except in the
1565  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
1566  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
1567  * had to do some stuff with LWLocks).
1568  */
1569 #ifndef EXEC_BACKEND
1570  InitProcess();
1571 #endif
1572 
1573  /*
1574  * If an exception is encountered, processing resumes here.
1575  *
1576  * See notes in postgres.c about the design of this coding.
1577  */
1578  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1579  {
1580  /* Prevents interrupts while cleaning up */
1581  HOLD_INTERRUPTS();
1582 
1583  /* Report the error to the server log */
1584  EmitErrorReport();
1585 
1586  /*
1587  * We can now go away. Note that because we called InitProcess, a
1588  * callback was registered to do ProcKill, which will clean up
1589  * necessary state.
1590  */
1591  proc_exit(0);
1592  }
1593 
1594  /* We can now handle ereport(ERROR) */
1595  PG_exception_stack = &local_sigjmp_buf;
1596 
1598 
1599  /*
1600  * Force zero_damaged_pages OFF in the autovac process, even if it is set
1601  * in postgresql.conf. We don't really want such a dangerous option being
1602  * applied non-interactively.
1603  */
1604  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1605 
1606  /*
1607  * Force settable timeouts off to avoid letting these settings prevent
1608  * regular maintenance from being executed.
1609  */
1610  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1611  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1612  SetConfigOption("idle_in_transaction_session_timeout", "0",
1614 
1615  /*
1616  * Force default_transaction_isolation to READ COMMITTED. We don't want
1617  * to pay the overhead of serializable mode, nor add any risk of causing
1618  * deadlocks or delaying other transactions.
1619  */
1620  SetConfigOption("default_transaction_isolation", "read committed",
1622 
1623  /*
1624  * Force synchronous replication off to allow regular maintenance even if
1625  * we are waiting for standbys to connect. This is important to ensure we
1626  * aren't blocked from performing anti-wraparound tasks.
1627  */
1629  SetConfigOption("synchronous_commit", "local",
1631 
1632  /*
1633  * Get the info about the database we're going to work on.
1634  */
1635  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1636 
1637  /*
1638  * beware of startingWorker being INVALID; this should normally not
1639  * happen, but if a worker fails after forking and before this, the
1640  * launcher might have decided to remove it from the queue and start
1641  * again.
1642  */
1644  {
1646  dbid = MyWorkerInfo->wi_dboid;
1648 
1649  /* insert into the running list */
1652 
1653  /*
1654  * remove from the "starting" pointer, so that the launcher can start
1655  * a new worker if required
1656  */
1658  LWLockRelease(AutovacuumLock);
1659 
1661 
1662  /* wake up the launcher */
1663  if (AutoVacuumShmem->av_launcherpid != 0)
1665  }
1666  else
1667  {
1668  /* no worker entry for me, go away */
1669  elog(WARNING, "autovacuum worker started without a worker entry");
1670  dbid = InvalidOid;
1671  LWLockRelease(AutovacuumLock);
1672  }
1673 
1674  if (OidIsValid(dbid))
1675  {
1676  char dbname[NAMEDATALEN];
1677 
1679  {
1680  /* First use of DSA in this worker, so attach to it */
1684  }
1685 
1686  /*
1687  * Report autovac startup to the stats collector. We deliberately do
1688  * this before InitPostgres, so that the last_autovac_time will get
1689  * updated even if the connection attempt fails. This is to prevent
1690  * autovac from getting "stuck" repeatedly selecting an unopenable
1691  * database, rather than making any progress on stuff it can connect
1692  * to.
1693  */
1694  pgstat_report_autovac(dbid);
1695 
1696  /*
1697  * Connect to the selected database
1698  *
1699  * Note: if we have selected a just-deleted database (due to using
1700  * stale stats info), we'll fail and exit here.
1701  */
1702  InitPostgres(NULL, dbid, NULL, InvalidOid, dbname);
1704  set_ps_display(dbname, false);
1705  ereport(DEBUG1,
1706  (errmsg("autovacuum: processing database \"%s\"", dbname)));
1707 
1708  if (PostAuthDelay)
1709  pg_usleep(PostAuthDelay * 1000000L);
1710 
1711  /* And do an appropriate amount of work */
1714  do_autovacuum();
1715  }
1716 
1717  /*
1718  * The launcher will be notified of my death in ProcKill, *if* we managed
1719  * to get a worker slot at all
1720  */
1721 
1722  /* All done, go away */
1723  proc_exit(0);
1724 }
static bool am_autovacuum_worker
Definition: autovacuum.c:137
void InitializeTimeouts(void)
Definition: timeout.c:340
#define SIGUSR1
Definition: win32.h:202
#define DEBUG1
Definition: elog.h:25
WorkerInfo av_startingWorker
Definition: autovacuum.c:269
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:300
static void do_autovacuum(void)
Definition: autovacuum.c:1949
PGPROC * MyProc
Definition: proc.c:67
static MultiXactId recentMulti
Definition: autovacuum.c:146
void set_ps_display(const char *activity, bool force)
Definition: ps_status.c:326
void proc_exit(int code)
Definition: ipc.c:99
#define SetProcessingMode(mode)
Definition: miscadmin.h:371
void BaseInit(void)
Definition: postinit.c:517
dlist_node wi_links
Definition: autovacuum.c:221
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define SIGQUIT
Definition: win32.h:189
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2654
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define NAMEDATALEN
void pg_usleep(long microsec)
Definition: signal.c:53
dsa_handle av_dsa_handle
Definition: autovacuum.c:270
#define SIG_IGN
Definition: win32.h:185
Definition: guc.h:75
void InitProcess(void)
Definition: proc.c:287
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:348
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6672
TransactionId ReadNewTransactionId(void)
Definition: varsup.c:250
void dsa_pin_mapping(dsa_area *area)
Definition: dsa.c:630
sigset_t UnBlockSig
Definition: pqsignal.c:22
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:284
int synchronous_commit
Definition: xact.c:82
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
int PostAuthDelay
Definition: postgres.c:97
static TransactionId recentXid
Definition: autovacuum.c:145
dsa_area * dsa_attach(dsa_handle handle)
Definition: dsa.c:505
void EmitErrorReport(void)
Definition: elog.c:1446
#define SIGPIPE
Definition: win32.h:193
#define SIGHUP
Definition: win32.h:188
#define InvalidOid
Definition: postgres_ext.h:36
#define SIG_DFL
Definition: win32.h:183
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
char * dbname
Definition: streamutil.c:38
static void FreeWorkerInfo(int code, Datum arg)
Definition: autovacuum.c:1730
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:274
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
static void av_sighup_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1411
sigjmp_buf * PG_exception_stack
Definition: elog.c:90
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, char *out_dbname)
Definition: postinit.c:558
int errmsg(const char *fmt,...)
Definition: elog.c:797
void die(SIGNAL_ARGS)
Definition: postgres.c:2623
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2675
static dsa_area * AutoVacuumDSA
Definition: autovacuum.c:310
PGPROC * wi_proc
Definition: autovacuum.c:224
#define elog
Definition: elog.h:219
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:260
dlist_head av_runningWorkers
Definition: autovacuum.c:268
#define SIGCHLD
Definition: win32.h:198
void pgstat_report_autovac(Oid dboid)
Definition: pgstat.c:1383
void quickdie(SIGNAL_ARGS)
Definition: postgres.c:2562
#define SIGUSR2
Definition: win32.h:203
void init_ps_display(const char *username, const char *dbname, const char *host_info, const char *initial_str)
Definition: ps_status.c:244
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:721
static void av_sighup_handler ( SIGNAL_ARGS  )
static

Definition at line 1411 of file autovacuum.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by AutoVacLauncherMain(), and AutoVacWorkerMain().

1412 {
1413  int save_errno = errno;
1414 
1415  got_SIGHUP = true;
1416  SetLatch(MyLatch);
1417 
1418  errno = save_errno;
1419 }
static volatile sig_atomic_t got_SIGHUP
Definition: autovacuum.c:140
void SetLatch(volatile Latch *latch)
Definition: latch.c:415
struct Latch * MyLatch
Definition: globals.c:51
static void avl_sigterm_handler ( SIGNAL_ARGS  )
static

Definition at line 1435 of file autovacuum.c.

References got_SIGTERM, MyLatch, and SetLatch().

Referenced by AutoVacLauncherMain().

1436 {
1437  int save_errno = errno;
1438 
1439  got_SIGTERM = true;
1440  SetLatch(MyLatch);
1441 
1442  errno = save_errno;
1443 }
static volatile sig_atomic_t got_SIGTERM
Definition: autovacuum.c:142
void SetLatch(volatile Latch *latch)
Definition: latch.c:415
struct Latch * MyLatch
Definition: globals.c:51
static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1423 of file autovacuum.c.

References got_SIGUSR2, MyLatch, and SetLatch().

Referenced by AutoVacLauncherMain().

1424 {
1425  int save_errno = errno;
1426 
1427  got_SIGUSR2 = true;
1428  SetLatch(MyLatch);
1429 
1430  errno = save_errno;
1431 }
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:141
void SetLatch(volatile Latch *latch)
Definition: latch.c:415
struct Latch * MyLatch
Definition: globals.c:51
static int db_comparator ( const void *  a,
const void *  b 
)
static

Definition at line 1117 of file autovacuum.c.

Referenced by rebuild_database_list().

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

Definition at line 1949 of file autovacuum.c.

References AbortOutOfAnyTransaction(), AccessExclusiveLock, AccessShareLock, add_wi_to_list(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Anum_pg_class_relkind, 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_relid, autovac_table::at_relname, autovac_table::at_sharedrel, autovac_table::at_vacoptions, autovac_table::at_vacuum_cost_delay, autovac_table::at_vacuum_cost_limit, autovac_balance_cost(), autovacuum_do_vac_analyze(), AutoVacuumUpdateDelay(), AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_workitems, AutovacWorkItems::avs_freeItems, AutovacWorkItems::avs_usedItems, AutoVacuumWorkItem::avw_active, AutoVacuumWorkItem::avw_database, AutoVacuumWorkItem::avw_next, BackendIdGetProc(), BAS_VACUUM, BTEqualStrategyNumber, CharGetDatum, CHECK_FOR_INTERRUPTS, CommitTransactionCommand(), ConditionalLockRelationOid(), 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, dsa_get_address(), 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, GetTempNamespaceBackendId(), got_SIGHUP, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, HASH_FIND, hash_search(), heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, HOLD_INTERRUPTS, InvalidBackendId, InvalidDsaPointer, InvalidOid, HASHCTL::keysize, lappend_oid(), lfirst_oid, LOG, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), MemSet, MultiXactMemberFreezeThreshold(), MyBackendId, MyDatabaseId, NameStr, NIL, NULL, ObjectIdGetDatum, OidIsValid, 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, RelationRelationId, ReleaseSysCache(), RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_TOASTVALUE, RELOID, RELPERSISTENCE_TEMP, remove_wi_from_list(), RESUME_INTERRUPTS, ScanKeyInit(), SearchSysCache1, SearchSysCacheCopy1, StartTransactionCommand(), table_recheck_autovac(), TopMemoryContext, TopTransactionContext, 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().

1950 {
1951  Relation classRel;
1952  HeapTuple tuple;
1953  HeapScanDesc relScan;
1954  Form_pg_database dbForm;
1955  List *table_oids = NIL;
1956  List *orphan_oids = NIL;
1957  HASHCTL ctl;
1958  HTAB *table_toast_map;
1959  ListCell *volatile cell;
1960  PgStat_StatDBEntry *shared;
1961  PgStat_StatDBEntry *dbentry;
1962  BufferAccessStrategy bstrategy;
1963  ScanKeyData key;
1964  TupleDesc pg_class_desc;
1965  int effective_multixact_freeze_max_age;
1966  bool did_vacuum = false;
1967  bool found_concurrent_worker = false;
1968 
1969  /*
1970  * StartTransactionCommand and CommitTransactionCommand will automatically
1971  * switch to other contexts. We need this one to keep the list of
1972  * relations to vacuum/analyze across transactions.
1973  */
1975  "AV worker",
1978 
1979  /*
1980  * may be NULL if we couldn't find an entry (only happens if we are
1981  * forcing a vacuum for anti-wrap purposes).
1982  */
1984 
1985  /* Start a transaction so our commands have one to play into. */
1987 
1988  /*
1989  * Clean up any dead statistics collector entries for this DB. We always
1990  * want to do this exactly once per DB-processing cycle, even if we find
1991  * nothing worth vacuuming in the database.
1992  */
1994 
1995  /*
1996  * Compute the multixact age for which freezing is urgent. This is
1997  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
1998  * short of multixact member space.
1999  */
2000  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
2001 
2002  /*
2003  * Find the pg_database entry and select the default freeze ages. We use
2004  * zero in template and nonconnectable databases, else the system-wide
2005  * default.
2006  */
2008  if (!HeapTupleIsValid(tuple))
2009  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
2010  dbForm = (Form_pg_database) GETSTRUCT(tuple);
2011 
2012  if (dbForm->datistemplate || !dbForm->datallowconn)
2013  {
2018  }
2019  else
2020  {
2025  }
2026 
2027  ReleaseSysCache(tuple);
2028 
2029  /* StartTransactionCommand changed elsewhere */
2031 
2032  /* The database hash where pgstat keeps shared relations */
2034 
2036 
2037  /* create a copy so we can use it after closing pg_class */
2038  pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
2039 
2040  /* create hash table for toast <-> main relid mapping */
2041  MemSet(&ctl, 0, sizeof(ctl));
2042  ctl.keysize = sizeof(Oid);
2043  ctl.entrysize = sizeof(av_relation);
2044 
2045  table_toast_map = hash_create("TOAST to main relid map",
2046  100,
2047  &ctl,
2048  HASH_ELEM | HASH_BLOBS);
2049 
2050  /*
2051  * Scan pg_class to determine which tables to vacuum.
2052  *
2053  * We do this in two passes: on the first one we collect the list of plain
2054  * relations and materialized views, and on the second one we collect
2055  * TOAST tables. The reason for doing the second pass is that during it we
2056  * want to use the main relation's pg_class.reloptions entry if the TOAST
2057  * table does not have any, and we cannot obtain it unless we know
2058  * beforehand what's the main table OID.
2059  *
2060  * We need to check TOAST tables separately because in cases with short,
2061  * wide tables there might be proportionally much more activity in the
2062  * TOAST table than in its parent.
2063  */
2064  relScan = heap_beginscan_catalog(classRel, 0, NULL);
2065 
2066  /*
2067  * On the first pass, we collect main tables to vacuum, and also the main
2068  * table relid to TOAST relid mapping.
2069  */
2070  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2071  {
2072  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2073  PgStat_StatTabEntry *tabentry;
2074  AutoVacOpts *relopts;
2075  Oid relid;
2076  bool dovacuum;
2077  bool doanalyze;
2078  bool wraparound;
2079 
2080  if (classForm->relkind != RELKIND_RELATION &&
2081  classForm->relkind != RELKIND_MATVIEW)
2082  continue;
2083 
2084  relid = HeapTupleGetOid(tuple);
2085 
2086  /*
2087  * Check if it is a temp table (presumably, of some other backend's).
2088  * We cannot safely process other backends' temp tables.
2089  */
2090  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2091  {
2092  int backendID;
2093 
2094  backendID = GetTempNamespaceBackendId(classForm->relnamespace);
2095 
2096  /* We just ignore it if the owning backend is still active */
2097  if (backendID != InvalidBackendId &&
2098  (backendID == MyBackendId ||
2099  BackendIdGetProc(backendID) == NULL))
2100  {
2101  /*
2102  * The table seems to be orphaned -- although it might be that
2103  * the owning backend has already deleted it and exited; our
2104  * pg_class scan snapshot is not necessarily up-to-date
2105  * anymore, so we could be looking at a committed-dead entry.
2106  * Remember it so we can try to delete it later.
2107  */
2108  orphan_oids = lappend_oid(orphan_oids, relid);
2109  }
2110  continue;
2111  }
2112 
2113  /* Fetch reloptions and the pgstat entry for this table */
2114  relopts = extract_autovac_opts(tuple, pg_class_desc);
2115  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
2116  shared, dbentry);
2117 
2118  /* Check if it needs vacuum or analyze */
2119  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2120  effective_multixact_freeze_max_age,
2121  &dovacuum, &doanalyze, &wraparound);
2122 
2123  /* Relations that need work are added to table_oids */
2124  if (dovacuum || doanalyze)
2125  table_oids = lappend_oid(table_oids, relid);
2126 
2127  /*
2128  * Remember TOAST associations for the second pass. Note: we must do
2129  * this whether or not the table is going to be vacuumed, because we
2130  * don't automatically vacuum toast tables along the parent table.
2131  */
2132  if (OidIsValid(classForm->reltoastrelid))
2133  {
2134  av_relation *hentry;
2135  bool found;
2136 
2137  hentry = hash_search(table_toast_map,
2138  &classForm->reltoastrelid,
2139  HASH_ENTER, &found);
2140 
2141  if (!found)
2142  {
2143  /* hash_search already filled in the key */
2144  hentry->ar_relid = relid;
2145  hentry->ar_hasrelopts = false;
2146  if (relopts != NULL)
2147  {
2148  hentry->ar_hasrelopts = true;
2149  memcpy(&hentry->ar_reloptions, relopts,
2150  sizeof(AutoVacOpts));
2151  }
2152  }
2153  }
2154  }
2155 
2156  heap_endscan(relScan);
2157 
2158  /* second pass: check TOAST tables */
2159  ScanKeyInit(&key,
2161  BTEqualStrategyNumber, F_CHAREQ,
2163 
2164  relScan = heap_beginscan_catalog(classRel, 1, &key);
2165  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2166  {
2167  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2168  PgStat_StatTabEntry *tabentry;
2169  Oid relid;
2170  AutoVacOpts *relopts = NULL;
2171  bool dovacuum;
2172  bool doanalyze;
2173  bool wraparound;
2174 
2175  /*
2176  * We cannot safely process other backends' temp tables, so skip 'em.
2177  */
2178  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2179  continue;
2180 
2181  relid = HeapTupleGetOid(tuple);
2182 
2183  /*
2184  * fetch reloptions -- if this toast table does not have them, try the
2185  * main rel
2186  */
2187  relopts = extract_autovac_opts(tuple, pg_class_desc);
2188  if (relopts == NULL)
2189  {
2190  av_relation *hentry;
2191  bool found;
2192 
2193  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2194  if (found && hentry->ar_hasrelopts)
2195  relopts = &hentry->ar_reloptions;
2196  }
2197 
2198  /* Fetch the pgstat entry for this table */
2199  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
2200  shared, dbentry);
2201 
2202  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2203  effective_multixact_freeze_max_age,
2204  &dovacuum, &doanalyze, &wraparound);
2205 
2206  /* ignore analyze for toast tables */
2207  if (dovacuum)
2208  table_oids = lappend_oid(table_oids, relid);
2209  }
2210 
2211  heap_endscan(relScan);
2212  heap_close(classRel, AccessShareLock);
2213 
2214  /*
2215  * Recheck orphan temporary tables, and if they still seem orphaned, drop
2216  * them. We'll eat a transaction per dropped table, which might seem
2217  * excessive, but we should only need to do anything as a result of a
2218  * previous backend crash, so this should not happen often enough to
2219  * justify "optimizing". Using separate transactions ensures that we
2220  * don't bloat the lock table if there are many temp tables to be dropped,
2221  * and it ensures that we don't lose work if a deletion attempt fails.
2222  */
2223  foreach(cell, orphan_oids)
2224  {
2225  Oid relid = lfirst_oid(cell);
2226  Form_pg_class classForm;
2227  int backendID;
2228  ObjectAddress object;
2229 
2230  /*
2231  * Check for user-requested abort.
2232  */
2234 
2235  /*
2236  * Try to lock the table. If we can't get the lock immediately,
2237  * somebody else is using (or dropping) the table, so it's not our
2238  * concern anymore. Having the lock prevents race conditions below.
2239  */
2241  continue;
2242 
2243  /*
2244  * Re-fetch the pg_class tuple and re-check whether it still seems to
2245  * be an orphaned temp table. If it's not there or no longer the same
2246  * relation, ignore it.
2247  */
2248  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2249  if (!HeapTupleIsValid(tuple))
2250  {
2251  /* be sure to drop useless lock so we don't bloat lock table */
2253  continue;
2254  }
2255  classForm = (Form_pg_class) GETSTRUCT(tuple);
2256 
2257  /*
2258  * Make all the same tests made in the loop above. In event of OID
2259  * counter wraparound, the pg_class entry we have now might be
2260  * completely unrelated to the one we saw before.
2261  */
2262  if (!((classForm->relkind == RELKIND_RELATION ||
2263  classForm->relkind == RELKIND_MATVIEW) &&
2264  classForm->relpersistence == RELPERSISTENCE_TEMP))
2265  {
2267  continue;
2268  }
2269  backendID = GetTempNamespaceBackendId(classForm->relnamespace);
2270  if (!(backendID != InvalidBackendId &&
2271  (backendID == MyBackendId ||
2272  BackendIdGetProc(backendID) == NULL)))
2273  {
2275  continue;
2276  }
2277 
2278  /* OK, let's delete it */
2279  ereport(LOG,
2280  (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2282  get_namespace_name(classForm->relnamespace),
2283  NameStr(classForm->relname))));
2284 
2285  object.classId = RelationRelationId;
2286  object.objectId = relid;
2287  object.objectSubId = 0;
2288  performDeletion(&object, DROP_CASCADE,
2292 
2293  /*
2294  * To commit the deletion, end current transaction and start a new
2295  * one. Note this also releases the lock we took.
2296  */
2299 
2300  /* StartTransactionCommand changed current memory context */
2302  }
2303 
2304  /*
2305  * Create a buffer access strategy object for VACUUM to use. We want to
2306  * use the same one across all the vacuum operations we perform, since the
2307  * point is for VACUUM not to blow out the shared cache.
2308  */
2309  bstrategy = GetAccessStrategy(BAS_VACUUM);
2310 
2311  /*
2312  * create a memory context to act as fake PortalContext, so that the
2313  * contexts created in the vacuum code are cleaned up for each table.
2314  */
2316  "Autovacuum Portal",
2318 
2319  /*
2320  * Perform operations on collected tables.
2321  */
2322  foreach(cell, table_oids)
2323  {
2324  Oid relid = lfirst_oid(cell);
2325  autovac_table *tab;
2326  bool skipit;
2327  int stdVacuumCostDelay;
2328  int stdVacuumCostLimit;
2329  dlist_iter iter;
2330 
2332 
2333  /*
2334  * Check for config changes before processing each collected table.
2335  */
2336  if (got_SIGHUP)
2337  {
2338  got_SIGHUP = false;
2340 
2341  /*
2342  * You might be tempted to bail out if we see autovacuum is now
2343  * disabled. Must resist that temptation -- this might be a
2344  * for-wraparound emergency worker, in which case that would be
2345  * entirely inappropriate.
2346  */
2347  }
2348 
2349  /*
2350  * hold schedule lock from here until we're sure that this table still
2351  * needs vacuuming. We also need the AutovacuumLock to walk the
2352  * worker array, but we'll let go of that one quickly.
2353  */
2354  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2355  LWLockAcquire(AutovacuumLock, LW_SHARED);
2356 
2357  /*
2358  * Check whether the table is being vacuumed concurrently by another
2359  * worker.
2360  */
2361  skipit = false;
2363  {
2364  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2365 
2366  /* ignore myself */
2367  if (worker == MyWorkerInfo)
2368  continue;
2369 
2370  /* ignore workers in other databases (unless table is shared) */
2371  if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2372  continue;
2373 
2374  if (worker->wi_tableoid == relid)
2375  {
2376  skipit = true;
2377  found_concurrent_worker = true;
2378  break;
2379  }
2380  }
2381  LWLockRelease(AutovacuumLock);
2382  if (skipit)
2383  {
2384  LWLockRelease(AutovacuumScheduleLock);
2385  continue;
2386  }
2387 
2388  /*
2389  * Check whether pgstat data still says we need to vacuum this table.
2390  * It could have changed if something else processed the table while
2391  * we weren't looking.
2392  *
2393  * Note: we have a special case in pgstat code to ensure that the
2394  * stats we read are as up-to-date as possible, to avoid the problem
2395  * that somebody just finished vacuuming this table. The window to
2396  * the race condition is not closed but it is very small.
2397  */
2399  tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
2400  effective_multixact_freeze_max_age);
2401  if (tab == NULL)
2402  {
2403  /* someone else vacuumed the table, or it went away */
2404  LWLockRelease(AutovacuumScheduleLock);
2405  continue;
2406  }
2407 
2408  /*
2409  * Ok, good to go. Store the table in shared memory before releasing
2410  * the lock so that other workers don't vacuum it concurrently.
2411  */
2412  MyWorkerInfo->wi_tableoid = relid;
2414  LWLockRelease(AutovacuumScheduleLock);
2415 
2416  /*
2417  * Remember the prevailing values of the vacuum cost GUCs. We have to
2418  * restore these at the bottom of the loop, else we'll compute wrong
2419  * values in the next iteration of autovac_balance_cost().
2420  */
2421  stdVacuumCostDelay = VacuumCostDelay;
2422  stdVacuumCostLimit = VacuumCostLimit;
2423 
2424  /* Must hold AutovacuumLock while mucking with cost balance info */
2425  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2426 
2427  /* advertise my cost delay parameters for the balancing algorithm */
2432 
2433  /* do a balance */
2435 
2436  /* set the active cost parameters from the result of that */
2438 
2439  /* done */
2440  LWLockRelease(AutovacuumLock);
2441 
2442  /* clean up memory before each iteration */
2444 
2445  /*
2446  * Save the relation name for a possible error message, to avoid a
2447  * catalog lookup in case of an error. If any of these return NULL,
2448  * then the relation has been dropped since last we checked; skip it.
2449  * Note: they must live in a long-lived memory context because we call
2450  * vacuum and analyze in different transactions.
2451  */
2452 
2453  tab->at_relname = get_rel_name(tab->at_relid);
2456  if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2457  goto deleted;
2458 
2459  /*
2460  * We will abort vacuuming the current table if something errors out,
2461  * and continue with the next one in schedule; in particular, this
2462  * happens if we are interrupted with SIGINT.
2463  */
2464  PG_TRY();
2465  {
2466  /* have at it */
2468  autovacuum_do_vac_analyze(tab, bstrategy);
2469 
2470  /*
2471  * Clear a possible query-cancel signal, to avoid a late reaction
2472  * to an automatically-sent signal because of vacuuming the
2473  * current table (we're done with it, so it would make no sense to
2474  * cancel at this point.)
2475  */
2476  QueryCancelPending = false;
2477  }
2478  PG_CATCH();
2479  {
2480  /*
2481  * Abort the transaction, start a new one, and proceed with the
2482  * next table in our list.
2483  */
2484  HOLD_INTERRUPTS();
2485  if (tab->at_vacoptions & VACOPT_VACUUM)
2486  errcontext("automatic vacuum of table \"%s.%s.%s\"",
2487  tab->at_datname, tab->at_nspname, tab->at_relname);
2488  else
2489  errcontext("automatic analyze of table \"%s.%s.%s\"",
2490  tab->at_datname, tab->at_nspname, tab->at_relname);
2491  EmitErrorReport();
2492 
2493  /* this resets the PGXACT flags too */
2495  FlushErrorState();
2497 
2498  /* restart our transaction for the following operations */
2501  }
2502  PG_END_TRY();
2503 
2504  did_vacuum = true;
2505 
2506  /* the PGXACT flags are reset at the next end of transaction */
2507 
2508  /* be tidy */
2509 deleted:
2510  if (tab->at_datname != NULL)
2511  pfree(tab->at_datname);
2512  if (tab->at_nspname != NULL)
2513  pfree(tab->at_nspname);
2514  if (tab->at_relname != NULL)
2515  pfree(tab->at_relname);
2516  pfree(tab);
2517 
2518  /*
2519  * Remove my info from shared memory. We could, but intentionally
2520  * don't, clear wi_cost_limit and friends --- this is on the
2521  * assumption that we probably have more to do with similar cost
2522  * settings, so we don't want to give up our share of I/O for a very
2523  * short interval and thereby thrash the global balance.
2524  */
2525  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2527  MyWorkerInfo->wi_sharedrel = false;
2528  LWLockRelease(AutovacuumLock);
2529 
2530  /* restore vacuum cost GUCs for the next iteration */
2531  VacuumCostDelay = stdVacuumCostDelay;
2532  VacuumCostLimit = stdVacuumCostLimit;
2533  }
2534 
2535  /*
2536  * Perform additional work items, as requested by backends.
2537  */
2539  {
2540  dsa_pointer wi_ptr;
2541  AutovacWorkItems *workitems;
2542 
2543  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2544 
2545  /*
2546  * Scan the list of pending items, and process the inactive ones in
2547  * our database.
2548  */
2549  workitems = (AutovacWorkItems *)
2551  wi_ptr = workitems->avs_usedItems;
2552 
2553  while (wi_ptr != InvalidDsaPointer)
2554  {
2555  AutoVacuumWorkItem *workitem;
2556 
2557  workitem = (AutoVacuumWorkItem *)
2558  dsa_get_address(AutoVacuumDSA, wi_ptr);
2559 
2560  if (workitem->avw_database == MyDatabaseId && !workitem->avw_active)
2561  {
2562  dsa_pointer next_ptr;
2563 
2564  /* claim this one */
2565  workitem->avw_active = true;
2566 
2567  LWLockRelease(AutovacuumLock);
2568 
2569  perform_work_item(workitem);
2570 
2571  /*
2572  * Check for config changes before acquiring lock for further
2573  * jobs.
2574  */
2576  if (got_SIGHUP)
2577  {
2578  got_SIGHUP = false;
2580  }
2581 
2582  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2583 
2584  /* Put the array item back for the next user */
2585  next_ptr = workitem->avw_next;
2586  remove_wi_from_list(&workitems->avs_usedItems, wi_ptr);
2587  add_wi_to_list(&workitems->avs_freeItems, wi_ptr);
2588  wi_ptr = next_ptr;
2589  }
2590  else
2591  wi_ptr = workitem->avw_next;
2592  }
2593 
2594  /* all done */
2595  LWLockRelease(AutovacuumLock);
2596  }
2597 
2598  /*
2599  * We leak table_toast_map here (among other things), but since we're
2600  * going away soon, it's not a problem.
2601  */
2602 
2603  /*
2604  * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2605  * only need to do this once, not after each table.
2606  *
2607  * Even if we didn't vacuum anything, it may still be important to do
2608  * this, because one indirect effect of vac_update_datfrozenxid() is to
2609  * update ShmemVariableCache->xidVacLimit. That might need to be done
2610  * even if we haven't vacuumed anything, because relations with older
2611  * relfrozenxid values or other databases with older datfrozenxid values
2612  * might have been dropped, allowing xidVacLimit to advance.
2613  *
2614  * However, it's also important not to do this blindly in all cases,
2615  * because when autovacuum=off this will restart the autovacuum launcher.
2616  * If we're not careful, an infinite loop can result, where workers find
2617  * no work to do and restart the launcher, which starts another worker in
2618  * the same database that finds no work to do. To prevent that, we skip
2619  * this if (1) we found no work to do and (2) we skipped at least one
2620  * table due to concurrent autovacuum activity. In that case, the other
2621  * worker has already done it, or will do so when it finishes.
2622  */
2623  if (did_vacuum || !found_concurrent_worker)
2625 
2626  /* Finally close out the last transaction. */
2628 }
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:525
#define NIL
Definition: pg_list.h:69
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:138
static int default_freeze_table_age
Definition: autovacuum.c:150
static void remove_wi_from_list(dsa_pointer *list, dsa_pointer wi_ptr)
Definition: autovacuum.c:3465
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:141
BackendId MyBackendId
Definition: globals.c:72
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
static void autovac_balance_cost(void)
Definition: autovacuum.c:1795
MemoryContext TopTransactionContext
Definition: mcxt.c:48
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:61
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
int at_vacuum_cost_delay
Definition: autovacuum.c:192
#define InvalidDsaPointer
Definition: dsa.h:78
#define HASH_ELEM
Definition: hsearch.h:87
void ProcessConfigFile(GucContext context)
void vac_update_datfrozenxid(void)
Definition: vacuum.c:922
static int default_multixact_freeze_min_age
Definition: autovacuum.c:151
#define RelationGetDescr(relation)
Definition: rel.h:429
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:182
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
void CommitTransactionCommand(void)
Definition: xact.c:2749
#define RelationRelationId
Definition: pg_class.h:29
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:155
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1750
#define RELKIND_MATVIEW
Definition: pg_class.h:165
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
Size entrysize
Definition: hsearch.h:73
#define MemSet(start, val, len)
Definition: c.h:857
static volatile sig_atomic_t got_SIGHUP
Definition: autovacuum.c:140
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2387
int GetTempNamespaceBackendId(Oid namespaceId)
Definition: namespace.c:3152
#define heap_close(r, l)
Definition: heapam.h:97
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
char * at_datname
Definition: autovacuum.c:198
#define LOG
Definition: elog.h:26
unsigned int Oid
Definition: postgres_ext.h:31
volatile bool QueryCancelPending
Definition: globals.c:30
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:538
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4224
void FlushErrorState(void)
Definition: elog.c:1587
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
uint64 dsa_pointer
Definition: dsa.h:62
MemoryContext PortalContext
Definition: mcxt.c:52
bool at_sharedrel
Definition: autovacuum.c:195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:116
#define Anum_pg_class_relkind
Definition: pg_class.h:118
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:924
int at_vacuum_cost_limit
Definition: autovacuum.c:193
Definition: dynahash.c:193
char * at_relname
Definition: autovacuum.c:196
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
void pfree(void *pointer)
Definition: mcxt.c:950
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
int VacuumCostLimit
Definition: globals.c:131
dsa_pointer avw_next
Definition: autovacuum.c:299
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:60
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
static void add_wi_to_list(dsa_pointer *list, dsa_pointer wi_ptr)
Definition: autovacuum.c:3492
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
Definition: autovacuum.c:2734
dsa_pointer avs_freeItems
Definition: autovacuum.c:307
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:303
static PgStat_StatTabEntry * get_pgstat_tabentry_relid(Oid relid, bool isshared, PgStat_StatDBEntry *shared, PgStat_StatDBEntry *dbentry)
Definition: autovacuum.c:2760
static void perform_work_item(AutoVacuumWorkItem *workitem)
Definition: autovacuum.c:2634
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:284
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
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:2969
#define ereport(elevel, rest)
Definition: elog.h:122
void pgstat_vacuum_stat(void)
Definition: pgstat.c:1022
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2817
int wi_cost_limit_base
Definition: autovacuum.c:230
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define HASH_BLOBS
Definition: hsearch.h:88
char * at_nspname
Definition: autovacuum.c:197
#define InvalidBackendId
Definition: backendid.h:23
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:301
dsa_pointer av_workitems
Definition: autovacuum.c:271
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Oid MyDatabaseId
Definition: globals.c:76
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
Size keysize
Definition: hsearch.h:72
dlist_node * cur
Definition: ilist.h:161
void EmitErrorReport(void)
Definition: elog.c:1446
dsa_pointer avs_usedItems
Definition: autovacuum.c:306
#define InvalidOid
Definition: postgres_ext.h:36
int VacuumCostDelay
Definition: globals.c:132
#define PG_CATCH()
Definition: elog.h:293
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:176
void StartTransactionCommand(void)
Definition: xact.c:2679
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:274
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
int vacuum_freeze_min_age
Definition: vacuum.c:58
int vacuum_freeze_table_age
Definition: vacuum.c:59
#define CharGetDatum(X)
Definition: postgres.h:422
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:165
AutoVacOpts ar_reloptions
Definition: autovacuum.c:182
#define AccessExclusiveLock
Definition: lockdefs.h:46
static void autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
Definition: autovacuum.c:3114
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
static dsa_area * AutoVacuumDSA
Definition: autovacuum.c:310
#define errcontext
Definition: elog.h:164
#define NameStr(name)
Definition: c.h:499
struct av_relation av_relation
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
void AutoVacuumUpdateDelay(void)
Definition: autovacuum.c:1779
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
dlist_head av_runningWorkers
Definition: autovacuum.c:268
#define PG_TRY()
Definition: elog.h:284
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:178
#define RELKIND_RELATION
Definition: pg_class.h:160
bool ar_hasrelopts
Definition: autovacuum.c:181
Definition: pg_list.h:45
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
static int default_multixact_freeze_table_age
Definition: autovacuum.c:152
static int default_freeze_min_age
Definition: autovacuum.c:149
#define PG_END_TRY()
Definition: elog.h:300
#define BTEqualStrategyNumber
Definition: stratnum.h:31
bool at_dobalance
Definition: autovacuum.c:194
#define lfirst_oid(lc)
Definition: pg_list.h:108
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:2787
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:174
PGPROC * BackendIdGetProc(int backendID)
Definition: sinvaladt.c:377
static Oid do_start_worker ( void  )
static

Definition at line 1137 of file autovacuum.c.

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

Referenced by AutoVacLauncherMain(), and launch_worker().

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

Definition at line 2734 of file autovacuum.c.

References Assert, av, extractRelOptions(), GETSTRUCT, NULL, palloc(), pfree(), RELKIND_MATVIEW, RELKIND_RELATION, and RELKIND_TOASTVALUE.

Referenced by do_autovacuum(), and table_recheck_autovac().

2735 {
2736  bytea *relopts;
2737  AutoVacOpts *av;
2738 
2739  Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2740  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2741  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2742 
2743  relopts = extractRelOptions(tup, pg_class_desc, NULL);
2744  if (relopts == NULL)
2745  return NULL;
2746 
2747  av = palloc(sizeof(AutoVacOpts));
2748  memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2749  pfree(relopts);
2750 
2751  return av;
2752 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RELKIND_MATVIEW
Definition: pg_class.h:165
void pfree(void *pointer)
Definition: mcxt.c:950
struct @18::@19 av[32]
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
Definition: reloptions.c:956
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
void * palloc(Size size)
Definition: mcxt.c:849
Definition: c.h:439
#define RELKIND_RELATION
Definition: pg_class.h:160
static void FreeWorkerInfo ( int  code,
Datum  arg 
)
static

Definition at line 1730 of file autovacuum.c.

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

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

Definition at line 1883 of file autovacuum.c.

References AccessShareLock, avw_dbase::adw_datid, avw_dbase::adw_entry, avw_dbase::adw_frozenxid, avw_dbase::adw_minmulti, avw_dbase::adw_name, CommitTransactionCommand(), CurrentMemoryContext, DatabaseRelationId, dblist, ForwardScanDirection, GETSTRUCT, GetTransactionSnapshot(), heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, lappend(), MemoryContextSwitchTo(), NameStr, NIL, NULL, palloc(), pstrdup(), and StartTransactionCommand().

Referenced by do_start_worker(), and rebuild_database_list().

1884 {
1885  List *dblist = NIL;
1886  Relation rel;
1887  HeapScanDesc scan;
1888  HeapTuple tup;
1889  MemoryContext resultcxt;
1890 
1891  /* This is the context that we will allocate our output data in */
1892  resultcxt = CurrentMemoryContext;
1893 
1894  /*
1895  * Start a transaction so we can access pg_database, and get a snapshot.
1896  * We don't have a use for the snapshot itself, but we're interested in
1897  * the secondary effect that it sets RecentGlobalXmin. (This is critical
1898  * for anything that reads heap pages, because HOT may decide to prune
1899  * them even if the process doesn't attempt to modify any tuples.)
1900  */
1902  (void) GetTransactionSnapshot();
1903 
1905  scan = heap_beginscan_catalog(rel, 0, NULL);
1906 
1907  while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1908  {
1909  Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1910  avw_dbase *avdb;
1911  MemoryContext oldcxt;
1912 
1913  /*
1914  * Allocate our results in the caller's context, not the
1915  * transaction's. We do this inside the loop, and restore the original
1916  * context at the end, so that leaky things like heap_getnext() are
1917  * not called in a potentially long-lived context.
1918  */
1919  oldcxt = MemoryContextSwitchTo(resultcxt);
1920 
1921  avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1922 
1923  avdb->adw_datid = HeapTupleGetOid(tup);
1924  avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1925  avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1926  avdb->adw_minmulti = pgdatabase->datminmxid;
1927  /* this gets set later: */
1928  avdb->adw_entry = NULL;
1929 
1930  dblist = lappend(dblist, avdb);
1931  MemoryContextSwitchTo(oldcxt);
1932  }
1933 
1934  heap_endscan(scan);
1936 
1938 
1939  return dblist;
1940 }
#define NIL
Definition: pg_list.h:69
MultiXactId adw_minmulti
Definition: autovacuum.c:172
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
char * pstrdup(const char *in)
Definition: mcxt.c:1077
#define DatabaseRelationId
Definition: pg_database.h:29
void CommitTransactionCommand(void)
Definition: xact.c:2749
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
#define heap_close(r, l)
Definition: heapam.h:97
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
_stringlist * dblist
Definition: pg_regress.c:72
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1399
char * adw_name
Definition: autovacuum.c:170
List * lappend(List *list, void *datum)
Definition: list.c:128
TransactionId adw_frozenxid
Definition: autovacuum.c:171
PgStat_StatDBEntry * adw_entry
Definition: autovacuum.c:173
Oid adw_datid
Definition: autovacuum.c:169
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
void StartTransactionCommand(void)
Definition: xact.c:2679
void * palloc(Size size)
Definition: mcxt.c:849
#define NameStr(name)
Definition: c.h:499
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
Definition: pg_list.h:45
static PgStat_StatTabEntry * get_pgstat_tabentry_relid ( Oid  relid,
bool  isshared,
PgStat_StatDBEntry shared,
PgStat_StatDBEntry dbentry 
)
static

Definition at line 2760 of file autovacuum.c.

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

Referenced by do_autovacuum(), and table_recheck_autovac().

2762 {
2763  PgStat_StatTabEntry *tabentry = NULL;
2764 
2765  if (isshared)
2766  {
2767  if (PointerIsValid(shared))
2768  tabentry = hash_search(shared->tables, &relid,
2769  HASH_FIND, NULL);
2770  }
2771  else if (PointerIsValid(dbentry))
2772  tabentry = hash_search(dbentry->tables, &relid,
2773  HASH_FIND, NULL);
2774 
2775  return tabentry;
2776 }
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
#define NULL
Definition: c.h:229
#define PointerIsValid(pointer)
Definition: c.h:526
bool IsAutoVacuumLauncherProcess ( void  )

Definition at line 3354 of file autovacuum.c.

References am_autovacuum_launcher.

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

3355 {
3356  return am_autovacuum_launcher;
3357 }
static bool am_autovacuum_launcher
Definition: autovacuum.c:136
static void launch_worker ( TimestampTz  now)
static

Definition at line 1352 of file autovacuum.c.

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

Referenced by AutoVacLauncherMain().

1353 {
1354  Oid dbid;
1355  dlist_iter iter;
1356 
1357  dbid = do_start_worker();
1358  if (OidIsValid(dbid))
1359  {
1360  bool found = false;
1361 
1362  /*
1363  * Walk the database list and update the corresponding entry. If the
1364  * database is not on the list, we'll recreate the list.
1365  */
1366  dlist_foreach(iter, &DatabaseList)
1367  {
1368  avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1369 
1370  if (avdb->adl_datid == dbid)
1371  {
1372  found = true;
1373 
1374  /*
1375  * add autovacuum_naptime seconds to the current time, and use
1376  * that as the new "next_worker" field for this database.
1377  */
1378  avdb->adl_next_worker =
1380 
1382  break;
1383  }
1384  }
1385 
1386  /*
1387  * If the database was not present in the database list, we rebuild
1388  * the list. It's possible that the database does not get into the
1389  * list anyway, for example if it's a database that doesn't have a
1390  * pgstat entry, but this is not a problem because we don't want to
1391  * schedule workers regularly into those in any case.
1392  */
1393  if (!found)
1394  rebuild_database_list(dbid);
1395  }
1396 }
int autovacuum_naptime
Definition: autovacuum.c:115
TimestampTz adl_next_worker
Definition: autovacuum.c:161
#define dlist_foreach(iter, lhead)
Definition: ilist.h:507
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
Oid adl_datid
Definition: autovacuum.c:160
static dlist_head DatabaseList
Definition: autovacuum.c:280
dlist_node * cur
Definition: ilist.h:161
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
static void dlist_move_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:385
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:936
static Oid do_start_worker(void)
Definition: autovacuum.c:1137
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
static void launcher_determine_sleep ( bool  canlaunch,
bool  recursing,
struct timeval *  nap 
)
static

Definition at line 852 of file autovacuum.c.

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

Referenced by AutoVacLauncherMain().

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

Definition at line 2634 of file autovacuum.c.

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

Referenced by do_autovacuum().

2635 {
2636  char *cur_datname = NULL;
2637  char *cur_nspname = NULL;
2638  char *cur_relname = NULL;
2639 
2640  /*
2641  * Note we do not store table info in MyWorkerInfo, since this is not
2642  * vacuuming proper.
2643  */
2644 
2645  /*
2646  * Save the relation name for a possible error message, to avoid a catalog
2647  * lookup in case of an error. If any of these return NULL, then the
2648  * relation has been dropped since last we checked; skip it. Note: they
2649  * must live in a long-lived memory context because we call vacuum and
2650  * analyze in different transactions.
2651  */
2652 
2653  cur_relname = get_rel_name(workitem->avw_relation);
2654  cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2655  cur_datname = get_database_name(MyDatabaseId);
2656  if (!cur_relname || !cur_nspname || !cur_datname)
2657  goto deleted2;
2658 
2659  autovac_report_workitem(workitem, cur_nspname, cur_datname);
2660 
2661  /*
2662  * We will abort the current work item if something errors out, and
2663  * continue with the next one; in particular, this happens if we are
2664  * interrupted with SIGINT. Note that this means that the work item list
2665  * can be lossy.
2666  */
2667  PG_TRY();
2668  {
2669  /* have at it */
2671 
2672  switch (workitem->avw_type)
2673  {
2676  ObjectIdGetDatum(workitem->avw_relation),
2677  Int64GetDatum((int64) workitem->avw_blockNumber));
2678  break;
2679  default:
2680  elog(WARNING, "unrecognized work item found: type %d",
2681  workitem->avw_type);
2682  break;
2683  }
2684 
2685  /*
2686  * Clear a possible query-cancel signal, to avoid a late reaction to
2687  * an automatically-sent signal because of vacuuming the current table
2688  * (we're done with it, so it would make no sense to cancel at this
2689  * point.)
2690  */
2691  QueryCancelPending = false;
2692  }
2693  PG_CATCH();
2694  {
2695  /*
2696  * Abort the transaction, start a new one, and proceed with the next
2697  * table in our list.
2698  */
2699  HOLD_INTERRUPTS();
2700  errcontext("processing work entry for relation \"%s.%s.%s\"",
2701  cur_datname, cur_nspname, cur_relname);
2702  EmitErrorReport();
2703 
2704  /* this resets the PGXACT flags too */
2706  FlushErrorState();
2708 
2709  /* restart our transaction for the following operations */
2712  }
2713  PG_END_TRY();
2714 
2715  /* We intentionally do not set did_vacuum here */
2716 
2717  /* be tidy */
2718 deleted2:
2719  if (cur_datname)
2720  pfree(cur_datname);
2721  if (cur_nspname)
2722  pfree(cur_nspname);
2723  if (cur_relname)
2724  pfree(cur_relname);
2725 }
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:294
MemoryContext TopTransactionContext
Definition: mcxt.c:48
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1750
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
volatile bool QueryCancelPending
Definition: globals.c:30
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4224
void FlushErrorState(void)
Definition: elog.c:1587
MemoryContext PortalContext
Definition: mcxt.c:52
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:850
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:116
void pfree(void *pointer)
Definition: mcxt.c:950
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
Definition: autovacuum.c:3179
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1791
#define WARNING
Definition: elog.h:40
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
Oid MyDatabaseId
Definition: globals.c:76
BlockNumber avw_blockNumber
Definition: autovacuum.c:297
void EmitErrorReport(void)
Definition: elog.c:1446
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:229
void StartTransactionCommand(void)
Definition: xact.c:2679
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
#define errcontext
Definition: elog.h:164
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1726
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:586
#define PG_END_TRY()
Definition: elog.h:300
static void rebuild_database_list ( Oid  newdb)
static

Definition at line 936 of file autovacuum.c.

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

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

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

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

Referenced by do_autovacuum(), and table_recheck_autovac().

2978 {
2979  bool force_vacuum;
2980  bool av_enabled;
2981  float4 reltuples; /* pg_class.reltuples */
2982 
2983  /* constants from reloptions or GUC variables */
2984  int vac_base_thresh,
2985  anl_base_thresh;
2986  float4 vac_scale_factor,
2987  anl_scale_factor;
2988 
2989  /* thresholds calculated from above constants */
2990  float4 vacthresh,
2991  anlthresh;
2992 
2993  /* number of vacuum (resp. analyze) tuples at this time */
2994  float4 vactuples,
2995  anltuples;
2996 
2997  /* freeze parameters */
2998  int freeze_max_age;
2999  int multixact_freeze_max_age;
3000  TransactionId xidForceLimit;
3001  MultiXactId multiForceLimit;
3002 
3003  AssertArg(classForm != NULL);
3004  AssertArg(OidIsValid(relid));
3005 
3006  /*
3007  * Determine vacuum/analyze equation parameters. We have two possible
3008  * sources: the passed reloptions (which could be a main table or a toast
3009  * table), or the autovacuum GUC variables.
3010  */
3011 
3012  /* -1 in autovac setting means use plain vacuum_cost_delay */
3013  vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3014  ? relopts->vacuum_scale_factor
3016 
3017  vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3018  ? relopts->vacuum_threshold
3020 
3021  anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3022  ? relopts->analyze_scale_factor
3024 
3025  anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3026  ? relopts->analyze_threshold
3028 
3029  freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3032 
3033  multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3034  ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3035  : effective_multixact_freeze_max_age;
3036 
3037  av_enabled = (relopts ? relopts->enabled : true);
3038 
3039  /* Force vacuum if table is at risk of wraparound */
3040  xidForceLimit = recentXid - freeze_max_age;
3041  if (xidForceLimit < FirstNormalTransactionId)
3042  xidForceLimit -= FirstNormalTransactionId;
3043  force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
3044  TransactionIdPrecedes(classForm->relfrozenxid,
3045  xidForceLimit));
3046  if (!force_vacuum)
3047  {
3048  multiForceLimit = recentMulti - multixact_freeze_max_age;
3049  if (multiForceLimit < FirstMultiXactId)
3050  multiForceLimit -= FirstMultiXactId;
3051  force_vacuum = MultiXactIdPrecedes(classForm->relminmxid,
3052  multiForceLimit);
3053  }
3054  *wraparound = force_vacuum;
3055 
3056  /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3057  if (!av_enabled && !force_vacuum)
3058  {
3059  *doanalyze = false;
3060  *dovacuum = false;
3061  return;
3062  }
3063 
3064  /*
3065  * If we found the table in the stats hash, and autovacuum is currently
3066  * enabled, make a threshold-based decision whether to vacuum and/or
3067  * analyze. If autovacuum is currently disabled, we must be here for
3068  * anti-wraparound vacuuming only, so don't vacuum (or analyze) anything
3069  * that's not being forced.
3070  */
3071  if (PointerIsValid(tabentry) && AutoVacuumingActive())
3072  {
3073  reltuples = classForm->reltuples;
3074  vactuples = tabentry->n_dead_tuples;
3075  anltuples = tabentry->changes_since_analyze;
3076 
3077  vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3078  anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3079 
3080  /*
3081  * Note that we don't need to take special consideration for stat
3082  * reset, because if that happens, the last vacuum and analyze counts
3083  * will be reset too.
3084  */
3085  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3086  NameStr(classForm->relname),
3087  vactuples, vacthresh, anltuples, anlthresh);
3088 
3089  /* Determine if this table needs vacuum or analyze. */
3090  *dovacuum = force_vacuum || (vactuples > vacthresh);
3091  *doanalyze = (anltuples > anlthresh);
3092  }
3093  else
3094  {
3095  /*
3096  * Skip a table not found in stat hash, unless we have to force vacuum
3097  * for anti-wrap purposes. If it's not acted upon, there's no need to
3098  * vacuum it.
3099  */
3100  *dovacuum = force_vacuum;
3101  *doanalyze = false;
3102  }
3103 
3104  /* ANALYZE refuses to work with pg_statistic */
3105  if (relid == StatisticRelationId)
3106  *doanalyze = false;
3107 }
double autovacuum_anl_scale
Definition: autovacuum.c:119
uint32 TransactionId
Definition: c.h:397
#define DEBUG3
Definition: elog.h:23
float8 vacuum_scale_factor
Definition: rel.h:272
#define Min(x, y)
Definition: c.h:806
static MultiXactId recentMulti
Definition: autovacuum.c:146
#define OidIsValid(objectId)
Definition: c.h:538
#define FirstNormalTransactionId
Definition: transam.h:34
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3219
int autovacuum_freeze_max_age
Definition: autovacuum.c:120
PgStat_Counter n_dead_tuples
Definition: pgstat.h:630
int analyze_threshold
Definition: rel.h:262
int autovacuum_vac_thresh
Definition: autovacuum.c:116
#define FirstMultiXactId
Definition: multixact.h:24
#define AssertArg(condition)
Definition: c.h:677
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
float float4
Definition: c.h:380
int vacuum_threshold
Definition: rel.h:261
#define StatisticRelationId
Definition: pg_statistic.h:29
static TransactionId recentXid
Definition: autovacuum.c:145
PgStat_Counter changes_since_analyze
Definition: pgstat.h:631
double autovacuum_vac_scale
Definition: autovacuum.c:117
float8 analyze_scale_factor
Definition: rel.h:273
TransactionId MultiXactId
Definition: c.h:407
int freeze_max_age
Definition: rel.h:266
#define NULL
Definition: c.h:229
bool enabled
Definition: rel.h:260
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3140
#define NameStr(name)
Definition: c.h:499
int multixact_freeze_max_age
Definition: rel.h:269
#define elog
Definition: elog.h:219
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define PointerIsValid(pointer)
Definition: c.h:526
int autovacuum_anl_thresh
Definition: autovacuum.c:118
static void remove_wi_from_list ( dsa_pointer list,
dsa_pointer  wi_ptr 
)
static

Definition at line 3465 of file autovacuum.c.

References AutoVacuumWorkItem::avw_next, AutoVacuumWorkItem::avw_prev, dsa_get_address(), InvalidDsaPointer, and next.

Referenced by AutoVacuumRequestWork(), and do_autovacuum().

3466 {
3467  AutoVacuumWorkItem *workitem = dsa_get_address(AutoVacuumDSA, wi_ptr);
3468  dsa_pointer next = workitem->avw_next;
3469  dsa_pointer prev = workitem->avw_prev;
3470 
3471  workitem->avw_next = workitem->avw_prev = InvalidDsaPointer;
3472 
3473  if (next != InvalidDsaPointer)
3474  {
3475  workitem = dsa_get_address(AutoVacuumDSA, next);
3476  workitem->avw_prev = prev;
3477  }
3478 
3479  if (prev != InvalidDsaPointer)
3480  {
3481  workitem = dsa_get_address(AutoVacuumDSA, prev);
3482  workitem->avw_next = next;
3483  }
3484  else
3485  *list = next;
3486 }
static int32 next
Definition: blutils.c:210
#define InvalidDsaPointer
Definition: dsa.h:78
dsa_pointer avw_prev
Definition: autovacuum.c:300
uint64 dsa_pointer
Definition: dsa.h:62
void * dsa_get_address(dsa_area *area, dsa_pointer dp)
Definition: dsa.c:924
dsa_pointer avw_next
Definition: autovacuum.c:299
tuple list
Definition: sort-test.py:11
static dsa_area * AutoVacuumDSA
Definition: autovacuum.c:310
int StartAutoVacLauncher ( void  )

Definition at line 404 of file autovacuum.c.

References AutoVacLauncherMain(), AutoVacPID, ClosePostmasterPorts(), ereport, errmsg(), fork_process(), InitPostmasterChild(), LOG, and NULL.

Referenced by reaper(), and ServerLoop().

405 {
406  pid_t AutoVacPID;
407 
408 #ifdef EXEC_BACKEND
409  switch ((AutoVacPID = avlauncher_forkexec()))
410 #else
411  switch ((AutoVacPID = fork_process()))
412 #endif
413  {
414  case -1:
415  ereport(LOG,
416  (errmsg("could not fork autovacuum launcher process: %m")));
417  return 0;
418 
419 #ifndef EXEC_BACKEND
420  case 0:
421  /* in postmaster child ... */
423 
424  /* Close the postmaster's sockets */
425  ClosePostmasterPorts(false);
426 
428  break;
429 #endif
430  default:
431  return (int) AutoVacPID;
432  }
433 
434  /* shouldn't get here */
435  return 0;
436 }
void InitPostmasterChild(void)
Definition: miscinit.c:175
NON_EXEC_STATIC void AutoVacLauncherMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: autovacuum.c:442
pid_t fork_process(void)
Definition: fork_process.c:31
#define LOG
Definition: elog.h:26
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2435
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
static pid_t AutoVacPID
Definition: postmaster.c:252
int errmsg(const char *fmt,...)
Definition: elog.c:797
int StartAutoVacWorker ( void  )

Definition at line 1488 of file autovacuum.c.

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

Referenced by StartAutovacuumWorker().

1489 {
1490  pid_t worker_pid;
1491 
1492 #ifdef EXEC_BACKEND
1493  switch ((worker_pid = avworker_forkexec()))
1494 #else
1495  switch ((worker_pid = fork_process()))
1496 #endif
1497  {
1498  case -1:
1499  ereport(LOG,
1500  (errmsg("could not fork autovacuum worker process: %m")));
1501  return 0;
1502 
1503 #ifndef EXEC_BACKEND
1504  case 0:
1505  /* in postmaster child ... */
1507 
1508  /* Close the postmaster's sockets */
1509  ClosePostmasterPorts(false);
1510 
1511  AutoVacWorkerMain(0, NULL);
1512  break;
1513 #endif
1514  default:
1515  return (int) worker_pid;
1516  }
1517 
1518  /* shouldn't get here */
1519  return 0;
1520 }
void InitPostmasterChild(void)
Definition: miscinit.c:175
pid_t fork_process(void)
Definition: fork_process.c:31
#define LOG
Definition: elog.h:26
NON_EXEC_STATIC void AutoVacWorkerMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: autovacuum.c:1526
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2435
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
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 2787 of file autovacuum.c.

References av_relation::ar_hasrelopts, av_relation::ar_reloptions, autovac_table::at_datname, autovac_table::at_dobalance, autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relid, autovac_table::at_relname, autovac_table::at_sharedrel, autovac_table::at_vacoptions, autovac_table::at_vacuum_cost_delay, autovac_table::at_vacuum_cost_limit, autovac_refresh_stats(), autovacuum_vac_cost_delay, autovacuum_vac_cost_limit, default_freeze_min_age, default_freeze_table_age, default_multixact_freeze_min_age, default_multixact_freeze_table_age, extract_autovac_opts(), VacuumParams::freeze_min_age, AutoVacOpts::freeze_min_age, VacuumParams::freeze_table_age, AutoVacOpts::freeze_table_age, get_pgstat_tabentry_relid(), GETSTRUCT, HASH_FIND, hash_search(), heap_freetuple(), HeapTupleIsValid, InvalidOid, VacuumParams::is_wraparound, Log_autovacuum_min_duration, VacuumParams::log_min_duration, AutoVacOpts::log_min_duration, VacuumParams::multixact_freeze_min_age, AutoVacOpts::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, AutoVacOpts::multixact_freeze_table_age, MyDatabaseId, NULL, ObjectIdGetDatum, palloc(), pgstat_fetch_stat_dbentry(), relation_needs_vacanalyze(), RELKIND_TOASTVALUE, RELOID, SearchSysCacheCopy1, VACOPT_ANALYZE, VACOPT_NOWAIT, VACOPT_SKIPTOAST, VACOPT_VACUUM, AutoVacOpts::vacuum_cost_delay, AutoVacOpts::vacuum_cost_limit, VacuumCostDelay, and VacuumCostLimit.

Referenced by do_autovacuum().

2790 {
2791  Form_pg_class classForm;
2792  HeapTuple classTup;
2793  bool dovacuum;
2794  bool doanalyze;
2795  autovac_table *tab = NULL;
2796  PgStat_StatTabEntry *tabentry;
2797  PgStat_StatDBEntry *shared;
2798  PgStat_StatDBEntry *dbentry;
2799  bool wraparound;
2800  AutoVacOpts *avopts;
2801 
2802  /* use fresh stats */
2804 
2807 
2808  /* fetch the relation's relcache entry */
2809  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2810  if (!HeapTupleIsValid(classTup))
2811  return NULL;
2812  classForm = (Form_pg_class) GETSTRUCT(classTup);
2813 
2814  /*
2815  * Get the applicable reloptions. If it is a TOAST table, try to get the
2816  * main table reloptions if the toast table itself doesn't have.
2817  */
2818  avopts = extract_autovac_opts(classTup, pg_class_desc);
2819  if (classForm->relkind == RELKIND_TOASTVALUE &&
2820  avopts == NULL && table_toast_map != NULL)
2821  {
2822  av_relation *hentry;
2823  bool found;
2824 
2825  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2826  if (found && hentry->ar_hasrelopts)
2827  avopts = &hentry->ar_reloptions;
2828  }
2829 
2830  /* fetch the pgstat table entry */
2831  tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
2832  shared, dbentry);
2833 
2834  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2835  effective_multixact_freeze_max_age,
2836  &dovacuum, &doanalyze, &wraparound);
2837 
2838  /* ignore ANALYZE for toast tables */
2839  if (classForm->relkind == RELKIND_TOASTVALUE)
2840  doanalyze = false;
2841 
2842  /* OK, it needs something done */
2843  if (doanalyze || dovacuum)
2844  {
2845  int freeze_min_age;
2846  int freeze_table_age;
2847  int multixact_freeze_min_age;
2848  int multixact_freeze_table_age;
2849  int vac_cost_limit;
2850  int vac_cost_delay;
2851  int log_min_duration;
2852 
2853  /*
2854  * Calculate the vacuum cost parameters and the freeze ages. If there
2855  * are options set in pg_class.reloptions, use them; in the case of a
2856  * toast table, try the main table too. Otherwise use the GUC
2857  * defaults, autovacuum's own first and plain vacuum second.
2858  */
2859 
2860  /* -1 in autovac setting means use plain vacuum_cost_delay */
2861  vac_cost_delay = (avopts && avopts->vacuum_cost_delay >= 0)
2862  ? avopts->vacuum_cost_delay
2863  : (autovacuum_vac_cost_delay >= 0)
2865  : VacuumCostDelay;
2866 
2867  /* 0 or -1 in autovac setting means use plain vacuum_cost_limit */
2868  vac_cost_limit = (avopts && avopts->vacuum_cost_limit > 0)
2869  ? avopts->vacuum_cost_limit
2872  : VacuumCostLimit;
2873 
2874  /* -1 in autovac setting means use log_autovacuum_min_duration */
2875  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2876  ? avopts->log_min_duration
2878 
2879  /* these do not have autovacuum-specific settings */
2880  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2881  ? avopts->freeze_min_age
2883 
2884  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2885  ? avopts->freeze_table_age
2887 
2888  multixact_freeze_min_age = (avopts &&
2889  avopts->multixact_freeze_min_age >= 0)
2890  ? avopts->multixact_freeze_min_age
2892 
2893  multixact_freeze_table_age = (avopts &&
2894  avopts->multixact_freeze_table_age >= 0)
2895  ? avopts->multixact_freeze_table_age
2897 
2898  tab = palloc(sizeof(autovac_table));
2899  tab->at_relid = relid;
2900  tab->at_sharedrel = classForm->relisshared;
2902  (dovacuum ? VACOPT_VACUUM : 0) |
2903  (doanalyze ? VACOPT_ANALYZE : 0) |
2904  (!wraparound ? VACOPT_NOWAIT : 0);
2905  tab->at_params.freeze_min_age = freeze_min_age;
2906  tab->at_params.freeze_table_age = freeze_table_age;
2907  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2908  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2909  tab->at_params.is_wraparound = wraparound;
2910  tab->at_params.log_min_duration = log_min_duration;
2911  tab->at_vacuum_cost_limit = vac_cost_limit;
2912  tab->at_vacuum_cost_delay = vac_cost_delay;
2913  tab->at_relname = NULL;
2914  tab->at_nspname = NULL;
2915  tab->at_datname = NULL;
2916 
2917  /*
2918  * If any of the cost delay parameters has been set individually for
2919  * this table, disable the balancing algorithm.
2920  */
2921  tab->at_dobalance =
2922  !(avopts && (avopts->vacuum_cost_limit > 0 ||
2923  avopts->vacuum_cost_delay > 0));
2924  }
2925 
2926  heap_freetuple(classTup);
2927 
2928  return tab;
2929 }
int vacuum_cost_delay
Definition: rel.h:263
int multixact_freeze_table_age
Definition: vacuum.h:142
static int default_freeze_table_age
Definition: autovacuum.c:150
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
int at_vacuum_cost_delay
Definition: autovacuum.c:192
static int default_multixact_freeze_min_age
Definition: autovacuum.c:151
int freeze_min_age
Definition: rel.h:265
static void autovac_refresh_stats(void)
Definition: autovacuum.c:3436
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dbid)
Definition: pgstat.c:2387
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:885
char * at_datname
Definition: autovacuum.c:198
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
int freeze_table_age
Definition: vacuum.h:139
int autovacuum_vac_cost_limit
Definition: autovacuum.c:124
bool at_sharedrel
Definition: autovacuum.c:195
int freeze_table_age
Definition: rel.h:267
int at_vacuum_cost_limit
Definition: autovacuum.c:193
char * at_relname
Definition: autovacuum.c:196
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
int VacuumCostLimit
Definition: globals.c:131
int freeze_min_age
Definition: vacuum.h:138
bool is_wraparound
Definition: vacuum.h:144
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
Definition: autovacuum.c:2734
static PgStat_StatTabEntry * get_pgstat_tabentry_relid(Oid relid, bool isshared, PgStat_StatDBEntry *shared, PgStat_StatDBEntry *dbentry)
Definition: autovacuum.c:2760
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:2969
int autovacuum_vac_cost_delay
Definition: autovacuum.c:123
char * at_nspname
Definition: autovacuum.c:197
int multixact_freeze_table_age
Definition: rel.h:270
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
Oid MyDatabaseId
Definition: globals.c:76
#define InvalidOid
Definition: postgres_ext.h:36
int VacuumCostDelay
Definition: globals.c:132
VacuumParams at_params
Definition: autovacuum.c:191
int vacuum_cost_limit
Definition: rel.h:264
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
int multixact_freeze_min_age
Definition: rel.h:268
int log_min_duration
Definition: vacuum.h:145
int log_min_duration
Definition: rel.h:271
int Log_autovacuum_min_duration
Definition: autovacuum.c:126
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:165
AutoVacOpts ar_reloptions
Definition: autovacuum.c:182
void * palloc(Size size)
Definition: mcxt.c:849
bool ar_hasrelopts
Definition: autovacuum.c:181
static int default_multixact_freeze_table_age
Definition: autovacuum.c:152
int multixact_freeze_min_age
Definition: vacuum.h:140
static int default_freeze_min_age
Definition: autovacuum.c:149
bool at_dobalance
Definition: autovacuum.c:194

Variable Documentation

bool am_autovacuum_launcher = false
static

Definition at line 136 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and IsAutoVacuumLauncherProcess().

bool am_autovacuum_worker = false
static

Definition at line 137 of file autovacuum.c.

Referenced by AutoVacWorkerMain(), and IsAutoVacuumWorkerProcess().

MemoryContext AutovacMemCxt
static

Definition at line 155 of file autovacuum.c.

double autovacuum_anl_scale

Definition at line 119 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

int autovacuum_anl_thresh

Definition at line 118 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

int autovacuum_freeze_max_age
int autovacuum_multixact_freeze_max_age

Definition at line 121 of file autovacuum.c.

Referenced by MultiXactMemberFreezeThreshold(), and SetMultiXactIdLimit().

int autovacuum_naptime
bool autovacuum_start_daemon = false

Definition at line 112 of file autovacuum.c.

Referenced by autovac_init(), and AutoVacuumingActive().

int autovacuum_vac_cost_delay

Definition at line 123 of file autovacuum.c.

Referenced by autovac_balance_cost(), and table_recheck_autovac().

int autovacuum_vac_cost_limit

Definition at line 124 of file autovacuum.c.

Referenced by autovac_balance_cost(), and table_recheck_autovac().

double autovacuum_vac_scale

Definition at line 117 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

int autovacuum_vac_thresh

Definition at line 116 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

int autovacuum_work_mem = -1

Definition at line 114 of file autovacuum.c.

Referenced by ginInsertCleanup(), and lazy_space_alloc().

dsa_area* AutoVacuumDSA = NULL
static

Definition at line 310 of file autovacuum.c.

int AutovacuumLauncherPid = 0

Definition at line 313 of file autovacuum.c.

Referenced by FreeWorkerInfo(), and ProcKill().

AutoVacuumShmemStruct* AutoVacuumShmem
static

Definition at line 274 of file autovacuum.c.

dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
static

Definition at line 280 of file autovacuum.c.

MemoryContext DatabaseListCxt = NULL
static

Definition at line 281 of file autovacuum.c.

int default_freeze_min_age
static

Definition at line 149 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

int default_freeze_table_age
static

Definition at line 150 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

int default_multixact_freeze_min_age
static

Definition at line 151 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

int default_multixact_freeze_table_age
static

Definition at line 152 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

volatile sig_atomic_t got_SIGHUP = false
static
volatile sig_atomic_t got_SIGTERM = false
static
volatile sig_atomic_t got_SIGUSR2 = false
static

Definition at line 141 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and avl_sigusr2_handler().

int Log_autovacuum_min_duration = -1

Definition at line 126 of file autovacuum.c.

Referenced by table_recheck_autovac().

WorkerInfo MyWorkerInfo = NULL
static

Definition at line 284 of file autovacuum.c.

MultiXactId recentMulti
static

Definition at line 146 of file autovacuum.c.

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

TransactionId recentXid
static

Definition at line 145 of file autovacuum.c.

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