PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
autovacuum.h File Reference
#include "storage/block.h"
Include dependency graph for autovacuum.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Enumerations

enum  AutoVacuumWorkItemType { AVW_BRINSummarizeRange }
 

Functions

bool AutoVacuumingActive (void)
 
void autovac_init (void)
 
void AutoVacWorkerFailed (void)
 
pg_noreturn void AutoVacLauncherMain (const void *startup_data, size_t startup_data_len)
 
pg_noreturn void AutoVacWorkerMain (const void *startup_data, size_t startup_data_len)
 
bool AutoVacuumRequestWork (AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
 
Size AutoVacuumShmemSize (void)
 
void AutoVacuumShmemInit (void)
 

Variables

PGDLLIMPORT bool autovacuum_start_daemon
 
PGDLLIMPORT int autovacuum_worker_slots
 
PGDLLIMPORT int autovacuum_max_workers
 
PGDLLIMPORT int autovacuum_work_mem
 
PGDLLIMPORT int autovacuum_naptime
 
PGDLLIMPORT int autovacuum_vac_thresh
 
PGDLLIMPORT int autovacuum_vac_max_thresh
 
PGDLLIMPORT double autovacuum_vac_scale
 
PGDLLIMPORT int autovacuum_vac_ins_thresh
 
PGDLLIMPORT double autovacuum_vac_ins_scale
 
PGDLLIMPORT int autovacuum_anl_thresh
 
PGDLLIMPORT double autovacuum_anl_scale
 
PGDLLIMPORT int autovacuum_freeze_max_age
 
PGDLLIMPORT int autovacuum_multixact_freeze_max_age
 
PGDLLIMPORT double autovacuum_vac_cost_delay
 
PGDLLIMPORT int autovacuum_vac_cost_limit
 
PGDLLIMPORT int AutovacuumLauncherPid
 
PGDLLIMPORT int Log_autovacuum_min_duration
 

Enumeration Type Documentation

◆ AutoVacuumWorkItemType

Enumerator
AVW_BRINSummarizeRange 

Definition at line 23 of file autovacuum.h.

24{
AutoVacuumWorkItemType
Definition: autovacuum.h:24
@ AVW_BRINSummarizeRange
Definition: autovacuum.h:25

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

◆ AutoVacLauncherMain()

pg_noreturn 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
@ AutoVacRebalance
Definition: autovacuum.c:252
@ AutoVacForkFailed
Definition: autovacuum.c:251
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 AutoVacuumShmemStruct * AutoVacuumShmem
Definition: autovacuum.c:304
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
Assert(PointerIsAligned(start, uint64))
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:616
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition: postinit.c:723
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
PGPROC * wi_proc
Definition: autovacuum.c:236
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.

◆ 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
BlockNumber avw_blockNumber
Definition: autovacuum.c:270
AutoVacuumWorkItemType avw_type
Definition: autovacuum.c:265
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
pg_atomic_uint32 av_nworkersForBalance
Definition: autovacuum.c:301
dlist_head av_runningWorkers
Definition: autovacuum.c:298

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

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

pg_noreturn 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
static WorkerInfo MyWorkerInfo
Definition: autovacuum.c:314
#define OidIsValid(objectId)
Definition: c.h:746
#define elog(elevel,...)
Definition: elog.h:225
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.

Variable Documentation

◆ autovacuum_anl_scale

PGDLLIMPORT double autovacuum_anl_scale
extern

Definition at line 129 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_anl_thresh

PGDLLIMPORT int autovacuum_anl_thresh
extern

Definition at line 128 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_freeze_max_age

PGDLLIMPORT int autovacuum_freeze_max_age
extern

◆ autovacuum_max_workers

PGDLLIMPORT int autovacuum_max_workers
extern

◆ autovacuum_multixact_freeze_max_age

PGDLLIMPORT int autovacuum_multixact_freeze_max_age
extern

◆ autovacuum_naptime

PGDLLIMPORT int autovacuum_naptime
extern

◆ autovacuum_start_daemon

PGDLLIMPORT bool autovacuum_start_daemon
extern

Definition at line 118 of file autovacuum.c.

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

◆ autovacuum_vac_cost_delay

PGDLLIMPORT double autovacuum_vac_cost_delay
extern

Definition at line 133 of file autovacuum.c.

Referenced by VacuumUpdateCosts().

◆ autovacuum_vac_cost_limit

PGDLLIMPORT int autovacuum_vac_cost_limit
extern

Definition at line 134 of file autovacuum.c.

Referenced by AutoVacuumUpdateCostLimit().

◆ autovacuum_vac_ins_scale

PGDLLIMPORT double autovacuum_vac_ins_scale
extern

Definition at line 127 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_ins_thresh

PGDLLIMPORT int autovacuum_vac_ins_thresh
extern

Definition at line 126 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_max_thresh

PGDLLIMPORT int autovacuum_vac_max_thresh
extern

Definition at line 124 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_scale

PGDLLIMPORT double autovacuum_vac_scale
extern

Definition at line 125 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_vac_thresh

PGDLLIMPORT int autovacuum_vac_thresh
extern

Definition at line 123 of file autovacuum.c.

Referenced by relation_needs_vacanalyze().

◆ autovacuum_work_mem

PGDLLIMPORT int autovacuum_work_mem
extern

Definition at line 121 of file autovacuum.c.

Referenced by dead_items_alloc(), and ginInsertCleanup().

◆ autovacuum_worker_slots

◆ AutovacuumLauncherPid

PGDLLIMPORT int AutovacuumLauncherPid
extern

Definition at line 317 of file autovacuum.c.

Referenced by FreeWorkerInfo(), and ProcKill().

◆ Log_autovacuum_min_duration

PGDLLIMPORT int Log_autovacuum_min_duration
extern

Definition at line 136 of file autovacuum.c.

Referenced by table_recheck_autovac().