PostgreSQL Source Code git master
Loading...
Searching...
No Matches
autovacuum.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * autovacuum.c
4 *
5 * PostgreSQL Integrated Autovacuum Daemon
6 *
7 * The autovacuum system is structured in two different kinds of processes: the
8 * autovacuum launcher and the autovacuum worker. The launcher is an
9 * always-running process, started by the postmaster when the autovacuum GUC
10 * parameter is set. The launcher schedules autovacuum workers to be started
11 * when appropriate. The workers are the processes which execute the actual
12 * vacuuming; they connect to a database as determined in the launcher, and
13 * once connected they examine the catalogs to select the tables to vacuum.
14 *
15 * The autovacuum launcher cannot start the worker processes by itself,
16 * because doing so would cause robustness issues (namely, failure to shut
17 * them down on exceptional conditions, and also, since the launcher is
18 * connected to shared memory and is thus subject to corruption there, it is
19 * not as robust as the postmaster). So it leaves that task to the postmaster.
20 *
21 * There is an autovacuum shared memory area, where the launcher stores
22 * information about the database it wants vacuumed. When it wants a new
23 * worker to start, it sets a flag in shared memory and sends a signal to the
24 * postmaster. Then postmaster knows nothing more than it must start a worker;
25 * so it forks a new child, which turns into a worker. This new process
26 * connects to shared memory, and there it can inspect the information that the
27 * launcher has set up.
28 *
29 * If the fork() call fails in the postmaster, it sets a flag in the shared
30 * memory area, and sends a signal to the launcher. The launcher, upon
31 * noticing the flag, can try starting the worker again by resending the
32 * signal. Note that the failure can only be transient (fork failure due to
33 * high load, memory pressure, too many processes, etc); more permanent
34 * problems, like failure to connect to a database, are detected later in the
35 * worker and dealt with just by having the worker exit normally. The launcher
36 * will launch a new worker again later, per schedule.
37 *
38 * When the worker is done vacuuming it sends SIGUSR2 to the launcher. The
39 * launcher then wakes up and is able to launch another worker, if the schedule
40 * is so tight that a new worker is needed immediately. At this time the
41 * launcher can also balance the settings for the various remaining workers'
42 * cost-based vacuum delay feature.
43 *
44 * Note that there can be more than one worker in a database concurrently.
45 * They will store the table they are currently vacuuming in shared memory, so
46 * that other workers avoid being blocked waiting for the vacuum lock for that
47 * table. They will also fetch the last time the table was vacuumed from
48 * pgstats just before vacuuming each table, to avoid vacuuming a table that
49 * was just finished being vacuumed by another worker and thus is no longer
50 * noted in shared memory. However, there is a small window (due to not yet
51 * holding the relation lock) during which a worker may choose a table that was
52 * already vacuumed; this is a bug in the current design.
53 *
54 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
55 * Portions Copyright (c) 1994, Regents of the University of California
56 *
57 *
58 * IDENTIFICATION
59 * src/backend/postmaster/autovacuum.c
60 *
61 *-------------------------------------------------------------------------
62 */
63#include "postgres.h"
64
65#include <math.h>
66#include <signal.h>
67#include <sys/time.h>
68#include <unistd.h>
69
70#include "access/heapam.h"
71#include "access/htup_details.h"
72#include "access/multixact.h"
73#include "access/reloptions.h"
74#include "access/tableam.h"
75#include "access/transam.h"
76#include "access/xact.h"
77#include "catalog/dependency.h"
78#include "catalog/namespace.h"
79#include "catalog/pg_database.h"
81#include "commands/vacuum.h"
82#include "common/int.h"
83#include "funcapi.h"
84#include "lib/ilist.h"
85#include "libpq/pqsignal.h"
86#include "miscadmin.h"
87#include "nodes/makefuncs.h"
88#include "pgstat.h"
92#include "storage/aio_subsys.h"
93#include "storage/bufmgr.h"
94#include "storage/ipc.h"
95#include "storage/fd.h"
96#include "storage/latch.h"
97#include "storage/lmgr.h"
98#include "storage/pmsignal.h"
99#include "storage/proc.h"
100#include "storage/procsignal.h"
101#include "storage/smgr.h"
102#include "storage/subsystems.h"
103#include "tcop/tcopprot.h"
104#include "utils/fmgroids.h"
105#include "utils/fmgrprotos.h"
106#include "utils/guc_hooks.h"
108#include "utils/lsyscache.h"
109#include "utils/memutils.h"
110#include "utils/ps_status.h"
111#include "utils/rel.h"
112#include "utils/snapmgr.h"
113#include "utils/syscache.h"
114#include "utils/timeout.h"
115#include "utils/timestamp.h"
116#include "utils/tuplestore.h"
117#include "utils/wait_event.h"
118
119
120/*
121 * GUC parameters
122 */
144
147
148/* the minimum allowed time between two awakenings of the launcher */
149#define MIN_AUTOVAC_SLEEPTIME 100.0 /* milliseconds */
150#define MAX_AUTOVAC_SLEEPTIME 300 /* seconds */
151
152/*
153 * Variables to save the cost-related storage parameters for the current
154 * relation being vacuumed by this autovacuum worker. Using these, we can
155 * ensure we don't overwrite the values of vacuum_cost_delay and
156 * vacuum_cost_limit after reloading the configuration file. They are
157 * initialized to "invalid" values to indicate that no cost-related storage
158 * parameters were specified and will be set in do_autovacuum() after checking
159 * the storage parameters in table_recheck_autovac().
160 */
163
164/* Flags set by signal handlers */
165static volatile sig_atomic_t got_SIGUSR2 = false;
166
167/* Comparison points for determining whether freeze_max_age is exceeded */
170
171/* Default freeze ages to use for autovacuum (varies by database) */
176
177/* Memory context for long-lived data */
179
180/* struct to keep track of databases in launcher */
188
189/* struct to keep track of databases in worker */
198
199/* struct to keep track of tables to vacuum and/or analyze, in 1st pass */
200typedef struct av_relation
201{
202 Oid ar_toastrelid; /* hash key - must be first */
205 AutoVacOpts ar_reloptions; /* copy of AutoVacOpts from the main table's
206 * reloptions, or NULL if none */
208
209/* struct to keep track of tables to vacuum and/or analyze, after rechecking */
221
222/*-------------
223 * This struct holds information about a single worker's whereabouts. We keep
224 * an array of these in shared memory, sized according to
225 * autovacuum_worker_slots.
226 *
227 * wi_links entry into free list or running list
228 * wi_dboid OID of the database this worker is supposed to work on
229 * wi_tableoid OID of the table currently being vacuumed, if any
230 * wi_sharedrel flag indicating whether table is marked relisshared
231 * wi_proc pointer to PGPROC of the running worker, NULL if not started
232 * wi_launchtime Time at which this worker was launched
233 * wi_dobalance Whether this worker should be included in balance calculations
234 *
235 * All fields are protected by AutovacuumLock, except for wi_tableoid and
236 * wi_sharedrel which are protected by AutovacuumScheduleLock (note these
237 * two fields are read-only for everyone except that worker itself).
238 *-------------
239 */
250
252
253/*
254 * Possible signals received by the launcher from remote processes. These are
255 * stored atomically in shared memory so that other processes can set them
256 * without locking.
257 */
258typedef enum
259{
260 AutoVacForkFailed, /* failed trying to start a worker */
261 AutoVacRebalance, /* rebalance the cost limits */
263
264#define AutoVacNumSignals (AutoVacRebalance + 1)
265
266/*
267 * Autovacuum workitem array, stored in AutoVacuumShmem->av_workItems. This
268 * list is mostly protected by AutovacuumLock, except that if an item is
269 * marked 'active' other processes must not modify the work-identifying
270 * members.
271 */
281
282#define NUM_WORKITEMS 256
283
284/*-------------
285 * The main autovacuum shmem struct. On shared memory we store this main
286 * struct and the array of WorkerInfo structs. This struct keeps:
287 *
288 * av_signal set by other processes to indicate various conditions
289 * av_freeWorkers the WorkerInfo freelist
290 * av_runningWorkers the WorkerInfo non-free queue
291 * av_startingWorker pointer to WorkerInfo currently being started (cleared by
292 * the worker itself as soon as it's up and running)
293 * av_workItems work item array
294 * av_nworkersForBalance the number of autovacuum workers to use when
295 * calculating the per worker cost limit
296 *
297 * This struct is protected by AutovacuumLock, except for av_signal and parts
298 * of the worker list (see above).
299 *-------------
300 */
310
312
313static void AutoVacuumShmemRequest(void *arg);
314static void AutoVacuumShmemInit(void *arg);
315
320
321/*
322 * the database list (of avl_dbase elements) in the launcher, and the context
323 * that contains it
324 */
327
328/*
329 * This struct is used by relation_needs_vacanalyze() to return the table's
330 * score (i.e., the maximum of the component scores) as well as the component
331 * scores themselves.
332 */
333typedef struct
334{
335 double max; /* maximum of all values below */
336 double xid; /* transaction ID component */
337 double mxid; /* multixact ID component */
338 double vac; /* vacuum component */
339 double vac_ins; /* vacuum insert component */
340 double anl; /* analyze component */
342
343/*
344 * This struct is used to track and sort the list of tables to process.
345 */
346typedef struct
347{
349 double score;
351
352/*
353 * Dummy pointer to persuade Valgrind that we've not leaked the array of
354 * avl_dbase structs. Make it global to ensure the compiler doesn't
355 * optimize it away.
356 */
357#ifdef USE_VALGRIND
360#endif
361
362/* Pointer to my own WorkerInfo, valid on each worker */
364
365static Oid do_start_worker(void);
366static void ProcessAutoVacLauncherInterrupts(void);
367pg_noreturn static void AutoVacLauncherShutdown(void);
368static void launcher_determine_sleep(bool canlaunch, bool recursing,
369 struct timeval *nap);
370static void launch_worker(TimestampTz now);
371static List *get_database_list(void);
372static void rebuild_database_list(Oid newdb);
373static int db_comparator(const void *a, const void *b);
375
376static void do_autovacuum(void);
377static void FreeWorkerInfo(int code, Datum arg);
378
385 int elevel,
386 bool *dovacuum, bool *doanalyze, bool *wraparound,
388
390 BufferAccessStrategy bstrategy);
394static void autovac_report_activity(autovac_table *tab);
396 const char *nspname, const char *relname);
398static bool av_worker_available(void);
399static void check_av_worker_gucs(void);
400
401
402
403/********************************************************************
404 * AUTOVACUUM LAUNCHER CODE
405 ********************************************************************/
406
407/*
408 * Main entry point for the autovacuum launcher process.
409 */
410void
412{
414
416
417 /* Release postmaster's working memory context */
419 {
422 }
423
425
427 (errmsg_internal("autovacuum launcher started")));
428
429 if (PostAuthDelay)
430 pg_usleep(PostAuthDelay * 1000000L);
431
433
434 /*
435 * Set up signal handlers. We operate on databases much like a regular
436 * backend, so we use the same signal handling. See equivalent code in
437 * tcop/postgres.c.
438 */
442 /* SIGQUIT handler was already set up by InitPostmasterChild */
443
444 InitializeTimeouts(); /* establishes SIGALRM handler */
445
451
452 /*
453 * Create a per-backend PGPROC struct in shared memory. We must do this
454 * before we can use LWLocks or access any shared memory.
455 */
456 InitProcess();
457
458 /* Early initialization */
459 BaseInit();
460
462
464
465 /*
466 * Create a memory context that we will do all our work in. We do this so
467 * that we can reset the context during error recovery and thereby avoid
468 * possible memory leaks.
469 */
471 "Autovacuum Launcher",
474
475 /*
476 * If an exception is encountered, processing resumes here.
477 *
478 * This code is a stripped down version of PostgresMain error recovery.
479 *
480 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
481 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
482 * signals other than SIGQUIT will be blocked until we complete error
483 * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
484 * call redundant, but it is not since InterruptPending might be set
485 * already.
486 */
487 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
488 {
489 /* since not using PG_TRY, must reset error stack by hand */
491
492 /* Prevents interrupts while cleaning up */
494
495 /* Forget any pending QueryCancel or timeout request */
497 QueryCancelPending = false; /* second to avoid race condition */
498
499 /* Report the error to the server log */
501
502 /* Abort the current transaction in order to recover */
504
505 /*
506 * Release any other resources, for the case where we were not in a
507 * transaction.
508 */
513 /* this is probably dead code, but let's be safe: */
516 AtEOXact_Buffers(false);
518 AtEOXact_Files(false);
519 AtEOXact_HashTables(false);
520
521 /*
522 * Now return to normal top-level context and clear ErrorContext for
523 * next time.
524 */
527
528 /* Flush any leaked data in the top-level context */
530
531 /* don't leave dangling pointers to freed memory */
534
535 /* Now we can allow interrupts again */
537
538 /* if in shutdown mode, no need for anything further; just go away */
541
542 /*
543 * Sleep at least 1 second after any error. We don't want to be
544 * filling the error logs as fast as we can.
545 */
546 pg_usleep(1000000L);
547 }
548
549 /* We can now handle ereport(ERROR) */
551
552 /* must unblock signals before calling rebuild_database_list */
554
555 /*
556 * Set always-secure search path. Launcher doesn't connect to a database,
557 * so this has no effect.
558 */
559 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
560
561 /*
562 * Force zero_damaged_pages OFF in the autovac process, even if it is set
563 * in postgresql.conf. We don't really want such a dangerous option being
564 * applied non-interactively.
565 */
566 SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
567
568 /*
569 * Force settable timeouts off to avoid letting these settings prevent
570 * regular maintenance from being executed.
571 */
572 SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
573 SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
574 SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
575 SetConfigOption("idle_in_transaction_session_timeout", "0",
577
578 /*
579 * Force default_transaction_isolation to READ COMMITTED. We don't want
580 * to pay the overhead of serializable mode, nor add any risk of causing
581 * deadlocks or delaying other transactions.
582 */
583 SetConfigOption("default_transaction_isolation", "read committed",
585
586 /*
587 * Even when system is configured to use a different fetch consistency,
588 * for autovac we always want fresh stats.
589 */
590 SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
591
592 /*
593 * In emergency mode, just start a worker (unless shutdown was requested)
594 * and go away.
595 */
596 if (!AutoVacuumingActive())
597 {
600 proc_exit(0); /* done */
601 }
602
603 /*
604 * Create the initial database list. The invariant we want this list to
605 * keep is that it's ordered by decreasing next_worker. As soon as an
606 * entry is updated to a higher time, it will be moved to the front (which
607 * is correct because the only operation is to add autovacuum_naptime to
608 * the entry, and time always increases).
609 */
611
612 /* loop until shutdown request */
614 {
615 struct timeval nap;
617 bool can_launch;
618
619 /*
620 * This loop is a bit different from the normal use of WaitLatch,
621 * because we'd like to sleep before the first launch of a child
622 * process. So it's WaitLatch, then ResetLatch, then check for
623 * wakening conditions.
624 */
625
627
628 /*
629 * Wait until naptime expires or we get some type of signal (all the
630 * signal handlers will wake us by calling SetLatch).
631 */
634 (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
636
638
640
641 /*
642 * a worker finished, or postmaster signaled failure to start a worker
643 */
644 if (got_SIGUSR2)
645 {
646 got_SIGUSR2 = false;
647
648 /* rebalance cost limits, if needed */
650 {
655 }
656
658 {
659 /*
660 * If the postmaster failed to start a new worker, we sleep
661 * for a little while and resend the signal. The new worker's
662 * state is still in memory, so this is sufficient. After
663 * that, we restart the main loop.
664 *
665 * XXX should we put a limit to the number of times we retry?
666 * I don't think it makes much sense, because a future start
667 * of a worker will continue to fail in the same way.
668 */
670 pg_usleep(1000000L); /* 1s */
672 continue;
673 }
674 }
675
676 /*
677 * There are some conditions that we need to check before trying to
678 * start a worker. First, we need to make sure that there is a worker
679 * slot available. Second, we need to make sure that no other worker
680 * failed while starting up.
681 */
682
685
687
689 {
690 int waittime;
692
693 /*
694 * We can't launch another worker when another one is still
695 * starting up (or failed while doing so), so just sleep for a bit
696 * more; that worker will wake us up again as soon as it's ready.
697 * We will only wait autovacuum_naptime seconds (up to a maximum
698 * of 60 seconds) for this to happen however. Note that failure
699 * to connect to a particular database is not a problem here,
700 * because the worker removes itself from the startingWorker
701 * pointer before trying to connect. Problems detected by the
702 * postmaster (like fork() failure) are also reported and handled
703 * differently. The only problems that may cause this code to
704 * fire are errors in the earlier sections of AutoVacWorkerMain,
705 * before the worker removes the WorkerInfo from the
706 * startingWorker pointer.
707 */
708 waittime = Min(autovacuum_naptime, 60) * 1000;
710 waittime))
711 {
714
715 /*
716 * No other process can put a worker in starting mode, so if
717 * startingWorker is still INVALID after exchanging our lock,
718 * we assume it's the same one we saw above (so we don't
719 * recheck the launch time).
720 */
722 {
724 worker->wi_dboid = InvalidOid;
725 worker->wi_tableoid = InvalidOid;
726 worker->wi_sharedrel = false;
727 worker->wi_proc = NULL;
728 worker->wi_launchtime = 0;
730 &worker->wi_links);
733 errmsg("autovacuum worker took too long to start; canceled"));
734 }
735 }
736 else
737 can_launch = false;
738 }
739 LWLockRelease(AutovacuumLock); /* either shared or exclusive */
740
741 /* if we can't do anything, just go back to sleep */
742 if (!can_launch)
743 continue;
744
745 /* We're OK to start a new worker */
746
748 {
749 /*
750 * Special case when the list is empty: start a worker right away.
751 * This covers the initial case, when no database is in pgstats
752 * (thus the list is empty). Note that the constraints in
753 * launcher_determine_sleep keep us from starting workers too
754 * quickly (at most once every autovacuum_naptime when the list is
755 * empty).
756 */
758 }
759 else
760 {
761 /*
762 * because rebuild_database_list constructs a list with most
763 * distant adl_next_worker first, we obtain our database from the
764 * tail of the list.
765 */
767
769
770 /*
771 * launch a worker if next_worker is right now or it is in the
772 * past
773 */
774 if (TimestampDifferenceExceeds(avdb->adl_next_worker,
775 current_time, 0))
777 }
778 }
779
781}
782
783/*
784 * Process any new interrupts.
785 */
786static void
788{
789 /* the normal shutdown case */
792
794 {
796
797 ConfigReloadPending = false;
799
800 /* shutdown requested in config file? */
801 if (!AutoVacuumingActive())
803
804 /*
805 * If autovacuum_max_workers changed, emit a WARNING if
806 * autovacuum_worker_slots < autovacuum_max_workers. If it didn't
807 * change, skip this to avoid too many repeated log messages.
808 */
811
812 /* rebuild the list in case the naptime changed */
814 }
815
816 /* Process barrier events */
819
820 /* Perform logging of memory contexts of this process */
823
824 /* Process sinval catchup interrupts that happened while sleeping */
826}
827
828/*
829 * Perform a normal exit from the autovac launcher.
830 */
831static void
833{
835 (errmsg_internal("autovacuum launcher shutting down")));
836 proc_exit(0); /* done */
837}
838
839/*
840 * Determine the time to sleep, based on the database list.
841 *
842 * The "canlaunch" parameter indicates whether we can start a worker right now,
843 * for example due to the workers being all busy. If this is false, we will
844 * cause a long sleep, which will be interrupted when a worker exits.
845 */
846static void
847launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
848{
849 /*
850 * We sleep until the next scheduled vacuum. We trust that when the
851 * database list was built, care was taken so that no entries have times
852 * in the past; if the first entry has too close a next_worker value, or a
853 * time in the past, we will sleep a small nominal time.
854 */
855 if (!canlaunch)
856 {
857 nap->tv_sec = autovacuum_naptime;
858 nap->tv_usec = 0;
859 }
860 else if (!dlist_is_empty(&DatabaseList))
861 {
865 long secs;
866 int usecs;
867
869
870 next_wakeup = avdb->adl_next_worker;
872
873 nap->tv_sec = secs;
874 nap->tv_usec = usecs;
875 }
876 else
877 {
878 /* list is empty, sleep for whole autovacuum_naptime seconds */
879 nap->tv_sec = autovacuum_naptime;
880 nap->tv_usec = 0;
881 }
882
883 /*
884 * If the result is exactly zero, it means a database had an entry with
885 * time in the past. Rebuild the list so that the databases are evenly
886 * distributed again, and recalculate the time to sleep. This can happen
887 * if there are more tables needing vacuum than workers, and they all take
888 * longer to vacuum than autovacuum_naptime.
889 *
890 * We only recurse once. rebuild_database_list should always return times
891 * in the future, but it seems best not to trust too much on that.
892 */
893 if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
894 {
897 return;
898 }
899
900 /* The smallest time we'll allow the launcher to sleep. */
901 if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
902 {
903 nap->tv_sec = 0;
904 nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000;
905 }
906
907 /*
908 * If the sleep time is too large, clamp it to an arbitrary maximum (plus
909 * any fractional seconds, for simplicity). This avoids an essentially
910 * infinite sleep in strange cases like the system clock going backwards a
911 * few years.
912 */
913 if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME)
914 nap->tv_sec = MAX_AUTOVAC_SLEEPTIME;
915}
916
917/*
918 * Build an updated DatabaseList. It must only contain databases that appear
919 * in pgstats, and must be sorted by next_worker from highest to lowest,
920 * distributed regularly across the next autovacuum_naptime interval.
921 *
922 * Receives the Oid of the database that made this list be generated (we call
923 * this the "new" database, because when the database was already present on
924 * the list, we expect that this function is not called at all). The
925 * preexisting list, if any, will be used to preserve the order of the
926 * databases in the autovacuum_naptime period. The new database is put at the
927 * end of the interval. The actual values are not saved, which should not be
928 * much of a problem.
929 */
930static void
932{
933 List *dblist;
934 ListCell *cell;
938 HASHCTL hctl;
939 int score;
940 int nelems;
941 HTAB *dbhash;
942 dlist_iter iter;
943
945 "Autovacuum database list",
948 "Autovacuum database list (tmp)",
951
952 /*
953 * Implementing this is not as simple as it sounds, because we need to put
954 * the new database at the end of the list; next the databases that were
955 * already on the list, and finally (at the tail of the list) all the
956 * other databases that are not on the existing list.
957 *
958 * To do this, we build an empty hash table of scored databases. We will
959 * start with the lowest score (zero) for the new database, then
960 * increasing scores for the databases in the existing list, in order, and
961 * lastly increasing scores for all databases gotten via
962 * get_database_list() that are not already on the hash.
963 *
964 * Then we will put all the hash elements into an array, sort the array by
965 * score, and finally put the array elements into the new doubly linked
966 * list.
967 */
968 hctl.keysize = sizeof(Oid);
969 hctl.entrysize = sizeof(avl_dbase);
970 hctl.hcxt = tmpcxt;
971 dbhash = hash_create("autovacuum db hash", 20, &hctl, /* magic number here
972 * FIXME */
974
975 /* start by inserting the new database */
976 score = 0;
977 if (OidIsValid(newdb))
978 {
979 avl_dbase *db;
980 PgStat_StatDBEntry *entry;
981
982 /* only consider this database if it has a pgstat entry */
984 if (entry != NULL)
985 {
986 /* we assume it isn't found because the hash was just created */
988
989 /* hash_search already filled in the key */
990 db->adl_score = score++;
991 /* next_worker is filled in later */
992 }
993 }
994
995 /* Now insert the databases from the existing list */
997 {
998 avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
999 avl_dbase *db;
1000 bool found;
1001 PgStat_StatDBEntry *entry;
1002
1003 /*
1004 * skip databases with no stat entries -- in particular, this gets rid
1005 * of dropped databases
1006 */
1007 entry = pgstat_fetch_stat_dbentry(avdb->adl_datid);
1008 if (entry == NULL)
1009 continue;
1010
1011 db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found);
1012
1013 if (!found)
1014 {
1015 /* hash_search already filled in the key */
1016 db->adl_score = score++;
1017 /* next_worker is filled in later */
1018 }
1019 }
1020
1021 /* finally, insert all qualifying databases not previously inserted */
1023 foreach(cell, dblist)
1024 {
1025 avw_dbase *avdb = lfirst(cell);
1026 avl_dbase *db;
1027 bool found;
1028 PgStat_StatDBEntry *entry;
1029
1030 /* only consider databases with a pgstat entry */
1031 entry = pgstat_fetch_stat_dbentry(avdb->adw_datid);
1032 if (entry == NULL)
1033 continue;
1034
1035 db = hash_search(dbhash, &(avdb->adw_datid), HASH_ENTER, &found);
1036 /* only update the score if the database was not already on the hash */
1037 if (!found)
1038 {
1039 /* hash_search already filled in the key */
1040 db->adl_score = score++;
1041 /* next_worker is filled in later */
1042 }
1043 }
1044 nelems = score;
1045
1046 /* from here on, the allocated memory belongs to the new list */
1049
1050 if (nelems > 0)
1051 {
1053 int millis_increment;
1055 avl_dbase *db;
1057 int i;
1058
1059 /* put all the hash elements into an array */
1060 dbary = palloc(nelems * sizeof(avl_dbase));
1061 /* keep Valgrind quiet */
1062#ifdef USE_VALGRIND
1064#endif
1065
1066 i = 0;
1068 while ((db = hash_seq_search(&seq)) != NULL)
1069 memcpy(&(dbary[i++]), db, sizeof(avl_dbase));
1070
1071 /* sort the array */
1072 qsort(dbary, nelems, sizeof(avl_dbase), db_comparator);
1073
1074 /*
1075 * Determine the time interval between databases in the schedule. If
1076 * we see that the configured naptime would take us to sleep times
1077 * lower than our min sleep time (which launcher_determine_sleep is
1078 * coded not to allow), silently use a larger naptime (but don't touch
1079 * the GUC variable).
1080 */
1081 millis_increment = 1000.0 * autovacuum_naptime / nelems;
1084
1086
1087 /*
1088 * move the elements from the array into the dlist, setting the
1089 * next_worker while walking the array
1090 */
1091 for (i = 0; i < nelems; i++)
1092 {
1093 db = &(dbary[i]);
1094
1098
1099 /* later elements should go closer to the head of the list */
1101 }
1102 }
1103
1104 /* all done, clean up memory */
1105 if (DatabaseListCxt != NULL)
1110}
1111
1112/* qsort comparator for avl_dbase, using adl_score */
1113static int
1114db_comparator(const void *a, const void *b)
1115{
1116 return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1117 ((const avl_dbase *) b)->adl_score);
1118}
1119
1120/*
1121 * do_start_worker
1122 *
1123 * Bare-bones procedure for starting an autovacuum worker from the launcher.
1124 * It determines what database to work on, sets up shared memory stuff and
1125 * signals postmaster to start the worker. It fails gracefully if invoked when
1126 * autovacuum_workers are already active.
1127 *
1128 * Return value is the OID of the database that the worker is going to process,
1129 * or InvalidOid if no worker was actually started.
1130 */
1131static Oid
1133{
1134 List *dblist;
1135 ListCell *cell;
1138 bool for_xid_wrap;
1139 bool for_multi_wrap;
1140 avw_dbase *avdb;
1142 bool skipit = false;
1143 Oid retval = InvalidOid;
1145 oldcxt;
1146
1147 /* return quickly when there are no free workers */
1149 if (!av_worker_available())
1150 {
1152 return InvalidOid;
1153 }
1155
1156 /*
1157 * Create and switch to a temporary context to avoid leaking the memory
1158 * allocated for the database list.
1159 */
1161 "Autovacuum start worker (tmp)",
1164
1165 /* Get a list of databases */
1167
1168 /*
1169 * Determine the oldest datfrozenxid/relfrozenxid that we will allow to
1170 * pass without forcing a vacuum. (This limit can be tightened for
1171 * particular tables, but not loosened.)
1172 */
1175 /* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
1176 /* this can cause the limit to go backwards by 3, but that's OK */
1179
1180 /* Also determine the oldest datminmxid we will consider. */
1185
1186 /*
1187 * Choose a database to connect to. We pick the database that was least
1188 * recently auto-vacuumed, or one that needs vacuuming to prevent Xid
1189 * wraparound-related data loss. If any db at risk of Xid wraparound is
1190 * found, we pick the one with oldest datfrozenxid, independently of
1191 * autovacuum times; similarly we pick the one with the oldest datminmxid
1192 * if any is in MultiXactId wraparound. Note that those in Xid wraparound
1193 * danger are given more priority than those in multi wraparound danger.
1194 *
1195 * Note that a database with no stats entry is not considered, except for
1196 * Xid wraparound purposes. The theory is that if no one has ever
1197 * connected to it since the stats were last initialized, it doesn't need
1198 * vacuuming.
1199 *
1200 * XXX This could be improved if we had more info about whether it needs
1201 * vacuuming before connecting to it. Perhaps look through the pgstats
1202 * data for the database's tables? One idea is to keep track of the
1203 * number of new and dead tuples per database in pgstats. However it
1204 * isn't clear how to construct a metric that measures that and not cause
1205 * starvation for less busy databases.
1206 */
1207 avdb = NULL;
1208 for_xid_wrap = false;
1209 for_multi_wrap = false;
1211 foreach(cell, dblist)
1212 {
1213 avw_dbase *tmp = lfirst(cell);
1214 dlist_iter iter;
1215
1216 /* Check to see if this one is at risk of wraparound */
1218 {
1219 if (avdb == NULL ||
1221 avdb->adw_frozenxid))
1222 avdb = tmp;
1223 for_xid_wrap = true;
1224 continue;
1225 }
1226 else if (for_xid_wrap)
1227 continue; /* ignore not-at-risk DBs */
1229 {
1230 if (avdb == NULL ||
1231 MultiXactIdPrecedes(tmp->adw_minmulti, avdb->adw_minmulti))
1232 avdb = tmp;
1233 for_multi_wrap = true;
1234 continue;
1235 }
1236 else if (for_multi_wrap)
1237 continue; /* ignore not-at-risk DBs */
1238
1239 /* Find pgstat entry if any */
1241
1242 /*
1243 * Skip a database with no pgstat entry; it means it hasn't seen any
1244 * activity.
1245 */
1246 if (!tmp->adw_entry)
1247 continue;
1248
1249 /*
1250 * Also, skip a database that appears on the database list as having
1251 * been processed recently (less than autovacuum_naptime seconds ago).
1252 * We do this so that we don't select a database which we just
1253 * selected, but that pgstat hasn't gotten around to updating the last
1254 * autovacuum time yet.
1255 */
1256 skipit = false;
1257
1259 {
1260 avl_dbase *dbp = dlist_container(avl_dbase, adl_node, iter.cur);
1261
1262 if (dbp->adl_datid == tmp->adw_datid)
1263 {
1264 /*
1265 * Skip this database if its next_worker value falls between
1266 * the current time and the current time plus naptime.
1267 */
1268 if (!TimestampDifferenceExceeds(dbp->adl_next_worker,
1269 current_time, 0) &&
1271 dbp->adl_next_worker,
1272 autovacuum_naptime * 1000))
1273 skipit = true;
1274
1275 break;
1276 }
1277 }
1278 if (skipit)
1279 continue;
1280
1281 /*
1282 * Remember the db with oldest autovac time. (If we are here, both
1283 * tmp->entry and db->entry must be non-null.)
1284 */
1285 if (avdb == NULL ||
1286 tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time)
1287 avdb = tmp;
1288 }
1289
1290 /* Found a database -- process it */
1291 if (avdb != NULL)
1292 {
1293 WorkerInfo worker;
1295
1297
1298 /*
1299 * Get a worker entry from the freelist. We checked above, so there
1300 * really should be a free slot.
1301 */
1303
1304 worker = dlist_container(WorkerInfoData, wi_links, wptr);
1305 worker->wi_dboid = avdb->adw_datid;
1306 worker->wi_proc = NULL;
1308
1310
1312
1314
1315 retval = avdb->adw_datid;
1316 }
1317 else if (skipit)
1318 {
1319 /*
1320 * If we skipped all databases on the list, rebuild it, because it
1321 * probably contains a dropped database.
1322 */
1324 }
1325
1328
1329 return retval;
1330}
1331
1332/*
1333 * launch_worker
1334 *
1335 * Wrapper for starting a worker from the launcher. Besides actually starting
1336 * it, update the database list to reflect the next time that another one will
1337 * need to be started on the selected database. The actual database choice is
1338 * left to do_start_worker.
1339 *
1340 * This routine is also expected to insert an entry into the database list if
1341 * the selected database was previously absent from the list.
1342 */
1343static void
1345{
1346 Oid dbid;
1347 dlist_iter iter;
1348
1349 dbid = do_start_worker();
1350 if (OidIsValid(dbid))
1351 {
1352 bool found = false;
1353
1354 /*
1355 * Walk the database list and update the corresponding entry. If the
1356 * database is not on the list, we'll recreate the list.
1357 */
1359 {
1360 avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1361
1362 if (avdb->adl_datid == dbid)
1363 {
1364 found = true;
1365
1366 /*
1367 * add autovacuum_naptime seconds to the current time, and use
1368 * that as the new "next_worker" field for this database.
1369 */
1370 avdb->adl_next_worker =
1372
1374 break;
1375 }
1376 }
1377
1378 /*
1379 * If the database was not present in the database list, we rebuild
1380 * the list. It's possible that the database does not get into the
1381 * list anyway, for example if it's a database that doesn't have a
1382 * pgstat entry, but this is not a problem because we don't want to
1383 * schedule workers regularly into those in any case.
1384 */
1385 if (!found)
1387 }
1388}
1389
1390/*
1391 * Called from postmaster to signal a failure to fork a process to become
1392 * worker. The postmaster should kill(SIGUSR2) the launcher shortly
1393 * after calling this function.
1394 */
1395void
1400
1401/* SIGUSR2: a worker is up and running, or just finished, or failed to fork */
1402static void
1408
1409
1410/********************************************************************
1411 * AUTOVACUUM WORKER CODE
1412 ********************************************************************/
1413
1414/*
1415 * Main entry point for autovacuum worker processes.
1416 */
1417void
1419{
1421 Oid dbid;
1422
1424
1425 /* Release postmaster's working memory context */
1427 {
1430 }
1431
1433
1435
1436 /*
1437 * Set up signal handlers. We operate on databases much like a regular
1438 * backend, so we use the same signal handling. See equivalent code in
1439 * tcop/postgres.c.
1440 */
1442
1443 /*
1444 * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1445 * means abort and exit cleanly, and SIGQUIT means abandon ship.
1446 */
1449 /* SIGQUIT handler was already set up by InitPostmasterChild */
1450
1451 InitializeTimeouts(); /* establishes SIGALRM handler */
1452
1458
1459 /*
1460 * Create a per-backend PGPROC struct in shared memory. We must do this
1461 * before we can use LWLocks or access any shared memory.
1462 */
1463 InitProcess();
1464
1465 /* Early initialization */
1466 BaseInit();
1467
1468 /*
1469 * If an exception is encountered, processing resumes here.
1470 *
1471 * Unlike most auxiliary processes, we don't attempt to continue
1472 * processing after an error; we just clean up and exit. The autovac
1473 * launcher is responsible for spawning another worker later.
1474 *
1475 * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
1476 * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
1477 * signals other than SIGQUIT will be blocked until we exit. It might
1478 * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
1479 * it is not since InterruptPending might be set already.
1480 */
1481 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1482 {
1483 /* since not using PG_TRY, must reset error stack by hand */
1485
1486 /* Prevents interrupts while cleaning up */
1488
1489 /* Report the error to the server log */
1491
1492 /*
1493 * We can now go away. Note that because we called InitProcess, a
1494 * callback was registered to do ProcKill, which will clean up
1495 * necessary state.
1496 */
1497 proc_exit(0);
1498 }
1499
1500 /* We can now handle ereport(ERROR) */
1502
1504
1505 /*
1506 * Set always-secure search path, so malicious users can't redirect user
1507 * code (e.g. pg_index.indexprs). (That code runs in a
1508 * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1509 * take control of the entire autovacuum worker in any case.)
1510 */
1511 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1512
1513 /*
1514 * Force zero_damaged_pages OFF in the autovac process, even if it is set
1515 * in postgresql.conf. We don't really want such a dangerous option being
1516 * applied non-interactively.
1517 */
1518 SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1519
1520 /*
1521 * Force settable timeouts off to avoid letting these settings prevent
1522 * regular maintenance from being executed.
1523 */
1524 SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1525 SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1526 SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1527 SetConfigOption("idle_in_transaction_session_timeout", "0",
1529
1530 /*
1531 * Force default_transaction_isolation to READ COMMITTED. We don't want
1532 * to pay the overhead of serializable mode, nor add any risk of causing
1533 * deadlocks or delaying other transactions.
1534 */
1535 SetConfigOption("default_transaction_isolation", "read committed",
1537
1538 /*
1539 * Force synchronous replication off to allow regular maintenance even if
1540 * we are waiting for standbys to connect. This is important to ensure we
1541 * aren't blocked from performing anti-wraparound tasks.
1542 */
1544 SetConfigOption("synchronous_commit", "local",
1546
1547 /*
1548 * Even when system is configured to use a different fetch consistency,
1549 * for autovac we always want fresh stats.
1550 */
1551 SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
1552
1553 /*
1554 * Get the info about the database we're going to work on.
1555 */
1557
1558 /*
1559 * beware of startingWorker being INVALID; this should normally not
1560 * happen, but if a worker fails after forking and before this, the
1561 * launcher might have decided to remove it from the queue and start
1562 * again.
1563 */
1565 {
1567
1569 dbid = MyWorkerInfo->wi_dboid;
1571
1572 /* insert into the running list */
1575
1576 /*
1577 * remove from the "starting" pointer, so that the launcher can start
1578 * a new worker if required
1579 */
1582
1584
1585 /* wake up the launcher */
1588 {
1589 int pid = GetPGProcByNumber(launcherProc)->pid;
1590
1591 if (pid != 0)
1592 kill(pid, SIGUSR2);
1593 }
1594 }
1595 else
1596 {
1597 /* no worker entry for me, go away */
1598 elog(WARNING, "autovacuum worker started without a worker entry");
1599 dbid = InvalidOid;
1601 }
1602
1603 if (OidIsValid(dbid))
1604 {
1605 char dbname[NAMEDATALEN];
1606
1607 /*
1608 * Report autovac startup to the cumulative stats system. We
1609 * deliberately do this before InitPostgres, so that the
1610 * last_autovac_time will get updated even if the connection attempt
1611 * fails. This is to prevent autovac from getting "stuck" repeatedly
1612 * selecting an unopenable database, rather than making any progress
1613 * on stuff it can connect to.
1614 */
1616
1617 /*
1618 * Connect to the selected database, specifying no particular user,
1619 * and ignoring datallowconn. Collect the database's name for
1620 * display.
1621 *
1622 * Note: if we have selected a just-deleted database (due to using
1623 * stale stats info), we'll fail and exit here.
1624 */
1627 dbname);
1631 (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1632
1633 if (PostAuthDelay)
1634 pg_usleep(PostAuthDelay * 1000000L);
1635
1636 /* And do an appropriate amount of work */
1639 do_autovacuum();
1640 }
1641
1642 /* All done, go away */
1643 proc_exit(0);
1644}
1645
1646/*
1647 * Return a WorkerInfo to the free list
1648 */
1649static void
1651{
1652 if (MyWorkerInfo != NULL)
1653 {
1655
1659 MyWorkerInfo->wi_sharedrel = false;
1665 /* not mine anymore */
1667
1668 /*
1669 * now that we're inactive, cause a rebalancing of the surviving
1670 * workers
1671 */
1674 }
1675}
1676
1677/*
1678 * Update vacuum cost-based delay-related parameters for autovacuum workers and
1679 * backends executing VACUUM or ANALYZE using the value of relevant GUCs and
1680 * global state. This must be called during setup for vacuum and after every
1681 * config reload to ensure up-to-date values.
1682 */
1683void
1685{
1686 if (MyWorkerInfo)
1687 {
1690 else if (autovacuum_vac_cost_delay >= 0)
1692 else
1693 /* fall back to VacuumCostDelay */
1695
1697 }
1698 else
1699 {
1700 /* Must be explicit VACUUM or ANALYZE or parallel autovacuum worker */
1703 }
1704
1705 /*
1706 * If configuration changes are allowed to impact VacuumCostActive, make
1707 * sure it is updated.
1708 */
1711 else if (vacuum_cost_delay > 0)
1712 VacuumCostActive = true;
1713 else
1714 {
1715 VacuumCostActive = false;
1717 }
1718
1719 /*
1720 * Since the cost logging requires a lock, avoid rendering the log message
1721 * in case we are using a message level where the log wouldn't be emitted.
1722 */
1724 {
1725 Oid dboid,
1726 tableoid;
1727
1729
1731 dboid = MyWorkerInfo->wi_dboid;
1732 tableoid = MyWorkerInfo->wi_tableoid;
1734
1735 elog(DEBUG2,
1736 "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1737 dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1739 vacuum_cost_delay > 0 ? "yes" : "no",
1740 VacuumFailsafeActive ? "yes" : "no");
1741 }
1742}
1743
1744/*
1745 * Update vacuum_cost_limit with the correct value for an autovacuum worker,
1746 * given the value of other relevant cost limit parameters and the number of
1747 * workers across which the limit must be balanced. Autovacuum workers must
1748 * call this regularly in case av_nworkersForBalance has been updated by
1749 * another worker or by the autovacuum launcher. They must also call it after a
1750 * config reload.
1751 */
1752void
1754{
1755 if (!MyWorkerInfo)
1756 return;
1757
1758 /*
1759 * note: in cost_limit, zero also means use value from elsewhere, because
1760 * zero is not a valid value.
1761 */
1762
1765 else
1766 {
1768
1771 else
1773
1774 /* Only balance limit if no cost-related storage parameters specified */
1776 return;
1777
1779
1781
1782 /* There is at least 1 autovac worker (this worker) */
1783 if (nworkers_for_balance <= 0)
1784 elog(ERROR, "nworkers_for_balance must be > 0");
1785
1787 }
1788}
1789
1790/*
1791 * autovac_recalculate_workers_for_balance
1792 * Recalculate the number of workers to consider, given cost-related
1793 * storage parameters and the current number of active workers.
1794 *
1795 * Caller must hold the AutovacuumLock in at least shared mode to access
1796 * worker->wi_proc.
1797 */
1798static void
1825
1826/*
1827 * get_database_list
1828 * Return a list of all databases found in pg_database.
1829 *
1830 * The list and associated data is allocated in the caller's memory context,
1831 * which is in charge of ensuring that it's properly cleaned up afterwards.
1832 *
1833 * Note: this is the only function in which the autovacuum launcher uses a
1834 * transaction. Although we aren't attached to any particular database and
1835 * therefore can't access most catalogs, we do have enough infrastructure
1836 * to do a seqscan on pg_database.
1837 */
1838static List *
1840{
1841 List *dblist = NIL;
1842 Relation rel;
1843 TableScanDesc scan;
1844 HeapTuple tup;
1846
1847 /* This is the context that we will allocate our output data in */
1849
1850 /*
1851 * Start a transaction so we can access pg_database.
1852 */
1854
1856 scan = table_beginscan_catalog(rel, 0, NULL);
1857
1859 {
1861 avw_dbase *avdb;
1863
1864 /*
1865 * If database has partially been dropped, we can't, nor need to,
1866 * vacuum it.
1867 */
1869 {
1870 elog(DEBUG2,
1871 "autovacuum: skipping invalid database \"%s\"",
1872 NameStr(pgdatabase->datname));
1873 continue;
1874 }
1875
1876 /*
1877 * Allocate our results in the caller's context, not the
1878 * transaction's. We do this inside the loop, and restore the original
1879 * context at the end, so that leaky things like heap_getnext() are
1880 * not called in a potentially long-lived context.
1881 */
1883
1885
1886 avdb->adw_datid = pgdatabase->oid;
1887 avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1888 avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1889 avdb->adw_minmulti = pgdatabase->datminmxid;
1890 /* this gets set later: */
1891 avdb->adw_entry = NULL;
1892
1895 }
1896
1897 table_endscan(scan);
1899
1901
1902 /* Be sure to restore caller's memory context */
1904
1905 return dblist;
1906}
1907
1908/*
1909 * List comparator for TableToProcess. Note that this sorts the tables based
1910 * on their scores in descending order.
1911 */
1912static int
1914{
1917
1918 return (t2->score < t1->score) ? -1 : (t2->score > t1->score) ? 1 : 0;
1919}
1920
1921/*
1922 * Process a database table-by-table
1923 *
1924 * Note that CHECK_FOR_INTERRUPTS is supposed to be used in certain spots in
1925 * order not to ignore shutdown commands for too long.
1926 */
1927static void
1929{
1931 HeapTuple tuple;
1935 List *orphan_oids = NIL;
1936 HASHCTL ctl;
1938 ListCell *volatile cell;
1939 BufferAccessStrategy bstrategy;
1940 ScanKeyData key;
1943 bool did_vacuum = false;
1944 bool found_concurrent_worker = false;
1945 int i;
1946
1947 /*
1948 * StartTransactionCommand and CommitTransactionCommand will automatically
1949 * switch to other contexts. We need this one to keep the list of
1950 * relations to vacuum/analyze across transactions.
1951 */
1953 "Autovacuum worker",
1956
1957 /* Start a transaction so our commands have one to play into. */
1959
1960 /*
1961 * This injection point is put in a transaction block to work with a wait
1962 * that uses a condition variable.
1963 */
1964 INJECTION_POINT("autovacuum-worker-start", NULL);
1965
1966 /*
1967 * Compute the multixact age for which freezing is urgent. This is
1968 * normally autovacuum_multixact_freeze_max_age, but may be less if
1969 * multixact members are bloated.
1970 */
1972
1973 /*
1974 * Find the pg_database entry and select the default freeze ages. We use
1975 * zero in template and nonconnectable databases, else the system-wide
1976 * default.
1977 */
1979 if (!HeapTupleIsValid(tuple))
1980 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1982
1983 if (dbForm->datistemplate || !dbForm->datallowconn)
1984 {
1989 }
1990 else
1991 {
1996 }
1997
1998 ReleaseSysCache(tuple);
1999
2000 /* StartTransactionCommand changed elsewhere */
2002
2004
2005 /* create a copy so we can use it after closing pg_class */
2007
2008 /* create hash table for toast <-> main relid mapping */
2009 ctl.keysize = sizeof(Oid);
2010 ctl.entrysize = sizeof(av_relation);
2011
2012 table_toast_map = hash_create("TOAST to main relid map",
2013 100,
2014 &ctl,
2016
2017 /*
2018 * Scan pg_class to determine which tables to vacuum.
2019 *
2020 * We do this in two passes: on the first one we collect the list of plain
2021 * relations and materialized views, and on the second one we collect
2022 * TOAST tables. The reason for doing the second pass is that during it we
2023 * want to use the main relation's pg_class.reloptions entry if the TOAST
2024 * table does not have any, and we cannot obtain it unless we know
2025 * beforehand what's the main table OID.
2026 *
2027 * We need to check TOAST tables separately because in cases with short,
2028 * wide tables there might be proportionally much more activity in the
2029 * TOAST table than in its parent.
2030 */
2032
2033 /*
2034 * On the first pass, we collect main tables to vacuum, and also the main
2035 * table relid to TOAST relid mapping.
2036 */
2037 while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2038 {
2041 Oid relid;
2042 bool dovacuum;
2043 bool doanalyze;
2044 bool wraparound;
2046
2047 if (classForm->relkind != RELKIND_RELATION &&
2048 classForm->relkind != RELKIND_MATVIEW)
2049 continue;
2050
2051 relid = classForm->oid;
2052
2053 /*
2054 * Check if it is a temp table (presumably, of some other backend's).
2055 * We cannot safely process other backends' temp tables.
2056 */
2057 if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2058 {
2059 /*
2060 * We just ignore it if the owning backend is still active and
2061 * using the temporary schema. Also, for safety, ignore it if the
2062 * namespace doesn't exist or isn't a temp namespace after all.
2063 */
2065 {
2066 /*
2067 * The table seems to be orphaned -- although it might be that
2068 * the owning backend has already deleted it and exited; our
2069 * pg_class scan snapshot is not necessarily up-to-date
2070 * anymore, so we could be looking at a committed-dead entry.
2071 * Remember it so we can try to delete it later.
2072 */
2074 }
2075 continue;
2076 }
2077
2078 /* Fetch reloptions and the pgstat entry for this table */
2080
2081 /* Check if it needs vacuum or analyze */
2084 DEBUG3,
2086 &scores);
2087
2088 /* Relations that need work are added to tables_to_process */
2089 if (dovacuum || doanalyze)
2090 {
2092
2093 table->oid = relid;
2094 table->score = scores.max;
2096 }
2097
2098 /*
2099 * Remember TOAST associations for the second pass. Note: we must do
2100 * this whether or not the table is going to be vacuumed, because we
2101 * don't automatically vacuum toast tables along the parent table.
2102 */
2103 if (OidIsValid(classForm->reltoastrelid))
2104 {
2106 bool found;
2107
2109 &classForm->reltoastrelid,
2110 HASH_ENTER, &found);
2111
2112 if (!found)
2113 {
2114 /* hash_search already filled in the key */
2115 hentry->ar_relid = relid;
2116 hentry->ar_hasrelopts = false;
2117 if (relopts != NULL)
2118 {
2119 hentry->ar_hasrelopts = true;
2120 memcpy(&hentry->ar_reloptions, relopts,
2121 sizeof(AutoVacOpts));
2122 }
2123 }
2124 }
2125
2126 /* Release stuff to avoid per-relation leakage */
2127 if (relopts)
2128 pfree(relopts);
2129 }
2130
2132
2133 /* second pass: check TOAST tables */
2134 ScanKeyInit(&key,
2138
2140 while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2141 {
2143 Oid relid;
2145 bool free_relopts = false;
2146 bool dovacuum;
2147 bool doanalyze;
2148 bool wraparound;
2150
2151 /*
2152 * We cannot safely process other backends' temp tables, so skip 'em.
2153 */
2154 if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2155 continue;
2156
2157 relid = classForm->oid;
2158
2159 /*
2160 * fetch reloptions -- if this toast table does not have them, try the
2161 * main rel
2162 */
2164 if (relopts)
2165 free_relopts = true;
2166 else
2167 {
2169 bool found;
2170
2171 hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2172 if (found && hentry->ar_hasrelopts)
2173 relopts = &hentry->ar_reloptions;
2174 }
2175
2178 DEBUG3,
2180 &scores);
2181
2182 /* ignore analyze for toast tables */
2183 if (dovacuum)
2184 {
2186
2187 table->oid = relid;
2188 table->score = scores.max;
2190 }
2191
2192 /* Release stuff to avoid leakage */
2193 if (free_relopts)
2194 pfree(relopts);
2195 }
2196
2199
2200 /*
2201 * Recheck orphan temporary tables, and if they still seem orphaned, drop
2202 * them. We'll eat a transaction per dropped table, which might seem
2203 * excessive, but we should only need to do anything as a result of a
2204 * previous backend crash, so this should not happen often enough to
2205 * justify "optimizing". Using separate transactions ensures that we
2206 * don't bloat the lock table if there are many temp tables to be dropped,
2207 * and it ensures that we don't lose work if a deletion attempt fails.
2208 */
2209 foreach(cell, orphan_oids)
2210 {
2211 Oid relid = lfirst_oid(cell);
2213 ObjectAddress object;
2214
2215 /*
2216 * Check for user-requested abort.
2217 */
2219
2220 /*
2221 * Try to lock the table. If we can't get the lock immediately,
2222 * somebody else is using (or dropping) the table, so it's not our
2223 * concern anymore. Having the lock prevents race conditions below.
2224 */
2226 continue;
2227
2228 /*
2229 * Re-fetch the pg_class tuple and re-check whether it still seems to
2230 * be an orphaned temp table. If it's not there or no longer the same
2231 * relation, ignore it.
2232 */
2234 if (!HeapTupleIsValid(tuple))
2235 {
2236 /* be sure to drop useless lock so we don't bloat lock table */
2238 continue;
2239 }
2241
2242 /*
2243 * Make all the same tests made in the loop above. In event of OID
2244 * counter wraparound, the pg_class entry we have now might be
2245 * completely unrelated to the one we saw before.
2246 */
2247 if (!((classForm->relkind == RELKIND_RELATION ||
2248 classForm->relkind == RELKIND_MATVIEW) &&
2249 classForm->relpersistence == RELPERSISTENCE_TEMP))
2250 {
2252 continue;
2253 }
2254
2256 {
2258 continue;
2259 }
2260
2261 /*
2262 * Try to lock the temp namespace, too. Even though we have lock on
2263 * the table itself, there's a risk of deadlock against an incoming
2264 * backend trying to clean out the temp namespace, in case this table
2265 * has dependencies (such as sequences) that the backend's
2266 * performDeletion call might visit in a different order. If we can
2267 * get AccessShareLock on the namespace, that's sufficient to ensure
2268 * we're not running concurrently with RemoveTempRelations. If we
2269 * can't, back off and let RemoveTempRelations do its thing.
2270 */
2272 classForm->relnamespace, 0,
2274 {
2276 continue;
2277 }
2278
2279 /* OK, let's delete it */
2280 ereport(LOG,
2281 (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2283 get_namespace_name(classForm->relnamespace),
2284 NameStr(classForm->relname))));
2285
2286 /*
2287 * Deletion might involve TOAST table access, so ensure we have a
2288 * valid snapshot.
2289 */
2291
2292 object.classId = RelationRelationId;
2293 object.objectId = relid;
2294 object.objectSubId = 0;
2299
2300 /*
2301 * To commit the deletion, end current transaction and start a new
2302 * one. Note this also releases the locks we took.
2303 */
2307
2308 /* StartTransactionCommand changed current memory context */
2310 }
2311
2312 /*
2313 * In case list_sort() would modify the list even when all the scores are
2314 * 0.0, skip sorting if all the weight parameters are set to 0.0. This is
2315 * probably not necessary, but we want to ensure folks have a guaranteed
2316 * escape hatch from the scoring system.
2317 */
2318 if (autovacuum_freeze_score_weight != 0.0 ||
2324
2325 /*
2326 * Optionally, create a buffer access strategy object for VACUUM to use.
2327 * We use the same BufferAccessStrategy object for all tables VACUUMed by
2328 * this worker to prevent autovacuum from blowing out shared buffers.
2329 *
2330 * VacuumBufferUsageLimit being set to 0 results in
2331 * GetAccessStrategyWithSize returning NULL, effectively meaning we can
2332 * use up to all of shared buffers.
2333 *
2334 * If we later enter failsafe mode on any of the tables being vacuumed, we
2335 * will cease use of the BufferAccessStrategy only for that table.
2336 *
2337 * XXX should we consider adding code to adjust the size of this if
2338 * VacuumBufferUsageLimit changes?
2339 */
2341
2342 /*
2343 * create a memory context to act as fake PortalContext, so that the
2344 * contexts created in the vacuum code are cleaned up for each table.
2345 */
2347 "Autovacuum Portal",
2349
2350 /*
2351 * Perform operations on collected tables.
2352 */
2354 {
2355 Oid relid = table->oid;
2357 autovac_table *tab;
2358 bool isshared;
2359 bool skipit;
2360 dlist_iter iter;
2361
2363
2364 /*
2365 * Check for config changes before processing each collected table.
2366 */
2368 {
2369 ConfigReloadPending = false;
2371
2372 /*
2373 * You might be tempted to bail out if we see autovacuum is now
2374 * disabled. Must resist that temptation -- this might be a
2375 * for-wraparound emergency worker, in which case that would be
2376 * entirely inappropriate.
2377 */
2378 }
2379
2380 /*
2381 * Find out whether the table is shared or not. (It's slightly
2382 * annoying to fetch the syscache entry just for this, but in typical
2383 * cases it adds little cost because table_recheck_autovac would
2384 * refetch the entry anyway. We could buy that back by copying the
2385 * tuple here and passing it to table_recheck_autovac, but that
2386 * increases the odds of that function working with stale data.)
2387 */
2390 continue; /* somebody deleted the rel, forget it */
2393
2394 /*
2395 * Hold schedule lock from here until we've claimed the table. We
2396 * also need the AutovacuumLock to walk the worker array, but that one
2397 * can just be a shared lock.
2398 */
2401
2402 /*
2403 * Check whether the table is being vacuumed concurrently by another
2404 * worker.
2405 */
2406 skipit = false;
2408 {
2409 WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2410
2411 /* ignore myself */
2412 if (worker == MyWorkerInfo)
2413 continue;
2414
2415 /* ignore workers in other databases (unless table is shared) */
2416 if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2417 continue;
2418
2419 if (worker->wi_tableoid == relid)
2420 {
2421 skipit = true;
2423 break;
2424 }
2425 }
2427 if (skipit)
2428 {
2430 continue;
2431 }
2432
2433 /*
2434 * Store the table's OID in shared memory before releasing the
2435 * schedule lock, so that other workers don't try to vacuum it
2436 * concurrently. (We claim it here so as not to hold
2437 * AutovacuumScheduleLock while rechecking the stats.)
2438 */
2439 MyWorkerInfo->wi_tableoid = relid;
2440 MyWorkerInfo->wi_sharedrel = isshared;
2442
2443 /*
2444 * Check whether pgstat data still says we need to vacuum this table.
2445 * It could have changed if something else processed the table while
2446 * we weren't looking. This doesn't entirely close the race condition,
2447 * but it is very small.
2448 */
2452 if (tab == NULL)
2453 {
2454 /* someone else vacuumed the table, or it went away */
2457 MyWorkerInfo->wi_sharedrel = false;
2459 continue;
2460 }
2461
2462 /*
2463 * Save the cost-related storage parameter values in global variables
2464 * for reference when updating vacuum_cost_delay and vacuum_cost_limit
2465 * during vacuuming this table.
2466 */
2469
2470 /*
2471 * We only expect this worker to ever set the flag, so don't bother
2472 * checking the return value. We shouldn't have to retry.
2473 */
2474 if (tab->at_dobalance)
2476 else
2478
2482
2483 /*
2484 * We wait until this point to update cost delay and cost limit
2485 * values, even though we reloaded the configuration file above, so
2486 * that we can take into account the cost-related storage parameters.
2487 */
2489
2490
2491 /* clean up memory before each iteration */
2493
2494 /*
2495 * Save the relation name for a possible error message, to avoid a
2496 * catalog lookup in case of an error. If any of these return NULL,
2497 * then the relation has been dropped since last we checked; skip it.
2498 * Note: they must live in a long-lived memory context because we call
2499 * vacuum and analyze in different transactions.
2500 */
2501
2502 tab->at_relname = get_rel_name(tab->at_relid);
2505 if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2506 goto deleted;
2507
2508 /*
2509 * We will abort vacuuming the current table if something errors out,
2510 * and continue with the next one in schedule; in particular, this
2511 * happens if we are interrupted with SIGINT.
2512 */
2513 PG_TRY();
2514 {
2515 /* Use PortalContext for any per-table allocations */
2517
2518 /* have at it */
2519 autovacuum_do_vac_analyze(tab, bstrategy);
2520
2521 /*
2522 * Clear a possible query-cancel signal, to avoid a late reaction
2523 * to an automatically-sent signal because of vacuuming the
2524 * current table (we're done with it, so it would make no sense to
2525 * cancel at this point.)
2526 */
2527 QueryCancelPending = false;
2528 }
2529 PG_CATCH();
2530 {
2531 /*
2532 * Abort the transaction, start a new one, and proceed with the
2533 * next table in our list.
2534 */
2536 if (tab->at_params.options & VACOPT_VACUUM)
2537 errcontext("automatic vacuum of table \"%s.%s.%s\"",
2538 tab->at_datname, tab->at_nspname, tab->at_relname);
2539 else
2540 errcontext("automatic analyze of table \"%s.%s.%s\"",
2541 tab->at_datname, tab->at_nspname, tab->at_relname);
2543
2544 /* this resets ProcGlobal->statusFlags[i] too */
2548
2549 /* restart our transaction for the following operations */
2552 }
2553 PG_END_TRY();
2554
2555 /* Make sure we're back in AutovacMemCxt */
2557
2558 did_vacuum = true;
2559
2560 /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2561
2562 /* be tidy */
2563deleted:
2564 if (tab->at_datname != NULL)
2565 pfree(tab->at_datname);
2566 if (tab->at_nspname != NULL)
2567 pfree(tab->at_nspname);
2568 if (tab->at_relname != NULL)
2569 pfree(tab->at_relname);
2570 pfree(tab);
2571
2572 /*
2573 * Remove my info from shared memory. We set wi_dobalance on the
2574 * assumption that we are more likely than not to vacuum a table with
2575 * no cost-related storage parameters next, so we want to claim our
2576 * share of I/O as soon as possible to avoid thrashing the global
2577 * balance.
2578 */
2581 MyWorkerInfo->wi_sharedrel = false;
2584 }
2585
2587
2588 /*
2589 * Perform additional work items, as requested by backends.
2590 */
2592 for (i = 0; i < NUM_WORKITEMS; i++)
2593 {
2595
2596 if (!workitem->avw_used)
2597 continue;
2598 if (workitem->avw_active)
2599 continue;
2600 if (workitem->avw_database != MyDatabaseId)
2601 continue;
2602
2603 /* claim this one, and release lock while performing it */
2604 workitem->avw_active = true;
2606
2609 if (ActiveSnapshotSet()) /* transaction could have aborted */
2611
2612 /*
2613 * Check for config changes before acquiring lock for further jobs.
2614 */
2617 {
2618 ConfigReloadPending = false;
2621 }
2622
2624
2625 /* and mark it done */
2626 workitem->avw_active = false;
2627 workitem->avw_used = false;
2628 }
2630
2631 /*
2632 * We leak table_toast_map here (among other things), but since we're
2633 * going away soon, it's not a problem normally. But when using Valgrind,
2634 * release some stuff to reduce complaints about leaked storage.
2635 */
2636#ifdef USE_VALGRIND
2639 if (bstrategy)
2640 pfree(bstrategy);
2641#endif
2642
2643 /* Run the rest in xact context, mainly to avoid Valgrind leak warnings */
2645
2646 /*
2647 * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2648 * only need to do this once, not after each table.
2649 *
2650 * Even if we didn't vacuum anything, it may still be important to do
2651 * this, because one indirect effect of vac_update_datfrozenxid() is to
2652 * update TransamVariables->xidVacLimit. That might need to be done even
2653 * if we haven't vacuumed anything, because relations with older
2654 * relfrozenxid values or other databases with older datfrozenxid values
2655 * might have been dropped, allowing xidVacLimit to advance.
2656 *
2657 * However, it's also important not to do this blindly in all cases,
2658 * because when autovacuum=off this will restart the autovacuum launcher.
2659 * If we're not careful, an infinite loop can result, where workers find
2660 * no work to do and restart the launcher, which starts another worker in
2661 * the same database that finds no work to do. To prevent that, we skip
2662 * this if (1) we found no work to do and (2) we skipped at least one
2663 * table due to concurrent autovacuum activity. In that case, the other
2664 * worker has already done it, or will do so when it finishes.
2665 */
2668
2669 /* Finally close out the last transaction. */
2671}
2672
2673/*
2674 * Execute a previously registered work item.
2675 */
2676static void
2678{
2679 char *cur_datname = NULL;
2680 char *cur_nspname = NULL;
2681 char *cur_relname = NULL;
2682
2683 /*
2684 * Note we do not store table info in MyWorkerInfo, since this is not
2685 * vacuuming proper.
2686 */
2687
2688 /*
2689 * Save the relation name for a possible error message, to avoid a catalog
2690 * lookup in case of an error. If any of these return NULL, then the
2691 * relation has been dropped since last we checked; skip it.
2692 */
2694
2695 cur_relname = get_rel_name(workitem->avw_relation);
2698 if (!cur_relname || !cur_nspname || !cur_datname)
2699 goto deleted2;
2700
2702
2703 /* clean up memory before each work item */
2705
2706 /*
2707 * We will abort the current work item if something errors out, and
2708 * continue with the next one; in particular, this happens if we are
2709 * interrupted with SIGINT. Note that this means that the work item list
2710 * can be lossy.
2711 */
2712 PG_TRY();
2713 {
2714 /* Use PortalContext for any per-work-item allocations */
2716
2717 /*
2718 * Have at it. Functions called here are responsible for any required
2719 * user switch and sandbox.
2720 */
2721 switch (workitem->avw_type)
2722 {
2725 ObjectIdGetDatum(workitem->avw_relation),
2726 Int64GetDatum((int64) workitem->avw_blockNumber));
2727 break;
2728 default:
2729 elog(WARNING, "unrecognized work item found: type %d",
2730 workitem->avw_type);
2731 break;
2732 }
2733
2734 /*
2735 * Clear a possible query-cancel signal, to avoid a late reaction to
2736 * an automatically-sent signal because of vacuuming the current table
2737 * (we're done with it, so it would make no sense to cancel at this
2738 * point.)
2739 */
2740 QueryCancelPending = false;
2741 }
2742 PG_CATCH();
2743 {
2744 /*
2745 * Abort the transaction, start a new one, and proceed with the next
2746 * table in our list.
2747 */
2749 errcontext("processing work entry for relation \"%s.%s.%s\"",
2750 cur_datname, cur_nspname, cur_relname);
2752
2753 /* this resets ProcGlobal->statusFlags[i] too */
2757
2758 /* restart our transaction for the following operations */
2761 }
2762 PG_END_TRY();
2763
2764 /* Make sure we're back in AutovacMemCxt */
2766
2767 /* We intentionally do not set did_vacuum here */
2768
2769 /* be tidy */
2770deleted2:
2771 if (cur_datname)
2773 if (cur_nspname)
2775 if (cur_relname)
2776 pfree(cur_relname);
2777}
2778
2779/*
2780 * extract_autovac_opts
2781 *
2782 * Given a relation's pg_class tuple, return a palloc'd copy of the
2783 * AutoVacOpts portion of reloptions, if set; otherwise, return NULL.
2784 *
2785 * Note: callers do not have a relation lock on the table at this point,
2786 * so the table could have been dropped, and its catalog rows gone, after
2787 * we acquired the pg_class row. If pg_class had a TOAST table, this would
2788 * be a risk; fortunately, it doesn't.
2789 */
2790static AutoVacOpts *
2792{
2793 bytea *relopts;
2794 AutoVacOpts *av;
2795
2797 ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2799
2801 if (relopts == NULL)
2802 return NULL;
2803
2805 memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2806 pfree(relopts);
2807
2808 return av;
2809}
2810
2811
2812/*
2813 * table_recheck_autovac
2814 *
2815 * Recheck whether a table still needs vacuum or analyze. Return value is a
2816 * valid autovac_table pointer if it does, NULL otherwise.
2817 *
2818 * Note that the returned autovac_table does not have the name fields set.
2819 */
2820static autovac_table *
2824{
2827 bool dovacuum;
2828 bool doanalyze;
2829 autovac_table *tab = NULL;
2830 bool wraparound;
2832 bool free_avopts = false;
2834
2835 /* fetch the relation's relcache entry */
2838 return NULL;
2840
2841 /*
2842 * Get the applicable reloptions. If it is a TOAST table, try to get the
2843 * main table reloptions if the toast table itself doesn't have.
2844 */
2846 if (avopts)
2847 free_avopts = true;
2848 else if (classForm->relkind == RELKIND_TOASTVALUE &&
2850 {
2852 bool found;
2853
2854 hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2855 if (found && hentry->ar_hasrelopts)
2856 avopts = &hentry->ar_reloptions;
2857 }
2858
2861 DEBUG3,
2863 &scores);
2864
2865 /* OK, it needs something done */
2866 if (doanalyze || dovacuum)
2867 {
2868 int freeze_min_age;
2869 int freeze_table_age;
2870 int multixact_freeze_min_age;
2871 int multixact_freeze_table_age;
2872 int log_vacuum_min_duration;
2873 int log_analyze_min_duration;
2874
2875 /*
2876 * Calculate the vacuum cost parameters and the freeze ages. If there
2877 * are options set in pg_class.reloptions, use them; in the case of a
2878 * toast table, try the main table too. Otherwise use the GUC
2879 * defaults, autovacuum's own first and plain vacuum second.
2880 */
2881
2882 /* -1 in autovac setting means use log_autovacuum_min_duration */
2883 log_vacuum_min_duration = (avopts && avopts->log_vacuum_min_duration >= 0)
2884 ? avopts->log_vacuum_min_duration
2886
2887 /* -1 in autovac setting means use log_autoanalyze_min_duration */
2888 log_analyze_min_duration = (avopts && avopts->log_analyze_min_duration >= 0)
2889 ? avopts->log_analyze_min_duration
2891
2892 /* these do not have autovacuum-specific settings */
2893 freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2894 ? avopts->freeze_min_age
2896
2897 freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2898 ? avopts->freeze_table_age
2900
2901 multixact_freeze_min_age = (avopts &&
2902 avopts->multixact_freeze_min_age >= 0)
2903 ? avopts->multixact_freeze_min_age
2905
2906 multixact_freeze_table_age = (avopts &&
2907 avopts->multixact_freeze_table_age >= 0)
2908 ? avopts->multixact_freeze_table_age
2910
2912 tab->at_relid = relid;
2913
2914 /*
2915 * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2916 * that vacuum() skips toast relations. Also note we tell vacuum() to
2917 * skip vac_update_datfrozenxid(); we'll do that separately.
2918 */
2919 tab->at_params.options =
2923 (doanalyze ? VACOPT_ANALYZE : 0) |
2925
2926 /*
2927 * index_cleanup and truncate are unspecified at first in autovacuum.
2928 * They will be filled in with usable values using their reloptions
2929 * (or reloption defaults) later.
2930 */
2933 tab->at_params.freeze_min_age = freeze_min_age;
2934 tab->at_params.freeze_table_age = freeze_table_age;
2935 tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2936 tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2938 tab->at_params.log_vacuum_min_duration = log_vacuum_min_duration;
2939 tab->at_params.log_analyze_min_duration = log_analyze_min_duration;
2941
2942 /* Determine the number of parallel vacuum workers to use */
2943 tab->at_params.nworkers = 0;
2944 if (avopts)
2945 {
2946 if (avopts->autovacuum_parallel_workers == 0)
2947 {
2948 /*
2949 * Disable parallel vacuum, if the reloption sets the parallel
2950 * degree as zero.
2951 */
2952 tab->at_params.nworkers = -1;
2953 }
2954 else if (avopts->autovacuum_parallel_workers > 0)
2955 tab->at_params.nworkers = avopts->autovacuum_parallel_workers;
2956
2957 /*
2958 * autovacuum_parallel_workers == -1 falls through, keep
2959 * nworkers=0
2960 */
2961 }
2962
2963 /*
2964 * Later, in vacuum_rel(), we check reloptions for any
2965 * vacuum_max_eager_freeze_failure_rate override.
2966 */
2969 avopts->vacuum_cost_limit : 0;
2971 avopts->vacuum_cost_delay : -1;
2972 tab->at_relname = NULL;
2973 tab->at_nspname = NULL;
2974 tab->at_datname = NULL;
2975
2976 /*
2977 * If any of the cost delay parameters has been set individually for
2978 * this table, disable the balancing algorithm.
2979 */
2980 tab->at_dobalance =
2981 !(avopts && (avopts->vacuum_cost_limit > 0 ||
2982 avopts->vacuum_cost_delay >= 0));
2983 }
2984
2985 if (free_avopts)
2986 pfree(avopts);
2988 return tab;
2989}
2990
2991/*
2992 * relation_needs_vacanalyze
2993 *
2994 * Check whether a relation needs to be vacuumed or analyzed; return each into
2995 * "dovacuum" and "doanalyze", respectively. Also return whether the vacuum is
2996 * being forced because of Xid or multixact wraparound.
2997 *
2998 * relopts is a pointer to the AutoVacOpts options (either for itself in the
2999 * case of a plain table, or for either itself or its parent table in the case
3000 * of a TOAST table), NULL if none.
3001 *
3002 * A table needs to be vacuumed if the number of dead tuples exceeds a
3003 * threshold. This threshold is calculated as
3004 *
3005 * threshold = vac_base_thresh + vac_scale_factor * reltuples
3006 * if (threshold > vac_max_thresh)
3007 * threshold = vac_max_thresh;
3008 *
3009 * For analyze, the analysis done is that the number of tuples inserted,
3010 * deleted and updated since the last analyze exceeds a threshold calculated
3011 * in the same fashion as above. Note that the cumulative stats system stores
3012 * the number of tuples (both live and dead) that there were as of the last
3013 * analyze. This is asymmetric to the VACUUM case.
3014 *
3015 * We also force vacuum if the table's relfrozenxid is more than freeze_max_age
3016 * transactions back, and if its relminmxid is more than
3017 * multixact_freeze_max_age multixacts back.
3018 *
3019 * A table whose autovacuum_enabled option is false is
3020 * automatically skipped (unless we have to vacuum it due to freeze_max_age).
3021 * Thus autovacuum can be disabled for specific tables. Also, when the cumulative
3022 * stats system does not have data about a table, it will be skipped.
3023 *
3024 * A table whose vac_base_thresh value is < 0 takes the base value from the
3025 * autovacuum_vacuum_threshold GUC variable. Similarly, a vac_scale_factor
3026 * value < 0 is substituted with the value of
3027 * autovacuum_vacuum_scale_factor GUC variable. Ditto for analyze.
3028 *
3029 * This function also returns scores that can be used to sort the list of
3030 * tables to process. The idea is to have autovacuum prioritize tables that
3031 * are furthest beyond their thresholds (e.g., a table nearing transaction ID
3032 * wraparound should be vacuumed first). This prioritization scheme is
3033 * certainly far from perfect; there are simply too many possibilities for any
3034 * scoring technique to work across all workloads, and the situation might
3035 * change significantly between the time we calculate the score and the time
3036 * that autovacuum processes it. However, we have attempted to develop
3037 * something that is expected to work for a large portion of workloads with
3038 * reasonable parameter settings.
3039 *
3040 * The autovacuum table score is calculated as the maximum of the ratios of
3041 * each of the table's relevant values to its threshold. For example, if the
3042 * number of inserted tuples is 100, and the insert threshold for the table is
3043 * 80, the insert score is 1.25. If all other scores are below that value, the
3044 * returned score will be 1.25. The other criteria considered for the score
3045 * are the table ages (both relfrozenxid and relminmxid) compared to the
3046 * corresponding freeze-max-age setting, the number of updated/deleted tuples
3047 * compared to the vacuum threshold, and the number of inserted/updated/deleted
3048 * tuples compared to the analyze threshold.
3049 *
3050 * One exception to the previous paragraph is for tables nearing wraparound,
3051 * i.e., those that have surpassed the effective failsafe ages. In that case,
3052 * the relfrozenxid/relminmxid-based score is scaled aggressively so that the
3053 * table has a decent chance of sorting to the front of the list. Furthermore,
3054 * the relminmxid-based score is scaled aggressively as
3055 * effective_multixact_freeze_max_age is lowered due to high multixact member
3056 * space usage.
3057 *
3058 * To adjust how strongly each component contributes to the score, the
3059 * following parameters can be adjusted from their default of 1.0 to anywhere
3060 * between 0.0 and 10.0 (inclusive). Setting all of these to 0.0 restores
3061 * pre-v19 prioritization behavior:
3062 *
3063 * autovacuum_freeze_score_weight
3064 * autovacuum_multixact_freeze_score_weight
3065 * autovacuum_vacuum_score_weight
3066 * autovacuum_vacuum_insert_score_weight
3067 * autovacuum_analyze_score_weight
3068 *
3069 * The autovacuum table score is returned in scores->max. The component scores
3070 * are also returned in the "scores" argument via the other members of the
3071 * AutoVacuumScores struct.
3072 */
3073static void
3078 int elevel,
3079 /* output params below */
3080 bool *dovacuum,
3081 bool *doanalyze,
3082 bool *wraparound,
3084{
3086 bool force_vacuum;
3087 bool av_enabled;
3088 bool may_free = false;
3089
3090 /* constants from reloptions or GUC variables */
3091 int vac_base_thresh,
3098
3099 /* thresholds calculated from above constants */
3102 anlthresh;
3103
3104 /* number of vacuum (resp. analyze) tuples at this time */
3106 instuples,
3107 anltuples;
3108
3109 /* freeze parameters */
3110 int freeze_max_age;
3111 int multixact_freeze_max_age;
3113 TransactionId relfrozenxid;
3114 MultiXactId relminmxid;
3120
3122 float4 reltuples = classForm->reltuples;
3123 int32 relpages = classForm->relpages;
3124 int32 relallfrozen = classForm->relallfrozen;
3125
3126 Assert(classForm != NULL);
3127 Assert(OidIsValid(relid));
3128
3129 memset(scores, 0, sizeof(AutoVacuumScores));
3130 *dovacuum = false;
3131 *doanalyze = false;
3132
3133 /*
3134 * Determine vacuum/analyze equation parameters. We have two possible
3135 * sources: the passed reloptions (which could be a main table or a toast
3136 * table), or the autovacuum GUC variables.
3137 */
3138
3139 /* -1 in autovac setting means use plain vacuum_scale_factor */
3140 vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3141 ? relopts->vacuum_scale_factor
3143
3144 vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3145 ? relopts->vacuum_threshold
3147
3148 /* -1 is used to disable max threshold */
3149 vac_max_thresh = (relopts && relopts->vacuum_max_threshold >= -1)
3150 ? relopts->vacuum_max_threshold
3152
3153 vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3154 ? relopts->vacuum_ins_scale_factor
3156
3157 /* -1 is used to disable insert vacuums */
3158 vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3159 ? relopts->vacuum_ins_threshold
3161
3162 anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3163 ? relopts->analyze_scale_factor
3165
3166 anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3167 ? relopts->analyze_threshold
3169
3170 freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3171 ? Min(relopts->freeze_max_age, autovacuum_freeze_max_age)
3173
3174 multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3175 ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3177
3178 av_enabled = (relopts ? relopts->enabled : true);
3180
3181 relfrozenxid = classForm->relfrozenxid;
3182 relminmxid = classForm->relminmxid;
3183
3184 /* Force vacuum if table is at risk of wraparound */
3185 xidForceLimit = recentXid - freeze_max_age;
3188 force_vacuum = (TransactionIdIsNormal(relfrozenxid) &&
3189 TransactionIdPrecedes(relfrozenxid, xidForceLimit));
3190 if (!force_vacuum)
3191 {
3192 multiForceLimit = recentMulti - multixact_freeze_max_age;
3195 force_vacuum = MultiXactIdIsValid(relminmxid) &&
3197 }
3199
3200 /*
3201 * To calculate the (M)XID age portion of the score, divide the age by its
3202 * respective *_freeze_max_age parameter. The multixact_freeze_max_age
3203 * variable might be 0 here (i.e., a division-by-zero hazard), so in that
3204 * case we use the mxid_age as the MXID score.
3205 */
3206 xid_age = TransactionIdIsNormal(relfrozenxid) ? recentXid - relfrozenxid : 0;
3207 mxid_age = MultiXactIdIsValid(relminmxid) ? recentMulti - relminmxid : 0;
3208
3209 scores->xid = (double) xid_age / freeze_max_age;
3210 scores->mxid = (double) mxid_age / Max(1, multixact_freeze_max_age);
3211
3212 /*
3213 * To ensure tables are given increased priority once they begin
3214 * approaching wraparound, we scale the score aggressively if the ages
3215 * surpass vacuum_failsafe_age or vacuum_multixact_failsafe_age.
3216 *
3217 * As in vacuum_xid_failsafe_check(), the effective failsafe age is no
3218 * less than 105% the value of the respective *_freeze_max_age parameter.
3219 * Note that per-table settings could result in a low score even if the
3220 * table surpasses the failsafe settings. However, this is a strange
3221 * enough corner case that we don't bother trying to handle it.
3222 *
3223 * We further adjust the effective failsafe ages with the weight
3224 * parameters so that increasing them lowers the ages at which we begin
3225 * scaling aggressively.
3226 */
3231
3236
3238 scores->xid = pow(scores->xid, Max(1.0, (double) xid_age / 100000000));
3240 scores->mxid = pow(scores->mxid, Max(1.0, (double) mxid_age / 100000000));
3241
3244
3245 scores->max = Max(scores->xid, scores->mxid);
3246 if (force_vacuum)
3247 *dovacuum = true;
3248
3249 /*
3250 * If we found stats for the table, and autovacuum is currently enabled,
3251 * make a threshold-based decision whether to vacuum and/or analyze. If
3252 * autovacuum is currently disabled, we must be here for anti-wraparound
3253 * vacuuming only, so don't vacuum (or analyze) anything that's not being
3254 * forced.
3255 */
3257 relid, &may_free);
3258 if (!tabentry)
3259 return;
3260
3261 vactuples = tabentry->dead_tuples;
3262 instuples = tabentry->ins_since_vacuum;
3263 anltuples = tabentry->mod_since_analyze;
3264
3265 /* If the table hasn't yet been vacuumed, take reltuples as zero */
3266 if (reltuples < 0)
3267 reltuples = 0;
3268
3269 /*
3270 * If we have data for relallfrozen, calculate the unfrozen percentage of
3271 * the table to modify insert scale factor. This helps us decide whether
3272 * or not to vacuum an insert-heavy table based on the number of inserts
3273 * to the more "active" part of the table.
3274 */
3275 if (relpages > 0 && relallfrozen > 0)
3276 {
3277 /*
3278 * It could be the stats were updated manually and relallfrozen >
3279 * relpages. Clamp relallfrozen to relpages to avoid nonsensical
3280 * calculations.
3281 */
3282 relallfrozen = Min(relallfrozen, relpages);
3283 pcnt_unfrozen = 1 - ((float4) relallfrozen / relpages);
3284 }
3285
3289
3291 vac_ins_scale_factor * reltuples * pcnt_unfrozen;
3293
3294 /* Determine if this table needs vacuum, and update the score. */
3295 scores->vac = (double) vactuples / Max(vacthresh, 1);
3297 scores->max = Max(scores->max, scores->vac);
3299 *dovacuum = true;
3300
3301 if (vac_ins_base_thresh >= 0)
3302 {
3303 scores->vac_ins = (double) instuples / Max(vacinsthresh, 1);
3305 scores->max = Max(scores->max, scores->vac_ins);
3307 *dovacuum = true;
3308 }
3309
3310 /*
3311 * Determine if this table needs analyze, and update the score. Note that
3312 * we don't analyze TOAST tables and pg_statistic.
3313 */
3314 if (relid != StatisticRelationId &&
3315 classForm->relkind != RELKIND_TOASTVALUE)
3316 {
3317 scores->anl = (double) anltuples / Max(anlthresh, 1);
3319 scores->max = Max(scores->max, scores->anl);
3321 *doanalyze = true;
3322 }
3323
3324 if (vac_ins_base_thresh >= 0)
3325 elog(elevel, "%s: vac: %.0f (thresh %.0f, score %.2f), ins: %.0f (thresh %.0f, score %.2f), anl: %.0f (thresh %.0f, score %.2f), xid score: %.2f, mxid score: %.2f",
3326 NameStr(classForm->relname),
3327 vactuples, vacthresh, scores->vac,
3328 instuples, vacinsthresh, scores->vac_ins,
3329 anltuples, anlthresh, scores->anl,
3330 scores->xid, scores->mxid);
3331 else
3332 elog(elevel, "%s: vac: %.0f (thresh %.0f, score %.2f), ins: (disabled), anl: %.0f (thresh %.0f, score %.2f), xid score: %.2f, mxid score: %.2f",
3333 NameStr(classForm->relname),
3334 vactuples, vacthresh, scores->vac,
3335 anltuples, anlthresh, scores->anl,
3336 scores->xid, scores->mxid);
3337
3338 /* Avoid leaking pgstat entries until the end of autovacuum. */
3339 if (may_free)
3340 pfree(tabentry);
3341}
3342
3343/*
3344 * autovacuum_do_vac_analyze
3345 * Vacuum and/or analyze the specified table
3346 *
3347 * We expect the caller to have switched into a memory context that won't
3348 * disappear at transaction commit.
3349 */
3350static void
3352{
3354 VacuumRelation *rel;
3355 List *rel_list;
3358
3359 /* Let pgstat know what we're doing */
3361
3362 /* Create a context that vacuum() can use as cross-transaction storage */
3364 "Vacuum",
3366
3367 /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3369 rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3371 rel_list = list_make1(rel);
3373
3374 vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3375
3377}
3378
3379/*
3380 * autovac_report_activity
3381 * Report to pgstat what autovacuum is doing
3382 *
3383 * We send a SQL string corresponding to what the user would see if the
3384 * equivalent command was to be issued manually.
3385 *
3386 * Note we assume that we are going to report the next command as soon as we're
3387 * done with the current one, and exit right after the last one, so we don't
3388 * bother to report "<IDLE>" or some such.
3389 */
3390static void
3392{
3393#define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3395 int len;
3396
3397 /* Report the command and possible options */
3398 if (tab->at_params.options & VACOPT_VACUUM)
3400 "autovacuum: VACUUM%s",
3401 tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3402 else
3404 "autovacuum: ANALYZE");
3405
3406 /*
3407 * Report the qualified name of the relation.
3408 */
3409 len = strlen(activity);
3410
3412 " %s.%s%s", tab->at_nspname, tab->at_relname,
3413 tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3414
3415 /* Set statement_timestamp() to current time for pg_stat_activity */
3417
3419}
3420
3421/*
3422 * autovac_report_workitem
3423 * Report to pgstat that autovacuum is processing a work item
3424 */
3425static void
3427 const char *nspname, const char *relname)
3428{
3429 char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3430 char blk[12 + 2];
3431 int len;
3432
3433 switch (workitem->avw_type)
3434 {
3437 "autovacuum: BRIN summarize");
3438 break;
3439 }
3440
3441 /*
3442 * Report the qualified name of the relation, and the block number if any
3443 */
3444 len = strlen(activity);
3445
3446 if (BlockNumberIsValid(workitem->avw_blockNumber))
3447 snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3448 else
3449 blk[0] = '\0';
3450
3452 " %s.%s%s", nspname, relname, blk);
3453
3454 /* Set statement_timestamp() to current time for pg_stat_activity */
3456
3458}
3459
3460/*
3461 * AutoVacuumingActive
3462 * Check GUC vars and report whether the autovacuum process should be
3463 * running.
3464 */
3465bool
3467{
3469 return false;
3470 return true;
3471}
3472
3473/*
3474 * Request one work item to the next autovacuum run processing our database.
3475 * Return false if the request can't be recorded.
3476 */
3477bool
3479 BlockNumber blkno)
3480{
3481 int i;
3482 bool result = false;
3483
3485
3486 /*
3487 * Locate an unused work item and fill it with the given data.
3488 */
3489 for (i = 0; i < NUM_WORKITEMS; i++)
3490 {
3492
3493 if (workitem->avw_used)
3494 continue;
3495
3496 workitem->avw_used = true;
3497 workitem->avw_active = false;
3498 workitem->avw_type = type;
3499 workitem->avw_database = MyDatabaseId;
3500 workitem->avw_relation = relationId;
3501 workitem->avw_blockNumber = blkno;
3502 result = true;
3503
3504 /* done */
3505 break;
3506 }
3507
3509
3510 return result;
3511}
3512
3513/*
3514 * autovac_init
3515 * This is called at postmaster initialization.
3516 *
3517 * All we do here is annoy the user if he got it wrong.
3518 */
3519void
3521{
3523 return;
3524 else if (!pgstat_track_counts)
3526 (errmsg("autovacuum not started because of misconfiguration"),
3527 errhint("Enable the \"track_counts\" option.")));
3528 else
3530}
3531
3532/*
3533 * AutoVacuumShmemRequest
3534 * Register shared memory space needed for autovacuum
3535 */
3536static void
3538{
3539 Size size;
3540
3541 /*
3542 * Need the fixed struct and the array of WorkerInfoData.
3543 */
3544 size = sizeof(AutoVacuumShmemStruct);
3545 size = MAXALIGN(size);
3547 sizeof(WorkerInfoData)));
3548
3549 ShmemRequestStruct(.name = "AutoVacuum Data",
3550 .size = size,
3551 .ptr = (void **) &AutoVacuumShmem,
3552 );
3553}
3554
3555/*
3556 * AutoVacuumShmemInit
3557 * Initialize autovacuum-related shared memory
3558 */
3559static void
3561{
3562 WorkerInfo worker;
3563
3569
3570 worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3572
3573 /* initialize the WorkerInfo free list */
3574 for (int i = 0; i < autovacuum_worker_slots; i++)
3575 {
3577 &worker[i].wi_links);
3578 pg_atomic_init_flag(&worker[i].wi_dobalance);
3579 }
3580
3582}
3583
3584/*
3585 * GUC check_hook for autovacuum_work_mem
3586 */
3587bool
3589{
3590 /*
3591 * -1 indicates fallback.
3592 *
3593 * If we haven't yet changed the boot_val default of -1, just let it be.
3594 * Autovacuum will look to maintenance_work_mem instead.
3595 */
3596 if (*newval == -1)
3597 return true;
3598
3599 /*
3600 * We clamp manually-set values to at least 64kB. Since
3601 * maintenance_work_mem is always set to at least this value, do the same
3602 * here.
3603 */
3604 if (*newval < 64)
3605 *newval = 64;
3606
3607 return true;
3608}
3609
3610/*
3611 * Returns whether there is a free autovacuum worker slot available.
3612 */
3613static bool
3626
3627/*
3628 * Emits a WARNING if autovacuum_worker_slots < autovacuum_max_workers.
3629 */
3630static void
3632{
3636 errmsg("\"%s\" (%d) should be less than or equal to \"%s\" (%d)",
3637 "autovacuum_max_workers", autovacuum_max_workers,
3638 "autovacuum_worker_slots", autovacuum_worker_slots),
3639 errdetail("The server will only start up to \"%s\" (%d) autovacuum workers at a given time.",
3640 "autovacuum_worker_slots", autovacuum_worker_slots)));
3641}
3642
3643/*
3644 * pg_stat_get_autovacuum_scores
3645 *
3646 * Returns current autovacuum scores for all relevant tables in the current
3647 * database.
3648 */
3649Datum
3651{
3653 Relation rel;
3654 TableScanDesc scan;
3655 HeapTuple tup;
3656 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
3657
3658 InitMaterializedSRF(fcinfo, 0);
3659
3660 /* some prerequisite initialization */
3664
3665 /* scan pg_class */
3667 scan = table_beginscan_catalog(rel, 0, NULL);
3668 while ((tup = heap_getnext(scan, ForwardScanDirection)) != NULL)
3669 {
3672 bool dovacuum;
3673 bool doanalyze;
3674 bool wraparound;
3676 Datum vals[10];
3677 bool nulls[10] = {false};
3678
3679 /* skip ineligible entries */
3680 if (form->relkind != RELKIND_RELATION &&
3681 form->relkind != RELKIND_MATVIEW &&
3682 form->relkind != RELKIND_TOASTVALUE)
3683 continue;
3684 if (form->relpersistence == RELPERSISTENCE_TEMP)
3685 continue;
3686
3690 LOG_NEVER,
3692 &scores);
3693 if (avopts)
3694 pfree(avopts);
3695
3696 vals[0] = ObjectIdGetDatum(form->oid);
3697 vals[1] = Float8GetDatum(scores.max);
3698 vals[2] = Float8GetDatum(scores.xid);
3699 vals[3] = Float8GetDatum(scores.mxid);
3700 vals[4] = Float8GetDatum(scores.vac);
3701 vals[5] = Float8GetDatum(scores.vac_ins);
3702 vals[6] = Float8GetDatum(scores.anl);
3703 vals[7] = BoolGetDatum(dovacuum);
3704 vals[8] = BoolGetDatum(doanalyze);
3705 vals[9] = BoolGetDatum(wraparound);
3706
3707 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, vals, nulls);
3708 }
3709 table_endscan(scan);
3711
3712 return (Datum) 0;
3713}
void pgaio_error_cleanup(void)
Definition aio.c:1175
static void pg_atomic_clear_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:200
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition atomics.h:214
static bool pg_atomic_test_set_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:176
static bool pg_atomic_unlocked_test_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:189
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition atomics.h:269
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:232
static void pg_atomic_init_flag(volatile pg_atomic_flag *ptr)
Definition atomics.h:163
static Oid do_start_worker(void)
static void launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
Definition autovacuum.c:847
int autovacuum_worker_slots
Definition autovacuum.c:124
void VacuumUpdateCosts(void)
void AutoVacLauncherMain(const void *startup_data, size_t startup_data_len)
Definition autovacuum.c:411
static volatile sig_atomic_t got_SIGUSR2
Definition autovacuum.c:165
static void avl_sigusr2_handler(SIGNAL_ARGS)
int autovacuum_multixact_freeze_max_age
Definition autovacuum.c:136
static bool av_worker_available(void)
static int default_multixact_freeze_table_age
Definition autovacuum.c:175
int autovacuum_naptime
Definition autovacuum.c:127
double autovacuum_vac_scale
Definition autovacuum.c:130
void AutoVacWorkerMain(const void *startup_data, size_t startup_data_len)
static void FreeWorkerInfo(int code, Datum arg)
Datum pg_stat_get_autovacuum_scores(PG_FUNCTION_ARGS)
int Log_autovacuum_min_duration
Definition autovacuum.c:145
int autovacuum_anl_thresh
Definition autovacuum.c:133
static TransactionId recentXid
Definition autovacuum.c:168
#define NUM_WORKITEMS
Definition autovacuum.c:282
static List * get_database_list(void)
bool check_autovacuum_work_mem(int *newval, void **extra, GucSource source)
static void autovac_report_activity(autovac_table *tab)
static void AutoVacuumShmemInit(void *arg)
static int default_multixact_freeze_min_age
Definition autovacuum.c:174
const ShmemCallbacks AutoVacuumShmemCallbacks
Definition autovacuum.c:316
static void do_autovacuum(void)
int autovacuum_vac_cost_limit
Definition autovacuum.c:143
static double av_storage_param_cost_delay
Definition autovacuum.c:161
bool AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId, BlockNumber blkno)
bool AutoVacuumingActive(void)
static int TableToProcessComparator(const ListCell *a, const ListCell *b)
int autovacuum_max_workers
Definition autovacuum.c:125
int autovacuum_freeze_max_age
Definition autovacuum.c:135
static int db_comparator(const void *a, const void *b)
static int av_storage_param_cost_limit
Definition autovacuum.c:162
double autovacuum_vac_cost_delay
Definition autovacuum.c:142
static pg_noreturn void AutoVacLauncherShutdown(void)
Definition autovacuum.c:832
#define AutoVacNumSignals
Definition autovacuum.c:264
int autovacuum_vac_thresh
Definition autovacuum.c:128
AutoVacuumSignal
Definition autovacuum.c:259
@ AutoVacRebalance
Definition autovacuum.c:261
@ AutoVacForkFailed
Definition autovacuum.c:260
static void launch_worker(TimestampTz now)
static dlist_head DatabaseList
Definition autovacuum.c:325
static void rebuild_database_list(Oid newdb)
Definition autovacuum.c:931
static AutoVacuumShmemStruct * AutoVacuumShmem
Definition autovacuum.c:311
double autovacuum_analyze_score_weight
Definition autovacuum.c:141
int autovacuum_work_mem
Definition autovacuum.c:126
double autovacuum_vacuum_insert_score_weight
Definition autovacuum.c:140
static void check_av_worker_gucs(void)
static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts, Form_pg_class classForm, int effective_multixact_freeze_max_age, int elevel, bool *dovacuum, bool *doanalyze, bool *wraparound, AutoVacuumScores *scores)
double autovacuum_vacuum_score_weight
Definition autovacuum.c:139
#define MIN_AUTOVAC_SLEEPTIME
Definition autovacuum.c:149
#define MAX_AUTOVAC_ACTIV_LEN
double autovacuum_anl_scale
Definition autovacuum.c:134
int autovacuum_vac_ins_thresh
Definition autovacuum.c:131
#define MAX_AUTOVAC_SLEEPTIME
Definition autovacuum.c:150
static MemoryContext DatabaseListCxt
Definition autovacuum.c:326
void AutoVacWorkerFailed(void)
struct WorkerInfoData * WorkerInfo
Definition autovacuum.c:251
double autovacuum_multixact_freeze_score_weight
Definition autovacuum.c:138
bool autovacuum_start_daemon
Definition autovacuum.c:123
static void perform_work_item(AutoVacuumWorkItem *workitem)
static void AutoVacuumShmemRequest(void *arg)
double autovacuum_vac_ins_scale
Definition autovacuum.c:132
static MultiXactId recentMulti
Definition autovacuum.c:169
static int default_freeze_min_age
Definition autovacuum.c:172
static void autovac_recalculate_workers_for_balance(void)
int autovacuum_vac_max_thresh
Definition autovacuum.c:129
void AutoVacuumUpdateCostLimit(void)
static WorkerInfo MyWorkerInfo
Definition autovacuum.c:363
static void autovac_report_workitem(AutoVacuumWorkItem *workitem, const char *nspname, const char *relname)
void autovac_init(void)
static autovac_table * table_recheck_autovac(Oid relid, HTAB *table_toast_map, TupleDesc pg_class_desc, int effective_multixact_freeze_max_age)
static MemoryContext AutovacMemCxt
Definition autovacuum.c:178
double autovacuum_freeze_score_weight
Definition autovacuum.c:137
static void ProcessAutoVacLauncherInterrupts(void)
Definition autovacuum.c:787
static AutoVacOpts * extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
static int default_freeze_table_age
Definition autovacuum.c:173
static void autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
int Log_autoanalyze_min_duration
Definition autovacuum.c:146
AutoVacuumWorkItemType
Definition autovacuum.h:24
@ AVW_BRINSummarizeRange
Definition autovacuum.h:25
sigset_t UnBlockSig
Definition pqsignal.c:22
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1729
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition timestamp.c:1789
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1649
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1613
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_RUNNING
uint32 BlockNumber
Definition block.h:31
static bool BlockNumberIsValid(BlockNumber blockNumber)
Definition block.h:71
Datum brin_summarize_range(PG_FUNCTION_ARGS)
Definition brin.c:1386
void AtEOXact_Buffers(bool isCommit)
Definition bufmgr.c:4222
void UnlockBuffers(void)
Definition bufmgr.c:5875
@ BAS_VACUUM
Definition bufmgr.h:40
#define NameStr(name)
Definition c.h:894
#define Min(x, y)
Definition c.h:1131
#define MAXALIGN(LEN)
Definition c.h:955
#define pg_noreturn
Definition c.h:249
#define Max(x, y)
Definition c.h:1125
#define SIGNAL_ARGS
Definition c.h:1519
#define Assert(condition)
Definition c.h:1002
int64_t int64
Definition c.h:680
TransactionId MultiXactId
Definition c.h:805
int32_t int32
Definition c.h:679
uint32_t uint32
Definition c.h:683
float float4
Definition c.h:772
uint32 TransactionId
Definition c.h:795
#define OidIsValid(objectId)
Definition c.h:917
size_t Size
Definition c.h:748
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
int64 TimestampTz
Definition timestamp.h:39
bool database_is_invalid_form(Form_pg_database datform)
void performDeletion(const ObjectAddress *object, DropBehavior behavior, int flags)
Definition dependency.c:279
#define PERFORM_DELETION_SKIP_EXTENSIONS
Definition dependency.h:96
#define PERFORM_DELETION_QUIETLY
Definition dependency.h:94
#define PERFORM_DELETION_INTERNAL
Definition dependency.h:92
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
void AtEOXact_HashTables(bool isCommit)
Definition dynahash.c:1864
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
void hash_destroy(HTAB *hashp)
Definition dynahash.c:802
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
Datum arg
Definition elog.c:1323
void EmitErrorReport(void)
Definition elog.c:1883
ErrorContextCallback * error_context_stack
Definition elog.c:100
void FlushErrorState(void)
Definition elog.c:2063
bool message_level_is_interesting(int elevel)
Definition elog.c:285
int errcode(int sqlerrcode)
Definition elog.c:875
sigjmp_buf * PG_exception_stack
Definition elog.c:102
#define LOG
Definition elog.h:32
#define errcontext
Definition elog.h:200
int errhint(const char *fmt,...) pg_attribute_printf(1
#define DEBUG3
Definition elog.h:29
int errdetail(const char *fmt,...) pg_attribute_printf(1
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define PG_TRY(...)
Definition elog.h:374
#define WARNING
Definition elog.h:37
#define DEBUG2
Definition elog.h:30
#define PG_END_TRY(...)
Definition elog.h:399
#define DEBUG1
Definition elog.h:31
#define ERROR
Definition elog.h:40
#define PG_CATCH(...)
Definition elog.h:384
#define elog(elevel,...)
Definition elog.h:228
#define LOG_NEVER
Definition elog.h:26
#define ereport(elevel,...)
Definition elog.h:152
void AtEOXact_Files(bool isCommit)
Definition fd.c:3212
#define palloc_object(type)
Definition fe_memutils.h:89
#define DirectFunctionCall2(func, arg1, arg2)
Definition fmgr.h:690
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
BufferAccessStrategy GetAccessStrategyWithSize(BufferAccessStrategyType btype, int ring_size_kb)
Definition freelist.c:511
void InitMaterializedSRF(FunctionCallInfo fcinfo, uint32 flags)
Definition funcapi.c:76
volatile sig_atomic_t LogMemoryContextPending
Definition globals.c:41
volatile sig_atomic_t ProcSignalBarrierPending
Definition globals.c:40
int VacuumCostLimit
Definition globals.c:157
bool VacuumCostActive
Definition globals.c:161
int VacuumCostBalance
Definition globals.c:160
volatile sig_atomic_t QueryCancelPending
Definition globals.c:33
int VacuumBufferUsageLimit
Definition globals.c:152
struct Latch * MyLatch
Definition globals.c:65
double VacuumCostDelay
Definition globals.c:158
Oid MyDatabaseId
Definition globals.c:96
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4234
#define newval
GucSource
Definition guc.h:112
@ PGC_S_OVERRIDE
Definition guc.h:123
@ PGC_SUSET
Definition guc.h:78
@ PGC_SIGHUP
Definition guc.h:75
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1436
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
@ HASH_FIND
Definition hsearch.h:108
@ HASH_ENTER
Definition hsearch.h:109
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
#define dlist_foreach(iter, lhead)
Definition ilist.h:623
static void dlist_init(dlist_head *head)
Definition ilist.h:314
static void dlist_delete(dlist_node *node)
Definition ilist.h:405
static uint32 dclist_count(const dclist_head *head)
Definition ilist.h:932
#define dlist_reverse_foreach(iter, lhead)
Definition ilist.h:654
#define dlist_tail_element(type, membername, lhead)
Definition ilist.h:612
static void dlist_push_head(dlist_head *head, dlist_node *node)
Definition ilist.h:347
static bool dlist_is_empty(const dlist_head *head)
Definition ilist.h:336
static dlist_node * dclist_pop_head_node(dclist_head *head)
Definition ilist.h:789
static void dclist_push_head(dclist_head *head, dlist_node *node)
Definition ilist.h:693
static void dclist_init(dclist_head *head)
Definition ilist.h:671
static void dlist_move_head(dlist_head *head, dlist_node *node)
Definition ilist.h:467
#define DLIST_STATIC_INIT(name)
Definition ilist.h:281
#define dlist_container(type, membername, ptr)
Definition ilist.h:593
#define INJECTION_POINT(name, arg)
static int pg_cmp_s32(int32 a, int32 b)
Definition int.h:713
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition interrupt.c:104
volatile sig_atomic_t ShutdownRequestPending
Definition interrupt.c:28
volatile sig_atomic_t ConfigReloadPending
Definition interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition interrupt.c:61
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:372
void proc_exit(int code)
Definition ipc.c:105
int b
Definition isn.c:74
int a
Definition isn.c:73
int i
Definition isn.c:77
void SetLatch(Latch *latch)
Definition latch.c:290
void ResetLatch(Latch *latch)
Definition latch.c:374
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition latch.c:172
List * lappend(List *list, void *datum)
Definition list.c:339
void list_sort(List *list, list_sort_comparator cmp)
Definition list.c:1674
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
void list_free_deep(List *list)
Definition list.c:1560
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:151
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:229
bool ConditionalLockDatabaseObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1032
#define AccessExclusiveLock
Definition lockdefs.h:43
#define AccessShareLock
Definition lockdefs.h:36
char * get_rel_name(Oid relid)
Definition lsyscache.c:2242
char * get_database_name(Oid dbid)
Definition lsyscache.c:1392
Oid get_rel_namespace(Oid relid)
Definition lsyscache.c:2266
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3682
bool LWLockHeldByMe(LWLock *lock)
Definition lwlock.c:1885
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
void LWLockReleaseAll(void)
Definition lwlock.c:1866
@ LW_SHARED
Definition lwlock.h:105
@ LW_EXCLUSIVE
Definition lwlock.h:104
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
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:406
Size add_size(Size s1, Size s2)
Definition mcxt.c:1733
MemoryContext TopTransactionContext
Definition mcxt.c:172
char * pstrdup(const char *in)
Definition mcxt.c:1910
void pfree(void *pointer)
Definition mcxt.c:1619
MemoryContext TopMemoryContext
Definition mcxt.c:167
Size mul_size(Size s1, Size s2)
Definition mcxt.c:1752
void * palloc(Size size)
Definition mcxt.c:1390
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
MemoryContext PostmasterContext
Definition mcxt.c:169
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1343
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:475
MemoryContext PortalContext
Definition mcxt.c:176
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h:138
@ NormalProcessing
Definition miscadmin.h:481
@ InitProcessing
Definition miscadmin.h:480
#define GetProcessingMode()
Definition miscadmin.h:490
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
#define HOLD_INTERRUPTS()
Definition miscadmin.h:136
#define SetProcessingMode(mode)
Definition miscadmin.h:492
#define INIT_PG_OVERRIDE_ALLOW_CONNS
Definition miscadmin.h:509
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition multixact.c:2865
int MultiXactMemberFreezeThreshold(void)
Definition multixact.c:2590
MultiXactId ReadNextMultiXactId(void)
Definition multixact.c:679
#define MultiXactIdIsValid(multi)
Definition multixact.h:29
#define FirstMultiXactId
Definition multixact.h:26
TempNamespaceStatus checkTempNamespaceStatus(Oid namespaceId)
Definition namespace.c:3801
@ TEMP_NAMESPACE_IDLE
Definition namespace.h:66
static char * errmsg
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
@ DROP_CASCADE
NameData relname
Definition pg_class.h:40
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
#define NAMEDATALEN
const void size_t len
END_CATALOG_STRUCT typedef FormData_pg_database * Form_pg_database
#define lfirst(lc)
Definition pg_list.h:172
#define NIL
Definition pg_list.h:68
#define list_make1(x1)
Definition pg_list.h:244
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
#define lfirst_oid(lc)
Definition pg_list.h:174
static const struct lconv_member_info table[]
_stringlist * dblist
Definition pg_regress.c:99
static rewind_source * source
Definition pg_rewind.c:89
#define die(msg)
bool pgstat_track_counts
Definition pgstat.c:204
void pgstat_report_autovac(Oid dboid)
PgStat_StatDBEntry * pgstat_fetch_stat_dbentry(Oid dboid)
PgStat_StatTabEntry * pgstat_fetch_stat_tabentry_ext(bool shared, Oid reloid, bool *may_free)
void SendPostmasterSignal(PMSignalReason reason)
Definition pmsignal.c:164
@ PMSIGNAL_START_AUTOVAC_WORKER
Definition pmsignal.h:40
#define pqsignal
Definition port.h:548
#define PG_SIG_IGN
Definition port.h:552
#define snprintf
Definition port.h:261
#define qsort(a, b, c, d)
Definition port.h:496
#define PG_SIG_DFL
Definition port.h:551
int PostAuthDelay
Definition postgres.c:105
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3172
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3155
static Datum Int64GetDatum(int64 X)
Definition postgres.h:426
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static Datum Float8GetDatum(float8 X)
Definition postgres.h:515
static Datum CharGetDatum(char X)
Definition postgres.h:132
#define InvalidOid
unsigned int Oid
void BaseInit(void)
Definition postinit.c:622
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, uint32 flags, char *out_dbname)
Definition postinit.c:722
static int fb(int x)
#define GetPGProcByNumber(n)
Definition proc.h:506
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
int ProcNumber
Definition procnumber.h:24
void ProcessProcSignalBarrier(void)
Definition procsignal.c:511
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:696
void init_ps_display(const char *fixed_part)
Definition ps_status.c:286
static void set_ps_display(const char *activity)
Definition ps_status.h:40
tree ctl
Definition radixtree.h:1838
#define RelationGetDescr(relation)
Definition rel.h:542
bytea * extractRelOptions(HeapTuple tuple, TupleDesc tupdesc, amoptions_function amoptions)
void ReleaseAuxProcessResources(bool isCommit)
Definition resowner.c:1026
ResourceOwner AuxProcessResourceOwner
Definition resowner.c:176
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
@ ForwardScanDirection
Definition sdir.h:28
struct @10::@11 av[32]
#define ShmemRequestStruct(...)
Definition shmem.h:176
void pg_usleep(long microsec)
Definition signal.c:53
void ProcessCatchupInterrupt(void)
Definition sinval.c:173
void AtEOXact_SMgr(void)
Definition smgr.c:1017
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
bool ActiveSnapshotSet(void)
Definition snapmgr.c:812
void PopActiveSnapshot(void)
Definition snapmgr.c:775
PGPROC * MyProc
Definition proc.c:71
PROC_HDR * ProcGlobal
Definition proc.c:74
void InitProcess(void)
Definition proc.c:393
#define BTEqualStrategyNumber
Definition stratnum.h:31
char * dbname
Definition streamutil.c:49
dclist_head av_freeWorkers
Definition autovacuum.c:304
WorkerInfo av_startingWorker
Definition autovacuum.c:306
sig_atomic_t av_signal[AutoVacNumSignals]
Definition autovacuum.c:303
AutoVacuumWorkItem av_workItems[NUM_WORKITEMS]
Definition autovacuum.c:307
pg_atomic_uint32 av_nworkersForBalance
Definition autovacuum.c:308
dlist_head av_runningWorkers
Definition autovacuum.c:305
BlockNumber avw_blockNumber
Definition autovacuum.c:279
AutoVacuumWorkItemType avw_type
Definition autovacuum.c:274
Size keysize
Definition hsearch.h:69
Size entrysize
Definition hsearch.h:70
MemoryContext hcxt
Definition hsearch.h:81
Definition pg_list.h:54
Definition proc.h:179
pg_atomic_uint32 avLauncherProc
Definition proc.h:491
TimestampTz last_autovac_time
Definition pgstat.h:378
ShmemRequestCallback request_fn
Definition shmem.h:133
int nworkers
Definition vacuum.h:250
int freeze_table_age
Definition vacuum.h:220
VacOptValue truncate
Definition vacuum.h:235
int freeze_min_age
Definition vacuum.h:219
int log_vacuum_min_duration
Definition vacuum.h:226
uint32 options
Definition vacuum.h:218
bool is_wraparound
Definition vacuum.h:225
int multixact_freeze_min_age
Definition vacuum.h:221
int multixact_freeze_table_age
Definition vacuum.h:223
Oid toast_parent
Definition vacuum.h:236
VacOptValue index_cleanup
Definition vacuum.h:234
int log_analyze_min_duration
Definition vacuum.h:230
double max_eager_freeze_failure_rate
Definition vacuum.h:243
TimestampTz wi_launchtime
Definition autovacuum.c:246
dlist_node wi_links
Definition autovacuum.c:242
PGPROC * wi_proc
Definition autovacuum.c:245
pg_atomic_flag wi_dobalance
Definition autovacuum.c:247
double at_storage_param_vac_cost_delay
Definition autovacuum.c:214
int at_storage_param_vac_cost_limit
Definition autovacuum.c:215
char * at_nspname
Definition autovacuum.c:218
char * at_relname
Definition autovacuum.c:217
char * at_datname
Definition autovacuum.c:219
VacuumParams at_params
Definition autovacuum.c:213
bool ar_hasrelopts
Definition autovacuum.c:204
AutoVacOpts ar_reloptions
Definition autovacuum.c:205
Oid ar_toastrelid
Definition autovacuum.c:202
Oid adl_datid
Definition autovacuum.c:183
dlist_node adl_node
Definition autovacuum.c:186
int adl_score
Definition autovacuum.c:185
TimestampTz adl_next_worker
Definition autovacuum.c:184
PgStat_StatDBEntry * adw_entry
Definition autovacuum.c:196
Oid adw_datid
Definition autovacuum.c:192
TransactionId adw_frozenxid
Definition autovacuum.c:194
char * adw_name
Definition autovacuum.c:193
MultiXactId adw_minmulti
Definition autovacuum.c:195
dlist_node * cur
Definition ilist.h:179
Definition c.h:835
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, ScanKeyData *key)
Definition tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition tableam.h:1061
void disable_all_timeouts(bool keep_indicators)
Definition timeout.c:751
void InitializeTimeouts(void)
Definition timeout.c:470
static TransactionId ReadNextTransactionId(void)
Definition transam.h:375
#define FirstNormalTransactionId
Definition transam.h:34
#define TransactionIdIsNormal(xid)
Definition transam.h:42
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
void FreeTupleDesc(TupleDesc tupdesc)
Definition tupdesc.c:569
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition tupdesc.c:242
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition tuplestore.c:785
#define TimestampTzPlusMilliseconds(tz, ms)
Definition timestamp.h:85
void vacuum(List *relations, const VacuumParams *params, BufferAccessStrategy bstrategy, MemoryContext vac_context, bool isTopLevel)
Definition vacuum.c:494
int vacuum_freeze_min_age
Definition vacuum.c:76
double vacuum_max_eager_freeze_failure_rate
Definition vacuum.c:82
double vacuum_cost_delay
Definition vacuum.c:92
int vacuum_multixact_freeze_table_age
Definition vacuum.c:79
int vacuum_freeze_table_age
Definition vacuum.c:77
int vacuum_multixact_failsafe_age
Definition vacuum.c:81
int vacuum_multixact_freeze_min_age
Definition vacuum.c:78
void vac_update_datfrozenxid(void)
Definition vacuum.c:1614
bool VacuumFailsafeActive
Definition vacuum.c:111
int vacuum_cost_limit
Definition vacuum.c:93
int vacuum_failsafe_age
Definition vacuum.c:80
#define VACOPT_SKIP_LOCKED
Definition vacuum.h:184
#define VACOPT_VACUUM
Definition vacuum.h:179
#define VACOPT_SKIP_DATABASE_STATS
Definition vacuum.h:188
@ VACOPTVALUE_UNSPECIFIED
Definition vacuum.h:201
#define VACOPT_PROCESS_MAIN
Definition vacuum.h:185
#define VACOPT_ANALYZE
Definition vacuum.h:180
static void pgstat_report_wait_end(void)
Definition wait_event.h:83
const char * type
const char * name
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET
#define SIGCHLD
Definition win32_port.h:168
#define SIGHUP
Definition win32_port.h:158
#define SIGPIPE
Definition win32_port.h:163
#define kill(pid, sig)
Definition win32_port.h:507
#define SIGUSR1
Definition win32_port.h:170
#define SIGUSR2
Definition win32_port.h:171
int synchronous_commit
Definition xact.c:89
void StartTransactionCommand(void)
Definition xact.c:3112
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:916
void CommitTransactionCommand(void)
Definition xact.c:3210
void AbortOutOfAnyTransaction(void)
Definition xact.c:4916
void AbortCurrentTransaction(void)
Definition xact.c:3504
@ SYNCHRONOUS_COMMIT_LOCAL_FLUSH
Definition xact.h:72
Datum xid_age(PG_FUNCTION_ARGS)
Definition xid.c:117
Datum mxid_age(PG_FUNCTION_ARGS)
Definition xid.c:133