PostgreSQL Source Code git master
Loading...
Searching...
No Matches
autovacuum.c File Reference
#include "postgres.h"
#include <math.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 "funcapi.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/fd.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 "storage/subsystems.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 "utils/tuplestore.h"
#include "utils/wait_event.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
 
struct  AutoVacuumScores
 
struct  TableToProcess
 

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 void AutoVacuumShmemRequest (void *arg)
 
static void AutoVacuumShmemInit (void *arg)
 
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 relation_needs_vacanalyze (Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, int elevel, bool *dovacuum, bool *doanalyze, bool *wraparound, AutoVacuumScores *scores)
 
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)
 
static int TableToProcessComparator (const ListCell *a, const ListCell *b)
 
bool AutoVacuumingActive (void)
 
bool AutoVacuumRequestWork (AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
 
void autovac_init (void)
 
bool check_autovacuum_work_mem (int *newval, void **extra, GucSource source)
 
Datum pg_stat_get_autovacuum_scores (PG_FUNCTION_ARGS)
 

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_freeze_score_weight = 1.0
 
double autovacuum_multixact_freeze_score_weight = 1.0
 
double autovacuum_vacuum_score_weight = 1.0
 
double autovacuum_vacuum_insert_score_weight = 1.0
 
double autovacuum_analyze_score_weight = 1.0
 
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
 
const ShmemCallbacks AutoVacuumShmemCallbacks
 
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 264 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 150 of file autovacuum.c.

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 149 of file autovacuum.c.

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

Definition at line 282 of file autovacuum.c.

Typedef Documentation

◆ autovac_table

◆ AutoVacuumWorkItem

◆ av_relation

◆ avl_dbase

◆ avw_dbase

◆ WorkerInfo

Definition at line 251 of file autovacuum.c.

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 

Definition at line 258 of file autovacuum.c.

259{
260 AutoVacForkFailed, /* failed trying to start a worker */
261 AutoVacRebalance, /* rebalance the cost limits */
AutoVacuumSignal
Definition autovacuum.c:259
@ AutoVacRebalance
Definition autovacuum.c:261
@ AutoVacForkFailed
Definition autovacuum.c:260

Function Documentation

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3520 of file autovacuum.c.

3521{
3523 return;
3524 else if (!pgstat_track_counts)
3526 (errmsg("autovacuum not started because of misconfiguration"),
3527 errhint("Enable the \"track_counts\" option.")));
3528 else
3530}
static void check_av_worker_gucs(void)
bool autovacuum_start_daemon
Definition autovacuum.c:123
int errhint(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:37
#define ereport(elevel,...)
Definition elog.h:152
static char * errmsg
bool pgstat_track_counts
Definition pgstat.c:204

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

1800{
1801 dlist_iter iter;
1803 int nworkers_for_balance = 0;
1804
1806
1809
1811 {
1812 WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1813
1814 if (worker->wi_proc == NULL ||
1816 continue;
1817
1819 }
1820
1824}
static bool pg_atomic_unlocked_test_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:189
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition atomics.h:269
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:232
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition autovacuum.c:311
#define Assert(condition)
Definition c.h:1002
#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:1885
static int fb(int x)
pg_atomic_uint32 av_nworkersForBalance
Definition autovacuum.c:308
dlist_head av_runningWorkers
Definition autovacuum.c:305
PGPROC * wi_proc
Definition autovacuum.c:245
pg_atomic_flag wi_dobalance
Definition autovacuum.c:247
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 3391 of file autovacuum.c.

3392{
3393#define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3395 int len;
3396
3397 /* Report the command and possible options */
3398 if (tab->at_params.options & VACOPT_VACUUM)
3400 "autovacuum: VACUUM%s",
3401 tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3402 else
3404 "autovacuum: ANALYZE");
3405
3406 /*
3407 * Report the qualified name of the relation.
3408 */
3409 len = strlen(activity);
3410
3412 " %s.%s%s", tab->at_nspname, tab->at_relname,
3413 tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3414
3415 /* Set statement_timestamp() to current time for pg_stat_activity */
3417
3419}
#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:261
uint32 options
Definition vacuum.h:218
bool is_wraparound
Definition vacuum.h:225
char * at_nspname
Definition autovacuum.c:218
char * at_relname
Definition autovacuum.c:217
VacuumParams at_params
Definition autovacuum.c:213
#define VACOPT_VACUUM
Definition vacuum.h:179
#define VACOPT_ANALYZE
Definition vacuum.h:180
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:916

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

3428{
3429 char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3430 char blk[12 + 2];
3431 int len;
3432
3433 switch (workitem->avw_type)
3434 {
3437 "autovacuum: BRIN summarize");
3438 break;
3439 }
3440
3441 /*
3442 * Report the qualified name of the relation, and the block number if any
3443 */
3444 len = strlen(activity);
3445
3446 if (BlockNumberIsValid(workitem->avw_blockNumber))
3447 snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3448 else
3449 blk[0] = '\0';
3450
3452 " %s.%s%s", nspname, relname, blk);
3453
3454 /* Set statement_timestamp() to current time for pg_stat_activity */
3456
3458}
@ AVW_BRINSummarizeRange
Definition autovacuum.h:25
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition block.h:71
NameData relname
Definition pg_class.h:40

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

412{
414
416
417 /* Release postmaster's working memory context */
419 {
422 }
423
425
427 (errmsg_internal("autovacuum launcher started")));
428
429 if (PostAuthDelay)
430 pg_usleep(PostAuthDelay * 1000000L);
431
433
434 /*
435 * Set up signal handlers. We operate on databases much like a regular
436 * backend, so we use the same signal handling. See equivalent code in
437 * tcop/postgres.c.
438 */
442 /* SIGQUIT handler was already set up by InitPostmasterChild */
443
444 InitializeTimeouts(); /* establishes SIGALRM handler */
445
451
452 /*
453 * Create a per-backend PGPROC struct in shared memory. We must do this
454 * before we can use LWLocks or access any shared memory.
455 */
456 InitProcess();
457
458 /* Early initialization */
459 BaseInit();
460
462
464
465 /*
466 * Create a memory context that we will do all our work in. We do this so
467 * that we can reset the context during error recovery and thereby avoid
468 * possible memory leaks.
469 */
471 "Autovacuum Launcher",
474
475 /*
476 * If an exception is encountered, processing resumes here.
477 *
478 * This code is a stripped down version of PostgresMain error recovery.
479 *
480 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
481 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
482 * signals other than SIGQUIT will be blocked until we complete error
483 * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
484 * call redundant, but it is not since InterruptPending might be set
485 * already.
486 */
487 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
488 {
489 /* since not using PG_TRY, must reset error stack by hand */
491
492 /* Prevents interrupts while cleaning up */
494
495 /* Forget any pending QueryCancel or timeout request */
497 QueryCancelPending = false; /* second to avoid race condition */
498
499 /* Report the error to the server log */
501
502 /* Abort the current transaction in order to recover */
504
505 /*
506 * Release any other resources, for the case where we were not in a
507 * transaction.
508 */
513 /* this is probably dead code, but let's be safe: */
516 AtEOXact_Buffers(false);
518 AtEOXact_Files(false);
519 AtEOXact_HashTables(false);
520
521 /*
522 * Now return to normal top-level context and clear ErrorContext for
523 * next time.
524 */
527
528 /* Flush any leaked data in the top-level context */
530
531 /* don't leave dangling pointers to freed memory */
534
535 /* Now we can allow interrupts again */
537
538 /* if in shutdown mode, no need for anything further; just go away */
541
542 /*
543 * Sleep at least 1 second after any error. We don't want to be
544 * filling the error logs as fast as we can.
545 */
546 pg_usleep(1000000L);
547 }
548
549 /* We can now handle ereport(ERROR) */
551
552 /* must unblock signals before calling rebuild_database_list */
554
555 /*
556 * Set always-secure search path. Launcher doesn't connect to a database,
557 * so this has no effect.
558 */
559 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
560
561 /*
562 * Force zero_damaged_pages OFF in the autovac process, even if it is set
563 * in postgresql.conf. We don't really want such a dangerous option being
564 * applied non-interactively.
565 */
566 SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
567
568 /*
569 * Force settable timeouts off to avoid letting these settings prevent
570 * regular maintenance from being executed.
571 */
572 SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
573 SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
574 SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
575 SetConfigOption("idle_in_transaction_session_timeout", "0",
577
578 /*
579 * Force default_transaction_isolation to READ COMMITTED. We don't want
580 * to pay the overhead of serializable mode, nor add any risk of causing
581 * deadlocks or delaying other transactions.
582 */
583 SetConfigOption("default_transaction_isolation", "read committed",
585
586 /*
587 * Even when system is configured to use a different fetch consistency,
588 * for autovac we always want fresh stats.
589 */
590 SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
591
592 /*
593 * In emergency mode, just start a worker (unless shutdown was requested)
594 * and go away.
595 */
596 if (!AutoVacuumingActive())
597 {
600 proc_exit(0); /* done */
601 }
602
603 /*
604 * Create the initial database list. The invariant we want this list to
605 * keep is that it's ordered by decreasing next_worker. As soon as an
606 * entry is updated to a higher time, it will be moved to the front (which
607 * is correct because the only operation is to add autovacuum_naptime to
608 * the entry, and time always increases).
609 */
611
612 /* loop until shutdown request */
614 {
615 struct timeval nap;
617 bool can_launch;
618
619 /*
620 * This loop is a bit different from the normal use of WaitLatch,
621 * because we'd like to sleep before the first launch of a child
622 * process. So it's WaitLatch, then ResetLatch, then check for
623 * wakening conditions.
624 */
625
627
628 /*
629 * Wait until naptime expires or we get some type of signal (all the
630 * signal handlers will wake us by calling SetLatch).
631 */
634 (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
636
638
640
641 /*
642 * a worker finished, or postmaster signaled failure to start a worker
643 */
644 if (got_SIGUSR2)
645 {
646 got_SIGUSR2 = false;
647
648 /* rebalance cost limits, if needed */
650 {
655 }
656
658 {
659 /*
660 * If the postmaster failed to start a new worker, we sleep
661 * for a little while and resend the signal. The new worker's
662 * state is still in memory, so this is sufficient. After
663 * that, we restart the main loop.
664 *
665 * XXX should we put a limit to the number of times we retry?
666 * I don't think it makes much sense, because a future start
667 * of a worker will continue to fail in the same way.
668 */
670 pg_usleep(1000000L); /* 1s */
672 continue;
673 }
674 }
675
676 /*
677 * There are some conditions that we need to check before trying to
678 * start a worker. First, we need to make sure that there is a worker
679 * slot available. Second, we need to make sure that no other worker
680 * failed while starting up.
681 */
682
685
687
689 {
690 int waittime;
692
693 /*
694 * We can't launch another worker when another one is still
695 * starting up (or failed while doing so), so just sleep for a bit
696 * more; that worker will wake us up again as soon as it's ready.
697 * We will only wait autovacuum_naptime seconds (up to a maximum
698 * of 60 seconds) for this to happen however. Note that failure
699 * to connect to a particular database is not a problem here,
700 * because the worker removes itself from the startingWorker
701 * pointer before trying to connect. Problems detected by the
702 * postmaster (like fork() failure) are also reported and handled
703 * differently. The only problems that may cause this code to
704 * fire are errors in the earlier sections of AutoVacWorkerMain,
705 * before the worker removes the WorkerInfo from the
706 * startingWorker pointer.
707 */
708 waittime = Min(autovacuum_naptime, 60) * 1000;
710 waittime))
711 {
714
715 /*
716 * No other process can put a worker in starting mode, so if
717 * startingWorker is still INVALID after exchanging our lock,
718 * we assume it's the same one we saw above (so we don't
719 * recheck the launch time).
720 */
722 {
724 worker->wi_dboid = InvalidOid;
725 worker->wi_tableoid = InvalidOid;
726 worker->wi_sharedrel = false;
727 worker->wi_proc = NULL;
728 worker->wi_launchtime = 0;
730 &worker->wi_links);
733 errmsg("autovacuum worker took too long to start; canceled"));
734 }
735 }
736 else
737 can_launch = false;
738 }
739 LWLockRelease(AutovacuumLock); /* either shared or exclusive */
740
741 /* if we can't do anything, just go back to sleep */
742 if (!can_launch)
743 continue;
744
745 /* We're OK to start a new worker */
746
748 {
749 /*
750 * Special case when the list is empty: start a worker right away.
751 * This covers the initial case, when no database is in pgstats
752 * (thus the list is empty). Note that the constraints in
753 * launcher_determine_sleep keep us from starting workers too
754 * quickly (at most once every autovacuum_naptime when the list is
755 * empty).
756 */
758 }
759 else
760 {
761 /*
762 * because rebuild_database_list constructs a list with most
763 * distant adl_next_worker first, we obtain our database from the
764 * tail of the list.
765 */
767
769
770 /*
771 * launch a worker if next_worker is right now or it is in the
772 * past
773 */
774 if (TimestampDifferenceExceeds(avdb->adl_next_worker,
775 current_time, 0))
777 }
778 }
779
781}
void pgaio_error_cleanup(void)
Definition aio.c:1175
static Oid do_start_worker(void)
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition autovacuum.c:847
static volatile sig_atomic_t got_SIGUSR2
Definition autovacuum.c:165
static void avl_sigusr2_handler(SIGNAL_ARGS)
static bool av_worker_available(void)
int autovacuum_naptime
Definition autovacuum.c:127
bool AutoVacuumingActive(void)
static pg_noreturn void AutoVacLauncherShutdown(void)
Definition autovacuum.c:832
static void launch_worker(TimestampTz now)
static dlist_head DatabaseList
Definition autovacuum.c:325
static void rebuild_database_list(Oid newdb)
Definition autovacuum.c:931
static MemoryContext DatabaseListCxt
Definition autovacuum.c:326
static void autovac_recalculate_workers_for_balance(void)
static MemoryContext AutovacMemCxt
Definition autovacuum.c:178
static void ProcessAutoVacLauncherInterrupts(void)
Definition autovacuum.c:787
sigset_t UnBlockSig
Definition pqsignal.c:22
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition timestamp.c:1789
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1649
void AtEOXact_Buffers(bool isCommit)
Definition bufmgr.c:4222
void UnlockBuffers(void)
Definition bufmgr.c:5875
#define Min(x, y)
Definition c.h:1131
int64 TimestampTz
Definition timestamp.h:39
void AtEOXact_HashTables(bool isCommit)
Definition dynahash.c:1864
void EmitErrorReport(void)
Definition elog.c:1883
ErrorContextCallback * error_context_stack
Definition elog.c:100
void FlushErrorState(void)
Definition elog.c:2063
sigjmp_buf * PG_exception_stack
Definition elog.c:102
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG1
Definition elog.h:31
void AtEOXact_Files(bool isCommit)
Definition fd.c:3212
volatile sig_atomic_t QueryCancelPending
Definition globals.c:33
struct Latch * MyLatch
Definition globals.c:65
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4234
@ 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:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
void LWLockReleaseAll(void)
Definition lwlock.c:1866
@ LW_SHARED
Definition lwlock.h:105
@ LW_EXCLUSIVE
Definition lwlock.h:104
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
MemoryContext TopMemoryContext
Definition mcxt.c:167
MemoryContext PostmasterContext
Definition mcxt.c:169
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:475
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h:138
@ NormalProcessing
Definition miscadmin.h:481
@ InitProcessing
Definition miscadmin.h:480
#define GetProcessingMode()
Definition miscadmin.h:490
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
#define SetProcessingMode(mode)
Definition miscadmin.h:492
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
void SendPostmasterSignal(PMSignalReason reason)
Definition pmsignal.c:164
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition pmsignal.h:40
#define pqsignal
Definition port.h:548
#define PG_SIG_IGN
Definition port.h:552
#define PG_SIG_DFL
Definition port.h:551
int PostAuthDelay
Definition postgres.c:105
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3172
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3155
#define InvalidOid
void BaseInit(void)
Definition postinit.c:622
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
Definition postinit.c:722
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:696
void init_ps_display(const char *fixed_part)
Definition ps_status.c:286
void ReleaseAuxProcessResources(bool isCommit)
Definition resowner.c:1026
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:393
dclist_head av_freeWorkers
Definition autovacuum.c:304
WorkerInfo av_startingWorker
Definition autovacuum.c:306
sig_atomic_t av_signal[AutoVacNumSignals]
Definition autovacuum.c:303
TimestampTz wi_launchtime
Definition autovacuum.c:246
dlist_node wi_links
Definition autovacuum.c:242
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:83
#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:3504

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_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, NormalProcessing, PG_exception_stack, PG_SIG_DFL, PG_SIG_IGN, 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 832 of file autovacuum.c.

833{
835 (errmsg_internal("autovacuum launcher shutting down")));
836 proc_exit(0); /* done */
837}

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

3352{
3354 VacuumRelation *rel;
3355 List *rel_list;
3358
3359 /* Let pgstat know what we're doing */
3361
3362 /* Create a context that vacuum() can use as cross-transaction storage */
3364 "Vacuum",
3366
3367 /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3369 rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3371 rel_list = list_make1(rel);
3373
3374 vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3375
3377}
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:161
#define NIL
Definition pg_list.h:68
#define list_make1(x1)
Definition pg_list.h:244
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 3478 of file autovacuum.c.

3480{
3481 int i;
3482 bool result = false;
3483
3485
3486 /*
3487 * Locate an unused work item and fill it with the given data.
3488 */
3489 for (i = 0; i < NUM_WORKITEMS; i++)
3490 {
3492
3493 if (workitem->avw_used)
3494 continue;
3495
3496 workitem->avw_used = true;
3497 workitem->avw_active = false;
3498 workitem->avw_type = type;
3499 workitem->avw_database = MyDatabaseId;
3500 workitem->avw_relation = relationId;
3501 workitem->avw_blockNumber = blkno;
3502 result = true;
3503
3504 /* done */
3505 break;
3506 }
3507
3509
3510 return result;
3511}
#define NUM_WORKITEMS
Definition autovacuum.c:282
uint32 result
Oid MyDatabaseId
Definition globals.c:96
int i
Definition isn.c:77
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition autovacuum.c:307
const char * type

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

Referenced by brininsert().

◆ AutoVacuumShmemInit()

static void AutoVacuumShmemInit ( void arg)
static

Definition at line 3560 of file autovacuum.c.

3561{
3562 WorkerInfo worker;
3563
3569
3570 worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3572
3573 /* initialize the WorkerInfo free list */
3574 for (int i = 0; i < autovacuum_worker_slots; i++)
3575 {
3577 &worker[i].wi_links);
3578 pg_atomic_init_flag(&worker[i].wi_dobalance);
3579 }
3580
3582}
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition atomics.h:214
static void pg_atomic_init_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:163
int autovacuum_worker_slots
Definition autovacuum.c:124
struct WorkerInfoData * WorkerInfo
Definition autovacuum.c:251
#define MAXALIGN(LEN)
Definition c.h:955
static void dclist_init(dclist_head *head)
Definition ilist.h:671

References autovacuum_worker_slots, AutoVacuumShmem, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_nworkersForBalance, AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_startingWorker, AutoVacuumShmemStruct::av_workItems, dclist_init(), dclist_push_head(), dlist_init(), fb(), i, MAXALIGN, NUM_WORKITEMS, pg_atomic_init_flag(), pg_atomic_init_u32(), and WorkerInfoData::wi_links.

◆ AutoVacuumShmemRequest()

static void AutoVacuumShmemRequest ( void arg)
static

Definition at line 3537 of file autovacuum.c.

3538{
3539 Size size;
3540
3541 /*
3542 * Need the fixed struct and the array of WorkerInfoData.
3543 */
3544 size = sizeof(AutoVacuumShmemStruct);
3545 size = MAXALIGN(size);
3547 sizeof(WorkerInfoData)));
3548
3549 ShmemRequestStruct(.name = "AutoVacuum Data",
3550 .size = size,
3551 .ptr = (void **) &AutoVacuumShmem,
3552 );
3553}
size_t Size
Definition c.h:748
Size add_size(Size s1, Size s2)
Definition mcxt.c:1733
Size mul_size(Size s1, Size s2)
Definition mcxt.c:1752
#define ShmemRequestStruct(...)
Definition shmem.h:176
const char * name

References add_size(), autovacuum_worker_slots, AutoVacuumShmem, MAXALIGN, mul_size(), name, and ShmemRequestStruct.

◆ AutoVacuumUpdateCostLimit()

void AutoVacuumUpdateCostLimit ( void  )

Definition at line 1753 of file autovacuum.c.

1754{
1755 if (!MyWorkerInfo)
1756 return;
1757
1758 /*
1759 * note: in cost_limit, zero also means use value from elsewhere, because
1760 * zero is not a valid value.
1761 */
1762
1765 else
1766 {
1768
1771 else
1773
1774 /* Only balance limit if no cost-related storage parameters specified */
1776 return;
1777
1779
1781
1782 /* There is at least 1 autovac worker (this worker) */
1783 if (nworkers_for_balance <= 0)
1784 elog(ERROR, "nworkers_for_balance must be > 0");
1785
1787 }
1788}
int autovacuum_vac_cost_limit
Definition autovacuum.c:143
static int av_storage_param_cost_limit
Definition autovacuum.c:162
static WorkerInfo MyWorkerInfo
Definition autovacuum.c:363
#define Max(x, y)
Definition c.h:1125
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
int VacuumCostLimit
Definition globals.c:157
int vacuum_cost_limit
Definition vacuum.c:93

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

1397{
1399}

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

1419{
1421 Oid dbid;
1422
1424
1425 /* Release postmaster's working memory context */
1427 {
1430 }
1431
1433
1435
1436 /*
1437 * Set up signal handlers. We operate on databases much like a regular
1438 * backend, so we use the same signal handling. See equivalent code in
1439 * tcop/postgres.c.
1440 */
1442
1443 /*
1444 * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1445 * means abort and exit cleanly, and SIGQUIT means abandon ship.
1446 */
1449 /* SIGQUIT handler was already set up by InitPostmasterChild */
1450
1451 InitializeTimeouts(); /* establishes SIGALRM handler */
1452
1458
1459 /*
1460 * Create a per-backend PGPROC struct in shared memory. We must do this
1461 * before we can use LWLocks or access any shared memory.
1462 */
1463 InitProcess();
1464
1465 /* Early initialization */
1466 BaseInit();
1467
1468 /*
1469 * If an exception is encountered, processing resumes here.
1470 *
1471 * Unlike most auxiliary processes, we don't attempt to continue
1472 * processing after an error; we just clean up and exit. The autovac
1473 * launcher is responsible for spawning another worker later.
1474 *
1475 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
1476 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
1477 * signals other than SIGQUIT will be blocked until we exit. It might
1478 * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
1479 * it is not since InterruptPending might be set already.
1480 */
1481 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1482 {
1483 /* since not using PG_TRY, must reset error stack by hand */
1485
1486 /* Prevents interrupts while cleaning up */
1488
1489 /* Report the error to the server log */
1491
1492 /*
1493 * We can now go away. Note that because we called InitProcess, a
1494 * callback was registered to do ProcKill, which will clean up
1495 * necessary state.
1496 */
1497 proc_exit(0);
1498 }
1499
1500 /* We can now handle ereport(ERROR) */
1502
1504
1505 /*
1506 * Set always-secure search path, so malicious users can't redirect user
1507 * code (e.g. pg_index.indexprs). (That code runs in a
1508 * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1509 * take control of the entire autovacuum worker in any case.)
1510 */
1511 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1512
1513 /*
1514 * Force zero_damaged_pages OFF in the autovac process, even if it is set
1515 * in postgresql.conf. We don't really want such a dangerous option being
1516 * applied non-interactively.
1517 */
1518 SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1519
1520 /*
1521 * Force settable timeouts off to avoid letting these settings prevent
1522 * regular maintenance from being executed.
1523 */
1524 SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1525 SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1526 SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1527 SetConfigOption("idle_in_transaction_session_timeout", "0",
1529
1530 /*
1531 * Force default_transaction_isolation to READ COMMITTED. We don't want
1532 * to pay the overhead of serializable mode, nor add any risk of causing
1533 * deadlocks or delaying other transactions.
1534 */
1535 SetConfigOption("default_transaction_isolation", "read committed",
1537
1538 /*
1539 * Force synchronous replication off to allow regular maintenance even if
1540 * we are waiting for standbys to connect. This is important to ensure we
1541 * aren't blocked from performing anti-wraparound tasks.
1542 */
1544 SetConfigOption("synchronous_commit", "local",
1546
1547 /*
1548 * Even when system is configured to use a different fetch consistency,
1549 * for autovac we always want fresh stats.
1550 */
1551 SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
1552
1553 /*
1554 * Get the info about the database we're going to work on.
1555 */
1557
1558 /*
1559 * beware of startingWorker being INVALID; this should normally not
1560 * happen, but if a worker fails after forking and before this, the
1561 * launcher might have decided to remove it from the queue and start
1562 * again.
1563 */
1565 {
1567
1569 dbid = MyWorkerInfo->wi_dboid;
1571
1572 /* insert into the running list */
1575
1576 /*
1577 * remove from the "starting" pointer, so that the launcher can start
1578 * a new worker if required
1579 */
1582
1584
1585 /* wake up the launcher */
1588 {
1589 int pid = GetPGProcByNumber(launcherProc)->pid;
1590
1591 if (pid != 0)
1592 kill(pid, SIGUSR2);
1593 }
1594 }
1595 else
1596 {
1597 /* no worker entry for me, go away */
1598 elog(WARNING, "autovacuum worker started without a worker entry");
1599 dbid = InvalidOid;
1601 }
1602
1603 if (OidIsValid(dbid))
1604 {
1605 char dbname[NAMEDATALEN];
1606
1607 /*
1608 * Report autovac startup to the cumulative stats system. We
1609 * deliberately do this before InitPostgres, so that the
1610 * last_autovac_time will get updated even if the connection attempt
1611 * fails. This is to prevent autovac from getting "stuck" repeatedly
1612 * selecting an unopenable database, rather than making any progress
1613 * on stuff it can connect to.
1614 */
1616
1617 /*
1618 * Connect to the selected database, specifying no particular user,
1619 * and ignoring datallowconn. Collect the database's name for
1620 * display.
1621 *
1622 * Note: if we have selected a just-deleted database (due to using
1623 * stale stats info), we'll fail and exit here.
1624 */
1627 dbname);
1631 (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1632
1633 if (PostAuthDelay)
1634 pg_usleep(PostAuthDelay * 1000000L);
1635
1636 /* And do an appropriate amount of work */
1639 do_autovacuum();
1640 }
1641
1642 /* All done, go away */
1643 proc_exit(0);
1644}
static void FreeWorkerInfo(int code, Datum arg)
static TransactionId recentXid
Definition autovacuum.c:168
static void do_autovacuum(void)
static MultiXactId recentMulti
Definition autovacuum.c:169
#define OidIsValid(objectId)
Definition c.h:917
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:509
MultiXactId ReadNextMultiXactId(void)
Definition multixact.c:679
#define NAMEDATALEN
#define die(msg)
void pgstat_report_autovac(Oid dboid)
unsigned int Oid
#define GetPGProcByNumber(n)
Definition proc.h:506
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
int ProcNumber
Definition procnumber.h:24
static void set_ps_display(const char *activity)
Definition ps_status.h:40
PGPROC * MyProc
Definition proc.c:71
PROC_HDR * ProcGlobal
Definition proc.c:74
char * dbname
Definition streamutil.c:49
pg_atomic_uint32 avLauncherProc
Definition proc.h:491
static TransactionId ReadNextTransactionId(void)
Definition transam.h:375
#define kill(pid, sig)
Definition win32_port.h:507
int synchronous_commit
Definition xact.c:89
@ SYNCHRONOUS_COMMIT_LOCAL_FLUSH
Definition xact.h:72

References Assert, AutoVacuumShmem, AutoVacuumShmemStruct::av_runningWorkers, AutoVacuumShmemStruct::av_startingWorker, PROC_HDR::avLauncherProc, BaseInit(), dbname, DEBUG1, die, dlist_push_head(), do_autovacuum(), elog, EmitErrorReport(), ereport, errmsg_internal(), error_context_stack, fb(), FloatExceptionHandler(), FreeWorkerInfo(), GetPGProcByNumber, GetProcessingMode, HOLD_INTERRUPTS, INIT_PG_OVERRIDE_ALLOW_CONNS, init_ps_display(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, INVALID_PROC_NUMBER, InvalidOid, kill, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MemoryContextDelete(), MyProc, MyWorkerInfo, NAMEDATALEN, NormalProcessing, OidIsValid, on_shmem_exit(), pg_atomic_read_u32(), PG_exception_stack, PG_SIG_DFL, PG_SIG_IGN, pg_usleep(), PGC_S_OVERRIDE, PGC_SUSET, pgstat_report_autovac(), PostAuthDelay, PostmasterContext, pqsignal, proc_exit(), ProcGlobal, 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 3614 of file autovacuum.c.

3615{
3616 int free_slots;
3617 int reserved_slots;
3618
3620
3623
3624 return free_slots > reserved_slots;
3625}
int autovacuum_max_workers
Definition autovacuum.c:125
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 1403 of file autovacuum.c.

1404{
1405 got_SIGUSR2 = true;
1407}
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 3588 of file autovacuum.c.

3589{
3590 /*
3591 * -1 indicates fallback.
3592 *
3593 * If we haven't yet changed the boot_val default of -1, just let it be.
3594 * Autovacuum will look to maintenance_work_mem instead.
3595 */
3596 if (*newval == -1)
3597 return true;
3598
3599 /*
3600 * We clamp manually-set values to at least 64kB. Since
3601 * maintenance_work_mem is always set to at least this value, do the same
3602 * here.
3603 */
3604 if (*newval < 64)
3605 *newval = 64;
3606
3607 return true;
3608}
#define newval

References newval.

◆ check_av_worker_gucs()

static void check_av_worker_gucs ( void  )
static

Definition at line 3631 of file autovacuum.c.

3632{
3636 errmsg("\"%s\" (%d) should be less than or equal to \"%s\" (%d)",
3637 "autovacuum_max_workers", autovacuum_max_workers,
3638 "autovacuum_worker_slots", autovacuum_worker_slots),
3639 errdetail("The server will only start up to \"%s\" (%d) autovacuum workers at a given time.",
3640 "autovacuum_worker_slots", autovacuum_worker_slots)));
3641}
int errcode(int sqlerrcode)
Definition elog.c:875
int errdetail(const char *fmt,...) pg_attribute_printf(1

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

1115{
1116 return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1117 ((const avl_dbase *) b)->adl_score);
1118}
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 1928 of file autovacuum.c.

1929{
1931 HeapTuple tuple;
1935 List *orphan_oids = NIL;
1936 HASHCTL ctl;
1938 ListCell *volatile cell;
1939 BufferAccessStrategy bstrategy;
1943 bool did_vacuum = false;
1944 bool found_concurrent_worker = false;
1945 int i;
1946
1947 /*
1948 * StartTransactionCommand and CommitTransactionCommand will automatically
1949 * switch to other contexts. We need this one to keep the list of
1950 * relations to vacuum/analyze across transactions.
1951 */
1953 "Autovacuum worker",
1956
1957 /* Start a transaction so our commands have one to play into. */
1959
1960 /*
1961 * This injection point is put in a transaction block to work with a wait
1962 * that uses a condition variable.
1963 */
1964 INJECTION_POINT("autovacuum-worker-start", NULL);
1965
1966 /*
1967 * Compute the multixact age for which freezing is urgent. This is
1968 * normally autovacuum_multixact_freeze_max_age, but may be less if
1969 * multixact members are bloated.
1970 */
1972
1973 /*
1974 * Find the pg_database entry and select the default freeze ages. We use
1975 * zero in template and nonconnectable databases, else the system-wide
1976 * default.
1977 */
1979 if (!HeapTupleIsValid(tuple))
1980 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1982
1983 if (dbForm->datistemplate || !dbForm->datallowconn)
1984 {
1989 }
1990 else
1991 {
1996 }
1997
1998 ReleaseSysCache(tuple);
1999
2000 /* StartTransactionCommand changed elsewhere */
2002
2004
2005 /* create a copy so we can use it after closing pg_class */
2007
2008 /* create hash table for toast <-> main relid mapping */
2009 ctl.keysize = sizeof(Oid);
2010 ctl.entrysize = sizeof(av_relation);
2011
2012 table_toast_map = hash_create("TOAST to main relid map",
2013 100,
2014 &ctl,
2016
2017 /*
2018 * Scan pg_class to determine which tables to vacuum.
2019 *
2020 * We do this in two passes: on the first one we collect the list of plain
2021 * relations and materialized views, and on the second one we collect
2022 * TOAST tables. The reason for doing the second pass is that during it we
2023 * want to use the main relation's pg_class.reloptions entry if the TOAST
2024 * table does not have any, and we cannot obtain it unless we know
2025 * beforehand what's the main table OID.
2026 *
2027 * We need to check TOAST tables separately because in cases with short,
2028 * wide tables there might be proportionally much more activity in the
2029 * TOAST table than in its parent.
2030 */
2032
2033 /*
2034 * On the first pass, we collect main tables to vacuum, and also the main
2035 * table relid to TOAST relid mapping.
2036 */
2037 while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2038 {
2041 Oid relid;
2042 bool dovacuum;
2043 bool doanalyze;
2044 bool wraparound;
2046
2047 if (classForm->relkind != RELKIND_RELATION &&
2048 classForm->relkind != RELKIND_MATVIEW)
2049 continue;
2050
2051 relid = classForm->oid;
2052
2053 /*
2054 * Check if it is a temp table (presumably, of some other backend's).
2055 * We cannot safely process other backends' temp tables.
2056 */
2057 if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2058 {
2059 /*
2060 * We just ignore it if the owning backend is still active and
2061 * using the temporary schema. Also, for safety, ignore it if the
2062 * namespace doesn't exist or isn't a temp namespace after all.
2063 */
2065 {
2066 /*
2067 * The table seems to be orphaned -- although it might be that
2068 * the owning backend has already deleted it and exited; our
2069 * pg_class scan snapshot is not necessarily up-to-date
2070 * anymore, so we could be looking at a committed-dead entry.
2071 * Remember it so we can try to delete it later.
2072 */
2074 }
2075 continue;
2076 }
2077
2078 /* Fetch reloptions and the pgstat entry for this table */
2080
2081 /* Check if it needs vacuum or analyze */
2084 DEBUG3,
2086 &scores);
2087
2088 /* Relations that need work are added to tables_to_process */
2089 if (dovacuum || doanalyze)
2090 {
2092
2093 table->oid = relid;
2094 table->score = scores.max;
2096 }
2097
2098 /*
2099 * Remember TOAST associations for the second pass. Note: we must do
2100 * this whether or not the table is going to be vacuumed, because we
2101 * don't automatically vacuum toast tables along the parent table.
2102 */
2103 if (OidIsValid(classForm->reltoastrelid))
2104 {
2106 bool found;
2107
2109 &classForm->reltoastrelid,
2110 HASH_ENTER, &found);
2111
2112 if (!found)
2113 {
2114 /* hash_search already filled in the key */
2115 hentry->ar_relid = relid;
2116 hentry->ar_hasrelopts = false;
2117 if (relopts != NULL)
2118 {
2119 hentry->ar_hasrelopts = true;
2120 memcpy(&hentry->ar_reloptions, relopts,
2121 sizeof(AutoVacOpts));
2122 }
2123 }
2124 }
2125
2126 /* Release stuff to avoid per-relation leakage */
2127 if (relopts)
2128 pfree(relopts);
2129 }
2130
2132
2133 /* second pass: check TOAST tables */
2134 ScanKeyInit(&key,
2138
2140 while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2141 {
2143 Oid relid;
2145 bool free_relopts = false;
2146 bool dovacuum;
2147 bool doanalyze;
2148 bool wraparound;
2150
2151 /*
2152 * We cannot safely process other backends' temp tables, so skip 'em.
2153 */
2154 if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2155 continue;
2156
2157 relid = classForm->oid;
2158
2159 /*
2160 * fetch reloptions -- if this toast table does not have them, try the
2161 * main rel
2162 */
2164 if (relopts)
2165 free_relopts = true;
2166 else
2167 {
2169 bool found;
2170
2171 hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2172 if (found && hentry->ar_hasrelopts)
2173 relopts = &hentry->ar_reloptions;
2174 }
2175
2178 DEBUG3,
2180 &scores);
2181
2182 /* ignore analyze for toast tables */
2183 if (dovacuum)
2184 {
2186
2187 table->oid = relid;
2188 table->score = scores.max;
2190 }
2191
2192 /* Release stuff to avoid leakage */
2193 if (free_relopts)
2194 pfree(relopts);
2195 }
2196
2199
2200 /*
2201 * Recheck orphan temporary tables, and if they still seem orphaned, drop
2202 * them. We'll eat a transaction per dropped table, which might seem
2203 * excessive, but we should only need to do anything as a result of a
2204 * previous backend crash, so this should not happen often enough to
2205 * justify "optimizing". Using separate transactions ensures that we
2206 * don't bloat the lock table if there are many temp tables to be dropped,
2207 * and it ensures that we don't lose work if a deletion attempt fails.
2208 */
2209 foreach(cell, orphan_oids)
2210 {
2211 Oid relid = lfirst_oid(cell);
2213 ObjectAddress object;
2214
2215 /*
2216 * Check for user-requested abort.
2217 */
2219
2220 /*
2221 * Try to lock the table. If we can't get the lock immediately,
2222 * somebody else is using (or dropping) the table, so it's not our
2223 * concern anymore. Having the lock prevents race conditions below.
2224 */
2226 continue;
2227
2228 /*
2229 * Re-fetch the pg_class tuple and re-check whether it still seems to
2230 * be an orphaned temp table. If it's not there or no longer the same
2231 * relation, ignore it.
2232 */
2234 if (!HeapTupleIsValid(tuple))
2235 {
2236 /* be sure to drop useless lock so we don't bloat lock table */
2238 continue;
2239 }
2241
2242 /*
2243 * Make all the same tests made in the loop above. In event of OID
2244 * counter wraparound, the pg_class entry we have now might be
2245 * completely unrelated to the one we saw before.
2246 */
2247 if (!((classForm->relkind == RELKIND_RELATION ||
2248 classForm->relkind == RELKIND_MATVIEW) &&
2249 classForm->relpersistence == RELPERSISTENCE_TEMP))
2250 {
2252 continue;
2253 }
2254
2256 {
2258 continue;
2259 }
2260
2261 /*
2262 * Try to lock the temp namespace, too. Even though we have lock on
2263 * the table itself, there's a risk of deadlock against an incoming
2264 * backend trying to clean out the temp namespace, in case this table
2265 * has dependencies (such as sequences) that the backend's
2266 * performDeletion call might visit in a different order. If we can
2267 * get AccessShareLock on the namespace, that's sufficient to ensure
2268 * we're not running concurrently with RemoveTempRelations. If we
2269 * can't, back off and let RemoveTempRelations do its thing.
2270 */
2272 classForm->relnamespace, 0,
2274 {
2276 continue;
2277 }
2278
2279 /* OK, let's delete it */
2280 ereport(LOG,
2281 (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2283 get_namespace_name(classForm->relnamespace),
2284 NameStr(classForm->relname))));
2285
2286 /*
2287 * Deletion might involve TOAST table access, so ensure we have a
2288 * valid snapshot.
2289 */
2291
2292 object.classId = RelationRelationId;
2293 object.objectId = relid;
2294 object.objectSubId = 0;
2299
2300 /*
2301 * To commit the deletion, end current transaction and start a new
2302 * one. Note this also releases the locks we took.
2303 */
2307
2308 /* StartTransactionCommand changed current memory context */
2310 }
2311
2312 /*
2313 * In case list_sort() would modify the list even when all the scores are
2314 * 0.0, skip sorting if all the weight parameters are set to 0.0. This is
2315 * probably not necessary, but we want to ensure folks have a guaranteed
2316 * escape hatch from the scoring system.
2317 */
2318 if (autovacuum_freeze_score_weight != 0.0 ||
2324
2325 /*
2326 * Optionally, create a buffer access strategy object for VACUUM to use.
2327 * We use the same BufferAccessStrategy object for all tables VACUUMed by
2328 * this worker to prevent autovacuum from blowing out shared buffers.
2329 *
2330 * VacuumBufferUsageLimit being set to 0 results in
2331 * GetAccessStrategyWithSize returning NULL, effectively meaning we can
2332 * use up to all of shared buffers.
2333 *
2334 * If we later enter failsafe mode on any of the tables being vacuumed, we
2335 * will cease use of the BufferAccessStrategy only for that table.
2336 *
2337 * XXX should we consider adding code to adjust the size of this if
2338 * VacuumBufferUsageLimit changes?
2339 */
2341
2342 /*
2343 * create a memory context to act as fake PortalContext, so that the
2344 * contexts created in the vacuum code are cleaned up for each table.
2345 */
2347 "Autovacuum Portal",
2349
2350 /*
2351 * Perform operations on collected tables.
2352 */
2354 {
2355 Oid relid = table->oid;
2357 autovac_table *tab;
2358 bool isshared;
2359 bool skipit;
2360 dlist_iter iter;
2361
2363
2364 /*
2365 * Check for config changes before processing each collected table.
2366 */
2368 {
2369 ConfigReloadPending = false;
2371
2372 /*
2373 * You might be tempted to bail out if we see autovacuum is now
2374 * disabled. Must resist that temptation -- this might be a
2375 * for-wraparound emergency worker, in which case that would be
2376 * entirely inappropriate.
2377 */
2378 }
2379
2380 /*
2381 * Find out whether the table is shared or not. (It's slightly
2382 * annoying to fetch the syscache entry just for this, but in typical
2383 * cases it adds little cost because table_recheck_autovac would
2384 * refetch the entry anyway. We could buy that back by copying the
2385 * tuple here and passing it to table_recheck_autovac, but that
2386 * increases the odds of that function working with stale data.)
2387 */
2390 continue; /* somebody deleted the rel, forget it */
2393
2394 /*
2395 * Hold schedule lock from here until we've claimed the table. We
2396 * also need the AutovacuumLock to walk the worker array, but that one
2397 * can just be a shared lock.
2398 */
2401
2402 /*
2403 * Check whether the table is being vacuumed concurrently by another
2404 * worker.
2405 */
2406 skipit = false;
2408 {
2409 WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2410
2411 /* ignore myself */
2412 if (worker == MyWorkerInfo)
2413 continue;
2414
2415 /* ignore workers in other databases (unless table is shared) */
2416 if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2417 continue;
2418
2419 if (worker->wi_tableoid == relid)
2420 {
2421 skipit = true;
2423 break;
2424 }
2425 }
2427 if (skipit)
2428 {
2430 continue;
2431 }
2432
2433 /*
2434 * Store the table's OID in shared memory before releasing the
2435 * schedule lock, so that other workers don't try to vacuum it
2436 * concurrently. (We claim it here so as not to hold
2437 * AutovacuumScheduleLock while rechecking the stats.)
2438 */
2439 MyWorkerInfo->wi_tableoid = relid;
2440 MyWorkerInfo->wi_sharedrel = isshared;
2442
2443 /*
2444 * Check whether pgstat data still says we need to vacuum this table.
2445 * It could have changed if something else processed the table while
2446 * we weren't looking. This doesn't entirely close the race condition,
2447 * but it is very small.
2448 */
2452 if (tab == NULL)
2453 {
2454 /* someone else vacuumed the table, or it went away */
2457 MyWorkerInfo->wi_sharedrel = false;
2459 continue;
2460 }
2461
2462 /*
2463 * Save the cost-related storage parameter values in global variables
2464 * for reference when updating vacuum_cost_delay and vacuum_cost_limit
2465 * during vacuuming this table.
2466 */
2469
2470 /*
2471 * We only expect this worker to ever set the flag, so don't bother
2472 * checking the return value. We shouldn't have to retry.
2473 */
2474 if (tab->at_dobalance)
2476 else
2478
2482
2483 /*
2484 * We wait until this point to update cost delay and cost limit
2485 * values, even though we reloaded the configuration file above, so
2486 * that we can take into account the cost-related storage parameters.
2487 */
2489
2490
2491 /* clean up memory before each iteration */
2493
2494 /*
2495 * Save the relation name for a possible error message, to avoid a
2496 * catalog lookup in case of an error. If any of these return NULL,
2497 * then the relation has been dropped since last we checked; skip it.
2498 * Note: they must live in a long-lived memory context because we call
2499 * vacuum and analyze in different transactions.
2500 */
2501
2502 tab->at_relname = get_rel_name(tab->at_relid);
2505 if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2506 goto deleted;
2507
2508 /*
2509 * We will abort vacuuming the current table if something errors out,
2510 * and continue with the next one in schedule; in particular, this
2511 * happens if we are interrupted with SIGINT.
2512 */
2513 PG_TRY();
2514 {
2515 /* Use PortalContext for any per-table allocations */
2517
2518 /* have at it */
2519 autovacuum_do_vac_analyze(tab, bstrategy);
2520
2521 /*
2522 * Clear a possible query-cancel signal, to avoid a late reaction
2523 * to an automatically-sent signal because of vacuuming the
2524 * current table (we're done with it, so it would make no sense to
2525 * cancel at this point.)
2526 */
2527 QueryCancelPending = false;
2528 }
2529 PG_CATCH();
2530 {
2531 /*
2532 * Abort the transaction, start a new one, and proceed with the
2533 * next table in our list.
2534 */
2536 if (tab->at_params.options & VACOPT_VACUUM)
2537 errcontext("automatic vacuum of table \"%s.%s.%s\"",
2538 tab->at_datname, tab->at_nspname, tab->at_relname);
2539 else
2540 errcontext("automatic analyze of table \"%s.%s.%s\"",
2541 tab->at_datname, tab->at_nspname, tab->at_relname);
2543
2544 /* this resets ProcGlobal->statusFlags[i] too */
2548
2549 /* restart our transaction for the following operations */
2552 }
2553 PG_END_TRY();
2554
2555 /* Make sure we're back in AutovacMemCxt */
2557
2558 did_vacuum = true;
2559
2560 /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2561
2562 /* be tidy */
2563deleted:
2564 if (tab->at_datname != NULL)
2565 pfree(tab->at_datname);
2566 if (tab->at_nspname != NULL)
2567 pfree(tab->at_nspname);
2568 if (tab->at_relname != NULL)
2569 pfree(tab->at_relname);
2570 pfree(tab);
2571
2572 /*
2573 * Remove my info from shared memory. We set wi_dobalance on the
2574 * assumption that we are more likely than not to vacuum a table with
2575 * no cost-related storage parameters next, so we want to claim our
2576 * share of I/O as soon as possible to avoid thrashing the global
2577 * balance.
2578 */
2581 MyWorkerInfo->wi_sharedrel = false;
2584 }
2585
2587
2588 /*
2589 * Perform additional work items, as requested by backends.
2590 */
2592 for (i = 0; i < NUM_WORKITEMS; i++)
2593 {
2595
2596 if (!workitem->avw_used)
2597 continue;
2598 if (workitem->avw_active)
2599 continue;
2600 if (workitem->avw_database != MyDatabaseId)
2601 continue;
2602
2603 /* claim this one, and release lock while performing it */
2604 workitem->avw_active = true;
2606
2609 if (ActiveSnapshotSet()) /* transaction could have aborted */
2611
2612 /*
2613 * Check for config changes before acquiring lock for further jobs.
2614 */
2617 {
2618 ConfigReloadPending = false;
2621 }
2622
2624
2625 /* and mark it done */
2626 workitem->avw_active = false;
2627 workitem->avw_used = false;
2628 }
2630
2631 /*
2632 * We leak table_toast_map here (among other things), but since we're
2633 * going away soon, it's not a problem normally. But when using Valgrind,
2634 * release some stuff to reduce complaints about leaked storage.
2635 */
2636#ifdef USE_VALGRIND
2639 if (bstrategy)
2640 pfree(bstrategy);
2641#endif
2642
2643 /* Run the rest in xact context, mainly to avoid Valgrind leak warnings */
2645
2646 /*
2647 * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2648 * only need to do this once, not after each table.
2649 *
2650 * Even if we didn't vacuum anything, it may still be important to do
2651 * this, because one indirect effect of vac_update_datfrozenxid() is to
2652 * update TransamVariables->xidVacLimit. That might need to be done even
2653 * if we haven't vacuumed anything, because relations with older
2654 * relfrozenxid values or other databases with older datfrozenxid values
2655 * might have been dropped, allowing xidVacLimit to advance.
2656 *
2657 * However, it's also important not to do this blindly in all cases,
2658 * because when autovacuum=off this will restart the autovacuum launcher.
2659 * If we're not careful, an infinite loop can result, where workers find
2660 * no work to do and restart the launcher, which starts another worker in
2661 * the same database that finds no work to do. To prevent that, we skip
2662 * this if (1) we found no work to do and (2) we skipped at least one
2663 * table due to concurrent autovacuum activity. In that case, the other
2664 * worker has already done it, or will do so when it finishes.
2665 */
2668
2669 /* Finally close out the last transaction. */
2671}
static void pg_atomic_clear_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:200
static bool pg_atomic_test_set_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:176
void VacuumUpdateCosts(void)
static int default_multixact_freeze_table_age
Definition autovacuum.c:175
static int default_multixact_freeze_min_age
Definition autovacuum.c:174
static double av_storage_param_cost_delay
Definition autovacuum.c:161
static int TableToProcessComparator(const ListCell *a, const ListCell *b)
double autovacuum_analyze_score_weight
Definition autovacuum.c:141
double autovacuum_vacuum_insert_score_weight
Definition autovacuum.c:140
static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, int elevel, bool *dovacuum, bool *doanalyze, bool *wraparound, AutoVacuumScores *scores)
double autovacuum_vacuum_score_weight
Definition autovacuum.c:139
double autovacuum_multixact_freeze_score_weight
Definition autovacuum.c:138
static void perform_work_item(AutoVacuumWorkItem *workitem)
static int default_freeze_min_age
Definition autovacuum.c:172
static autovac_table * table_recheck_autovac(Oid relid, HTAB *table_toast_map, TupleDesc pg_class_desc, int effective_multixact_freeze_max_age)
double autovacuum_freeze_score_weight
Definition autovacuum.c:137
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
static int default_freeze_table_age
Definition autovacuum.c:173
static void autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
@ BAS_VACUUM
Definition bufmgr.h:40
#define NameStr(name)
Definition c.h:894
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition dependency.c:279
#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:889
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
void hash_destroy(HTAB *hashp)
Definition dynahash.c:802
#define LOG
Definition elog.h:32
#define errcontext
Definition elog.h:200
#define DEBUG3
Definition elog.h:29
#define PG_TRY(...)
Definition elog.h:374
#define PG_END_TRY(...)
Definition elog.h:399
#define PG_CATCH(...)
Definition elog.h:384
#define palloc_object(type)
Definition fe_memutils.h:89
BufferAccessStrategy GetAccessStrategyWithSize(BufferAccessStrategyType btype, int ring_size_kb)
Definition freelist.c:511
int VacuumBufferUsageLimit
Definition globals.c:152
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:1436
@ HASH_FIND
Definition hsearch.h:108
@ HASH_ENTER
Definition hsearch.h:109
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
#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(List *list, void *datum)
Definition list.c:339
void list_sort(List *list, list_sort_comparator cmp)
Definition list.c:1674
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
void list_free_deep(List *list)
Definition list.c:1560
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:2242
char * get_database_name(Oid dbid)
Definition lsyscache.c:1392
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2266
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3682
MemoryContext TopTransactionContext
Definition mcxt.c:172
void pfree(void *pointer)
Definition mcxt.c:1619
MemoryContext PortalContext
Definition mcxt.c:176
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
int MultiXactMemberFreezeThreshold(void)
Definition multixact.c:2590
TempNamespaceStatus checkTempNamespaceStatus(Oid namespaceId)
Definition namespace.c:3801
@ TEMP_NAMESPACE_IDLE
Definition namespace.h:66
@ DROP_CASCADE
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
END_CATALOG_STRUCT typedef FormData_pg_database * Form_pg_database
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
#define lfirst_oid(lc)
Definition pg_list.h:174
static const struct lconv_member_info table[]
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
static Datum CharGetDatum(char X)
Definition postgres.h:132
tree ctl
Definition radixtree.h:1838
#define RelationGetDescr(relation)
Definition rel.h:542
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:214
int at_storage_param_vac_cost_limit
Definition autovacuum.c:215
char * at_datname
Definition autovacuum.c:219
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
#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:1061
void FreeTupleDesc(TupleDesc tupdesc)
Definition tupdesc.c:569
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition tupdesc.c:242
int vacuum_freeze_min_age
Definition vacuum.c:76
int vacuum_multixact_freeze_table_age
Definition vacuum.c:79
int vacuum_freeze_table_age
Definition vacuum.c:77
int vacuum_multixact_freeze_min_age
Definition vacuum.c:78
void vac_update_datfrozenxid(void)
Definition vacuum.c:1614
void StartTransactionCommand(void)
Definition xact.c:3112
void CommitTransactionCommand(void)
Definition xact.c:3210
void AbortOutOfAnyTransaction(void)
Definition xact.c:4916

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_analyze_score_weight, autovacuum_do_vac_analyze(), autovacuum_freeze_score_weight, autovacuum_multixact_freeze_score_weight, autovacuum_vacuum_insert_score_weight, autovacuum_vacuum_score_weight, 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, DEBUG3, 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(), foreach_ptr, Form_pg_database, 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(), lappend_oid(), lfirst_oid, list_free_deep(), list_sort(), LOG, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), memcpy(), MemoryContextReset(), MemoryContextSwitchTo(), MultiXactMemberFreezeThreshold(), MyDatabaseId, MyWorkerInfo, NameStr, NIL, NUM_WORKITEMS, ObjectIdGetDatum(), OidIsValid, VacuumParams::options, palloc_object, 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, PopActiveSnapshot(), PortalContext, ProcessConfigFile(), PushActiveSnapshot(), QueryCancelPending, relation_needs_vacanalyze(), RelationGetDescr, ReleaseSysCache(), RESUME_INTERRUPTS, ScanKeyInit(), SearchSysCache1(), SearchSysCacheCopy1, StartTransactionCommand(), table, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), table_recheck_autovac(), TableToProcessComparator(), 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 1132 of file autovacuum.c.

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

2792{
2793 bytea *relopts;
2794 AutoVacOpts *av;
2795
2797 ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2799
2801 if (relopts == NULL)
2802 return NULL;
2803
2805 memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2806 pfree(relopts);
2807
2808 return av;
2809}
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
struct @10::@11 av[32]
Definition c.h:835

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

Referenced by do_autovacuum(), pg_stat_get_autovacuum_scores(), and table_recheck_autovac().

◆ FreeWorkerInfo()

◆ get_database_list()

static List * get_database_list ( void  )
static

Definition at line 1839 of file autovacuum.c.

1840{
1841 List *dblist = NIL;
1842 Relation rel;
1843 TableScanDesc scan;
1844 HeapTuple tup;
1846
1847 /* This is the context that we will allocate our output data in */
1849
1850 /*
1851 * Start a transaction so we can access pg_database.
1852 */
1854
1856 scan = table_beginscan_catalog(rel, 0, NULL);
1857
1859 {
1861 avw_dbase *avdb;
1863
1864 /*
1865 * If database has partially been dropped, we can't, nor need to,
1866 * vacuum it.
1867 */
1869 {
1870 elog(DEBUG2,
1871 "autovacuum: skipping invalid database \"%s\"",
1872 NameStr(pgdatabase->datname));
1873 continue;
1874 }
1875
1876 /*
1877 * Allocate our results in the caller's context, not the
1878 * transaction's. We do this inside the loop, and restore the original
1879 * context at the end, so that leaky things like heap_getnext() are
1880 * not called in a potentially long-lived context.
1881 */
1883
1885
1886 avdb->adw_datid = pgdatabase->oid;
1887 avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1888 avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1889 avdb->adw_minmulti = pgdatabase->datminmxid;
1890 /* this gets set later: */
1891 avdb->adw_entry = NULL;
1892
1895 }
1896
1897 table_endscan(scan);
1899
1901
1902 /* Be sure to restore caller's memory context */
1904
1905 return dblist;
1906}
bool database_is_invalid_form(Form_pg_database datform)
#define DEBUG2
Definition elog.h:30
char * pstrdup(const char *in)
Definition mcxt.c:1910

References AccessShareLock, CommitTransactionCommand(), CurrentMemoryContext, database_is_invalid_form(), dblist, DEBUG2, elog, fb(), Form_pg_database, 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 1344 of file autovacuum.c.

1345{
1346 Oid dbid;
1347 dlist_iter iter;
1348
1349 dbid = do_start_worker();
1350 if (OidIsValid(dbid))
1351 {
1352 bool found = false;
1353
1354 /*
1355 * Walk the database list and update the corresponding entry. If the
1356 * database is not on the list, we'll recreate the list.
1357 */
1359 {
1360 avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1361
1362 if (avdb->adl_datid == dbid)
1363 {
1364 found = true;
1365
1366 /*
1367 * add autovacuum_naptime seconds to the current time, and use
1368 * that as the new "next_worker" field for this database.
1369 */
1370 avdb->adl_next_worker =
1372
1374 break;
1375 }
1376 }
1377
1378 /*
1379 * If the database was not present in the database list, we rebuild
1380 * the list. It's possible that the database does not get into the
1381 * list anyway, for example if it's a database that doesn't have a
1382 * pgstat entry, but this is not a problem because we don't want to
1383 * schedule workers regularly into those in any case.
1384 */
1385 if (!found)
1387 }
1388}
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1613
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 847 of file autovacuum.c.

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

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

2678{
2679 char *cur_datname = NULL;
2680 char *cur_nspname = NULL;
2681 char *cur_relname = NULL;
2682
2683 /*
2684 * Note we do not store table info in MyWorkerInfo, since this is not
2685 * vacuuming proper.
2686 */
2687
2688 /*
2689 * Save the relation name for a possible error message, to avoid a catalog
2690 * lookup in case of an error. If any of these return NULL, then the
2691 * relation has been dropped since last we checked; skip it.
2692 */
2694
2695 cur_relname = get_rel_name(workitem->avw_relation);
2698 if (!cur_relname || !cur_nspname || !cur_datname)
2699 goto deleted2;
2700
2702
2703 /* clean up memory before each work item */
2705
2706 /*
2707 * We will abort the current work item if something errors out, and
2708 * continue with the next one; in particular, this happens if we are
2709 * interrupted with SIGINT. Note that this means that the work item list
2710 * can be lossy.
2711 */
2712 PG_TRY();
2713 {
2714 /* Use PortalContext for any per-work-item allocations */
2716
2717 /*
2718 * Have at it. Functions called here are responsible for any required
2719 * user switch and sandbox.
2720 */
2721 switch (workitem->avw_type)
2722 {
2725 ObjectIdGetDatum(workitem->avw_relation),
2726 Int64GetDatum((int64) workitem->avw_blockNumber));
2727 break;
2728 default:
2729 elog(WARNING, "unrecognized work item found: type %d",
2730 workitem->avw_type);
2731 break;
2732 }
2733
2734 /*
2735 * Clear a possible query-cancel signal, to avoid a late reaction to
2736 * an automatically-sent signal because of vacuuming the current table
2737 * (we're done with it, so it would make no sense to cancel at this
2738 * point.)
2739 */
2740 QueryCancelPending = false;
2741 }
2742 PG_CATCH();
2743 {
2744 /*
2745 * Abort the transaction, start a new one, and proceed with the next
2746 * table in our list.
2747 */
2749 errcontext("processing work entry for relation \"%s.%s.%s\"",
2750 cur_datname, cur_nspname, cur_relname);
2752
2753 /* this resets ProcGlobal->statusFlags[i] too */
2757
2758 /* restart our transaction for the following operations */
2761 }
2762 PG_END_TRY();
2763
2764 /* Make sure we're back in AutovacMemCxt */
2766
2767 /* We intentionally do not set did_vacuum here */
2768
2769 /* be tidy */
2770deleted2:
2771 if (cur_datname)
2773 if (cur_nspname)
2775 if (cur_relname)
2776 pfree(cur_relname);
2777}
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition brin.c:1386
int64_t int64
Definition c.h:680
#define DirectFunctionCall2(func, arg1, arg2)
Definition fmgr.h:690
static Datum Int64GetDatum(int64 X)
Definition postgres.h:426

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

◆ pg_stat_get_autovacuum_scores()

Datum pg_stat_get_autovacuum_scores ( PG_FUNCTION_ARGS  )

Definition at line 3650 of file autovacuum.c.

3651{
3653 Relation rel;
3654 TableScanDesc scan;
3655 HeapTuple tup;
3656 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
3657
3658 InitMaterializedSRF(fcinfo, 0);
3659
3660 /* some prerequisite initialization */
3664
3665 /* scan pg_class */
3667 scan = table_beginscan_catalog(rel, 0, NULL);
3668 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
3669 {
3672 bool dovacuum;
3673 bool doanalyze;
3674 bool wraparound;
3676 Datum vals[10];
3677 bool nulls[10] = {false};
3678
3679 /* skip ineligible entries */
3680 if (form->relkind != RELKIND_RELATION &&
3681 form->relkind != RELKIND_MATVIEW &&
3682 form->relkind != RELKIND_TOASTVALUE)
3683 continue;
3684 if (form->relpersistence == RELPERSISTENCE_TEMP)
3685 continue;
3686
3690 LOG_NEVER,
3692 &scores);
3693 if (avopts)
3694 pfree(avopts);
3695
3696 vals[0] = ObjectIdGetDatum(form->oid);
3697 vals[1] = Float8GetDatum(scores.max);
3698 vals[2] = Float8GetDatum(scores.xid);
3699 vals[3] = Float8GetDatum(scores.mxid);
3700 vals[4] = Float8GetDatum(scores.vac);
3701 vals[5] = Float8GetDatum(scores.vac_ins);
3702 vals[6] = Float8GetDatum(scores.anl);
3703 vals[7] = BoolGetDatum(dovacuum);
3704 vals[8] = BoolGetDatum(doanalyze);
3705 vals[9] = BoolGetDatum(wraparound);
3706
3707 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, vals, nulls);
3708 }
3709 table_endscan(scan);
3711
3712 return (Datum) 0;
3713}
#define LOG_NEVER
Definition elog.h:26
void InitMaterializedSRF(FunctionCallInfo fcinfo, uint32 flags)
Definition funcapi.c:76
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
uint64_t Datum
Definition postgres.h:70
static Datum Float8GetDatum(float8 X)
Definition postgres.h:515
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:785

References AccessShareLock, BoolGetDatum(), extract_autovac_opts(), fb(), Float8GetDatum(), ForwardScanDirection, GETSTRUCT(), heap_getnext(), InitMaterializedSRF(), LOG_NEVER, MultiXactMemberFreezeThreshold(), ObjectIdGetDatum(), pfree(), ReadNextMultiXactId(), ReadNextTransactionId(), recentMulti, recentXid, relation_needs_vacanalyze(), RelationGetDescr, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and tuplestore_putvalues().

◆ ProcessAutoVacLauncherInterrupts()

static void ProcessAutoVacLauncherInterrupts ( void  )
static

Definition at line 787 of file autovacuum.c.

788{
789 /* the normal shutdown case */
792
794 {
796
797 ConfigReloadPending = false;
799
800 /* shutdown requested in config file? */
801 if (!AutoVacuumingActive())
803
804 /*
805 * If autovacuum_max_workers changed, emit a WARNING if
806 * autovacuum_worker_slots < autovacuum_max_workers. If it didn't
807 * change, skip this to avoid too many repeated log messages.
808 */
811
812 /* rebuild the list in case the naptime changed */
814 }
815
816 /* Process barrier events */
819
820 /* Perform logging of memory contexts of this process */
823
824 /* Process sinval catchup interrupts that happened while sleeping */
826}
volatile sig_atomic_t LogMemoryContextPending
Definition globals.c:41
volatile sig_atomic_t ProcSignalBarrierPending
Definition globals.c:40
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1343
void ProcessProcSignalBarrier(void)
Definition procsignal.c:511
void ProcessCatchupInterrupt(void)
Definition sinval.c:173

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

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

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

◆ relation_needs_vacanalyze()

static void relation_needs_vacanalyze ( Oid  relid,
AutoVacOpts relopts,
Form_pg_class  classForm,
int  effective_multixact_freeze_max_age,
int  elevel,
bool dovacuum,
bool doanalyze,
bool wraparound,
AutoVacuumScores scores 
)
static

Definition at line 3074 of file autovacuum.c.

3084{
3086 bool force_vacuum;
3087 bool av_enabled;
3088 bool may_free = false;
3089
3090 /* constants from reloptions or GUC variables */
3091 int vac_base_thresh,
3098
3099 /* thresholds calculated from above constants */
3102 anlthresh;
3103
3104 /* number of vacuum (resp. analyze) tuples at this time */
3106 instuples,
3107 anltuples;
3108
3109 /* freeze parameters */
3110 int freeze_max_age;
3111 int multixact_freeze_max_age;
3113 TransactionId relfrozenxid;
3114 MultiXactId relminmxid;
3120
3122 float4 reltuples = classForm->reltuples;
3123 int32 relpages = classForm->relpages;
3124 int32 relallfrozen = classForm->relallfrozen;
3125
3126 Assert(classForm != NULL);
3127 Assert(OidIsValid(relid));
3128
3129 memset(scores, 0, sizeof(AutoVacuumScores));
3130 *dovacuum = false;
3131 *doanalyze = false;
3132
3133 /*
3134 * Determine vacuum/analyze equation parameters. We have two possible
3135 * sources: the passed reloptions (which could be a main table or a toast
3136 * table), or the autovacuum GUC variables.
3137 */
3138
3139 /* -1 in autovac setting means use plain vacuum_scale_factor */
3140 vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3141 ? relopts->vacuum_scale_factor
3143
3144 vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3145 ? relopts->vacuum_threshold
3147
3148 /* -1 is used to disable max threshold */
3149 vac_max_thresh = (relopts && relopts->vacuum_max_threshold >= -1)
3150 ? relopts->vacuum_max_threshold
3152
3153 vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3154 ? relopts->vacuum_ins_scale_factor
3156
3157 /* -1 is used to disable insert vacuums */
3158 vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3159 ? relopts->vacuum_ins_threshold
3161
3162 anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3163 ? relopts->analyze_scale_factor
3165
3166 anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3167 ? relopts->analyze_threshold
3169
3170 freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3171 ? Min(relopts->freeze_max_age, autovacuum_freeze_max_age)
3173
3174 multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3175 ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3177
3178 av_enabled = (relopts ? relopts->enabled : true);
3180
3181 relfrozenxid = classForm->relfrozenxid;
3182 relminmxid = classForm->relminmxid;
3183
3184 /* Force vacuum if table is at risk of wraparound */
3185 xidForceLimit = recentXid - freeze_max_age;
3188 force_vacuum = (TransactionIdIsNormal(relfrozenxid) &&
3189 TransactionIdPrecedes(relfrozenxid, xidForceLimit));
3190 if (!force_vacuum)
3191 {
3192 multiForceLimit = recentMulti - multixact_freeze_max_age;
3195 force_vacuum = MultiXactIdIsValid(relminmxid) &&
3197 }
3199
3200 /*
3201 * To calculate the (M)XID age portion of the score, divide the age by its
3202 * respective *_freeze_max_age parameter. The multixact_freeze_max_age
3203 * variable might be 0 here (i.e., a division-by-zero hazard), so in that
3204 * case we use the mxid_age as the MXID score.
3205 */
3206 xid_age = TransactionIdIsNormal(relfrozenxid) ? recentXid - relfrozenxid : 0;
3207 mxid_age = MultiXactIdIsValid(relminmxid) ? recentMulti - relminmxid : 0;
3208
3209 scores->xid = (double) xid_age / freeze_max_age;
3210 scores->mxid = (double) mxid_age / Max(1, multixact_freeze_max_age);
3211
3212 /*
3213 * To ensure tables are given increased priority once they begin
3214 * approaching wraparound, we scale the score aggressively if the ages
3215 * surpass vacuum_failsafe_age or vacuum_multixact_failsafe_age.
3216 *
3217 * As in vacuum_xid_failsafe_check(), the effective failsafe age is no
3218 * less than 105% the value of the respective *_freeze_max_age parameter.
3219 * Note that per-table settings could result in a low score even if the
3220 * table surpasses the failsafe settings. However, this is a strange
3221 * enough corner case that we don't bother trying to handle it.
3222 *
3223 * We further adjust the effective failsafe ages with the weight
3224 * parameters so that increasing them lowers the ages at which we begin
3225 * scaling aggressively.
3226 */
3231
3236
3238 scores->xid = pow(scores->xid, Max(1.0, (double) xid_age / 100000000));
3240 scores->mxid = pow(scores->mxid, Max(1.0, (double) mxid_age / 100000000));
3241
3244
3245 scores->max = Max(scores->xid, scores->mxid);
3246 if (force_vacuum)
3247 *dovacuum = true;
3248
3249 /*
3250 * If we found stats for the table, and autovacuum is currently enabled,
3251 * make a threshold-based decision whether to vacuum and/or analyze. If
3252 * autovacuum is currently disabled, we must be here for anti-wraparound
3253 * vacuuming only, so don't vacuum (or analyze) anything that's not being
3254 * forced.
3255 */
3257 relid, &may_free);
3258 if (!tabentry)
3259 return;
3260
3261 vactuples = tabentry->dead_tuples;
3262 instuples = tabentry->ins_since_vacuum;
3263 anltuples = tabentry->mod_since_analyze;
3264
3265 /* If the table hasn't yet been vacuumed, take reltuples as zero */
3266 if (reltuples < 0)
3267 reltuples = 0;
3268
3269 /*
3270 * If we have data for relallfrozen, calculate the unfrozen percentage of
3271 * the table to modify insert scale factor. This helps us decide whether
3272 * or not to vacuum an insert-heavy table based on the number of inserts
3273 * to the more "active" part of the table.
3274 */
3275 if (relpages > 0 && relallfrozen > 0)
3276 {
3277 /*
3278 * It could be the stats were updated manually and relallfrozen >
3279 * relpages. Clamp relallfrozen to relpages to avoid nonsensical
3280 * calculations.
3281 */
3282 relallfrozen = Min(relallfrozen, relpages);
3283 pcnt_unfrozen = 1 - ((float4) relallfrozen / relpages);
3284 }
3285
3289
3291 vac_ins_scale_factor * reltuples * pcnt_unfrozen;
3293
3294 /* Determine if this table needs vacuum, and update the score. */
3295 scores->vac = (double) vactuples / Max(vacthresh, 1);
3297 scores->max = Max(scores->max, scores->vac);
3299 *dovacuum = true;
3300
3301 if (vac_ins_base_thresh >= 0)
3302 {
3303 scores->vac_ins = (double) instuples / Max(vacinsthresh, 1);
3305 scores->max = Max(scores->max, scores->vac_ins);
3307 *dovacuum = true;
3308 }
3309
3310 /*
3311 * Determine if this table needs analyze, and update the score. Note that
3312 * we don't analyze TOAST tables and pg_statistic.
3313 */
3314 if (relid != StatisticRelationId &&
3315 classForm->relkind != RELKIND_TOASTVALUE)
3316 {
3317 scores->anl = (double) anltuples / Max(anlthresh, 1);
3319 scores->max = Max(scores->max, scores->anl);
3321 *doanalyze = true;
3322 }
3323
3324 if (vac_ins_base_thresh >= 0)
3325 elog(elevel, "%s: vac: %.0f (thresh %.0f, score %.2f), ins: %.0f (thresh %.0f, score %.2f), anl: %.0f (thresh %.0f, score %.2f), xid score: %.2f, mxid score: %.2f",
3326 NameStr(classForm->relname),
3327 vactuples, vacthresh, scores->vac,
3328 instuples, vacinsthresh, scores->vac_ins,
3329 anltuples, anlthresh, scores->anl,
3330 scores->xid, scores->mxid);
3331 else
3332 elog(elevel, "%s: vac: %.0f (thresh %.0f, score %.2f), ins: (disabled), anl: %.0f (thresh %.0f, score %.2f), xid score: %.2f, mxid score: %.2f",
3333 NameStr(classForm->relname),
3334 vactuples, vacthresh, scores->vac,
3335 anltuples, anlthresh, scores->anl,
3336 scores->xid, scores->mxid);
3337
3338 /* Avoid leaking pgstat entries until the end of autovacuum. */
3339 if (may_free)
3340 pfree(tabentry);
3341}
int autovacuum_multixact_freeze_max_age
Definition autovacuum.c:136
double autovacuum_vac_scale
Definition autovacuum.c:130
int autovacuum_anl_thresh
Definition autovacuum.c:133
int autovacuum_vac_thresh
Definition autovacuum.c:128
double autovacuum_anl_scale
Definition autovacuum.c:134
int autovacuum_vac_ins_thresh
Definition autovacuum.c:131
double autovacuum_vac_ins_scale
Definition autovacuum.c:132
int autovacuum_vac_max_thresh
Definition autovacuum.c:129
int32_t int32
Definition c.h:679
uint32_t uint32
Definition c.h:683
float float4
Definition c.h:772
#define MultiXactIdIsValid(multi)
Definition multixact.h:29
PgStat_StatTabEntry * pgstat_fetch_stat_tabentry_ext(bool shared, Oid reloid, bool *may_free)
#define TransactionIdIsNormal(xid)
Definition transam.h:42
int vacuum_multixact_failsafe_age
Definition vacuum.c:81
int vacuum_failsafe_age
Definition vacuum.c:80
Datum xid_age(PG_FUNCTION_ARGS)
Definition xid.c:117
Datum mxid_age(PG_FUNCTION_ARGS)
Definition xid.c:133

References Assert, autovacuum_analyze_score_weight, autovacuum_anl_scale, autovacuum_anl_thresh, autovacuum_freeze_max_age, autovacuum_freeze_score_weight, autovacuum_multixact_freeze_max_age, autovacuum_multixact_freeze_score_weight, autovacuum_vac_ins_scale, autovacuum_vac_ins_thresh, autovacuum_vac_max_thresh, autovacuum_vac_scale, autovacuum_vac_thresh, autovacuum_vacuum_insert_score_weight, autovacuum_vacuum_score_weight, AutoVacuumingActive(), elog, fb(), FirstMultiXactId, FirstNormalTransactionId, Max, Min, MultiXactIdIsValid, MultiXactIdPrecedes(), mxid_age(), NameStr, OidIsValid, pfree(), pgstat_fetch_stat_tabentry_ext(), recentMulti, recentXid, TransactionIdIsNormal, TransactionIdPrecedes(), vacuum_failsafe_age, vacuum_multixact_failsafe_age, and xid_age().

Referenced by do_autovacuum(), pg_stat_get_autovacuum_scores(), and table_recheck_autovac().

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

2824{
2827 bool dovacuum;
2828 bool doanalyze;
2829 autovac_table *tab = NULL;
2830 bool wraparound;
2832 bool free_avopts = false;
2834
2835 /* fetch the relation's relcache entry */
2838 return NULL;
2840
2841 /*
2842 * Get the applicable reloptions. If it is a TOAST table, try to get the
2843 * main table reloptions if the toast table itself doesn't have.
2844 */
2846 if (avopts)
2847 free_avopts = true;
2848 else if (classForm->relkind == RELKIND_TOASTVALUE &&
2850 {
2852 bool found;
2853
2854 hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2855 if (found && hentry->ar_hasrelopts)
2856 avopts = &hentry->ar_reloptions;
2857 }
2858
2861 DEBUG3,
2863 &scores);
2864
2865 /* OK, it needs something done */
2866 if (doanalyze || dovacuum)
2867 {
2868 int freeze_min_age;
2869 int freeze_table_age;
2870 int multixact_freeze_min_age;
2871 int multixact_freeze_table_age;
2872 int log_vacuum_min_duration;
2873 int log_analyze_min_duration;
2874
2875 /*
2876 * Calculate the vacuum cost parameters and the freeze ages. If there
2877 * are options set in pg_class.reloptions, use them; in the case of a
2878 * toast table, try the main table too. Otherwise use the GUC
2879 * defaults, autovacuum's own first and plain vacuum second.
2880 */
2881
2882 /* -1 in autovac setting means use log_autovacuum_min_duration */
2883 log_vacuum_min_duration = (avopts && avopts->log_vacuum_min_duration >= 0)
2884 ? avopts->log_vacuum_min_duration
2886
2887 /* -1 in autovac setting means use log_autoanalyze_min_duration */
2888 log_analyze_min_duration = (avopts && avopts->log_analyze_min_duration >= 0)
2889 ? avopts->log_analyze_min_duration
2891
2892 /* these do not have autovacuum-specific settings */
2893 freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2894 ? avopts->freeze_min_age
2896
2897 freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2898 ? avopts->freeze_table_age
2900
2901 multixact_freeze_min_age = (avopts &&
2902 avopts->multixact_freeze_min_age >= 0)
2903 ? avopts->multixact_freeze_min_age
2905
2906 multixact_freeze_table_age = (avopts &&
2907 avopts->multixact_freeze_table_age >= 0)
2908 ? avopts->multixact_freeze_table_age
2910
2912 tab->at_relid = relid;
2913
2914 /*
2915 * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2916 * that vacuum() skips toast relations. Also note we tell vacuum() to
2917 * skip vac_update_datfrozenxid(); we'll do that separately.
2918 */
2919 tab->at_params.options =
2923 (doanalyze ? VACOPT_ANALYZE : 0) |
2925
2926 /*
2927 * index_cleanup and truncate are unspecified at first in autovacuum.
2928 * They will be filled in with usable values using their reloptions
2929 * (or reloption defaults) later.
2930 */
2933 tab->at_params.freeze_min_age = freeze_min_age;
2934 tab->at_params.freeze_table_age = freeze_table_age;
2935 tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2936 tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2938 tab->at_params.log_vacuum_min_duration = log_vacuum_min_duration;
2939 tab->at_params.log_analyze_min_duration = log_analyze_min_duration;
2941
2942 /* Determine the number of parallel vacuum workers to use */
2943 tab->at_params.nworkers = 0;
2944 if (avopts)
2945 {
2946 if (avopts->autovacuum_parallel_workers == 0)
2947 {
2948 /*
2949 * Disable parallel vacuum, if the reloption sets the parallel
2950 * degree as zero.
2951 */
2952 tab->at_params.nworkers = -1;
2953 }
2954 else if (avopts->autovacuum_parallel_workers > 0)
2955 tab->at_params.nworkers = avopts->autovacuum_parallel_workers;
2956
2957 /*
2958 * autovacuum_parallel_workers == -1 falls through, keep
2959 * nworkers=0
2960 */
2961 }
2962
2963 /*
2964 * Later, in vacuum_rel(), we check reloptions for any
2965 * vacuum_max_eager_freeze_failure_rate override.
2966 */
2969 avopts->vacuum_cost_limit : 0;
2971 avopts->vacuum_cost_delay : -1;
2972 tab->at_relname = NULL;
2973 tab->at_nspname = NULL;
2974 tab->at_datname = NULL;
2975
2976 /*
2977 * If any of the cost delay parameters has been set individually for
2978 * this table, disable the balancing algorithm.
2979 */
2980 tab->at_dobalance =
2981 !(avopts && (avopts->vacuum_cost_limit > 0 ||
2982 avopts->vacuum_cost_delay >= 0));
2983 }
2984
2985 if (free_avopts)
2986 pfree(avopts);
2988 return tab;
2989}
int Log_autovacuum_min_duration
Definition autovacuum.c:145
int Log_autoanalyze_min_duration
Definition autovacuum.c:146
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
int nworkers
Definition vacuum.h:250
int freeze_table_age
Definition vacuum.h:220
VacOptValue truncate
Definition vacuum.h:235
int freeze_min_age
Definition vacuum.h:219
int log_vacuum_min_duration
Definition vacuum.h:226
int multixact_freeze_min_age
Definition vacuum.h:221
int multixact_freeze_table_age
Definition vacuum.h:223
Oid toast_parent
Definition vacuum.h:236
VacOptValue index_cleanup
Definition vacuum.h:234
int log_analyze_min_duration
Definition vacuum.h:230
double max_eager_freeze_failure_rate
Definition vacuum.h:243
double vacuum_max_eager_freeze_failure_rate
Definition vacuum.c:82
#define VACOPT_SKIP_LOCKED
Definition vacuum.h:184
#define VACOPT_SKIP_DATABASE_STATS
Definition vacuum.h:188
@ VACOPTVALUE_UNSPECIFIED
Definition vacuum.h:201
#define VACOPT_PROCESS_MAIN
Definition vacuum.h:185

References 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, DEBUG3, 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(), 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().

◆ TableToProcessComparator()

static int TableToProcessComparator ( const ListCell a,
const ListCell b 
)
static

Definition at line 1913 of file autovacuum.c.

1914{
1917
1918 return (t2->score < t1->score) ? -1 : (t2->score > t1->score) ? 1 : 0;
1919}

References a, b, fb(), and lfirst.

Referenced by do_autovacuum().

◆ VacuumUpdateCosts()

void VacuumUpdateCosts ( void  )

Definition at line 1684 of file autovacuum.c.

1685{
1686 if (MyWorkerInfo)
1687 {
1690 else if (autovacuum_vac_cost_delay >= 0)
1692 else
1693 /* fall back to VacuumCostDelay */
1695
1697 }
1698 else
1699 {
1700 /* Must be explicit VACUUM or ANALYZE or parallel autovacuum worker */
1703 }
1704
1705 /*
1706 * If configuration changes are allowed to impact VacuumCostActive, make
1707 * sure it is updated.
1708 */
1711 else if (vacuum_cost_delay > 0)
1712 VacuumCostActive = true;
1713 else
1714 {
1715 VacuumCostActive = false;
1717 }
1718
1719 /*
1720 * Since the cost logging requires a lock, avoid rendering the log message
1721 * in case we are using a message level where the log wouldn't be emitted.
1722 */
1724 {
1725 Oid dboid,
1726 tableoid;
1727
1729
1731 dboid = MyWorkerInfo->wi_dboid;
1732 tableoid = MyWorkerInfo->wi_tableoid;
1734
1735 elog(DEBUG2,
1736 "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1737 dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1739 vacuum_cost_delay > 0 ? "yes" : "no",
1740 VacuumFailsafeActive ? "yes" : "no");
1741 }
1742}
double autovacuum_vac_cost_delay
Definition autovacuum.c:142
void AutoVacuumUpdateCostLimit(void)
bool message_level_is_interesting(int elevel)
Definition elog.c:285
bool VacuumCostActive
Definition globals.c:161
int VacuumCostBalance
Definition globals.c:160
double VacuumCostDelay
Definition globals.c:158
double vacuum_cost_delay
Definition vacuum.c:92
bool VacuumFailsafeActive
Definition vacuum.c:111

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 DataChecksumsWorkerMain(), do_autovacuum(), parallel_vacuum_main(), parallel_vacuum_update_shared_delay_params(), vacuum(), and vacuum_delay_point().

Variable Documentation

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

◆ autovacuum_analyze_score_weight

double autovacuum_analyze_score_weight = 1.0

Definition at line 141 of file autovacuum.c.

Referenced by do_autovacuum(), and relation_needs_vacanalyze().

◆ autovacuum_anl_scale

double autovacuum_anl_scale

Definition at line 134 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 133 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

◆ autovacuum_freeze_score_weight

double autovacuum_freeze_score_weight = 1.0

Definition at line 137 of file autovacuum.c.

Referenced by do_autovacuum(), and relation_needs_vacanalyze().

◆ autovacuum_max_workers

int autovacuum_max_workers

◆ autovacuum_multixact_freeze_max_age

int autovacuum_multixact_freeze_max_age

◆ autovacuum_multixact_freeze_score_weight

double autovacuum_multixact_freeze_score_weight = 1.0

Definition at line 138 of file autovacuum.c.

Referenced by do_autovacuum(), and relation_needs_vacanalyze().

◆ autovacuum_naptime

◆ autovacuum_start_daemon

bool autovacuum_start_daemon = false

Definition at line 123 of file autovacuum.c.

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

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 142 of file autovacuum.c.

Referenced by VacuumUpdateCosts().

◆ autovacuum_vac_cost_limit

int autovacuum_vac_cost_limit

Definition at line 143 of file autovacuum.c.

Referenced by AutoVacuumUpdateCostLimit().

◆ autovacuum_vac_ins_scale

double autovacuum_vac_ins_scale

Definition at line 132 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 131 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_max_thresh

int autovacuum_vac_max_thresh

Definition at line 129 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 130 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 128 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vacuum_insert_score_weight

double autovacuum_vacuum_insert_score_weight = 1.0

Definition at line 140 of file autovacuum.c.

Referenced by do_autovacuum(), and relation_needs_vacanalyze().

◆ autovacuum_vacuum_score_weight

double autovacuum_vacuum_score_weight = 1.0

Definition at line 139 of file autovacuum.c.

Referenced by do_autovacuum(), and relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 126 of file autovacuum.c.

Referenced by dead_items_alloc(), and ginInsertCleanup().

◆ autovacuum_worker_slots

◆ AutoVacuumShmem

◆ AutoVacuumShmemCallbacks

const ShmemCallbacks AutoVacuumShmemCallbacks
Initial value:
= {
.request_fn = AutoVacuumShmemRequest,
.init_fn = AutoVacuumShmemInit,
}
static void AutoVacuumShmemInit(void *arg)
static void AutoVacuumShmemRequest(void *arg)

Definition at line 316 of file autovacuum.c.

316 {
317 .request_fn = AutoVacuumShmemRequest,
318 .init_fn = AutoVacuumShmemInit,
319};

◆ av_storage_param_cost_delay

double av_storage_param_cost_delay = -1
static

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

Referenced by AutoVacuumUpdateCostLimit(), and do_autovacuum().

◆ DatabaseList

◆ DatabaseListCxt

MemoryContext DatabaseListCxt = NULL
static

Definition at line 326 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and rebuild_database_list().

◆ default_freeze_min_age

int default_freeze_min_age
static

Definition at line 172 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 173 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 174 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 175 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 165 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and avl_sigusr2_handler().

◆ Log_autoanalyze_min_duration

int Log_autoanalyze_min_duration = 600000

Definition at line 146 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = 600000

Definition at line 145 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

◆ recentMulti

◆ recentXid