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

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Enumerations

enum  AutoVacuumSignal { AutoVacForkFailed , AutoVacRebalance , AutoVacNumSignals }
 

Functions

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

Variables

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

Macro Definition Documentation

◆ MAX_AUTOVAC_ACTIV_LEN

#define MAX_AUTOVAC_ACTIV_LEN   (NAMEDATALEN * 2 + 56)

◆ MAX_AUTOVAC_SLEEPTIME

#define MAX_AUTOVAC_SLEEPTIME   300 /* seconds */

Definition at line 136 of file autovacuum.c.

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 135 of file autovacuum.c.

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

Definition at line 263 of file autovacuum.c.

Typedef Documentation

◆ autovac_table

typedef struct autovac_table autovac_table

◆ AutoVacuumWorkItem

◆ av_relation

typedef struct av_relation av_relation

◆ avl_dbase

typedef struct avl_dbase avl_dbase

◆ avw_dbase

typedef struct avw_dbase avw_dbase

◆ WorkerInfo

typedef struct WorkerInfoData* WorkerInfo

Definition at line 233 of file autovacuum.c.

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

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

Function Documentation

◆ autovac_balance_cost()

static void autovac_balance_cost ( void  )
static

Definition at line 1797 of file autovacuum.c.

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

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

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

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3301 of file autovacuum.c.

3302 {
3304  ereport(WARNING,
3305  (errmsg("autovacuum not started because of misconfiguration"),
3306  errhint("Enable the \"track_counts\" option.")));
3307 }
bool autovacuum_start_daemon
Definition: autovacuum.c:116
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define WARNING
Definition: elog.h:36
#define ereport(elevel,...)
Definition: elog.h:149
bool pgstat_track_counts
Definition: pgstat.c:187

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

Referenced by PostmasterMain().

◆ autovac_report_activity()

static void autovac_report_activity ( autovac_table tab)
static

Definition at line 3172 of file autovacuum.c.

3173 {
3174 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3175  char activity[MAX_AUTOVAC_ACTIV_LEN];
3176  int len;
3177 
3178  /* Report the command and possible options */
3179  if (tab->at_params.options & VACOPT_VACUUM)
3180  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3181  "autovacuum: VACUUM%s",
3182  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3183  else
3184  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3185  "autovacuum: ANALYZE");
3186 
3187  /*
3188  * Report the qualified name of the relation.
3189  */
3190  len = strlen(activity);
3191 
3192  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3193  " %s.%s%s", tab->at_nspname, tab->at_relname,
3194  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3195 
3196  /* Set statement_timestamp() to current time for pg_stat_activity */
3198 
3200 }
#define MAX_AUTOVAC_ACTIV_LEN
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
const void size_t len
#define snprintf
Definition: port.h:238
bits32 options
Definition: vacuum.h:219
bool is_wraparound
Definition: vacuum.h:226
char * at_nspname
Definition: autovacuum.c:197
char * at_relname
Definition: autovacuum.c:196
VacuumParams at_params
Definition: autovacuum.c:191
#define VACOPT_VACUUM
Definition: vacuum.h:183
#define VACOPT_ANALYZE
Definition: vacuum.h:184
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:899

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

Referenced by autovacuum_do_vac_analyze().

◆ autovac_report_workitem()

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

Definition at line 3207 of file autovacuum.c.

3209 {
3210  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3211  char blk[12 + 2];
3212  int len;
3213 
3214  switch (workitem->avw_type)
3215  {
3217  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3218  "autovacuum: BRIN summarize");
3219  break;
3220  }
3221 
3222  /*
3223  * Report the qualified name of the relation, and the block number if any
3224  */
3225  len = strlen(activity);
3226 
3227  if (BlockNumberIsValid(workitem->avw_blockNumber))
3228  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3229  else
3230  blk[0] = '\0';
3231 
3232  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3233  " %s.%s%s", nspname, relname, blk);
3234 
3235  /* Set statement_timestamp() to current time for pg_stat_activity */
3237 
3239 }
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
NameData relname
Definition: pg_class.h:38
BlockNumber avw_blockNumber
Definition: autovacuum.c:260
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:255

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

Referenced by perform_work_item().

◆ AutoVacLauncherMain()

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

Definition at line 431 of file autovacuum.c.

432 {
433  sigjmp_buf local_sigjmp_buf;
434 
435  am_autovacuum_launcher = true;
436 
438  init_ps_display(NULL);
439 
440  ereport(DEBUG1,
441  (errmsg_internal("autovacuum launcher started")));
442 
443  if (PostAuthDelay)
444  pg_usleep(PostAuthDelay * 1000000L);
445 
447 
448  /*
449  * Set up signal handlers. We operate on databases much like a regular
450  * backend, so we use the same signal handling. See equivalent code in
451  * tcop/postgres.c.
452  */
456  /* SIGQUIT handler was already set up by InitPostmasterChild */
457 
458  InitializeTimeouts(); /* establishes SIGALRM handler */
459 
465 
466  /*
467  * Create a per-backend PGPROC struct in shared memory, except in the
468  * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
469  * this before we can use LWLocks (and in the EXEC_BACKEND case we already
470  * had to do some stuff with LWLocks).
471  */
472 #ifndef EXEC_BACKEND
473  InitProcess();
474 #endif
475 
476  /* Early initialization */
477  BaseInit();
478 
479  InitPostgres(NULL, InvalidOid, NULL, InvalidOid, false, false, NULL);
480 
482 
483  /*
484  * Create a memory context that we will do all our work in. We do this so
485  * that we can reset the context during error recovery and thereby avoid
486  * possible memory leaks.
487  */
489  "Autovacuum Launcher",
492 
493  /*
494  * If an exception is encountered, processing resumes here.
495  *
496  * This code is a stripped down version of PostgresMain error recovery.
497  *
498  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
499  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
500  * signals other than SIGQUIT will be blocked until we complete error
501  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
502  * call redundant, but it is not since InterruptPending might be set
503  * already.
504  */
505  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
506  {
507  /* since not using PG_TRY, must reset error stack by hand */
508  error_context_stack = NULL;
509 
510  /* Prevents interrupts while cleaning up */
511  HOLD_INTERRUPTS();
512 
513  /* Forget any pending QueryCancel or timeout request */
514  disable_all_timeouts(false);
515  QueryCancelPending = false; /* second to avoid race condition */
516 
517  /* Report the error to the server log */
518  EmitErrorReport();
519 
520  /* Abort the current transaction in order to recover */
522 
523  /*
524  * Release any other resources, for the case where we were not in a
525  * transaction.
526  */
529  AbortBufferIO();
530  UnlockBuffers();
531  /* this is probably dead code, but let's be safe: */
534  AtEOXact_Buffers(false);
535  AtEOXact_SMgr();
536  AtEOXact_Files(false);
537  AtEOXact_HashTables(false);
538 
539  /*
540  * Now return to normal top-level context and clear ErrorContext for
541  * next time.
542  */
544  FlushErrorState();
545 
546  /* Flush any leaked data in the top-level context */
548 
549  /* don't leave dangling pointers to freed memory */
550  DatabaseListCxt = NULL;
552 
553  /* Now we can allow interrupts again */
555 
556  /* if in shutdown mode, no need for anything further; just go away */
559 
560  /*
561  * Sleep at least 1 second after any error. We don't want to be
562  * filling the error logs as fast as we can.
563  */
564  pg_usleep(1000000L);
565  }
566 
567  /* We can now handle ereport(ERROR) */
568  PG_exception_stack = &local_sigjmp_buf;
569 
570  /* must unblock signals before calling rebuild_database_list */
571  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
572 
573  /*
574  * Set always-secure search path. Launcher doesn't connect to a database,
575  * so this has no effect.
576  */
577  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
578 
579  /*
580  * Force zero_damaged_pages OFF in the autovac process, even if it is set
581  * in postgresql.conf. We don't really want such a dangerous option being
582  * applied non-interactively.
583  */
584  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
585 
586  /*
587  * Force settable timeouts off to avoid letting these settings prevent
588  * regular maintenance from being executed.
589  */
590  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
591  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
592  SetConfigOption("idle_in_transaction_session_timeout", "0",
594 
595  /*
596  * Force default_transaction_isolation to READ COMMITTED. We don't want
597  * to pay the overhead of serializable mode, nor add any risk of causing
598  * deadlocks or delaying other transactions.
599  */
600  SetConfigOption("default_transaction_isolation", "read committed",
602 
603  /*
604  * Even when system is configured to use a different fetch consistency,
605  * for autovac we always want fresh stats.
606  */
607  SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
608 
609  /*
610  * In emergency mode, just start a worker (unless shutdown was requested)
611  * and go away.
612  */
613  if (!AutoVacuumingActive())
614  {
616  do_start_worker();
617  proc_exit(0); /* done */
618  }
619 
621 
622  /*
623  * Create the initial database list. The invariant we want this list to
624  * keep is that it's ordered by decreasing next_time. As soon as an entry
625  * is updated to a higher time, it will be moved to the front (which is
626  * correct because the only operation is to add autovacuum_naptime to the
627  * entry, and time always increases).
628  */
630 
631  /* loop until shutdown request */
632  while (!ShutdownRequestPending)
633  {
634  struct timeval nap;
636  bool can_launch;
637 
638  /*
639  * This loop is a bit different from the normal use of WaitLatch,
640  * because we'd like to sleep before the first launch of a child
641  * process. So it's WaitLatch, then ResetLatch, then check for
642  * wakening conditions.
643  */
644 
646  false, &nap);
647 
648  /*
649  * Wait until naptime expires or we get some type of signal (all the
650  * signal handlers will wake us by calling SetLatch).
651  */
652  (void) WaitLatch(MyLatch,
654  (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
656 
658 
660 
661  /*
662  * a worker finished, or postmaster signaled failure to start a worker
663  */
664  if (got_SIGUSR2)
665  {
666  got_SIGUSR2 = false;
667 
668  /* rebalance cost limits, if needed */
670  {
671  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
674  LWLockRelease(AutovacuumLock);
675  }
676 
678  {
679  /*
680  * If the postmaster failed to start a new worker, we sleep
681  * for a little while and resend the signal. The new worker's
682  * state is still in memory, so this is sufficient. After
683  * that, we restart the main loop.
684  *
685  * XXX should we put a limit to the number of times we retry?
686  * I don't think it makes much sense, because a future start
687  * of a worker will continue to fail in the same way.
688  */
690  pg_usleep(1000000L); /* 1s */
692  continue;
693  }
694  }
695 
696  /*
697  * There are some conditions that we need to check before trying to
698  * start a worker. First, we need to make sure that there is a worker
699  * slot available. Second, we need to make sure that no other worker
700  * failed while starting up.
701  */
702 
704  LWLockAcquire(AutovacuumLock, LW_SHARED);
705 
707 
708  if (AutoVacuumShmem->av_startingWorker != NULL)
709  {
710  int waittime;
712 
713  /*
714  * We can't launch another worker when another one is still
715  * starting up (or failed while doing so), so just sleep for a bit
716  * more; that worker will wake us up again as soon as it's ready.
717  * We will only wait autovacuum_naptime seconds (up to a maximum
718  * of 60 seconds) for this to happen however. Note that failure
719  * to connect to a particular database is not a problem here,
720  * because the worker removes itself from the startingWorker
721  * pointer before trying to connect. Problems detected by the
722  * postmaster (like fork() failure) are also reported and handled
723  * differently. The only problems that may cause this code to
724  * fire are errors in the earlier sections of AutoVacWorkerMain,
725  * before the worker removes the WorkerInfo from the
726  * startingWorker pointer.
727  */
728  waittime = Min(autovacuum_naptime, 60) * 1000;
730  waittime))
731  {
732  LWLockRelease(AutovacuumLock);
733  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
734 
735  /*
736  * No other process can put a worker in starting mode, so if
737  * startingWorker is still INVALID after exchanging our lock,
738  * we assume it's the same one we saw above (so we don't
739  * recheck the launch time).
740  */
741  if (AutoVacuumShmem->av_startingWorker != NULL)
742  {
744  worker->wi_dboid = InvalidOid;
745  worker->wi_tableoid = InvalidOid;
746  worker->wi_sharedrel = false;
747  worker->wi_proc = NULL;
748  worker->wi_launchtime = 0;
750  &worker->wi_links);
753  errmsg("autovacuum worker took too long to start; canceled"));
754  }
755  }
756  else
757  can_launch = false;
758  }
759  LWLockRelease(AutovacuumLock); /* either shared or exclusive */
760 
761  /* if we can't do anything, just go back to sleep */
762  if (!can_launch)
763  continue;
764 
765  /* We're OK to start a new worker */
766 
768  {
769  /*
770  * Special case when the list is empty: start a worker right away.
771  * This covers the initial case, when no database is in pgstats
772  * (thus the list is empty). Note that the constraints in
773  * launcher_determine_sleep keep us from starting workers too
774  * quickly (at most once every autovacuum_naptime when the list is
775  * empty).
776  */
778  }
779  else
780  {
781  /*
782  * because rebuild_database_list constructs a list with most
783  * distant adl_next_worker first, we obtain our database from the
784  * tail of the list.
785  */
786  avl_dbase *avdb;
787 
788  avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
789 
790  /*
791  * launch a worker if next_worker is right now or it is in the
792  * past
793  */
795  current_time, 0))
797  }
798  }
799 
801 }
static void autovac_balance_cost(void)
Definition: autovacuum.c:1797
static Oid do_start_worker(void)
Definition: autovacuum.c:1147
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition: autovacuum.c:864
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:143
static void avl_sigusr2_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1418
static void HandleAutoVacLauncherInterrupts(void)
Definition: autovacuum.c:807
int autovacuum_naptime
Definition: autovacuum.c:119
static bool am_autovacuum_launcher
Definition: autovacuum.c:139
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3247
static void AutoVacLauncherShutdown(void)
Definition: autovacuum.c:315
static void launch_worker(TimestampTz now)
Definition: autovacuum.c:1359
static dlist_head DatabaseList
Definition: autovacuum.c:297
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:948
static MemoryContext DatabaseListCxt
Definition: autovacuum.c:298
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:156
sigset_t UnBlockSig
Definition: pqsignal.c:22
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1727
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1582
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2642
void UnlockBuffers(void)
Definition: bufmgr.c:4217
void AbortBufferIO(void)
Definition: bufmgr.c:4708
int64 TimestampTz
Definition: timestamp.h:39
Datum current_time(PG_FUNCTION_ARGS)
Definition: date.c:340
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1878
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
void EmitErrorReport(void)
Definition: elog.c:1669
ErrorContextCallback * error_context_stack
Definition: elog.c:95
void FlushErrorState(void)
Definition: elog.c:1825
sigjmp_buf * PG_exception_stack
Definition: elog.c:97
#define DEBUG1
Definition: elog.h:30
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2966
int MyProcPid
Definition: globals.c:44
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:58
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4176
@ PGC_S_OVERRIDE
Definition: guc.h:119
@ PGC_SUSET
Definition: guc.h:74
static void dlist_init(dlist_head *head)
Definition: ilist.h:314
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:612
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:347
static bool dlist_is_empty(const dlist_head *head)
Definition: ilist.h:336
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:109
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:28
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void proc_exit(int code)
Definition: ipc.c:104
void ResetLatch(Latch *latch)
Definition: latch.c:699
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:492
#define WL_TIMEOUT
Definition: latch.h:128
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void LWLockReleaseAll(void)
Definition: lwlock.c:1902
@ LW_SHARED
Definition: lwlock.h:116
@ LW_EXCLUSIVE
Definition: lwlock.h:115
MemoryContext TopMemoryContext
Definition: mcxt.c:141
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:70
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
@ NormalProcessing
Definition: miscadmin.h:400
@ InitProcessing
Definition: miscadmin.h:399
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
#define SetProcessingMode(mode)
Definition: miscadmin.h:411
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:321
BackendType MyBackendType
Definition: miscinit.c:63
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:181
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition: pmsignal.h:39
pqsigfunc pqsignal(int signo, pqsigfunc func)
int PostAuthDelay
Definition: postgres.c:95
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:2990
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:2969
#define InvalidOid
Definition: postgres_ext.h:36
void BaseInit(void)
Definition: postinit.c:636
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bool load_session_libraries, bool override_allow_connections, char *out_dbname)
Definition: postinit.c:725
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:639
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:242
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:912
ResourceOwner AuxProcessResourceOwner
Definition: resowner.c:149
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:709
void InitProcess(void)
Definition: proc.c:297
dlist_head av_freeWorkers
Definition: autovacuum.c:285
WorkerInfo av_startingWorker
Definition: autovacuum.c:287
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:283
TimestampTz wi_launchtime
Definition: autovacuum.c:225
dlist_node wi_links
Definition: autovacuum.c:221
TimestampTz adl_next_worker
Definition: autovacuum.c:162
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:755
void InitializeTimeouts(void)
Definition: timeout.c:474
@ WAIT_EVENT_AUTOVACUUM_MAIN
Definition: wait_event.h:39
static void pgstat_report_wait_end(void)
Definition: wait_event.h:287
#define SIGCHLD
Definition: win32_port.h:186
#define SIGHUP
Definition: win32_port.h:176
#define SIG_DFL
Definition: win32_port.h:171
#define SIGPIPE
Definition: win32_port.h:181
#define SIGUSR1
Definition: win32_port.h:188
#define SIGUSR2
Definition: win32_port.h:189
#define SIG_IGN
Definition: win32_port.h:173
void AbortCurrentTransaction(void)
Definition: xact.c:3312

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

◆ AutoVacLauncherShutdown()

static void AutoVacLauncherShutdown ( void  )
static

Definition at line 315 of file autovacuum.c.

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

Referenced by AutoVacLauncherMain(), and HandleAutoVacLauncherInterrupts().

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3143 of file autovacuum.c.

3144 {
3145  RangeVar *rangevar;
3146  VacuumRelation *rel;
3147  List *rel_list;
3148 
3149  /* Let pgstat know what we're doing */
3151 
3152  /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3153  rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3154  rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3155  rel_list = list_make1(rel);
3156 
3157  vacuum(rel_list, &tab->at_params, bstrategy, true);
3158 }
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3172
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:819
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
Definition: pg_list.h:54
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:311

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

Referenced by do_autovacuum().

◆ AutoVacuumingActive()

bool AutoVacuumingActive ( void  )

Definition at line 3247 of file autovacuum.c.

3248 {
3250  return false;
3251  return true;
3252 }

References autovacuum_start_daemon, and pgstat_track_counts.

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

◆ AutoVacuumRequestWork()

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

Definition at line 3259 of file autovacuum.c.

3261 {
3262  int i;
3263  bool result = false;
3264 
3265  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3266 
3267  /*
3268  * Locate an unused work item and fill it with the given data.
3269  */
3270  for (i = 0; i < NUM_WORKITEMS; i++)
3271  {
3273 
3274  if (workitem->avw_used)
3275  continue;
3276 
3277  workitem->avw_used = true;
3278  workitem->avw_active = false;
3279  workitem->avw_type = type;
3280  workitem->avw_database = MyDatabaseId;
3281  workitem->avw_relation = relationId;
3282  workitem->avw_blockNumber = blkno;
3283  result = true;
3284 
3285  /* done */
3286  break;
3287  }
3288 
3289  LWLockRelease(AutovacuumLock);
3290 
3291  return result;
3292 }
#define NUM_WORKITEMS
Definition: autovacuum.c:263
Oid MyDatabaseId
Definition: globals.c:89
int i
Definition: isn.c:73
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:288

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

Referenced by brininsert().

◆ AutoVacuumShmemInit()

void AutoVacuumShmemInit ( void  )

Definition at line 3351 of file autovacuum.c.

3352 {
3353  bool found;
3354 
3356  ShmemInitStruct("AutoVacuum Data",
3358  &found);
3359 
3360  if (!IsUnderPostmaster)
3361  {
3362  WorkerInfo worker;
3363  int i;
3364 
3365  Assert(!found);
3366 
3371  memset(AutoVacuumShmem->av_workItems, 0,
3372  sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3373 
3374  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3375  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3376 
3377  /* initialize the WorkerInfo free list */
3378  for (i = 0; i < autovacuum_max_workers; i++)
3380  &worker[i].wi_links);
3381  }
3382  else
3383  Assert(found);
3384 }
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3332
int autovacuum_max_workers
Definition: autovacuum.c:117
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:233
#define MAXALIGN(LEN)
Definition: c.h:795
bool IsUnderPostmaster
Definition: globals.c:113
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396

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

Referenced by CreateSharedMemoryAndSemaphores().

◆ AutoVacuumShmemSize()

Size AutoVacuumShmemSize ( void  )

Definition at line 3332 of file autovacuum.c.

3333 {
3334  Size size;
3335 
3336  /*
3337  * Need the fixed struct and the array of WorkerInfoData.
3338  */
3339  size = sizeof(AutoVacuumShmemStruct);
3340  size = MAXALIGN(size);
3342  sizeof(WorkerInfoData)));
3343  return size;
3344 }
size_t Size
Definition: c.h:589
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

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

Referenced by AutoVacuumShmemInit(), and CalculateShmemSize().

◆ AutoVacuumUpdateDelay()

void AutoVacuumUpdateDelay ( void  )

Definition at line 1781 of file autovacuum.c.

1782 {
1783  if (MyWorkerInfo)
1784  {
1787  }
1788 }
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:301

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

Referenced by do_autovacuum(), and vacuum_delay_point().

◆ AutoVacWorkerFailed()

void AutoVacWorkerFailed ( void  )

Definition at line 1411 of file autovacuum.c.

1412 {
1414 }

References AutoVacForkFailed, AutoVacuumShmem, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

◆ AutoVacWorkerMain()

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

Definition at line 1509 of file autovacuum.c.

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

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

Referenced by StartAutoVacWorker().

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1418 of file autovacuum.c.

1419 {
1420  int save_errno = errno;
1421 
1422  got_SIGUSR2 = true;
1423  SetLatch(MyLatch);
1424 
1425  errno = save_errno;
1426 }
void SetLatch(Latch *latch)
Definition: latch.c:607

References got_SIGUSR2, MyLatch, and SetLatch().

Referenced by AutoVacLauncherMain().

◆ check_autovacuum_work_mem()

bool check_autovacuum_work_mem ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 3390 of file autovacuum.c.

3391 {
3392  /*
3393  * -1 indicates fallback.
3394  *
3395  * If we haven't yet changed the boot_val default of -1, just let it be.
3396  * Autovacuum will look to maintenance_work_mem instead.
3397  */
3398  if (*newval == -1)
3399  return true;
3400 
3401  /*
3402  * We clamp manually-set values to at least 1MB. Since
3403  * maintenance_work_mem is always set to at least this value, do the same
3404  * here.
3405  */
3406  if (*newval < 1024)
3407  *newval = 1024;
3408 
3409  return true;
3410 }
#define newval

References newval.

◆ db_comparator()

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

Definition at line 1127 of file autovacuum.c.

1128 {
1129  if (((const avl_dbase *) a)->adl_score == ((const avl_dbase *) b)->adl_score)
1130  return 0;
1131  else
1132  return (((const avl_dbase *) a)->adl_score < ((const avl_dbase *) b)->adl_score) ? 1 : -1;
1133 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69

References a, and b.

Referenced by rebuild_database_list().

◆ do_autovacuum()

static void do_autovacuum ( void  )
static

Definition at line 1958 of file autovacuum.c.

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

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

Referenced by AutoVacWorkerMain().

◆ do_start_worker()

static Oid do_start_worker ( void  )
static

Definition at line 1147 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain(), and launch_worker().

◆ extract_autovac_opts()

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

Definition at line 2729 of file autovacuum.c.

2730 {
2731  bytea *relopts;
2732  AutoVacOpts *av;
2733 
2734  Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2735  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2736  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2737 
2738  relopts = extractRelOptions(tup, pg_class_desc, NULL);
2739  if (relopts == NULL)
2740  return NULL;
2741 
2742  av = palloc(sizeof(AutoVacOpts));
2743  memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2744  pfree(relopts);
2745 
2746  return av;
2747 }
void * palloc(Size size)
Definition: mcxt.c:1210
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
Definition: reloptions.c:1381
Definition: c.h:671

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

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ FreeWorkerInfo()

static void FreeWorkerInfo ( int  code,
Datum  arg 
)
static

Definition at line 1732 of file autovacuum.c.

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

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

Referenced by AutoVacWorkerMain().

◆ get_database_list()

static List* get_database_list ( void  )
static

Definition at line 1885 of file autovacuum.c.

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

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

Referenced by do_start_worker(), and rebuild_database_list().

◆ HandleAutoVacLauncherInterrupts()

static void HandleAutoVacLauncherInterrupts ( void  )
static

Definition at line 807 of file autovacuum.c.

808 {
809  /* the normal shutdown case */
812 
814  {
815  ConfigReloadPending = false;
817 
818  /* shutdown requested in config file? */
819  if (!AutoVacuumingActive())
821 
822  /* rebalance in case the default cost parameters changed */
823  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
825  LWLockRelease(AutovacuumLock);
826 
827  /* rebuild the list in case the naptime changed */
829  }
830 
831  /* Process barrier events */
834 
835  /* Perform logging of memory contexts of this process */
838 
839  /* Process sinval catchup interrupts that happened while sleeping */
841 }
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1183
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:468
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176

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

Referenced by AutoVacLauncherMain().

◆ IsAutoVacuumLauncherProcess()

bool IsAutoVacuumLauncherProcess ( void  )

Definition at line 3315 of file autovacuum.c.

3316 {
3317  return am_autovacuum_launcher;
3318 }

References am_autovacuum_launcher.

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

◆ IsAutoVacuumWorkerProcess()

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1359 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain().

◆ launcher_determine_sleep()

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

Definition at line 864 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain().

◆ perform_work_item()

static void perform_work_item ( AutoVacuumWorkItem workitem)
static

Definition at line 2618 of file autovacuum.c.

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

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

Referenced by do_autovacuum().

◆ rebuild_database_list()

static void rebuild_database_list ( Oid  newdb)
static

Definition at line 948 of file autovacuum.c.

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

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, AutovacMemCxt, autovacuum_naptime, dlist_iter::cur, current_time(), DatabaseList, DatabaseListCxt, db_comparator(), dblist, dlist_container, dlist_foreach, dlist_init(), dlist_push_head(), HASHCTL::entrysize, get_database_list(), GetCurrentTimestamp(), HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), hash_seq_init(), hash_seq_search(), HASHCTL::hcxt, i, HASHCTL::keysize, lfirst, MemoryContextDelete(), MemoryContextSwitchTo(), MIN_AUTOVAC_SLEEPTIME, OidIsValid, palloc(), pgstat_fetch_stat_dbentry(), qsort, and TimestampTzPlusMilliseconds.

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

◆ recheck_relation_needs_vacanalyze()

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

Definition at line 2912 of file autovacuum.c.

2919 {
2920  PgStat_StatTabEntry *tabentry;
2921 
2922  /* fetch the pgstat table entry */
2923  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2924  relid);
2925 
2926  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2927  effective_multixact_freeze_max_age,
2928  dovacuum, doanalyze, wraparound);
2929 
2930  /* ignore ANALYZE for toast tables */
2931  if (classForm->relkind == RELKIND_TOASTVALUE)
2932  *doanalyze = false;
2933 }

References pgstat_fetch_stat_tabentry_ext(), and relation_needs_vacanalyze().

Referenced by table_recheck_autovac().

◆ relation_needs_vacanalyze()

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

Definition at line 2973 of file autovacuum.c.

2982 {
2983  bool force_vacuum;
2984  bool av_enabled;
2985  float4 reltuples; /* pg_class.reltuples */
2986 
2987  /* constants from reloptions or GUC variables */
2988  int vac_base_thresh,
2989  vac_ins_base_thresh,
2990  anl_base_thresh;
2991  float4 vac_scale_factor,
2992  vac_ins_scale_factor,
2993  anl_scale_factor;
2994 
2995  /* thresholds calculated from above constants */
2996  float4 vacthresh,
2997  vacinsthresh,
2998  anlthresh;
2999 
3000  /* number of vacuum (resp. analyze) tuples at this time */
3001  float4 vactuples,
3002  instuples,
3003  anltuples;
3004 
3005  /* freeze parameters */
3006  int freeze_max_age;
3007  int multixact_freeze_max_age;
3008  TransactionId xidForceLimit;
3009  MultiXactId multiForceLimit;
3010 
3011  Assert(classForm != NULL);
3012  Assert(OidIsValid(relid));
3013 
3014  /*
3015  * Determine vacuum/analyze equation parameters. We have two possible
3016  * sources: the passed reloptions (which could be a main table or a toast
3017  * table), or the autovacuum GUC variables.
3018  */
3019 
3020  /* -1 in autovac setting means use plain vacuum_scale_factor */
3021  vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3022  ? relopts->vacuum_scale_factor
3024 
3025  vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3026  ? relopts->vacuum_threshold
3028 
3029  vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3030  ? relopts->vacuum_ins_scale_factor
3032 
3033  /* -1 is used to disable insert vacuums */
3034  vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3035  ? relopts->vacuum_ins_threshold
3037 
3038  anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3039  ? relopts->analyze_scale_factor
3041 
3042  anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3043  ? relopts->analyze_threshold
3045 
3046  freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3049 
3050  multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3051  ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3052  : effective_multixact_freeze_max_age;
3053 
3054  av_enabled = (relopts ? relopts->enabled : true);
3055 
3056  /* Force vacuum if table is at risk of wraparound */
3057  xidForceLimit = recentXid - freeze_max_age;
3058  if (xidForceLimit < FirstNormalTransactionId)
3059  xidForceLimit -= FirstNormalTransactionId;
3060  force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
3061  TransactionIdPrecedes(classForm->relfrozenxid,
3062  xidForceLimit));
3063  if (!force_vacuum)
3064  {
3065  multiForceLimit = recentMulti - multixact_freeze_max_age;
3066  if (multiForceLimit < FirstMultiXactId)
3067  multiForceLimit -= FirstMultiXactId;
3068  force_vacuum = MultiXactIdIsValid(classForm->relminmxid) &&
3069  MultiXactIdPrecedes(classForm->relminmxid, multiForceLimit);
3070  }
3071  *wraparound = force_vacuum;
3072 
3073  /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3074  if (!av_enabled && !force_vacuum)
3075  {
3076  *doanalyze = false;
3077  *dovacuum = false;
3078  return;
3079  }
3080 
3081  /*
3082  * If we found stats for the table, and autovacuum is currently enabled,
3083  * make a threshold-based decision whether to vacuum and/or analyze. If
3084  * autovacuum is currently disabled, we must be here for anti-wraparound
3085  * vacuuming only, so don't vacuum (or analyze) anything that's not being
3086  * forced.
3087  */
3088  if (PointerIsValid(tabentry) && AutoVacuumingActive())
3089  {
3090  reltuples = classForm->reltuples;
3091  vactuples = tabentry->dead_tuples;
3092  instuples = tabentry->ins_since_vacuum;
3093  anltuples = tabentry->mod_since_analyze;
3094 
3095  /* If the table hasn't yet been vacuumed, take reltuples as zero */
3096  if (reltuples < 0)
3097  reltuples = 0;
3098 
3099  vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3100  vacinsthresh = (float4) vac_ins_base_thresh + vac_ins_scale_factor * reltuples;
3101  anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3102 
3103  /*
3104  * Note that we don't need to take special consideration for stat
3105  * reset, because if that happens, the last vacuum and analyze counts
3106  * will be reset too.
3107  */
3108  if (vac_ins_base_thresh >= 0)
3109  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3110  NameStr(classForm->relname),
3111  vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3112  else
3113  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3114  NameStr(classForm->relname),
3115  vactuples, vacthresh, anltuples, anlthresh);
3116 
3117  /* Determine if this table needs vacuum or analyze. */
3118  *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3119  (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3120  *doanalyze = (anltuples > anlthresh);
3121  }
3122  else
3123  {
3124  /*
3125  * Skip a table not found in stat hash, unless we have to force vacuum
3126  * for anti-wrap purposes. If it's not acted upon, there's no need to
3127  * vacuum it.
3128  */
3129  *dovacuum = force_vacuum;
3130  *doanalyze = false;
3131  }
3132 
3133  /* ANALYZE refuses to work with pg_statistic */
3134  if (relid == StatisticRelationId)
3135  *doanalyze = false;
3136 }
double autovacuum_vac_scale
Definition: autovacuum.c:121
int autovacuum_anl_thresh
Definition: autovacuum.c:124
int autovacuum_vac_thresh
Definition: autovacuum.c:120
double autovacuum_anl_scale
Definition: autovacuum.c:125
int autovacuum_vac_ins_thresh
Definition: autovacuum.c:122
double autovacuum_vac_ins_scale
Definition: autovacuum.c:123
#define PointerIsValid(pointer)
Definition: c.h:747
float float4
Definition: c.h:613
#define DEBUG3
Definition: elog.h:28
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
int vacuum_ins_threshold
Definition: rel.h:310
int multixact_freeze_max_age
Definition: rel.h:317
float8 vacuum_scale_factor
Definition: rel.h:321
int analyze_threshold
Definition: rel.h:311
float8 vacuum_ins_scale_factor
Definition: rel.h:322
bool enabled
Definition: rel.h:308
int freeze_max_age
Definition: rel.h:314
int vacuum_threshold
Definition: rel.h:309
float8 analyze_scale_factor
Definition: rel.h:323
PgStat_Counter ins_since_vacuum
Definition: pgstat.h:408
PgStat_Counter mod_since_analyze
Definition: pgstat.h:407
PgStat_Counter dead_tuples
Definition: pgstat.h:406
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

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

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

◆ StartAutoVacWorker()

int StartAutoVacWorker ( void  )

Definition at line 1471 of file autovacuum.c.

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

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

Referenced by StartAutovacuumWorker().

◆ table_recheck_autovac()

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

Definition at line 2759 of file autovacuum.c.

2762 {
2763  Form_pg_class classForm;
2764  HeapTuple classTup;
2765  bool dovacuum;
2766  bool doanalyze;
2767  autovac_table *tab = NULL;
2768  bool wraparound;
2769  AutoVacOpts *avopts;
2770 
2771  /* fetch the relation's relcache entry */
2772  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2773  if (!HeapTupleIsValid(classTup))
2774  return NULL;
2775  classForm = (Form_pg_class) GETSTRUCT(classTup);
2776 
2777  /*
2778  * Get the applicable reloptions. If it is a TOAST table, try to get the
2779  * main table reloptions if the toast table itself doesn't have.
2780  */
2781  avopts = extract_autovac_opts(classTup, pg_class_desc);
2782  if (classForm->relkind == RELKIND_TOASTVALUE &&
2783  avopts == NULL && table_toast_map != NULL)
2784  {
2785  av_relation *hentry;
2786  bool found;
2787 
2788  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2789  if (found && hentry->ar_hasrelopts)
2790  avopts = &hentry->ar_reloptions;
2791  }
2792 
2793  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2794  effective_multixact_freeze_max_age,
2795  &dovacuum, &doanalyze, &wraparound);
2796 
2797  /* OK, it needs something done */
2798  if (doanalyze || dovacuum)
2799  {
2800  int freeze_min_age;
2801  int freeze_table_age;
2802  int multixact_freeze_min_age;
2803  int multixact_freeze_table_age;
2804  int vac_cost_limit;
2805  double vac_cost_delay;
2806  int log_min_duration;
2807 
2808  /*
2809  * Calculate the vacuum cost parameters and the freeze ages. If there
2810  * are options set in pg_class.reloptions, use them; in the case of a
2811  * toast table, try the main table too. Otherwise use the GUC
2812  * defaults, autovacuum's own first and plain vacuum second.
2813  */
2814 
2815  /* -1 in autovac setting means use plain vacuum_cost_delay */
2816  vac_cost_delay = (avopts && avopts->vacuum_cost_delay >= 0)
2817  ? avopts->vacuum_cost_delay
2818  : (autovacuum_vac_cost_delay >= 0)
2820  : VacuumCostDelay;
2821 
2822  /* 0 or -1 in autovac setting means use plain vacuum_cost_limit */
2823  vac_cost_limit = (avopts && avopts->vacuum_cost_limit > 0)
2824  ? avopts->vacuum_cost_limit
2827  : VacuumCostLimit;
2828 
2829  /* -1 in autovac setting means use log_autovacuum_min_duration */
2830  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2831  ? avopts->log_min_duration
2833 
2834  /* these do not have autovacuum-specific settings */
2835  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2836  ? avopts->freeze_min_age
2838 
2839  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2840  ? avopts->freeze_table_age
2842 
2843  multixact_freeze_min_age = (avopts &&
2844  avopts->multixact_freeze_min_age >= 0)
2845  ? avopts->multixact_freeze_min_age
2847 
2848  multixact_freeze_table_age = (avopts &&
2849  avopts->multixact_freeze_table_age >= 0)
2850  ? avopts->multixact_freeze_table_age
2852 
2853  tab = palloc(sizeof(autovac_table));
2854  tab->at_relid = relid;
2855  tab->at_sharedrel = classForm->relisshared;
2856 
2857  /*
2858  * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2859  * that vacuum() skips toast relations. Also note we tell vacuum() to
2860  * skip vac_update_datfrozenxid(); we'll do that separately.
2861  */
2862  tab->at_params.options =
2863  (dovacuum ? (VACOPT_VACUUM |
2866  (doanalyze ? VACOPT_ANALYZE : 0) |
2867  (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2868 
2869  /*
2870  * index_cleanup and truncate are unspecified at first in autovacuum.
2871  * They will be filled in with usable values using their reloptions
2872  * (or reloption defaults) later.
2873  */
2876  /* As of now, we don't support parallel vacuum for autovacuum */
2877  tab->at_params.nworkers = -1;
2878  tab->at_params.freeze_min_age = freeze_min_age;
2879  tab->at_params.freeze_table_age = freeze_table_age;
2880  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2881  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2882  tab->at_params.is_wraparound = wraparound;
2883  tab->at_params.log_min_duration = log_min_duration;
2884  tab->at_vacuum_cost_limit = vac_cost_limit;
2885  tab->at_vacuum_cost_delay = vac_cost_delay;
2886  tab->at_relname = NULL;
2887  tab->at_nspname = NULL;
2888  tab->at_datname = NULL;
2889 
2890  /*
2891  * If any of the cost delay parameters has been set individually for
2892  * this table, disable the balancing algorithm.
2893  */
2894  tab->at_dobalance =
2895  !(avopts && (avopts->vacuum_cost_limit > 0 ||
2896  avopts->vacuum_cost_delay > 0));
2897  }
2898 
2899  heap_freetuple(classTup);
2900  return tab;
2901 }
int Log_autovacuum_min_duration
Definition: autovacuum.c:132
static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
Definition: autovacuum.c:2912
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
int log_min_duration
Definition: rel.h:319
float8 vacuum_cost_delay
Definition: rel.h:320
int vacuum_cost_limit
Definition: rel.h:312
int multixact_freeze_table_age
Definition: rel.h:318
int freeze_min_age
Definition: rel.h:313
int freeze_table_age
Definition: rel.h:315
int multixact_freeze_min_age
Definition: rel.h:316
int nworkers
Definition: vacuum.h:238
int freeze_table_age
Definition: vacuum.h:221
VacOptValue truncate
Definition: vacuum.h:231
int freeze_min_age
Definition: vacuum.h:220
int multixact_freeze_min_age
Definition: vacuum.h:222
int multixact_freeze_table_age
Definition: vacuum.h:224
int log_min_duration
Definition: vacuum.h:227
VacOptValue index_cleanup
Definition: vacuum.h:230
bool at_sharedrel
Definition: autovacuum.c:195
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:188
#define VACOPT_SKIP_DATABASE_STATS
Definition: vacuum.h:192
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:205
#define VACOPT_PROCESS_MAIN
Definition: vacuum.h:189

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

Referenced by do_autovacuum().

Variable Documentation

◆ am_autovacuum_launcher

bool am_autovacuum_launcher = false
static

Definition at line 139 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and IsAutoVacuumLauncherProcess().

◆ am_autovacuum_worker

bool am_autovacuum_worker = false
static

Definition at line 140 of file autovacuum.c.

Referenced by AutoVacWorkerMain(), and IsAutoVacuumWorkerProcess().

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

◆ autovacuum_anl_scale

double autovacuum_anl_scale

Definition at line 125 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 124 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

int autovacuum_freeze_max_age

◆ autovacuum_max_workers

◆ autovacuum_multixact_freeze_max_age

int autovacuum_multixact_freeze_max_age

◆ autovacuum_naptime

int autovacuum_naptime

◆ autovacuum_start_daemon

bool autovacuum_start_daemon = false

Definition at line 116 of file autovacuum.c.

Referenced by autovac_init(), and AutoVacuumingActive().

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 129 of file autovacuum.c.

Referenced by autovac_balance_cost(), and table_recheck_autovac().

◆ autovacuum_vac_cost_limit

int autovacuum_vac_cost_limit

Definition at line 130 of file autovacuum.c.

Referenced by autovac_balance_cost(), and table_recheck_autovac().

◆ autovacuum_vac_ins_scale

double autovacuum_vac_ins_scale

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 122 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 121 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 120 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 118 of file autovacuum.c.

Referenced by dead_items_max_items(), and ginInsertCleanup().

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

Definition at line 304 of file autovacuum.c.

Referenced by FreeWorkerInfo(), and ProcKill().

◆ AutoVacuumShmem

◆ DatabaseList

dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
static

◆ DatabaseListCxt

MemoryContext DatabaseListCxt = NULL
static

Definition at line 298 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and rebuild_database_list().

◆ default_freeze_min_age

int default_freeze_min_age
static

Definition at line 150 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_freeze_table_age

int default_freeze_table_age
static

Definition at line 151 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_multixact_freeze_min_age

int default_multixact_freeze_min_age
static

Definition at line 152 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_multixact_freeze_table_age

int default_multixact_freeze_table_age
static

Definition at line 153 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ got_SIGUSR2

volatile sig_atomic_t got_SIGUSR2 = false
static

Definition at line 143 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and avl_sigusr2_handler().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = 600000

Definition at line 132 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

WorkerInfo MyWorkerInfo = NULL
static

◆ recentMulti

MultiXactId recentMulti
static

Definition at line 147 of file autovacuum.c.

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

◆ recentXid

TransactionId recentXid
static

Definition at line 146 of file autovacuum.c.

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