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

Go to the source code of this file.

Data Structures

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

Macros

#define 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)
 

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

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 134 of file autovacuum.c.

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

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

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 
AutoVacNumSignals 

Definition at line 239 of file autovacuum.c.

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

Function Documentation

◆ autovac_balance_cost()

static void autovac_balance_cost ( void  )
static

Definition at line 1795 of file autovacuum.c.

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

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

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

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3289 of file autovacuum.c.

3290 {
3292  ereport(WARNING,
3293  (errmsg("autovacuum not started because of misconfiguration"),
3294  errhint("Enable the \"track_counts\" option.")));
3295 }
bool autovacuum_start_daemon
Definition: autovacuum.c:115
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define WARNING
Definition: elog.h:30
#define ereport(elevel,...)
Definition: elog.h:143
bool pgstat_track_counts
Definition: pgstat.c:186

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

3161 {
3162 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3163  char activity[MAX_AUTOVAC_ACTIV_LEN];
3164  int len;
3165 
3166  /* Report the command and possible options */
3167  if (tab->at_params.options & VACOPT_VACUUM)
3168  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3169  "autovacuum: VACUUM%s",
3170  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3171  else
3172  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3173  "autovacuum: ANALYZE");
3174 
3175  /*
3176  * Report the qualified name of the relation.
3177  */
3178  len = strlen(activity);
3179 
3180  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3181  " %s.%s%s", tab->at_nspname, tab->at_relname,
3182  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3183 
3184  /* Set statement_timestamp() to current time for pg_stat_activity */
3186 
3188 }
#define MAX_AUTOVAC_ACTIV_LEN
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
const void size_t len
#define snprintf
Definition: port.h:225
bits32 options
Definition: vacuum.h:216
bool is_wraparound
Definition: vacuum.h:223
char * at_nspname
Definition: autovacuum.c:196
char * at_relname
Definition: autovacuum.c:195
VacuumParams at_params
Definition: autovacuum.c:190
#define VACOPT_VACUUM
Definition: vacuum.h:183
#define VACOPT_ANALYZE
Definition: vacuum.h:184
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:886

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

3197 {
3198  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3199  char blk[12 + 2];
3200  int len;
3201 
3202  switch (workitem->avw_type)
3203  {
3205  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3206  "autovacuum: BRIN summarize");
3207  break;
3208  }
3209 
3210  /*
3211  * Report the qualified name of the relation, and the block number if any
3212  */
3213  len = strlen(activity);
3214 
3215  if (BlockNumberIsValid(workitem->avw_blockNumber))
3216  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3217  else
3218  blk[0] = '\0';
3219 
3220  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3221  " %s.%s%s", nspname, relname, blk);
3222 
3223  /* Set statement_timestamp() to current time for pg_stat_activity */
3225 
3227 }
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
NameData relname
Definition: pg_class.h:38
BlockNumber avw_blockNumber
Definition: autovacuum.c:259
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:254

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

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

References AbortBufferIO(), AbortCurrentTransaction(), avl_dbase::adl_next_worker, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, am_autovacuum_launcher, AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), autovac_balance_cost(), AutoVacForkFailed, AutoVacLauncherShutdown(), AutovacMemCxt, AutoVacRebalance, autovacuum_naptime, AutoVacuumingActive(), AutoVacuumShmem, AuxProcessResourceOwner, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_signal, AutoVacuumShmemStruct::av_startingWorker, avl_sigusr2_handler(), B_AUTOVAC_LAUNCHER, BaseInit(), DatabaseList, DatabaseListCxt, DEBUG1, disable_all_timeouts(), dlist_init(), dlist_is_empty(), dlist_push_head(), dlist_tail_element, do_start_worker(), EmitErrorReport(), ereport, errmsg(), errmsg_internal(), error_context_stack, FloatExceptionHandler(), FlushErrorState(), GetCurrentTimestamp(), got_SIGUSR2, HandleAutoVacLauncherInterrupts(), HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InvalidOid, launch_worker(), launcher_determine_sleep(), LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), LWLockReleaseAll(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), Min, MyBackendType, MyLatch, MyProcPid, NormalProcessing, PG_exception_stack, PG_SETMASK, pg_usleep(), PGC_S_OVERRIDE, PGC_SUSET, pgstat_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 314 of file autovacuum.c.

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

3132 {
3133  RangeVar *rangevar;
3134  VacuumRelation *rel;
3135  List *rel_list;
3136 
3137  /* Let pgstat know what we're doing */
3139 
3140  /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3141  rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3142  rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3143  rel_list = list_make1(rel);
3144 
3145  vacuum(rel_list, &tab->at_params, bstrategy, true);
3146 }
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3160
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:813
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:423
#define NIL
Definition: pg_list.h:65
#define list_make1(x1)
Definition: pg_list.h:206
Definition: pg_list.h:51
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:298

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

Referenced by do_autovacuum().

◆ AutoVacuumingActive()

bool AutoVacuumingActive ( void  )

Definition at line 3235 of file autovacuum.c.

3236 {
3238  return false;
3239  return true;
3240 }

References autovacuum_start_daemon, and pgstat_track_counts.

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

◆ AutoVacuumRequestWork()

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

Definition at line 3247 of file autovacuum.c.

3249 {
3250  int i;
3251  bool result = false;
3252 
3253  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3254 
3255  /*
3256  * Locate an unused work item and fill it with the given data.
3257  */
3258  for (i = 0; i < NUM_WORKITEMS; i++)
3259  {
3261 
3262  if (workitem->avw_used)
3263  continue;
3264 
3265  workitem->avw_used = true;
3266  workitem->avw_active = false;
3267  workitem->avw_type = type;
3268  workitem->avw_database = MyDatabaseId;
3269  workitem->avw_relation = relationId;
3270  workitem->avw_blockNumber = blkno;
3271  result = true;
3272 
3273  /* done */
3274  break;
3275  }
3276 
3277  LWLockRelease(AutovacuumLock);
3278 
3279  return result;
3280 }
#define NUM_WORKITEMS
Definition: autovacuum.c:262
Oid MyDatabaseId
Definition: globals.c:89
int i
Definition: isn.c:73
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:287

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

3340 {
3341  bool found;
3342 
3344  ShmemInitStruct("AutoVacuum Data",
3346  &found);
3347 
3348  if (!IsUnderPostmaster)
3349  {
3350  WorkerInfo worker;
3351  int i;
3352 
3353  Assert(!found);
3354 
3359  memset(AutoVacuumShmem->av_workItems, 0,
3360  sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3361 
3362  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3363  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3364 
3365  /* initialize the WorkerInfo free list */
3366  for (i = 0; i < autovacuum_max_workers; i++)
3368  &worker[i].wi_links);
3369  }
3370  else
3371  Assert(found);
3372 }
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3320
int autovacuum_max_workers
Definition: autovacuum.c:116
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:232
#define MAXALIGN(LEN)
Definition: c.h:768
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 3320 of file autovacuum.c.

3321 {
3322  Size size;
3323 
3324  /*
3325  * Need the fixed struct and the array of WorkerInfoData.
3326  */
3327  size = sizeof(AutoVacuumShmemStruct);
3328  size = MAXALIGN(size);
3330  sizeof(WorkerInfoData)));
3331  return size;
3332 }
size_t Size
Definition: c.h:551
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 1779 of file autovacuum.c.

1780 {
1781  if (MyWorkerInfo)
1782  {
1785  }
1786 }
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:300

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

1411 {
1413 }

References AutoVacForkFailed, AutoVacuumShmem, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

◆ AutoVacWorkerMain()

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

Definition at line 1508 of file autovacuum.c.

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

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

Referenced by StartAutoVacWorker().

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1417 of file autovacuum.c.

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

References got_SIGUSR2, MyLatch, and SetLatch().

Referenced by AutoVacLauncherMain().

◆ db_comparator()

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

Definition at line 1126 of file autovacuum.c.

1127 {
1128  if (((const avl_dbase *) a)->adl_score == ((const avl_dbase *) b)->adl_score)
1129  return 0;
1130  else
1131  return (((const avl_dbase *) a)->adl_score < ((const avl_dbase *) b)->adl_score) ? 1 : -1;
1132 }
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 1953 of file autovacuum.c.

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

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

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

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

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

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

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

Referenced by AutoVacWorkerMain().

◆ get_database_list()

static List* get_database_list ( void  )
static

Definition at line 1883 of file autovacuum.c.

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

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

807 {
808  /* the normal shutdown case */
811 
813  {
814  ConfigReloadPending = false;
816 
817  /* shutdown requested in config file? */
818  if (!AutoVacuumingActive())
820 
821  /* rebalance in case the default cost parameters changed */
822  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
824  LWLockRelease(AutovacuumLock);
825 
826  /* rebuild the list in case the naptime changed */
828  }
829 
830  /* Process barrier events */
833 
834  /* Perform logging of memory contexts of this process */
837 
838  /* Process sinval catchup interrupts that happened while sleeping */
840 }
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:38
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1041
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:467
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 3303 of file autovacuum.c.

3304 {
3305  return am_autovacuum_launcher;
3306 }

References am_autovacuum_launcher.

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

◆ IsAutoVacuumWorkerProcess()

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1358 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain().

◆ launcher_determine_sleep()

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

Definition at line 863 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain().

◆ perform_work_item()

static void perform_work_item ( AutoVacuumWorkItem workitem)
static

Definition at line 2613 of file autovacuum.c.

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

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

Referenced by do_autovacuum().

◆ rebuild_database_list()

static void rebuild_database_list ( Oid  newdb)
static

Definition at line 947 of file autovacuum.c.

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

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, 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 2900 of file autovacuum.c.

2907 {
2908  PgStat_StatTabEntry *tabentry;
2909 
2910  /* fetch the pgstat table entry */
2911  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2912  relid);
2913 
2914  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2915  effective_multixact_freeze_max_age,
2916  dovacuum, doanalyze, wraparound);
2917 
2918  /* ignore ANALYZE for toast tables */
2919  if (classForm->relkind == RELKIND_TOASTVALUE)
2920  *doanalyze = false;
2921 }

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

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

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

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

◆ StartAutoVacWorker()

int StartAutoVacWorker ( void  )

Definition at line 1470 of file autovacuum.c.

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

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

2757 {
2758  Form_pg_class classForm;
2759  HeapTuple classTup;
2760  bool dovacuum;
2761  bool doanalyze;
2762  autovac_table *tab = NULL;
2763  bool wraparound;
2764  AutoVacOpts *avopts;
2765 
2766  /* fetch the relation's relcache entry */
2767  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2768  if (!HeapTupleIsValid(classTup))
2769  return NULL;
2770  classForm = (Form_pg_class) GETSTRUCT(classTup);
2771 
2772  /*
2773  * Get the applicable reloptions. If it is a TOAST table, try to get the
2774  * main table reloptions if the toast table itself doesn't have.
2775  */
2776  avopts = extract_autovac_opts(classTup, pg_class_desc);
2777  if (classForm->relkind == RELKIND_TOASTVALUE &&
2778  avopts == NULL && table_toast_map != NULL)
2779  {
2780  av_relation *hentry;
2781  bool found;
2782 
2783  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2784  if (found && hentry->ar_hasrelopts)
2785  avopts = &hentry->ar_reloptions;
2786  }
2787 
2788  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2789  effective_multixact_freeze_max_age,
2790  &dovacuum, &doanalyze, &wraparound);
2791 
2792  /* OK, it needs something done */
2793  if (doanalyze || dovacuum)
2794  {
2795  int freeze_min_age;
2796  int freeze_table_age;
2797  int multixact_freeze_min_age;
2798  int multixact_freeze_table_age;
2799  int vac_cost_limit;
2800  double vac_cost_delay;
2801  int log_min_duration;
2802 
2803  /*
2804  * Calculate the vacuum cost parameters and the freeze ages. If there
2805  * are options set in pg_class.reloptions, use them; in the case of a
2806  * toast table, try the main table too. Otherwise use the GUC
2807  * defaults, autovacuum's own first and plain vacuum second.
2808  */
2809 
2810  /* -1 in autovac setting means use plain vacuum_cost_delay */
2811  vac_cost_delay = (avopts && avopts->vacuum_cost_delay >= 0)
2812  ? avopts->vacuum_cost_delay
2813  : (autovacuum_vac_cost_delay >= 0)
2815  : VacuumCostDelay;
2816 
2817  /* 0 or -1 in autovac setting means use plain vacuum_cost_limit */
2818  vac_cost_limit = (avopts && avopts->vacuum_cost_limit > 0)
2819  ? avopts->vacuum_cost_limit
2822  : VacuumCostLimit;
2823 
2824  /* -1 in autovac setting means use log_autovacuum_min_duration */
2825  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2826  ? avopts->log_min_duration
2828 
2829  /* these do not have autovacuum-specific settings */
2830  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2831  ? avopts->freeze_min_age
2833 
2834  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2835  ? avopts->freeze_table_age
2837 
2838  multixact_freeze_min_age = (avopts &&
2839  avopts->multixact_freeze_min_age >= 0)
2840  ? avopts->multixact_freeze_min_age
2842 
2843  multixact_freeze_table_age = (avopts &&
2844  avopts->multixact_freeze_table_age >= 0)
2845  ? avopts->multixact_freeze_table_age
2847 
2848  tab = palloc(sizeof(autovac_table));
2849  tab->at_relid = relid;
2850  tab->at_sharedrel = classForm->relisshared;
2851 
2852  /* Note that this skips toast relations */
2853  tab->at_params.options = (dovacuum ? VACOPT_VACUUM : 0) |
2854  (doanalyze ? VACOPT_ANALYZE : 0) |
2855  (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2856 
2857  /*
2858  * index_cleanup and truncate are unspecified at first in autovacuum.
2859  * They will be filled in with usable values using their reloptions
2860  * (or reloption defaults) later.
2861  */
2864  /* As of now, we don't support parallel vacuum for autovacuum */
2865  tab->at_params.nworkers = -1;
2866  tab->at_params.freeze_min_age = freeze_min_age;
2867  tab->at_params.freeze_table_age = freeze_table_age;
2868  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2869  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2870  tab->at_params.is_wraparound = wraparound;
2871  tab->at_params.log_min_duration = log_min_duration;
2872  tab->at_vacuum_cost_limit = vac_cost_limit;
2873  tab->at_vacuum_cost_delay = vac_cost_delay;
2874  tab->at_relname = NULL;
2875  tab->at_nspname = NULL;
2876  tab->at_datname = NULL;
2877 
2878  /*
2879  * If any of the cost delay parameters has been set individually for
2880  * this table, disable the balancing algorithm.
2881  */
2882  tab->at_dobalance =
2883  !(avopts && (avopts->vacuum_cost_limit > 0 ||
2884  avopts->vacuum_cost_delay > 0));
2885  }
2886 
2887  heap_freetuple(classTup);
2888  return tab;
2889 }
int Log_autovacuum_min_duration
Definition: autovacuum.c:131
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:2900
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
int log_min_duration
Definition: rel.h:304
float8 vacuum_cost_delay
Definition: rel.h:305
int vacuum_cost_limit
Definition: rel.h:297
int multixact_freeze_table_age
Definition: rel.h:303
int freeze_min_age
Definition: rel.h:298
int freeze_table_age
Definition: rel.h:300
int multixact_freeze_min_age
Definition: rel.h:301
int nworkers
Definition: vacuum.h:235
int freeze_table_age
Definition: vacuum.h:218
VacOptValue truncate
Definition: vacuum.h:228
int freeze_min_age
Definition: vacuum.h:217
int multixact_freeze_min_age
Definition: vacuum.h:219
int multixact_freeze_table_age
Definition: vacuum.h:221
int log_min_duration
Definition: vacuum.h:224
VacOptValue index_cleanup
Definition: vacuum.h:227
bool at_sharedrel
Definition: autovacuum.c:194
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:188
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:202

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

Referenced by do_autovacuum().

Variable Documentation

◆ am_autovacuum_launcher

bool am_autovacuum_launcher = false
static

Definition at line 138 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and IsAutoVacuumLauncherProcess().

◆ am_autovacuum_worker

bool am_autovacuum_worker = false
static

Definition at line 139 of file autovacuum.c.

Referenced by AutoVacWorkerMain(), and IsAutoVacuumWorkerProcess().

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

◆ autovacuum_anl_scale

double autovacuum_anl_scale

Definition at line 124 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

int autovacuum_freeze_max_age

◆ autovacuum_max_workers

◆ autovacuum_multixact_freeze_max_age

int autovacuum_multixact_freeze_max_age

◆ autovacuum_naptime

int autovacuum_naptime

◆ autovacuum_start_daemon

bool autovacuum_start_daemon = false

Definition at line 115 of file autovacuum.c.

Referenced by autovac_init(), and AutoVacuumingActive().

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 128 of file autovacuum.c.

Referenced by autovac_balance_cost(), and table_recheck_autovac().

◆ autovacuum_vac_cost_limit

int autovacuum_vac_cost_limit

Definition at line 129 of file autovacuum.c.

Referenced by autovac_balance_cost(), and table_recheck_autovac().

◆ autovacuum_vac_ins_scale

double autovacuum_vac_ins_scale

Definition at line 122 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 121 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 120 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 119 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 117 of file autovacuum.c.

Referenced by dead_items_max_items(), and ginInsertCleanup().

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

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

Referenced by AutoVacLauncherMain(), and rebuild_database_list().

◆ default_freeze_min_age

int default_freeze_min_age
static

Definition at line 149 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 150 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 151 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 152 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 142 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and avl_sigusr2_handler().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = 600000

Definition at line 131 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

WorkerInfo MyWorkerInfo = NULL
static

◆ recentMulti

MultiXactId recentMulti
static

Definition at line 146 of file autovacuum.c.

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

◆ recentXid

TransactionId recentXid
static

Definition at line 145 of file autovacuum.c.

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