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 "catalog/pg_namespace.h"
#include "commands/dbcommands.h"
#include "commands/vacuum.h"
#include "common/int.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/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/smgr.h"
#include "tcop/tcopprot.h"
#include "utils/fmgroids.h"
#include "utils/fmgrprotos.h"
#include "utils/guc_hooks.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/ps_status.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
Include dependency graph for autovacuum.c:

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Enumerations

enum  AutoVacuumSignal { AutoVacForkFailed , AutoVacRebalance , AutoVacNumSignals }
 

Functions

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)
 
void AutoVacWorkerMain (char *startup_data, size_t startup_data_len)
 
static void FreeWorkerInfo (int code, Datum arg)
 
void VacuumUpdateCosts (void)
 
void AutoVacuumUpdateCostLimit (void)
 
static void autovac_recalculate_workers_for_balance (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)
 
Size AutoVacuumShmemSize (void)
 
void AutoVacuumShmemInit (void)
 
bool check_autovacuum_work_mem (int *newval, void **extra, GucSource source)
 

Variables

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

Macro Definition Documentation

◆ MAX_AUTOVAC_ACTIV_LEN

#define MAX_AUTOVAC_ACTIV_LEN   (NAMEDATALEN * 2 + 56)

◆ MAX_AUTOVAC_SLEEPTIME

#define MAX_AUTOVAC_SLEEPTIME   300 /* seconds */

Definition at line 136 of file autovacuum.c.

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 135 of file autovacuum.c.

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

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

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 
AutoVacNumSignals 

Definition at line 245 of file autovacuum.c.

246 {
247  AutoVacForkFailed, /* failed trying to start a worker */
248  AutoVacRebalance, /* rebalance the cost limits */
249  AutoVacNumSignals, /* must be last */
AutoVacuumSignal
Definition: autovacuum.c:246
@ AutoVacRebalance
Definition: autovacuum.c:248
@ AutoVacForkFailed
Definition: autovacuum.c:247
@ AutoVacNumSignals
Definition: autovacuum.c:249

Function Documentation

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3243 of file autovacuum.c.

3244 {
3246  ereport(WARNING,
3247  (errmsg("autovacuum not started because of misconfiguration"),
3248  errhint("Enable the \"track_counts\" option.")));
3249 }
bool autovacuum_start_daemon
Definition: autovacuum.c:116
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define WARNING
Definition: elog.h:36
#define ereport(elevel,...)
Definition: elog.h:149
bool pgstat_track_counts
Definition: pgstat.c:184

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

Referenced by PostmasterMain().

◆ autovac_recalculate_workers_for_balance()

static void autovac_recalculate_workers_for_balance ( void  )
static

Definition at line 1748 of file autovacuum.c.

1749 {
1750  dlist_iter iter;
1751  int orig_nworkers_for_balance;
1752  int nworkers_for_balance = 0;
1753 
1754  Assert(LWLockHeldByMe(AutovacuumLock));
1755 
1756  orig_nworkers_for_balance =
1758 
1760  {
1761  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1762 
1763  if (worker->wi_proc == NULL ||
1765  continue;
1766 
1767  nworkers_for_balance++;
1768  }
1769 
1770  if (nworkers_for_balance != orig_nworkers_for_balance)
1772  nworkers_for_balance);
1773 }
static bool pg_atomic_unlocked_test_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:191
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:271
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:234
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:299
#define Assert(condition)
Definition: c.h:858
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
bool LWLockHeldByMe(LWLock *lock)
Definition: lwlock.c:1895
pg_atomic_uint32 av_nworkersForBalance
Definition: autovacuum.c:296
dlist_head av_runningWorkers
Definition: autovacuum.c:293
PGPROC * wi_proc
Definition: autovacuum.c:232
pg_atomic_flag wi_dobalance
Definition: autovacuum.c:234
dlist_node * cur
Definition: ilist.h:179

References Assert, AutoVacuumShmem, AutoVacuumShmemStruct::av_nworkersForBalance, AutoVacuumShmemStruct::av_runningWorkers, dlist_iter::cur, dlist_container, dlist_foreach, LWLockHeldByMe(), pg_atomic_read_u32(), pg_atomic_unlocked_test_flag(), pg_atomic_write_u32(), WorkerInfoData::wi_dobalance, and WorkerInfoData::wi_proc.

Referenced by do_autovacuum().

◆ autovac_report_activity()

static void autovac_report_activity ( autovac_table tab)
static

Definition at line 3114 of file autovacuum.c.

3115 {
3116 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3117  char activity[MAX_AUTOVAC_ACTIV_LEN];
3118  int len;
3119 
3120  /* Report the command and possible options */
3121  if (tab->at_params.options & VACOPT_VACUUM)
3122  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3123  "autovacuum: VACUUM%s",
3124  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3125  else
3126  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3127  "autovacuum: ANALYZE");
3128 
3129  /*
3130  * Report the qualified name of the relation.
3131  */
3132  len = strlen(activity);
3133 
3134  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3135  " %s.%s%s", tab->at_nspname, tab->at_relname,
3136  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3137 
3138  /* Set statement_timestamp() to current time for pg_stat_activity */
3140 
3142 }
#define MAX_AUTOVAC_ACTIV_LEN
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
const void size_t len
#define snprintf
Definition: port.h:238
bits32 options
Definition: vacuum.h:219
bool is_wraparound
Definition: vacuum.h:226
char * at_nspname
Definition: autovacuum.c:205
char * at_relname
Definition: autovacuum.c:204
VacuumParams at_params
Definition: autovacuum.c:199
#define VACOPT_VACUUM
Definition: vacuum.h:180
#define VACOPT_ANALYZE
Definition: vacuum.h:181
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:911

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

3151 {
3152  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3153  char blk[12 + 2];
3154  int len;
3155 
3156  switch (workitem->avw_type)
3157  {
3159  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3160  "autovacuum: BRIN summarize");
3161  break;
3162  }
3163 
3164  /*
3165  * Report the qualified name of the relation, and the block number if any
3166  */
3167  len = strlen(activity);
3168 
3169  if (BlockNumberIsValid(workitem->avw_blockNumber))
3170  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3171  else
3172  blk[0] = '\0';
3173 
3174  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3175  " %s.%s%s", nspname, relname, blk);
3176 
3177  /* Set statement_timestamp() to current time for pg_stat_activity */
3179 
3181 }
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
NameData relname
Definition: pg_class.h:38
BlockNumber avw_blockNumber
Definition: autovacuum.c:265
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:260

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

◆ AutoVacLauncherShutdown()

static void AutoVacLauncherShutdown ( void  )
static

Definition at line 316 of file autovacuum.c.

362 {
363  sigjmp_buf local_sigjmp_buf;
364 
365  Assert(startup_data_len == 0);
366 
367  /* Release postmaster's working memory context */
368  if (PostmasterContext)
369  {
371  PostmasterContext = NULL;
372  }
373 
375  init_ps_display(NULL);
376 
377  ereport(DEBUG1,
378  (errmsg_internal("autovacuum launcher started")));
379 
380  if (PostAuthDelay)
381  pg_usleep(PostAuthDelay * 1000000L);
382 
384 
385  /*
386  * Set up signal handlers. We operate on databases much like a regular
387  * backend, so we use the same signal handling. See equivalent code in
388  * tcop/postgres.c.
389  */
393  /* SIGQUIT handler was already set up by InitPostmasterChild */
394 
395  InitializeTimeouts(); /* establishes SIGALRM handler */
396 
402 
403  /*
404  * Create a per-backend PGPROC struct in shared memory. We must do this
405  * before we can use LWLocks or access any shared memory.
406  */
407  InitProcess();
408 
409  /* Early initialization */
410  BaseInit();
411 
412  InitPostgres(NULL, InvalidOid, NULL, InvalidOid, 0, NULL);
413 
415 
416  /*
417  * Create a memory context that we will do all our work in. We do this so
418  * that we can reset the context during error recovery and thereby avoid
419  * possible memory leaks.
420  */
422  "Autovacuum Launcher",
425 
426  /*
427  * If an exception is encountered, processing resumes here.
428  *
429  * This code is a stripped down version of PostgresMain error recovery.
430  *
431  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
432  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
433  * signals other than SIGQUIT will be blocked until we complete error
434  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
435  * call redundant, but it is not since InterruptPending might be set
436  * already.
437  */
438  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
439  {
440  /* since not using PG_TRY, must reset error stack by hand */
441  error_context_stack = NULL;
442 
443  /* Prevents interrupts while cleaning up */
444  HOLD_INTERRUPTS();
445 
446  /* Forget any pending QueryCancel or timeout request */
447  disable_all_timeouts(false);
448  QueryCancelPending = false; /* second to avoid race condition */
449 
450  /* Report the error to the server log */
451  EmitErrorReport();
452 
453  /* Abort the current transaction in order to recover */
455 
456  /*
457  * Release any other resources, for the case where we were not in a
458  * transaction.
459  */
462  UnlockBuffers();
463  /* this is probably dead code, but let's be safe: */
466  AtEOXact_Buffers(false);
467  AtEOXact_SMgr();
468  AtEOXact_Files(false);
469  AtEOXact_HashTables(false);
470 
471  /*
472  * Now return to normal top-level context and clear ErrorContext for
473  * next time.
474  */
476  FlushErrorState();
477 
478  /* Flush any leaked data in the top-level context */
480 
481  /* don't leave dangling pointers to freed memory */
482  DatabaseListCxt = NULL;
484 
485  /* Now we can allow interrupts again */
487 
488  /* if in shutdown mode, no need for anything further; just go away */
491 
492  /*
493  * Sleep at least 1 second after any error. We don't want to be
494  * filling the error logs as fast as we can.
495  */
496  pg_usleep(1000000L);
497  }
498 
499  /* We can now handle ereport(ERROR) */
500  PG_exception_stack = &local_sigjmp_buf;
501 
502  /* must unblock signals before calling rebuild_database_list */
503  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
504 
505  /*
506  * Set always-secure search path. Launcher doesn't connect to a database,
507  * so this has no effect.
508  */
509  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
510 
511  /*
512  * Force zero_damaged_pages OFF in the autovac process, even if it is set
513  * in postgresql.conf. We don't really want such a dangerous option being
514  * applied non-interactively.
515  */
516  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
517 
518  /*
519  * Force settable timeouts off to avoid letting these settings prevent
520  * regular maintenance from being executed.
521  */
522  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
523  SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
524  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
525  SetConfigOption("idle_in_transaction_session_timeout", "0",
527 
528  /*
529  * Force default_transaction_isolation to READ COMMITTED. We don't want
530  * to pay the overhead of serializable mode, nor add any risk of causing
531  * deadlocks or delaying other transactions.
532  */
533  SetConfigOption("default_transaction_isolation", "read committed",
535 
536  /*
537  * Even when system is configured to use a different fetch consistency,
538  * for autovac we always want fresh stats.
539  */
540  SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
541 
542  /*
543  * In emergency mode, just start a worker (unless shutdown was requested)
544  * and go away.
545  */
546  if (!AutoVacuumingActive())
547  {
549  do_start_worker();
550  proc_exit(0); /* done */
551  }
552 
554 
555  /*
556  * Create the initial database list. The invariant we want this list to
557  * keep is that it's ordered by decreasing next_time. As soon as an entry
558  * is updated to a higher time, it will be moved to the front (which is
559  * correct because the only operation is to add autovacuum_naptime to the
560  * entry, and time always increases).
561  */
563 
564  /* loop until shutdown request */
565  while (!ShutdownRequestPending)
566  {
567  struct timeval nap;
568  TimestampTz current_time = 0;
569  bool can_launch;
570 
571  /*
572  * This loop is a bit different from the normal use of WaitLatch,
573  * because we'd like to sleep before the first launch of a child
574  * process. So it's WaitLatch, then ResetLatch, then check for
575  * wakening conditions.
576  */
577 
579  false, &nap);
580 
581  /*
582  * Wait until naptime expires or we get some type of signal (all the
583  * signal handlers will wake us by calling SetLatch).
584  */
585  (void) WaitLatch(MyLatch,
587  (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
588  WAIT_EVENT_AUTOVACUUM_MAIN);
589 
591 
593 
594  /*
595  * a worker finished, or postmaster signaled failure to start a worker
596  */
597  if (got_SIGUSR2)
598  {
599  got_SIGUSR2 = false;
600 
601  /* rebalance cost limits, if needed */
603  {
604  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
607  LWLockRelease(AutovacuumLock);
608  }
609 
611  {
612  /*
613  * If the postmaster failed to start a new worker, we sleep
614  * for a little while and resend the signal. The new worker's
615  * state is still in memory, so this is sufficient. After
616  * that, we restart the main loop.
617  *
618  * XXX should we put a limit to the number of times we retry?
619  * I don't think it makes much sense, because a future start
620  * of a worker will continue to fail in the same way.
621  */
623  pg_usleep(1000000L); /* 1s */
625  continue;
626  }
627  }
628 
629  /*
630  * There are some conditions that we need to check before trying to
631  * start a worker. First, we need to make sure that there is a worker
632  * slot available. Second, we need to make sure that no other worker
633  * failed while starting up.
634  */
635 
636  current_time = GetCurrentTimestamp();
637  LWLockAcquire(AutovacuumLock, LW_SHARED);
638 
640 
641  if (AutoVacuumShmem->av_startingWorker != NULL)
642  {
643  int waittime;
645 
646  /*
647  * We can't launch another worker when another one is still
648  * starting up (or failed while doing so), so just sleep for a bit
649  * more; that worker will wake us up again as soon as it's ready.
650  * We will only wait autovacuum_naptime seconds (up to a maximum
651  * of 60 seconds) for this to happen however. Note that failure
652  * to connect to a particular database is not a problem here,
653  * because the worker removes itself from the startingWorker
654  * pointer before trying to connect. Problems detected by the
655  * postmaster (like fork() failure) are also reported and handled
656  * differently. The only problems that may cause this code to
657  * fire are errors in the earlier sections of AutoVacWorkerMain,
658  * before the worker removes the WorkerInfo from the
659  * startingWorker pointer.
660  */
661  waittime = Min(autovacuum_naptime, 60) * 1000;
662  if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
663  waittime))
664  {
665  LWLockRelease(AutovacuumLock);
666  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
667 
668  /*
669  * No other process can put a worker in starting mode, so if
670  * startingWorker is still INVALID after exchanging our lock,
671  * we assume it's the same one we saw above (so we don't
672  * recheck the launch time).
673  */
674  if (AutoVacuumShmem->av_startingWorker != NULL)
675  {
677  worker->wi_dboid = InvalidOid;
678  worker->wi_tableoid = InvalidOid;
679  worker->wi_sharedrel = false;
680  worker->wi_proc = NULL;
681  worker->wi_launchtime = 0;
683  &worker->wi_links);
686  errmsg("autovacuum worker took too long to start; canceled"));
687  }
688  }
689  else
690  can_launch = false;
691  }
692  LWLockRelease(AutovacuumLock); /* either shared or exclusive */
693 
694  /* if we can't do anything, just go back to sleep */
695  if (!can_launch)
696  continue;
697 
698  /* We're OK to start a new worker */
699 
701  {
702  /*
703  * Special case when the list is empty: start a worker right away.
704  * This covers the initial case, when no database is in pgstats
705  * (thus the list is empty). Note that the constraints in
706  * launcher_determine_sleep keep us from starting workers too
707  * quickly (at most once every autovacuum_naptime when the list is
708  * empty).
709  */
710  launch_worker(current_time);
711  }
712  else
713  {
714  /*
715  * because rebuild_database_list constructs a list with most
716  * distant adl_next_worker first, we obtain our database from the
717  * tail of the list.
718  */
719  avl_dbase *avdb;
720 
721  avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
722 
723  /*
724  * launch a worker if next_worker is right now or it is in the
725  * past
726  */
728  current_time, 0))
729  launch_worker(current_time);
730  }
731  }
732 
734 }
static Oid do_start_worker(void)
Definition: autovacuum.c:1073
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition: autovacuum.c:792
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:151
static void avl_sigusr2_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1344
static void HandleAutoVacLauncherInterrupts(void)
Definition: autovacuum.c:740
int autovacuum_naptime
Definition: autovacuum.c:119
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3189
static void AutoVacLauncherShutdown(void)
Definition: autovacuum.c:316
static void launch_worker(TimestampTz now)
Definition: autovacuum.c:1285
static dlist_head DatabaseList
Definition: autovacuum.c:305
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:876
static MemoryContext DatabaseListCxt
Definition: autovacuum.c:306
static void autovac_recalculate_workers_for_balance(void)
Definition: autovacuum.c:1748
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:164
sigset_t UnBlockSig
Definition: pqsignal.c:22
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1790
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:3502
void UnlockBuffers(void)
Definition: bufmgr.c:5057
#define Min(x, y)
Definition: c.h:1004
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1869
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
void EmitErrorReport(void)
Definition: elog.c:1672
ErrorContextCallback * error_context_stack
Definition: elog.c:94
void FlushErrorState(void)
Definition: elog.c:1836
sigjmp_buf * PG_exception_stack
Definition: elog.c:96
#define DEBUG1
Definition: elog.h:30
void AtEOXact_Files(bool isCommit)
Definition: fd.c:3165
int MyProcPid
Definition: globals.c:45
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:31
struct Latch * MyLatch
Definition: globals.c:60
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4285
@ PGC_S_OVERRIDE
Definition: guc.h:119
@ PGC_SUSET
Definition: guc.h:74
static void dlist_init(dlist_head *head)
Definition: ilist.h:314
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:612
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:347
static bool dlist_is_empty(const dlist_head *head)
Definition: ilist.h:336
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:105
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:724
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:517
#define WL_TIMEOUT
Definition: latch.h:130
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_LATCH_SET
Definition: latch.h:127
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1170
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783
void LWLockReleaseAll(void)
Definition: lwlock.c:1878
@ LW_SHARED
Definition: lwlock.h:115
@ LW_EXCLUSIVE
Definition: lwlock.h:114
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
MemoryContext TopMemoryContext
Definition: mcxt.c:149
MemoryContext PostmasterContext
Definition: mcxt.c:151
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
@ NormalProcessing
Definition: miscadmin.h:449
@ InitProcessing
Definition: miscadmin.h:448
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
#define SetProcessingMode(mode)
Definition: miscadmin.h:460
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:339
BackendType MyBackendType
Definition: miscinit.c:63
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:181
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition: pmsignal.h:39
pqsigfunc pqsignal(int signo, pqsigfunc func)
int PostAuthDelay
Definition: postgres.c:101
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3019
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3002
#define InvalidOid
Definition: postgres_ext.h:36
void BaseInit(void)
Definition: postinit.c:645
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:736
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:635
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:267
MemoryContextSwitchTo(old_ctx)
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:1002
ResourceOwner AuxProcessResourceOwner
Definition: resowner.c:168
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:807
void InitProcess(void)
Definition: proc.c:296
dlist_head av_freeWorkers
Definition: autovacuum.c:292
WorkerInfo av_startingWorker
Definition: autovacuum.c:294
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:290
TimestampTz wi_launchtime
Definition: autovacuum.c:233
dlist_node wi_links
Definition: autovacuum.c:229
TimestampTz adl_next_worker
Definition: autovacuum.c:170
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:751
void InitializeTimeouts(void)
Definition: timeout.c:470
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
#define SIGCHLD
Definition: win32_port.h:178
#define SIGHUP
Definition: win32_port.h:168
#define SIG_DFL
Definition: win32_port.h:163
#define SIGPIPE
Definition: win32_port.h:173
#define SIGUSR1
Definition: win32_port.h:180
#define SIGUSR2
Definition: win32_port.h:181
#define SIG_IGN
Definition: win32_port.h:165
void AbortCurrentTransaction(void)
Definition: xact.c:3387

Referenced by HandleAutoVacLauncherInterrupts().

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3078 of file autovacuum.c.

3079 {
3080  RangeVar *rangevar;
3081  VacuumRelation *rel;
3082  List *rel_list;
3083  MemoryContext vac_context;
3084 
3085  /* Let pgstat know what we're doing */
3087 
3088  /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3089  rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3090  rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3091  rel_list = list_make1(rel);
3092 
3094  "Vacuum",
3096 
3097  vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3098 
3099  MemoryContextDelete(vac_context);
3100 }
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3114
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:832
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
Definition: pg_list.h:54
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, MemoryContext vac_context, bool isTopLevel)
Definition: vacuum.c:478

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

Referenced by do_autovacuum().

◆ AutoVacuumingActive()

bool AutoVacuumingActive ( void  )

Definition at line 3189 of file autovacuum.c.

3190 {
3192  return false;
3193  return true;
3194 }

References autovacuum_start_daemon, and pgstat_track_counts.

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

◆ AutoVacuumRequestWork()

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

Definition at line 3201 of file autovacuum.c.

3203 {
3204  int i;
3205  bool result = false;
3206 
3207  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3208 
3209  /*
3210  * Locate an unused work item and fill it with the given data.
3211  */
3212  for (i = 0; i < NUM_WORKITEMS; i++)
3213  {
3215 
3216  if (workitem->avw_used)
3217  continue;
3218 
3219  workitem->avw_used = true;
3220  workitem->avw_active = false;
3221  workitem->avw_type = type;
3222  workitem->avw_database = MyDatabaseId;
3223  workitem->avw_relation = relationId;
3224  workitem->avw_blockNumber = blkno;
3225  result = true;
3226 
3227  /* done */
3228  break;
3229  }
3230 
3231  LWLockRelease(AutovacuumLock);
3232 
3233  return result;
3234 }
#define NUM_WORKITEMS
Definition: autovacuum.c:268
Oid MyDatabaseId
Definition: globals.c:91
int i
Definition: isn.c:73
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:295
const char * type

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 type.

Referenced by brininsert().

◆ AutoVacuumShmemInit()

void AutoVacuumShmemInit ( void  )

Definition at line 3275 of file autovacuum.c.

3276 {
3277  bool found;
3278 
3280  ShmemInitStruct("AutoVacuum Data",
3282  &found);
3283 
3284  if (!IsUnderPostmaster)
3285  {
3286  WorkerInfo worker;
3287  int i;
3288 
3289  Assert(!found);
3290 
3295  memset(AutoVacuumShmem->av_workItems, 0,
3296  sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3297 
3298  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3299  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3300 
3301  /* initialize the WorkerInfo free list */
3302  for (i = 0; i < autovacuum_max_workers; i++)
3303  {
3305  &worker[i].wi_links);
3306  pg_atomic_init_flag(&worker[i].wi_dobalance);
3307  }
3308 
3310 
3311  }
3312  else
3313  Assert(found);
3314 }
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:216
static void pg_atomic_init_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:165
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3256
int autovacuum_max_workers
Definition: autovacuum.c:117
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:238
#define MAXALIGN(LEN)
Definition: c.h:811
bool IsUnderPostmaster
Definition: globals.c:117
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387

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

Referenced by CreateOrAttachShmemStructs().

◆ AutoVacuumShmemSize()

Size AutoVacuumShmemSize ( void  )

Definition at line 3256 of file autovacuum.c.

3257 {
3258  Size size;
3259 
3260  /*
3261  * Need the fixed struct and the array of WorkerInfoData.
3262  */
3263  size = sizeof(AutoVacuumShmemStruct);
3264  size = MAXALIGN(size);
3266  sizeof(WorkerInfoData)));
3267  return size;
3268 }
size_t Size
Definition: c.h:605
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
static pg_noinline void Size size
Definition: slab.c:607

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

Referenced by AutoVacuumShmemInit(), and CalculateShmemSize().

◆ AutoVacuumUpdateCostLimit()

void AutoVacuumUpdateCostLimit ( void  )

Definition at line 1702 of file autovacuum.c.

1703 {
1704  if (!MyWorkerInfo)
1705  return;
1706 
1707  /*
1708  * note: in cost_limit, zero also means use value from elsewhere, because
1709  * zero is not a valid value.
1710  */
1711 
1714  else
1715  {
1716  int nworkers_for_balance;
1717 
1718  if (autovacuum_vac_cost_limit > 0)
1720  else
1722 
1723  /* Only balance limit if no cost-related storage parameters specified */
1725  return;
1726 
1728 
1729  nworkers_for_balance = pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1730 
1731  /* There is at least 1 autovac worker (this worker) */
1732  if (nworkers_for_balance <= 0)
1733  elog(ERROR, "nworkers_for_balance must be > 0");
1734 
1735  vacuum_cost_limit = Max(vacuum_cost_limit / nworkers_for_balance, 1);
1736  }
1737 }
int autovacuum_vac_cost_limit
Definition: autovacuum.c:130
static int av_storage_param_cost_limit
Definition: autovacuum.c:148
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:309
#define Max(x, y)
Definition: c.h:998
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
int VacuumCostLimit
Definition: globals.c:151
int vacuum_cost_limit
Definition: vacuum.c:81

References Assert, autovacuum_vac_cost_limit, AutoVacuumShmem, AutoVacuumShmemStruct::av_nworkersForBalance, av_storage_param_cost_limit, elog, ERROR, Max, MyWorkerInfo, pg_atomic_read_u32(), pg_atomic_unlocked_test_flag(), vacuum_cost_limit, VacuumCostLimit, and WorkerInfoData::wi_dobalance.

Referenced by vacuum_delay_point(), and VacuumUpdateCosts().

◆ AutoVacWorkerFailed()

void AutoVacWorkerFailed ( void  )

Definition at line 1337 of file autovacuum.c.

1338 {
1340 }

References AutoVacForkFailed, AutoVacuumShmem, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

◆ AutoVacWorkerMain()

void AutoVacWorkerMain ( char *  startup_data,
size_t  startup_data_len 
)

Definition at line 1359 of file autovacuum.c.

1360 {
1361  sigjmp_buf local_sigjmp_buf;
1362  Oid dbid;
1363 
1364  Assert(startup_data_len == 0);
1365 
1366  /* Release postmaster's working memory context */
1367  if (PostmasterContext)
1368  {
1370  PostmasterContext = NULL;
1371  }
1372 
1374  init_ps_display(NULL);
1375 
1377 
1378  /*
1379  * Set up signal handlers. We operate on databases much like a regular
1380  * backend, so we use the same signal handling. See equivalent code in
1381  * tcop/postgres.c.
1382  */
1384 
1385  /*
1386  * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1387  * means abort and exit cleanly, and SIGQUIT means abandon ship.
1388  */
1390  pqsignal(SIGTERM, die);
1391  /* SIGQUIT handler was already set up by InitPostmasterChild */
1392 
1393  InitializeTimeouts(); /* establishes SIGALRM handler */
1394 
1400 
1401  /*
1402  * Create a per-backend PGPROC struct in shared memory. We must do this
1403  * before we can use LWLocks or access any shared memory.
1404  */
1405  InitProcess();
1406 
1407  /* Early initialization */
1408  BaseInit();
1409 
1410  /*
1411  * If an exception is encountered, processing resumes here.
1412  *
1413  * Unlike most auxiliary processes, we don't attempt to continue
1414  * processing after an error; we just clean up and exit. The autovac
1415  * launcher is responsible for spawning another worker later.
1416  *
1417  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
1418  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
1419  * signals other than SIGQUIT will be blocked until we exit. It might
1420  * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
1421  * it is not since InterruptPending might be set already.
1422  */
1423  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1424  {
1425  /* since not using PG_TRY, must reset error stack by hand */
1426  error_context_stack = NULL;
1427 
1428  /* Prevents interrupts while cleaning up */
1429  HOLD_INTERRUPTS();
1430 
1431  /* Report the error to the server log */
1432  EmitErrorReport();
1433 
1434  /*
1435  * We can now go away. Note that because we called InitProcess, a
1436  * callback was registered to do ProcKill, which will clean up
1437  * necessary state.
1438  */
1439  proc_exit(0);
1440  }
1441 
1442  /* We can now handle ereport(ERROR) */
1443  PG_exception_stack = &local_sigjmp_buf;
1444 
1445  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
1446 
1447  /*
1448  * Set always-secure search path, so malicious users can't redirect user
1449  * code (e.g. pg_index.indexprs). (That code runs in a
1450  * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1451  * take control of the entire autovacuum worker in any case.)
1452  */
1453  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1454 
1455  /*
1456  * Force zero_damaged_pages OFF in the autovac process, even if it is set
1457  * in postgresql.conf. We don't really want such a dangerous option being
1458  * applied non-interactively.
1459  */
1460  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1461 
1462  /*
1463  * Force settable timeouts off to avoid letting these settings prevent
1464  * regular maintenance from being executed.
1465  */
1466  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1467  SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1468  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1469  SetConfigOption("idle_in_transaction_session_timeout", "0",
1471 
1472  /*
1473  * Force default_transaction_isolation to READ COMMITTED. We don't want
1474  * to pay the overhead of serializable mode, nor add any risk of causing
1475  * deadlocks or delaying other transactions.
1476  */
1477  SetConfigOption("default_transaction_isolation", "read committed",
1479 
1480  /*
1481  * Force synchronous replication off to allow regular maintenance even if
1482  * we are waiting for standbys to connect. This is important to ensure we
1483  * aren't blocked from performing anti-wraparound tasks.
1484  */
1486  SetConfigOption("synchronous_commit", "local",
1488 
1489  /*
1490  * Even when system is configured to use a different fetch consistency,
1491  * for autovac we always want fresh stats.
1492  */
1493  SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
1494 
1495  /*
1496  * Get the info about the database we're going to work on.
1497  */
1498  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1499 
1500  /*
1501  * beware of startingWorker being INVALID; this should normally not
1502  * happen, but if a worker fails after forking and before this, the
1503  * launcher might have decided to remove it from the queue and start
1504  * again.
1505  */
1506  if (AutoVacuumShmem->av_startingWorker != NULL)
1507  {
1509  dbid = MyWorkerInfo->wi_dboid;
1511 
1512  /* insert into the running list */
1515 
1516  /*
1517  * remove from the "starting" pointer, so that the launcher can start
1518  * a new worker if required
1519  */
1521  LWLockRelease(AutovacuumLock);
1522 
1524 
1525  /* wake up the launcher */
1526  if (AutoVacuumShmem->av_launcherpid != 0)
1528  }
1529  else
1530  {
1531  /* no worker entry for me, go away */
1532  elog(WARNING, "autovacuum worker started without a worker entry");
1533  dbid = InvalidOid;
1534  LWLockRelease(AutovacuumLock);
1535  }
1536 
1537  if (OidIsValid(dbid))
1538  {
1539  char dbname[NAMEDATALEN];
1540 
1541  /*
1542  * Report autovac startup to the cumulative stats system. We
1543  * deliberately do this before InitPostgres, so that the
1544  * last_autovac_time will get updated even if the connection attempt
1545  * fails. This is to prevent autovac from getting "stuck" repeatedly
1546  * selecting an unopenable database, rather than making any progress
1547  * on stuff it can connect to.
1548  */
1549  pgstat_report_autovac(dbid);
1550 
1551  /*
1552  * Connect to the selected database, specifying no particular user
1553  *
1554  * Note: if we have selected a just-deleted database (due to using
1555  * stale stats info), we'll fail and exit here.
1556  */
1557  InitPostgres(NULL, dbid, NULL, InvalidOid, 0, dbname);
1560  ereport(DEBUG1,
1561  (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1562 
1563  if (PostAuthDelay)
1564  pg_usleep(PostAuthDelay * 1000000L);
1565 
1566  /* And do an appropriate amount of work */
1569  do_autovacuum();
1570  }
1571 
1572  /*
1573  * The launcher will be notified of my death in ProcKill, *if* we managed
1574  * to get a worker slot at all
1575  */
1576 
1577  /* All done, go away */
1578  proc_exit(0);
1579 }
static void FreeWorkerInfo(int code, Datum arg)
Definition: autovacuum.c:1585
static TransactionId recentXid
Definition: autovacuum.c:154
static void do_autovacuum(void)
Definition: autovacuum.c:1873
static MultiXactId recentMulti
Definition: autovacuum.c:155
#define OidIsValid(objectId)
Definition: c.h:775
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:365
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:340
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:729
#define NAMEDATALEN
#define die(msg)
void pgstat_report_autovac(Oid dboid)
unsigned int Oid
Definition: postgres_ext.h:31
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
PGPROC * MyProc
Definition: proc.c:66
char * dbname
Definition: streamutil.c:52
static TransactionId ReadNextTransactionId(void)
Definition: transam.h:315
#define kill(pid, sig)
Definition: win32_port.h:485
int synchronous_commit
Definition: xact.c:85
@ SYNCHRONOUS_COMMIT_LOCAL_FLUSH
Definition: xact.h:71

References Assert, 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(), MemoryContextDelete(), MyBackendType, MyProc, MyWorkerInfo, NAMEDATALEN, NormalProcessing, OidIsValid, on_shmem_exit(), PG_exception_stack, pg_usleep(), PGC_S_OVERRIDE, PGC_SUSET, pgstat_report_autovac(), PostAuthDelay, PostmasterContext, 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.

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1344 of file autovacuum.c.

1345 {
1346  got_SIGUSR2 = true;
1347  SetLatch(MyLatch);
1348 }
void SetLatch(Latch *latch)
Definition: latch.c:632

References got_SIGUSR2, MyLatch, and SetLatch().

◆ check_autovacuum_work_mem()

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

Definition at line 3320 of file autovacuum.c.

3321 {
3322  /*
3323  * -1 indicates fallback.
3324  *
3325  * If we haven't yet changed the boot_val default of -1, just let it be.
3326  * Autovacuum will look to maintenance_work_mem instead.
3327  */
3328  if (*newval == -1)
3329  return true;
3330 
3331  /*
3332  * We clamp manually-set values to at least 1MB. Since
3333  * maintenance_work_mem is always set to at least this value, do the same
3334  * here.
3335  */
3336  if (*newval < 1024)
3337  *newval = 1024;
3338 
3339  return true;
3340 }
#define newval

References newval.

◆ db_comparator()

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

Definition at line 1055 of file autovacuum.c.

1056 {
1057  return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1058  ((const avl_dbase *) b)->adl_score);
1059 }
static int pg_cmp_s32(int32 a, int32 b)
Definition: int.h:483
int b
Definition: isn.c:70
int a
Definition: isn.c:69

References a, b, and pg_cmp_s32().

Referenced by rebuild_database_list().

◆ do_autovacuum()

static void do_autovacuum ( void  )
static

Definition at line 1873 of file autovacuum.c.

1874 {
1875  Relation classRel;
1876  HeapTuple tuple;
1877  TableScanDesc relScan;
1878  Form_pg_database dbForm;
1879  List *table_oids = NIL;
1880  List *orphan_oids = NIL;
1881  HASHCTL ctl;
1882  HTAB *table_toast_map;
1883  ListCell *volatile cell;
1884  BufferAccessStrategy bstrategy;
1885  ScanKeyData key;
1886  TupleDesc pg_class_desc;
1887  int effective_multixact_freeze_max_age;
1888  bool did_vacuum = false;
1889  bool found_concurrent_worker = false;
1890  int i;
1891 
1892  /*
1893  * StartTransactionCommand and CommitTransactionCommand will automatically
1894  * switch to other contexts. We need this one to keep the list of
1895  * relations to vacuum/analyze across transactions.
1896  */
1898  "Autovacuum worker",
1901 
1902  /* Start a transaction so our commands have one to play into. */
1904 
1905  /*
1906  * Compute the multixact age for which freezing is urgent. This is
1907  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
1908  * short of multixact member space.
1909  */
1910  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
1911 
1912  /*
1913  * Find the pg_database entry and select the default freeze ages. We use
1914  * zero in template and nonconnectable databases, else the system-wide
1915  * default.
1916  */
1917  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
1918  if (!HeapTupleIsValid(tuple))
1919  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1920  dbForm = (Form_pg_database) GETSTRUCT(tuple);
1921 
1922  if (dbForm->datistemplate || !dbForm->datallowconn)
1923  {
1928  }
1929  else
1930  {
1935  }
1936 
1937  ReleaseSysCache(tuple);
1938 
1939  /* StartTransactionCommand changed elsewhere */
1941 
1942  classRel = table_open(RelationRelationId, AccessShareLock);
1943 
1944  /* create a copy so we can use it after closing pg_class */
1945  pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
1946 
1947  /* create hash table for toast <-> main relid mapping */
1948  ctl.keysize = sizeof(Oid);
1949  ctl.entrysize = sizeof(av_relation);
1950 
1951  table_toast_map = hash_create("TOAST to main relid map",
1952  100,
1953  &ctl,
1954  HASH_ELEM | HASH_BLOBS);
1955 
1956  /*
1957  * Scan pg_class to determine which tables to vacuum.
1958  *
1959  * We do this in two passes: on the first one we collect the list of plain
1960  * relations and materialized views, and on the second one we collect
1961  * TOAST tables. The reason for doing the second pass is that during it we
1962  * want to use the main relation's pg_class.reloptions entry if the TOAST
1963  * table does not have any, and we cannot obtain it unless we know
1964  * beforehand what's the main table OID.
1965  *
1966  * We need to check TOAST tables separately because in cases with short,
1967  * wide tables there might be proportionally much more activity in the
1968  * TOAST table than in its parent.
1969  */
1970  relScan = table_beginscan_catalog(classRel, 0, NULL);
1971 
1972  /*
1973  * On the first pass, we collect main tables to vacuum, and also the main
1974  * table relid to TOAST relid mapping.
1975  */
1976  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
1977  {
1978  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
1979  PgStat_StatTabEntry *tabentry;
1980  AutoVacOpts *relopts;
1981  Oid relid;
1982  bool dovacuum;
1983  bool doanalyze;
1984  bool wraparound;
1985 
1986  if (classForm->relkind != RELKIND_RELATION &&
1987  classForm->relkind != RELKIND_MATVIEW)
1988  continue;
1989 
1990  relid = classForm->oid;
1991 
1992  /*
1993  * Check if it is a temp table (presumably, of some other backend's).
1994  * We cannot safely process other backends' temp tables.
1995  */
1996  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
1997  {
1998  /*
1999  * We just ignore it if the owning backend is still active and
2000  * using the temporary schema. Also, for safety, ignore it if the
2001  * namespace doesn't exist or isn't a temp namespace after all.
2002  */
2003  if (checkTempNamespaceStatus(classForm->relnamespace) == TEMP_NAMESPACE_IDLE)
2004  {
2005  /*
2006  * The table seems to be orphaned -- although it might be that
2007  * the owning backend has already deleted it and exited; our
2008  * pg_class scan snapshot is not necessarily up-to-date
2009  * anymore, so we could be looking at a committed-dead entry.
2010  * Remember it so we can try to delete it later.
2011  */
2012  orphan_oids = lappend_oid(orphan_oids, relid);
2013  }
2014  continue;
2015  }
2016 
2017  /* Fetch reloptions and the pgstat entry for this table */
2018  relopts = extract_autovac_opts(tuple, pg_class_desc);
2019  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2020  relid);
2021 
2022  /* Check if it needs vacuum or analyze */
2023  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2024  effective_multixact_freeze_max_age,
2025  &dovacuum, &doanalyze, &wraparound);
2026 
2027  /* Relations that need work are added to table_oids */
2028  if (dovacuum || doanalyze)
2029  table_oids = lappend_oid(table_oids, relid);
2030 
2031  /*
2032  * Remember TOAST associations for the second pass. Note: we must do
2033  * this whether or not the table is going to be vacuumed, because we
2034  * don't automatically vacuum toast tables along the parent table.
2035  */
2036  if (OidIsValid(classForm->reltoastrelid))
2037  {
2038  av_relation *hentry;
2039  bool found;
2040 
2041  hentry = hash_search(table_toast_map,
2042  &classForm->reltoastrelid,
2043  HASH_ENTER, &found);
2044 
2045  if (!found)
2046  {
2047  /* hash_search already filled in the key */
2048  hentry->ar_relid = relid;
2049  hentry->ar_hasrelopts = false;
2050  if (relopts != NULL)
2051  {
2052  hentry->ar_hasrelopts = true;
2053  memcpy(&hentry->ar_reloptions, relopts,
2054  sizeof(AutoVacOpts));
2055  }
2056  }
2057  }
2058  }
2059 
2060  table_endscan(relScan);
2061 
2062  /* second pass: check TOAST tables */
2063  ScanKeyInit(&key,
2064  Anum_pg_class_relkind,
2065  BTEqualStrategyNumber, F_CHAREQ,
2066  CharGetDatum(RELKIND_TOASTVALUE));
2067 
2068  relScan = table_beginscan_catalog(classRel, 1, &key);
2069  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2070  {
2071  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2072  PgStat_StatTabEntry *tabentry;
2073  Oid relid;
2074  AutoVacOpts *relopts = NULL;
2075  bool dovacuum;
2076  bool doanalyze;
2077  bool wraparound;
2078 
2079  /*
2080  * We cannot safely process other backends' temp tables, so skip 'em.
2081  */
2082  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2083  continue;
2084 
2085  relid = classForm->oid;
2086 
2087  /*
2088  * fetch reloptions -- if this toast table does not have them, try the
2089  * main rel
2090  */
2091  relopts = extract_autovac_opts(tuple, pg_class_desc);
2092  if (relopts == NULL)
2093  {
2094  av_relation *hentry;
2095  bool found;
2096 
2097  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2098  if (found && hentry->ar_hasrelopts)
2099  relopts = &hentry->ar_reloptions;
2100  }
2101 
2102  /* Fetch the pgstat entry for this table */
2103  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2104  relid);
2105 
2106  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2107  effective_multixact_freeze_max_age,
2108  &dovacuum, &doanalyze, &wraparound);
2109 
2110  /* ignore analyze for toast tables */
2111  if (dovacuum)
2112  table_oids = lappend_oid(table_oids, relid);
2113  }
2114 
2115  table_endscan(relScan);
2116  table_close(classRel, AccessShareLock);
2117 
2118  /*
2119  * Recheck orphan temporary tables, and if they still seem orphaned, drop
2120  * them. We'll eat a transaction per dropped table, which might seem
2121  * excessive, but we should only need to do anything as a result of a
2122  * previous backend crash, so this should not happen often enough to
2123  * justify "optimizing". Using separate transactions ensures that we
2124  * don't bloat the lock table if there are many temp tables to be dropped,
2125  * and it ensures that we don't lose work if a deletion attempt fails.
2126  */
2127  foreach(cell, orphan_oids)
2128  {
2129  Oid relid = lfirst_oid(cell);
2130  Form_pg_class classForm;
2131  ObjectAddress object;
2132 
2133  /*
2134  * Check for user-requested abort.
2135  */
2137 
2138  /*
2139  * Try to lock the table. If we can't get the lock immediately,
2140  * somebody else is using (or dropping) the table, so it's not our
2141  * concern anymore. Having the lock prevents race conditions below.
2142  */
2144  continue;
2145 
2146  /*
2147  * Re-fetch the pg_class tuple and re-check whether it still seems to
2148  * be an orphaned temp table. If it's not there or no longer the same
2149  * relation, ignore it.
2150  */
2151  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2152  if (!HeapTupleIsValid(tuple))
2153  {
2154  /* be sure to drop useless lock so we don't bloat lock table */
2156  continue;
2157  }
2158  classForm = (Form_pg_class) GETSTRUCT(tuple);
2159 
2160  /*
2161  * Make all the same tests made in the loop above. In event of OID
2162  * counter wraparound, the pg_class entry we have now might be
2163  * completely unrelated to the one we saw before.
2164  */
2165  if (!((classForm->relkind == RELKIND_RELATION ||
2166  classForm->relkind == RELKIND_MATVIEW) &&
2167  classForm->relpersistence == RELPERSISTENCE_TEMP))
2168  {
2170  continue;
2171  }
2172 
2173  if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE)
2174  {
2176  continue;
2177  }
2178 
2179  /*
2180  * Try to lock the temp namespace, too. Even though we have lock on
2181  * the table itself, there's a risk of deadlock against an incoming
2182  * backend trying to clean out the temp namespace, in case this table
2183  * has dependencies (such as sequences) that the backend's
2184  * performDeletion call might visit in a different order. If we can
2185  * get AccessShareLock on the namespace, that's sufficient to ensure
2186  * we're not running concurrently with RemoveTempRelations. If we
2187  * can't, back off and let RemoveTempRelations do its thing.
2188  */
2189  if (!ConditionalLockDatabaseObject(NamespaceRelationId,
2190  classForm->relnamespace, 0,
2191  AccessShareLock))
2192  {
2194  continue;
2195  }
2196 
2197  /* OK, let's delete it */
2198  ereport(LOG,
2199  (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2201  get_namespace_name(classForm->relnamespace),
2202  NameStr(classForm->relname))));
2203 
2204  object.classId = RelationRelationId;
2205  object.objectId = relid;
2206  object.objectSubId = 0;
2207  performDeletion(&object, DROP_CASCADE,
2211 
2212  /*
2213  * To commit the deletion, end current transaction and start a new
2214  * one. Note this also releases the locks we took.
2215  */
2218 
2219  /* StartTransactionCommand changed current memory context */
2221  }
2222 
2223  /*
2224  * Optionally, create a buffer access strategy object for VACUUM to use.
2225  * We use the same BufferAccessStrategy object for all tables VACUUMed by
2226  * this worker to prevent autovacuum from blowing out shared buffers.
2227  *
2228  * VacuumBufferUsageLimit being set to 0 results in
2229  * GetAccessStrategyWithSize returning NULL, effectively meaning we can
2230  * use up to all of shared buffers.
2231  *
2232  * If we later enter failsafe mode on any of the tables being vacuumed, we
2233  * will cease use of the BufferAccessStrategy only for that table.
2234  *
2235  * XXX should we consider adding code to adjust the size of this if
2236  * VacuumBufferUsageLimit changes?
2237  */
2239 
2240  /*
2241  * create a memory context to act as fake PortalContext, so that the
2242  * contexts created in the vacuum code are cleaned up for each table.
2243  */
2245  "Autovacuum Portal",
2247 
2248  /*
2249  * Perform operations on collected tables.
2250  */
2251  foreach(cell, table_oids)
2252  {
2253  Oid relid = lfirst_oid(cell);
2254  HeapTuple classTup;
2255  autovac_table *tab;
2256  bool isshared;
2257  bool skipit;
2258  dlist_iter iter;
2259 
2261 
2262  /*
2263  * Check for config changes before processing each collected table.
2264  */
2265  if (ConfigReloadPending)
2266  {
2267  ConfigReloadPending = false;
2269 
2270  /*
2271  * You might be tempted to bail out if we see autovacuum is now
2272  * disabled. Must resist that temptation -- this might be a
2273  * for-wraparound emergency worker, in which case that would be
2274  * entirely inappropriate.
2275  */
2276  }
2277 
2278  /*
2279  * Find out whether the table is shared or not. (It's slightly
2280  * annoying to fetch the syscache entry just for this, but in typical
2281  * cases it adds little cost because table_recheck_autovac would
2282  * refetch the entry anyway. We could buy that back by copying the
2283  * tuple here and passing it to table_recheck_autovac, but that
2284  * increases the odds of that function working with stale data.)
2285  */
2286  classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2287  if (!HeapTupleIsValid(classTup))
2288  continue; /* somebody deleted the rel, forget it */
2289  isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared;
2290  ReleaseSysCache(classTup);
2291 
2292  /*
2293  * Hold schedule lock from here until we've claimed the table. We
2294  * also need the AutovacuumLock to walk the worker array, but that one
2295  * can just be a shared lock.
2296  */
2297  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2298  LWLockAcquire(AutovacuumLock, LW_SHARED);
2299 
2300  /*
2301  * Check whether the table is being vacuumed concurrently by another
2302  * worker.
2303  */
2304  skipit = false;
2306  {
2307  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2308 
2309  /* ignore myself */
2310  if (worker == MyWorkerInfo)
2311  continue;
2312 
2313  /* ignore workers in other databases (unless table is shared) */
2314  if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2315  continue;
2316 
2317  if (worker->wi_tableoid == relid)
2318  {
2319  skipit = true;
2320  found_concurrent_worker = true;
2321  break;
2322  }
2323  }
2324  LWLockRelease(AutovacuumLock);
2325  if (skipit)
2326  {
2327  LWLockRelease(AutovacuumScheduleLock);
2328  continue;
2329  }
2330 
2331  /*
2332  * Store the table's OID in shared memory before releasing the
2333  * schedule lock, so that other workers don't try to vacuum it
2334  * concurrently. (We claim it here so as not to hold
2335  * AutovacuumScheduleLock while rechecking the stats.)
2336  */
2337  MyWorkerInfo->wi_tableoid = relid;
2338  MyWorkerInfo->wi_sharedrel = isshared;
2339  LWLockRelease(AutovacuumScheduleLock);
2340 
2341  /*
2342  * Check whether pgstat data still says we need to vacuum this table.
2343  * It could have changed if something else processed the table while
2344  * we weren't looking. This doesn't entirely close the race condition,
2345  * but it is very small.
2346  */
2348  tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
2349  effective_multixact_freeze_max_age);
2350  if (tab == NULL)
2351  {
2352  /* someone else vacuumed the table, or it went away */
2353  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2355  MyWorkerInfo->wi_sharedrel = false;
2356  LWLockRelease(AutovacuumScheduleLock);
2357  continue;
2358  }
2359 
2360  /*
2361  * Save the cost-related storage parameter values in global variables
2362  * for reference when updating vacuum_cost_delay and vacuum_cost_limit
2363  * during vacuuming this table.
2364  */
2367 
2368  /*
2369  * We only expect this worker to ever set the flag, so don't bother
2370  * checking the return value. We shouldn't have to retry.
2371  */
2372  if (tab->at_dobalance)
2374  else
2376 
2377  LWLockAcquire(AutovacuumLock, LW_SHARED);
2379  LWLockRelease(AutovacuumLock);
2380 
2381  /*
2382  * We wait until this point to update cost delay and cost limit
2383  * values, even though we reloaded the configuration file above, so
2384  * that we can take into account the cost-related storage parameters.
2385  */
2387 
2388 
2389  /* clean up memory before each iteration */
2391 
2392  /*
2393  * Save the relation name for a possible error message, to avoid a
2394  * catalog lookup in case of an error. If any of these return NULL,
2395  * then the relation has been dropped since last we checked; skip it.
2396  * Note: they must live in a long-lived memory context because we call
2397  * vacuum and analyze in different transactions.
2398  */
2399 
2400  tab->at_relname = get_rel_name(tab->at_relid);
2403  if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2404  goto deleted;
2405 
2406  /*
2407  * We will abort vacuuming the current table if something errors out,
2408  * and continue with the next one in schedule; in particular, this
2409  * happens if we are interrupted with SIGINT.
2410  */
2411  PG_TRY();
2412  {
2413  /* Use PortalContext for any per-table allocations */
2415 
2416  /* have at it */
2417  autovacuum_do_vac_analyze(tab, bstrategy);
2418 
2419  /*
2420  * Clear a possible query-cancel signal, to avoid a late reaction
2421  * to an automatically-sent signal because of vacuuming the
2422  * current table (we're done with it, so it would make no sense to
2423  * cancel at this point.)
2424  */
2425  QueryCancelPending = false;
2426  }
2427  PG_CATCH();
2428  {
2429  /*
2430  * Abort the transaction, start a new one, and proceed with the
2431  * next table in our list.
2432  */
2433  HOLD_INTERRUPTS();
2434  if (tab->at_params.options & VACOPT_VACUUM)
2435  errcontext("automatic vacuum of table \"%s.%s.%s\"",
2436  tab->at_datname, tab->at_nspname, tab->at_relname);
2437  else
2438  errcontext("automatic analyze of table \"%s.%s.%s\"",
2439  tab->at_datname, tab->at_nspname, tab->at_relname);
2440  EmitErrorReport();
2441 
2442  /* this resets ProcGlobal->statusFlags[i] too */
2444  FlushErrorState();
2446 
2447  /* restart our transaction for the following operations */
2450  }
2451  PG_END_TRY();
2452 
2453  /* Make sure we're back in AutovacMemCxt */
2455 
2456  did_vacuum = true;
2457 
2458  /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2459 
2460  /* be tidy */
2461 deleted:
2462  if (tab->at_datname != NULL)
2463  pfree(tab->at_datname);
2464  if (tab->at_nspname != NULL)
2465  pfree(tab->at_nspname);
2466  if (tab->at_relname != NULL)
2467  pfree(tab->at_relname);
2468  pfree(tab);
2469 
2470  /*
2471  * Remove my info from shared memory. We set wi_dobalance on the
2472  * assumption that we are more likely than not to vacuum a table with
2473  * no cost-related storage parameters next, so we want to claim our
2474  * share of I/O as soon as possible to avoid thrashing the global
2475  * balance.
2476  */
2477  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2479  MyWorkerInfo->wi_sharedrel = false;
2480  LWLockRelease(AutovacuumScheduleLock);
2482  }
2483 
2484  /*
2485  * Perform additional work items, as requested by backends.
2486  */
2487  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2488  for (i = 0; i < NUM_WORKITEMS; i++)
2489  {
2491 
2492  if (!workitem->avw_used)
2493  continue;
2494  if (workitem->avw_active)
2495  continue;
2496  if (workitem->avw_database != MyDatabaseId)
2497  continue;
2498 
2499  /* claim this one, and release lock while performing it */
2500  workitem->avw_active = true;
2501  LWLockRelease(AutovacuumLock);
2502 
2503  perform_work_item(workitem);
2504 
2505  /*
2506  * Check for config changes before acquiring lock for further jobs.
2507  */
2509  if (ConfigReloadPending)
2510  {
2511  ConfigReloadPending = false;
2514  }
2515 
2516  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2517 
2518  /* and mark it done */
2519  workitem->avw_active = false;
2520  workitem->avw_used = false;
2521  }
2522  LWLockRelease(AutovacuumLock);
2523 
2524  /*
2525  * We leak table_toast_map here (among other things), but since we're
2526  * going away soon, it's not a problem.
2527  */
2528 
2529  /*
2530  * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2531  * only need to do this once, not after each table.
2532  *
2533  * Even if we didn't vacuum anything, it may still be important to do
2534  * this, because one indirect effect of vac_update_datfrozenxid() is to
2535  * update TransamVariables->xidVacLimit. That might need to be done even
2536  * if we haven't vacuumed anything, because relations with older
2537  * relfrozenxid values or other databases with older datfrozenxid values
2538  * might have been dropped, allowing xidVacLimit to advance.
2539  *
2540  * However, it's also important not to do this blindly in all cases,
2541  * because when autovacuum=off this will restart the autovacuum launcher.
2542  * If we're not careful, an infinite loop can result, where workers find
2543  * no work to do and restart the launcher, which starts another worker in
2544  * the same database that finds no work to do. To prevent that, we skip
2545  * this if (1) we found no work to do and (2) we skipped at least one
2546  * table due to concurrent autovacuum activity. In that case, the other
2547  * worker has already done it, or will do so when it finishes.
2548  */
2549  if (did_vacuum || !found_concurrent_worker)
2551 
2552  /* Finally close out the last transaction. */
2554 }
static void pg_atomic_clear_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:202
static bool pg_atomic_test_set_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:178
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:2905
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:2704
void VacuumUpdateCosts(void)
Definition: autovacuum.c:1633
static int default_multixact_freeze_table_age
Definition: autovacuum.c:161
struct av_relation av_relation
static int default_multixact_freeze_min_age
Definition: autovacuum.c:160
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
Definition: autovacuum.c:2674
static double av_storage_param_cost_delay
Definition: autovacuum.c:147
static void perform_work_item(AutoVacuumWorkItem *workitem)
Definition: autovacuum.c:2560
static int default_freeze_min_age
Definition: autovacuum.c:158
static int default_freeze_table_age
Definition: autovacuum.c:159
static void autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
Definition: autovacuum.c:3078
@ BAS_VACUUM
Definition: bufmgr.h:39
#define NameStr(name)
Definition: c.h:746
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3153
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:273
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:89
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:87
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:85
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
#define LOG
Definition: elog.h:31
#define errcontext
Definition: elog.h:196
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_CATCH(...)
Definition: elog.h:380
BufferAccessStrategy GetAccessStrategyWithSize(BufferAccessStrategyType btype, int ring_size_kb)
Definition: freelist.c:584
int VacuumBufferUsageLimit
Definition: globals.c:146
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1248
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:227
bool ConditionalLockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1028
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3366
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1952
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1928
void pfree(void *pointer)
Definition: mcxt.c:1520
MemoryContext PortalContext
Definition: mcxt.c:158
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2929
TempNamespaceStatus checkTempNamespaceStatus(Oid namespaceId)
Definition: namespace.c:3714
@ TEMP_NAMESPACE_IDLE
Definition: namespace.h:48
@ DROP_CASCADE
Definition: parsenodes.h:2337
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
FormData_pg_database * Form_pg_database
Definition: pg_database.h:96
#define lfirst_oid(lc)
Definition: pg_list.h:174
PgStat_StatTabEntry * pgstat_fetch_stat_tabentry_ext(bool shared, Oid reloid)
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static Datum CharGetDatum(char X)
Definition: postgres.h:122
tree ctl
Definition: radixtree.h:1851
#define RelationGetDescr(relation)
Definition: rel.h:531
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:28
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Definition: dynahash.c:220
bool at_dobalance
Definition: autovacuum.c:202
double at_storage_param_vac_cost_delay
Definition: autovacuum.c:200
int at_storage_param_vac_cost_limit
Definition: autovacuum.c:201
char * at_datname
Definition: autovacuum.c:206
bool ar_hasrelopts
Definition: autovacuum.c:190
AutoVacOpts ar_reloptions
Definition: autovacuum.c:191
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1029
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:133
int vacuum_freeze_min_age
Definition: vacuum.c:67
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:70
int vacuum_freeze_table_age
Definition: vacuum.c:68
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:69
void vac_update_datfrozenxid(void)
Definition: vacuum.c:1565
void StartTransactionCommand(void)
Definition: xact.c:2995
void CommitTransactionCommand(void)
Definition: xact.c:3093
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4811

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_storage_param_vac_cost_delay, autovac_table::at_storage_param_vac_cost_limit, autovac_recalculate_workers_for_balance(), AutovacMemCxt, autovacuum_do_vac_analyze(), AutoVacuumShmem, AutoVacuumShmemStruct::av_runningWorkers, av_storage_param_cost_delay, av_storage_param_cost_limit, AutoVacuumShmemStruct::av_workItems, AutoVacuumWorkItem::avw_active, AutoVacuumWorkItem::avw_database, AutoVacuumWorkItem::avw_used, BAS_VACUUM, BTEqualStrategyNumber, CharGetDatum(), CHECK_FOR_INTERRUPTS, checkTempNamespaceStatus(), CommitTransactionCommand(), ConditionalLockDatabaseObject(), ConditionalLockRelationOid(), ConfigReloadPending, CreateTupleDescCopy(), ctl, dlist_iter::cur, 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(), ereport, errcontext, errmsg(), ERROR, extract_autovac_opts(), FlushErrorState(), ForwardScanDirection, get_database_name(), get_namespace_name(), get_rel_name(), get_rel_namespace(), GetAccessStrategyWithSize(), GETSTRUCT, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, HASH_FIND, hash_search(), heap_getnext(), HeapTupleIsValid, HOLD_INTERRUPTS, i, InvalidOid, sort-test::key, lappend_oid(), lfirst_oid, LOG, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextReset(), 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_atomic_clear_flag(), pg_atomic_test_set_flag(), PG_CATCH, PG_END_TRY, PG_TRY, PGC_SIGHUP, pgstat_fetch_stat_tabentry_ext(), PortalContext, ProcessConfigFile(), QueryCancelPending, relation_needs_vacanalyze(), RelationGetDescr, ReleaseSysCache(), 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, VacuumBufferUsageLimit, VacuumUpdateCosts(), 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 1073 of file autovacuum.c.

1074 {
1075  List *dblist;
1076  ListCell *cell;
1077  TransactionId xidForceLimit;
1078  MultiXactId multiForceLimit;
1079  bool for_xid_wrap;
1080  bool for_multi_wrap;
1081  avw_dbase *avdb;
1082  TimestampTz current_time;
1083  bool skipit = false;
1084  Oid retval = InvalidOid;
1085  MemoryContext tmpcxt,
1086  oldcxt;
1087 
1088  /* return quickly when there are no free workers */
1089  LWLockAcquire(AutovacuumLock, LW_SHARED);
1091  {
1092  LWLockRelease(AutovacuumLock);
1093  return InvalidOid;
1094  }
1095  LWLockRelease(AutovacuumLock);
1096 
1097  /*
1098  * Create and switch to a temporary context to avoid leaking the memory
1099  * allocated for the database list.
1100  */
1102  "Autovacuum start worker (tmp)",
1104  oldcxt = MemoryContextSwitchTo(tmpcxt);
1105 
1106  /* Get a list of databases */
1108 
1109  /*
1110  * Determine the oldest datfrozenxid/relfrozenxid that we will allow to
1111  * pass without forcing a vacuum. (This limit can be tightened for
1112  * particular tables, but not loosened.)
1113  */
1115  xidForceLimit = recentXid - autovacuum_freeze_max_age;
1116  /* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
1117  /* this can cause the limit to go backwards by 3, but that's OK */
1118  if (xidForceLimit < FirstNormalTransactionId)
1119  xidForceLimit -= FirstNormalTransactionId;
1120 
1121  /* Also determine the oldest datminmxid we will consider. */
1123  multiForceLimit = recentMulti - MultiXactMemberFreezeThreshold();
1124  if (multiForceLimit < FirstMultiXactId)
1125  multiForceLimit -= FirstMultiXactId;
1126 
1127  /*
1128  * Choose a database to connect to. We pick the database that was least
1129  * recently auto-vacuumed, or one that needs vacuuming to prevent Xid
1130  * wraparound-related data loss. If any db at risk of Xid wraparound is
1131  * found, we pick the one with oldest datfrozenxid, independently of
1132  * autovacuum times; similarly we pick the one with the oldest datminmxid
1133  * if any is in MultiXactId wraparound. Note that those in Xid wraparound
1134  * danger are given more priority than those in multi wraparound danger.
1135  *
1136  * Note that a database with no stats entry is not considered, except for
1137  * Xid wraparound purposes. The theory is that if no one has ever
1138  * connected to it since the stats were last initialized, it doesn't need
1139  * vacuuming.
1140  *
1141  * XXX This could be improved if we had more info about whether it needs
1142  * vacuuming before connecting to it. Perhaps look through the pgstats
1143  * data for the database's tables? One idea is to keep track of the
1144  * number of new and dead tuples per database in pgstats. However it
1145  * isn't clear how to construct a metric that measures that and not cause
1146  * starvation for less busy databases.
1147  */
1148  avdb = NULL;
1149  for_xid_wrap = false;
1150  for_multi_wrap = false;
1151  current_time = GetCurrentTimestamp();
1152  foreach(cell, dblist)
1153  {
1154  avw_dbase *tmp = lfirst(cell);
1155  dlist_iter iter;
1156 
1157  /* Check to see if this one is at risk of wraparound */
1158  if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit))
1159  {
1160  if (avdb == NULL ||
1162  avdb->adw_frozenxid))
1163  avdb = tmp;
1164  for_xid_wrap = true;
1165  continue;
1166  }
1167  else if (for_xid_wrap)
1168  continue; /* ignore not-at-risk DBs */
1169  else if (MultiXactIdPrecedes(tmp->adw_minmulti, multiForceLimit))
1170  {
1171  if (avdb == NULL ||
1173  avdb = tmp;
1174  for_multi_wrap = true;
1175  continue;
1176  }
1177  else if (for_multi_wrap)
1178  continue; /* ignore not-at-risk DBs */
1179 
1180  /* Find pgstat entry if any */
1182 
1183  /*
1184  * Skip a database with no pgstat entry; it means it hasn't seen any
1185  * activity.
1186  */
1187  if (!tmp->adw_entry)
1188  continue;
1189 
1190  /*
1191  * Also, skip a database that appears on the database list as having
1192  * been processed recently (less than autovacuum_naptime seconds ago).
1193  * We do this so that we don't select a database which we just
1194  * selected, but that pgstat hasn't gotten around to updating the last
1195  * autovacuum time yet.
1196  */
1197  skipit = false;
1198 
1200  {
1201  avl_dbase *dbp = dlist_container(avl_dbase, adl_node, iter.cur);
1202 
1203  if (dbp->adl_datid == tmp->adw_datid)
1204  {
1205  /*
1206  * Skip this database if its next_worker value falls between
1207  * the current time and the current time plus naptime.
1208  */
1210  current_time, 0) &&
1211  !TimestampDifferenceExceeds(current_time,
1212  dbp->adl_next_worker,
1213  autovacuum_naptime * 1000))
1214  skipit = true;
1215 
1216  break;
1217  }
1218  }
1219  if (skipit)
1220  continue;
1221 
1222  /*
1223  * Remember the db with oldest autovac time. (If we are here, both
1224  * tmp->entry and db->entry must be non-null.)
1225  */
1226  if (avdb == NULL ||
1228  avdb = tmp;
1229  }
1230 
1231  /* Found a database -- process it */
1232  if (avdb != NULL)
1233  {
1234  WorkerInfo worker;
1235  dlist_node *wptr;
1236 
1237  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1238 
1239  /*
1240  * Get a worker entry from the freelist. We checked above, so there
1241  * really should be a free slot.
1242  */
1244 
1245  worker = dlist_container(WorkerInfoData, wi_links, wptr);
1246  worker->wi_dboid = avdb->adw_datid;
1247  worker->wi_proc = NULL;
1248  worker->wi_launchtime = GetCurrentTimestamp();
1249 
1251 
1252  LWLockRelease(AutovacuumLock);
1253 
1255 
1256  retval = avdb->adw_datid;
1257  }
1258  else if (skipit)
1259  {
1260  /*
1261  * If we skipped all databases on the list, rebuild it, because it
1262  * probably contains a dropped database.
1263  */
1265  }
1266 
1267  MemoryContextSwitchTo(oldcxt);
1268  MemoryContextDelete(tmpcxt);
1269 
1270  return retval;
1271 }
int autovacuum_freeze_max_age
Definition: autovacuum.c:126
static List * get_database_list(void)
Definition: autovacuum.c:1788
TransactionId MultiXactId
Definition: c.h:662
uint32 TransactionId
Definition: c.h:652
#define dlist_reverse_foreach(iter, lhead)
Definition: ilist.h:654
static dlist_node * dlist_pop_head_node(dlist_head *head)
Definition: ilist.h:450
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3260
#define FirstMultiXactId
Definition: multixact.h:25
#define lfirst(lc)
Definition: pg_list.h:172
_stringlist * dblist
Definition: pg_regress.c:98
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dboid)
TimestampTz last_autovac_time
Definition: pgstat.h:334
Oid adl_datid
Definition: autovacuum.c:169
PgStat_StatDBEntry * adw_entry
Definition: autovacuum.c:182
Oid adw_datid
Definition: autovacuum.c:178
TransactionId adw_frozenxid
Definition: autovacuum.c:180
MultiXactId adw_minmulti
Definition: autovacuum.c:181
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define FirstNormalTransactionId
Definition: transam.h:34

References avl_dbase::adl_datid, avl_dbase::adl_next_worker, avw_dbase::adw_datid, avw_dbase::adw_entry, avw_dbase::adw_frozenxid, avw_dbase::adw_minmulti, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, autovacuum_freeze_max_age, autovacuum_naptime, AutoVacuumShmem, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_startingWorker, dlist_iter::cur, 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 launch_worker().

◆ extract_autovac_opts()

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

Definition at line 2674 of file autovacuum.c.

2675 {
2676  bytea *relopts;
2677  AutoVacOpts *av;
2678 
2679  Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2680  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2681  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2682 
2683  relopts = extractRelOptions(tup, pg_class_desc, NULL);
2684  if (relopts == NULL)
2685  return NULL;
2686 
2687  av = palloc(sizeof(AutoVacOpts));
2688  memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2689  pfree(relopts);
2690 
2691  return av;
2692 }
void * palloc(Size size)
Definition: mcxt.c:1316
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
Definition: reloptions.c:1379
struct @10::@11 av[32]
Definition: c.h:687

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

1586 {
1587  if (MyWorkerInfo != NULL)
1588  {
1589  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1590 
1591  /*
1592  * Wake the launcher up so that he can launch a new worker immediately
1593  * if required. We only save the launcher's PID in local memory here;
1594  * the actual signal will be sent when the PGPROC is recycled. Note
1595  * that we always do this, so that the launcher can rebalance the cost
1596  * limit setting of the remaining workers.
1597  *
1598  * We somewhat ignore the risk that the launcher changes its PID
1599  * between us reading it and the actual kill; we expect ProcKill to be
1600  * called shortly after us, and we assume that PIDs are not reused too
1601  * quickly after a process exits.
1602  */
1604 
1608  MyWorkerInfo->wi_sharedrel = false;
1609  MyWorkerInfo->wi_proc = NULL;
1614  /* not mine anymore */
1615  MyWorkerInfo = NULL;
1616 
1617  /*
1618  * now that we're inactive, cause a rebalancing of the surviving
1619  * workers
1620  */
1622  LWLockRelease(AutovacuumLock);
1623  }
1624 }
int AutovacuumLauncherPid
Definition: autovacuum.c:312
static void dlist_delete(dlist_node *node)
Definition: ilist.h:405

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

1789 {
1790  List *dblist = NIL;
1791  Relation rel;
1792  TableScanDesc scan;
1793  HeapTuple tup;
1794  MemoryContext resultcxt;
1795 
1796  /* This is the context that we will allocate our output data in */
1797  resultcxt = CurrentMemoryContext;
1798 
1799  /*
1800  * Start a transaction so we can access pg_database, and get a snapshot.
1801  * We don't have a use for the snapshot itself, but we're interested in
1802  * the secondary effect that it sets RecentGlobalXmin. (This is critical
1803  * for anything that reads heap pages, because HOT may decide to prune
1804  * them even if the process doesn't attempt to modify any tuples.)
1805  *
1806  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
1807  * not pushed/active does not reliably prevent HOT pruning (->xmin could
1808  * e.g. be cleared when cache invalidations are processed).
1809  */
1811  (void) GetTransactionSnapshot();
1812 
1813  rel = table_open(DatabaseRelationId, AccessShareLock);
1814  scan = table_beginscan_catalog(rel, 0, NULL);
1815 
1816  while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1817  {
1818  Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1819  avw_dbase *avdb;
1820  MemoryContext oldcxt;
1821 
1822  /*
1823  * If database has partially been dropped, we can't, nor need to,
1824  * vacuum it.
1825  */
1826  if (database_is_invalid_form(pgdatabase))
1827  {
1828  elog(DEBUG2,
1829  "autovacuum: skipping invalid database \"%s\"",
1830  NameStr(pgdatabase->datname));
1831  continue;
1832  }
1833 
1834  /*
1835  * Allocate our results in the caller's context, not the
1836  * transaction's. We do this inside the loop, and restore the original
1837  * context at the end, so that leaky things like heap_getnext() are
1838  * not called in a potentially long-lived context.
1839  */
1840  oldcxt = MemoryContextSwitchTo(resultcxt);
1841 
1842  avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1843 
1844  avdb->adw_datid = pgdatabase->oid;
1845  avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1846  avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1847  avdb->adw_minmulti = pgdatabase->datminmxid;
1848  /* this gets set later: */
1849  avdb->adw_entry = NULL;
1850 
1851  dblist = lappend(dblist, avdb);
1852  MemoryContextSwitchTo(oldcxt);
1853  }
1854 
1855  table_endscan(scan);
1857 
1859 
1860  /* Be sure to restore caller's memory context */
1861  MemoryContextSwitchTo(resultcxt);
1862 
1863  return dblist;
1864 }
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3177
#define DEBUG2
Definition: elog.h:29
List * lappend(List *list, void *datum)
Definition: list.c:339
char * pstrdup(const char *in)
Definition: mcxt.c:1695
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
char * adw_name
Definition: autovacuum.c:179

References AccessShareLock, avw_dbase::adw_datid, avw_dbase::adw_entry, avw_dbase::adw_frozenxid, avw_dbase::adw_minmulti, avw_dbase::adw_name, CommitTransactionCommand(), CurrentMemoryContext, database_is_invalid_form(), dblist, DEBUG2, elog, 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 740 of file autovacuum.c.

741 {
742  /* the normal shutdown case */
745 
747  {
748  ConfigReloadPending = false;
750 
751  /* shutdown requested in config file? */
752  if (!AutoVacuumingActive())
754 
755  /* rebuild the list in case the naptime changed */
757  }
758 
759  /* Process barrier events */
762 
763  /* Perform logging of memory contexts of this process */
766 
767  /* Process sinval catchup interrupts that happened while sleeping */
769 }
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:39
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:38
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1288
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:464
void ProcessCatchupInterrupt(void)
Definition: sinval.c:174

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

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1285 of file autovacuum.c.

1286 {
1287  Oid dbid;
1288  dlist_iter iter;
1289 
1290  dbid = do_start_worker();
1291  if (OidIsValid(dbid))
1292  {
1293  bool found = false;
1294 
1295  /*
1296  * Walk the database list and update the corresponding entry. If the
1297  * database is not on the list, we'll recreate the list.
1298  */
1299  dlist_foreach(iter, &DatabaseList)
1300  {
1301  avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1302 
1303  if (avdb->adl_datid == dbid)
1304  {
1305  found = true;
1306 
1307  /*
1308  * add autovacuum_naptime seconds to the current time, and use
1309  * that as the new "next_worker" field for this database.
1310  */
1311  avdb->adl_next_worker =
1313 
1315  break;
1316  }
1317  }
1318 
1319  /*
1320  * If the database was not present in the database list, we rebuild
1321  * the list. It's possible that the database does not get into the
1322  * list anyway, for example if it's a database that doesn't have a
1323  * pgstat entry, but this is not a problem because we don't want to
1324  * schedule workers regularly into those in any case.
1325  */
1326  if (!found)
1327  rebuild_database_list(dbid);
1328  }
1329 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1618
static void dlist_move_head(dlist_head *head, dlist_node *node)
Definition: ilist.h:467
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85

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

◆ launcher_determine_sleep()

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

Definition at line 792 of file autovacuum.c.

793 {
794  /*
795  * We sleep until the next scheduled vacuum. We trust that when the
796  * database list was built, care was taken so that no entries have times
797  * in the past; if the first entry has too close a next_worker value, or a
798  * time in the past, we will sleep a small nominal time.
799  */
800  if (!canlaunch)
801  {
802  nap->tv_sec = autovacuum_naptime;
803  nap->tv_usec = 0;
804  }
805  else if (!dlist_is_empty(&DatabaseList))
806  {
807  TimestampTz current_time = GetCurrentTimestamp();
808  TimestampTz next_wakeup;
809  avl_dbase *avdb;
810  long secs;
811  int usecs;
812 
813  avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
814 
815  next_wakeup = avdb->adl_next_worker;
816  TimestampDifference(current_time, next_wakeup, &secs, &usecs);
817 
818  nap->tv_sec = secs;
819  nap->tv_usec = usecs;
820  }
821  else
822  {
823  /* list is empty, sleep for whole autovacuum_naptime seconds */
824  nap->tv_sec = autovacuum_naptime;
825  nap->tv_usec = 0;
826  }
827 
828  /*
829  * If the result is exactly zero, it means a database had an entry with
830  * time in the past. Rebuild the list so that the databases are evenly
831  * distributed again, and recalculate the time to sleep. This can happen
832  * if there are more tables needing vacuum than workers, and they all take
833  * longer to vacuum than autovacuum_naptime.
834  *
835  * We only recurse once. rebuild_database_list should always return times
836  * in the future, but it seems best not to trust too much on that.
837  */
838  if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
839  {
841  launcher_determine_sleep(canlaunch, true, nap);
842  return;
843  }
844 
845  /* The smallest time we'll allow the launcher to sleep. */
846  if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
847  {
848  nap->tv_sec = 0;
849  nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000;
850  }
851 
852  /*
853  * If the sleep time is too large, clamp it to an arbitrary maximum (plus
854  * any fractional seconds, for simplicity). This avoids an essentially
855  * infinite sleep in strange cases like the system clock going backwards a
856  * few years.
857  */
858  if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME)
859  nap->tv_sec = MAX_AUTOVAC_SLEEPTIME;
860 }
#define MIN_AUTOVAC_SLEEPTIME
Definition: autovacuum.c:135
#define MAX_AUTOVAC_SLEEPTIME
Definition: autovacuum.c:136
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1730

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

◆ perform_work_item()

static void perform_work_item ( AutoVacuumWorkItem workitem)
static

Definition at line 2560 of file autovacuum.c.

2561 {
2562  char *cur_datname = NULL;
2563  char *cur_nspname = NULL;
2564  char *cur_relname = NULL;
2565 
2566  /*
2567  * Note we do not store table info in MyWorkerInfo, since this is not
2568  * vacuuming proper.
2569  */
2570 
2571  /*
2572  * Save the relation name for a possible error message, to avoid a catalog
2573  * lookup in case of an error. If any of these return NULL, then the
2574  * relation has been dropped since last we checked; skip it.
2575  */
2577 
2578  cur_relname = get_rel_name(workitem->avw_relation);
2579  cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2580  cur_datname = get_database_name(MyDatabaseId);
2581  if (!cur_relname || !cur_nspname || !cur_datname)
2582  goto deleted2;
2583 
2584  autovac_report_workitem(workitem, cur_nspname, cur_relname);
2585 
2586  /* clean up memory before each work item */
2588 
2589  /*
2590  * We will abort the current work item if something errors out, and
2591  * continue with the next one; in particular, this happens if we are
2592  * interrupted with SIGINT. Note that this means that the work item list
2593  * can be lossy.
2594  */
2595  PG_TRY();
2596  {
2597  /* Use PortalContext for any per-work-item allocations */
2599 
2600  /*
2601  * Have at it. Functions called here are responsible for any required
2602  * user switch and sandbox.
2603  */
2604  switch (workitem->avw_type)
2605  {
2608  ObjectIdGetDatum(workitem->avw_relation),
2609  Int64GetDatum((int64) workitem->avw_blockNumber));
2610  break;
2611  default:
2612  elog(WARNING, "unrecognized work item found: type %d",
2613  workitem->avw_type);
2614  break;
2615  }
2616 
2617  /*
2618  * Clear a possible query-cancel signal, to avoid a late reaction to
2619  * an automatically-sent signal because of vacuuming the current table
2620  * (we're done with it, so it would make no sense to cancel at this
2621  * point.)
2622  */
2623  QueryCancelPending = false;
2624  }
2625  PG_CATCH();
2626  {
2627  /*
2628  * Abort the transaction, start a new one, and proceed with the next
2629  * table in our list.
2630  */
2631  HOLD_INTERRUPTS();
2632  errcontext("processing work entry for relation \"%s.%s.%s\"",
2633  cur_datname, cur_nspname, cur_relname);
2634  EmitErrorReport();
2635 
2636  /* this resets ProcGlobal->statusFlags[i] too */
2638  FlushErrorState();
2640 
2641  /* restart our transaction for the following operations */
2644  }
2645  PG_END_TRY();
2646 
2647  /* Make sure we're back in AutovacMemCxt */
2649 
2650  /* We intentionally do not set did_vacuum here */
2651 
2652  /* be tidy */
2653 deleted2:
2654  if (cur_datname)
2655  pfree(cur_datname);
2656  if (cur_nspname)
2657  pfree(cur_nspname);
2658  if (cur_relname)
2659  pfree(cur_relname);
2660 }
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
Definition: autovacuum.c:3149
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:1369
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1807
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:644

References AbortOutOfAnyTransaction(), Assert, autovac_report_workitem(), AutovacMemCxt, AutoVacuumWorkItem::avw_blockNumber, AVW_BRINSummarizeRange, AutoVacuumWorkItem::avw_relation, AutoVacuumWorkItem::avw_type, brin_summarize_range(), CurrentMemoryContext, DirectFunctionCall2, elog, EmitErrorReport(), errcontext, FlushErrorState(), get_database_name(), get_namespace_name(), get_rel_name(), get_rel_namespace(), HOLD_INTERRUPTS, Int64GetDatum(), MemoryContextReset(), 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 876 of file autovacuum.c.

877 {
878  List *dblist;
879  ListCell *cell;
880  MemoryContext newcxt;
881  MemoryContext oldcxt;
882  MemoryContext tmpcxt;
883  HASHCTL hctl;
884  int score;
885  int nelems;
886  HTAB *dbhash;
887  dlist_iter iter;
888 
890  "Autovacuum database list",
892  tmpcxt = AllocSetContextCreate(newcxt,
893  "Autovacuum database list (tmp)",
895  oldcxt = MemoryContextSwitchTo(tmpcxt);
896 
897  /*
898  * Implementing this is not as simple as it sounds, because we need to put
899  * the new database at the end of the list; next the databases that were
900  * already on the list, and finally (at the tail of the list) all the
901  * other databases that are not on the existing list.
902  *
903  * To do this, we build an empty hash table of scored databases. We will
904  * start with the lowest score (zero) for the new database, then
905  * increasing scores for the databases in the existing list, in order, and
906  * lastly increasing scores for all databases gotten via
907  * get_database_list() that are not already on the hash.
908  *
909  * Then we will put all the hash elements into an array, sort the array by
910  * score, and finally put the array elements into the new doubly linked
911  * list.
912  */
913  hctl.keysize = sizeof(Oid);
914  hctl.entrysize = sizeof(avl_dbase);
915  hctl.hcxt = tmpcxt;
916  dbhash = hash_create("autovacuum db hash", 20, &hctl, /* magic number here
917  * FIXME */
919 
920  /* start by inserting the new database */
921  score = 0;
922  if (OidIsValid(newdb))
923  {
924  avl_dbase *db;
925  PgStat_StatDBEntry *entry;
926 
927  /* only consider this database if it has a pgstat entry */
928  entry = pgstat_fetch_stat_dbentry(newdb);
929  if (entry != NULL)
930  {
931  /* we assume it isn't found because the hash was just created */
932  db = hash_search(dbhash, &newdb, HASH_ENTER, NULL);
933 
934  /* hash_search already filled in the key */
935  db->adl_score = score++;
936  /* next_worker is filled in later */
937  }
938  }
939 
940  /* Now insert the databases from the existing list */
942  {
943  avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
944  avl_dbase *db;
945  bool found;
946  PgStat_StatDBEntry *entry;
947 
948  /*
949  * skip databases with no stat entries -- in particular, this gets rid
950  * of dropped databases
951  */
952  entry = pgstat_fetch_stat_dbentry(avdb->adl_datid);
953  if (entry == NULL)
954  continue;
955 
956  db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found);
957 
958  if (!found)
959  {
960  /* hash_search already filled in the key */
961  db->adl_score = score++;
962  /* next_worker is filled in later */
963  }
964  }
965 
966  /* finally, insert all qualifying databases not previously inserted */
968  foreach(cell, dblist)
969  {
970  avw_dbase *avdb = lfirst(cell);
971  avl_dbase *db;
972  bool found;
973  PgStat_StatDBEntry *entry;
974 
975  /* only consider databases with a pgstat entry */
976  entry = pgstat_fetch_stat_dbentry(avdb->adw_datid);
977  if (entry == NULL)
978  continue;
979 
980  db = hash_search(dbhash, &(avdb->adw_datid), HASH_ENTER, &found);
981  /* only update the score if the database was not already on the hash */
982  if (!found)
983  {
984  /* hash_search already filled in the key */
985  db->adl_score = score++;
986  /* next_worker is filled in later */
987  }
988  }
989  nelems = score;
990 
991  /* from here on, the allocated memory belongs to the new list */
992  MemoryContextSwitchTo(newcxt);
994 
995  if (nelems > 0)
996  {
997  TimestampTz current_time;
998  int millis_increment;
999  avl_dbase *dbary;
1000  avl_dbase *db;
1001  HASH_SEQ_STATUS seq;
1002  int i;
1003 
1004  /* put all the hash elements into an array */
1005  dbary = palloc(nelems * sizeof(avl_dbase));
1006 
1007  i = 0;
1008  hash_seq_init(&seq, dbhash);
1009  while ((db = hash_seq_search(&seq)) != NULL)
1010  memcpy(&(dbary[i++]), db, sizeof(avl_dbase));
1011 
1012  /* sort the array */
1013  qsort(dbary, nelems, sizeof(avl_dbase), db_comparator);
1014 
1015  /*
1016  * Determine the time interval between databases in the schedule. If
1017  * we see that the configured naptime would take us to sleep times
1018  * lower than our min sleep time (which launcher_determine_sleep is
1019  * coded not to allow), silently use a larger naptime (but don't touch
1020  * the GUC variable).
1021  */
1022  millis_increment = 1000.0 * autovacuum_naptime / nelems;
1023  if (millis_increment <= MIN_AUTOVAC_SLEEPTIME)
1024  millis_increment = MIN_AUTOVAC_SLEEPTIME * 1.1;
1025 
1026  current_time = GetCurrentTimestamp();
1027 
1028  /*
1029  * move the elements from the array into the dlist, setting the
1030  * next_worker while walking the array
1031  */
1032  for (i = 0; i < nelems; i++)
1033  {
1034  db = &(dbary[i]);
1035 
1036  current_time = TimestampTzPlusMilliseconds(current_time,
1037  millis_increment);
1038  db->adl_next_worker = current_time;
1039 
1040  /* later elements should go closer to the head of the list */
1042  }
1043  }
1044 
1045  /* all done, clean up memory */
1046  if (DatabaseListCxt != NULL)
1048  MemoryContextDelete(tmpcxt);
1049  DatabaseListCxt = newcxt;
1050  MemoryContextSwitchTo(oldcxt);
1051 }
static int db_comparator(const void *a, const void *b)
Definition: autovacuum.c:1055
struct avl_dbase avl_dbase
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1395
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1385
#define HASH_CONTEXT
Definition: hsearch.h:102
#define qsort(a, b, c, d)
Definition: port.h:449
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
dlist_node adl_node
Definition: autovacuum.c:172
int adl_score
Definition: autovacuum.c:171

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

2851 {
2852  PgStat_StatTabEntry *tabentry;
2853 
2854  /* fetch the pgstat table entry */
2855  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2856  relid);
2857 
2858  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2859  effective_multixact_freeze_max_age,
2860  dovacuum, doanalyze, wraparound);
2861 
2862  /* ignore ANALYZE for toast tables */
2863  if (classForm->relkind == RELKIND_TOASTVALUE)
2864  *doanalyze = false;
2865 }

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

2914 {
2915  bool force_vacuum;
2916  bool av_enabled;
2917  float4 reltuples; /* pg_class.reltuples */
2918 
2919  /* constants from reloptions or GUC variables */
2920  int vac_base_thresh,
2921  vac_ins_base_thresh,
2922  anl_base_thresh;
2923  float4 vac_scale_factor,
2924  vac_ins_scale_factor,
2925  anl_scale_factor;
2926 
2927  /* thresholds calculated from above constants */
2928  float4 vacthresh,
2929  vacinsthresh,
2930  anlthresh;
2931 
2932  /* number of vacuum (resp. analyze) tuples at this time */
2933  float4 vactuples,
2934  instuples,
2935  anltuples;
2936 
2937  /* freeze parameters */
2938  int freeze_max_age;
2939  int multixact_freeze_max_age;
2940  TransactionId xidForceLimit;
2941  MultiXactId multiForceLimit;
2942 
2943  Assert(classForm != NULL);
2944  Assert(OidIsValid(relid));
2945 
2946  /*
2947  * Determine vacuum/analyze equation parameters. We have two possible
2948  * sources: the passed reloptions (which could be a main table or a toast
2949  * table), or the autovacuum GUC variables.
2950  */
2951 
2952  /* -1 in autovac setting means use plain vacuum_scale_factor */
2953  vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
2954  ? relopts->vacuum_scale_factor
2956 
2957  vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
2958  ? relopts->vacuum_threshold
2960 
2961  vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
2962  ? relopts->vacuum_ins_scale_factor
2964 
2965  /* -1 is used to disable insert vacuums */
2966  vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
2967  ? relopts->vacuum_ins_threshold
2969 
2970  anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
2971  ? relopts->analyze_scale_factor
2973 
2974  anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
2975  ? relopts->analyze_threshold
2977 
2978  freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
2981 
2982  multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
2983  ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
2984  : effective_multixact_freeze_max_age;
2985 
2986  av_enabled = (relopts ? relopts->enabled : true);
2987 
2988  /* Force vacuum if table is at risk of wraparound */
2989  xidForceLimit = recentXid - freeze_max_age;
2990  if (xidForceLimit < FirstNormalTransactionId)
2991  xidForceLimit -= FirstNormalTransactionId;
2992  force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
2993  TransactionIdPrecedes(classForm->relfrozenxid,
2994  xidForceLimit));
2995  if (!force_vacuum)
2996  {
2997  multiForceLimit = recentMulti - multixact_freeze_max_age;
2998  if (multiForceLimit < FirstMultiXactId)
2999  multiForceLimit -= FirstMultiXactId;
3000  force_vacuum = MultiXactIdIsValid(classForm->relminmxid) &&
3001  MultiXactIdPrecedes(classForm->relminmxid, multiForceLimit);
3002  }
3003  *wraparound = force_vacuum;
3004 
3005  /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3006  if (!av_enabled && !force_vacuum)
3007  {
3008  *doanalyze = false;
3009  *dovacuum = false;
3010  return;
3011  }
3012 
3013  /*
3014  * If we found stats for the table, and autovacuum is currently enabled,
3015  * make a threshold-based decision whether to vacuum and/or analyze. If
3016  * autovacuum is currently disabled, we must be here for anti-wraparound
3017  * vacuuming only, so don't vacuum (or analyze) anything that's not being
3018  * forced.
3019  */
3020  if (PointerIsValid(tabentry) && AutoVacuumingActive())
3021  {
3022  reltuples = classForm->reltuples;
3023  vactuples = tabentry->dead_tuples;
3024  instuples = tabentry->ins_since_vacuum;
3025  anltuples = tabentry->mod_since_analyze;
3026 
3027  /* If the table hasn't yet been vacuumed, take reltuples as zero */
3028  if (reltuples < 0)
3029  reltuples = 0;
3030 
3031  vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3032  vacinsthresh = (float4) vac_ins_base_thresh + vac_ins_scale_factor * reltuples;
3033  anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3034 
3035  /*
3036  * Note that we don't need to take special consideration for stat
3037  * reset, because if that happens, the last vacuum and analyze counts
3038  * will be reset too.
3039  */
3040  if (vac_ins_base_thresh >= 0)
3041  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3042  NameStr(classForm->relname),
3043  vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3044  else
3045  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3046  NameStr(classForm->relname),
3047  vactuples, vacthresh, anltuples, anlthresh);
3048 
3049  /* Determine if this table needs vacuum or analyze. */
3050  *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3051  (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3052  *doanalyze = (anltuples > anlthresh);
3053  }
3054  else
3055  {
3056  /*
3057  * Skip a table not found in stat hash, unless we have to force vacuum
3058  * for anti-wrap purposes. If it's not acted upon, there's no need to
3059  * vacuum it.
3060  */
3061  *dovacuum = force_vacuum;
3062  *doanalyze = false;
3063  }
3064 
3065  /* ANALYZE refuses to work with pg_statistic */
3066  if (relid == StatisticRelationId)
3067  *doanalyze = false;
3068 }
double autovacuum_vac_scale
Definition: autovacuum.c:121
int autovacuum_anl_thresh
Definition: autovacuum.c:124
int autovacuum_vac_thresh
Definition: autovacuum.c:120
double autovacuum_anl_scale
Definition: autovacuum.c:125
int autovacuum_vac_ins_thresh
Definition: autovacuum.c:122
double autovacuum_vac_ins_scale
Definition: autovacuum.c:123
#define PointerIsValid(pointer)
Definition: c.h:763
float float4
Definition: c.h:629
#define DEBUG3
Definition: elog.h:28
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
int vacuum_ins_threshold
Definition: rel.h:312
int multixact_freeze_max_age
Definition: rel.h:319
float8 vacuum_scale_factor
Definition: rel.h:323
int analyze_threshold
Definition: rel.h:313
float8 vacuum_ins_scale_factor
Definition: rel.h:324
bool enabled
Definition: rel.h:310
int freeze_max_age
Definition: rel.h:316
int vacuum_threshold
Definition: rel.h:311
float8 analyze_scale_factor
Definition: rel.h:325
PgStat_Counter ins_since_vacuum
Definition: pgstat.h:416
PgStat_Counter mod_since_analyze
Definition: pgstat.h:415
PgStat_Counter dead_tuples
Definition: pgstat.h:414
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

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

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

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

2707 {
2708  Form_pg_class classForm;
2709  HeapTuple classTup;
2710  bool dovacuum;
2711  bool doanalyze;
2712  autovac_table *tab = NULL;
2713  bool wraparound;
2714  AutoVacOpts *avopts;
2715 
2716  /* fetch the relation's relcache entry */
2717  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2718  if (!HeapTupleIsValid(classTup))
2719  return NULL;
2720  classForm = (Form_pg_class) GETSTRUCT(classTup);
2721 
2722  /*
2723  * Get the applicable reloptions. If it is a TOAST table, try to get the
2724  * main table reloptions if the toast table itself doesn't have.
2725  */
2726  avopts = extract_autovac_opts(classTup, pg_class_desc);
2727  if (classForm->relkind == RELKIND_TOASTVALUE &&
2728  avopts == NULL && table_toast_map != NULL)
2729  {
2730  av_relation *hentry;
2731  bool found;
2732 
2733  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2734  if (found && hentry->ar_hasrelopts)
2735  avopts = &hentry->ar_reloptions;
2736  }
2737 
2738  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2739  effective_multixact_freeze_max_age,
2740  &dovacuum, &doanalyze, &wraparound);
2741 
2742  /* OK, it needs something done */
2743  if (doanalyze || dovacuum)
2744  {
2745  int freeze_min_age;
2746  int freeze_table_age;
2747  int multixact_freeze_min_age;
2748  int multixact_freeze_table_age;
2749  int log_min_duration;
2750 
2751  /*
2752  * Calculate the vacuum cost parameters and the freeze ages. If there
2753  * are options set in pg_class.reloptions, use them; in the case of a
2754  * toast table, try the main table too. Otherwise use the GUC
2755  * defaults, autovacuum's own first and plain vacuum second.
2756  */
2757 
2758  /* -1 in autovac setting means use log_autovacuum_min_duration */
2759  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2760  ? avopts->log_min_duration
2762 
2763  /* these do not have autovacuum-specific settings */
2764  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2765  ? avopts->freeze_min_age
2767 
2768  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2769  ? avopts->freeze_table_age
2771 
2772  multixact_freeze_min_age = (avopts &&
2773  avopts->multixact_freeze_min_age >= 0)
2774  ? avopts->multixact_freeze_min_age
2776 
2777  multixact_freeze_table_age = (avopts &&
2778  avopts->multixact_freeze_table_age >= 0)
2779  ? avopts->multixact_freeze_table_age
2781 
2782  tab = palloc(sizeof(autovac_table));
2783  tab->at_relid = relid;
2784  tab->at_sharedrel = classForm->relisshared;
2785 
2786  /*
2787  * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2788  * that vacuum() skips toast relations. Also note we tell vacuum() to
2789  * skip vac_update_datfrozenxid(); we'll do that separately.
2790  */
2791  tab->at_params.options =
2792  (dovacuum ? (VACOPT_VACUUM |
2795  (doanalyze ? VACOPT_ANALYZE : 0) |
2796  (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2797 
2798  /*
2799  * index_cleanup and truncate are unspecified at first in autovacuum.
2800  * They will be filled in with usable values using their reloptions
2801  * (or reloption defaults) later.
2802  */
2805  /* As of now, we don't support parallel vacuum for autovacuum */
2806  tab->at_params.nworkers = -1;
2807  tab->at_params.freeze_min_age = freeze_min_age;
2808  tab->at_params.freeze_table_age = freeze_table_age;
2809  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2810  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2811  tab->at_params.is_wraparound = wraparound;
2812  tab->at_params.log_min_duration = log_min_duration;
2814  tab->at_storage_param_vac_cost_limit = avopts ?
2815  avopts->vacuum_cost_limit : 0;
2816  tab->at_storage_param_vac_cost_delay = avopts ?
2817  avopts->vacuum_cost_delay : -1;
2818  tab->at_relname = NULL;
2819  tab->at_nspname = NULL;
2820  tab->at_datname = NULL;
2821 
2822  /*
2823  * If any of the cost delay parameters has been set individually for
2824  * this table, disable the balancing algorithm.
2825  */
2826  tab->at_dobalance =
2827  !(avopts && (avopts->vacuum_cost_limit > 0 ||
2828  avopts->vacuum_cost_delay >= 0));
2829  }
2830 
2831  heap_freetuple(classTup);
2832  return tab;
2833 }
int Log_autovacuum_min_duration
Definition: autovacuum.c:132
static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
Definition: autovacuum.c:2844
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
int log_min_duration
Definition: rel.h:321
float8 vacuum_cost_delay
Definition: rel.h:322
int vacuum_cost_limit
Definition: rel.h:314
int multixact_freeze_table_age
Definition: rel.h:320
int freeze_min_age
Definition: rel.h:315
int freeze_table_age
Definition: rel.h:317
int multixact_freeze_min_age
Definition: rel.h:318
int nworkers
Definition: vacuum.h:239
int freeze_table_age
Definition: vacuum.h:221
VacOptValue truncate
Definition: vacuum.h:231
int freeze_min_age
Definition: vacuum.h:220
int multixact_freeze_min_age
Definition: vacuum.h:222
int multixact_freeze_table_age
Definition: vacuum.h:224
int log_min_duration
Definition: vacuum.h:227
Oid toast_parent
Definition: vacuum.h:232
VacOptValue index_cleanup
Definition: vacuum.h:230
bool at_sharedrel
Definition: autovacuum.c:203
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:185
#define VACOPT_SKIP_DATABASE_STATS
Definition: vacuum.h:189
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:202
#define VACOPT_PROCESS_MAIN
Definition: vacuum.h:186

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_storage_param_vac_cost_delay, autovac_table::at_storage_param_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, InvalidOid, VacuumParams::is_wraparound, Log_autovacuum_min_duration, VacuumParams::log_min_duration, AutoVacOpts::log_min_duration, VacuumParams::multixact_freeze_min_age, AutoVacOpts::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, AutoVacOpts::multixact_freeze_table_age, VacuumParams::nworkers, ObjectIdGetDatum(), VacuumParams::options, palloc(), recheck_relation_needs_vacanalyze(), SearchSysCacheCopy1, VacuumParams::toast_parent, VacuumParams::truncate, VACOPT_ANALYZE, VACOPT_PROCESS_MAIN, VACOPT_SKIP_DATABASE_STATS, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, VACOPTVALUE_UNSPECIFIED, AutoVacOpts::vacuum_cost_delay, and AutoVacOpts::vacuum_cost_limit.

Referenced by do_autovacuum().

◆ VacuumUpdateCosts()

void VacuumUpdateCosts ( void  )

Definition at line 1633 of file autovacuum.c.

1634 {
1635  if (MyWorkerInfo)
1636  {
1637  if (av_storage_param_cost_delay >= 0)
1639  else if (autovacuum_vac_cost_delay >= 0)
1641  else
1642  /* fall back to VacuumCostDelay */
1644 
1646  }
1647  else
1648  {
1649  /* Must be explicit VACUUM or ANALYZE */
1652  }
1653 
1654  /*
1655  * If configuration changes are allowed to impact VacuumCostActive, make
1656  * sure it is updated.
1657  */
1660  else if (vacuum_cost_delay > 0)
1661  VacuumCostActive = true;
1662  else
1663  {
1664  VacuumCostActive = false;
1665  VacuumCostBalance = 0;
1666  }
1667 
1668  /*
1669  * Since the cost logging requires a lock, avoid rendering the log message
1670  * in case we are using a message level where the log wouldn't be emitted.
1671  */
1673  {
1674  Oid dboid,
1675  tableoid;
1676 
1677  Assert(!LWLockHeldByMe(AutovacuumLock));
1678 
1679  LWLockAcquire(AutovacuumLock, LW_SHARED);
1680  dboid = MyWorkerInfo->wi_dboid;
1681  tableoid = MyWorkerInfo->wi_tableoid;
1682  LWLockRelease(AutovacuumLock);
1683 
1684  elog(DEBUG2,
1685  "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1686  dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1688  vacuum_cost_delay > 0 ? "yes" : "no",
1689  VacuumFailsafeActive ? "yes" : "no");
1690  }
1691 }
double autovacuum_vac_cost_delay
Definition: autovacuum.c:129
void AutoVacuumUpdateCostLimit(void)
Definition: autovacuum.c:1702
bool message_level_is_interesting(int elevel)
Definition: elog.c:276
bool VacuumCostActive
Definition: globals.c:159
int VacuumCostBalance
Definition: globals.c:158
double VacuumCostDelay
Definition: globals.c:152
double vacuum_cost_delay
Definition: vacuum.c:80
bool VacuumFailsafeActive
Definition: vacuum.c:96

References Assert, autovacuum_vac_cost_delay, AutoVacuumUpdateCostLimit(), av_storage_param_cost_delay, DEBUG2, elog, LW_SHARED, LWLockAcquire(), LWLockHeldByMe(), LWLockRelease(), message_level_is_interesting(), MyWorkerInfo, pg_atomic_unlocked_test_flag(), vacuum_cost_delay, vacuum_cost_limit, VacuumCostActive, VacuumCostBalance, VacuumCostDelay, VacuumCostLimit, VacuumFailsafeActive, WorkerInfoData::wi_dboid, WorkerInfoData::wi_dobalance, and WorkerInfoData::wi_tableoid.

Referenced by do_autovacuum(), parallel_vacuum_main(), vacuum(), and vacuum_delay_point().

Variable Documentation

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

Definition at line 164 of file autovacuum.c.

Referenced by do_autovacuum(), perform_work_item(), and rebuild_database_list().

◆ autovacuum_anl_scale

double autovacuum_anl_scale

Definition at line 125 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 124 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

int autovacuum_freeze_max_age

◆ autovacuum_max_workers

◆ autovacuum_multixact_freeze_max_age

int autovacuum_multixact_freeze_max_age

◆ autovacuum_naptime

int autovacuum_naptime

◆ autovacuum_start_daemon

bool autovacuum_start_daemon = false

Definition at line 116 of file autovacuum.c.

Referenced by autovac_init(), and AutoVacuumingActive().

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 129 of file autovacuum.c.

Referenced by VacuumUpdateCosts().

◆ autovacuum_vac_cost_limit

int autovacuum_vac_cost_limit

Definition at line 130 of file autovacuum.c.

Referenced by AutoVacuumUpdateCostLimit().

◆ autovacuum_vac_ins_scale

double autovacuum_vac_ins_scale

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 122 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 121 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 120 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 118 of file autovacuum.c.

Referenced by dead_items_alloc(), and ginInsertCleanup().

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

Definition at line 312 of file autovacuum.c.

Referenced by FreeWorkerInfo(), and ProcKill().

◆ AutoVacuumShmem

◆ av_storage_param_cost_delay

double av_storage_param_cost_delay = -1
static

Definition at line 147 of file autovacuum.c.

Referenced by do_autovacuum(), and VacuumUpdateCosts().

◆ av_storage_param_cost_limit

int av_storage_param_cost_limit = -1
static

Definition at line 148 of file autovacuum.c.

Referenced by AutoVacuumUpdateCostLimit(), and do_autovacuum().

◆ DatabaseList

dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
static

◆ DatabaseListCxt

MemoryContext DatabaseListCxt = NULL
static

Definition at line 306 of file autovacuum.c.

Referenced by rebuild_database_list().

◆ default_freeze_min_age

int default_freeze_min_age
static

Definition at line 158 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 159 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 160 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 161 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 151 of file autovacuum.c.

Referenced by avl_sigusr2_handler().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = 600000

Definition at line 132 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

WorkerInfo MyWorkerInfo = NULL
static

◆ recentMulti

MultiXactId recentMulti
static

Definition at line 155 of file autovacuum.c.

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

◆ recentXid

TransactionId recentXid
static

Definition at line 154 of file autovacuum.c.

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