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

Go to the source code of this file.

Data Structures

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

Macros

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */
 
#define MAX_AUTOVAC_SLEEPTIME   300 /* seconds */
 
#define AutoVacNumSignals   (AutoVacRebalance + 1)
 
#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 }
 

Functions

static Oid do_start_worker (void)
 
static void ProcessAutoVacLauncherInterrupts (void)
 
static pg_noreturn void AutoVacLauncherShutdown (void)
 
static void launcher_determine_sleep (bool canlaunch, bool recursing, struct timeval *nap)
 
static void launch_worker (TimestampTz now)
 
static Listget_database_list (void)
 
static void rebuild_database_list (Oid newdb)
 
static int db_comparator (const void *a, const void *b)
 
static void autovac_recalculate_workers_for_balance (void)
 
static void do_autovacuum (void)
 
static void FreeWorkerInfo (int code, Datum arg)
 
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 AutoVacOptsextract_autovac_opts (HeapTuple tup, TupleDesc pg_class_desc)
 
static void perform_work_item (AutoVacuumWorkItem *workitem)
 
static void autovac_report_activity (autovac_table *tab)
 
static void autovac_report_workitem (AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
 
static void avl_sigusr2_handler (SIGNAL_ARGS)
 
static bool av_worker_available (void)
 
static void check_av_worker_gucs (void)
 
void AutoVacLauncherMain (const void *startup_data, size_t startup_data_len)
 
void AutoVacWorkerFailed (void)
 
void AutoVacWorkerMain (const void *startup_data, size_t startup_data_len)
 
void VacuumUpdateCosts (void)
 
void AutoVacuumUpdateCostLimit (void)
 
bool AutoVacuumingActive (void)
 
bool AutoVacuumRequestWork (AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
 
void autovac_init (void)
 
Size AutoVacuumShmemSize (void)
 
void AutoVacuumShmemInit (void)
 
bool check_autovacuum_work_mem (int *newval, void **extra, GucSource source)
 

Variables

bool autovacuum_start_daemon = false
 
int autovacuum_worker_slots
 
int autovacuum_max_workers
 
int autovacuum_work_mem = -1
 
int autovacuum_naptime
 
int autovacuum_vac_thresh
 
int autovacuum_vac_max_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
 
int Log_autoanalyze_min_duration = 600000
 
static double av_storage_param_cost_delay = -1
 
static int av_storage_param_cost_limit = -1
 
static volatile sig_atomic_t got_SIGUSR2 = false
 
static TransactionId recentXid
 
static MultiXactId recentMulti
 
static int default_freeze_min_age
 
static int default_freeze_table_age
 
static int default_multixact_freeze_min_age
 
static int default_multixact_freeze_table_age
 
static MemoryContext AutovacMemCxt
 
static AutoVacuumShmemStructAutoVacuumShmem
 
static dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
 
static MemoryContext DatabaseListCxt = NULL
 
static WorkerInfo MyWorkerInfo = NULL
 

Macro Definition Documentation

◆ AutoVacNumSignals

#define AutoVacNumSignals   (AutoVacRebalance + 1)

Definition at line 255 of file autovacuum.c.

◆ MAX_AUTOVAC_ACTIV_LEN

#define MAX_AUTOVAC_ACTIV_LEN   (NAMEDATALEN * 2 + 56)

◆ MAX_AUTOVAC_SLEEPTIME

#define MAX_AUTOVAC_SLEEPTIME   300 /* seconds */

Definition at line 140 of file autovacuum.c.

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 139 of file autovacuum.c.

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

Definition at line 273 of file autovacuum.c.

Typedef Documentation

◆ autovac_table

◆ AutoVacuumWorkItem

◆ av_relation

◆ avl_dbase

◆ avw_dbase

◆ WorkerInfo

Definition at line 242 of file autovacuum.c.

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 

Definition at line 249 of file autovacuum.c.

250{
251 AutoVacForkFailed, /* failed trying to start a worker */
252 AutoVacRebalance, /* rebalance the cost limits */
AutoVacuumSignal
Definition autovacuum.c:250
@ AutoVacRebalance
Definition autovacuum.c:252
@ AutoVacForkFailed
Definition autovacuum.c:251

Function Documentation

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3344 of file autovacuum.c.

3345{
3347 return;
3348 else if (!pgstat_track_counts)
3350 (errmsg("autovacuum not started because of misconfiguration"),
3351 errhint("Enable the \"track_counts\" option.")));
3352 else
3354}
static void check_av_worker_gucs(void)
bool autovacuum_start_daemon
Definition autovacuum.c:117
int errhint(const char *fmt,...)
Definition elog.c:1330
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define WARNING
Definition elog.h:36
#define ereport(elevel,...)
Definition elog.h:150
bool pgstat_track_counts
Definition pgstat.c:203

References autovacuum_start_daemon, check_av_worker_gucs(), 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 1759 of file autovacuum.c.

1760{
1761 dlist_iter iter;
1763 int nworkers_for_balance = 0;
1764
1766
1769
1771 {
1772 WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1773
1774 if (worker->wi_proc == NULL ||
1776 continue;
1777
1779 }
1780
1784}
static bool pg_atomic_unlocked_test_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:194
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition atomics.h:274
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:237
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition autovacuum.c:304
#define Assert(condition)
Definition c.h:873
#define dlist_foreach(iter, lhead)
Definition ilist.h:623
#define dlist_container(type, membername, ptr)
Definition ilist.h:593
bool LWLockHeldByMe(LWLock *lock)
Definition lwlock.c:1911
static int fb(int x)
pg_atomic_uint32 av_nworkersForBalance
Definition autovacuum.c:301
dlist_head av_runningWorkers
Definition autovacuum.c:298
PGPROC * wi_proc
Definition autovacuum.c:236
pg_atomic_flag wi_dobalance
Definition autovacuum.c:238
dlist_node * cur
Definition ilist.h:179

References Assert, AutoVacuumShmem, AutoVacuumShmemStruct::av_nworkersForBalance, AutoVacuumShmemStruct::av_runningWorkers, dlist_iter::cur, dlist_container, dlist_foreach, fb(), 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 3215 of file autovacuum.c.

3216{
3217#define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3219 int len;
3220
3221 /* Report the command and possible options */
3222 if (tab->at_params.options & VACOPT_VACUUM)
3224 "autovacuum: VACUUM%s",
3225 tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3226 else
3228 "autovacuum: ANALYZE");
3229
3230 /*
3231 * Report the qualified name of the relation.
3232 */
3233 len = strlen(activity);
3234
3236 " %s.%s%s", tab->at_nspname, tab->at_relname,
3237 tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3238
3239 /* Set statement_timestamp() to current time for pg_stat_activity */
3241
3243}
#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:260
bits32 options
Definition vacuum.h:219
bool is_wraparound
Definition vacuum.h:226
char * at_nspname
Definition autovacuum.c:209
char * at_relname
Definition autovacuum.c:208
VacuumParams at_params
Definition autovacuum.c:203
#define VACOPT_VACUUM
Definition vacuum.h:180
#define VACOPT_ANALYZE
Definition vacuum.h:181
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:915

References autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relname, fb(), 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 3250 of file autovacuum.c.

3252{
3253 char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3254 char blk[12 + 2];
3255 int len;
3256
3257 switch (workitem->avw_type)
3258 {
3261 "autovacuum: BRIN summarize");
3262 break;
3263 }
3264
3265 /*
3266 * Report the qualified name of the relation, and the block number if any
3267 */
3268 len = strlen(activity);
3269
3270 if (BlockNumberIsValid(workitem->avw_blockNumber))
3271 snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3272 else
3273 blk[0] = '\0';
3274
3276 " %s.%s%s", nspname, relname, blk);
3277
3278 /* Set statement_timestamp() to current time for pg_stat_activity */
3280
3282}
@ AVW_BRINSummarizeRange
Definition autovacuum.h:25
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition block.h:71
NameData relname
Definition pg_class.h:38

References AVW_BRINSummarizeRange, BlockNumberIsValid(), fb(), len, MAX_AUTOVAC_ACTIV_LEN, pgstat_report_activity(), relname, SetCurrentStatementStartTimestamp(), snprintf, and STATE_RUNNING.

Referenced by perform_work_item().

◆ AutoVacLauncherMain()

void AutoVacLauncherMain ( const void startup_data,
size_t  startup_data_len 
)

Definition at line 375 of file autovacuum.c.

376{
378
380
381 /* Release postmaster's working memory context */
383 {
386 }
387
389
391 (errmsg_internal("autovacuum launcher started")));
392
393 if (PostAuthDelay)
394 pg_usleep(PostAuthDelay * 1000000L);
395
397
398 /*
399 * Set up signal handlers. We operate on databases much like a regular
400 * backend, so we use the same signal handling. See equivalent code in
401 * tcop/postgres.c.
402 */
406 /* SIGQUIT handler was already set up by InitPostmasterChild */
407
408 InitializeTimeouts(); /* establishes SIGALRM handler */
409
415
416 /*
417 * Create a per-backend PGPROC struct in shared memory. We must do this
418 * before we can use LWLocks or access any shared memory.
419 */
420 InitProcess();
421
422 /* Early initialization */
423 BaseInit();
424
426
428
429 /*
430 * Create a memory context that we will do all our work in. We do this so
431 * that we can reset the context during error recovery and thereby avoid
432 * possible memory leaks.
433 */
435 "Autovacuum Launcher",
438
439 /*
440 * If an exception is encountered, processing resumes here.
441 *
442 * This code is a stripped down version of PostgresMain error recovery.
443 *
444 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
445 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
446 * signals other than SIGQUIT will be blocked until we complete error
447 * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
448 * call redundant, but it is not since InterruptPending might be set
449 * already.
450 */
451 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
452 {
453 /* since not using PG_TRY, must reset error stack by hand */
455
456 /* Prevents interrupts while cleaning up */
458
459 /* Forget any pending QueryCancel or timeout request */
461 QueryCancelPending = false; /* second to avoid race condition */
462
463 /* Report the error to the server log */
465
466 /* Abort the current transaction in order to recover */
468
469 /*
470 * Release any other resources, for the case where we were not in a
471 * transaction.
472 */
477 /* this is probably dead code, but let's be safe: */
480 AtEOXact_Buffers(false);
482 AtEOXact_Files(false);
483 AtEOXact_HashTables(false);
484
485 /*
486 * Now return to normal top-level context and clear ErrorContext for
487 * next time.
488 */
491
492 /* Flush any leaked data in the top-level context */
494
495 /* don't leave dangling pointers to freed memory */
498
499 /* Now we can allow interrupts again */
501
502 /* if in shutdown mode, no need for anything further; just go away */
505
506 /*
507 * Sleep at least 1 second after any error. We don't want to be
508 * filling the error logs as fast as we can.
509 */
510 pg_usleep(1000000L);
511 }
512
513 /* We can now handle ereport(ERROR) */
515
516 /* must unblock signals before calling rebuild_database_list */
518
519 /*
520 * Set always-secure search path. Launcher doesn't connect to a database,
521 * so this has no effect.
522 */
523 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
524
525 /*
526 * Force zero_damaged_pages OFF in the autovac process, even if it is set
527 * in postgresql.conf. We don't really want such a dangerous option being
528 * applied non-interactively.
529 */
530 SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
531
532 /*
533 * Force settable timeouts off to avoid letting these settings prevent
534 * regular maintenance from being executed.
535 */
536 SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
537 SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
538 SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
539 SetConfigOption("idle_in_transaction_session_timeout", "0",
541
542 /*
543 * Force default_transaction_isolation to READ COMMITTED. We don't want
544 * to pay the overhead of serializable mode, nor add any risk of causing
545 * deadlocks or delaying other transactions.
546 */
547 SetConfigOption("default_transaction_isolation", "read committed",
549
550 /*
551 * Even when system is configured to use a different fetch consistency,
552 * for autovac we always want fresh stats.
553 */
554 SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
555
556 /*
557 * In emergency mode, just start a worker (unless shutdown was requested)
558 * and go away.
559 */
560 if (!AutoVacuumingActive())
561 {
564 proc_exit(0); /* done */
565 }
566
568
569 /*
570 * Create the initial database list. The invariant we want this list to
571 * keep is that it's ordered by decreasing next_worker. As soon as an
572 * entry is updated to a higher time, it will be moved to the front (which
573 * is correct because the only operation is to add autovacuum_naptime to
574 * the entry, and time always increases).
575 */
577
578 /* loop until shutdown request */
580 {
581 struct timeval nap;
583 bool can_launch;
584
585 /*
586 * This loop is a bit different from the normal use of WaitLatch,
587 * because we'd like to sleep before the first launch of a child
588 * process. So it's WaitLatch, then ResetLatch, then check for
589 * wakening conditions.
590 */
591
593
594 /*
595 * Wait until naptime expires or we get some type of signal (all the
596 * signal handlers will wake us by calling SetLatch).
597 */
600 (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
602
604
606
607 /*
608 * a worker finished, or postmaster signaled failure to start a worker
609 */
610 if (got_SIGUSR2)
611 {
612 got_SIGUSR2 = false;
613
614 /* rebalance cost limits, if needed */
616 {
621 }
622
624 {
625 /*
626 * If the postmaster failed to start a new worker, we sleep
627 * for a little while and resend the signal. The new worker's
628 * state is still in memory, so this is sufficient. After
629 * that, we restart the main loop.
630 *
631 * XXX should we put a limit to the number of times we retry?
632 * I don't think it makes much sense, because a future start
633 * of a worker will continue to fail in the same way.
634 */
636 pg_usleep(1000000L); /* 1s */
638 continue;
639 }
640 }
641
642 /*
643 * There are some conditions that we need to check before trying to
644 * start a worker. First, we need to make sure that there is a worker
645 * slot available. Second, we need to make sure that no other worker
646 * failed while starting up.
647 */
648
651
653
655 {
656 int waittime;
658
659 /*
660 * We can't launch another worker when another one is still
661 * starting up (or failed while doing so), so just sleep for a bit
662 * more; that worker will wake us up again as soon as it's ready.
663 * We will only wait autovacuum_naptime seconds (up to a maximum
664 * of 60 seconds) for this to happen however. Note that failure
665 * to connect to a particular database is not a problem here,
666 * because the worker removes itself from the startingWorker
667 * pointer before trying to connect. Problems detected by the
668 * postmaster (like fork() failure) are also reported and handled
669 * differently. The only problems that may cause this code to
670 * fire are errors in the earlier sections of AutoVacWorkerMain,
671 * before the worker removes the WorkerInfo from the
672 * startingWorker pointer.
673 */
674 waittime = Min(autovacuum_naptime, 60) * 1000;
676 waittime))
677 {
680
681 /*
682 * No other process can put a worker in starting mode, so if
683 * startingWorker is still INVALID after exchanging our lock,
684 * we assume it's the same one we saw above (so we don't
685 * recheck the launch time).
686 */
688 {
690 worker->wi_dboid = InvalidOid;
691 worker->wi_tableoid = InvalidOid;
692 worker->wi_sharedrel = false;
693 worker->wi_proc = NULL;
694 worker->wi_launchtime = 0;
696 &worker->wi_links);
699 errmsg("autovacuum worker took too long to start; canceled"));
700 }
701 }
702 else
703 can_launch = false;
704 }
705 LWLockRelease(AutovacuumLock); /* either shared or exclusive */
706
707 /* if we can't do anything, just go back to sleep */
708 if (!can_launch)
709 continue;
710
711 /* We're OK to start a new worker */
712
714 {
715 /*
716 * Special case when the list is empty: start a worker right away.
717 * This covers the initial case, when no database is in pgstats
718 * (thus the list is empty). Note that the constraints in
719 * launcher_determine_sleep keep us from starting workers too
720 * quickly (at most once every autovacuum_naptime when the list is
721 * empty).
722 */
724 }
725 else
726 {
727 /*
728 * because rebuild_database_list constructs a list with most
729 * distant adl_next_worker first, we obtain our database from the
730 * tail of the list.
731 */
733
735
736 /*
737 * launch a worker if next_worker is right now or it is in the
738 * past
739 */
740 if (TimestampDifferenceExceeds(avdb->adl_next_worker,
741 current_time, 0))
743 }
744 }
745
747}
void pgaio_error_cleanup(void)
Definition aio.c:1165
static Oid do_start_worker(void)
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition autovacuum.c:815
static volatile sig_atomic_t got_SIGUSR2
Definition autovacuum.c:155
static void avl_sigusr2_handler(SIGNAL_ARGS)
static bool av_worker_available(void)
int autovacuum_naptime
Definition autovacuum.c:121
bool AutoVacuumingActive(void)
static pg_noreturn void AutoVacLauncherShutdown(void)
Definition autovacuum.c:798
static void launch_worker(TimestampTz now)
static dlist_head DatabaseList
Definition autovacuum.c:310
static void rebuild_database_list(Oid newdb)
Definition autovacuum.c:899
static MemoryContext DatabaseListCxt
Definition autovacuum.c:311
static void autovac_recalculate_workers_for_balance(void)
static MemoryContext AutovacMemCxt
Definition autovacuum.c:168
static void ProcessAutoVacLauncherInterrupts(void)
Definition autovacuum.c:753
sigset_t UnBlockSig
Definition pqsignal.c:22
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition timestamp.c:1781
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1645
void AtEOXact_Buffers(bool isCommit)
Definition bufmgr.c:4103
void UnlockBuffers(void)
Definition bufmgr.c:5709
#define Min(x, y)
Definition c.h:997
int64 TimestampTz
Definition timestamp.h:39
void AtEOXact_HashTables(bool isCommit)
Definition dynahash.c:1931
int errmsg_internal(const char *fmt,...)
Definition elog.c:1170
void EmitErrorReport(void)
Definition elog.c:1704
ErrorContextCallback * error_context_stack
Definition elog.c:95
void FlushErrorState(void)
Definition elog.c:1884
sigjmp_buf * PG_exception_stack
Definition elog.c:97
#define DEBUG1
Definition elog.h:30
void AtEOXact_Files(bool isCommit)
Definition fd.c:3213
int MyProcPid
Definition globals.c:47
volatile sig_atomic_t QueryCancelPending
Definition globals.c:33
struct Latch * MyLatch
Definition globals.c:63
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4196
@ PGC_S_OVERRIDE
Definition guc.h:123
@ PGC_SUSET
Definition guc.h:78
static void dlist_init(dlist_head *head)
Definition ilist.h:314
#define dlist_tail_element(type, membername, lhead)
Definition ilist.h:612
static bool dlist_is_empty(const dlist_head *head)
Definition ilist.h:336
static void dclist_push_head(dclist_head *head, dlist_node *node)
Definition ilist.h:693
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition interrupt.c:104
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:105
void ResetLatch(Latch *latch)
Definition latch.c:374
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition latch.c:172
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1176
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1793
void LWLockReleaseAll(void)
Definition lwlock.c:1892
@ LW_SHARED
Definition lwlock.h:113
@ LW_EXCLUSIVE
Definition lwlock.h:112
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
MemoryContext TopMemoryContext
Definition mcxt.c:166
MemoryContext PostmasterContext
Definition mcxt.c:168
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h:136
@ NormalProcessing
Definition miscadmin.h:472
@ InitProcessing
Definition miscadmin.h:471
#define GetProcessingMode()
Definition miscadmin.h:481
#define HOLD_INTERRUPTS()
Definition miscadmin.h:134
#define SetProcessingMode(mode)
Definition miscadmin.h:483
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
void SendPostmasterSignal(PMSignalReason reason)
Definition pmsignal.c:165
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition pmsignal.h:40
#define pqsignal
Definition port.h:547
int PostAuthDelay
Definition postgres.c:100
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3058
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3041
#define InvalidOid
void BaseInit(void)
Definition postinit.c:607
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition postinit.c:710
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:677
void init_ps_display(const char *fixed_part)
Definition ps_status.c:285
void ReleaseAuxProcessResources(bool isCommit)
Definition resowner.c:1016
ResourceOwner AuxProcessResourceOwner
Definition resowner.c:176
void pg_usleep(long microsec)
Definition signal.c:53
void AtEOXact_SMgr(void)
Definition smgr.c:1017
void InitProcess(void)
Definition proc.c:395
dclist_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:237
dlist_node wi_links
Definition autovacuum.c:233
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:85
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET
#define SIGCHLD
Definition win32_port.h:168
#define SIGHUP
Definition win32_port.h:158
#define SIGPIPE
Definition win32_port.h:163
#define SIGUSR1
Definition win32_port.h:170
#define SIGUSR2
Definition win32_port.h:171
void AbortCurrentTransaction(void)
Definition xact.c:3472

References AbortCurrentTransaction(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, 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, av_worker_available(), avl_sigusr2_handler(), BaseInit(), DatabaseList, DatabaseListCxt, dclist_push_head(), DEBUG1, disable_all_timeouts(), dlist_init(), dlist_is_empty(), dlist_tail_element, do_start_worker(), EmitErrorReport(), ereport, errmsg(), errmsg_internal(), error_context_stack, fb(), FloatExceptionHandler(), FlushErrorState(), GetCurrentTimestamp(), GetProcessingMode, got_SIGUSR2, HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InvalidOid, launch_worker(), launcher_determine_sleep(), LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), LWLockReleaseAll(), MemoryContextDelete(), MemoryContextReset(), MemoryContextSwitchTo(), Min, MyLatch, MyProcPid, NormalProcessing, PG_exception_stack, pg_usleep(), pgaio_error_cleanup(), PGC_S_OVERRIDE, PGC_SUSET, pgstat_report_wait_end(), PMSIGNAL_START_AUTOVAC_WORKER, PostAuthDelay, PostmasterContext, pqsignal, proc_exit(), ProcessAutoVacLauncherInterrupts(), procsignal_sigusr1_handler(), QueryCancelPending, rebuild_database_list(), ReleaseAuxProcessResources(), ResetLatch(), RESUME_INTERRUPTS, SendPostmasterSignal(), SetConfigOption(), SetProcessingMode, ShutdownRequestPending, 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 798 of file autovacuum.c.

799{
801 (errmsg_internal("autovacuum launcher shutting down")));
803
804 proc_exit(0); /* done */
805}

References AutoVacuumShmem, AutoVacuumShmemStruct::av_launcherpid, DEBUG1, ereport, errmsg_internal(), and proc_exit().

Referenced by AutoVacLauncherMain(), and ProcessAutoVacLauncherInterrupts().

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3175 of file autovacuum.c.

3176{
3178 VacuumRelation *rel;
3179 List *rel_list;
3182
3183 /* Let pgstat know what we're doing */
3185
3186 /* Create a context that vacuum() can use as cross-transaction storage */
3188 "Vacuum",
3190
3191 /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3193 rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3195 rel_list = list_make1(rel);
3197
3198 vacuum(rel_list, tab->at_params, bstrategy, vac_context, true);
3199
3201}
static void autovac_report_activity(autovac_table *tab)
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition makefuncs.c:907
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition makefuncs.c:473
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
#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, const VacuumParams params, BufferAccessStrategy bstrategy, MemoryContext vac_context, bool isTopLevel)
Definition vacuum.c:494

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, fb(), list_make1, makeRangeVar(), makeVacuumRelation(), MemoryContextDelete(), MemoryContextSwitchTo(), NIL, and vacuum().

Referenced by do_autovacuum().

◆ AutoVacuumingActive()

bool AutoVacuumingActive ( void  )

◆ AutoVacuumRequestWork()

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

Definition at line 3302 of file autovacuum.c.

3304{
3305 int i;
3306 bool result = false;
3307
3309
3310 /*
3311 * Locate an unused work item and fill it with the given data.
3312 */
3313 for (i = 0; i < NUM_WORKITEMS; i++)
3314 {
3316
3317 if (workitem->avw_used)
3318 continue;
3319
3320 workitem->avw_used = true;
3321 workitem->avw_active = false;
3322 workitem->avw_type = type;
3323 workitem->avw_database = MyDatabaseId;
3324 workitem->avw_relation = relationId;
3325 workitem->avw_blockNumber = blkno;
3326 result = true;
3327
3328 /* done */
3329 break;
3330 }
3331
3333
3334 return result;
3335}
#define NUM_WORKITEMS
Definition autovacuum.c:273
Oid MyDatabaseId
Definition globals.c:94
int i
Definition isn.c:77
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition autovacuum.c:300
const char * type

References AutoVacuumShmem, AutoVacuumShmemStruct::av_workItems, AutoVacuumWorkItem::avw_used, fb(), i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyDatabaseId, NUM_WORKITEMS, and type.

Referenced by brininsert().

◆ AutoVacuumShmemInit()

void AutoVacuumShmemInit ( void  )

Definition at line 3380 of file autovacuum.c.

3381{
3382 bool found;
3383
3385 ShmemInitStruct("AutoVacuum Data",
3387 &found);
3388
3389 if (!IsUnderPostmaster)
3390 {
3391 WorkerInfo worker;
3392 int i;
3393
3394 Assert(!found);
3395
3402
3403 worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3405
3406 /* initialize the WorkerInfo free list */
3407 for (i = 0; i < autovacuum_worker_slots; i++)
3408 {
3410 &worker[i].wi_links);
3411 pg_atomic_init_flag(&worker[i].wi_dobalance);
3412 }
3413
3415
3416 }
3417 else
3418 Assert(found);
3419}
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition atomics.h:219
static void pg_atomic_init_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:168
int autovacuum_worker_slots
Definition autovacuum.c:118
Size AutoVacuumShmemSize(void)
struct WorkerInfoData * WorkerInfo
Definition autovacuum.c:242
#define MAXALIGN(LEN)
Definition c.h:826
bool IsUnderPostmaster
Definition globals.c:120
static void dclist_init(dclist_head *head)
Definition ilist.h:671
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:378

References Assert, autovacuum_worker_slots, AutoVacuumShmem, AutoVacuumShmemSize(), AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_nworkersForBalance, AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_startingWorker, AutoVacuumShmemStruct::av_workItems, dclist_init(), dclist_push_head(), dlist_init(), fb(), 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 3361 of file autovacuum.c.

3362{
3363 Size size;
3364
3365 /*
3366 * Need the fixed struct and the array of WorkerInfoData.
3367 */
3368 size = sizeof(AutoVacuumShmemStruct);
3369 size = MAXALIGN(size);
3371 sizeof(WorkerInfoData)));
3372 return size;
3373}
size_t Size
Definition c.h:619
Size add_size(Size s1, Size s2)
Definition shmem.c:482
Size mul_size(Size s1, Size s2)
Definition shmem.c:497

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

Referenced by AutoVacuumShmemInit(), and CalculateShmemSize().

◆ AutoVacuumUpdateCostLimit()

void AutoVacuumUpdateCostLimit ( void  )

Definition at line 1713 of file autovacuum.c.

1714{
1715 if (!MyWorkerInfo)
1716 return;
1717
1718 /*
1719 * note: in cost_limit, zero also means use value from elsewhere, because
1720 * zero is not a valid value.
1721 */
1722
1725 else
1726 {
1728
1731 else
1733
1734 /* Only balance limit if no cost-related storage parameters specified */
1736 return;
1737
1739
1741
1742 /* There is at least 1 autovac worker (this worker) */
1743 if (nworkers_for_balance <= 0)
1744 elog(ERROR, "nworkers_for_balance must be > 0");
1745
1747 }
1748}
int autovacuum_vac_cost_limit
Definition autovacuum.c:133
static int av_storage_param_cost_limit
Definition autovacuum.c:152
static WorkerInfo MyWorkerInfo
Definition autovacuum.c:324
#define Max(x, y)
Definition c.h:991
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
int VacuumCostLimit
Definition globals.c:154
int vacuum_cost_limit
Definition vacuum.c:92

References Assert, autovacuum_vac_cost_limit, AutoVacuumShmem, AutoVacuumShmemStruct::av_nworkersForBalance, av_storage_param_cost_limit, elog, ERROR, fb(), 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 1364 of file autovacuum.c.

1365{
1367}

References AutoVacForkFailed, AutoVacuumShmem, and AutoVacuumShmemStruct::av_signal.

Referenced by StartAutovacuumWorker().

◆ AutoVacWorkerMain()

void AutoVacWorkerMain ( const void startup_data,
size_t  startup_data_len 
)

Definition at line 1386 of file autovacuum.c.

1387{
1389 Oid dbid;
1390
1392
1393 /* Release postmaster's working memory context */
1395 {
1398 }
1399
1401
1403
1404 /*
1405 * Set up signal handlers. We operate on databases much like a regular
1406 * backend, so we use the same signal handling. See equivalent code in
1407 * tcop/postgres.c.
1408 */
1410
1411 /*
1412 * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1413 * means abort and exit cleanly, and SIGQUIT means abandon ship.
1414 */
1417 /* SIGQUIT handler was already set up by InitPostmasterChild */
1418
1419 InitializeTimeouts(); /* establishes SIGALRM handler */
1420
1426
1427 /*
1428 * Create a per-backend PGPROC struct in shared memory. We must do this
1429 * before we can use LWLocks or access any shared memory.
1430 */
1431 InitProcess();
1432
1433 /* Early initialization */
1434 BaseInit();
1435
1436 /*
1437 * If an exception is encountered, processing resumes here.
1438 *
1439 * Unlike most auxiliary processes, we don't attempt to continue
1440 * processing after an error; we just clean up and exit. The autovac
1441 * launcher is responsible for spawning another worker later.
1442 *
1443 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
1444 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
1445 * signals other than SIGQUIT will be blocked until we exit. It might
1446 * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
1447 * it is not since InterruptPending might be set already.
1448 */
1449 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1450 {
1451 /* since not using PG_TRY, must reset error stack by hand */
1453
1454 /* Prevents interrupts while cleaning up */
1456
1457 /* Report the error to the server log */
1459
1460 /*
1461 * We can now go away. Note that because we called InitProcess, a
1462 * callback was registered to do ProcKill, which will clean up
1463 * necessary state.
1464 */
1465 proc_exit(0);
1466 }
1467
1468 /* We can now handle ereport(ERROR) */
1470
1472
1473 /*
1474 * Set always-secure search path, so malicious users can't redirect user
1475 * code (e.g. pg_index.indexprs). (That code runs in a
1476 * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1477 * take control of the entire autovacuum worker in any case.)
1478 */
1479 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1480
1481 /*
1482 * Force zero_damaged_pages OFF in the autovac process, even if it is set
1483 * in postgresql.conf. We don't really want such a dangerous option being
1484 * applied non-interactively.
1485 */
1486 SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1487
1488 /*
1489 * Force settable timeouts off to avoid letting these settings prevent
1490 * regular maintenance from being executed.
1491 */
1492 SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1493 SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1494 SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1495 SetConfigOption("idle_in_transaction_session_timeout", "0",
1497
1498 /*
1499 * Force default_transaction_isolation to READ COMMITTED. We don't want
1500 * to pay the overhead of serializable mode, nor add any risk of causing
1501 * deadlocks or delaying other transactions.
1502 */
1503 SetConfigOption("default_transaction_isolation", "read committed",
1505
1506 /*
1507 * Force synchronous replication off to allow regular maintenance even if
1508 * we are waiting for standbys to connect. This is important to ensure we
1509 * aren't blocked from performing anti-wraparound tasks.
1510 */
1512 SetConfigOption("synchronous_commit", "local",
1514
1515 /*
1516 * Even when system is configured to use a different fetch consistency,
1517 * for autovac we always want fresh stats.
1518 */
1519 SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
1520
1521 /*
1522 * Get the info about the database we're going to work on.
1523 */
1525
1526 /*
1527 * beware of startingWorker being INVALID; this should normally not
1528 * happen, but if a worker fails after forking and before this, the
1529 * launcher might have decided to remove it from the queue and start
1530 * again.
1531 */
1533 {
1535 dbid = MyWorkerInfo->wi_dboid;
1537
1538 /* insert into the running list */
1541
1542 /*
1543 * remove from the "starting" pointer, so that the launcher can start
1544 * a new worker if required
1545 */
1548
1550
1551 /* wake up the launcher */
1554 }
1555 else
1556 {
1557 /* no worker entry for me, go away */
1558 elog(WARNING, "autovacuum worker started without a worker entry");
1559 dbid = InvalidOid;
1561 }
1562
1563 if (OidIsValid(dbid))
1564 {
1565 char dbname[NAMEDATALEN];
1566
1567 /*
1568 * Report autovac startup to the cumulative stats system. We
1569 * deliberately do this before InitPostgres, so that the
1570 * last_autovac_time will get updated even if the connection attempt
1571 * fails. This is to prevent autovac from getting "stuck" repeatedly
1572 * selecting an unopenable database, rather than making any progress
1573 * on stuff it can connect to.
1574 */
1576
1577 /*
1578 * Connect to the selected database, specifying no particular user,
1579 * and ignoring datallowconn. Collect the database's name for
1580 * display.
1581 *
1582 * Note: if we have selected a just-deleted database (due to using
1583 * stale stats info), we'll fail and exit here.
1584 */
1587 dbname);
1591 (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1592
1593 if (PostAuthDelay)
1594 pg_usleep(PostAuthDelay * 1000000L);
1595
1596 /* And do an appropriate amount of work */
1599 do_autovacuum();
1600 }
1601
1602 /* All done, go away */
1603 proc_exit(0);
1604}
static void FreeWorkerInfo(int code, Datum arg)
static TransactionId recentXid
Definition autovacuum.c:158
static void do_autovacuum(void)
static MultiXactId recentMulti
Definition autovacuum.c:159
#define OidIsValid(objectId)
Definition c.h:788
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition ilist.h:347
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:372
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition miscadmin.h:500
MultiXactId ReadNextMultiXactId(void)
Definition multixact.c:620
#define NAMEDATALEN
#define die(msg)
void pgstat_report_autovac(Oid dboid)
unsigned int Oid
static void set_ps_display(const char *activity)
Definition ps_status.h:40
PGPROC * MyProc
Definition proc.c:67
char * dbname
Definition streamutil.c:49
static TransactionId ReadNextTransactionId(void)
Definition transam.h:377
#define kill(pid, sig)
Definition win32_port.h:490
int synchronous_commit
Definition xact.c:88
@ SYNCHRONOUS_COMMIT_LOCAL_FLUSH
Definition xact.h:72

References Assert, AutoVacuumShmem, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_startingWorker, BaseInit(), dbname, DEBUG1, die, dlist_push_head(), do_autovacuum(), elog, EmitErrorReport(), ereport, errmsg_internal(), error_context_stack, fb(), FloatExceptionHandler(), FreeWorkerInfo(), GetProcessingMode, HOLD_INTERRUPTS, INIT_PG_OVERRIDE_ALLOW_CONNS, init_ps_display(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, InvalidOid, kill, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MemoryContextDelete(), MyProc, MyWorkerInfo, NAMEDATALEN, NormalProcessing, OidIsValid, on_shmem_exit(), PG_exception_stack, pg_usleep(), PGC_S_OVERRIDE, PGC_SUSET, pgstat_report_autovac(), PostAuthDelay, PostmasterContext, pqsignal, proc_exit(), procsignal_sigusr1_handler(), ReadNextMultiXactId(), ReadNextTransactionId(), recentMulti, recentXid, set_ps_display(), SetConfigOption(), SetProcessingMode, 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.

◆ av_worker_available()

static bool av_worker_available ( void  )
static

Definition at line 3451 of file autovacuum.c.

3452{
3453 int free_slots;
3454 int reserved_slots;
3455
3457
3460
3461 return free_slots > reserved_slots;
3462}
int autovacuum_max_workers
Definition autovacuum.c:119
static uint32 dclist_count(const dclist_head *head)
Definition ilist.h:932

References autovacuum_max_workers, autovacuum_worker_slots, AutoVacuumShmem, AutoVacuumShmemStruct::av_freeWorkers, dclist_count(), fb(), and Max.

Referenced by AutoVacLauncherMain(), and do_start_worker().

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1371 of file autovacuum.c.

1372{
1373 got_SIGUSR2 = true;
1375}
void SetLatch(Latch *latch)
Definition latch.c:290

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

3426{
3427 /*
3428 * -1 indicates fallback.
3429 *
3430 * If we haven't yet changed the boot_val default of -1, just let it be.
3431 * Autovacuum will look to maintenance_work_mem instead.
3432 */
3433 if (*newval == -1)
3434 return true;
3435
3436 /*
3437 * We clamp manually-set values to at least 64kB. Since
3438 * maintenance_work_mem is always set to at least this value, do the same
3439 * here.
3440 */
3441 if (*newval < 64)
3442 *newval = 64;
3443
3444 return true;
3445}
#define newval

References newval.

◆ check_av_worker_gucs()

static void check_av_worker_gucs ( void  )
static

Definition at line 3468 of file autovacuum.c.

3469{
3473 errmsg("\"autovacuum_max_workers\" (%d) should be less than or equal to \"autovacuum_worker_slots\" (%d)",
3475 errdetail("The server will only start up to \"autovacuum_worker_slots\" (%d) autovacuum workers at a given time.",
3477}
int errdetail(const char *fmt,...)
Definition elog.c:1216
int errcode(int sqlerrcode)
Definition elog.c:863

References autovacuum_max_workers, autovacuum_worker_slots, ereport, errcode(), errdetail(), errmsg(), fb(), and WARNING.

Referenced by autovac_init(), and ProcessAutoVacLauncherInterrupts().

◆ db_comparator()

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

Definition at line 1082 of file autovacuum.c.

1083{
1084 return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1085 ((const avl_dbase *) b)->adl_score);
1086}
static int pg_cmp_s32(int32 a, int32 b)
Definition int.h:713
int b
Definition isn.c:74
int a
Definition isn.c:73

References a, b, and pg_cmp_s32().

Referenced by rebuild_database_list().

◆ do_autovacuum()

static void do_autovacuum ( void  )
static

Definition at line 1875 of file autovacuum.c.

1876{
1878 HeapTuple tuple;
1881 List *table_oids = NIL;
1882 List *orphan_oids = NIL;
1883 HASHCTL ctl;
1885 ListCell *volatile cell;
1886 BufferAccessStrategy bstrategy;
1890 bool did_vacuum = false;
1891 bool found_concurrent_worker = false;
1892 int i;
1893
1894 /*
1895 * StartTransactionCommand and CommitTransactionCommand will automatically
1896 * switch to other contexts. We need this one to keep the list of
1897 * relations to vacuum/analyze across transactions.
1898 */
1900 "Autovacuum worker",
1903
1904 /* Start a transaction so our commands have one to play into. */
1906
1907 /*
1908 * This injection point is put in a transaction block to work with a wait
1909 * that uses a condition variable.
1910 */
1911 INJECTION_POINT("autovacuum-worker-start", NULL);
1912
1913 /*
1914 * Compute the multixact age for which freezing is urgent. This is
1915 * normally autovacuum_multixact_freeze_max_age, but may be less if
1916 * multixact members are bloated.
1917 */
1919
1920 /*
1921 * Find the pg_database entry and select the default freeze ages. We use
1922 * zero in template and nonconnectable databases, else the system-wide
1923 * default.
1924 */
1926 if (!HeapTupleIsValid(tuple))
1927 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1929
1930 if (dbForm->datistemplate || !dbForm->datallowconn)
1931 {
1936 }
1937 else
1938 {
1943 }
1944
1945 ReleaseSysCache(tuple);
1946
1947 /* StartTransactionCommand changed elsewhere */
1949
1951
1952 /* create a copy so we can use it after closing pg_class */
1954
1955 /* create hash table for toast <-> main relid mapping */
1956 ctl.keysize = sizeof(Oid);
1957 ctl.entrysize = sizeof(av_relation);
1958
1959 table_toast_map = hash_create("TOAST to main relid map",
1960 100,
1961 &ctl,
1963
1964 /*
1965 * Scan pg_class to determine which tables to vacuum.
1966 *
1967 * We do this in two passes: on the first one we collect the list of plain
1968 * relations and materialized views, and on the second one we collect
1969 * TOAST tables. The reason for doing the second pass is that during it we
1970 * want to use the main relation's pg_class.reloptions entry if the TOAST
1971 * table does not have any, and we cannot obtain it unless we know
1972 * beforehand what's the main table OID.
1973 *
1974 * We need to check TOAST tables separately because in cases with short,
1975 * wide tables there might be proportionally much more activity in the
1976 * TOAST table than in its parent.
1977 */
1979
1980 /*
1981 * On the first pass, we collect main tables to vacuum, and also the main
1982 * table relid to TOAST relid mapping.
1983 */
1984 while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
1985 {
1989 Oid relid;
1990 bool dovacuum;
1991 bool doanalyze;
1992 bool wraparound;
1993
1994 if (classForm->relkind != RELKIND_RELATION &&
1995 classForm->relkind != RELKIND_MATVIEW)
1996 continue;
1997
1998 relid = classForm->oid;
1999
2000 /*
2001 * Check if it is a temp table (presumably, of some other backend's).
2002 * We cannot safely process other backends' temp tables.
2003 */
2004 if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2005 {
2006 /*
2007 * We just ignore it if the owning backend is still active and
2008 * using the temporary schema. Also, for safety, ignore it if the
2009 * namespace doesn't exist or isn't a temp namespace after all.
2010 */
2012 {
2013 /*
2014 * The table seems to be orphaned -- although it might be that
2015 * the owning backend has already deleted it and exited; our
2016 * pg_class scan snapshot is not necessarily up-to-date
2017 * anymore, so we could be looking at a committed-dead entry.
2018 * Remember it so we can try to delete it later.
2019 */
2021 }
2022 continue;
2023 }
2024
2025 /* Fetch reloptions and the pgstat entry for this table */
2028 relid);
2029
2030 /* Check if it needs vacuum or analyze */
2034
2035 /* Relations that need work are added to table_oids */
2036 if (dovacuum || doanalyze)
2038
2039 /*
2040 * Remember TOAST associations for the second pass. Note: we must do
2041 * this whether or not the table is going to be vacuumed, because we
2042 * don't automatically vacuum toast tables along the parent table.
2043 */
2044 if (OidIsValid(classForm->reltoastrelid))
2045 {
2047 bool found;
2048
2050 &classForm->reltoastrelid,
2051 HASH_ENTER, &found);
2052
2053 if (!found)
2054 {
2055 /* hash_search already filled in the key */
2056 hentry->ar_relid = relid;
2057 hentry->ar_hasrelopts = false;
2058 if (relopts != NULL)
2059 {
2060 hentry->ar_hasrelopts = true;
2061 memcpy(&hentry->ar_reloptions, relopts,
2062 sizeof(AutoVacOpts));
2063 }
2064 }
2065 }
2066
2067 /* Release stuff to avoid per-relation leakage */
2068 if (relopts)
2069 pfree(relopts);
2070 if (tabentry)
2071 pfree(tabentry);
2072 }
2073
2075
2076 /* second pass: check TOAST tables */
2077 ScanKeyInit(&key,
2081
2083 while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2084 {
2087 Oid relid;
2089 bool free_relopts = false;
2090 bool dovacuum;
2091 bool doanalyze;
2092 bool wraparound;
2093
2094 /*
2095 * We cannot safely process other backends' temp tables, so skip 'em.
2096 */
2097 if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2098 continue;
2099
2100 relid = classForm->oid;
2101
2102 /*
2103 * fetch reloptions -- if this toast table does not have them, try the
2104 * main rel
2105 */
2107 if (relopts)
2108 free_relopts = true;
2109 else
2110 {
2112 bool found;
2113
2114 hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2115 if (found && hentry->ar_hasrelopts)
2116 relopts = &hentry->ar_reloptions;
2117 }
2118
2119 /* Fetch the pgstat entry for this table */
2121 relid);
2122
2126
2127 /* ignore analyze for toast tables */
2128 if (dovacuum)
2130
2131 /* Release stuff to avoid leakage */
2132 if (free_relopts)
2133 pfree(relopts);
2134 if (tabentry)
2135 pfree(tabentry);
2136 }
2137
2140
2141 /*
2142 * Recheck orphan temporary tables, and if they still seem orphaned, drop
2143 * them. We'll eat a transaction per dropped table, which might seem
2144 * excessive, but we should only need to do anything as a result of a
2145 * previous backend crash, so this should not happen often enough to
2146 * justify "optimizing". Using separate transactions ensures that we
2147 * don't bloat the lock table if there are many temp tables to be dropped,
2148 * and it ensures that we don't lose work if a deletion attempt fails.
2149 */
2150 foreach(cell, orphan_oids)
2151 {
2152 Oid relid = lfirst_oid(cell);
2154 ObjectAddress object;
2155
2156 /*
2157 * Check for user-requested abort.
2158 */
2160
2161 /*
2162 * Try to lock the table. If we can't get the lock immediately,
2163 * somebody else is using (or dropping) the table, so it's not our
2164 * concern anymore. Having the lock prevents race conditions below.
2165 */
2167 continue;
2168
2169 /*
2170 * Re-fetch the pg_class tuple and re-check whether it still seems to
2171 * be an orphaned temp table. If it's not there or no longer the same
2172 * relation, ignore it.
2173 */
2175 if (!HeapTupleIsValid(tuple))
2176 {
2177 /* be sure to drop useless lock so we don't bloat lock table */
2179 continue;
2180 }
2182
2183 /*
2184 * Make all the same tests made in the loop above. In event of OID
2185 * counter wraparound, the pg_class entry we have now might be
2186 * completely unrelated to the one we saw before.
2187 */
2188 if (!((classForm->relkind == RELKIND_RELATION ||
2189 classForm->relkind == RELKIND_MATVIEW) &&
2190 classForm->relpersistence == RELPERSISTENCE_TEMP))
2191 {
2193 continue;
2194 }
2195
2197 {
2199 continue;
2200 }
2201
2202 /*
2203 * Try to lock the temp namespace, too. Even though we have lock on
2204 * the table itself, there's a risk of deadlock against an incoming
2205 * backend trying to clean out the temp namespace, in case this table
2206 * has dependencies (such as sequences) that the backend's
2207 * performDeletion call might visit in a different order. If we can
2208 * get AccessShareLock on the namespace, that's sufficient to ensure
2209 * we're not running concurrently with RemoveTempRelations. If we
2210 * can't, back off and let RemoveTempRelations do its thing.
2211 */
2213 classForm->relnamespace, 0,
2215 {
2217 continue;
2218 }
2219
2220 /* OK, let's delete it */
2221 ereport(LOG,
2222 (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2224 get_namespace_name(classForm->relnamespace),
2225 NameStr(classForm->relname))));
2226
2227 /*
2228 * Deletion might involve TOAST table access, so ensure we have a
2229 * valid snapshot.
2230 */
2232
2233 object.classId = RelationRelationId;
2234 object.objectId = relid;
2235 object.objectSubId = 0;
2240
2241 /*
2242 * To commit the deletion, end current transaction and start a new
2243 * one. Note this also releases the locks we took.
2244 */
2248
2249 /* StartTransactionCommand changed current memory context */
2251 }
2252
2253 /*
2254 * Optionally, create a buffer access strategy object for VACUUM to use.
2255 * We use the same BufferAccessStrategy object for all tables VACUUMed by
2256 * this worker to prevent autovacuum from blowing out shared buffers.
2257 *
2258 * VacuumBufferUsageLimit being set to 0 results in
2259 * GetAccessStrategyWithSize returning NULL, effectively meaning we can
2260 * use up to all of shared buffers.
2261 *
2262 * If we later enter failsafe mode on any of the tables being vacuumed, we
2263 * will cease use of the BufferAccessStrategy only for that table.
2264 *
2265 * XXX should we consider adding code to adjust the size of this if
2266 * VacuumBufferUsageLimit changes?
2267 */
2269
2270 /*
2271 * create a memory context to act as fake PortalContext, so that the
2272 * contexts created in the vacuum code are cleaned up for each table.
2273 */
2275 "Autovacuum Portal",
2277
2278 /*
2279 * Perform operations on collected tables.
2280 */
2281 foreach(cell, table_oids)
2282 {
2283 Oid relid = lfirst_oid(cell);
2285 autovac_table *tab;
2286 bool isshared;
2287 bool skipit;
2288 dlist_iter iter;
2289
2291
2292 /*
2293 * Check for config changes before processing each collected table.
2294 */
2296 {
2297 ConfigReloadPending = false;
2299
2300 /*
2301 * You might be tempted to bail out if we see autovacuum is now
2302 * disabled. Must resist that temptation -- this might be a
2303 * for-wraparound emergency worker, in which case that would be
2304 * entirely inappropriate.
2305 */
2306 }
2307
2308 /*
2309 * Find out whether the table is shared or not. (It's slightly
2310 * annoying to fetch the syscache entry just for this, but in typical
2311 * cases it adds little cost because table_recheck_autovac would
2312 * refetch the entry anyway. We could buy that back by copying the
2313 * tuple here and passing it to table_recheck_autovac, but that
2314 * increases the odds of that function working with stale data.)
2315 */
2318 continue; /* somebody deleted the rel, forget it */
2321
2322 /*
2323 * Hold schedule lock from here until we've claimed the table. We
2324 * also need the AutovacuumLock to walk the worker array, but that one
2325 * can just be a shared lock.
2326 */
2329
2330 /*
2331 * Check whether the table is being vacuumed concurrently by another
2332 * worker.
2333 */
2334 skipit = false;
2336 {
2337 WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2338
2339 /* ignore myself */
2340 if (worker == MyWorkerInfo)
2341 continue;
2342
2343 /* ignore workers in other databases (unless table is shared) */
2344 if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2345 continue;
2346
2347 if (worker->wi_tableoid == relid)
2348 {
2349 skipit = true;
2351 break;
2352 }
2353 }
2355 if (skipit)
2356 {
2358 continue;
2359 }
2360
2361 /*
2362 * Store the table's OID in shared memory before releasing the
2363 * schedule lock, so that other workers don't try to vacuum it
2364 * concurrently. (We claim it here so as not to hold
2365 * AutovacuumScheduleLock while rechecking the stats.)
2366 */
2367 MyWorkerInfo->wi_tableoid = relid;
2368 MyWorkerInfo->wi_sharedrel = isshared;
2370
2371 /*
2372 * Check whether pgstat data still says we need to vacuum this table.
2373 * It could have changed if something else processed the table while
2374 * we weren't looking. This doesn't entirely close the race condition,
2375 * but it is very small.
2376 */
2380 if (tab == NULL)
2381 {
2382 /* someone else vacuumed the table, or it went away */
2385 MyWorkerInfo->wi_sharedrel = false;
2387 continue;
2388 }
2389
2390 /*
2391 * Save the cost-related storage parameter values in global variables
2392 * for reference when updating vacuum_cost_delay and vacuum_cost_limit
2393 * during vacuuming this table.
2394 */
2397
2398 /*
2399 * We only expect this worker to ever set the flag, so don't bother
2400 * checking the return value. We shouldn't have to retry.
2401 */
2402 if (tab->at_dobalance)
2404 else
2406
2410
2411 /*
2412 * We wait until this point to update cost delay and cost limit
2413 * values, even though we reloaded the configuration file above, so
2414 * that we can take into account the cost-related storage parameters.
2415 */
2417
2418
2419 /* clean up memory before each iteration */
2421
2422 /*
2423 * Save the relation name for a possible error message, to avoid a
2424 * catalog lookup in case of an error. If any of these return NULL,
2425 * then the relation has been dropped since last we checked; skip it.
2426 * Note: they must live in a long-lived memory context because we call
2427 * vacuum and analyze in different transactions.
2428 */
2429
2430 tab->at_relname = get_rel_name(tab->at_relid);
2433 if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2434 goto deleted;
2435
2436 /*
2437 * We will abort vacuuming the current table if something errors out,
2438 * and continue with the next one in schedule; in particular, this
2439 * happens if we are interrupted with SIGINT.
2440 */
2441 PG_TRY();
2442 {
2443 /* Use PortalContext for any per-table allocations */
2445
2446 /* have at it */
2447 autovacuum_do_vac_analyze(tab, bstrategy);
2448
2449 /*
2450 * Clear a possible query-cancel signal, to avoid a late reaction
2451 * to an automatically-sent signal because of vacuuming the
2452 * current table (we're done with it, so it would make no sense to
2453 * cancel at this point.)
2454 */
2455 QueryCancelPending = false;
2456 }
2457 PG_CATCH();
2458 {
2459 /*
2460 * Abort the transaction, start a new one, and proceed with the
2461 * next table in our list.
2462 */
2464 if (tab->at_params.options & VACOPT_VACUUM)
2465 errcontext("automatic vacuum of table \"%s.%s.%s\"",
2466 tab->at_datname, tab->at_nspname, tab->at_relname);
2467 else
2468 errcontext("automatic analyze of table \"%s.%s.%s\"",
2469 tab->at_datname, tab->at_nspname, tab->at_relname);
2471
2472 /* this resets ProcGlobal->statusFlags[i] too */
2476
2477 /* restart our transaction for the following operations */
2480 }
2481 PG_END_TRY();
2482
2483 /* Make sure we're back in AutovacMemCxt */
2485
2486 did_vacuum = true;
2487
2488 /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2489
2490 /* be tidy */
2491deleted:
2492 if (tab->at_datname != NULL)
2493 pfree(tab->at_datname);
2494 if (tab->at_nspname != NULL)
2495 pfree(tab->at_nspname);
2496 if (tab->at_relname != NULL)
2497 pfree(tab->at_relname);
2498 pfree(tab);
2499
2500 /*
2501 * Remove my info from shared memory. We set wi_dobalance on the
2502 * assumption that we are more likely than not to vacuum a table with
2503 * no cost-related storage parameters next, so we want to claim our
2504 * share of I/O as soon as possible to avoid thrashing the global
2505 * balance.
2506 */
2509 MyWorkerInfo->wi_sharedrel = false;
2512 }
2513
2515
2516 /*
2517 * Perform additional work items, as requested by backends.
2518 */
2520 for (i = 0; i < NUM_WORKITEMS; i++)
2521 {
2523
2524 if (!workitem->avw_used)
2525 continue;
2526 if (workitem->avw_active)
2527 continue;
2528 if (workitem->avw_database != MyDatabaseId)
2529 continue;
2530
2531 /* claim this one, and release lock while performing it */
2532 workitem->avw_active = true;
2534
2537 if (ActiveSnapshotSet()) /* transaction could have aborted */
2539
2540 /*
2541 * Check for config changes before acquiring lock for further jobs.
2542 */
2545 {
2546 ConfigReloadPending = false;
2549 }
2550
2552
2553 /* and mark it done */
2554 workitem->avw_active = false;
2555 workitem->avw_used = false;
2556 }
2558
2559 /*
2560 * We leak table_toast_map here (among other things), but since we're
2561 * going away soon, it's not a problem normally. But when using Valgrind,
2562 * release some stuff to reduce complaints about leaked storage.
2563 */
2564#ifdef USE_VALGRIND
2567 if (bstrategy)
2568 pfree(bstrategy);
2569#endif
2570
2571 /* Run the rest in xact context, mainly to avoid Valgrind leak warnings */
2573
2574 /*
2575 * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2576 * only need to do this once, not after each table.
2577 *
2578 * Even if we didn't vacuum anything, it may still be important to do
2579 * this, because one indirect effect of vac_update_datfrozenxid() is to
2580 * update TransamVariables->xidVacLimit. That might need to be done even
2581 * if we haven't vacuumed anything, because relations with older
2582 * relfrozenxid values or other databases with older datfrozenxid values
2583 * might have been dropped, allowing xidVacLimit to advance.
2584 *
2585 * However, it's also important not to do this blindly in all cases,
2586 * because when autovacuum=off this will restart the autovacuum launcher.
2587 * If we're not careful, an infinite loop can result, where workers find
2588 * no work to do and restart the launcher, which starts another worker in
2589 * the same database that finds no work to do. To prevent that, we skip
2590 * this if (1) we found no work to do and (2) we skipped at least one
2591 * table due to concurrent autovacuum activity. In that case, the other
2592 * worker has already done it, or will do so when it finishes.
2593 */
2596
2597 /* Finally close out the last transaction. */
2599}
static void pg_atomic_clear_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:205
static bool pg_atomic_test_set_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:181
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)
void VacuumUpdateCosts(void)
static int default_multixact_freeze_table_age
Definition autovacuum.c:165
static int default_multixact_freeze_min_age
Definition autovacuum.c:164
static double av_storage_param_cost_delay
Definition autovacuum.c:151
static void perform_work_item(AutoVacuumWorkItem *workitem)
static int default_freeze_min_age
Definition autovacuum.c:162
static autovac_table * table_recheck_autovac(Oid relid, HTAB *table_toast_map, TupleDesc pg_class_desc, int effective_multixact_freeze_max_age)
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
static int default_freeze_table_age
Definition autovacuum.c:163
static void autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
@ BAS_VACUUM
Definition bufmgr.h:40
#define NameStr(name)
Definition c.h:765
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition dependency.c:274
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition dependency.h:96
#define PERFORM_DELETION_QUIETLY
Definition dependency.h:94
#define PERFORM_DELETION_INTERNAL
Definition dependency.h:92
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
void hash_destroy(HTAB *hashp)
Definition dynahash.c:865
#define LOG
Definition elog.h:31
#define errcontext
Definition elog.h:198
#define PG_TRY(...)
Definition elog.h:372
#define PG_END_TRY(...)
Definition elog.h:397
#define PG_CATCH(...)
Definition elog.h:382
BufferAccessStrategy GetAccessStrategyWithSize(BufferAccessStrategyType btype, int ring_size_kb)
Definition freelist.c:546
int VacuumBufferUsageLimit
Definition globals.c:149
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
@ PGC_SIGHUP
Definition guc.h:75
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1409
@ 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
static void * GETSTRUCT(const HeapTupleData *tuple)
#define INJECTION_POINT(name, arg)
volatile sig_atomic_t ConfigReloadPending
Definition interrupt.c:27
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
void list_free(List *list)
Definition list.c:1546
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:151
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:229
bool ConditionalLockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1032
#define AccessExclusiveLock
Definition lockdefs.h:43
#define AccessShareLock
Definition lockdefs.h:36
char * get_rel_name(Oid relid)
Definition lsyscache.c:2078
char * get_database_name(Oid dbid)
Definition lsyscache.c:1242
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2102
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3516
MemoryContext TopTransactionContext
Definition mcxt.c:171
void pfree(void *pointer)
Definition mcxt.c:1616
MemoryContext PortalContext
Definition mcxt.c:175
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
int MultiXactMemberFreezeThreshold(void)
Definition multixact.c:2511
TempNamespaceStatus checkTempNamespaceStatus(Oid namespaceId)
Definition namespace.c:3799
@ TEMP_NAMESPACE_IDLE
Definition namespace.h:66
@ DROP_CASCADE
FormData_pg_class * Form_pg_class
Definition pg_class.h:156
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:262
static Datum CharGetDatum(char X)
Definition postgres.h:132
tree ctl
Definition radixtree.h:1838
#define RelationGetDescr(relation)
Definition rel.h:540
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
@ ForwardScanDirection
Definition sdir.h:28
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
bool ActiveSnapshotSet(void)
Definition snapmgr.c:812
void PopActiveSnapshot(void)
Definition snapmgr.c:775
#define BTEqualStrategyNumber
Definition stratnum.h:31
double at_storage_param_vac_cost_delay
Definition autovacuum.c:204
int at_storage_param_vac_cost_limit
Definition autovacuum.c:205
char * at_datname
Definition autovacuum.c:210
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition syscache.c:220
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
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, ScanKeyData *key)
Definition tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition tableam.h:1005
void FreeTupleDesc(TupleDesc tupdesc)
Definition tupdesc.c:485
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition tupdesc.c:235
int vacuum_freeze_min_age
Definition vacuum.c:75
int vacuum_multixact_freeze_table_age
Definition vacuum.c:78
int vacuum_freeze_table_age
Definition vacuum.c:76
int vacuum_multixact_freeze_min_age
Definition vacuum.c:77
void vac_update_datfrozenxid(void)
Definition vacuum.c:1608
void StartTransactionCommand(void)
Definition xact.c:3080
void CommitTransactionCommand(void)
Definition xact.c:3178
void AbortOutOfAnyTransaction(void)
Definition xact.c:4884

References AbortOutOfAnyTransaction(), AccessExclusiveLock, AccessShareLock, ActiveSnapshotSet(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, 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, BAS_VACUUM, BTEqualStrategyNumber, CharGetDatum(), CHECK_FOR_INTERRUPTS, checkTempNamespaceStatus(), CommitTransactionCommand(), ConditionalLockDatabaseObject(), ConditionalLockRelationOid(), ConfigReloadPending, CreateTupleDescCopy(), ctl, dlist_iter::cur, default_freeze_min_age, default_freeze_table_age, default_multixact_freeze_min_age, default_multixact_freeze_table_age, dlist_container, dlist_foreach, DROP_CASCADE, elog, EmitErrorReport(), ereport, errcontext, errmsg(), ERROR, extract_autovac_opts(), fb(), FlushErrorState(), ForwardScanDirection, FreeTupleDesc(), get_database_name(), get_namespace_name(), get_rel_name(), get_rel_namespace(), GetAccessStrategyWithSize(), GETSTRUCT(), GetTransactionSnapshot(), HASH_BLOBS, hash_create(), hash_destroy(), HASH_ELEM, HASH_ENTER, HASH_FIND, hash_search(), heap_getnext(), HeapTupleIsValid, HOLD_INTERRUPTS, i, INJECTION_POINT, InvalidOid, lappend_oid(), lfirst_oid, list_free(), 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(), PopActiveSnapshot(), PortalContext, ProcessConfigFile(), PushActiveSnapshot(), 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, TopTransactionContext, 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 1100 of file autovacuum.c.

1101{
1102 List *dblist;
1103 ListCell *cell;
1106 bool for_xid_wrap;
1107 bool for_multi_wrap;
1108 avw_dbase *avdb;
1110 bool skipit = false;
1111 Oid retval = InvalidOid;
1113 oldcxt;
1114
1115 /* return quickly when there are no free workers */
1117 if (!av_worker_available())
1118 {
1120 return InvalidOid;
1121 }
1123
1124 /*
1125 * Create and switch to a temporary context to avoid leaking the memory
1126 * allocated for the database list.
1127 */
1129 "Autovacuum start worker (tmp)",
1132
1133 /* Get a list of databases */
1135
1136 /*
1137 * Determine the oldest datfrozenxid/relfrozenxid that we will allow to
1138 * pass without forcing a vacuum. (This limit can be tightened for
1139 * particular tables, but not loosened.)
1140 */
1143 /* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
1144 /* this can cause the limit to go backwards by 3, but that's OK */
1147
1148 /* Also determine the oldest datminmxid we will consider. */
1153
1154 /*
1155 * Choose a database to connect to. We pick the database that was least
1156 * recently auto-vacuumed, or one that needs vacuuming to prevent Xid
1157 * wraparound-related data loss. If any db at risk of Xid wraparound is
1158 * found, we pick the one with oldest datfrozenxid, independently of
1159 * autovacuum times; similarly we pick the one with the oldest datminmxid
1160 * if any is in MultiXactId wraparound. Note that those in Xid wraparound
1161 * danger are given more priority than those in multi wraparound danger.
1162 *
1163 * Note that a database with no stats entry is not considered, except for
1164 * Xid wraparound purposes. The theory is that if no one has ever
1165 * connected to it since the stats were last initialized, it doesn't need
1166 * vacuuming.
1167 *
1168 * XXX This could be improved if we had more info about whether it needs
1169 * vacuuming before connecting to it. Perhaps look through the pgstats
1170 * data for the database's tables? One idea is to keep track of the
1171 * number of new and dead tuples per database in pgstats. However it
1172 * isn't clear how to construct a metric that measures that and not cause
1173 * starvation for less busy databases.
1174 */
1175 avdb = NULL;
1176 for_xid_wrap = false;
1177 for_multi_wrap = false;
1179 foreach(cell, dblist)
1180 {
1181 avw_dbase *tmp = lfirst(cell);
1182 dlist_iter iter;
1183
1184 /* Check to see if this one is at risk of wraparound */
1186 {
1187 if (avdb == NULL ||
1189 avdb->adw_frozenxid))
1190 avdb = tmp;
1191 for_xid_wrap = true;
1192 continue;
1193 }
1194 else if (for_xid_wrap)
1195 continue; /* ignore not-at-risk DBs */
1197 {
1198 if (avdb == NULL ||
1199 MultiXactIdPrecedes(tmp->adw_minmulti, avdb->adw_minmulti))
1200 avdb = tmp;
1201 for_multi_wrap = true;
1202 continue;
1203 }
1204 else if (for_multi_wrap)
1205 continue; /* ignore not-at-risk DBs */
1206
1207 /* Find pgstat entry if any */
1209
1210 /*
1211 * Skip a database with no pgstat entry; it means it hasn't seen any
1212 * activity.
1213 */
1214 if (!tmp->adw_entry)
1215 continue;
1216
1217 /*
1218 * Also, skip a database that appears on the database list as having
1219 * been processed recently (less than autovacuum_naptime seconds ago).
1220 * We do this so that we don't select a database which we just
1221 * selected, but that pgstat hasn't gotten around to updating the last
1222 * autovacuum time yet.
1223 */
1224 skipit = false;
1225
1227 {
1228 avl_dbase *dbp = dlist_container(avl_dbase, adl_node, iter.cur);
1229
1230 if (dbp->adl_datid == tmp->adw_datid)
1231 {
1232 /*
1233 * Skip this database if its next_worker value falls between
1234 * the current time and the current time plus naptime.
1235 */
1236 if (!TimestampDifferenceExceeds(dbp->adl_next_worker,
1237 current_time, 0) &&
1239 dbp->adl_next_worker,
1240 autovacuum_naptime * 1000))
1241 skipit = true;
1242
1243 break;
1244 }
1245 }
1246 if (skipit)
1247 continue;
1248
1249 /*
1250 * Remember the db with oldest autovac time. (If we are here, both
1251 * tmp->entry and db->entry must be non-null.)
1252 */
1253 if (avdb == NULL ||
1254 tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time)
1255 avdb = tmp;
1256 }
1257
1258 /* Found a database -- process it */
1259 if (avdb != NULL)
1260 {
1261 WorkerInfo worker;
1263
1265
1266 /*
1267 * Get a worker entry from the freelist. We checked above, so there
1268 * really should be a free slot.
1269 */
1271
1272 worker = dlist_container(WorkerInfoData, wi_links, wptr);
1273 worker->wi_dboid = avdb->adw_datid;
1274 worker->wi_proc = NULL;
1276
1278
1280
1282
1283 retval = avdb->adw_datid;
1284 }
1285 else if (skipit)
1286 {
1287 /*
1288 * If we skipped all databases on the list, rebuild it, because it
1289 * probably contains a dropped database.
1290 */
1292 }
1293
1296
1297 return retval;
1298}
static List * get_database_list(void)
int autovacuum_freeze_max_age
Definition autovacuum.c:129
TransactionId MultiXactId
Definition c.h:676
uint32 TransactionId
Definition c.h:666
#define dlist_reverse_foreach(iter, lhead)
Definition ilist.h:654
static dlist_node * dclist_pop_head_node(dclist_head *head)
Definition ilist.h:789
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition multixact.c:2765
#define FirstMultiXactId
Definition multixact.h:26
#define lfirst(lc)
Definition pg_list.h:172
_stringlist * dblist
Definition pg_regress.c:97
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dboid)
TimestampTz last_autovac_time
Definition pgstat.h:356
PgStat_StatDBEntry * adw_entry
Definition autovacuum.c:186
Oid adw_datid
Definition autovacuum.c:182
TransactionId adw_frozenxid
Definition autovacuum.c:184
MultiXactId adw_minmulti
Definition autovacuum.c:185
#define FirstNormalTransactionId
Definition transam.h:34
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263

References 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, av_worker_available(), dlist_iter::cur, CurrentMemoryContext, DatabaseList, dblist, dclist_pop_head_node(), dlist_container, dlist_reverse_foreach, fb(), 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 2719 of file autovacuum.c.

2720{
2721 bytea *relopts;
2722 AutoVacOpts *av;
2723
2725 ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2727
2729 if (relopts == NULL)
2730 return NULL;
2731
2733 memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2734 pfree(relopts);
2735
2736 return av;
2737}
#define palloc_object(type)
Definition fe_memutils.h:74
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
struct @10::@11 av[32]
Definition c.h:706

References Assert, av, extractRelOptions(), fb(), GETSTRUCT(), palloc_object, and pfree().

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ FreeWorkerInfo()

◆ get_database_list()

static List * get_database_list ( void  )
static

Definition at line 1799 of file autovacuum.c.

1800{
1801 List *dblist = NIL;
1802 Relation rel;
1803 TableScanDesc scan;
1804 HeapTuple tup;
1806
1807 /* This is the context that we will allocate our output data in */
1809
1810 /*
1811 * Start a transaction so we can access pg_database.
1812 */
1814
1816 scan = table_beginscan_catalog(rel, 0, NULL);
1817
1819 {
1821 avw_dbase *avdb;
1823
1824 /*
1825 * If database has partially been dropped, we can't, nor need to,
1826 * vacuum it.
1827 */
1829 {
1830 elog(DEBUG2,
1831 "autovacuum: skipping invalid database \"%s\"",
1832 NameStr(pgdatabase->datname));
1833 continue;
1834 }
1835
1836 /*
1837 * Allocate our results in the caller's context, not the
1838 * transaction's. We do this inside the loop, and restore the original
1839 * context at the end, so that leaky things like heap_getnext() are
1840 * not called in a potentially long-lived context.
1841 */
1843
1845
1846 avdb->adw_datid = pgdatabase->oid;
1847 avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1848 avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1849 avdb->adw_minmulti = pgdatabase->datminmxid;
1850 /* this gets set later: */
1851 avdb->adw_entry = NULL;
1852
1855 }
1856
1857 table_endscan(scan);
1859
1861
1862 /* Be sure to restore caller's memory context */
1864
1865 return dblist;
1866}
bool database_is_invalid_form(Form_pg_database datform)
#define DEBUG2
Definition elog.h:29
List * lappend(List *list, void *datum)
Definition list.c:339
char * pstrdup(const char *in)
Definition mcxt.c:1781

References AccessShareLock, CommitTransactionCommand(), CurrentMemoryContext, database_is_invalid_form(), dblist, DEBUG2, elog, fb(), ForwardScanDirection, GETSTRUCT(), heap_getnext(), HeapTupleIsValid, lappend(), MemoryContextSwitchTo(), NameStr, NIL, palloc_object, pstrdup(), StartTransactionCommand(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by do_start_worker(), and rebuild_database_list().

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1312 of file autovacuum.c.

1313{
1314 Oid dbid;
1315 dlist_iter iter;
1316
1317 dbid = do_start_worker();
1318 if (OidIsValid(dbid))
1319 {
1320 bool found = false;
1321
1322 /*
1323 * Walk the database list and update the corresponding entry. If the
1324 * database is not on the list, we'll recreate the list.
1325 */
1327 {
1328 avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1329
1330 if (avdb->adl_datid == dbid)
1331 {
1332 found = true;
1333
1334 /*
1335 * add autovacuum_naptime seconds to the current time, and use
1336 * that as the new "next_worker" field for this database.
1337 */
1338 avdb->adl_next_worker =
1340
1342 break;
1343 }
1344 }
1345
1346 /*
1347 * If the database was not present in the database list, we rebuild
1348 * the list. It's possible that the database does not get into the
1349 * list anyway, for example if it's a database that doesn't have a
1350 * pgstat entry, but this is not a problem because we don't want to
1351 * schedule workers regularly into those in any case.
1352 */
1353 if (!found)
1355 }
1356}
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1609
static void dlist_move_head(dlist_head *head, dlist_node *node)
Definition ilist.h:467
#define TimestampTzPlusMilliseconds(tz, ms)
Definition timestamp.h:85

References autovacuum_naptime, dlist_iter::cur, DatabaseList, dlist_container, dlist_foreach, dlist_move_head(), do_start_worker(), fb(), 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 815 of file autovacuum.c.

816{
817 /*
818 * We sleep until the next scheduled vacuum. We trust that when the
819 * database list was built, care was taken so that no entries have times
820 * in the past; if the first entry has too close a next_worker value, or a
821 * time in the past, we will sleep a small nominal time.
822 */
823 if (!canlaunch)
824 {
825 nap->tv_sec = autovacuum_naptime;
826 nap->tv_usec = 0;
827 }
828 else if (!dlist_is_empty(&DatabaseList))
829 {
833 long secs;
834 int usecs;
835
837
838 next_wakeup = avdb->adl_next_worker;
840
841 nap->tv_sec = secs;
842 nap->tv_usec = usecs;
843 }
844 else
845 {
846 /* list is empty, sleep for whole autovacuum_naptime seconds */
847 nap->tv_sec = autovacuum_naptime;
848 nap->tv_usec = 0;
849 }
850
851 /*
852 * If the result is exactly zero, it means a database had an entry with
853 * time in the past. Rebuild the list so that the databases are evenly
854 * distributed again, and recalculate the time to sleep. This can happen
855 * if there are more tables needing vacuum than workers, and they all take
856 * longer to vacuum than autovacuum_naptime.
857 *
858 * We only recurse once. rebuild_database_list should always return times
859 * in the future, but it seems best not to trust too much on that.
860 */
861 if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
862 {
865 return;
866 }
867
868 /* The smallest time we'll allow the launcher to sleep. */
869 if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
870 {
871 nap->tv_sec = 0;
872 nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000;
873 }
874
875 /*
876 * If the sleep time is too large, clamp it to an arbitrary maximum (plus
877 * any fractional seconds, for simplicity). This avoids an essentially
878 * infinite sleep in strange cases like the system clock going backwards a
879 * few years.
880 */
881 if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME)
882 nap->tv_sec = MAX_AUTOVAC_SLEEPTIME;
883}
#define MIN_AUTOVAC_SLEEPTIME
Definition autovacuum.c:139
#define MAX_AUTOVAC_SLEEPTIME
Definition autovacuum.c:140
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1721

References autovacuum_naptime, DatabaseList, dlist_is_empty(), dlist_tail_element, fb(), GetCurrentTimestamp(), InvalidOid, launcher_determine_sleep(), MAX_AUTOVAC_SLEEPTIME, MIN_AUTOVAC_SLEEPTIME, rebuild_database_list(), and TimestampDifference().

Referenced by AutoVacLauncherMain(), and launcher_determine_sleep().

◆ perform_work_item()

static void perform_work_item ( AutoVacuumWorkItem workitem)
static

Definition at line 2605 of file autovacuum.c.

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

References AbortOutOfAnyTransaction(), Assert, autovac_report_workitem(), AutovacMemCxt, AVW_BRINSummarizeRange, brin_summarize_range(), CurrentMemoryContext, DirectFunctionCall2, elog, EmitErrorReport(), errcontext, fb(), 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().

◆ ProcessAutoVacLauncherInterrupts()

static void ProcessAutoVacLauncherInterrupts ( void  )
static

Definition at line 753 of file autovacuum.c.

754{
755 /* the normal shutdown case */
758
760 {
762
763 ConfigReloadPending = false;
765
766 /* shutdown requested in config file? */
767 if (!AutoVacuumingActive())
769
770 /*
771 * If autovacuum_max_workers changed, emit a WARNING if
772 * autovacuum_worker_slots < autovacuum_max_workers. If it didn't
773 * change, skip this to avoid too many repeated log messages.
774 */
777
778 /* rebuild the list in case the naptime changed */
780 }
781
782 /* Process barrier events */
785
786 /* Perform logging of memory contexts of this process */
789
790 /* Process sinval catchup interrupts that happened while sleeping */
792}
volatile sig_atomic_t LogMemoryContextPending
Definition globals.c:41
volatile sig_atomic_t ProcSignalBarrierPending
Definition globals.c:40
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1340
void ProcessProcSignalBarrier(void)
Definition procsignal.c:499
void ProcessCatchupInterrupt(void)
Definition sinval.c:174

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

Referenced by AutoVacLauncherMain().

◆ rebuild_database_list()

static void rebuild_database_list ( Oid  newdb)
static

Definition at line 899 of file autovacuum.c.

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

References avl_dbase::adl_next_worker, avl_dbase::adl_node, avl_dbase::adl_score, 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, fb(), 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(), launch_worker(), launcher_determine_sleep(), and ProcessAutoVacLauncherInterrupts().

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

2914{
2916
2917 /* fetch the pgstat table entry */
2919 relid);
2920
2924
2925 /* Release tabentry to avoid leakage */
2926 if (tabentry)
2927 pfree(tabentry);
2928
2929 /* ignore ANALYZE for toast tables */
2930 if (classForm->relkind == RELKIND_TOASTVALUE)
2931 *doanalyze = false;
2932}

References fb(), pfree(), 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 2974 of file autovacuum.c.

2983{
2984 bool force_vacuum;
2985 bool av_enabled;
2986
2987 /* constants from reloptions or GUC variables */
2988 int vac_base_thresh,
2995
2996 /* thresholds calculated from above constants */
2999 anlthresh;
3000
3001 /* number of vacuum (resp. analyze) tuples at this time */
3003 instuples,
3004 anltuples;
3005
3006 /* freeze parameters */
3007 int freeze_max_age;
3008 int multixact_freeze_max_age;
3010 TransactionId relfrozenxid;
3012
3013 Assert(classForm != NULL);
3014 Assert(OidIsValid(relid));
3015
3016 /*
3017 * Determine vacuum/analyze equation parameters. We have two possible
3018 * sources: the passed reloptions (which could be a main table or a toast
3019 * table), or the autovacuum GUC variables.
3020 */
3021
3022 /* -1 in autovac setting means use plain vacuum_scale_factor */
3023 vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3024 ? relopts->vacuum_scale_factor
3026
3027 vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3028 ? relopts->vacuum_threshold
3030
3031 /* -1 is used to disable max threshold */
3032 vac_max_thresh = (relopts && relopts->vacuum_max_threshold >= -1)
3033 ? relopts->vacuum_max_threshold
3035
3036 vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3037 ? relopts->vacuum_ins_scale_factor
3039
3040 /* -1 is used to disable insert vacuums */
3041 vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3042 ? relopts->vacuum_ins_threshold
3044
3045 anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3046 ? relopts->analyze_scale_factor
3048
3049 anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3050 ? relopts->analyze_threshold
3052
3053 freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3054 ? Min(relopts->freeze_max_age, autovacuum_freeze_max_age)
3056
3057 multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3058 ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3060
3061 av_enabled = (relopts ? relopts->enabled : true);
3062
3063 /* Force vacuum if table is at risk of wraparound */
3064 xidForceLimit = recentXid - freeze_max_age;
3067 relfrozenxid = classForm->relfrozenxid;
3068 force_vacuum = (TransactionIdIsNormal(relfrozenxid) &&
3069 TransactionIdPrecedes(relfrozenxid, xidForceLimit));
3070 if (!force_vacuum)
3071 {
3072 MultiXactId relminmxid = classForm->relminmxid;
3073
3074 multiForceLimit = recentMulti - multixact_freeze_max_age;
3077 force_vacuum = MultiXactIdIsValid(relminmxid) &&
3079 }
3081
3082 /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3083 if (!av_enabled && !force_vacuum)
3084 {
3085 *doanalyze = false;
3086 *dovacuum = false;
3087 return;
3088 }
3089
3090 /*
3091 * If we found stats for the table, and autovacuum is currently enabled,
3092 * make a threshold-based decision whether to vacuum and/or analyze. If
3093 * autovacuum is currently disabled, we must be here for anti-wraparound
3094 * vacuuming only, so don't vacuum (or analyze) anything that's not being
3095 * forced.
3096 */
3098 {
3100 float4 reltuples = classForm->reltuples;
3101 int32 relpages = classForm->relpages;
3102 int32 relallfrozen = classForm->relallfrozen;
3103
3104 vactuples = tabentry->dead_tuples;
3105 instuples = tabentry->ins_since_vacuum;
3106 anltuples = tabentry->mod_since_analyze;
3107
3108 /* If the table hasn't yet been vacuumed, take reltuples as zero */
3109 if (reltuples < 0)
3110 reltuples = 0;
3111
3112 /*
3113 * If we have data for relallfrozen, calculate the unfrozen percentage
3114 * of the table to modify insert scale factor. This helps us decide
3115 * whether or not to vacuum an insert-heavy table based on the number
3116 * of inserts to the more "active" part of the table.
3117 */
3118 if (relpages > 0 && relallfrozen > 0)
3119 {
3120 /*
3121 * It could be the stats were updated manually and relallfrozen >
3122 * relpages. Clamp relallfrozen to relpages to avoid nonsensical
3123 * calculations.
3124 */
3125 relallfrozen = Min(relallfrozen, relpages);
3126 pcnt_unfrozen = 1 - ((float4) relallfrozen / relpages);
3127 }
3128
3132
3134 vac_ins_scale_factor * reltuples * pcnt_unfrozen;
3136
3137 if (vac_ins_base_thresh >= 0)
3138 elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3139 NameStr(classForm->relname),
3141 else
3142 elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3143 NameStr(classForm->relname),
3145
3146 /* Determine if this table needs vacuum or analyze. */
3150 }
3151 else
3152 {
3153 /*
3154 * Skip a table not found in stat hash, unless we have to force vacuum
3155 * for anti-wrap purposes. If it's not acted upon, there's no need to
3156 * vacuum it.
3157 */
3159 *doanalyze = false;
3160 }
3161
3162 /* ANALYZE refuses to work with pg_statistic */
3163 if (relid == StatisticRelationId)
3164 *doanalyze = false;
3165}
double autovacuum_vac_scale
Definition autovacuum.c:124
int autovacuum_anl_thresh
Definition autovacuum.c:127
int autovacuum_vac_thresh
Definition autovacuum.c:122
double autovacuum_anl_scale
Definition autovacuum.c:128
int autovacuum_vac_ins_thresh
Definition autovacuum.c:125
double autovacuum_vac_ins_scale
Definition autovacuum.c:126
int autovacuum_vac_max_thresh
Definition autovacuum.c:123
int32_t int32
Definition c.h:542
float float4
Definition c.h:643
#define DEBUG3
Definition elog.h:28
#define MultiXactIdIsValid(multi)
Definition multixact.h:29
#define TransactionIdIsNormal(xid)
Definition transam.h:42

References Assert, autovacuum_anl_scale, autovacuum_anl_thresh, autovacuum_freeze_max_age, autovacuum_vac_ins_scale, autovacuum_vac_ins_thresh, autovacuum_vac_max_thresh, autovacuum_vac_scale, autovacuum_vac_thresh, AutoVacuumingActive(), DEBUG3, elog, fb(), FirstMultiXactId, FirstNormalTransactionId, Min, MultiXactIdIsValid, MultiXactIdPrecedes(), NameStr, OidIsValid, recentMulti, recentXid, TransactionIdIsNormal, and TransactionIdPrecedes().

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

◆ table_recheck_autovac()

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

Definition at line 2749 of file autovacuum.c.

2752{
2755 bool dovacuum;
2756 bool doanalyze;
2757 autovac_table *tab = NULL;
2758 bool wraparound;
2760 bool free_avopts = false;
2761
2762 /* fetch the relation's relcache entry */
2765 return NULL;
2767
2768 /*
2769 * Get the applicable reloptions. If it is a TOAST table, try to get the
2770 * main table reloptions if the toast table itself doesn't have.
2771 */
2773 if (avopts)
2774 free_avopts = true;
2775 else if (classForm->relkind == RELKIND_TOASTVALUE &&
2777 {
2779 bool found;
2780
2781 hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2782 if (found && hentry->ar_hasrelopts)
2783 avopts = &hentry->ar_reloptions;
2784 }
2785
2789
2790 /* OK, it needs something done */
2791 if (doanalyze || dovacuum)
2792 {
2793 int freeze_min_age;
2794 int freeze_table_age;
2795 int multixact_freeze_min_age;
2796 int multixact_freeze_table_age;
2797 int log_vacuum_min_duration;
2798 int log_analyze_min_duration;
2799
2800 /*
2801 * Calculate the vacuum cost parameters and the freeze ages. If there
2802 * are options set in pg_class.reloptions, use them; in the case of a
2803 * toast table, try the main table too. Otherwise use the GUC
2804 * defaults, autovacuum's own first and plain vacuum second.
2805 */
2806
2807 /* -1 in autovac setting means use log_autovacuum_min_duration */
2808 log_vacuum_min_duration = (avopts && avopts->log_vacuum_min_duration >= 0)
2809 ? avopts->log_vacuum_min_duration
2811
2812 /* -1 in autovac setting means use log_autoanalyze_min_duration */
2813 log_analyze_min_duration = (avopts && avopts->log_analyze_min_duration >= 0)
2814 ? avopts->log_analyze_min_duration
2816
2817 /* these do not have autovacuum-specific settings */
2818 freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2819 ? avopts->freeze_min_age
2821
2822 freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2823 ? avopts->freeze_table_age
2825
2826 multixact_freeze_min_age = (avopts &&
2827 avopts->multixact_freeze_min_age >= 0)
2828 ? avopts->multixact_freeze_min_age
2830
2831 multixact_freeze_table_age = (avopts &&
2832 avopts->multixact_freeze_table_age >= 0)
2833 ? avopts->multixact_freeze_table_age
2835
2837 tab->at_relid = relid;
2838 tab->at_sharedrel = classForm->relisshared;
2839
2840 /*
2841 * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2842 * that vacuum() skips toast relations. Also note we tell vacuum() to
2843 * skip vac_update_datfrozenxid(); we'll do that separately.
2844 */
2845 tab->at_params.options =
2849 (doanalyze ? VACOPT_ANALYZE : 0) |
2851
2852 /*
2853 * index_cleanup and truncate are unspecified at first in autovacuum.
2854 * They will be filled in with usable values using their reloptions
2855 * (or reloption defaults) later.
2856 */
2859 /* As of now, we don't support parallel vacuum for autovacuum */
2860 tab->at_params.nworkers = -1;
2861 tab->at_params.freeze_min_age = freeze_min_age;
2862 tab->at_params.freeze_table_age = freeze_table_age;
2863 tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2864 tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2866 tab->at_params.log_vacuum_min_duration = log_vacuum_min_duration;
2867 tab->at_params.log_analyze_min_duration = log_analyze_min_duration;
2869
2870 /*
2871 * Later, in vacuum_rel(), we check reloptions for any
2872 * vacuum_max_eager_freeze_failure_rate override.
2873 */
2876 avopts->vacuum_cost_limit : 0;
2878 avopts->vacuum_cost_delay : -1;
2879 tab->at_relname = NULL;
2880 tab->at_nspname = NULL;
2881 tab->at_datname = NULL;
2882
2883 /*
2884 * If any of the cost delay parameters has been set individually for
2885 * this table, disable the balancing algorithm.
2886 */
2887 tab->at_dobalance =
2888 !(avopts && (avopts->vacuum_cost_limit > 0 ||
2889 avopts->vacuum_cost_delay >= 0));
2890 }
2891
2892 if (free_avopts)
2893 pfree(avopts);
2895 return tab;
2896}
int Log_autovacuum_min_duration
Definition autovacuum.c:135
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)
int Log_autoanalyze_min_duration
Definition autovacuum.c:136
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1435
int nworkers
Definition vacuum.h:251
int freeze_table_age
Definition vacuum.h:221
VacOptValue truncate
Definition vacuum.h:236
int freeze_min_age
Definition vacuum.h:220
int log_vacuum_min_duration
Definition vacuum.h:227
int multixact_freeze_min_age
Definition vacuum.h:222
int multixact_freeze_table_age
Definition vacuum.h:224
Oid toast_parent
Definition vacuum.h:237
VacOptValue index_cleanup
Definition vacuum.h:235
int log_analyze_min_duration
Definition vacuum.h:231
double max_eager_freeze_failure_rate
Definition vacuum.h:244
double vacuum_max_eager_freeze_failure_rate
Definition vacuum.c:81
#define VACOPT_SKIP_LOCKED
Definition vacuum.h:185
#define VACOPT_SKIP_DATABASE_STATS
Definition vacuum.h:189
@ VACOPTVALUE_UNSPECIFIED
Definition vacuum.h:202
#define VACOPT_PROCESS_MAIN
Definition vacuum.h:186

References 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(), fb(), VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, GETSTRUCT(), HASH_FIND, hash_search(), heap_freetuple(), HeapTupleIsValid, VacuumParams::index_cleanup, InvalidOid, VacuumParams::is_wraparound, VacuumParams::log_analyze_min_duration, Log_autoanalyze_min_duration, Log_autovacuum_min_duration, VacuumParams::log_vacuum_min_duration, VacuumParams::max_eager_freeze_failure_rate, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, VacuumParams::nworkers, ObjectIdGetDatum(), VacuumParams::options, palloc_object, pfree(), recheck_relation_needs_vacanalyze(), SearchSysCacheCopy1, VacuumParams::toast_parent, VacuumParams::truncate, VACOPT_ANALYZE, VACOPT_PROCESS_MAIN, VACOPT_SKIP_DATABASE_STATS, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, VACOPTVALUE_UNSPECIFIED, and vacuum_max_eager_freeze_failure_rate.

Referenced by do_autovacuum().

◆ VacuumUpdateCosts()

void VacuumUpdateCosts ( void  )

Definition at line 1644 of file autovacuum.c.

1645{
1646 if (MyWorkerInfo)
1647 {
1650 else if (autovacuum_vac_cost_delay >= 0)
1652 else
1653 /* fall back to VacuumCostDelay */
1655
1657 }
1658 else
1659 {
1660 /* Must be explicit VACUUM or ANALYZE */
1663 }
1664
1665 /*
1666 * If configuration changes are allowed to impact VacuumCostActive, make
1667 * sure it is updated.
1668 */
1671 else if (vacuum_cost_delay > 0)
1672 VacuumCostActive = true;
1673 else
1674 {
1675 VacuumCostActive = false;
1677 }
1678
1679 /*
1680 * Since the cost logging requires a lock, avoid rendering the log message
1681 * in case we are using a message level where the log wouldn't be emitted.
1682 */
1684 {
1685 Oid dboid,
1686 tableoid;
1687
1689
1691 dboid = MyWorkerInfo->wi_dboid;
1692 tableoid = MyWorkerInfo->wi_tableoid;
1694
1695 elog(DEBUG2,
1696 "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1697 dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1699 vacuum_cost_delay > 0 ? "yes" : "no",
1700 VacuumFailsafeActive ? "yes" : "no");
1701 }
1702}
double autovacuum_vac_cost_delay
Definition autovacuum.c:132
void AutoVacuumUpdateCostLimit(void)
bool message_level_is_interesting(int elevel)
Definition elog.c:273
bool VacuumCostActive
Definition globals.c:158
int VacuumCostBalance
Definition globals.c:157
double VacuumCostDelay
Definition globals.c:155
double vacuum_cost_delay
Definition vacuum.c:91
bool VacuumFailsafeActive
Definition vacuum.c:110

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

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

Variable Documentation

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

◆ autovacuum_anl_scale

double autovacuum_anl_scale

Definition at line 128 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 127 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

◆ autovacuum_max_workers

int autovacuum_max_workers

◆ autovacuum_multixact_freeze_max_age

int autovacuum_multixact_freeze_max_age

◆ autovacuum_naptime

◆ autovacuum_start_daemon

bool autovacuum_start_daemon = false

Definition at line 117 of file autovacuum.c.

Referenced by autovac_init(), AutoVacuumingActive(), and removable_cutoff().

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 132 of file autovacuum.c.

Referenced by VacuumUpdateCosts().

◆ autovacuum_vac_cost_limit

int autovacuum_vac_cost_limit

Definition at line 133 of file autovacuum.c.

Referenced by AutoVacuumUpdateCostLimit().

◆ autovacuum_vac_ins_scale

double autovacuum_vac_ins_scale

Definition at line 126 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 125 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_max_thresh

int autovacuum_vac_max_thresh

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 124 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 122 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 120 of file autovacuum.c.

Referenced by dead_items_alloc(), and ginInsertCleanup().

◆ autovacuum_worker_slots

◆ AutoVacuumShmem

◆ av_storage_param_cost_delay

double av_storage_param_cost_delay = -1
static

Definition at line 151 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 152 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 162 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 163 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 164 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 165 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 155 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and avl_sigusr2_handler().

◆ Log_autoanalyze_min_duration

int Log_autoanalyze_min_duration = 600000

Definition at line 136 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = 600000

Definition at line 135 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

◆ recentMulti

MultiXactId recentMulti
static

Definition at line 159 of file autovacuum.c.

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

◆ recentXid

TransactionId recentXid
static

Definition at line 158 of file autovacuum.c.

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