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/injection_point.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 137 of file autovacuum.c.

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 136 of file autovacuum.c.

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

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

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 
AutoVacNumSignals 

Definition at line 246 of file autovacuum.c.

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

Function Documentation

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3253 of file autovacuum.c.

3254 {
3256  ereport(WARNING,
3257  (errmsg("autovacuum not started because of misconfiguration"),
3258  errhint("Enable the \"track_counts\" option.")));
3259 }
bool autovacuum_start_daemon
Definition: autovacuum.c:117
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define WARNING
Definition: elog.h:36
#define ereport(elevel,...)
Definition: elog.h:149
bool pgstat_track_counts
Definition: pgstat.c:192

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

1750 {
1751  dlist_iter iter;
1752  int orig_nworkers_for_balance;
1753  int nworkers_for_balance = 0;
1754 
1755  Assert(LWLockHeldByMe(AutovacuumLock));
1756 
1757  orig_nworkers_for_balance =
1759 
1761  {
1762  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1763 
1764  if (worker->wi_proc == NULL ||
1766  continue;
1767 
1768  nworkers_for_balance++;
1769  }
1770 
1771  if (nworkers_for_balance != orig_nworkers_for_balance)
1773  nworkers_for_balance);
1774 }
static bool pg_atomic_unlocked_test_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:189
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:269
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:232
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:300
#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:1893
pg_atomic_uint32 av_nworkersForBalance
Definition: autovacuum.c:297
dlist_head av_runningWorkers
Definition: autovacuum.c:294
PGPROC * wi_proc
Definition: autovacuum.c:233
pg_atomic_flag wi_dobalance
Definition: autovacuum.c:235
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 3124 of file autovacuum.c.

3125 {
3126 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3127  char activity[MAX_AUTOVAC_ACTIV_LEN];
3128  int len;
3129 
3130  /* Report the command and possible options */
3131  if (tab->at_params.options & VACOPT_VACUUM)
3132  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3133  "autovacuum: VACUUM%s",
3134  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3135  else
3136  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3137  "autovacuum: ANALYZE");
3138 
3139  /*
3140  * Report the qualified name of the relation.
3141  */
3142  len = strlen(activity);
3143 
3144  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3145  " %s.%s%s", tab->at_nspname, tab->at_relname,
3146  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3147 
3148  /* Set statement_timestamp() to current time for pg_stat_activity */
3150 
3152 }
#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:206
char * at_relname
Definition: autovacuum.c:205
VacuumParams at_params
Definition: autovacuum.c:200
#define VACOPT_VACUUM
Definition: vacuum.h:180
#define VACOPT_ANALYZE
Definition: vacuum.h:181
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:912

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

3161 {
3162  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3163  char blk[12 + 2];
3164  int len;
3165 
3166  switch (workitem->avw_type)
3167  {
3169  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3170  "autovacuum: BRIN summarize");
3171  break;
3172  }
3173 
3174  /*
3175  * Report the qualified name of the relation, and the block number if any
3176  */
3177  len = strlen(activity);
3178 
3179  if (BlockNumberIsValid(workitem->avw_blockNumber))
3180  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3181  else
3182  blk[0] = '\0';
3183 
3184  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3185  " %s.%s%s", nspname, relname, blk);
3186 
3187  /* Set statement_timestamp() to current time for pg_stat_activity */
3189 
3191 }
@ 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:266
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:261

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

363 {
364  sigjmp_buf local_sigjmp_buf;
365 
366  Assert(startup_data_len == 0);
367 
368  /* Release postmaster's working memory context */
369  if (PostmasterContext)
370  {
372  PostmasterContext = NULL;
373  }
374 
376  init_ps_display(NULL);
377 
378  ereport(DEBUG1,
379  (errmsg_internal("autovacuum launcher started")));
380 
381  if (PostAuthDelay)
382  pg_usleep(PostAuthDelay * 1000000L);
383 
385 
386  /*
387  * Set up signal handlers. We operate on databases much like a regular
388  * backend, so we use the same signal handling. See equivalent code in
389  * tcop/postgres.c.
390  */
394  /* SIGQUIT handler was already set up by InitPostmasterChild */
395 
396  InitializeTimeouts(); /* establishes SIGALRM handler */
397 
403 
404  /*
405  * Create a per-backend PGPROC struct in shared memory. We must do this
406  * before we can use LWLocks or access any shared memory.
407  */
408  InitProcess();
409 
410  /* Early initialization */
411  BaseInit();
412 
413  InitPostgres(NULL, InvalidOid, NULL, InvalidOid, 0, NULL);
414 
416 
417  /*
418  * Create a memory context that we will do all our work in. We do this so
419  * that we can reset the context during error recovery and thereby avoid
420  * possible memory leaks.
421  */
423  "Autovacuum Launcher",
426 
427  /*
428  * If an exception is encountered, processing resumes here.
429  *
430  * This code is a stripped down version of PostgresMain error recovery.
431  *
432  * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
433  * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
434  * signals other than SIGQUIT will be blocked until we complete error
435  * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
436  * call redundant, but it is not since InterruptPending might be set
437  * already.
438  */
439  if (sigsetjmp(local_sigjmp_buf, 1) != 0)
440  {
441  /* since not using PG_TRY, must reset error stack by hand */
442  error_context_stack = NULL;
443 
444  /* Prevents interrupts while cleaning up */
445  HOLD_INTERRUPTS();
446 
447  /* Forget any pending QueryCancel or timeout request */
448  disable_all_timeouts(false);
449  QueryCancelPending = false; /* second to avoid race condition */
450 
451  /* Report the error to the server log */
452  EmitErrorReport();
453 
454  /* Abort the current transaction in order to recover */
456 
457  /*
458  * Release any other resources, for the case where we were not in a
459  * transaction.
460  */
463  UnlockBuffers();
464  /* this is probably dead code, but let's be safe: */
467  AtEOXact_Buffers(false);
468  AtEOXact_SMgr();
469  AtEOXact_Files(false);
470  AtEOXact_HashTables(false);
471 
472  /*
473  * Now return to normal top-level context and clear ErrorContext for
474  * next time.
475  */
477  FlushErrorState();
478 
479  /* Flush any leaked data in the top-level context */
481 
482  /* don't leave dangling pointers to freed memory */
483  DatabaseListCxt = NULL;
485 
486  /* Now we can allow interrupts again */
488 
489  /* if in shutdown mode, no need for anything further; just go away */
492 
493  /*
494  * Sleep at least 1 second after any error. We don't want to be
495  * filling the error logs as fast as we can.
496  */
497  pg_usleep(1000000L);
498  }
499 
500  /* We can now handle ereport(ERROR) */
501  PG_exception_stack = &local_sigjmp_buf;
502 
503  /* must unblock signals before calling rebuild_database_list */
504  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
505 
506  /*
507  * Set always-secure search path. Launcher doesn't connect to a database,
508  * so this has no effect.
509  */
510  SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
511 
512  /*
513  * Force zero_damaged_pages OFF in the autovac process, even if it is set
514  * in postgresql.conf. We don't really want such a dangerous option being
515  * applied non-interactively.
516  */
517  SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
518 
519  /*
520  * Force settable timeouts off to avoid letting these settings prevent
521  * regular maintenance from being executed.
522  */
523  SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
524  SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
525  SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
526  SetConfigOption("idle_in_transaction_session_timeout", "0",
528 
529  /*
530  * Force default_transaction_isolation to READ COMMITTED. We don't want
531  * to pay the overhead of serializable mode, nor add any risk of causing
532  * deadlocks or delaying other transactions.
533  */
534  SetConfigOption("default_transaction_isolation", "read committed",
536 
537  /*
538  * Even when system is configured to use a different fetch consistency,
539  * for autovac we always want fresh stats.
540  */
541  SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
542 
543  /*
544  * In emergency mode, just start a worker (unless shutdown was requested)
545  * and go away.
546  */
547  if (!AutoVacuumingActive())
548  {
550  do_start_worker();
551  proc_exit(0); /* done */
552  }
553 
555 
556  /*
557  * Create the initial database list. The invariant we want this list to
558  * keep is that it's ordered by decreasing next_time. As soon as an entry
559  * is updated to a higher time, it will be moved to the front (which is
560  * correct because the only operation is to add autovacuum_naptime to the
561  * entry, and time always increases).
562  */
564 
565  /* loop until shutdown request */
566  while (!ShutdownRequestPending)
567  {
568  struct timeval nap;
569  TimestampTz current_time = 0;
570  bool can_launch;
571 
572  /*
573  * This loop is a bit different from the normal use of WaitLatch,
574  * because we'd like to sleep before the first launch of a child
575  * process. So it's WaitLatch, then ResetLatch, then check for
576  * wakening conditions.
577  */
578 
580  false, &nap);
581 
582  /*
583  * Wait until naptime expires or we get some type of signal (all the
584  * signal handlers will wake us by calling SetLatch).
585  */
586  (void) WaitLatch(MyLatch,
588  (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
589  WAIT_EVENT_AUTOVACUUM_MAIN);
590 
592 
594 
595  /*
596  * a worker finished, or postmaster signaled failure to start a worker
597  */
598  if (got_SIGUSR2)
599  {
600  got_SIGUSR2 = false;
601 
602  /* rebalance cost limits, if needed */
604  {
605  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
608  LWLockRelease(AutovacuumLock);
609  }
610 
612  {
613  /*
614  * If the postmaster failed to start a new worker, we sleep
615  * for a little while and resend the signal. The new worker's
616  * state is still in memory, so this is sufficient. After
617  * that, we restart the main loop.
618  *
619  * XXX should we put a limit to the number of times we retry?
620  * I don't think it makes much sense, because a future start
621  * of a worker will continue to fail in the same way.
622  */
624  pg_usleep(1000000L); /* 1s */
626  continue;
627  }
628  }
629 
630  /*
631  * There are some conditions that we need to check before trying to
632  * start a worker. First, we need to make sure that there is a worker
633  * slot available. Second, we need to make sure that no other worker
634  * failed while starting up.
635  */
636 
637  current_time = GetCurrentTimestamp();
638  LWLockAcquire(AutovacuumLock, LW_SHARED);
639 
641 
642  if (AutoVacuumShmem->av_startingWorker != NULL)
643  {
644  int waittime;
646 
647  /*
648  * We can't launch another worker when another one is still
649  * starting up (or failed while doing so), so just sleep for a bit
650  * more; that worker will wake us up again as soon as it's ready.
651  * We will only wait autovacuum_naptime seconds (up to a maximum
652  * of 60 seconds) for this to happen however. Note that failure
653  * to connect to a particular database is not a problem here,
654  * because the worker removes itself from the startingWorker
655  * pointer before trying to connect. Problems detected by the
656  * postmaster (like fork() failure) are also reported and handled
657  * differently. The only problems that may cause this code to
658  * fire are errors in the earlier sections of AutoVacWorkerMain,
659  * before the worker removes the WorkerInfo from the
660  * startingWorker pointer.
661  */
662  waittime = Min(autovacuum_naptime, 60) * 1000;
663  if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
664  waittime))
665  {
666  LWLockRelease(AutovacuumLock);
667  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
668 
669  /*
670  * No other process can put a worker in starting mode, so if
671  * startingWorker is still INVALID after exchanging our lock,
672  * we assume it's the same one we saw above (so we don't
673  * recheck the launch time).
674  */
675  if (AutoVacuumShmem->av_startingWorker != NULL)
676  {
678  worker->wi_dboid = InvalidOid;
679  worker->wi_tableoid = InvalidOid;
680  worker->wi_sharedrel = false;
681  worker->wi_proc = NULL;
682  worker->wi_launchtime = 0;
684  &worker->wi_links);
687  errmsg("autovacuum worker took too long to start; canceled"));
688  }
689  }
690  else
691  can_launch = false;
692  }
693  LWLockRelease(AutovacuumLock); /* either shared or exclusive */
694 
695  /* if we can't do anything, just go back to sleep */
696  if (!can_launch)
697  continue;
698 
699  /* We're OK to start a new worker */
700 
702  {
703  /*
704  * Special case when the list is empty: start a worker right away.
705  * This covers the initial case, when no database is in pgstats
706  * (thus the list is empty). Note that the constraints in
707  * launcher_determine_sleep keep us from starting workers too
708  * quickly (at most once every autovacuum_naptime when the list is
709  * empty).
710  */
711  launch_worker(current_time);
712  }
713  else
714  {
715  /*
716  * because rebuild_database_list constructs a list with most
717  * distant adl_next_worker first, we obtain our database from the
718  * tail of the list.
719  */
720  avl_dbase *avdb;
721 
722  avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
723 
724  /*
725  * launch a worker if next_worker is right now or it is in the
726  * past
727  */
729  current_time, 0))
730  launch_worker(current_time);
731  }
732  }
733 
735 }
static Oid do_start_worker(void)
Definition: autovacuum.c:1074
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition: autovacuum.c:793
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:152
static void avl_sigusr2_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1345
static void HandleAutoVacLauncherInterrupts(void)
Definition: autovacuum.c:741
int autovacuum_naptime
Definition: autovacuum.c:120
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3199
static void AutoVacLauncherShutdown(void)
Definition: autovacuum.c:317
static void launch_worker(TimestampTz now)
Definition: autovacuum.c:1286
static dlist_head DatabaseList
Definition: autovacuum.c:306
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:877
static MemoryContext DatabaseListCxt
Definition: autovacuum.c:307
static void autovac_recalculate_workers_for_balance(void)
Definition: autovacuum.c:1749
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:165
sigset_t UnBlockSig
Definition: pqsignal.c:22
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1791
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1655
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:3571
void UnlockBuffers(void)
Definition: bufmgr.c:5143
#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:1157
void EmitErrorReport(void)
Definition: elog.c:1670
ErrorContextCallback * error_context_stack
Definition: elog.c:94
void FlushErrorState(void)
Definition: elog.c:1850
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:46
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:32
struct Latch * MyLatch
Definition: globals.c:61
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4282
@ 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:1168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
void LWLockReleaseAll(void)
Definition: lwlock.c:1876
@ 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 GetProcessingMode()
Definition: miscadmin.h:458
#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:3018
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3001
#define InvalidOid
Definition: postgres_ext.h:36
void BaseInit(void)
Definition: postinit.c:602
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:693
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:293
WorkerInfo av_startingWorker
Definition: autovacuum.c:295
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:291
TimestampTz wi_launchtime
Definition: autovacuum.c:234
dlist_node wi_links
Definition: autovacuum.c:230
TimestampTz adl_next_worker
Definition: autovacuum.c:171
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:101
#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:3425

Referenced by HandleAutoVacLauncherInterrupts().

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3088 of file autovacuum.c.

3089 {
3090  RangeVar *rangevar;
3091  VacuumRelation *rel;
3092  List *rel_list;
3093  MemoryContext vac_context;
3094 
3095  /* Let pgstat know what we're doing */
3097 
3098  /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3099  rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3100  rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3101  rel_list = list_make1(rel);
3102 
3104  "Vacuum",
3106 
3107  vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3108 
3109  MemoryContextDelete(vac_context);
3110 }
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3124
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 3199 of file autovacuum.c.

3200 {
3202  return false;
3203  return true;
3204 }

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

3213 {
3214  int i;
3215  bool result = false;
3216 
3217  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3218 
3219  /*
3220  * Locate an unused work item and fill it with the given data.
3221  */
3222  for (i = 0; i < NUM_WORKITEMS; i++)
3223  {
3225 
3226  if (workitem->avw_used)
3227  continue;
3228 
3229  workitem->avw_used = true;
3230  workitem->avw_active = false;
3231  workitem->avw_type = type;
3232  workitem->avw_database = MyDatabaseId;
3233  workitem->avw_relation = relationId;
3234  workitem->avw_blockNumber = blkno;
3235  result = true;
3236 
3237  /* done */
3238  break;
3239  }
3240 
3241  LWLockRelease(AutovacuumLock);
3242 
3243  return result;
3244 }
#define NUM_WORKITEMS
Definition: autovacuum.c:269
Oid MyDatabaseId
Definition: globals.c:92
int i
Definition: isn.c:73
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:296
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 3285 of file autovacuum.c.

3286 {
3287  bool found;
3288 
3290  ShmemInitStruct("AutoVacuum Data",
3292  &found);
3293 
3294  if (!IsUnderPostmaster)
3295  {
3296  WorkerInfo worker;
3297  int i;
3298 
3299  Assert(!found);
3300 
3305  memset(AutoVacuumShmem->av_workItems, 0,
3306  sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3307 
3308  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3309  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3310 
3311  /* initialize the WorkerInfo free list */
3312  for (i = 0; i < autovacuum_max_workers; i++)
3313  {
3315  &worker[i].wi_links);
3316  pg_atomic_init_flag(&worker[i].wi_dobalance);
3317  }
3318 
3320 
3321  }
3322  else
3323  Assert(found);
3324 }
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:214
static void pg_atomic_init_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:163
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3266
int autovacuum_max_workers
Definition: autovacuum.c:118
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:239
#define MAXALIGN(LEN)
Definition: c.h:811
bool IsUnderPostmaster
Definition: globals.c:118
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 3266 of file autovacuum.c.

3267 {
3268  Size size;
3269 
3270  /*
3271  * Need the fixed struct and the array of WorkerInfoData.
3272  */
3273  size = sizeof(AutoVacuumShmemStruct);
3274  size = MAXALIGN(size);
3276  sizeof(WorkerInfoData)));
3277  return size;
3278 }
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 1703 of file autovacuum.c.

1704 {
1705  if (!MyWorkerInfo)
1706  return;
1707 
1708  /*
1709  * note: in cost_limit, zero also means use value from elsewhere, because
1710  * zero is not a valid value.
1711  */
1712 
1715  else
1716  {
1717  int nworkers_for_balance;
1718 
1719  if (autovacuum_vac_cost_limit > 0)
1721  else
1723 
1724  /* Only balance limit if no cost-related storage parameters specified */
1726  return;
1727 
1729 
1730  nworkers_for_balance = pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1731 
1732  /* There is at least 1 autovac worker (this worker) */
1733  if (nworkers_for_balance <= 0)
1734  elog(ERROR, "nworkers_for_balance must be > 0");
1735 
1736  vacuum_cost_limit = Max(vacuum_cost_limit / nworkers_for_balance, 1);
1737  }
1738 }
int autovacuum_vac_cost_limit
Definition: autovacuum.c:131
static int av_storage_param_cost_limit
Definition: autovacuum.c:149
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:310
#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:152
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 1338 of file autovacuum.c.

1339 {
1341 }

References AutoVacForkFailed, AutoVacuumShmem, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

◆ AutoVacWorkerMain()

void AutoVacWorkerMain ( char *  startup_data,
size_t  startup_data_len 
)

Definition at line 1360 of file autovacuum.c.

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

1346 {
1347  got_SIGUSR2 = true;
1348  SetLatch(MyLatch);
1349 }
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 3330 of file autovacuum.c.

3331 {
3332  /*
3333  * -1 indicates fallback.
3334  *
3335  * If we haven't yet changed the boot_val default of -1, just let it be.
3336  * Autovacuum will look to maintenance_work_mem instead.
3337  */
3338  if (*newval == -1)
3339  return true;
3340 
3341  /*
3342  * We clamp manually-set values to at least 1MB. Since
3343  * maintenance_work_mem is always set to at least this value, do the same
3344  * here.
3345  */
3346  if (*newval < 1024)
3347  *newval = 1024;
3348 
3349  return true;
3350 }
#define newval

References newval.

◆ db_comparator()

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

Definition at line 1056 of file autovacuum.c.

1057 {
1058  return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1059  ((const avl_dbase *) b)->adl_score);
1060 }
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 1874 of file autovacuum.c.

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

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

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

2682 {
2683  bytea *relopts;
2684  AutoVacOpts *av;
2685 
2686  Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2687  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2688  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2689 
2690  relopts = extractRelOptions(tup, pg_class_desc, NULL);
2691  if (relopts == NULL)
2692  return NULL;
2693 
2694  av = palloc(sizeof(AutoVacOpts));
2695  memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2696  pfree(relopts);
2697 
2698  return av;
2699 }
void * palloc(Size size)
Definition: mcxt.c:1317
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 1586 of file autovacuum.c.

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

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

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

742 {
743  /* the normal shutdown case */
746 
748  {
749  ConfigReloadPending = false;
751 
752  /* shutdown requested in config file? */
753  if (!AutoVacuumingActive())
755 
756  /* rebuild the list in case the naptime changed */
758  }
759 
760  /* Process barrier events */
763 
764  /* Perform logging of memory contexts of this process */
767 
768  /* Process sinval catchup interrupts that happened while sleeping */
770 }
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:40
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:39
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1289
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 1286 of file autovacuum.c.

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

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

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

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

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

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

2858 {
2859  PgStat_StatTabEntry *tabentry;
2860 
2861  /* fetch the pgstat table entry */
2862  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2863  relid);
2864 
2865  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2866  effective_multixact_freeze_max_age,
2867  dovacuum, doanalyze, wraparound);
2868 
2869  /* ignore ANALYZE for toast tables */
2870  if (classForm->relkind == RELKIND_TOASTVALUE)
2871  *doanalyze = false;
2872 }

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

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

2714 {
2715  Form_pg_class classForm;
2716  HeapTuple classTup;
2717  bool dovacuum;
2718  bool doanalyze;
2719  autovac_table *tab = NULL;
2720  bool wraparound;
2721  AutoVacOpts *avopts;
2722 
2723  /* fetch the relation's relcache entry */
2724  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2725  if (!HeapTupleIsValid(classTup))
2726  return NULL;
2727  classForm = (Form_pg_class) GETSTRUCT(classTup);
2728 
2729  /*
2730  * Get the applicable reloptions. If it is a TOAST table, try to get the
2731  * main table reloptions if the toast table itself doesn't have.
2732  */
2733  avopts = extract_autovac_opts(classTup, pg_class_desc);
2734  if (classForm->relkind == RELKIND_TOASTVALUE &&
2735  avopts == NULL && table_toast_map != NULL)
2736  {
2737  av_relation *hentry;
2738  bool found;
2739 
2740  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2741  if (found && hentry->ar_hasrelopts)
2742  avopts = &hentry->ar_reloptions;
2743  }
2744 
2745  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2746  effective_multixact_freeze_max_age,
2747  &dovacuum, &doanalyze, &wraparound);
2748 
2749  /* OK, it needs something done */
2750  if (doanalyze || dovacuum)
2751  {
2752  int freeze_min_age;
2753  int freeze_table_age;
2754  int multixact_freeze_min_age;
2755  int multixact_freeze_table_age;
2756  int log_min_duration;
2757 
2758  /*
2759  * Calculate the vacuum cost parameters and the freeze ages. If there
2760  * are options set in pg_class.reloptions, use them; in the case of a
2761  * toast table, try the main table too. Otherwise use the GUC
2762  * defaults, autovacuum's own first and plain vacuum second.
2763  */
2764 
2765  /* -1 in autovac setting means use log_autovacuum_min_duration */
2766  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2767  ? avopts->log_min_duration
2769 
2770  /* these do not have autovacuum-specific settings */
2771  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2772  ? avopts->freeze_min_age
2774 
2775  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2776  ? avopts->freeze_table_age
2778 
2779  multixact_freeze_min_age = (avopts &&
2780  avopts->multixact_freeze_min_age >= 0)
2781  ? avopts->multixact_freeze_min_age
2783 
2784  multixact_freeze_table_age = (avopts &&
2785  avopts->multixact_freeze_table_age >= 0)
2786  ? avopts->multixact_freeze_table_age
2788 
2789  tab = palloc(sizeof(autovac_table));
2790  tab->at_relid = relid;
2791  tab->at_sharedrel = classForm->relisshared;
2792 
2793  /*
2794  * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2795  * that vacuum() skips toast relations. Also note we tell vacuum() to
2796  * skip vac_update_datfrozenxid(); we'll do that separately.
2797  */
2798  tab->at_params.options =
2799  (dovacuum ? (VACOPT_VACUUM |
2802  (doanalyze ? VACOPT_ANALYZE : 0) |
2803  (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2804 
2805  /*
2806  * index_cleanup and truncate are unspecified at first in autovacuum.
2807  * They will be filled in with usable values using their reloptions
2808  * (or reloption defaults) later.
2809  */
2812  /* As of now, we don't support parallel vacuum for autovacuum */
2813  tab->at_params.nworkers = -1;
2814  tab->at_params.freeze_min_age = freeze_min_age;
2815  tab->at_params.freeze_table_age = freeze_table_age;
2816  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2817  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2818  tab->at_params.is_wraparound = wraparound;
2819  tab->at_params.log_min_duration = log_min_duration;
2821  tab->at_storage_param_vac_cost_limit = avopts ?
2822  avopts->vacuum_cost_limit : 0;
2823  tab->at_storage_param_vac_cost_delay = avopts ?
2824  avopts->vacuum_cost_delay : -1;
2825  tab->at_relname = NULL;
2826  tab->at_nspname = NULL;
2827  tab->at_datname = NULL;
2828 
2829  /*
2830  * If any of the cost delay parameters has been set individually for
2831  * this table, disable the balancing algorithm.
2832  */
2833  tab->at_dobalance =
2834  !(avopts && (avopts->vacuum_cost_limit > 0 ||
2835  avopts->vacuum_cost_delay >= 0));
2836  }
2837 
2838  heap_freetuple(classTup);
2839  return tab;
2840 }
int Log_autovacuum_min_duration
Definition: autovacuum.c:133
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:2851
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:204
#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 1634 of file autovacuum.c.

1635 {
1636  if (MyWorkerInfo)
1637  {
1638  if (av_storage_param_cost_delay >= 0)
1640  else if (autovacuum_vac_cost_delay >= 0)
1642  else
1643  /* fall back to VacuumCostDelay */
1645 
1647  }
1648  else
1649  {
1650  /* Must be explicit VACUUM or ANALYZE */
1653  }
1654 
1655  /*
1656  * If configuration changes are allowed to impact VacuumCostActive, make
1657  * sure it is updated.
1658  */
1661  else if (vacuum_cost_delay > 0)
1662  VacuumCostActive = true;
1663  else
1664  {
1665  VacuumCostActive = false;
1666  VacuumCostBalance = 0;
1667  }
1668 
1669  /*
1670  * Since the cost logging requires a lock, avoid rendering the log message
1671  * in case we are using a message level where the log wouldn't be emitted.
1672  */
1674  {
1675  Oid dboid,
1676  tableoid;
1677 
1678  Assert(!LWLockHeldByMe(AutovacuumLock));
1679 
1680  LWLockAcquire(AutovacuumLock, LW_SHARED);
1681  dboid = MyWorkerInfo->wi_dboid;
1682  tableoid = MyWorkerInfo->wi_tableoid;
1683  LWLockRelease(AutovacuumLock);
1684 
1685  elog(DEBUG2,
1686  "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1687  dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1689  vacuum_cost_delay > 0 ? "yes" : "no",
1690  VacuumFailsafeActive ? "yes" : "no");
1691  }
1692 }
double autovacuum_vac_cost_delay
Definition: autovacuum.c:130
void AutoVacuumUpdateCostLimit(void)
Definition: autovacuum.c:1703
bool message_level_is_interesting(int elevel)
Definition: elog.c:272
bool VacuumCostActive
Definition: globals.c:160
int VacuumCostBalance
Definition: globals.c:159
double VacuumCostDelay
Definition: globals.c:153
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 165 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 126 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 125 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

int autovacuum_freeze_max_age

◆ autovacuum_max_workers

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

Referenced by autovac_init(), and AutoVacuumingActive().

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 130 of file autovacuum.c.

Referenced by VacuumUpdateCosts().

◆ autovacuum_vac_cost_limit

int autovacuum_vac_cost_limit

Definition at line 131 of file autovacuum.c.

Referenced by AutoVacuumUpdateCostLimit().

◆ autovacuum_vac_ins_scale

double autovacuum_vac_ins_scale

Definition at line 124 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 122 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 121 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 119 of file autovacuum.c.

Referenced by dead_items_alloc(), and ginInsertCleanup().

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

Definition at line 313 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 148 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 149 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 307 of file autovacuum.c.

Referenced by rebuild_database_list().

◆ default_freeze_min_age

int default_freeze_min_age
static

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

Referenced by avl_sigusr2_handler().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = 600000

Definition at line 133 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

WorkerInfo MyWorkerInfo = NULL
static

◆ recentMulti

MultiXactId recentMulti
static

Definition at line 156 of file autovacuum.c.

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

◆ recentXid

TransactionId recentXid
static

Definition at line 155 of file autovacuum.c.

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