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

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Enumerations

enum  AutoVacuumSignal { AutoVacForkFailed , AutoVacRebalance , AutoVacNumSignals }
 

Functions

NON_EXEC_STATIC void AutoVacWorkerMain (int argc, char *argv[]) pg_attribute_noreturn()
 
NON_EXEC_STATIC void AutoVacLauncherMain (int argc, char *argv[]) pg_attribute_noreturn()
 
static Oid do_start_worker (void)
 
static void HandleAutoVacLauncherInterrupts (void)
 
static void AutoVacLauncherShutdown (void)
 
static void launcher_determine_sleep (bool canlaunch, bool recursing, struct timeval *nap)
 
static void rebuild_database_list (Oid newdb)
 
static int db_comparator (const void *a, const void *b)
 
static void launch_worker (TimestampTz now)
 
void AutoVacWorkerFailed (void)
 
static void avl_sigusr2_handler (SIGNAL_ARGS)
 
int StartAutoVacWorker (void)
 
static void FreeWorkerInfo (int code, Datum arg)
 
void 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)
 
bool IsAutoVacuumLauncherProcess (void)
 
bool IsAutoVacuumWorkerProcess (void)
 
Size AutoVacuumShmemSize (void)
 
void AutoVacuumShmemInit (void)
 
bool check_autovacuum_work_mem (int *newval, void **extra, GucSource source)
 

Variables

bool autovacuum_start_daemon = false
 
int autovacuum_max_workers
 
int autovacuum_work_mem = -1
 
int autovacuum_naptime
 
int autovacuum_vac_thresh
 
double autovacuum_vac_scale
 
int autovacuum_vac_ins_thresh
 
double autovacuum_vac_ins_scale
 
int autovacuum_anl_thresh
 
double autovacuum_anl_scale
 
int autovacuum_freeze_max_age
 
int autovacuum_multixact_freeze_max_age
 
double autovacuum_vac_cost_delay
 
int autovacuum_vac_cost_limit
 
int Log_autovacuum_min_duration = 600000
 
static bool am_autovacuum_launcher = false
 
static bool am_autovacuum_worker = false
 
static 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 273 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 243 of file autovacuum.c.

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 
AutoVacNumSignals 

Definition at line 250 of file autovacuum.c.

251 {
252  AutoVacForkFailed, /* failed trying to start a worker */
253  AutoVacRebalance, /* rebalance the cost limits */
254  AutoVacNumSignals, /* must be last */
AutoVacuumSignal
Definition: autovacuum.c:251
@ AutoVacRebalance
Definition: autovacuum.c:253
@ AutoVacForkFailed
Definition: autovacuum.c:252
@ AutoVacNumSignals
Definition: autovacuum.c:254

Function Documentation

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3347 of file autovacuum.c.

3348 {
3350  ereport(WARNING,
3351  (errmsg("autovacuum not started because of misconfiguration"),
3352  errhint("Enable the \"track_counts\" option.")));
3353 }
bool autovacuum_start_daemon
Definition: autovacuum.c:117
int errhint(const char *fmt,...)
Definition: elog.c:1322
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define WARNING
Definition: elog.h:36
#define ereport(elevel,...)
Definition: elog.h:149
bool pgstat_track_counts
Definition: pgstat.c:187

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

Referenced by PostmasterMain().

◆ autovac_recalculate_workers_for_balance()

static void autovac_recalculate_workers_for_balance ( void  )
static

Definition at line 1871 of file autovacuum.c.

1872 {
1873  dlist_iter iter;
1874  int orig_nworkers_for_balance;
1875  int nworkers_for_balance = 0;
1876 
1877  Assert(LWLockHeldByMe(AutovacuumLock));
1878 
1879  orig_nworkers_for_balance =
1881 
1883  {
1884  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1885 
1886  if (worker->wi_proc == NULL ||
1888  continue;
1889 
1890  nworkers_for_balance++;
1891  }
1892 
1893  if (nworkers_for_balance != orig_nworkers_for_balance)
1895  nworkers_for_balance);
1896 }
static bool pg_atomic_unlocked_test_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:193
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:253
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:236
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:304
#define dlist_foreach(iter, lhead)
Definition: ilist.h:623
#define dlist_container(type, membername, ptr)
Definition: ilist.h:593
Assert(fmt[strlen(fmt) - 1] !='\n')
bool LWLockHeldByMe(LWLock *lock)
Definition: lwlock.c:1893
pg_atomic_uint32 av_nworkersForBalance
Definition: autovacuum.c:301
dlist_head av_runningWorkers
Definition: autovacuum.c:298
PGPROC * wi_proc
Definition: autovacuum.c:237
pg_atomic_flag wi_dobalance
Definition: autovacuum.c:239
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 AutoVacLauncherMain(), and do_autovacuum().

◆ autovac_report_activity()

static void autovac_report_activity ( autovac_table tab)
static

Definition at line 3218 of file autovacuum.c.

3219 {
3220 #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3221  char activity[MAX_AUTOVAC_ACTIV_LEN];
3222  int len;
3223 
3224  /* Report the command and possible options */
3225  if (tab->at_params.options & VACOPT_VACUUM)
3226  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3227  "autovacuum: VACUUM%s",
3228  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3229  else
3230  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3231  "autovacuum: ANALYZE");
3232 
3233  /*
3234  * Report the qualified name of the relation.
3235  */
3236  len = strlen(activity);
3237 
3238  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3239  " %s.%s%s", tab->at_nspname, tab->at_relname,
3240  tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3241 
3242  /* Set statement_timestamp() to current time for pg_stat_activity */
3244 
3246 }
#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:218
bool is_wraparound
Definition: vacuum.h:225
char * at_nspname
Definition: autovacuum.c:210
char * at_relname
Definition: autovacuum.c:209
VacuumParams at_params
Definition: autovacuum.c:204
#define VACOPT_VACUUM
Definition: vacuum.h:179
#define VACOPT_ANALYZE
Definition: vacuum.h:180
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:899

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

Referenced by autovacuum_do_vac_analyze().

◆ autovac_report_workitem()

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

Definition at line 3253 of file autovacuum.c.

3255 {
3256  char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3257  char blk[12 + 2];
3258  int len;
3259 
3260  switch (workitem->avw_type)
3261  {
3263  snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3264  "autovacuum: BRIN summarize");
3265  break;
3266  }
3267 
3268  /*
3269  * Report the qualified name of the relation, and the block number if any
3270  */
3271  len = strlen(activity);
3272 
3273  if (BlockNumberIsValid(workitem->avw_blockNumber))
3274  snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3275  else
3276  blk[0] = '\0';
3277 
3278  snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3279  " %s.%s%s", nspname, relname, blk);
3280 
3281  /* Set statement_timestamp() to current time for pg_stat_activity */
3283 
3285 }
@ 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:270
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:265

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

Referenced by perform_work_item().

◆ AutoVacLauncherMain()

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

Definition at line 435 of file autovacuum.c.

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

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

◆ AutoVacLauncherShutdown()

static void AutoVacLauncherShutdown ( void  )
static

Definition at line 328 of file autovacuum.c.

377 {
378  char *av[10];
379  int ac = 0;
380 
381  av[ac++] = "postgres";
382  av[ac++] = "--forkavlauncher";
383  av[ac++] = NULL; /* filled in by postmaster_forkexec */
384  av[ac] = NULL;
385 
386  Assert(ac < lengthof(av));
387 
388  return postmaster_forkexec(ac, av);
389 }
390 #endif
391 
392 /*
393  * Main entry point for autovacuum launcher process, to be called from the
394  * postmaster.
395  */
396 int
398 {
399  pid_t AutoVacPID;
400 
401 #ifdef EXEC_BACKEND
402  switch ((AutoVacPID = avlauncher_forkexec()))
403 #else
404  switch ((AutoVacPID = fork_process()))
405 #endif
406  {
407  case -1:
408  ereport(LOG,
409  (errmsg("could not fork autovacuum launcher process: %m")));
410  return 0;
411 
412 #ifndef EXEC_BACKEND
413  case 0:
414  /* in postmaster child ... */
416 
417  /* Close the postmaster's sockets */
418  ClosePostmasterPorts(false);
419 
420  AutoVacLauncherMain(0, NULL);
421  break;
422 #endif
423  default:
424  return (int) AutoVacPID;
425  }
426 
427  /* shouldn't get here */
428  return 0;
429 }
NON_EXEC_STATIC void AutoVacLauncherMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: autovacuum.c:435
int StartAutoVacLauncher(void)
#define lengthof(array)
Definition: c.h:777
#define LOG
Definition: elog.h:31
pid_t fork_process(void)
Definition: fork_process.c:32
void InitPostmasterChild(void)
Definition: miscinit.c:96
static pid_t AutoVacPID
Definition: postmaster.c:256
void ClosePostmasterPorts(bool am_syslogger)
Definition: postmaster.c:2502
struct @10::@11 av[32]

Referenced by AutoVacLauncherMain(), and HandleAutoVacLauncherInterrupts().

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3182 of file autovacuum.c.

3183 {
3184  RangeVar *rangevar;
3185  VacuumRelation *rel;
3186  List *rel_list;
3187  MemoryContext vac_context;
3188 
3189  /* Let pgstat know what we're doing */
3191 
3192  /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3193  rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3194  rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3195  rel_list = list_make1(rel);
3196 
3198  "Vacuum",
3200 
3201  vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3202 
3203  MemoryContextDelete(vac_context);
3204 }
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3218
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:817
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:425
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403
#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 3293 of file autovacuum.c.

3294 {
3296  return false;
3297  return true;
3298 }

References autovacuum_start_daemon, and pgstat_track_counts.

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

◆ AutoVacuumRequestWork()

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

Definition at line 3305 of file autovacuum.c.

3307 {
3308  int i;
3309  bool result = false;
3310 
3311  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3312 
3313  /*
3314  * Locate an unused work item and fill it with the given data.
3315  */
3316  for (i = 0; i < NUM_WORKITEMS; i++)
3317  {
3319 
3320  if (workitem->avw_used)
3321  continue;
3322 
3323  workitem->avw_used = true;
3324  workitem->avw_active = false;
3325  workitem->avw_type = type;
3326  workitem->avw_database = MyDatabaseId;
3327  workitem->avw_relation = relationId;
3328  workitem->avw_blockNumber = blkno;
3329  result = true;
3330 
3331  /* done */
3332  break;
3333  }
3334 
3335  LWLockRelease(AutovacuumLock);
3336 
3337  return result;
3338 }
#define NUM_WORKITEMS
Definition: autovacuum.c:273
Oid MyDatabaseId
Definition: globals.c:90
int i
Definition: isn.c:73
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:300
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 3397 of file autovacuum.c.

3398 {
3399  bool found;
3400 
3402  ShmemInitStruct("AutoVacuum Data",
3404  &found);
3405 
3406  if (!IsUnderPostmaster)
3407  {
3408  WorkerInfo worker;
3409  int i;
3410 
3411  Assert(!found);
3412 
3417  memset(AutoVacuumShmem->av_workItems, 0,
3418  sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3419 
3420  worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3421  MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3422 
3423  /* initialize the WorkerInfo free list */
3424  for (i = 0; i < autovacuum_max_workers; i++)
3425  {
3427  &worker[i].wi_links);
3428  pg_atomic_init_flag(&worker[i].wi_dobalance);
3429  }
3430 
3432 
3433  }
3434  else
3435  Assert(found);
3436 }
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:218
static void pg_atomic_init_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:167
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3378
int autovacuum_max_workers
Definition: autovacuum.c:118
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:243
#define MAXALIGN(LEN)
Definition: c.h:800
bool IsUnderPostmaster
Definition: globals.c:116
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:388

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

3379 {
3380  Size size;
3381 
3382  /*
3383  * Need the fixed struct and the array of WorkerInfoData.
3384  */
3385  size = sizeof(AutoVacuumShmemStruct);
3386  size = MAXALIGN(size);
3388  sizeof(WorkerInfoData)));
3389  return size;
3390 }
size_t Size
Definition: c.h:594
Size add_size(Size s1, Size s2)
Definition: shmem.c:494
Size mul_size(Size s1, Size s2)
Definition: shmem.c:511

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

Referenced by AutoVacuumShmemInit(), and CalculateShmemSize().

◆ AutoVacuumUpdateCostLimit()

void AutoVacuumUpdateCostLimit ( void  )

Definition at line 1825 of file autovacuum.c.

1826 {
1827  if (!MyWorkerInfo)
1828  return;
1829 
1830  /*
1831  * note: in cost_limit, zero also means use value from elsewhere, because
1832  * zero is not a valid value.
1833  */
1834 
1837  else
1838  {
1839  int nworkers_for_balance;
1840 
1841  if (autovacuum_vac_cost_limit > 0)
1843  else
1845 
1846  /* Only balance limit if no cost-related storage parameters specified */
1848  return;
1849 
1851 
1852  nworkers_for_balance = pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1853 
1854  /* There is at least 1 autovac worker (this worker) */
1855  if (nworkers_for_balance <= 0)
1856  elog(ERROR, "nworkers_for_balance must be > 0");
1857 
1858  vacuum_cost_limit = Max(vacuum_cost_limit / nworkers_for_balance, 1);
1859  }
1860 }
int autovacuum_vac_cost_limit
Definition: autovacuum.c:131
static int av_storage_param_cost_limit
Definition: autovacuum.c:153
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:314
#define Max(x, y)
Definition: c.h:987
#define ERROR
Definition: elog.h:39
int VacuumCostLimit
Definition: globals.c:151
int vacuum_cost_limit
Definition: vacuum.c:83

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

1405 {
1407 }

References AutoVacForkFailed, AutoVacuumShmem, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

◆ AutoVacWorkerMain()

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

Definition at line 1489 of file autovacuum.c.

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

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

Referenced by StartAutoVacWorker().

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1411 of file autovacuum.c.

1412 {
1413  got_SIGUSR2 = true;
1414  SetLatch(MyLatch);
1415 }
void SetLatch(Latch *latch)
Definition: latch.c:633

References got_SIGUSR2, MyLatch, and SetLatch().

Referenced by AutoVacLauncherMain().

◆ check_autovacuum_work_mem()

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

Definition at line 3442 of file autovacuum.c.

3443 {
3444  /*
3445  * -1 indicates fallback.
3446  *
3447  * If we haven't yet changed the boot_val default of -1, just let it be.
3448  * Autovacuum will look to maintenance_work_mem instead.
3449  */
3450  if (*newval == -1)
3451  return true;
3452 
3453  /*
3454  * We clamp manually-set values to at least 1MB. Since
3455  * maintenance_work_mem is always set to at least this value, do the same
3456  * here.
3457  */
3458  if (*newval < 1024)
3459  *newval = 1024;
3460 
3461  return true;
3462 }
#define newval

References newval.

◆ db_comparator()

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

Definition at line 1122 of file autovacuum.c.

1123 {
1124  return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1125  ((const avl_dbase *) b)->adl_score);
1126 }
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 1996 of file autovacuum.c.

1997 {
1998  Relation classRel;
1999  HeapTuple tuple;
2000  TableScanDesc relScan;
2001  Form_pg_database dbForm;
2002  List *table_oids = NIL;
2003  List *orphan_oids = NIL;
2004  HASHCTL ctl;
2005  HTAB *table_toast_map;
2006  ListCell *volatile cell;
2007  BufferAccessStrategy bstrategy;
2008  ScanKeyData key;
2009  TupleDesc pg_class_desc;
2010  int effective_multixact_freeze_max_age;
2011  bool did_vacuum = false;
2012  bool found_concurrent_worker = false;
2013  int i;
2014 
2015  /*
2016  * StartTransactionCommand and CommitTransactionCommand will automatically
2017  * switch to other contexts. We need this one to keep the list of
2018  * relations to vacuum/analyze across transactions.
2019  */
2021  "Autovacuum worker",
2024 
2025  /* Start a transaction so our commands have one to play into. */
2027 
2028  /*
2029  * Compute the multixact age for which freezing is urgent. This is
2030  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
2031  * short of multixact member space.
2032  */
2033  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
2034 
2035  /*
2036  * Find the pg_database entry and select the default freeze ages. We use
2037  * zero in template and nonconnectable databases, else the system-wide
2038  * default.
2039  */
2040  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
2041  if (!HeapTupleIsValid(tuple))
2042  elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
2043  dbForm = (Form_pg_database) GETSTRUCT(tuple);
2044 
2045  if (dbForm->datistemplate || !dbForm->datallowconn)
2046  {
2051  }
2052  else
2053  {
2058  }
2059 
2060  ReleaseSysCache(tuple);
2061 
2062  /* StartTransactionCommand changed elsewhere */
2064 
2065  classRel = table_open(RelationRelationId, AccessShareLock);
2066 
2067  /* create a copy so we can use it after closing pg_class */
2068  pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
2069 
2070  /* create hash table for toast <-> main relid mapping */
2071  ctl.keysize = sizeof(Oid);
2072  ctl.entrysize = sizeof(av_relation);
2073 
2074  table_toast_map = hash_create("TOAST to main relid map",
2075  100,
2076  &ctl,
2077  HASH_ELEM | HASH_BLOBS);
2078 
2079  /*
2080  * Scan pg_class to determine which tables to vacuum.
2081  *
2082  * We do this in two passes: on the first one we collect the list of plain
2083  * relations and materialized views, and on the second one we collect
2084  * TOAST tables. The reason for doing the second pass is that during it we
2085  * want to use the main relation's pg_class.reloptions entry if the TOAST
2086  * table does not have any, and we cannot obtain it unless we know
2087  * beforehand what's the main table OID.
2088  *
2089  * We need to check TOAST tables separately because in cases with short,
2090  * wide tables there might be proportionally much more activity in the
2091  * TOAST table than in its parent.
2092  */
2093  relScan = table_beginscan_catalog(classRel, 0, NULL);
2094 
2095  /*
2096  * On the first pass, we collect main tables to vacuum, and also the main
2097  * table relid to TOAST relid mapping.
2098  */
2099  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2100  {
2101  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2102  PgStat_StatTabEntry *tabentry;
2103  AutoVacOpts *relopts;
2104  Oid relid;
2105  bool dovacuum;
2106  bool doanalyze;
2107  bool wraparound;
2108 
2109  if (classForm->relkind != RELKIND_RELATION &&
2110  classForm->relkind != RELKIND_MATVIEW)
2111  continue;
2112 
2113  relid = classForm->oid;
2114 
2115  /*
2116  * Check if it is a temp table (presumably, of some other backend's).
2117  * We cannot safely process other backends' temp tables.
2118  */
2119  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2120  {
2121  /*
2122  * We just ignore it if the owning backend is still active and
2123  * using the temporary schema. Also, for safety, ignore it if the
2124  * namespace doesn't exist or isn't a temp namespace after all.
2125  */
2126  if (checkTempNamespaceStatus(classForm->relnamespace) == TEMP_NAMESPACE_IDLE)
2127  {
2128  /*
2129  * The table seems to be orphaned -- although it might be that
2130  * the owning backend has already deleted it and exited; our
2131  * pg_class scan snapshot is not necessarily up-to-date
2132  * anymore, so we could be looking at a committed-dead entry.
2133  * Remember it so we can try to delete it later.
2134  */
2135  orphan_oids = lappend_oid(orphan_oids, relid);
2136  }
2137  continue;
2138  }
2139 
2140  /* Fetch reloptions and the pgstat entry for this table */
2141  relopts = extract_autovac_opts(tuple, pg_class_desc);
2142  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2143  relid);
2144 
2145  /* Check if it needs vacuum or analyze */
2146  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2147  effective_multixact_freeze_max_age,
2148  &dovacuum, &doanalyze, &wraparound);
2149 
2150  /* Relations that need work are added to table_oids */
2151  if (dovacuum || doanalyze)
2152  table_oids = lappend_oid(table_oids, relid);
2153 
2154  /*
2155  * Remember TOAST associations for the second pass. Note: we must do
2156  * this whether or not the table is going to be vacuumed, because we
2157  * don't automatically vacuum toast tables along the parent table.
2158  */
2159  if (OidIsValid(classForm->reltoastrelid))
2160  {
2161  av_relation *hentry;
2162  bool found;
2163 
2164  hentry = hash_search(table_toast_map,
2165  &classForm->reltoastrelid,
2166  HASH_ENTER, &found);
2167 
2168  if (!found)
2169  {
2170  /* hash_search already filled in the key */
2171  hentry->ar_relid = relid;
2172  hentry->ar_hasrelopts = false;
2173  if (relopts != NULL)
2174  {
2175  hentry->ar_hasrelopts = true;
2176  memcpy(&hentry->ar_reloptions, relopts,
2177  sizeof(AutoVacOpts));
2178  }
2179  }
2180  }
2181  }
2182 
2183  table_endscan(relScan);
2184 
2185  /* second pass: check TOAST tables */
2186  ScanKeyInit(&key,
2187  Anum_pg_class_relkind,
2188  BTEqualStrategyNumber, F_CHAREQ,
2189  CharGetDatum(RELKIND_TOASTVALUE));
2190 
2191  relScan = table_beginscan_catalog(classRel, 1, &key);
2192  while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2193  {
2194  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2195  PgStat_StatTabEntry *tabentry;
2196  Oid relid;
2197  AutoVacOpts *relopts = NULL;
2198  bool dovacuum;
2199  bool doanalyze;
2200  bool wraparound;
2201 
2202  /*
2203  * We cannot safely process other backends' temp tables, so skip 'em.
2204  */
2205  if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2206  continue;
2207 
2208  relid = classForm->oid;
2209 
2210  /*
2211  * fetch reloptions -- if this toast table does not have them, try the
2212  * main rel
2213  */
2214  relopts = extract_autovac_opts(tuple, pg_class_desc);
2215  if (relopts == NULL)
2216  {
2217  av_relation *hentry;
2218  bool found;
2219 
2220  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2221  if (found && hentry->ar_hasrelopts)
2222  relopts = &hentry->ar_reloptions;
2223  }
2224 
2225  /* Fetch the pgstat entry for this table */
2226  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2227  relid);
2228 
2229  relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2230  effective_multixact_freeze_max_age,
2231  &dovacuum, &doanalyze, &wraparound);
2232 
2233  /* ignore analyze for toast tables */
2234  if (dovacuum)
2235  table_oids = lappend_oid(table_oids, relid);
2236  }
2237 
2238  table_endscan(relScan);
2239  table_close(classRel, AccessShareLock);
2240 
2241  /*
2242  * Recheck orphan temporary tables, and if they still seem orphaned, drop
2243  * them. We'll eat a transaction per dropped table, which might seem
2244  * excessive, but we should only need to do anything as a result of a
2245  * previous backend crash, so this should not happen often enough to
2246  * justify "optimizing". Using separate transactions ensures that we
2247  * don't bloat the lock table if there are many temp tables to be dropped,
2248  * and it ensures that we don't lose work if a deletion attempt fails.
2249  */
2250  foreach(cell, orphan_oids)
2251  {
2252  Oid relid = lfirst_oid(cell);
2253  Form_pg_class classForm;
2254  ObjectAddress object;
2255 
2256  /*
2257  * Check for user-requested abort.
2258  */
2260 
2261  /*
2262  * Try to lock the table. If we can't get the lock immediately,
2263  * somebody else is using (or dropping) the table, so it's not our
2264  * concern anymore. Having the lock prevents race conditions below.
2265  */
2267  continue;
2268 
2269  /*
2270  * Re-fetch the pg_class tuple and re-check whether it still seems to
2271  * be an orphaned temp table. If it's not there or no longer the same
2272  * relation, ignore it.
2273  */
2274  tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2275  if (!HeapTupleIsValid(tuple))
2276  {
2277  /* be sure to drop useless lock so we don't bloat lock table */
2279  continue;
2280  }
2281  classForm = (Form_pg_class) GETSTRUCT(tuple);
2282 
2283  /*
2284  * Make all the same tests made in the loop above. In event of OID
2285  * counter wraparound, the pg_class entry we have now might be
2286  * completely unrelated to the one we saw before.
2287  */
2288  if (!((classForm->relkind == RELKIND_RELATION ||
2289  classForm->relkind == RELKIND_MATVIEW) &&
2290  classForm->relpersistence == RELPERSISTENCE_TEMP))
2291  {
2293  continue;
2294  }
2295 
2296  if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE)
2297  {
2299  continue;
2300  }
2301 
2302  /* OK, let's delete it */
2303  ereport(LOG,
2304  (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2306  get_namespace_name(classForm->relnamespace),
2307  NameStr(classForm->relname))));
2308 
2309  object.classId = RelationRelationId;
2310  object.objectId = relid;
2311  object.objectSubId = 0;
2312  performDeletion(&object, DROP_CASCADE,
2316 
2317  /*
2318  * To commit the deletion, end current transaction and start a new
2319  * one. Note this also releases the lock we took.
2320  */
2323 
2324  /* StartTransactionCommand changed current memory context */
2326  }
2327 
2328  /*
2329  * Optionally, create a buffer access strategy object for VACUUM to use.
2330  * We use the same BufferAccessStrategy object for all tables VACUUMed by
2331  * this worker to prevent autovacuum from blowing out shared buffers.
2332  *
2333  * VacuumBufferUsageLimit being set to 0 results in
2334  * GetAccessStrategyWithSize returning NULL, effectively meaning we can
2335  * use up to all of shared buffers.
2336  *
2337  * If we later enter failsafe mode on any of the tables being vacuumed, we
2338  * will cease use of the BufferAccessStrategy only for that table.
2339  *
2340  * XXX should we consider adding code to adjust the size of this if
2341  * VacuumBufferUsageLimit changes?
2342  */
2344 
2345  /*
2346  * create a memory context to act as fake PortalContext, so that the
2347  * contexts created in the vacuum code are cleaned up for each table.
2348  */
2350  "Autovacuum Portal",
2352 
2353  /*
2354  * Perform operations on collected tables.
2355  */
2356  foreach(cell, table_oids)
2357  {
2358  Oid relid = lfirst_oid(cell);
2359  HeapTuple classTup;
2360  autovac_table *tab;
2361  bool isshared;
2362  bool skipit;
2363  dlist_iter iter;
2364 
2366 
2367  /*
2368  * Check for config changes before processing each collected table.
2369  */
2370  if (ConfigReloadPending)
2371  {
2372  ConfigReloadPending = false;
2374 
2375  /*
2376  * You might be tempted to bail out if we see autovacuum is now
2377  * disabled. Must resist that temptation -- this might be a
2378  * for-wraparound emergency worker, in which case that would be
2379  * entirely inappropriate.
2380  */
2381  }
2382 
2383  /*
2384  * Find out whether the table is shared or not. (It's slightly
2385  * annoying to fetch the syscache entry just for this, but in typical
2386  * cases it adds little cost because table_recheck_autovac would
2387  * refetch the entry anyway. We could buy that back by copying the
2388  * tuple here and passing it to table_recheck_autovac, but that
2389  * increases the odds of that function working with stale data.)
2390  */
2391  classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2392  if (!HeapTupleIsValid(classTup))
2393  continue; /* somebody deleted the rel, forget it */
2394  isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared;
2395  ReleaseSysCache(classTup);
2396 
2397  /*
2398  * Hold schedule lock from here until we've claimed the table. We
2399  * also need the AutovacuumLock to walk the worker array, but that one
2400  * can just be a shared lock.
2401  */
2402  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2403  LWLockAcquire(AutovacuumLock, LW_SHARED);
2404 
2405  /*
2406  * Check whether the table is being vacuumed concurrently by another
2407  * worker.
2408  */
2409  skipit = false;
2411  {
2412  WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2413 
2414  /* ignore myself */
2415  if (worker == MyWorkerInfo)
2416  continue;
2417 
2418  /* ignore workers in other databases (unless table is shared) */
2419  if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2420  continue;
2421 
2422  if (worker->wi_tableoid == relid)
2423  {
2424  skipit = true;
2425  found_concurrent_worker = true;
2426  break;
2427  }
2428  }
2429  LWLockRelease(AutovacuumLock);
2430  if (skipit)
2431  {
2432  LWLockRelease(AutovacuumScheduleLock);
2433  continue;
2434  }
2435 
2436  /*
2437  * Store the table's OID in shared memory before releasing the
2438  * schedule lock, so that other workers don't try to vacuum it
2439  * concurrently. (We claim it here so as not to hold
2440  * AutovacuumScheduleLock while rechecking the stats.)
2441  */
2442  MyWorkerInfo->wi_tableoid = relid;
2443  MyWorkerInfo->wi_sharedrel = isshared;
2444  LWLockRelease(AutovacuumScheduleLock);
2445 
2446  /*
2447  * Check whether pgstat data still says we need to vacuum this table.
2448  * It could have changed if something else processed the table while
2449  * we weren't looking. This doesn't entirely close the race condition,
2450  * but it is very small.
2451  */
2453  tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
2454  effective_multixact_freeze_max_age);
2455  if (tab == NULL)
2456  {
2457  /* someone else vacuumed the table, or it went away */
2458  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2460  MyWorkerInfo->wi_sharedrel = false;
2461  LWLockRelease(AutovacuumScheduleLock);
2462  continue;
2463  }
2464 
2465  /*
2466  * Save the cost-related storage parameter values in global variables
2467  * for reference when updating vacuum_cost_delay and vacuum_cost_limit
2468  * during vacuuming this table.
2469  */
2472 
2473  /*
2474  * We only expect this worker to ever set the flag, so don't bother
2475  * checking the return value. We shouldn't have to retry.
2476  */
2477  if (tab->at_dobalance)
2479  else
2481 
2482  LWLockAcquire(AutovacuumLock, LW_SHARED);
2484  LWLockRelease(AutovacuumLock);
2485 
2486  /*
2487  * We wait until this point to update cost delay and cost limit
2488  * values, even though we reloaded the configuration file above, so
2489  * that we can take into account the cost-related storage parameters.
2490  */
2492 
2493 
2494  /* clean up memory before each iteration */
2496 
2497  /*
2498  * Save the relation name for a possible error message, to avoid a
2499  * catalog lookup in case of an error. If any of these return NULL,
2500  * then the relation has been dropped since last we checked; skip it.
2501  * Note: they must live in a long-lived memory context because we call
2502  * vacuum and analyze in different transactions.
2503  */
2504 
2505  tab->at_relname = get_rel_name(tab->at_relid);
2508  if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2509  goto deleted;
2510 
2511  /*
2512  * We will abort vacuuming the current table if something errors out,
2513  * and continue with the next one in schedule; in particular, this
2514  * happens if we are interrupted with SIGINT.
2515  */
2516  PG_TRY();
2517  {
2518  /* Use PortalContext for any per-table allocations */
2520 
2521  /* have at it */
2522  autovacuum_do_vac_analyze(tab, bstrategy);
2523 
2524  /*
2525  * Clear a possible query-cancel signal, to avoid a late reaction
2526  * to an automatically-sent signal because of vacuuming the
2527  * current table (we're done with it, so it would make no sense to
2528  * cancel at this point.)
2529  */
2530  QueryCancelPending = false;
2531  }
2532  PG_CATCH();
2533  {
2534  /*
2535  * Abort the transaction, start a new one, and proceed with the
2536  * next table in our list.
2537  */
2538  HOLD_INTERRUPTS();
2539  if (tab->at_params.options & VACOPT_VACUUM)
2540  errcontext("automatic vacuum of table \"%s.%s.%s\"",
2541  tab->at_datname, tab->at_nspname, tab->at_relname);
2542  else
2543  errcontext("automatic analyze of table \"%s.%s.%s\"",
2544  tab->at_datname, tab->at_nspname, tab->at_relname);
2545  EmitErrorReport();
2546 
2547  /* this resets ProcGlobal->statusFlags[i] too */
2549  FlushErrorState();
2551 
2552  /* restart our transaction for the following operations */
2555  }
2556  PG_END_TRY();
2557 
2558  /* Make sure we're back in AutovacMemCxt */
2560 
2561  did_vacuum = true;
2562 
2563  /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2564 
2565  /* be tidy */
2566 deleted:
2567  if (tab->at_datname != NULL)
2568  pfree(tab->at_datname);
2569  if (tab->at_nspname != NULL)
2570  pfree(tab->at_nspname);
2571  if (tab->at_relname != NULL)
2572  pfree(tab->at_relname);
2573  pfree(tab);
2574 
2575  /*
2576  * Remove my info from shared memory. We set wi_dobalance on the
2577  * assumption that we are more likely than not to vacuum a table with
2578  * no cost-related storage parameters next, so we want to claim our
2579  * share of I/O as soon as possible to avoid thrashing the global
2580  * balance.
2581  */
2582  LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2584  MyWorkerInfo->wi_sharedrel = false;
2585  LWLockRelease(AutovacuumScheduleLock);
2587  }
2588 
2589  /*
2590  * Perform additional work items, as requested by backends.
2591  */
2592  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2593  for (i = 0; i < NUM_WORKITEMS; i++)
2594  {
2596 
2597  if (!workitem->avw_used)
2598  continue;
2599  if (workitem->avw_active)
2600  continue;
2601  if (workitem->avw_database != MyDatabaseId)
2602  continue;
2603 
2604  /* claim this one, and release lock while performing it */
2605  workitem->avw_active = true;
2606  LWLockRelease(AutovacuumLock);
2607 
2608  perform_work_item(workitem);
2609 
2610  /*
2611  * Check for config changes before acquiring lock for further jobs.
2612  */
2614  if (ConfigReloadPending)
2615  {
2616  ConfigReloadPending = false;
2619  }
2620 
2621  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2622 
2623  /* and mark it done */
2624  workitem->avw_active = false;
2625  workitem->avw_used = false;
2626  }
2627  LWLockRelease(AutovacuumLock);
2628 
2629  /*
2630  * We leak table_toast_map here (among other things), but since we're
2631  * going away soon, it's not a problem.
2632  */
2633 
2634  /*
2635  * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2636  * only need to do this once, not after each table.
2637  *
2638  * Even if we didn't vacuum anything, it may still be important to do
2639  * this, because one indirect effect of vac_update_datfrozenxid() is to
2640  * update TransamVariables->xidVacLimit. That might need to be done even
2641  * if we haven't vacuumed anything, because relations with older
2642  * relfrozenxid values or other databases with older datfrozenxid values
2643  * might have been dropped, allowing xidVacLimit to advance.
2644  *
2645  * However, it's also important not to do this blindly in all cases,
2646  * because when autovacuum=off this will restart the autovacuum launcher.
2647  * If we're not careful, an infinite loop can result, where workers find
2648  * no work to do and restart the launcher, which starts another worker in
2649  * the same database that finds no work to do. To prevent that, we skip
2650  * this if (1) we found no work to do and (2) we skipped at least one
2651  * table due to concurrent autovacuum activity. In that case, the other
2652  * worker has already done it, or will do so when it finishes.
2653  */
2654  if (did_vacuum || !found_concurrent_worker)
2656 
2657  /* Finally close out the last transaction. */
2659 }
static void pg_atomic_clear_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:204
static bool pg_atomic_test_set_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:180
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:3009
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:2809
void VacuumUpdateCosts(void)
Definition: autovacuum.c:1756
static int default_multixact_freeze_table_age
Definition: autovacuum.c:166
struct av_relation av_relation
static int default_multixact_freeze_min_age
Definition: autovacuum.c:165
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
Definition: autovacuum.c:2779
static double av_storage_param_cost_delay
Definition: autovacuum.c:152
static void perform_work_item(AutoVacuumWorkItem *workitem)
Definition: autovacuum.c:2665
static int default_freeze_min_age
Definition: autovacuum.c:163
static int default_freeze_table_age
Definition: autovacuum.c:164
static void autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
Definition: autovacuum.c:3182
@ BAS_VACUUM
Definition: bufmgr.h:38
#define NameStr(name)
Definition: c.h:735
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3089
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition: dependency.c:329
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition: dependency.h:140
#define PERFORM_DELETION_QUIETLY
Definition: dependency.h:138
#define PERFORM_DELETION_INTERNAL
Definition: dependency.h:136
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
#define errcontext
Definition: elog.h:196
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_CATCH(...)
Definition: elog.h:380
BufferAccessStrategy GetAccessStrategyWithSize(BufferAccessStrategyType btype, int ring_size_kb)
Definition: freelist.c:584
int VacuumBufferUsageLimit
Definition: globals.c:146
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1086
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:152
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:228
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3321
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1929
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1905
void pfree(void *pointer)
Definition: mcxt.c:1431
MemoryContext PortalContext
Definition: mcxt.c:150
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2832
TempNamespaceStatus checkTempNamespaceStatus(Oid namespaceId)
Definition: namespace.c:3714
@ TEMP_NAMESPACE_IDLE
Definition: namespace.h:47
@ DROP_CASCADE
Definition: parsenodes.h:2170
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
#define RelationGetDescr(relation)
Definition: rel.h:530
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
@ ForwardScanDirection
Definition: sdir.h:28
#define BTEqualStrategyNumber
Definition: stratnum.h:31
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
Definition: dynahash.c:220
bool at_dobalance
Definition: autovacuum.c:207
double at_storage_param_vac_cost_delay
Definition: autovacuum.c:205
int at_storage_param_vac_cost_limit
Definition: autovacuum.c:206
char * at_datname
Definition: autovacuum.c:211
bool ar_hasrelopts
Definition: autovacuum.c:195
AutoVacOpts ar_reloptions
Definition: autovacuum.c:196
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:267
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:219
#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:1009
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:133
int vacuum_freeze_min_age
Definition: vacuum.c:69
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:72
int vacuum_freeze_table_age
Definition: vacuum.c:70
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:71
void vac_update_datfrozenxid(void)
Definition: vacuum.c:1568
void StartTransactionCommand(void)
Definition: xact.c:2953
void CommitTransactionCommand(void)
Definition: xact.c:3050
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4728

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(), ConditionalLockRelationOid(), ConfigReloadPending, CreateTupleDescCopy(), 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(), HASHCTL::entrysize, ereport, errcontext, errmsg(), ERROR, extract_autovac_opts(), FlushErrorState(), ForwardScanDirection, get_database_name(), get_namespace_name(), get_rel_name(), get_rel_namespace(), GetAccessStrategyWithSize(), GETSTRUCT, HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, HASH_FIND, hash_search(), heap_getnext(), HeapTupleIsValid, HOLD_INTERRUPTS, i, InvalidOid, sort-test::key, HASHCTL::keysize, 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 1140 of file autovacuum.c.

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

◆ extract_autovac_opts()

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

Definition at line 2779 of file autovacuum.c.

2780 {
2781  bytea *relopts;
2782  AutoVacOpts *av;
2783 
2784  Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2785  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2786  ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2787 
2788  relopts = extractRelOptions(tup, pg_class_desc, NULL);
2789  if (relopts == NULL)
2790  return NULL;
2791 
2792  av = palloc(sizeof(AutoVacOpts));
2793  memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2794  pfree(relopts);
2795 
2796  return av;
2797 }
void * palloc(Size size)
Definition: mcxt.c:1201
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
Definition: reloptions.c:1381
Definition: c.h:676

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

1709 {
1710  if (MyWorkerInfo != NULL)
1711  {
1712  LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1713 
1714  /*
1715  * Wake the launcher up so that he can launch a new worker immediately
1716  * if required. We only save the launcher's PID in local memory here;
1717  * the actual signal will be sent when the PGPROC is recycled. Note
1718  * that we always do this, so that the launcher can rebalance the cost
1719  * limit setting of the remaining workers.
1720  *
1721  * We somewhat ignore the risk that the launcher changes its PID
1722  * between us reading it and the actual kill; we expect ProcKill to be
1723  * called shortly after us, and we assume that PIDs are not reused too
1724  * quickly after a process exits.
1725  */
1727 
1731  MyWorkerInfo->wi_sharedrel = false;
1732  MyWorkerInfo->wi_proc = NULL;
1737  /* not mine anymore */
1738  MyWorkerInfo = NULL;
1739 
1740  /*
1741  * now that we're inactive, cause a rebalancing of the surviving
1742  * workers
1743  */
1745  LWLockRelease(AutovacuumLock);
1746  }
1747 }
int AutovacuumLauncherPid
Definition: autovacuum.c:317
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 1911 of file autovacuum.c.

1912 {
1913  List *dblist = NIL;
1914  Relation rel;
1915  TableScanDesc scan;
1916  HeapTuple tup;
1917  MemoryContext resultcxt;
1918 
1919  /* This is the context that we will allocate our output data in */
1920  resultcxt = CurrentMemoryContext;
1921 
1922  /*
1923  * Start a transaction so we can access pg_database, and get a snapshot.
1924  * We don't have a use for the snapshot itself, but we're interested in
1925  * the secondary effect that it sets RecentGlobalXmin. (This is critical
1926  * for anything that reads heap pages, because HOT may decide to prune
1927  * them even if the process doesn't attempt to modify any tuples.)
1928  *
1929  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
1930  * not pushed/active does not reliably prevent HOT pruning (->xmin could
1931  * e.g. be cleared when cache invalidations are processed).
1932  */
1934  (void) GetTransactionSnapshot();
1935 
1936  rel = table_open(DatabaseRelationId, AccessShareLock);
1937  scan = table_beginscan_catalog(rel, 0, NULL);
1938 
1939  while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1940  {
1941  Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1942  avw_dbase *avdb;
1943  MemoryContext oldcxt;
1944 
1945  /*
1946  * If database has partially been dropped, we can't, nor need to,
1947  * vacuum it.
1948  */
1949  if (database_is_invalid_form(pgdatabase))
1950  {
1951  elog(DEBUG2,
1952  "autovacuum: skipping invalid database \"%s\"",
1953  NameStr(pgdatabase->datname));
1954  continue;
1955  }
1956 
1957  /*
1958  * Allocate our results in the caller's context, not the
1959  * transaction's. We do this inside the loop, and restore the original
1960  * context at the end, so that leaky things like heap_getnext() are
1961  * not called in a potentially long-lived context.
1962  */
1963  oldcxt = MemoryContextSwitchTo(resultcxt);
1964 
1965  avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1966 
1967  avdb->adw_datid = pgdatabase->oid;
1968  avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1969  avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1970  avdb->adw_minmulti = pgdatabase->datminmxid;
1971  /* this gets set later: */
1972  avdb->adw_entry = NULL;
1973 
1974  dblist = lappend(dblist, avdb);
1975  MemoryContextSwitchTo(oldcxt);
1976  }
1977 
1978  table_endscan(scan);
1980 
1982 
1983  /* Be sure to restore caller's memory context */
1984  MemoryContextSwitchTo(resultcxt);
1985 
1986  return dblist;
1987 }
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3113
#define DEBUG2
Definition: elog.h:29
List * lappend(List *list, void *datum)
Definition: list.c:339
char * pstrdup(const char *in)
Definition: mcxt.c:1619
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:223
char * adw_name
Definition: autovacuum.c:184

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

808 {
809  /* the normal shutdown case */
812 
814  {
815  ConfigReloadPending = false;
817 
818  /* shutdown requested in config file? */
819  if (!AutoVacuumingActive())
821 
822  /* rebuild the list in case the naptime changed */
824  }
825 
826  /* Process barrier events */
829 
830  /* Perform logging of memory contexts of this process */
833 
834  /* Process sinval catchup interrupts that happened while sleeping */
836 }
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:39
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:38
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1174
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:468
void ProcessCatchupInterrupt(void)
Definition: sinval.c:176

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

Referenced by AutoVacLauncherMain().

◆ IsAutoVacuumLauncherProcess()

bool IsAutoVacuumLauncherProcess ( void  )

Definition at line 3361 of file autovacuum.c.

3362 {
3363  return am_autovacuum_launcher;
3364 }

References am_autovacuum_launcher.

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

◆ IsAutoVacuumWorkerProcess()

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1352 of file autovacuum.c.

1353 {
1354  Oid dbid;
1355  dlist_iter iter;
1356 
1357  dbid = do_start_worker();
1358  if (OidIsValid(dbid))
1359  {
1360  bool found = false;
1361 
1362  /*
1363  * Walk the database list and update the corresponding entry. If the
1364  * database is not on the list, we'll recreate the list.
1365  */
1366  dlist_foreach(iter, &DatabaseList)
1367  {
1368  avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1369 
1370  if (avdb->adl_datid == dbid)
1371  {
1372  found = true;
1373 
1374  /*
1375  * add autovacuum_naptime seconds to the current time, and use
1376  * that as the new "next_worker" field for this database.
1377  */
1378  avdb->adl_next_worker =
1380 
1382  break;
1383  }
1384  }
1385 
1386  /*
1387  * If the database was not present in the database list, we rebuild
1388  * the list. It's possible that the database does not get into the
1389  * list anyway, for example if it's a database that doesn't have a
1390  * pgstat entry, but this is not a problem because we don't want to
1391  * schedule workers regularly into those in any case.
1392  */
1393  if (!found)
1394  rebuild_database_list(dbid);
1395  }
1396 }
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.

Referenced by AutoVacLauncherMain().

◆ launcher_determine_sleep()

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

Definition at line 859 of file autovacuum.c.

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

Referenced by AutoVacLauncherMain().

◆ perform_work_item()

static void perform_work_item ( AutoVacuumWorkItem workitem)
static

Definition at line 2665 of file autovacuum.c.

2666 {
2667  char *cur_datname = NULL;
2668  char *cur_nspname = NULL;
2669  char *cur_relname = NULL;
2670 
2671  /*
2672  * Note we do not store table info in MyWorkerInfo, since this is not
2673  * vacuuming proper.
2674  */
2675 
2676  /*
2677  * Save the relation name for a possible error message, to avoid a catalog
2678  * lookup in case of an error. If any of these return NULL, then the
2679  * relation has been dropped since last we checked; skip it.
2680  */
2682 
2683  cur_relname = get_rel_name(workitem->avw_relation);
2684  cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2685  cur_datname = get_database_name(MyDatabaseId);
2686  if (!cur_relname || !cur_nspname || !cur_datname)
2687  goto deleted2;
2688 
2689  autovac_report_workitem(workitem, cur_nspname, cur_relname);
2690 
2691  /* clean up memory before each work item */
2693 
2694  /*
2695  * We will abort the current work item if something errors out, and
2696  * continue with the next one; in particular, this happens if we are
2697  * interrupted with SIGINT. Note that this means that the work item list
2698  * can be lossy.
2699  */
2700  PG_TRY();
2701  {
2702  /* Use PortalContext for any per-work-item allocations */
2704 
2705  /*
2706  * Have at it. Functions called here are responsible for any required
2707  * user switch and sandbox.
2708  */
2709  switch (workitem->avw_type)
2710  {
2713  ObjectIdGetDatum(workitem->avw_relation),
2714  Int64GetDatum((int64) workitem->avw_blockNumber));
2715  break;
2716  default:
2717  elog(WARNING, "unrecognized work item found: type %d",
2718  workitem->avw_type);
2719  break;
2720  }
2721 
2722  /*
2723  * Clear a possible query-cancel signal, to avoid a late reaction to
2724  * an automatically-sent signal because of vacuuming the current table
2725  * (we're done with it, so it would make no sense to cancel at this
2726  * point.)
2727  */
2728  QueryCancelPending = false;
2729  }
2730  PG_CATCH();
2731  {
2732  /*
2733  * Abort the transaction, start a new one, and proceed with the next
2734  * table in our list.
2735  */
2736  HOLD_INTERRUPTS();
2737  errcontext("processing work entry for relation \"%s.%s.%s\"",
2738  cur_datname, cur_nspname, cur_relname);
2739  EmitErrorReport();
2740 
2741  /* this resets ProcGlobal->statusFlags[i] too */
2743  FlushErrorState();
2745 
2746  /* restart our transaction for the following operations */
2749  }
2750  PG_END_TRY();
2751 
2752  /* Make sure we're back in AutovacMemCxt */
2754 
2755  /* We intentionally do not set did_vacuum here */
2756 
2757  /* be tidy */
2758 deleted2:
2759  if (cur_datname)
2760  pfree(cur_datname);
2761  if (cur_nspname)
2762  pfree(cur_nspname);
2763  if (cur_relname)
2764  pfree(cur_relname);
2765 }
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
Definition: autovacuum.c:3253
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition: brin.c:1366
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 943 of file autovacuum.c.

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

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

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

◆ recheck_relation_needs_vacanalyze()

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

Definition at line 2948 of file autovacuum.c.

2955 {
2956  PgStat_StatTabEntry *tabentry;
2957 
2958  /* fetch the pgstat table entry */
2959  tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2960  relid);
2961 
2962  relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2963  effective_multixact_freeze_max_age,
2964  dovacuum, doanalyze, wraparound);
2965 
2966  /* ignore ANALYZE for toast tables */
2967  if (classForm->relkind == RELKIND_TOASTVALUE)
2968  *doanalyze = false;
2969 }

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

3018 {
3019  bool force_vacuum;
3020  bool av_enabled;
3021  float4 reltuples; /* pg_class.reltuples */
3022 
3023  /* constants from reloptions or GUC variables */
3024  int vac_base_thresh,
3025  vac_ins_base_thresh,
3026  anl_base_thresh;
3027  float4 vac_scale_factor,
3028  vac_ins_scale_factor,
3029  anl_scale_factor;
3030 
3031  /* thresholds calculated from above constants */
3032  float4 vacthresh,
3033  vacinsthresh,
3034  anlthresh;
3035 
3036  /* number of vacuum (resp. analyze) tuples at this time */
3037  float4 vactuples,
3038  instuples,
3039  anltuples;
3040 
3041  /* freeze parameters */
3042  int freeze_max_age;
3043  int multixact_freeze_max_age;
3044  TransactionId xidForceLimit;
3045  MultiXactId multiForceLimit;
3046 
3047  Assert(classForm != NULL);
3048  Assert(OidIsValid(relid));
3049 
3050  /*
3051  * Determine vacuum/analyze equation parameters. We have two possible
3052  * sources: the passed reloptions (which could be a main table or a toast
3053  * table), or the autovacuum GUC variables.
3054  */
3055 
3056  /* -1 in autovac setting means use plain vacuum_scale_factor */
3057  vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3058  ? relopts->vacuum_scale_factor
3060 
3061  vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3062  ? relopts->vacuum_threshold
3064 
3065  vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3066  ? relopts->vacuum_ins_scale_factor
3068 
3069  /* -1 is used to disable insert vacuums */
3070  vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3071  ? relopts->vacuum_ins_threshold
3073 
3074  anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3075  ? relopts->analyze_scale_factor
3077 
3078  anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3079  ? relopts->analyze_threshold
3081 
3082  freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3085 
3086  multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3087  ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3088  : effective_multixact_freeze_max_age;
3089 
3090  av_enabled = (relopts ? relopts->enabled : true);
3091 
3092  /* Force vacuum if table is at risk of wraparound */
3093  xidForceLimit = recentXid - freeze_max_age;
3094  if (xidForceLimit < FirstNormalTransactionId)
3095  xidForceLimit -= FirstNormalTransactionId;
3096  force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
3097  TransactionIdPrecedes(classForm->relfrozenxid,
3098  xidForceLimit));
3099  if (!force_vacuum)
3100  {
3101  multiForceLimit = recentMulti - multixact_freeze_max_age;
3102  if (multiForceLimit < FirstMultiXactId)
3103  multiForceLimit -= FirstMultiXactId;
3104  force_vacuum = MultiXactIdIsValid(classForm->relminmxid) &&
3105  MultiXactIdPrecedes(classForm->relminmxid, multiForceLimit);
3106  }
3107  *wraparound = force_vacuum;
3108 
3109  /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3110  if (!av_enabled && !force_vacuum)
3111  {
3112  *doanalyze = false;
3113  *dovacuum = false;
3114  return;
3115  }
3116 
3117  /*
3118  * If we found stats for the table, and autovacuum is currently enabled,
3119  * make a threshold-based decision whether to vacuum and/or analyze. If
3120  * autovacuum is currently disabled, we must be here for anti-wraparound
3121  * vacuuming only, so don't vacuum (or analyze) anything that's not being
3122  * forced.
3123  */
3124  if (PointerIsValid(tabentry) && AutoVacuumingActive())
3125  {
3126  reltuples = classForm->reltuples;
3127  vactuples = tabentry->dead_tuples;
3128  instuples = tabentry->ins_since_vacuum;
3129  anltuples = tabentry->mod_since_analyze;
3130 
3131  /* If the table hasn't yet been vacuumed, take reltuples as zero */
3132  if (reltuples < 0)
3133  reltuples = 0;
3134 
3135  vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3136  vacinsthresh = (float4) vac_ins_base_thresh + vac_ins_scale_factor * reltuples;
3137  anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3138 
3139  /*
3140  * Note that we don't need to take special consideration for stat
3141  * reset, because if that happens, the last vacuum and analyze counts
3142  * will be reset too.
3143  */
3144  if (vac_ins_base_thresh >= 0)
3145  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3146  NameStr(classForm->relname),
3147  vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3148  else
3149  elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3150  NameStr(classForm->relname),
3151  vactuples, vacthresh, anltuples, anlthresh);
3152 
3153  /* Determine if this table needs vacuum or analyze. */
3154  *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3155  (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3156  *doanalyze = (anltuples > anlthresh);
3157  }
3158  else
3159  {
3160  /*
3161  * Skip a table not found in stat hash, unless we have to force vacuum
3162  * for anti-wrap purposes. If it's not acted upon, there's no need to
3163  * vacuum it.
3164  */
3165  *dovacuum = force_vacuum;
3166  *doanalyze = false;
3167  }
3168 
3169  /* ANALYZE refuses to work with pg_statistic */
3170  if (relid == StatisticRelationId)
3171  *doanalyze = false;
3172 }
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:752
float float4
Definition: c.h:618
#define DEBUG3
Definition: elog.h:28
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
int vacuum_ins_threshold
Definition: rel.h:311
int multixact_freeze_max_age
Definition: rel.h:318
float8 vacuum_scale_factor
Definition: rel.h:322
int analyze_threshold
Definition: rel.h:312
float8 vacuum_ins_scale_factor
Definition: rel.h:323
bool enabled
Definition: rel.h:309
int freeze_max_age
Definition: rel.h:315
int vacuum_threshold
Definition: rel.h:310
float8 analyze_scale_factor
Definition: rel.h:324
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().

◆ StartAutoVacWorker()

int StartAutoVacWorker ( void  )

Definition at line 1451 of file autovacuum.c.

1452 {
1453  pid_t worker_pid;
1454 
1455 #ifdef EXEC_BACKEND
1456  switch ((worker_pid = avworker_forkexec()))
1457 #else
1458  switch ((worker_pid = fork_process()))
1459 #endif
1460  {
1461  case -1:
1462  ereport(LOG,
1463  (errmsg("could not fork autovacuum worker process: %m")));
1464  return 0;
1465 
1466 #ifndef EXEC_BACKEND
1467  case 0:
1468  /* in postmaster child ... */
1470 
1471  /* Close the postmaster's sockets */
1472  ClosePostmasterPorts(false);
1473 
1474  AutoVacWorkerMain(0, NULL);
1475  break;
1476 #endif
1477  default:
1478  return (int) worker_pid;
1479  }
1480 
1481  /* shouldn't get here */
1482  return 0;
1483 }
NON_EXEC_STATIC void AutoVacWorkerMain(int argc, char *argv[]) pg_attribute_noreturn()
Definition: autovacuum.c:1489

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

Referenced by StartAutovacuumWorker().

◆ table_recheck_autovac()

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

Definition at line 2809 of file autovacuum.c.

2812 {
2813  Form_pg_class classForm;
2814  HeapTuple classTup;
2815  bool dovacuum;
2816  bool doanalyze;
2817  autovac_table *tab = NULL;
2818  bool wraparound;
2819  AutoVacOpts *avopts;
2820 
2821  /* fetch the relation's relcache entry */
2822  classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2823  if (!HeapTupleIsValid(classTup))
2824  return NULL;
2825  classForm = (Form_pg_class) GETSTRUCT(classTup);
2826 
2827  /*
2828  * Get the applicable reloptions. If it is a TOAST table, try to get the
2829  * main table reloptions if the toast table itself doesn't have.
2830  */
2831  avopts = extract_autovac_opts(classTup, pg_class_desc);
2832  if (classForm->relkind == RELKIND_TOASTVALUE &&
2833  avopts == NULL && table_toast_map != NULL)
2834  {
2835  av_relation *hentry;
2836  bool found;
2837 
2838  hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2839  if (found && hentry->ar_hasrelopts)
2840  avopts = &hentry->ar_reloptions;
2841  }
2842 
2843  recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2844  effective_multixact_freeze_max_age,
2845  &dovacuum, &doanalyze, &wraparound);
2846 
2847  /* OK, it needs something done */
2848  if (doanalyze || dovacuum)
2849  {
2850  int freeze_min_age;
2851  int freeze_table_age;
2852  int multixact_freeze_min_age;
2853  int multixact_freeze_table_age;
2854  int log_min_duration;
2855 
2856  /*
2857  * Calculate the vacuum cost parameters and the freeze ages. If there
2858  * are options set in pg_class.reloptions, use them; in the case of a
2859  * toast table, try the main table too. Otherwise use the GUC
2860  * defaults, autovacuum's own first and plain vacuum second.
2861  */
2862 
2863  /* -1 in autovac setting means use log_autovacuum_min_duration */
2864  log_min_duration = (avopts && avopts->log_min_duration >= 0)
2865  ? avopts->log_min_duration
2867 
2868  /* these do not have autovacuum-specific settings */
2869  freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2870  ? avopts->freeze_min_age
2872 
2873  freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2874  ? avopts->freeze_table_age
2876 
2877  multixact_freeze_min_age = (avopts &&
2878  avopts->multixact_freeze_min_age >= 0)
2879  ? avopts->multixact_freeze_min_age
2881 
2882  multixact_freeze_table_age = (avopts &&
2883  avopts->multixact_freeze_table_age >= 0)
2884  ? avopts->multixact_freeze_table_age
2886 
2887  tab = palloc(sizeof(autovac_table));
2888  tab->at_relid = relid;
2889  tab->at_sharedrel = classForm->relisshared;
2890 
2891  /*
2892  * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2893  * that vacuum() skips toast relations. Also note we tell vacuum() to
2894  * skip vac_update_datfrozenxid(); we'll do that separately.
2895  */
2896  tab->at_params.options =
2897  (dovacuum ? (VACOPT_VACUUM |
2900  (doanalyze ? VACOPT_ANALYZE : 0) |
2901  (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2902 
2903  /*
2904  * index_cleanup and truncate are unspecified at first in autovacuum.
2905  * They will be filled in with usable values using their reloptions
2906  * (or reloption defaults) later.
2907  */
2910  /* As of now, we don't support parallel vacuum for autovacuum */
2911  tab->at_params.nworkers = -1;
2912  tab->at_params.freeze_min_age = freeze_min_age;
2913  tab->at_params.freeze_table_age = freeze_table_age;
2914  tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2915  tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2916  tab->at_params.is_wraparound = wraparound;
2917  tab->at_params.log_min_duration = log_min_duration;
2918  tab->at_storage_param_vac_cost_limit = avopts ?
2919  avopts->vacuum_cost_limit : 0;
2920  tab->at_storage_param_vac_cost_delay = avopts ?
2921  avopts->vacuum_cost_delay : -1;
2922  tab->at_relname = NULL;
2923  tab->at_nspname = NULL;
2924  tab->at_datname = NULL;
2925 
2926  /*
2927  * If any of the cost delay parameters has been set individually for
2928  * this table, disable the balancing algorithm.
2929  */
2930  tab->at_dobalance =
2931  !(avopts && (avopts->vacuum_cost_limit > 0 ||
2932  avopts->vacuum_cost_delay >= 0));
2933  }
2934 
2935  heap_freetuple(classTup);
2936  return tab;
2937 }
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:2948
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
int log_min_duration
Definition: rel.h:320
float8 vacuum_cost_delay
Definition: rel.h:321
int vacuum_cost_limit
Definition: rel.h:313
int multixact_freeze_table_age
Definition: rel.h:319
int freeze_min_age
Definition: rel.h:314
int freeze_table_age
Definition: rel.h:316
int multixact_freeze_min_age
Definition: rel.h:317
int nworkers
Definition: vacuum.h:237
int freeze_table_age
Definition: vacuum.h:220
VacOptValue truncate
Definition: vacuum.h:230
int freeze_min_age
Definition: vacuum.h:219
int multixact_freeze_min_age
Definition: vacuum.h:221
int multixact_freeze_table_age
Definition: vacuum.h:223
int log_min_duration
Definition: vacuum.h:226
VacOptValue index_cleanup
Definition: vacuum.h:229
bool at_sharedrel
Definition: autovacuum.c:208
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:184
#define VACOPT_SKIP_DATABASE_STATS
Definition: vacuum.h:188
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:201
#define VACOPT_PROCESS_MAIN
Definition: vacuum.h:185

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

1757 {
1758  if (MyWorkerInfo)
1759  {
1760  if (av_storage_param_cost_delay >= 0)
1762  else if (autovacuum_vac_cost_delay >= 0)
1764  else
1765  /* fall back to VacuumCostDelay */
1767 
1769  }
1770  else
1771  {
1772  /* Must be explicit VACUUM or ANALYZE */
1775  }
1776 
1777  /*
1778  * If configuration changes are allowed to impact VacuumCostActive, make
1779  * sure it is updated.
1780  */
1783  else if (vacuum_cost_delay > 0)
1784  VacuumCostActive = true;
1785  else
1786  {
1787  VacuumCostActive = false;
1788  VacuumCostBalance = 0;
1789  }
1790 
1791  /*
1792  * Since the cost logging requires a lock, avoid rendering the log message
1793  * in case we are using a message level where the log wouldn't be emitted.
1794  */
1796  {
1797  Oid dboid,
1798  tableoid;
1799 
1800  Assert(!LWLockHeldByMe(AutovacuumLock));
1801 
1802  LWLockAcquire(AutovacuumLock, LW_SHARED);
1803  dboid = MyWorkerInfo->wi_dboid;
1804  tableoid = MyWorkerInfo->wi_tableoid;
1805  LWLockRelease(AutovacuumLock);
1806 
1807  elog(DEBUG2,
1808  "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1809  dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1811  vacuum_cost_delay > 0 ? "yes" : "no",
1812  VacuumFailsafeActive ? "yes" : "no");
1813  }
1814 }
double autovacuum_vac_cost_delay
Definition: autovacuum.c:130
void AutoVacuumUpdateCostLimit(void)
Definition: autovacuum.c:1825
bool message_level_is_interesting(int elevel)
Definition: elog.c:277
bool VacuumCostActive
Definition: globals.c:159
int VacuumCostBalance
Definition: globals.c:158
double VacuumCostDelay
Definition: globals.c:152
double vacuum_cost_delay
Definition: vacuum.c:82
bool VacuumFailsafeActive
Definition: vacuum.c:98

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

◆ am_autovacuum_launcher

bool am_autovacuum_launcher = false
static

Definition at line 140 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and IsAutoVacuumLauncherProcess().

◆ am_autovacuum_worker

bool am_autovacuum_worker = false
static

Definition at line 141 of file autovacuum.c.

Referenced by AutoVacWorkerMain(), and IsAutoVacuumWorkerProcess().

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

◆ 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

◆ 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_max_items(), and ginInsertCleanup().

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

Definition at line 317 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 152 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 153 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 311 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and rebuild_database_list().

◆ default_freeze_min_age

int default_freeze_min_age
static

Definition at line 163 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 164 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 165 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 166 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 156 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and 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 160 of file autovacuum.c.

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

◆ recentXid

TransactionId recentXid
static

Definition at line 159 of file autovacuum.c.

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