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

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Enumerations

enum  AutoVacuumSignal { AutoVacForkFailed , AutoVacRebalance }
 

Functions

static Oid do_start_worker (void)
 
static void ProcessAutoVacLauncherInterrupts (void)
 
static pg_noreturn void AutoVacLauncherShutdown (void)
 
static void launcher_determine_sleep (bool canlaunch, bool recursing, struct timeval *nap)
 
static void launch_worker (TimestampTz now)
 
static Listget_database_list (void)
 
static void rebuild_database_list (Oid newdb)
 
static int db_comparator (const void *a, const void *b)
 
static void autovac_recalculate_workers_for_balance (void)
 
static void do_autovacuum (void)
 
static void FreeWorkerInfo (int code, Datum arg)
 
static autovac_tabletable_recheck_autovac (Oid relid, HTAB *table_toast_map, TupleDesc pg_class_desc, int effective_multixact_freeze_max_age)
 
static void recheck_relation_needs_vacanalyze (Oid relid, AutoVacOpts *avopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
 
static void relation_needs_vacanalyze (Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, PgStat_StatTabEntry *tabentry, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
 
static void autovacuum_do_vac_analyze (autovac_table *tab, BufferAccessStrategy bstrategy)
 
static AutoVacOptsextract_autovac_opts (HeapTuple tup, TupleDesc pg_class_desc)
 
static void perform_work_item (AutoVacuumWorkItem *workitem)
 
static void autovac_report_activity (autovac_table *tab)
 
static void autovac_report_workitem (AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
 
static void avl_sigusr2_handler (SIGNAL_ARGS)
 
static bool av_worker_available (void)
 
static void check_av_worker_gucs (void)
 
void AutoVacLauncherMain (const void *startup_data, size_t startup_data_len)
 
void AutoVacWorkerFailed (void)
 
void AutoVacWorkerMain (const void *startup_data, size_t startup_data_len)
 
void VacuumUpdateCosts (void)
 
void AutoVacuumUpdateCostLimit (void)
 
bool AutoVacuumingActive (void)
 
bool AutoVacuumRequestWork (AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
 
void autovac_init (void)
 
Size AutoVacuumShmemSize (void)
 
void AutoVacuumShmemInit (void)
 
bool check_autovacuum_work_mem (int *newval, void **extra, GucSource source)
 

Variables

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

Macro Definition Documentation

◆ AutoVacNumSignals

#define AutoVacNumSignals   (AutoVacRebalance + 1)

Definition at line 255 of file autovacuum.c.

◆ MAX_AUTOVAC_ACTIV_LEN

#define MAX_AUTOVAC_ACTIV_LEN   (NAMEDATALEN * 2 + 56)

◆ MAX_AUTOVAC_SLEEPTIME

#define MAX_AUTOVAC_SLEEPTIME   300 /* seconds */

Definition at line 140 of file autovacuum.c.

◆ MIN_AUTOVAC_SLEEPTIME

#define MIN_AUTOVAC_SLEEPTIME   100.0 /* milliseconds */

Definition at line 139 of file autovacuum.c.

◆ NUM_WORKITEMS

#define NUM_WORKITEMS   256

Definition at line 273 of file autovacuum.c.

Typedef Documentation

◆ autovac_table

typedef struct autovac_table autovac_table

◆ AutoVacuumWorkItem

◆ av_relation

typedef struct av_relation av_relation

◆ avl_dbase

typedef struct avl_dbase avl_dbase

◆ avw_dbase

typedef struct avw_dbase avw_dbase

◆ WorkerInfo

typedef struct WorkerInfoData* WorkerInfo

Definition at line 242 of file autovacuum.c.

◆ WorkerInfoData

Enumeration Type Documentation

◆ AutoVacuumSignal

Enumerator
AutoVacForkFailed 
AutoVacRebalance 

Definition at line 249 of file autovacuum.c.

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

Function Documentation

◆ autovac_init()

void autovac_init ( void  )

Definition at line 3306 of file autovacuum.c.

3307{
3309 return;
3310 else if (!pgstat_track_counts)
3312 (errmsg("autovacuum not started because of misconfiguration"),
3313 errhint("Enable the \"track_counts\" option.")));
3314 else
3316}
static void check_av_worker_gucs(void)
Definition: autovacuum.c:3430
bool autovacuum_start_daemon
Definition: autovacuum.c:118
int errhint(const char *fmt,...)
Definition: elog.c:1318
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define WARNING
Definition: elog.h:36
#define ereport(elevel,...)
Definition: elog.h:149
bool pgstat_track_counts
Definition: pgstat.c:203

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

Referenced by PostmasterMain().

◆ autovac_recalculate_workers_for_balance()

static void autovac_recalculate_workers_for_balance ( void  )
static

Definition at line 1773 of file autovacuum.c.

1774{
1775 dlist_iter iter;
1776 int orig_nworkers_for_balance;
1777 int nworkers_for_balance = 0;
1778
1779 Assert(LWLockHeldByMe(AutovacuumLock));
1780
1781 orig_nworkers_for_balance =
1783
1785 {
1786 WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1787
1788 if (worker->wi_proc == NULL ||
1790 continue;
1791
1792 nworkers_for_balance++;
1793 }
1794
1795 if (nworkers_for_balance != orig_nworkers_for_balance)
1797 nworkers_for_balance);
1798}
static bool pg_atomic_unlocked_test_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:196
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:276
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:239
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:304
Assert(PointerIsAligned(start, uint64))
#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:1985
pg_atomic_uint32 av_nworkersForBalance
Definition: autovacuum.c:301
dlist_head av_runningWorkers
Definition: autovacuum.c:298
PGPROC * wi_proc
Definition: autovacuum.c:236
pg_atomic_flag wi_dobalance
Definition: autovacuum.c:238
dlist_node * cur
Definition: ilist.h:179

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

3178{
3179#define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3180 char activity[MAX_AUTOVAC_ACTIV_LEN];
3181 int len;
3182
3183 /* Report the command and possible options */
3184 if (tab->at_params.options & VACOPT_VACUUM)
3186 "autovacuum: VACUUM%s",
3187 tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3188 else
3190 "autovacuum: ANALYZE");
3191
3192 /*
3193 * Report the qualified name of the relation.
3194 */
3195 len = strlen(activity);
3196
3197 snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3198 " %s.%s%s", tab->at_nspname, tab->at_relname,
3199 tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3200
3201 /* Set statement_timestamp() to current time for pg_stat_activity */
3203
3205}
#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:239
bits32 options
Definition: vacuum.h:219
bool is_wraparound
Definition: vacuum.h:226
char * at_nspname
Definition: autovacuum.c:209
char * at_relname
Definition: autovacuum.c:208
VacuumParams at_params
Definition: autovacuum.c:203
#define VACOPT_VACUUM
Definition: vacuum.h:180
#define VACOPT_ANALYZE
Definition: vacuum.h:181
void SetCurrentStatementStartTimestamp(void)
Definition: xact.c:914

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

Referenced by autovacuum_do_vac_analyze().

◆ autovac_report_workitem()

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

Definition at line 3212 of file autovacuum.c.

3214{
3215 char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3216 char blk[12 + 2];
3217 int len;
3218
3219 switch (workitem->avw_type)
3220 {
3223 "autovacuum: BRIN summarize");
3224 break;
3225 }
3226
3227 /*
3228 * Report the qualified name of the relation, and the block number if any
3229 */
3230 len = strlen(activity);
3231
3232 if (BlockNumberIsValid(workitem->avw_blockNumber))
3233 snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3234 else
3235 blk[0] = '\0';
3236
3237 snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3238 " %s.%s%s", nspname, relname, blk);
3239
3240 /* Set statement_timestamp() to current time for pg_stat_activity */
3242
3244}
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition: block.h:71
NameData relname
Definition: pg_class.h:38
BlockNumber avw_blockNumber
Definition: autovacuum.c:270
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:265

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

Referenced by perform_work_item().

◆ AutoVacLauncherMain()

void AutoVacLauncherMain ( const void *  startup_data,
size_t  startup_data_len 
)

Definition at line 368 of file autovacuum.c.

369{
370 sigjmp_buf local_sigjmp_buf;
371
372 Assert(startup_data_len == 0);
373
374 /* Release postmaster's working memory context */
376 {
378 PostmasterContext = NULL;
379 }
380
382 init_ps_display(NULL);
383
385 (errmsg_internal("autovacuum launcher started")));
386
387 if (PostAuthDelay)
388 pg_usleep(PostAuthDelay * 1000000L);
389
391
392 /*
393 * Set up signal handlers. We operate on databases much like a regular
394 * backend, so we use the same signal handling. See equivalent code in
395 * tcop/postgres.c.
396 */
400 /* SIGQUIT handler was already set up by InitPostmasterChild */
401
402 InitializeTimeouts(); /* establishes SIGALRM handler */
403
404 pqsignal(SIGPIPE, SIG_IGN);
408 pqsignal(SIGCHLD, SIG_DFL);
409
410 /*
411 * Create a per-backend PGPROC struct in shared memory. We must do this
412 * before we can use LWLocks or access any shared memory.
413 */
414 InitProcess();
415
416 /* Early initialization */
417 BaseInit();
418
419 InitPostgres(NULL, InvalidOid, NULL, InvalidOid, 0, NULL);
420
422
423 /*
424 * Create a memory context that we will do all our work in. We do this so
425 * that we can reset the context during error recovery and thereby avoid
426 * possible memory leaks.
427 */
429 "Autovacuum Launcher",
432
433 /*
434 * If an exception is encountered, processing resumes here.
435 *
436 * This code is a stripped down version of PostgresMain error recovery.
437 *
438 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
439 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
440 * signals other than SIGQUIT will be blocked until we complete error
441 * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
442 * call redundant, but it is not since InterruptPending might be set
443 * already.
444 */
445 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
446 {
447 /* since not using PG_TRY, must reset error stack by hand */
448 error_context_stack = NULL;
449
450 /* Prevents interrupts while cleaning up */
452
453 /* Forget any pending QueryCancel or timeout request */
455 QueryCancelPending = false; /* second to avoid race condition */
456
457 /* Report the error to the server log */
459
460 /* Abort the current transaction in order to recover */
462
463 /*
464 * Release any other resources, for the case where we were not in a
465 * transaction.
466 */
471 /* this is probably dead code, but let's be safe: */
474 AtEOXact_Buffers(false);
476 AtEOXact_Files(false);
477 AtEOXact_HashTables(false);
478
479 /*
480 * Now return to normal top-level context and clear ErrorContext for
481 * next time.
482 */
485
486 /* Flush any leaked data in the top-level context */
488
489 /* don't leave dangling pointers to freed memory */
490 DatabaseListCxt = NULL;
492
493 /* Now we can allow interrupts again */
495
496 /* if in shutdown mode, no need for anything further; just go away */
499
500 /*
501 * Sleep at least 1 second after any error. We don't want to be
502 * filling the error logs as fast as we can.
503 */
504 pg_usleep(1000000L);
505 }
506
507 /* We can now handle ereport(ERROR) */
508 PG_exception_stack = &local_sigjmp_buf;
509
510 /* must unblock signals before calling rebuild_database_list */
511 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
512
513 /*
514 * Set always-secure search path. Launcher doesn't connect to a database,
515 * so this has no effect.
516 */
517 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
518
519 /*
520 * Force zero_damaged_pages OFF in the autovac process, even if it is set
521 * in postgresql.conf. We don't really want such a dangerous option being
522 * applied non-interactively.
523 */
524 SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
525
526 /*
527 * Force settable timeouts off to avoid letting these settings prevent
528 * regular maintenance from being executed.
529 */
530 SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
531 SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
532 SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
533 SetConfigOption("idle_in_transaction_session_timeout", "0",
535
536 /*
537 * Force default_transaction_isolation to READ COMMITTED. We don't want
538 * to pay the overhead of serializable mode, nor add any risk of causing
539 * deadlocks or delaying other transactions.
540 */
541 SetConfigOption("default_transaction_isolation", "read committed",
543
544 /*
545 * Even when system is configured to use a different fetch consistency,
546 * for autovac we always want fresh stats.
547 */
548 SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
549
550 /*
551 * In emergency mode, just start a worker (unless shutdown was requested)
552 * and go away.
553 */
554 if (!AutoVacuumingActive())
555 {
558 proc_exit(0); /* done */
559 }
560
562
563 /*
564 * Create the initial database list. The invariant we want this list to
565 * keep is that it's ordered by decreasing next_time. As soon as an entry
566 * is updated to a higher time, it will be moved to the front (which is
567 * correct because the only operation is to add autovacuum_naptime to the
568 * entry, and time always increases).
569 */
571
572 /* loop until shutdown request */
574 {
575 struct timeval nap;
576 TimestampTz current_time = 0;
577 bool can_launch;
578
579 /*
580 * This loop is a bit different from the normal use of WaitLatch,
581 * because we'd like to sleep before the first launch of a child
582 * process. So it's WaitLatch, then ResetLatch, then check for
583 * wakening conditions.
584 */
585
587
588 /*
589 * Wait until naptime expires or we get some type of signal (all the
590 * signal handlers will wake us by calling SetLatch).
591 */
592 (void) WaitLatch(MyLatch,
594 (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
595 WAIT_EVENT_AUTOVACUUM_MAIN);
596
598
600
601 /*
602 * a worker finished, or postmaster signaled failure to start a worker
603 */
604 if (got_SIGUSR2)
605 {
606 got_SIGUSR2 = false;
607
608 /* rebalance cost limits, if needed */
610 {
611 LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
614 LWLockRelease(AutovacuumLock);
615 }
616
618 {
619 /*
620 * If the postmaster failed to start a new worker, we sleep
621 * for a little while and resend the signal. The new worker's
622 * state is still in memory, so this is sufficient. After
623 * that, we restart the main loop.
624 *
625 * XXX should we put a limit to the number of times we retry?
626 * I don't think it makes much sense, because a future start
627 * of a worker will continue to fail in the same way.
628 */
630 pg_usleep(1000000L); /* 1s */
632 continue;
633 }
634 }
635
636 /*
637 * There are some conditions that we need to check before trying to
638 * start a worker. First, we need to make sure that there is a worker
639 * slot available. Second, we need to make sure that no other worker
640 * failed while starting up.
641 */
642
643 current_time = GetCurrentTimestamp();
644 LWLockAcquire(AutovacuumLock, LW_SHARED);
645
646 can_launch = av_worker_available();
647
649 {
650 int waittime;
652
653 /*
654 * We can't launch another worker when another one is still
655 * starting up (or failed while doing so), so just sleep for a bit
656 * more; that worker will wake us up again as soon as it's ready.
657 * We will only wait autovacuum_naptime seconds (up to a maximum
658 * of 60 seconds) for this to happen however. Note that failure
659 * to connect to a particular database is not a problem here,
660 * because the worker removes itself from the startingWorker
661 * pointer before trying to connect. Problems detected by the
662 * postmaster (like fork() failure) are also reported and handled
663 * differently. The only problems that may cause this code to
664 * fire are errors in the earlier sections of AutoVacWorkerMain,
665 * before the worker removes the WorkerInfo from the
666 * startingWorker pointer.
667 */
668 waittime = Min(autovacuum_naptime, 60) * 1000;
669 if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
670 waittime))
671 {
672 LWLockRelease(AutovacuumLock);
673 LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
674
675 /*
676 * No other process can put a worker in starting mode, so if
677 * startingWorker is still INVALID after exchanging our lock,
678 * we assume it's the same one we saw above (so we don't
679 * recheck the launch time).
680 */
682 {
684 worker->wi_dboid = InvalidOid;
685 worker->wi_tableoid = InvalidOid;
686 worker->wi_sharedrel = false;
687 worker->wi_proc = NULL;
688 worker->wi_launchtime = 0;
690 &worker->wi_links);
693 errmsg("autovacuum worker took too long to start; canceled"));
694 }
695 }
696 else
697 can_launch = false;
698 }
699 LWLockRelease(AutovacuumLock); /* either shared or exclusive */
700
701 /* if we can't do anything, just go back to sleep */
702 if (!can_launch)
703 continue;
704
705 /* We're OK to start a new worker */
706
708 {
709 /*
710 * Special case when the list is empty: start a worker right away.
711 * This covers the initial case, when no database is in pgstats
712 * (thus the list is empty). Note that the constraints in
713 * launcher_determine_sleep keep us from starting workers too
714 * quickly (at most once every autovacuum_naptime when the list is
715 * empty).
716 */
717 launch_worker(current_time);
718 }
719 else
720 {
721 /*
722 * because rebuild_database_list constructs a list with most
723 * distant adl_next_worker first, we obtain our database from the
724 * tail of the list.
725 */
726 avl_dbase *avdb;
727
728 avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
729
730 /*
731 * launch a worker if next_worker is right now or it is in the
732 * past
733 */
735 current_time, 0))
736 launch_worker(current_time);
737 }
738 }
739
741}
void pgaio_error_cleanup(void)
Definition: aio.c:1078
static Oid do_start_worker(void)
Definition: autovacuum.c:1094
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition: autovacuum.c:813
static volatile sig_atomic_t got_SIGUSR2
Definition: autovacuum.c:155
static void avl_sigusr2_handler(SIGNAL_ARGS)
Definition: autovacuum.c:1365
static bool av_worker_available(void)
Definition: autovacuum.c:3413
int autovacuum_naptime
Definition: autovacuum.c:122
bool AutoVacuumingActive(void)
Definition: autovacuum.c:3252
static pg_noreturn void AutoVacLauncherShutdown(void)
Definition: autovacuum.c:796
static void launch_worker(TimestampTz now)
Definition: autovacuum.c:1306
static dlist_head DatabaseList
Definition: autovacuum.c:310
static void rebuild_database_list(Oid newdb)
Definition: autovacuum.c:897
static MemoryContext DatabaseListCxt
Definition: autovacuum.c:311
static void autovac_recalculate_workers_for_balance(void)
Definition: autovacuum.c:1773
static MemoryContext AutovacMemCxt
Definition: autovacuum.c:168
static void ProcessAutoVacLauncherInterrupts(void)
Definition: autovacuum.c:747
sigset_t UnBlockSig
Definition: pqsignal.c:22
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1781
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:3996
void UnlockBuffers(void)
Definition: bufmgr.c:5579
#define Min(x, y)
Definition: c.h:975
int64 TimestampTz
Definition: timestamp.h:39
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1913
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1158
void EmitErrorReport(void)
Definition: elog.c:1692
ErrorContextCallback * error_context_stack
Definition: elog.c:95
void FlushErrorState(void)
Definition: elog.c:1872
sigjmp_buf * PG_exception_stack
Definition: elog.c:97
#define DEBUG1
Definition: elog.h:30
void AtEOXact_Files(bool isCommit)
Definition: fd.c:3229
int MyProcPid
Definition: globals.c:48
volatile sig_atomic_t QueryCancelPending
Definition: globals.c:33
struct Latch * MyLatch
Definition: globals.c:64
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4332
@ 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:109
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:28
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:65
void proc_exit(int code)
Definition: ipc.c:104
void ResetLatch(Latch *latch)
Definition: latch.c:372
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:1182
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1902
void LWLockReleaseAll(void)
Definition: lwlock.c:1953
@ LW_SHARED
Definition: lwlock.h:115
@ LW_EXCLUSIVE
Definition: lwlock.h:114
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:414
MemoryContext TopMemoryContext
Definition: mcxt.c:165
MemoryContext PostmasterContext
Definition: mcxt.c:167
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:485
#define AllocSetContextCreate
Definition: memutils.h:149
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:180
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:136
@ NormalProcessing
Definition: miscadmin.h:472
@ InitProcessing
Definition: miscadmin.h:471
#define GetProcessingMode()
Definition: miscadmin.h:481
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:134
#define SetProcessingMode(mode)
Definition: miscadmin.h:483
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:344
BackendType MyBackendType
Definition: miscinit.c:64
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:165
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition: pmsignal.h:40
#define pqsignal
Definition: port.h:531
int PostAuthDelay
Definition: postgres.c:99
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3075
void StatementCancelHandler(SIGNAL_ARGS)
Definition: postgres.c:3058
#define InvalidOid
Definition: postgres_ext.h:35
void BaseInit(void)
Definition: postinit.c:612
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:719
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:673
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:269
void ReleaseAuxProcessResources(bool isCommit)
Definition: resowner.c:1019
ResourceOwner AuxProcessResourceOwner
Definition: resowner.c:176
void pg_usleep(long microsec)
Definition: signal.c:53
void AtEOXact_SMgr(void)
Definition: smgr.c:1008
void InitProcess(void)
Definition: proc.c:391
dclist_head av_freeWorkers
Definition: autovacuum.c:297
WorkerInfo av_startingWorker
Definition: autovacuum.c:299
sig_atomic_t av_signal[AutoVacNumSignals]
Definition: autovacuum.c:295
TimestampTz wi_launchtime
Definition: autovacuum.c:237
dlist_node wi_links
Definition: autovacuum.c:233
TimestampTz adl_next_worker
Definition: autovacuum.c:174
void disable_all_timeouts(bool keep_indicators)
Definition: timeout.c:751
void InitializeTimeouts(void)
Definition: timeout.c:470
static void pgstat_report_wait_end(void)
Definition: wait_event.h:101
#define WL_TIMEOUT
Definition: waiteventset.h:37
#define WL_EXIT_ON_PM_DEATH
Definition: waiteventset.h:39
#define WL_LATCH_SET
Definition: waiteventset.h:34
#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:3451

References AbortCurrentTransaction(), avl_dbase::adl_next_worker, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), AtEOXact_Buffers(), AtEOXact_Files(), AtEOXact_HashTables(), AtEOXact_SMgr(), autovac_recalculate_workers_for_balance(), AutoVacForkFailed, AutoVacLauncherShutdown(), AutovacMemCxt, AutoVacRebalance, autovacuum_naptime, AutoVacuumingActive(), AutoVacuumShmem, AuxProcessResourceOwner, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_signal, AutoVacuumShmemStruct::av_startingWorker, av_worker_available(), avl_sigusr2_handler(), B_AUTOVAC_LAUNCHER, 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, 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, MyBackendType, MyLatch, MyProcPid, NormalProcessing, PG_exception_stack, pg_usleep(), pgaio_error_cleanup(), PGC_S_OVERRIDE, PGC_SUSET, pgstat_report_wait_end(), PMSIGNAL_START_AUTOVAC_WORKER, PostAuthDelay, PostmasterContext, pqsignal, proc_exit(), ProcessAutoVacLauncherInterrupts(), procsignal_sigusr1_handler(), QueryCancelPending, rebuild_database_list(), ReleaseAuxProcessResources(), ResetLatch(), RESUME_INTERRUPTS, SendPostmasterSignal(), SetConfigOption(), SetProcessingMode, ShutdownRequestPending, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGPIPE, SIGUSR1, SIGUSR2, StatementCancelHandler(), TimestampDifferenceExceeds(), TopMemoryContext, UnBlockSig, UnlockBuffers(), WaitLatch(), WARNING, WorkerInfoData::wi_dboid, WorkerInfoData::wi_launchtime, WorkerInfoData::wi_links, WorkerInfoData::wi_proc, WorkerInfoData::wi_sharedrel, WorkerInfoData::wi_tableoid, WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

◆ AutoVacLauncherShutdown()

static void AutoVacLauncherShutdown ( void  )
static

Definition at line 796 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain(), and ProcessAutoVacLauncherInterrupts().

◆ autovacuum_do_vac_analyze()

static void autovacuum_do_vac_analyze ( autovac_table tab,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 3141 of file autovacuum.c.

3142{
3143 RangeVar *rangevar;
3144 VacuumRelation *rel;
3145 List *rel_list;
3146 MemoryContext vac_context;
3147
3148 /* Let pgstat know what we're doing */
3150
3151 /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3152 rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3153 rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3154 rel_list = list_make1(rel);
3155
3157 "Vacuum",
3159
3160 vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3161
3162 MemoryContextDelete(vac_context);
3163}
static void autovac_report_activity(autovac_table *tab)
Definition: autovacuum.c:3177
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:159
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
Definition: pg_list.h:54
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, MemoryContext vac_context, bool isTopLevel)
Definition: vacuum.c:496

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

Referenced by do_autovacuum().

◆ AutoVacuumingActive()

bool AutoVacuumingActive ( void  )

◆ AutoVacuumRequestWork()

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

Definition at line 3264 of file autovacuum.c.

3266{
3267 int i;
3268 bool result = false;
3269
3270 LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3271
3272 /*
3273 * Locate an unused work item and fill it with the given data.
3274 */
3275 for (i = 0; i < NUM_WORKITEMS; i++)
3276 {
3278
3279 if (workitem->avw_used)
3280 continue;
3281
3282 workitem->avw_used = true;
3283 workitem->avw_active = false;
3284 workitem->avw_type = type;
3285 workitem->avw_database = MyDatabaseId;
3286 workitem->avw_relation = relationId;
3287 workitem->avw_blockNumber = blkno;
3288 result = true;
3289
3290 /* done */
3291 break;
3292 }
3293
3294 LWLockRelease(AutovacuumLock);
3295
3296 return result;
3297}
#define NUM_WORKITEMS
Definition: autovacuum.c:273
Oid MyDatabaseId
Definition: globals.c:95
int i
Definition: isn.c:77
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition: autovacuum.c:300
const char * type

References AutoVacuumShmem, AutoVacuumShmemStruct::av_workItems, AutoVacuumWorkItem::avw_active, AutoVacuumWorkItem::avw_blockNumber, AutoVacuumWorkItem::avw_database, AutoVacuumWorkItem::avw_relation, AutoVacuumWorkItem::avw_type, AutoVacuumWorkItem::avw_used, i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyDatabaseId, NUM_WORKITEMS, and type.

Referenced by brininsert().

◆ AutoVacuumShmemInit()

void AutoVacuumShmemInit ( void  )

Definition at line 3342 of file autovacuum.c.

3343{
3344 bool found;
3345
3347 ShmemInitStruct("AutoVacuum Data",
3349 &found);
3350
3351 if (!IsUnderPostmaster)
3352 {
3353 WorkerInfo worker;
3354 int i;
3355
3356 Assert(!found);
3357
3362 memset(AutoVacuumShmem->av_workItems, 0,
3364
3365 worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3367
3368 /* initialize the WorkerInfo free list */
3369 for (i = 0; i < autovacuum_worker_slots; i++)
3370 {
3372 &worker[i].wi_links);
3373 pg_atomic_init_flag(&worker[i].wi_dobalance);
3374 }
3375
3377
3378 }
3379 else
3380 Assert(found);
3381}
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:221
static void pg_atomic_init_flag(volatile pg_atomic_flag *ptr)
Definition: atomics.h:170
int autovacuum_worker_slots
Definition: autovacuum.c:119
Size AutoVacuumShmemSize(void)
Definition: autovacuum.c:3323
struct WorkerInfoData * WorkerInfo
Definition: autovacuum.c:242
#define MAXALIGN(LEN)
Definition: c.h:782
bool IsUnderPostmaster
Definition: globals.c:121
static void dclist_init(dclist_head *head)
Definition: ilist.h:671
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387

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

Referenced by CreateOrAttachShmemStructs().

◆ AutoVacuumShmemSize()

Size AutoVacuumShmemSize ( void  )

Definition at line 3323 of file autovacuum.c.

3324{
3325 Size size;
3326
3327 /*
3328 * Need the fixed struct and the array of WorkerInfoData.
3329 */
3330 size = sizeof(AutoVacuumShmemStruct);
3331 size = MAXALIGN(size);
3333 sizeof(WorkerInfoData)));
3334 return size;
3335}
size_t Size
Definition: c.h:576
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510

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

Referenced by AutoVacuumShmemInit(), and CalculateShmemSize().

◆ AutoVacuumUpdateCostLimit()

void AutoVacuumUpdateCostLimit ( void  )

Definition at line 1727 of file autovacuum.c.

1728{
1729 if (!MyWorkerInfo)
1730 return;
1731
1732 /*
1733 * note: in cost_limit, zero also means use value from elsewhere, because
1734 * zero is not a valid value.
1735 */
1736
1739 else
1740 {
1741 int nworkers_for_balance;
1742
1745 else
1747
1748 /* Only balance limit if no cost-related storage parameters specified */
1750 return;
1751
1753
1755
1756 /* There is at least 1 autovac worker (this worker) */
1757 if (nworkers_for_balance <= 0)
1758 elog(ERROR, "nworkers_for_balance must be > 0");
1759
1760 vacuum_cost_limit = Max(vacuum_cost_limit / nworkers_for_balance, 1);
1761 }
1762}
int autovacuum_vac_cost_limit
Definition: autovacuum.c:134
static int av_storage_param_cost_limit
Definition: autovacuum.c:152
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:314
#define Max(x, y)
Definition: c.h:969
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
int VacuumCostLimit
Definition: globals.c:155
int vacuum_cost_limit
Definition: vacuum.c:90

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

Referenced by vacuum_delay_point(), and VacuumUpdateCosts().

◆ AutoVacWorkerFailed()

void AutoVacWorkerFailed ( void  )

Definition at line 1358 of file autovacuum.c.

1359{
1361}

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

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

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

3414{
3415 int free_slots;
3416 int reserved_slots;
3417
3419
3421 reserved_slots = Max(0, reserved_slots);
3422
3423 return free_slots > reserved_slots;
3424}
int autovacuum_max_workers
Definition: autovacuum.c:120
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(), and Max.

Referenced by AutoVacLauncherMain(), and do_start_worker().

◆ avl_sigusr2_handler()

static void avl_sigusr2_handler ( SIGNAL_ARGS  )
static

Definition at line 1365 of file autovacuum.c.

1366{
1367 got_SIGUSR2 = true;
1369}
void SetLatch(Latch *latch)
Definition: latch.c:288

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

3388{
3389 /*
3390 * -1 indicates fallback.
3391 *
3392 * If we haven't yet changed the boot_val default of -1, just let it be.
3393 * Autovacuum will look to maintenance_work_mem instead.
3394 */
3395 if (*newval == -1)
3396 return true;
3397
3398 /*
3399 * We clamp manually-set values to at least 64kB. Since
3400 * maintenance_work_mem is always set to at least this value, do the same
3401 * here.
3402 */
3403 if (*newval < 64)
3404 *newval = 64;
3405
3406 return true;
3407}
#define newval

References newval.

◆ check_av_worker_gucs()

static void check_av_worker_gucs ( void  )
static

Definition at line 3430 of file autovacuum.c.

3431{
3434 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3435 errmsg("\"autovacuum_max_workers\" (%d) should be less than or equal to \"autovacuum_worker_slots\" (%d)",
3437 errdetail("The server will only start up to \"autovacuum_worker_slots\" (%d) autovacuum workers at a given time.",
3439}
int errdetail(const char *fmt,...)
Definition: elog.c:1204
int errcode(int sqlerrcode)
Definition: elog.c:854

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

Referenced by autovac_init(), and ProcessAutoVacLauncherInterrupts().

◆ db_comparator()

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

Definition at line 1076 of file autovacuum.c.

1077{
1078 return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1079 ((const avl_dbase *) b)->adl_score);
1080}
static int pg_cmp_s32(int32 a, int32 b)
Definition: int.h:646
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 1889 of file autovacuum.c.

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

References AbortOutOfAnyTransaction(), AccessExclusiveLock, AccessShareLock, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, av_relation::ar_hasrelopts, av_relation::ar_relid, av_relation::ar_reloptions, autovac_table::at_datname, autovac_table::at_dobalance, autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relid, autovac_table::at_relname, autovac_table::at_storage_param_vac_cost_delay, autovac_table::at_storage_param_vac_cost_limit, autovac_recalculate_workers_for_balance(), AutovacMemCxt, autovacuum_do_vac_analyze(), AutoVacuumShmem, AutoVacuumShmemStruct::av_runningWorkers, av_storage_param_cost_delay, av_storage_param_cost_limit, AutoVacuumShmemStruct::av_workItems, AutoVacuumWorkItem::avw_active, AutoVacuumWorkItem::avw_database, AutoVacuumWorkItem::avw_used, BAS_VACUUM, BTEqualStrategyNumber, CharGetDatum(), CHECK_FOR_INTERRUPTS, checkTempNamespaceStatus(), CommitTransactionCommand(), ConditionalLockDatabaseObject(), ConditionalLockRelationOid(), ConfigReloadPending, CreateTupleDescCopy(), ctl, dlist_iter::cur, default_freeze_min_age, default_freeze_table_age, default_multixact_freeze_min_age, default_multixact_freeze_table_age, dlist_container, dlist_foreach, DROP_CASCADE, elog, EmitErrorReport(), ereport, errcontext, errmsg(), ERROR, extract_autovac_opts(), FlushErrorState(), ForwardScanDirection, get_database_name(), get_namespace_name(), get_rel_name(), get_rel_namespace(), GetAccessStrategyWithSize(), GETSTRUCT(), HASH_BLOBS, hash_create(), HASH_ELEM, HASH_ENTER, HASH_FIND, hash_search(), heap_getnext(), HeapTupleIsValid, HOLD_INTERRUPTS, i, INJECTION_POINT, InvalidOid, sort-test::key, lappend_oid(), lfirst_oid, LOG, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextReset(), MemoryContextSwitchTo(), MultiXactMemberFreezeThreshold(), MyDatabaseId, MyWorkerInfo, NameStr, NIL, NUM_WORKITEMS, ObjectIdGetDatum(), OidIsValid, VacuumParams::options, PERFORM_DELETION_INTERNAL, PERFORM_DELETION_QUIETLY, PERFORM_DELETION_SKIP_EXTENSIONS, perform_work_item(), performDeletion(), pfree(), pg_atomic_clear_flag(), pg_atomic_test_set_flag(), PG_CATCH, PG_END_TRY, PG_TRY, PGC_SIGHUP, pgstat_fetch_stat_tabentry_ext(), PortalContext, ProcessConfigFile(), QueryCancelPending, relation_needs_vacanalyze(), RelationGetDescr, ReleaseSysCache(), RESUME_INTERRUPTS, ScanKeyInit(), SearchSysCache1(), SearchSysCacheCopy1, StartTransactionCommand(), table_beginscan_catalog(), table_close(), table_endscan(), table_open(), table_recheck_autovac(), TEMP_NAMESPACE_IDLE, TopMemoryContext, UnlockRelationOid(), vac_update_datfrozenxid(), VACOPT_VACUUM, vacuum_freeze_min_age, vacuum_freeze_table_age, vacuum_multixact_freeze_min_age, vacuum_multixact_freeze_table_age, VacuumBufferUsageLimit, VacuumUpdateCosts(), WorkerInfoData::wi_dboid, WorkerInfoData::wi_dobalance, WorkerInfoData::wi_sharedrel, and WorkerInfoData::wi_tableoid.

Referenced by AutoVacWorkerMain().

◆ do_start_worker()

static Oid do_start_worker ( void  )
static

Definition at line 1094 of file autovacuum.c.

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

References avl_dbase::adl_datid, avl_dbase::adl_next_worker, avw_dbase::adw_datid, avw_dbase::adw_entry, avw_dbase::adw_frozenxid, avw_dbase::adw_minmulti, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, autovacuum_freeze_max_age, autovacuum_naptime, AutoVacuumShmem, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_startingWorker, av_worker_available(), dlist_iter::cur, CurrentMemoryContext, DatabaseList, dblist, dclist_pop_head_node(), dlist_container, dlist_reverse_foreach, FirstMultiXactId, FirstNormalTransactionId, get_database_list(), GetCurrentTimestamp(), InvalidOid, PgStat_StatDBEntry::last_autovac_time, lfirst, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextDelete(), MemoryContextSwitchTo(), MultiXactIdPrecedes(), MultiXactMemberFreezeThreshold(), pgstat_fetch_stat_dbentry(), PMSIGNAL_START_AUTOVAC_WORKER, ReadNextMultiXactId(), ReadNextTransactionId(), rebuild_database_list(), recentMulti, recentXid, SendPostmasterSignal(), TimestampDifferenceExceeds(), TransactionIdPrecedes(), WorkerInfoData::wi_dboid, WorkerInfoData::wi_launchtime, and WorkerInfoData::wi_proc.

Referenced by AutoVacLauncherMain(), and launch_worker().

◆ extract_autovac_opts()

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

Definition at line 2696 of file autovacuum.c.

2697{
2698 bytea *relopts;
2699 AutoVacOpts *av;
2700
2701 Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2702 ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2703 ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2704
2705 relopts = extractRelOptions(tup, pg_class_desc, NULL);
2706 if (relopts == NULL)
2707 return NULL;
2708
2709 av = palloc(sizeof(AutoVacOpts));
2710 memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2711 pfree(relopts);
2712
2713 return av;
2714}
void * palloc(Size size)
Definition: mcxt.c:1943
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
Definition: reloptions.c:1390
struct @10::@11 av[32]
Definition: c.h:658

References Assert(), av, extractRelOptions(), GETSTRUCT(), palloc(), and pfree().

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ FreeWorkerInfo()

static void FreeWorkerInfo ( int  code,
Datum  arg 
)
static

Definition at line 1610 of file autovacuum.c.

1611{
1612 if (MyWorkerInfo != NULL)
1613 {
1614 LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1615
1616 /*
1617 * Wake the launcher up so that he can launch a new worker immediately
1618 * if required. We only save the launcher's PID in local memory here;
1619 * the actual signal will be sent when the PGPROC is recycled. Note
1620 * that we always do this, so that the launcher can rebalance the cost
1621 * limit setting of the remaining workers.
1622 *
1623 * We somewhat ignore the risk that the launcher changes its PID
1624 * between us reading it and the actual kill; we expect ProcKill to be
1625 * called shortly after us, and we assume that PIDs are not reused too
1626 * quickly after a process exits.
1627 */
1629
1633 MyWorkerInfo->wi_sharedrel = false;
1634 MyWorkerInfo->wi_proc = NULL;
1639 /* not mine anymore */
1640 MyWorkerInfo = NULL;
1641
1642 /*
1643 * now that we're inactive, cause a rebalancing of the surviving
1644 * workers
1645 */
1647 LWLockRelease(AutovacuumLock);
1648 }
1649}
int AutovacuumLauncherPid
Definition: autovacuum.c:317
static void dlist_delete(dlist_node *node)
Definition: ilist.h:405

References AutoVacRebalance, AutovacuumLauncherPid, AutoVacuumShmem, AutoVacuumShmemStruct::av_freeWorkers, AutoVacuumShmemStruct::av_launcherpid, AutoVacuumShmemStruct::av_signal, dclist_push_head(), dlist_delete(), InvalidOid, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyWorkerInfo, pg_atomic_clear_flag(), WorkerInfoData::wi_dboid, WorkerInfoData::wi_dobalance, WorkerInfoData::wi_launchtime, WorkerInfoData::wi_links, WorkerInfoData::wi_proc, WorkerInfoData::wi_sharedrel, and WorkerInfoData::wi_tableoid.

Referenced by AutoVacWorkerMain().

◆ get_database_list()

static List * get_database_list ( void  )
static

Definition at line 1813 of file autovacuum.c.

1814{
1815 List *dblist = NIL;
1816 Relation rel;
1817 TableScanDesc scan;
1818 HeapTuple tup;
1819 MemoryContext resultcxt;
1820
1821 /* This is the context that we will allocate our output data in */
1822 resultcxt = CurrentMemoryContext;
1823
1824 /*
1825 * Start a transaction so we can access pg_database.
1826 */
1828
1829 rel = table_open(DatabaseRelationId, AccessShareLock);
1830 scan = table_beginscan_catalog(rel, 0, NULL);
1831
1833 {
1834 Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1835 avw_dbase *avdb;
1836 MemoryContext oldcxt;
1837
1838 /*
1839 * If database has partially been dropped, we can't, nor need to,
1840 * vacuum it.
1841 */
1842 if (database_is_invalid_form(pgdatabase))
1843 {
1844 elog(DEBUG2,
1845 "autovacuum: skipping invalid database \"%s\"",
1846 NameStr(pgdatabase->datname));
1847 continue;
1848 }
1849
1850 /*
1851 * Allocate our results in the caller's context, not the
1852 * transaction's. We do this inside the loop, and restore the original
1853 * context at the end, so that leaky things like heap_getnext() are
1854 * not called in a potentially long-lived context.
1855 */
1856 oldcxt = MemoryContextSwitchTo(resultcxt);
1857
1858 avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1859
1860 avdb->adw_datid = pgdatabase->oid;
1861 avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1862 avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1863 avdb->adw_minmulti = pgdatabase->datminmxid;
1864 /* this gets set later: */
1865 avdb->adw_entry = NULL;
1866
1867 dblist = lappend(dblist, avdb);
1868 MemoryContextSwitchTo(oldcxt);
1869 }
1870
1871 table_endscan(scan);
1873
1875
1876 /* Be sure to restore caller's memory context */
1877 MemoryContextSwitchTo(resultcxt);
1878
1879 return dblist;
1880}
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3212
#define DEBUG2
Definition: elog.h:29
List * lappend(List *list, void *datum)
Definition: list.c:339
char * pstrdup(const char *in)
Definition: mcxt.c:2325
char * adw_name
Definition: autovacuum.c:183

References AccessShareLock, avw_dbase::adw_datid, avw_dbase::adw_entry, avw_dbase::adw_frozenxid, avw_dbase::adw_minmulti, avw_dbase::adw_name, CommitTransactionCommand(), CurrentMemoryContext, database_is_invalid_form(), dblist, DEBUG2, elog, ForwardScanDirection, GETSTRUCT(), heap_getnext(), HeapTupleIsValid, lappend(), MemoryContextSwitchTo(), NameStr, NIL, palloc(), pstrdup(), StartTransactionCommand(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by do_start_worker(), and rebuild_database_list().

◆ launch_worker()

static void launch_worker ( TimestampTz  now)
static

Definition at line 1306 of file autovacuum.c.

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

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

Referenced by AutoVacLauncherMain().

◆ launcher_determine_sleep()

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

Definition at line 813 of file autovacuum.c.

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

References avl_dbase::adl_next_worker, autovacuum_naptime, DatabaseList, dlist_is_empty(), dlist_tail_element, 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 2582 of file autovacuum.c.

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

References AbortOutOfAnyTransaction(), Assert(), autovac_report_workitem(), AutovacMemCxt, AutoVacuumWorkItem::avw_blockNumber, AVW_BRINSummarizeRange, AutoVacuumWorkItem::avw_relation, AutoVacuumWorkItem::avw_type, brin_summarize_range(), CurrentMemoryContext, DirectFunctionCall2, elog, EmitErrorReport(), errcontext, FlushErrorState(), get_database_name(), get_namespace_name(), get_rel_name(), get_rel_namespace(), HOLD_INTERRUPTS, Int64GetDatum(), MemoryContextReset(), MemoryContextSwitchTo(), MyDatabaseId, ObjectIdGetDatum(), pfree(), PG_CATCH, PG_END_TRY, PG_TRY, PortalContext, QueryCancelPending, RESUME_INTERRUPTS, StartTransactionCommand(), and WARNING.

Referenced by do_autovacuum().

◆ ProcessAutoVacLauncherInterrupts()

static void ProcessAutoVacLauncherInterrupts ( void  )
static

Definition at line 747 of file autovacuum.c.

748{
749 /* the normal shutdown case */
752
754 {
755 int autovacuum_max_workers_prev = autovacuum_max_workers;
756
757 ConfigReloadPending = false;
759
760 /* shutdown requested in config file? */
761 if (!AutoVacuumingActive())
763
764 /*
765 * If autovacuum_max_workers changed, emit a WARNING if
766 * autovacuum_worker_slots < autovacuum_max_workers. If it didn't
767 * change, skip this to avoid too many repeated log messages.
768 */
769 if (autovacuum_max_workers_prev != autovacuum_max_workers)
771
772 /* rebuild the list in case the naptime changed */
774 }
775
776 /* Process barrier events */
779
780 /* Perform logging of memory contexts of this process */
783
784 /* Publish memory contexts of this process */
787
788 /* Process sinval catchup interrupts that happened while sleeping */
790}
volatile sig_atomic_t LogMemoryContextPending
Definition: globals.c:41
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:40
volatile sig_atomic_t PublishMemoryContextPending
Definition: globals.c:42
void ProcessGetMemoryContextInterrupt(void)
Definition: mcxt.c:1436
void ProcessLogMemoryContextInterrupt(void)
Definition: mcxt.c:1384
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:498
void ProcessCatchupInterrupt(void)
Definition: sinval.c:174

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

Referenced by AutoVacLauncherMain().

◆ rebuild_database_list()

static void rebuild_database_list ( Oid  newdb)
static

Definition at line 897 of file autovacuum.c.

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

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

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

◆ recheck_relation_needs_vacanalyze()

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

Definition at line 2872 of file autovacuum.c.

2879{
2880 PgStat_StatTabEntry *tabentry;
2881
2882 /* fetch the pgstat table entry */
2883 tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2884 relid);
2885
2886 relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2887 effective_multixact_freeze_max_age,
2888 dovacuum, doanalyze, wraparound);
2889
2890 /* ignore ANALYZE for toast tables */
2891 if (classForm->relkind == RELKIND_TOASTVALUE)
2892 *doanalyze = false;
2893}

References pgstat_fetch_stat_tabentry_ext(), and relation_needs_vacanalyze().

Referenced by table_recheck_autovac().

◆ relation_needs_vacanalyze()

static void relation_needs_vacanalyze ( Oid  relid,
AutoVacOpts relopts,
Form_pg_class  classForm,
PgStat_StatTabEntry tabentry,
int  effective_multixact_freeze_max_age,
bool *  dovacuum,
bool *  doanalyze,
bool *  wraparound 
)
static

Definition at line 2935 of file autovacuum.c.

2944{
2945 bool force_vacuum;
2946 bool av_enabled;
2947
2948 /* constants from reloptions or GUC variables */
2949 int vac_base_thresh,
2950 vac_max_thresh,
2951 vac_ins_base_thresh,
2952 anl_base_thresh;
2953 float4 vac_scale_factor,
2954 vac_ins_scale_factor,
2955 anl_scale_factor;
2956
2957 /* thresholds calculated from above constants */
2958 float4 vacthresh,
2959 vacinsthresh,
2960 anlthresh;
2961
2962 /* number of vacuum (resp. analyze) tuples at this time */
2963 float4 vactuples,
2964 instuples,
2965 anltuples;
2966
2967 /* freeze parameters */
2968 int freeze_max_age;
2969 int multixact_freeze_max_age;
2970 TransactionId xidForceLimit;
2971 TransactionId relfrozenxid;
2972 MultiXactId multiForceLimit;
2973
2974 Assert(classForm != NULL);
2975 Assert(OidIsValid(relid));
2976
2977 /*
2978 * Determine vacuum/analyze equation parameters. We have two possible
2979 * sources: the passed reloptions (which could be a main table or a toast
2980 * table), or the autovacuum GUC variables.
2981 */
2982
2983 /* -1 in autovac setting means use plain vacuum_scale_factor */
2984 vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
2985 ? relopts->vacuum_scale_factor
2987
2988 vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
2989 ? relopts->vacuum_threshold
2991
2992 /* -1 is used to disable max threshold */
2993 vac_max_thresh = (relopts && relopts->vacuum_max_threshold >= -1)
2994 ? relopts->vacuum_max_threshold
2996
2997 vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
2998 ? relopts->vacuum_ins_scale_factor
3000
3001 /* -1 is used to disable insert vacuums */
3002 vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3003 ? relopts->vacuum_ins_threshold
3005
3006 anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3007 ? relopts->analyze_scale_factor
3009
3010 anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3011 ? relopts->analyze_threshold
3013
3014 freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3017
3018 multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3019 ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3020 : effective_multixact_freeze_max_age;
3021
3022 av_enabled = (relopts ? relopts->enabled : true);
3023
3024 /* Force vacuum if table is at risk of wraparound */
3025 xidForceLimit = recentXid - freeze_max_age;
3026 if (xidForceLimit < FirstNormalTransactionId)
3027 xidForceLimit -= FirstNormalTransactionId;
3028 relfrozenxid = classForm->relfrozenxid;
3029 force_vacuum = (TransactionIdIsNormal(relfrozenxid) &&
3030 TransactionIdPrecedes(relfrozenxid, xidForceLimit));
3031 if (!force_vacuum)
3032 {
3033 MultiXactId relminmxid = classForm->relminmxid;
3034
3035 multiForceLimit = recentMulti - multixact_freeze_max_age;
3036 if (multiForceLimit < FirstMultiXactId)
3037 multiForceLimit -= FirstMultiXactId;
3038 force_vacuum = MultiXactIdIsValid(relminmxid) &&
3039 MultiXactIdPrecedes(relminmxid, multiForceLimit);
3040 }
3041 *wraparound = force_vacuum;
3042
3043 /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3044 if (!av_enabled && !force_vacuum)
3045 {
3046 *doanalyze = false;
3047 *dovacuum = false;
3048 return;
3049 }
3050
3051 /*
3052 * If we found stats for the table, and autovacuum is currently enabled,
3053 * make a threshold-based decision whether to vacuum and/or analyze. If
3054 * autovacuum is currently disabled, we must be here for anti-wraparound
3055 * vacuuming only, so don't vacuum (or analyze) anything that's not being
3056 * forced.
3057 */
3058 if (PointerIsValid(tabentry) && AutoVacuumingActive())
3059 {
3060 float4 pcnt_unfrozen = 1;
3061 float4 reltuples = classForm->reltuples;
3062 int32 relpages = classForm->relpages;
3063 int32 relallfrozen = classForm->relallfrozen;
3064
3065 vactuples = tabentry->dead_tuples;
3066 instuples = tabentry->ins_since_vacuum;
3067 anltuples = tabentry->mod_since_analyze;
3068
3069 /* If the table hasn't yet been vacuumed, take reltuples as zero */
3070 if (reltuples < 0)
3071 reltuples = 0;
3072
3073 /*
3074 * If we have data for relallfrozen, calculate the unfrozen percentage
3075 * of the table to modify insert scale factor. This helps us decide
3076 * whether or not to vacuum an insert-heavy table based on the number
3077 * of inserts to the more "active" part of the table.
3078 */
3079 if (relpages > 0 && relallfrozen > 0)
3080 {
3081 /*
3082 * It could be the stats were updated manually and relallfrozen >
3083 * relpages. Clamp relallfrozen to relpages to avoid nonsensical
3084 * calculations.
3085 */
3086 relallfrozen = Min(relallfrozen, relpages);
3087 pcnt_unfrozen = 1 - ((float4) relallfrozen / relpages);
3088 }
3089
3090 vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3091 if (vac_max_thresh >= 0 && vacthresh > (float4) vac_max_thresh)
3092 vacthresh = (float4) vac_max_thresh;
3093
3094 vacinsthresh = (float4) vac_ins_base_thresh +
3095 vac_ins_scale_factor * reltuples * pcnt_unfrozen;
3096 anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3097
3098 /*
3099 * Note that we don't need to take special consideration for stat
3100 * reset, because if that happens, the last vacuum and analyze counts
3101 * will be reset too.
3102 */
3103 if (vac_ins_base_thresh >= 0)
3104 elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3105 NameStr(classForm->relname),
3106 vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3107 else
3108 elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3109 NameStr(classForm->relname),
3110 vactuples, vacthresh, anltuples, anlthresh);
3111
3112 /* Determine if this table needs vacuum or analyze. */
3113 *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3114 (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3115 *doanalyze = (anltuples > anlthresh);
3116 }
3117 else
3118 {
3119 /*
3120 * Skip a table not found in stat hash, unless we have to force vacuum
3121 * for anti-wrap purposes. If it's not acted upon, there's no need to
3122 * vacuum it.
3123 */
3124 *dovacuum = force_vacuum;
3125 *doanalyze = false;
3126 }
3127
3128 /* ANALYZE refuses to work with pg_statistic */
3129 if (relid == StatisticRelationId)
3130 *doanalyze = false;
3131}
double autovacuum_vac_scale
Definition: autovacuum.c:125
int autovacuum_anl_thresh
Definition: autovacuum.c:128
int autovacuum_vac_thresh
Definition: autovacuum.c:123
double autovacuum_anl_scale
Definition: autovacuum.c:129
int autovacuum_vac_ins_thresh
Definition: autovacuum.c:126
double autovacuum_vac_ins_scale
Definition: autovacuum.c:127
int autovacuum_vac_max_thresh
Definition: autovacuum.c:124
#define PointerIsValid(pointer)
Definition: c.h:734
int32_t int32
Definition: c.h:498
float float4
Definition: c.h:600
#define DEBUG3
Definition: elog.h:28
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
int vacuum_ins_threshold
Definition: rel.h:316
int multixact_freeze_max_age
Definition: rel.h:323
float8 vacuum_scale_factor
Definition: rel.h:327
int analyze_threshold
Definition: rel.h:317
float8 vacuum_ins_scale_factor
Definition: rel.h:328
bool enabled
Definition: rel.h:313
int freeze_max_age
Definition: rel.h:320
int vacuum_max_threshold
Definition: rel.h:315
int vacuum_threshold
Definition: rel.h:314
float8 analyze_scale_factor
Definition: rel.h:329
PgStat_Counter ins_since_vacuum
Definition: pgstat.h:438
PgStat_Counter mod_since_analyze
Definition: pgstat.h:437
PgStat_Counter dead_tuples
Definition: pgstat.h:436
#define TransactionIdIsNormal(xid)
Definition: transam.h:42

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

Referenced by do_autovacuum(), and recheck_relation_needs_vacanalyze().

◆ table_recheck_autovac()

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

Definition at line 2726 of file autovacuum.c.

2729{
2730 Form_pg_class classForm;
2731 HeapTuple classTup;
2732 bool dovacuum;
2733 bool doanalyze;
2734 autovac_table *tab = NULL;
2735 bool wraparound;
2736 AutoVacOpts *avopts;
2737
2738 /* fetch the relation's relcache entry */
2739 classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2740 if (!HeapTupleIsValid(classTup))
2741 return NULL;
2742 classForm = (Form_pg_class) GETSTRUCT(classTup);
2743
2744 /*
2745 * Get the applicable reloptions. If it is a TOAST table, try to get the
2746 * main table reloptions if the toast table itself doesn't have.
2747 */
2748 avopts = extract_autovac_opts(classTup, pg_class_desc);
2749 if (classForm->relkind == RELKIND_TOASTVALUE &&
2750 avopts == NULL && table_toast_map != NULL)
2751 {
2752 av_relation *hentry;
2753 bool found;
2754
2755 hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2756 if (found && hentry->ar_hasrelopts)
2757 avopts = &hentry->ar_reloptions;
2758 }
2759
2760 recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2761 effective_multixact_freeze_max_age,
2762 &dovacuum, &doanalyze, &wraparound);
2763
2764 /* OK, it needs something done */
2765 if (doanalyze || dovacuum)
2766 {
2767 int freeze_min_age;
2768 int freeze_table_age;
2769 int multixact_freeze_min_age;
2770 int multixact_freeze_table_age;
2771 int log_min_duration;
2772
2773 /*
2774 * Calculate the vacuum cost parameters and the freeze ages. If there
2775 * are options set in pg_class.reloptions, use them; in the case of a
2776 * toast table, try the main table too. Otherwise use the GUC
2777 * defaults, autovacuum's own first and plain vacuum second.
2778 */
2779
2780 /* -1 in autovac setting means use log_autovacuum_min_duration */
2781 log_min_duration = (avopts && avopts->log_min_duration >= 0)
2782 ? avopts->log_min_duration
2784
2785 /* these do not have autovacuum-specific settings */
2786 freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2787 ? avopts->freeze_min_age
2789
2790 freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2791 ? avopts->freeze_table_age
2793
2794 multixact_freeze_min_age = (avopts &&
2795 avopts->multixact_freeze_min_age >= 0)
2796 ? avopts->multixact_freeze_min_age
2798
2799 multixact_freeze_table_age = (avopts &&
2800 avopts->multixact_freeze_table_age >= 0)
2803
2804 tab = palloc(sizeof(autovac_table));
2805 tab->at_relid = relid;
2806 tab->at_sharedrel = classForm->relisshared;
2807
2808 /*
2809 * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2810 * that vacuum() skips toast relations. Also note we tell vacuum() to
2811 * skip vac_update_datfrozenxid(); we'll do that separately.
2812 */
2813 tab->at_params.options =
2814 (dovacuum ? (VACOPT_VACUUM |
2817 (doanalyze ? VACOPT_ANALYZE : 0) |
2818 (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2819
2820 /*
2821 * index_cleanup and truncate are unspecified at first in autovacuum.
2822 * They will be filled in with usable values using their reloptions
2823 * (or reloption defaults) later.
2824 */
2827 /* As of now, we don't support parallel vacuum for autovacuum */
2828 tab->at_params.nworkers = -1;
2829 tab->at_params.freeze_min_age = freeze_min_age;
2830 tab->at_params.freeze_table_age = freeze_table_age;
2831 tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2832 tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2833 tab->at_params.is_wraparound = wraparound;
2834 tab->at_params.log_min_duration = log_min_duration;
2836
2837 /*
2838 * Later, in vacuum_rel(), we check reloptions for any
2839 * vacuum_max_eager_freeze_failure_rate override.
2840 */
2842 tab->at_storage_param_vac_cost_limit = avopts ?
2843 avopts->vacuum_cost_limit : 0;
2844 tab->at_storage_param_vac_cost_delay = avopts ?
2845 avopts->vacuum_cost_delay : -1;
2846 tab->at_relname = NULL;
2847 tab->at_nspname = NULL;
2848 tab->at_datname = NULL;
2849
2850 /*
2851 * If any of the cost delay parameters has been set individually for
2852 * this table, disable the balancing algorithm.
2853 */
2854 tab->at_dobalance =
2855 !(avopts && (avopts->vacuum_cost_limit > 0 ||
2856 avopts->vacuum_cost_delay >= 0));
2857 }
2858
2859 heap_freetuple(classTup);
2860 return tab;
2861}
int Log_autovacuum_min_duration
Definition: autovacuum.c:136
static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, bool *dovacuum, bool *doanalyze, bool *wraparound)
Definition: autovacuum.c:2872
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1435
int log_min_duration
Definition: rel.h:325
float8 vacuum_cost_delay
Definition: rel.h:326
int vacuum_cost_limit
Definition: rel.h:318
int multixact_freeze_table_age
Definition: rel.h:324
int freeze_min_age
Definition: rel.h:319
int freeze_table_age
Definition: rel.h:321
int multixact_freeze_min_age
Definition: rel.h:322
int nworkers
Definition: vacuum.h:246
int freeze_table_age
Definition: vacuum.h:221
VacOptValue truncate
Definition: vacuum.h:231
int freeze_min_age
Definition: vacuum.h:220
int multixact_freeze_min_age
Definition: vacuum.h:222
int multixact_freeze_table_age
Definition: vacuum.h:224
int log_min_duration
Definition: vacuum.h:227
Oid toast_parent
Definition: vacuum.h:232
VacOptValue index_cleanup
Definition: vacuum.h:230
double max_eager_freeze_failure_rate
Definition: vacuum.h:239
bool at_sharedrel
Definition: autovacuum.c:207
double vacuum_max_eager_freeze_failure_rate
Definition: vacuum.c:79
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:185
#define VACOPT_SKIP_DATABASE_STATS
Definition: vacuum.h:189
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:202
#define VACOPT_PROCESS_MAIN
Definition: vacuum.h:186

References av_relation::ar_hasrelopts, av_relation::ar_reloptions, autovac_table::at_datname, autovac_table::at_dobalance, autovac_table::at_nspname, autovac_table::at_params, autovac_table::at_relid, autovac_table::at_relname, autovac_table::at_sharedrel, autovac_table::at_storage_param_vac_cost_delay, autovac_table::at_storage_param_vac_cost_limit, default_freeze_min_age, default_freeze_table_age, default_multixact_freeze_min_age, default_multixact_freeze_table_age, extract_autovac_opts(), VacuumParams::freeze_min_age, AutoVacOpts::freeze_min_age, VacuumParams::freeze_table_age, AutoVacOpts::freeze_table_age, GETSTRUCT(), HASH_FIND, hash_search(), heap_freetuple(), HeapTupleIsValid, VacuumParams::index_cleanup, InvalidOid, VacuumParams::is_wraparound, Log_autovacuum_min_duration, VacuumParams::log_min_duration, AutoVacOpts::log_min_duration, VacuumParams::max_eager_freeze_failure_rate, VacuumParams::multixact_freeze_min_age, AutoVacOpts::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, AutoVacOpts::multixact_freeze_table_age, VacuumParams::nworkers, ObjectIdGetDatum(), VacuumParams::options, palloc(), recheck_relation_needs_vacanalyze(), SearchSysCacheCopy1, VacuumParams::toast_parent, VacuumParams::truncate, VACOPT_ANALYZE, VACOPT_PROCESS_MAIN, VACOPT_SKIP_DATABASE_STATS, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, VACOPTVALUE_UNSPECIFIED, AutoVacOpts::vacuum_cost_delay, AutoVacOpts::vacuum_cost_limit, and vacuum_max_eager_freeze_failure_rate.

Referenced by do_autovacuum().

◆ VacuumUpdateCosts()

void VacuumUpdateCosts ( void  )

Definition at line 1658 of file autovacuum.c.

1659{
1660 if (MyWorkerInfo)
1661 {
1664 else if (autovacuum_vac_cost_delay >= 0)
1666 else
1667 /* fall back to VacuumCostDelay */
1669
1671 }
1672 else
1673 {
1674 /* Must be explicit VACUUM or ANALYZE */
1677 }
1678
1679 /*
1680 * If configuration changes are allowed to impact VacuumCostActive, make
1681 * sure it is updated.
1682 */
1685 else if (vacuum_cost_delay > 0)
1686 VacuumCostActive = true;
1687 else
1688 {
1689 VacuumCostActive = false;
1691 }
1692
1693 /*
1694 * Since the cost logging requires a lock, avoid rendering the log message
1695 * in case we are using a message level where the log wouldn't be emitted.
1696 */
1698 {
1699 Oid dboid,
1700 tableoid;
1701
1702 Assert(!LWLockHeldByMe(AutovacuumLock));
1703
1704 LWLockAcquire(AutovacuumLock, LW_SHARED);
1705 dboid = MyWorkerInfo->wi_dboid;
1706 tableoid = MyWorkerInfo->wi_tableoid;
1707 LWLockRelease(AutovacuumLock);
1708
1709 elog(DEBUG2,
1710 "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1711 dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1713 vacuum_cost_delay > 0 ? "yes" : "no",
1714 VacuumFailsafeActive ? "yes" : "no");
1715 }
1716}
double autovacuum_vac_cost_delay
Definition: autovacuum.c:133
void AutoVacuumUpdateCostLimit(void)
Definition: autovacuum.c:1727
bool message_level_is_interesting(int elevel)
Definition: elog.c:273
bool VacuumCostActive
Definition: globals.c:159
int VacuumCostBalance
Definition: globals.c:158
double VacuumCostDelay
Definition: globals.c:156
double vacuum_cost_delay
Definition: vacuum.c:89
bool VacuumFailsafeActive
Definition: vacuum.c:108

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

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

Variable Documentation

◆ AutovacMemCxt

MemoryContext AutovacMemCxt
static

◆ autovacuum_anl_scale

double autovacuum_anl_scale

Definition at line 129 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

int autovacuum_anl_thresh

Definition at line 128 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

int autovacuum_freeze_max_age

◆ autovacuum_max_workers

int autovacuum_max_workers

◆ autovacuum_multixact_freeze_max_age

int autovacuum_multixact_freeze_max_age

◆ autovacuum_naptime

int autovacuum_naptime

◆ autovacuum_start_daemon

bool autovacuum_start_daemon = false

Definition at line 118 of file autovacuum.c.

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

◆ autovacuum_vac_cost_delay

double autovacuum_vac_cost_delay

Definition at line 133 of file autovacuum.c.

Referenced by VacuumUpdateCosts().

◆ autovacuum_vac_cost_limit

int autovacuum_vac_cost_limit

Definition at line 134 of file autovacuum.c.

Referenced by AutoVacuumUpdateCostLimit().

◆ autovacuum_vac_ins_scale

double autovacuum_vac_ins_scale

Definition at line 127 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

int autovacuum_vac_ins_thresh

Definition at line 126 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_max_thresh

int autovacuum_vac_max_thresh

Definition at line 124 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

double autovacuum_vac_scale

Definition at line 125 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

int autovacuum_vac_thresh

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

int autovacuum_work_mem = -1

Definition at line 121 of file autovacuum.c.

Referenced by dead_items_alloc(), and ginInsertCleanup().

◆ autovacuum_worker_slots

◆ AutovacuumLauncherPid

int AutovacuumLauncherPid = 0

Definition at line 317 of file autovacuum.c.

Referenced by FreeWorkerInfo(), and ProcKill().

◆ AutoVacuumShmem

◆ av_storage_param_cost_delay

double av_storage_param_cost_delay = -1
static

Definition at line 151 of file autovacuum.c.

Referenced by do_autovacuum(), and VacuumUpdateCosts().

◆ av_storage_param_cost_limit

int av_storage_param_cost_limit = -1
static

Definition at line 152 of file autovacuum.c.

Referenced by AutoVacuumUpdateCostLimit(), and do_autovacuum().

◆ DatabaseList

dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList)
static

◆ DatabaseListCxt

MemoryContext DatabaseListCxt = NULL
static

Definition at line 311 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and rebuild_database_list().

◆ default_freeze_min_age

int default_freeze_min_age
static

Definition at line 162 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_freeze_table_age

int default_freeze_table_age
static

Definition at line 163 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_multixact_freeze_min_age

int default_multixact_freeze_min_age
static

Definition at line 164 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ default_multixact_freeze_table_age

int default_multixact_freeze_table_age
static

Definition at line 165 of file autovacuum.c.

Referenced by do_autovacuum(), and table_recheck_autovac().

◆ got_SIGUSR2

volatile sig_atomic_t got_SIGUSR2 = false
static

Definition at line 155 of file autovacuum.c.

Referenced by AutoVacLauncherMain(), and avl_sigusr2_handler().

◆ Log_autovacuum_min_duration

int Log_autovacuum_min_duration = 600000

Definition at line 136 of file autovacuum.c.

Referenced by table_recheck_autovac().

◆ MyWorkerInfo

WorkerInfo MyWorkerInfo = NULL
static

◆ recentMulti

MultiXactId recentMulti
static

Definition at line 159 of file autovacuum.c.

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

◆ recentXid

TransactionId recentXid
static

Definition at line 158 of file autovacuum.c.

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