Line data Source code
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-2025, 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 <signal.h>
66 : #include <sys/time.h>
67 : #include <unistd.h>
68 :
69 : #include "access/heapam.h"
70 : #include "access/htup_details.h"
71 : #include "access/multixact.h"
72 : #include "access/reloptions.h"
73 : #include "access/tableam.h"
74 : #include "access/transam.h"
75 : #include "access/xact.h"
76 : #include "catalog/dependency.h"
77 : #include "catalog/namespace.h"
78 : #include "catalog/pg_database.h"
79 : #include "catalog/pg_namespace.h"
80 : #include "commands/dbcommands.h"
81 : #include "commands/vacuum.h"
82 : #include "common/int.h"
83 : #include "lib/ilist.h"
84 : #include "libpq/pqsignal.h"
85 : #include "miscadmin.h"
86 : #include "nodes/makefuncs.h"
87 : #include "pgstat.h"
88 : #include "postmaster/autovacuum.h"
89 : #include "postmaster/interrupt.h"
90 : #include "postmaster/postmaster.h"
91 : #include "storage/aio_subsys.h"
92 : #include "storage/bufmgr.h"
93 : #include "storage/ipc.h"
94 : #include "storage/latch.h"
95 : #include "storage/lmgr.h"
96 : #include "storage/pmsignal.h"
97 : #include "storage/proc.h"
98 : #include "storage/procsignal.h"
99 : #include "storage/smgr.h"
100 : #include "tcop/tcopprot.h"
101 : #include "utils/fmgroids.h"
102 : #include "utils/fmgrprotos.h"
103 : #include "utils/guc_hooks.h"
104 : #include "utils/injection_point.h"
105 : #include "utils/lsyscache.h"
106 : #include "utils/memutils.h"
107 : #include "utils/ps_status.h"
108 : #include "utils/rel.h"
109 : #include "utils/snapmgr.h"
110 : #include "utils/syscache.h"
111 : #include "utils/timeout.h"
112 : #include "utils/timestamp.h"
113 :
114 :
115 : /*
116 : * GUC parameters
117 : */
118 : bool autovacuum_start_daemon = false;
119 : int autovacuum_worker_slots;
120 : int autovacuum_max_workers;
121 : int autovacuum_work_mem = -1;
122 : int autovacuum_naptime;
123 : int autovacuum_vac_thresh;
124 : int autovacuum_vac_max_thresh;
125 : double autovacuum_vac_scale;
126 : int autovacuum_vac_ins_thresh;
127 : double autovacuum_vac_ins_scale;
128 : int autovacuum_anl_thresh;
129 : double autovacuum_anl_scale;
130 : int autovacuum_freeze_max_age;
131 : int autovacuum_multixact_freeze_max_age;
132 :
133 : double autovacuum_vac_cost_delay;
134 : int autovacuum_vac_cost_limit;
135 :
136 : int Log_autovacuum_min_duration = 600000;
137 :
138 : /* the minimum allowed time between two awakenings of the launcher */
139 : #define MIN_AUTOVAC_SLEEPTIME 100.0 /* milliseconds */
140 : #define MAX_AUTOVAC_SLEEPTIME 300 /* seconds */
141 :
142 : /*
143 : * Variables to save the cost-related storage parameters for the current
144 : * relation being vacuumed by this autovacuum worker. Using these, we can
145 : * ensure we don't overwrite the values of vacuum_cost_delay and
146 : * vacuum_cost_limit after reloading the configuration file. They are
147 : * initialized to "invalid" values to indicate that no cost-related storage
148 : * parameters were specified and will be set in do_autovacuum() after checking
149 : * the storage parameters in table_recheck_autovac().
150 : */
151 : static double av_storage_param_cost_delay = -1;
152 : static int av_storage_param_cost_limit = -1;
153 :
154 : /* Flags set by signal handlers */
155 : static volatile sig_atomic_t got_SIGUSR2 = false;
156 :
157 : /* Comparison points for determining whether freeze_max_age is exceeded */
158 : static TransactionId recentXid;
159 : static MultiXactId recentMulti;
160 :
161 : /* Default freeze ages to use for autovacuum (varies by database) */
162 : static int default_freeze_min_age;
163 : static int default_freeze_table_age;
164 : static int default_multixact_freeze_min_age;
165 : static int default_multixact_freeze_table_age;
166 :
167 : /* Memory context for long-lived data */
168 : static MemoryContext AutovacMemCxt;
169 :
170 : /* struct to keep track of databases in launcher */
171 : typedef struct avl_dbase
172 : {
173 : Oid adl_datid; /* hash key -- must be first */
174 : TimestampTz adl_next_worker;
175 : int adl_score;
176 : dlist_node adl_node;
177 : } avl_dbase;
178 :
179 : /* struct to keep track of databases in worker */
180 : typedef struct avw_dbase
181 : {
182 : Oid adw_datid;
183 : char *adw_name;
184 : TransactionId adw_frozenxid;
185 : MultiXactId adw_minmulti;
186 : PgStat_StatDBEntry *adw_entry;
187 : } avw_dbase;
188 :
189 : /* struct to keep track of tables to vacuum and/or analyze, in 1st pass */
190 : typedef struct av_relation
191 : {
192 : Oid ar_toastrelid; /* hash key - must be first */
193 : Oid ar_relid;
194 : bool ar_hasrelopts;
195 : AutoVacOpts ar_reloptions; /* copy of AutoVacOpts from the main table's
196 : * reloptions, or NULL if none */
197 : } av_relation;
198 :
199 : /* struct to keep track of tables to vacuum and/or analyze, after rechecking */
200 : typedef struct autovac_table
201 : {
202 : Oid at_relid;
203 : VacuumParams at_params;
204 : double at_storage_param_vac_cost_delay;
205 : int at_storage_param_vac_cost_limit;
206 : bool at_dobalance;
207 : bool at_sharedrel;
208 : char *at_relname;
209 : char *at_nspname;
210 : char *at_datname;
211 : } autovac_table;
212 :
213 : /*-------------
214 : * This struct holds information about a single worker's whereabouts. We keep
215 : * an array of these in shared memory, sized according to
216 : * autovacuum_worker_slots.
217 : *
218 : * wi_links entry into free list or running list
219 : * wi_dboid OID of the database this worker is supposed to work on
220 : * wi_tableoid OID of the table currently being vacuumed, if any
221 : * wi_sharedrel flag indicating whether table is marked relisshared
222 : * wi_proc pointer to PGPROC of the running worker, NULL if not started
223 : * wi_launchtime Time at which this worker was launched
224 : * wi_dobalance Whether this worker should be included in balance calculations
225 : *
226 : * All fields are protected by AutovacuumLock, except for wi_tableoid and
227 : * wi_sharedrel which are protected by AutovacuumScheduleLock (note these
228 : * two fields are read-only for everyone except that worker itself).
229 : *-------------
230 : */
231 : typedef struct WorkerInfoData
232 : {
233 : dlist_node wi_links;
234 : Oid wi_dboid;
235 : Oid wi_tableoid;
236 : PGPROC *wi_proc;
237 : TimestampTz wi_launchtime;
238 : pg_atomic_flag wi_dobalance;
239 : bool wi_sharedrel;
240 : } WorkerInfoData;
241 :
242 : typedef struct WorkerInfoData *WorkerInfo;
243 :
244 : /*
245 : * Possible signals received by the launcher from remote processes. These are
246 : * stored atomically in shared memory so that other processes can set them
247 : * without locking.
248 : */
249 : typedef enum
250 : {
251 : AutoVacForkFailed, /* failed trying to start a worker */
252 : AutoVacRebalance, /* rebalance the cost limits */
253 : } AutoVacuumSignal;
254 :
255 : #define AutoVacNumSignals (AutoVacRebalance + 1)
256 :
257 : /*
258 : * Autovacuum workitem array, stored in AutoVacuumShmem->av_workItems. This
259 : * list is mostly protected by AutovacuumLock, except that if an item is
260 : * marked 'active' other processes must not modify the work-identifying
261 : * members.
262 : */
263 : typedef struct AutoVacuumWorkItem
264 : {
265 : AutoVacuumWorkItemType avw_type;
266 : bool avw_used; /* below data is valid */
267 : bool avw_active; /* being processed */
268 : Oid avw_database;
269 : Oid avw_relation;
270 : BlockNumber avw_blockNumber;
271 : } AutoVacuumWorkItem;
272 :
273 : #define NUM_WORKITEMS 256
274 :
275 : /*-------------
276 : * The main autovacuum shmem struct. On shared memory we store this main
277 : * struct and the array of WorkerInfo structs. This struct keeps:
278 : *
279 : * av_signal set by other processes to indicate various conditions
280 : * av_launcherpid the PID of the autovacuum launcher
281 : * av_freeWorkers the WorkerInfo freelist
282 : * av_runningWorkers the WorkerInfo non-free queue
283 : * av_startingWorker pointer to WorkerInfo currently being started (cleared by
284 : * the worker itself as soon as it's up and running)
285 : * av_workItems work item array
286 : * av_nworkersForBalance the number of autovacuum workers to use when
287 : * calculating the per worker cost limit
288 : *
289 : * This struct is protected by AutovacuumLock, except for av_signal and parts
290 : * of the worker list (see above).
291 : *-------------
292 : */
293 : typedef struct
294 : {
295 : sig_atomic_t av_signal[AutoVacNumSignals];
296 : pid_t av_launcherpid;
297 : dclist_head av_freeWorkers;
298 : dlist_head av_runningWorkers;
299 : WorkerInfo av_startingWorker;
300 : AutoVacuumWorkItem av_workItems[NUM_WORKITEMS];
301 : pg_atomic_uint32 av_nworkersForBalance;
302 : } AutoVacuumShmemStruct;
303 :
304 : static AutoVacuumShmemStruct *AutoVacuumShmem;
305 :
306 : /*
307 : * the database list (of avl_dbase elements) in the launcher, and the context
308 : * that contains it
309 : */
310 : static dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList);
311 : static MemoryContext DatabaseListCxt = NULL;
312 :
313 : /* Pointer to my own WorkerInfo, valid on each worker */
314 : static WorkerInfo MyWorkerInfo = NULL;
315 :
316 : /* PID of launcher, valid only in worker while shutting down */
317 : int AutovacuumLauncherPid = 0;
318 :
319 : static Oid do_start_worker(void);
320 : static void ProcessAutoVacLauncherInterrupts(void);
321 : pg_noreturn static void AutoVacLauncherShutdown(void);
322 : static void launcher_determine_sleep(bool canlaunch, bool recursing,
323 : struct timeval *nap);
324 : static void launch_worker(TimestampTz now);
325 : static List *get_database_list(void);
326 : static void rebuild_database_list(Oid newdb);
327 : static int db_comparator(const void *a, const void *b);
328 : static void autovac_recalculate_workers_for_balance(void);
329 :
330 : static void do_autovacuum(void);
331 : static void FreeWorkerInfo(int code, Datum arg);
332 :
333 : static autovac_table *table_recheck_autovac(Oid relid, HTAB *table_toast_map,
334 : TupleDesc pg_class_desc,
335 : int effective_multixact_freeze_max_age);
336 : static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts,
337 : Form_pg_class classForm,
338 : int effective_multixact_freeze_max_age,
339 : bool *dovacuum, bool *doanalyze, bool *wraparound);
340 : static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts,
341 : Form_pg_class classForm,
342 : PgStat_StatTabEntry *tabentry,
343 : int effective_multixact_freeze_max_age,
344 : bool *dovacuum, bool *doanalyze, bool *wraparound);
345 :
346 : static void autovacuum_do_vac_analyze(autovac_table *tab,
347 : BufferAccessStrategy bstrategy);
348 : static AutoVacOpts *extract_autovac_opts(HeapTuple tup,
349 : TupleDesc pg_class_desc);
350 : static void perform_work_item(AutoVacuumWorkItem *workitem);
351 : static void autovac_report_activity(autovac_table *tab);
352 : static void autovac_report_workitem(AutoVacuumWorkItem *workitem,
353 : const char *nspname, const char *relname);
354 : static void avl_sigusr2_handler(SIGNAL_ARGS);
355 : static bool av_worker_available(void);
356 : static void check_av_worker_gucs(void);
357 :
358 :
359 :
360 : /********************************************************************
361 : * AUTOVACUUM LAUNCHER CODE
362 : ********************************************************************/
363 :
364 : /*
365 : * Main entry point for the autovacuum launcher process.
366 : */
367 : void
368 730 : AutoVacLauncherMain(const void *startup_data, size_t startup_data_len)
369 : {
370 : sigjmp_buf local_sigjmp_buf;
371 :
372 : Assert(startup_data_len == 0);
373 :
374 : /* Release postmaster's working memory context */
375 730 : if (PostmasterContext)
376 : {
377 730 : MemoryContextDelete(PostmasterContext);
378 730 : PostmasterContext = NULL;
379 : }
380 :
381 730 : MyBackendType = B_AUTOVAC_LAUNCHER;
382 730 : init_ps_display(NULL);
383 :
384 730 : ereport(DEBUG1,
385 : (errmsg_internal("autovacuum launcher started")));
386 :
387 730 : if (PostAuthDelay)
388 0 : pg_usleep(PostAuthDelay * 1000000L);
389 :
390 : Assert(GetProcessingMode() == InitProcessing);
391 :
392 : /*
393 : * Set up signal handlers. We operate on databases much like a regular
394 : * backend, so we use the same signal handling. See equivalent code in
395 : * tcop/postgres.c.
396 : */
397 730 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
398 730 : pqsignal(SIGINT, StatementCancelHandler);
399 730 : pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
400 : /* SIGQUIT handler was already set up by InitPostmasterChild */
401 :
402 730 : InitializeTimeouts(); /* establishes SIGALRM handler */
403 :
404 730 : pqsignal(SIGPIPE, SIG_IGN);
405 730 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
406 730 : pqsignal(SIGUSR2, avl_sigusr2_handler);
407 730 : pqsignal(SIGFPE, FloatExceptionHandler);
408 730 : pqsignal(SIGCHLD, SIG_DFL);
409 :
410 : /*
411 : * Create a per-backend PGPROC struct in shared memory. We must do this
412 : * before we can use LWLocks or access any shared memory.
413 : */
414 730 : InitProcess();
415 :
416 : /* Early initialization */
417 730 : BaseInit();
418 :
419 730 : InitPostgres(NULL, InvalidOid, NULL, InvalidOid, 0, NULL);
420 :
421 730 : SetProcessingMode(NormalProcessing);
422 :
423 : /*
424 : * Create a memory context that we will do all our work in. We do this so
425 : * that we can reset the context during error recovery and thereby avoid
426 : * possible memory leaks.
427 : */
428 730 : AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
429 : "Autovacuum Launcher",
430 : ALLOCSET_DEFAULT_SIZES);
431 730 : MemoryContextSwitchTo(AutovacMemCxt);
432 :
433 : /*
434 : * If an exception is encountered, processing resumes here.
435 : *
436 : * This code is a stripped down version of PostgresMain error recovery.
437 : *
438 : * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
439 : * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
440 : * signals other than SIGQUIT will be blocked until we complete error
441 : * recovery. It might seem that this policy makes the HOLD_INTERRUPTS()
442 : * call redundant, but it is not since InterruptPending might be set
443 : * already.
444 : */
445 730 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
446 : {
447 : /* since not using PG_TRY, must reset error stack by hand */
448 0 : error_context_stack = NULL;
449 :
450 : /* Prevents interrupts while cleaning up */
451 0 : HOLD_INTERRUPTS();
452 :
453 : /* Forget any pending QueryCancel or timeout request */
454 0 : disable_all_timeouts(false);
455 0 : QueryCancelPending = false; /* second to avoid race condition */
456 :
457 : /* Report the error to the server log */
458 0 : EmitErrorReport();
459 :
460 : /* Abort the current transaction in order to recover */
461 0 : AbortCurrentTransaction();
462 :
463 : /*
464 : * Release any other resources, for the case where we were not in a
465 : * transaction.
466 : */
467 0 : LWLockReleaseAll();
468 0 : pgstat_report_wait_end();
469 0 : pgaio_error_cleanup();
470 0 : UnlockBuffers();
471 : /* this is probably dead code, but let's be safe: */
472 0 : if (AuxProcessResourceOwner)
473 0 : ReleaseAuxProcessResources(false);
474 0 : AtEOXact_Buffers(false);
475 0 : AtEOXact_SMgr();
476 0 : AtEOXact_Files(false);
477 0 : AtEOXact_HashTables(false);
478 :
479 : /*
480 : * Now return to normal top-level context and clear ErrorContext for
481 : * next time.
482 : */
483 0 : MemoryContextSwitchTo(AutovacMemCxt);
484 0 : FlushErrorState();
485 :
486 : /* Flush any leaked data in the top-level context */
487 0 : MemoryContextReset(AutovacMemCxt);
488 :
489 : /* don't leave dangling pointers to freed memory */
490 0 : DatabaseListCxt = NULL;
491 0 : dlist_init(&DatabaseList);
492 :
493 : /* Now we can allow interrupts again */
494 0 : RESUME_INTERRUPTS();
495 :
496 : /* if in shutdown mode, no need for anything further; just go away */
497 0 : if (ShutdownRequestPending)
498 0 : AutoVacLauncherShutdown();
499 :
500 : /*
501 : * Sleep at least 1 second after any error. We don't want to be
502 : * filling the error logs as fast as we can.
503 : */
504 0 : pg_usleep(1000000L);
505 : }
506 :
507 : /* We can now handle ereport(ERROR) */
508 730 : PG_exception_stack = &local_sigjmp_buf;
509 :
510 : /* must unblock signals before calling rebuild_database_list */
511 730 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
512 :
513 : /*
514 : * Set always-secure search path. Launcher doesn't connect to a database,
515 : * so this has no effect.
516 : */
517 730 : SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
518 :
519 : /*
520 : * Force zero_damaged_pages OFF in the autovac process, even if it is set
521 : * in postgresql.conf. We don't really want such a dangerous option being
522 : * applied non-interactively.
523 : */
524 730 : SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
525 :
526 : /*
527 : * Force settable timeouts off to avoid letting these settings prevent
528 : * regular maintenance from being executed.
529 : */
530 730 : SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
531 730 : SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
532 730 : SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
533 730 : SetConfigOption("idle_in_transaction_session_timeout", "0",
534 : PGC_SUSET, PGC_S_OVERRIDE);
535 :
536 : /*
537 : * Force default_transaction_isolation to READ COMMITTED. We don't want
538 : * to pay the overhead of serializable mode, nor add any risk of causing
539 : * deadlocks or delaying other transactions.
540 : */
541 730 : SetConfigOption("default_transaction_isolation", "read committed",
542 : PGC_SUSET, PGC_S_OVERRIDE);
543 :
544 : /*
545 : * Even when system is configured to use a different fetch consistency,
546 : * for autovac we always want fresh stats.
547 : */
548 730 : SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
549 :
550 : /*
551 : * In emergency mode, just start a worker (unless shutdown was requested)
552 : * and go away.
553 : */
554 730 : if (!AutoVacuumingActive())
555 : {
556 0 : if (!ShutdownRequestPending)
557 0 : do_start_worker();
558 0 : proc_exit(0); /* done */
559 : }
560 :
561 730 : AutoVacuumShmem->av_launcherpid = MyProcPid;
562 :
563 : /*
564 : * Create the initial database list. The invariant we want this list to
565 : * keep is that it's ordered by decreasing next_time. As soon as an entry
566 : * is updated to a higher time, it will be moved to the front (which is
567 : * correct because the only operation is to add autovacuum_naptime to the
568 : * entry, and time always increases).
569 : */
570 730 : rebuild_database_list(InvalidOid);
571 :
572 : /* loop until shutdown request */
573 9904 : while (!ShutdownRequestPending)
574 : {
575 : struct timeval nap;
576 9902 : TimestampTz current_time = 0;
577 : bool can_launch;
578 :
579 : /*
580 : * This loop is a bit different from the normal use of WaitLatch,
581 : * because we'd like to sleep before the first launch of a child
582 : * process. So it's WaitLatch, then ResetLatch, then check for
583 : * wakening conditions.
584 : */
585 :
586 9902 : launcher_determine_sleep(av_worker_available(), false, &nap);
587 :
588 : /*
589 : * Wait until naptime expires or we get some type of signal (all the
590 : * signal handlers will wake us by calling SetLatch).
591 : */
592 9902 : (void) WaitLatch(MyLatch,
593 : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
594 9902 : (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
595 : WAIT_EVENT_AUTOVACUUM_MAIN);
596 :
597 9898 : ResetLatch(MyLatch);
598 :
599 9898 : ProcessAutoVacLauncherInterrupts();
600 :
601 : /*
602 : * a worker finished, or postmaster signaled failure to start a worker
603 : */
604 9174 : if (got_SIGUSR2)
605 : {
606 4712 : got_SIGUSR2 = false;
607 :
608 : /* rebalance cost limits, if needed */
609 4712 : if (AutoVacuumShmem->av_signal[AutoVacRebalance])
610 : {
611 2356 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
612 2356 : AutoVacuumShmem->av_signal[AutoVacRebalance] = false;
613 2356 : autovac_recalculate_workers_for_balance();
614 2356 : LWLockRelease(AutovacuumLock);
615 : }
616 :
617 4712 : if (AutoVacuumShmem->av_signal[AutoVacForkFailed])
618 : {
619 : /*
620 : * If the postmaster failed to start a new worker, we sleep
621 : * for a little while and resend the signal. The new worker's
622 : * state is still in memory, so this is sufficient. After
623 : * that, we restart the main loop.
624 : *
625 : * XXX should we put a limit to the number of times we retry?
626 : * I don't think it makes much sense, because a future start
627 : * of a worker will continue to fail in the same way.
628 : */
629 0 : AutoVacuumShmem->av_signal[AutoVacForkFailed] = false;
630 0 : pg_usleep(1000000L); /* 1s */
631 0 : SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
632 2070 : continue;
633 : }
634 : }
635 :
636 : /*
637 : * There are some conditions that we need to check before trying to
638 : * start a worker. First, we need to make sure that there is a worker
639 : * slot available. Second, we need to make sure that no other worker
640 : * failed while starting up.
641 : */
642 :
643 9174 : current_time = GetCurrentTimestamp();
644 9174 : LWLockAcquire(AutovacuumLock, LW_SHARED);
645 :
646 9174 : can_launch = av_worker_available();
647 :
648 9174 : if (AutoVacuumShmem->av_startingWorker != NULL)
649 : {
650 : int waittime;
651 36 : WorkerInfo worker = AutoVacuumShmem->av_startingWorker;
652 :
653 : /*
654 : * We can't launch another worker when another one is still
655 : * starting up (or failed while doing so), so just sleep for a bit
656 : * more; that worker will wake us up again as soon as it's ready.
657 : * We will only wait autovacuum_naptime seconds (up to a maximum
658 : * of 60 seconds) for this to happen however. Note that failure
659 : * to connect to a particular database is not a problem here,
660 : * because the worker removes itself from the startingWorker
661 : * pointer before trying to connect. Problems detected by the
662 : * postmaster (like fork() failure) are also reported and handled
663 : * differently. The only problems that may cause this code to
664 : * fire are errors in the earlier sections of AutoVacWorkerMain,
665 : * before the worker removes the WorkerInfo from the
666 : * startingWorker pointer.
667 : */
668 36 : waittime = Min(autovacuum_naptime, 60) * 1000;
669 36 : if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
670 : waittime))
671 : {
672 0 : LWLockRelease(AutovacuumLock);
673 0 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
674 :
675 : /*
676 : * No other process can put a worker in starting mode, so if
677 : * startingWorker is still INVALID after exchanging our lock,
678 : * we assume it's the same one we saw above (so we don't
679 : * recheck the launch time).
680 : */
681 0 : if (AutoVacuumShmem->av_startingWorker != NULL)
682 : {
683 0 : worker = AutoVacuumShmem->av_startingWorker;
684 0 : worker->wi_dboid = InvalidOid;
685 0 : worker->wi_tableoid = InvalidOid;
686 0 : worker->wi_sharedrel = false;
687 0 : worker->wi_proc = NULL;
688 0 : worker->wi_launchtime = 0;
689 0 : dclist_push_head(&AutoVacuumShmem->av_freeWorkers,
690 : &worker->wi_links);
691 0 : AutoVacuumShmem->av_startingWorker = NULL;
692 0 : ereport(WARNING,
693 : errmsg("autovacuum worker took too long to start; canceled"));
694 : }
695 : }
696 : else
697 36 : can_launch = false;
698 : }
699 9174 : LWLockRelease(AutovacuumLock); /* either shared or exclusive */
700 :
701 : /* if we can't do anything, just go back to sleep */
702 9174 : if (!can_launch)
703 2070 : continue;
704 :
705 : /* We're OK to start a new worker */
706 :
707 7104 : if (dlist_is_empty(&DatabaseList))
708 : {
709 : /*
710 : * Special case when the list is empty: start a worker right away.
711 : * This covers the initial case, when no database is in pgstats
712 : * (thus the list is empty). Note that the constraints in
713 : * launcher_determine_sleep keep us from starting workers too
714 : * quickly (at most once every autovacuum_naptime when the list is
715 : * empty).
716 : */
717 0 : launch_worker(current_time);
718 : }
719 : else
720 : {
721 : /*
722 : * because rebuild_database_list constructs a list with most
723 : * distant adl_next_worker first, we obtain our database from the
724 : * tail of the list.
725 : */
726 : avl_dbase *avdb;
727 :
728 7104 : avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
729 :
730 : /*
731 : * launch a worker if next_worker is right now or it is in the
732 : * past
733 : */
734 7104 : if (TimestampDifferenceExceeds(avdb->adl_next_worker,
735 : current_time, 0))
736 2356 : launch_worker(current_time);
737 : }
738 : }
739 :
740 2 : AutoVacLauncherShutdown();
741 : }
742 :
743 : /*
744 : * Process any new interrupts.
745 : */
746 : static void
747 9898 : ProcessAutoVacLauncherInterrupts(void)
748 : {
749 : /* the normal shutdown case */
750 9898 : if (ShutdownRequestPending)
751 724 : AutoVacLauncherShutdown();
752 :
753 9174 : if (ConfigReloadPending)
754 : {
755 60 : int autovacuum_max_workers_prev = autovacuum_max_workers;
756 :
757 60 : ConfigReloadPending = false;
758 60 : ProcessConfigFile(PGC_SIGHUP);
759 :
760 : /* shutdown requested in config file? */
761 60 : if (!AutoVacuumingActive())
762 0 : AutoVacLauncherShutdown();
763 :
764 : /*
765 : * If autovacuum_max_workers changed, emit a WARNING if
766 : * autovacuum_worker_slots < autovacuum_max_workers. If it didn't
767 : * change, skip this to avoid too many repeated log messages.
768 : */
769 60 : if (autovacuum_max_workers_prev != autovacuum_max_workers)
770 0 : check_av_worker_gucs();
771 :
772 : /* rebuild the list in case the naptime changed */
773 60 : rebuild_database_list(InvalidOid);
774 : }
775 :
776 : /* Process barrier events */
777 9174 : if (ProcSignalBarrierPending)
778 52 : ProcessProcSignalBarrier();
779 :
780 : /* Perform logging of memory contexts of this process */
781 9174 : if (LogMemoryContextPending)
782 0 : ProcessLogMemoryContextInterrupt();
783 :
784 : /* Process sinval catchup interrupts that happened while sleeping */
785 9174 : ProcessCatchupInterrupt();
786 9174 : }
787 :
788 : /*
789 : * Perform a normal exit from the autovac launcher.
790 : */
791 : static void
792 726 : AutoVacLauncherShutdown(void)
793 : {
794 726 : ereport(DEBUG1,
795 : (errmsg_internal("autovacuum launcher shutting down")));
796 726 : AutoVacuumShmem->av_launcherpid = 0;
797 :
798 726 : proc_exit(0); /* done */
799 : }
800 :
801 : /*
802 : * Determine the time to sleep, based on the database list.
803 : *
804 : * The "canlaunch" parameter indicates whether we can start a worker right now,
805 : * for example due to the workers being all busy. If this is false, we will
806 : * cause a long sleep, which will be interrupted when a worker exits.
807 : */
808 : static void
809 10056 : launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
810 : {
811 : /*
812 : * We sleep until the next scheduled vacuum. We trust that when the
813 : * database list was built, care was taken so that no entries have times
814 : * in the past; if the first entry has too close a next_worker value, or a
815 : * time in the past, we will sleep a small nominal time.
816 : */
817 10056 : if (!canlaunch)
818 : {
819 4028 : nap->tv_sec = autovacuum_naptime;
820 4028 : nap->tv_usec = 0;
821 : }
822 6028 : else if (!dlist_is_empty(&DatabaseList))
823 : {
824 5978 : TimestampTz current_time = GetCurrentTimestamp();
825 : TimestampTz next_wakeup;
826 : avl_dbase *avdb;
827 : long secs;
828 : int usecs;
829 :
830 5978 : avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
831 :
832 5978 : next_wakeup = avdb->adl_next_worker;
833 5978 : TimestampDifference(current_time, next_wakeup, &secs, &usecs);
834 :
835 5978 : nap->tv_sec = secs;
836 5978 : nap->tv_usec = usecs;
837 : }
838 : else
839 : {
840 : /* list is empty, sleep for whole autovacuum_naptime seconds */
841 50 : nap->tv_sec = autovacuum_naptime;
842 50 : nap->tv_usec = 0;
843 : }
844 :
845 : /*
846 : * If the result is exactly zero, it means a database had an entry with
847 : * time in the past. Rebuild the list so that the databases are evenly
848 : * distributed again, and recalculate the time to sleep. This can happen
849 : * if there are more tables needing vacuum than workers, and they all take
850 : * longer to vacuum than autovacuum_naptime.
851 : *
852 : * We only recurse once. rebuild_database_list should always return times
853 : * in the future, but it seems best not to trust too much on that.
854 : */
855 10056 : if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
856 : {
857 154 : rebuild_database_list(InvalidOid);
858 154 : launcher_determine_sleep(canlaunch, true, nap);
859 154 : return;
860 : }
861 :
862 : /* The smallest time we'll allow the launcher to sleep. */
863 9902 : if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
864 : {
865 1086 : nap->tv_sec = 0;
866 1086 : nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000;
867 : }
868 :
869 : /*
870 : * If the sleep time is too large, clamp it to an arbitrary maximum (plus
871 : * any fractional seconds, for simplicity). This avoids an essentially
872 : * infinite sleep in strange cases like the system clock going backwards a
873 : * few years.
874 : */
875 9902 : if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME)
876 18 : nap->tv_sec = MAX_AUTOVAC_SLEEPTIME;
877 : }
878 :
879 : /*
880 : * Build an updated DatabaseList. It must only contain databases that appear
881 : * in pgstats, and must be sorted by next_worker from highest to lowest,
882 : * distributed regularly across the next autovacuum_naptime interval.
883 : *
884 : * Receives the Oid of the database that made this list be generated (we call
885 : * this the "new" database, because when the database was already present on
886 : * the list, we expect that this function is not called at all). The
887 : * preexisting list, if any, will be used to preserve the order of the
888 : * databases in the autovacuum_naptime period. The new database is put at the
889 : * end of the interval. The actual values are not saved, which should not be
890 : * much of a problem.
891 : */
892 : static void
893 972 : rebuild_database_list(Oid newdb)
894 : {
895 : List *dblist;
896 : ListCell *cell;
897 : MemoryContext newcxt;
898 : MemoryContext oldcxt;
899 : MemoryContext tmpcxt;
900 : HASHCTL hctl;
901 : int score;
902 : int nelems;
903 : HTAB *dbhash;
904 : dlist_iter iter;
905 :
906 972 : newcxt = AllocSetContextCreate(AutovacMemCxt,
907 : "Autovacuum database list",
908 : ALLOCSET_DEFAULT_SIZES);
909 972 : tmpcxt = AllocSetContextCreate(newcxt,
910 : "Autovacuum database list (tmp)",
911 : ALLOCSET_DEFAULT_SIZES);
912 972 : oldcxt = MemoryContextSwitchTo(tmpcxt);
913 :
914 : /*
915 : * Implementing this is not as simple as it sounds, because we need to put
916 : * the new database at the end of the list; next the databases that were
917 : * already on the list, and finally (at the tail of the list) all the
918 : * other databases that are not on the existing list.
919 : *
920 : * To do this, we build an empty hash table of scored databases. We will
921 : * start with the lowest score (zero) for the new database, then
922 : * increasing scores for the databases in the existing list, in order, and
923 : * lastly increasing scores for all databases gotten via
924 : * get_database_list() that are not already on the hash.
925 : *
926 : * Then we will put all the hash elements into an array, sort the array by
927 : * score, and finally put the array elements into the new doubly linked
928 : * list.
929 : */
930 972 : hctl.keysize = sizeof(Oid);
931 972 : hctl.entrysize = sizeof(avl_dbase);
932 972 : hctl.hcxt = tmpcxt;
933 972 : dbhash = hash_create("autovacuum db hash", 20, &hctl, /* magic number here
934 : * FIXME */
935 : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
936 :
937 : /* start by inserting the new database */
938 972 : score = 0;
939 972 : if (OidIsValid(newdb))
940 : {
941 : avl_dbase *db;
942 : PgStat_StatDBEntry *entry;
943 :
944 : /* only consider this database if it has a pgstat entry */
945 28 : entry = pgstat_fetch_stat_dbentry(newdb);
946 28 : if (entry != NULL)
947 : {
948 : /* we assume it isn't found because the hash was just created */
949 22 : db = hash_search(dbhash, &newdb, HASH_ENTER, NULL);
950 :
951 : /* hash_search already filled in the key */
952 22 : db->adl_score = score++;
953 : /* next_worker is filled in later */
954 : }
955 : }
956 :
957 : /* Now insert the databases from the existing list */
958 1558 : dlist_foreach(iter, &DatabaseList)
959 : {
960 586 : avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
961 : avl_dbase *db;
962 : bool found;
963 : PgStat_StatDBEntry *entry;
964 :
965 : /*
966 : * skip databases with no stat entries -- in particular, this gets rid
967 : * of dropped databases
968 : */
969 586 : entry = pgstat_fetch_stat_dbentry(avdb->adl_datid);
970 586 : if (entry == NULL)
971 0 : continue;
972 :
973 586 : db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found);
974 :
975 586 : if (!found)
976 : {
977 : /* hash_search already filled in the key */
978 586 : db->adl_score = score++;
979 : /* next_worker is filled in later */
980 : }
981 : }
982 :
983 : /* finally, insert all qualifying databases not previously inserted */
984 972 : dblist = get_database_list();
985 4200 : foreach(cell, dblist)
986 : {
987 3228 : avw_dbase *avdb = lfirst(cell);
988 : avl_dbase *db;
989 : bool found;
990 : PgStat_StatDBEntry *entry;
991 :
992 : /* only consider databases with a pgstat entry */
993 3228 : entry = pgstat_fetch_stat_dbentry(avdb->adw_datid);
994 3228 : if (entry == NULL)
995 1618 : continue;
996 :
997 1610 : db = hash_search(dbhash, &(avdb->adw_datid), HASH_ENTER, &found);
998 : /* only update the score if the database was not already on the hash */
999 1610 : if (!found)
1000 : {
1001 : /* hash_search already filled in the key */
1002 1002 : db->adl_score = score++;
1003 : /* next_worker is filled in later */
1004 : }
1005 : }
1006 972 : nelems = score;
1007 :
1008 : /* from here on, the allocated memory belongs to the new list */
1009 972 : MemoryContextSwitchTo(newcxt);
1010 972 : dlist_init(&DatabaseList);
1011 :
1012 972 : if (nelems > 0)
1013 : {
1014 : TimestampTz current_time;
1015 : int millis_increment;
1016 : avl_dbase *dbary;
1017 : avl_dbase *db;
1018 : HASH_SEQ_STATUS seq;
1019 : int i;
1020 :
1021 : /* put all the hash elements into an array */
1022 922 : dbary = palloc(nelems * sizeof(avl_dbase));
1023 :
1024 922 : i = 0;
1025 922 : hash_seq_init(&seq, dbhash);
1026 2532 : while ((db = hash_seq_search(&seq)) != NULL)
1027 1610 : memcpy(&(dbary[i++]), db, sizeof(avl_dbase));
1028 :
1029 : /* sort the array */
1030 922 : qsort(dbary, nelems, sizeof(avl_dbase), db_comparator);
1031 :
1032 : /*
1033 : * Determine the time interval between databases in the schedule. If
1034 : * we see that the configured naptime would take us to sleep times
1035 : * lower than our min sleep time (which launcher_determine_sleep is
1036 : * coded not to allow), silently use a larger naptime (but don't touch
1037 : * the GUC variable).
1038 : */
1039 922 : millis_increment = 1000.0 * autovacuum_naptime / nelems;
1040 922 : if (millis_increment <= MIN_AUTOVAC_SLEEPTIME)
1041 0 : millis_increment = MIN_AUTOVAC_SLEEPTIME * 1.1;
1042 :
1043 922 : current_time = GetCurrentTimestamp();
1044 :
1045 : /*
1046 : * move the elements from the array into the dlist, setting the
1047 : * next_worker while walking the array
1048 : */
1049 2532 : for (i = 0; i < nelems; i++)
1050 : {
1051 1610 : db = &(dbary[i]);
1052 :
1053 1610 : current_time = TimestampTzPlusMilliseconds(current_time,
1054 : millis_increment);
1055 1610 : db->adl_next_worker = current_time;
1056 :
1057 : /* later elements should go closer to the head of the list */
1058 1610 : dlist_push_head(&DatabaseList, &db->adl_node);
1059 : }
1060 : }
1061 :
1062 : /* all done, clean up memory */
1063 972 : if (DatabaseListCxt != NULL)
1064 242 : MemoryContextDelete(DatabaseListCxt);
1065 972 : MemoryContextDelete(tmpcxt);
1066 972 : DatabaseListCxt = newcxt;
1067 972 : MemoryContextSwitchTo(oldcxt);
1068 972 : }
1069 :
1070 : /* qsort comparator for avl_dbase, using adl_score */
1071 : static int
1072 1000 : db_comparator(const void *a, const void *b)
1073 : {
1074 1000 : return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1075 : ((const avl_dbase *) b)->adl_score);
1076 : }
1077 :
1078 : /*
1079 : * do_start_worker
1080 : *
1081 : * Bare-bones procedure for starting an autovacuum worker from the launcher.
1082 : * It determines what database to work on, sets up shared memory stuff and
1083 : * signals postmaster to start the worker. It fails gracefully if invoked when
1084 : * autovacuum_workers are already active.
1085 : *
1086 : * Return value is the OID of the database that the worker is going to process,
1087 : * or InvalidOid if no worker was actually started.
1088 : */
1089 : static Oid
1090 2356 : do_start_worker(void)
1091 : {
1092 : List *dblist;
1093 : ListCell *cell;
1094 : TransactionId xidForceLimit;
1095 : MultiXactId multiForceLimit;
1096 : bool for_xid_wrap;
1097 : bool for_multi_wrap;
1098 : avw_dbase *avdb;
1099 : TimestampTz current_time;
1100 2356 : bool skipit = false;
1101 2356 : Oid retval = InvalidOid;
1102 : MemoryContext tmpcxt,
1103 : oldcxt;
1104 :
1105 : /* return quickly when there are no free workers */
1106 2356 : LWLockAcquire(AutovacuumLock, LW_SHARED);
1107 2356 : if (!av_worker_available())
1108 : {
1109 0 : LWLockRelease(AutovacuumLock);
1110 0 : return InvalidOid;
1111 : }
1112 2356 : LWLockRelease(AutovacuumLock);
1113 :
1114 : /*
1115 : * Create and switch to a temporary context to avoid leaking the memory
1116 : * allocated for the database list.
1117 : */
1118 2356 : tmpcxt = AllocSetContextCreate(CurrentMemoryContext,
1119 : "Autovacuum start worker (tmp)",
1120 : ALLOCSET_DEFAULT_SIZES);
1121 2356 : oldcxt = MemoryContextSwitchTo(tmpcxt);
1122 :
1123 : /* Get a list of databases */
1124 2356 : dblist = get_database_list();
1125 :
1126 : /*
1127 : * Determine the oldest datfrozenxid/relfrozenxid that we will allow to
1128 : * pass without forcing a vacuum. (This limit can be tightened for
1129 : * particular tables, but not loosened.)
1130 : */
1131 2356 : recentXid = ReadNextTransactionId();
1132 2356 : xidForceLimit = recentXid - autovacuum_freeze_max_age;
1133 : /* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
1134 : /* this can cause the limit to go backwards by 3, but that's OK */
1135 2356 : if (xidForceLimit < FirstNormalTransactionId)
1136 0 : xidForceLimit -= FirstNormalTransactionId;
1137 :
1138 : /* Also determine the oldest datminmxid we will consider. */
1139 2356 : recentMulti = ReadNextMultiXactId();
1140 2356 : multiForceLimit = recentMulti - MultiXactMemberFreezeThreshold();
1141 2356 : if (multiForceLimit < FirstMultiXactId)
1142 0 : multiForceLimit -= FirstMultiXactId;
1143 :
1144 : /*
1145 : * Choose a database to connect to. We pick the database that was least
1146 : * recently auto-vacuumed, or one that needs vacuuming to prevent Xid
1147 : * wraparound-related data loss. If any db at risk of Xid wraparound is
1148 : * found, we pick the one with oldest datfrozenxid, independently of
1149 : * autovacuum times; similarly we pick the one with the oldest datminmxid
1150 : * if any is in MultiXactId wraparound. Note that those in Xid wraparound
1151 : * danger are given more priority than those in multi wraparound danger.
1152 : *
1153 : * Note that a database with no stats entry is not considered, except for
1154 : * Xid wraparound purposes. The theory is that if no one has ever
1155 : * connected to it since the stats were last initialized, it doesn't need
1156 : * vacuuming.
1157 : *
1158 : * XXX This could be improved if we had more info about whether it needs
1159 : * vacuuming before connecting to it. Perhaps look through the pgstats
1160 : * data for the database's tables? One idea is to keep track of the
1161 : * number of new and dead tuples per database in pgstats. However it
1162 : * isn't clear how to construct a metric that measures that and not cause
1163 : * starvation for less busy databases.
1164 : */
1165 2356 : avdb = NULL;
1166 2356 : for_xid_wrap = false;
1167 2356 : for_multi_wrap = false;
1168 2356 : current_time = GetCurrentTimestamp();
1169 9482 : foreach(cell, dblist)
1170 : {
1171 7126 : avw_dbase *tmp = lfirst(cell);
1172 : dlist_iter iter;
1173 :
1174 : /* Check to see if this one is at risk of wraparound */
1175 7126 : if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit))
1176 : {
1177 3574 : if (avdb == NULL ||
1178 1372 : TransactionIdPrecedes(tmp->adw_frozenxid,
1179 : avdb->adw_frozenxid))
1180 920 : avdb = tmp;
1181 2202 : for_xid_wrap = true;
1182 5384 : continue;
1183 : }
1184 4924 : else if (for_xid_wrap)
1185 86 : continue; /* ignore not-at-risk DBs */
1186 4838 : else if (MultiXactIdPrecedes(tmp->adw_minmulti, multiForceLimit))
1187 : {
1188 0 : if (avdb == NULL ||
1189 0 : MultiXactIdPrecedes(tmp->adw_minmulti, avdb->adw_minmulti))
1190 0 : avdb = tmp;
1191 0 : for_multi_wrap = true;
1192 0 : continue;
1193 : }
1194 4838 : else if (for_multi_wrap)
1195 0 : continue; /* ignore not-at-risk DBs */
1196 :
1197 : /* Find pgstat entry if any */
1198 4838 : tmp->adw_entry = pgstat_fetch_stat_dbentry(tmp->adw_datid);
1199 :
1200 : /*
1201 : * Skip a database with no pgstat entry; it means it hasn't seen any
1202 : * activity.
1203 : */
1204 4838 : if (!tmp->adw_entry)
1205 46 : continue;
1206 :
1207 : /*
1208 : * Also, skip a database that appears on the database list as having
1209 : * been processed recently (less than autovacuum_naptime seconds ago).
1210 : * We do this so that we don't select a database which we just
1211 : * selected, but that pgstat hasn't gotten around to updating the last
1212 : * autovacuum time yet.
1213 : */
1214 4792 : skipit = false;
1215 :
1216 9756 : dlist_reverse_foreach(iter, &DatabaseList)
1217 : {
1218 9712 : avl_dbase *dbp = dlist_container(avl_dbase, adl_node, iter.cur);
1219 :
1220 9712 : if (dbp->adl_datid == tmp->adw_datid)
1221 : {
1222 : /*
1223 : * Skip this database if its next_worker value falls between
1224 : * the current time and the current time plus naptime.
1225 : */
1226 4748 : if (!TimestampDifferenceExceeds(dbp->adl_next_worker,
1227 3050 : current_time, 0) &&
1228 3050 : !TimestampDifferenceExceeds(current_time,
1229 : dbp->adl_next_worker,
1230 : autovacuum_naptime * 1000))
1231 3050 : skipit = true;
1232 :
1233 4748 : break;
1234 : }
1235 : }
1236 4792 : if (skipit)
1237 3050 : continue;
1238 :
1239 : /*
1240 : * Remember the db with oldest autovac time. (If we are here, both
1241 : * tmp->entry and db->entry must be non-null.)
1242 : */
1243 1742 : if (avdb == NULL ||
1244 216 : tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time)
1245 1568 : avdb = tmp;
1246 : }
1247 :
1248 : /* Found a database -- process it */
1249 2356 : if (avdb != NULL)
1250 : {
1251 : WorkerInfo worker;
1252 : dlist_node *wptr;
1253 :
1254 2356 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1255 :
1256 : /*
1257 : * Get a worker entry from the freelist. We checked above, so there
1258 : * really should be a free slot.
1259 : */
1260 2356 : wptr = dclist_pop_head_node(&AutoVacuumShmem->av_freeWorkers);
1261 :
1262 2356 : worker = dlist_container(WorkerInfoData, wi_links, wptr);
1263 2356 : worker->wi_dboid = avdb->adw_datid;
1264 2356 : worker->wi_proc = NULL;
1265 2356 : worker->wi_launchtime = GetCurrentTimestamp();
1266 :
1267 2356 : AutoVacuumShmem->av_startingWorker = worker;
1268 :
1269 2356 : LWLockRelease(AutovacuumLock);
1270 :
1271 2356 : SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
1272 :
1273 2356 : retval = avdb->adw_datid;
1274 : }
1275 0 : else if (skipit)
1276 : {
1277 : /*
1278 : * If we skipped all databases on the list, rebuild it, because it
1279 : * probably contains a dropped database.
1280 : */
1281 0 : rebuild_database_list(InvalidOid);
1282 : }
1283 :
1284 2356 : MemoryContextSwitchTo(oldcxt);
1285 2356 : MemoryContextDelete(tmpcxt);
1286 :
1287 2356 : return retval;
1288 : }
1289 :
1290 : /*
1291 : * launch_worker
1292 : *
1293 : * Wrapper for starting a worker from the launcher. Besides actually starting
1294 : * it, update the database list to reflect the next time that another one will
1295 : * need to be started on the selected database. The actual database choice is
1296 : * left to do_start_worker.
1297 : *
1298 : * This routine is also expected to insert an entry into the database list if
1299 : * the selected database was previously absent from the list.
1300 : */
1301 : static void
1302 2356 : launch_worker(TimestampTz now)
1303 : {
1304 : Oid dbid;
1305 : dlist_iter iter;
1306 :
1307 2356 : dbid = do_start_worker();
1308 2356 : if (OidIsValid(dbid))
1309 : {
1310 2356 : bool found = false;
1311 :
1312 : /*
1313 : * Walk the database list and update the corresponding entry. If the
1314 : * database is not on the list, we'll recreate the list.
1315 : */
1316 6120 : dlist_foreach(iter, &DatabaseList)
1317 : {
1318 6092 : avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1319 :
1320 6092 : if (avdb->adl_datid == dbid)
1321 : {
1322 2328 : found = true;
1323 :
1324 : /*
1325 : * add autovacuum_naptime seconds to the current time, and use
1326 : * that as the new "next_worker" field for this database.
1327 : */
1328 2328 : avdb->adl_next_worker =
1329 2328 : TimestampTzPlusMilliseconds(now, autovacuum_naptime * 1000);
1330 :
1331 2328 : dlist_move_head(&DatabaseList, iter.cur);
1332 2328 : break;
1333 : }
1334 : }
1335 :
1336 : /*
1337 : * If the database was not present in the database list, we rebuild
1338 : * the list. It's possible that the database does not get into the
1339 : * list anyway, for example if it's a database that doesn't have a
1340 : * pgstat entry, but this is not a problem because we don't want to
1341 : * schedule workers regularly into those in any case.
1342 : */
1343 2356 : if (!found)
1344 28 : rebuild_database_list(dbid);
1345 : }
1346 2356 : }
1347 :
1348 : /*
1349 : * Called from postmaster to signal a failure to fork a process to become
1350 : * worker. The postmaster should kill(SIGUSR2) the launcher shortly
1351 : * after calling this function.
1352 : */
1353 : void
1354 0 : AutoVacWorkerFailed(void)
1355 : {
1356 0 : AutoVacuumShmem->av_signal[AutoVacForkFailed] = true;
1357 0 : }
1358 :
1359 : /* SIGUSR2: a worker is up and running, or just finished, or failed to fork */
1360 : static void
1361 4712 : avl_sigusr2_handler(SIGNAL_ARGS)
1362 : {
1363 4712 : got_SIGUSR2 = true;
1364 4712 : SetLatch(MyLatch);
1365 4712 : }
1366 :
1367 :
1368 : /********************************************************************
1369 : * AUTOVACUUM WORKER CODE
1370 : ********************************************************************/
1371 :
1372 : /*
1373 : * Main entry point for autovacuum worker processes.
1374 : */
1375 : void
1376 2386 : AutoVacWorkerMain(const void *startup_data, size_t startup_data_len)
1377 : {
1378 : sigjmp_buf local_sigjmp_buf;
1379 : Oid dbid;
1380 :
1381 : Assert(startup_data_len == 0);
1382 :
1383 : /* Release postmaster's working memory context */
1384 2386 : if (PostmasterContext)
1385 : {
1386 2386 : MemoryContextDelete(PostmasterContext);
1387 2386 : PostmasterContext = NULL;
1388 : }
1389 :
1390 2386 : MyBackendType = B_AUTOVAC_WORKER;
1391 2386 : init_ps_display(NULL);
1392 :
1393 : Assert(GetProcessingMode() == InitProcessing);
1394 :
1395 : /*
1396 : * Set up signal handlers. We operate on databases much like a regular
1397 : * backend, so we use the same signal handling. See equivalent code in
1398 : * tcop/postgres.c.
1399 : */
1400 2386 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
1401 :
1402 : /*
1403 : * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
1404 : * means abort and exit cleanly, and SIGQUIT means abandon ship.
1405 : */
1406 2386 : pqsignal(SIGINT, StatementCancelHandler);
1407 2386 : pqsignal(SIGTERM, die);
1408 : /* SIGQUIT handler was already set up by InitPostmasterChild */
1409 :
1410 2386 : InitializeTimeouts(); /* establishes SIGALRM handler */
1411 :
1412 2386 : pqsignal(SIGPIPE, SIG_IGN);
1413 2386 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
1414 2386 : pqsignal(SIGUSR2, SIG_IGN);
1415 2386 : pqsignal(SIGFPE, FloatExceptionHandler);
1416 2386 : pqsignal(SIGCHLD, SIG_DFL);
1417 :
1418 : /*
1419 : * Create a per-backend PGPROC struct in shared memory. We must do this
1420 : * before we can use LWLocks or access any shared memory.
1421 : */
1422 2386 : InitProcess();
1423 :
1424 : /* Early initialization */
1425 2386 : BaseInit();
1426 :
1427 : /*
1428 : * If an exception is encountered, processing resumes here.
1429 : *
1430 : * Unlike most auxiliary processes, we don't attempt to continue
1431 : * processing after an error; we just clean up and exit. The autovac
1432 : * launcher is responsible for spawning another worker later.
1433 : *
1434 : * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
1435 : * (to wit, BlockSig) will be restored when longjmp'ing to here. Thus,
1436 : * signals other than SIGQUIT will be blocked until we exit. It might
1437 : * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
1438 : * it is not since InterruptPending might be set already.
1439 : */
1440 2386 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1441 : {
1442 : /* since not using PG_TRY, must reset error stack by hand */
1443 0 : error_context_stack = NULL;
1444 :
1445 : /* Prevents interrupts while cleaning up */
1446 0 : HOLD_INTERRUPTS();
1447 :
1448 : /* Report the error to the server log */
1449 0 : EmitErrorReport();
1450 :
1451 : /*
1452 : * We can now go away. Note that because we called InitProcess, a
1453 : * callback was registered to do ProcKill, which will clean up
1454 : * necessary state.
1455 : */
1456 0 : proc_exit(0);
1457 : }
1458 :
1459 : /* We can now handle ereport(ERROR) */
1460 2386 : PG_exception_stack = &local_sigjmp_buf;
1461 :
1462 2386 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
1463 :
1464 : /*
1465 : * Set always-secure search path, so malicious users can't redirect user
1466 : * code (e.g. pg_index.indexprs). (That code runs in a
1467 : * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
1468 : * take control of the entire autovacuum worker in any case.)
1469 : */
1470 2386 : SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1471 :
1472 : /*
1473 : * Force zero_damaged_pages OFF in the autovac process, even if it is set
1474 : * in postgresql.conf. We don't really want such a dangerous option being
1475 : * applied non-interactively.
1476 : */
1477 2386 : SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
1478 :
1479 : /*
1480 : * Force settable timeouts off to avoid letting these settings prevent
1481 : * regular maintenance from being executed.
1482 : */
1483 2386 : SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1484 2386 : SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1485 2386 : SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1486 2386 : SetConfigOption("idle_in_transaction_session_timeout", "0",
1487 : PGC_SUSET, PGC_S_OVERRIDE);
1488 :
1489 : /*
1490 : * Force default_transaction_isolation to READ COMMITTED. We don't want
1491 : * to pay the overhead of serializable mode, nor add any risk of causing
1492 : * deadlocks or delaying other transactions.
1493 : */
1494 2386 : SetConfigOption("default_transaction_isolation", "read committed",
1495 : PGC_SUSET, PGC_S_OVERRIDE);
1496 :
1497 : /*
1498 : * Force synchronous replication off to allow regular maintenance even if
1499 : * we are waiting for standbys to connect. This is important to ensure we
1500 : * aren't blocked from performing anti-wraparound tasks.
1501 : */
1502 2386 : if (synchronous_commit > SYNCHRONOUS_COMMIT_LOCAL_FLUSH)
1503 2386 : SetConfigOption("synchronous_commit", "local",
1504 : PGC_SUSET, PGC_S_OVERRIDE);
1505 :
1506 : /*
1507 : * Even when system is configured to use a different fetch consistency,
1508 : * for autovac we always want fresh stats.
1509 : */
1510 2386 : SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
1511 :
1512 : /*
1513 : * Get the info about the database we're going to work on.
1514 : */
1515 2386 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1516 :
1517 : /*
1518 : * beware of startingWorker being INVALID; this should normally not
1519 : * happen, but if a worker fails after forking and before this, the
1520 : * launcher might have decided to remove it from the queue and start
1521 : * again.
1522 : */
1523 2386 : if (AutoVacuumShmem->av_startingWorker != NULL)
1524 : {
1525 2386 : MyWorkerInfo = AutoVacuumShmem->av_startingWorker;
1526 2386 : dbid = MyWorkerInfo->wi_dboid;
1527 2386 : MyWorkerInfo->wi_proc = MyProc;
1528 :
1529 : /* insert into the running list */
1530 2386 : dlist_push_head(&AutoVacuumShmem->av_runningWorkers,
1531 2386 : &MyWorkerInfo->wi_links);
1532 :
1533 : /*
1534 : * remove from the "starting" pointer, so that the launcher can start
1535 : * a new worker if required
1536 : */
1537 2386 : AutoVacuumShmem->av_startingWorker = NULL;
1538 2386 : LWLockRelease(AutovacuumLock);
1539 :
1540 2386 : on_shmem_exit(FreeWorkerInfo, 0);
1541 :
1542 : /* wake up the launcher */
1543 2386 : if (AutoVacuumShmem->av_launcherpid != 0)
1544 2386 : kill(AutoVacuumShmem->av_launcherpid, SIGUSR2);
1545 : }
1546 : else
1547 : {
1548 : /* no worker entry for me, go away */
1549 0 : elog(WARNING, "autovacuum worker started without a worker entry");
1550 0 : dbid = InvalidOid;
1551 0 : LWLockRelease(AutovacuumLock);
1552 : }
1553 :
1554 2386 : if (OidIsValid(dbid))
1555 : {
1556 : char dbname[NAMEDATALEN];
1557 :
1558 : /*
1559 : * Report autovac startup to the cumulative stats system. We
1560 : * deliberately do this before InitPostgres, so that the
1561 : * last_autovac_time will get updated even if the connection attempt
1562 : * fails. This is to prevent autovac from getting "stuck" repeatedly
1563 : * selecting an unopenable database, rather than making any progress
1564 : * on stuff it can connect to.
1565 : */
1566 2386 : pgstat_report_autovac(dbid);
1567 :
1568 : /*
1569 : * Connect to the selected database, specifying no particular user,
1570 : * and ignoring datallowconn. Collect the database's name for
1571 : * display.
1572 : *
1573 : * Note: if we have selected a just-deleted database (due to using
1574 : * stale stats info), we'll fail and exit here.
1575 : */
1576 2386 : InitPostgres(NULL, dbid, NULL, InvalidOid,
1577 : INIT_PG_OVERRIDE_ALLOW_CONNS,
1578 : dbname);
1579 2384 : SetProcessingMode(NormalProcessing);
1580 2384 : set_ps_display(dbname);
1581 2384 : ereport(DEBUG1,
1582 : (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1583 :
1584 2384 : if (PostAuthDelay)
1585 0 : pg_usleep(PostAuthDelay * 1000000L);
1586 :
1587 : /* And do an appropriate amount of work */
1588 2384 : recentXid = ReadNextTransactionId();
1589 2384 : recentMulti = ReadNextMultiXactId();
1590 2384 : do_autovacuum();
1591 : }
1592 :
1593 : /*
1594 : * The launcher will be notified of my death in ProcKill, *if* we managed
1595 : * to get a worker slot at all
1596 : */
1597 :
1598 : /* All done, go away */
1599 2382 : proc_exit(0);
1600 : }
1601 :
1602 : /*
1603 : * Return a WorkerInfo to the free list
1604 : */
1605 : static void
1606 2386 : FreeWorkerInfo(int code, Datum arg)
1607 : {
1608 2386 : if (MyWorkerInfo != NULL)
1609 : {
1610 2386 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1611 :
1612 : /*
1613 : * Wake the launcher up so that he can launch a new worker immediately
1614 : * if required. We only save the launcher's PID in local memory here;
1615 : * the actual signal will be sent when the PGPROC is recycled. Note
1616 : * that we always do this, so that the launcher can rebalance the cost
1617 : * limit setting of the remaining workers.
1618 : *
1619 : * We somewhat ignore the risk that the launcher changes its PID
1620 : * between us reading it and the actual kill; we expect ProcKill to be
1621 : * called shortly after us, and we assume that PIDs are not reused too
1622 : * quickly after a process exits.
1623 : */
1624 2386 : AutovacuumLauncherPid = AutoVacuumShmem->av_launcherpid;
1625 :
1626 2386 : dlist_delete(&MyWorkerInfo->wi_links);
1627 2386 : MyWorkerInfo->wi_dboid = InvalidOid;
1628 2386 : MyWorkerInfo->wi_tableoid = InvalidOid;
1629 2386 : MyWorkerInfo->wi_sharedrel = false;
1630 2386 : MyWorkerInfo->wi_proc = NULL;
1631 2386 : MyWorkerInfo->wi_launchtime = 0;
1632 2386 : pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance);
1633 2386 : dclist_push_head(&AutoVacuumShmem->av_freeWorkers,
1634 2386 : &MyWorkerInfo->wi_links);
1635 : /* not mine anymore */
1636 2386 : MyWorkerInfo = NULL;
1637 :
1638 : /*
1639 : * now that we're inactive, cause a rebalancing of the surviving
1640 : * workers
1641 : */
1642 2386 : AutoVacuumShmem->av_signal[AutoVacRebalance] = true;
1643 2386 : LWLockRelease(AutovacuumLock);
1644 : }
1645 2386 : }
1646 :
1647 : /*
1648 : * Update vacuum cost-based delay-related parameters for autovacuum workers and
1649 : * backends executing VACUUM or ANALYZE using the value of relevant GUCs and
1650 : * global state. This must be called during setup for vacuum and after every
1651 : * config reload to ensure up-to-date values.
1652 : */
1653 : void
1654 199174 : VacuumUpdateCosts(void)
1655 : {
1656 199174 : if (MyWorkerInfo)
1657 : {
1658 185644 : if (av_storage_param_cost_delay >= 0)
1659 0 : vacuum_cost_delay = av_storage_param_cost_delay;
1660 185644 : else if (autovacuum_vac_cost_delay >= 0)
1661 185644 : vacuum_cost_delay = autovacuum_vac_cost_delay;
1662 : else
1663 : /* fall back to VacuumCostDelay */
1664 0 : vacuum_cost_delay = VacuumCostDelay;
1665 :
1666 185644 : AutoVacuumUpdateCostLimit();
1667 : }
1668 : else
1669 : {
1670 : /* Must be explicit VACUUM or ANALYZE */
1671 13530 : vacuum_cost_delay = VacuumCostDelay;
1672 13530 : vacuum_cost_limit = VacuumCostLimit;
1673 : }
1674 :
1675 : /*
1676 : * If configuration changes are allowed to impact VacuumCostActive, make
1677 : * sure it is updated.
1678 : */
1679 199174 : if (VacuumFailsafeActive)
1680 : Assert(!VacuumCostActive);
1681 199174 : else if (vacuum_cost_delay > 0)
1682 185644 : VacuumCostActive = true;
1683 : else
1684 : {
1685 13530 : VacuumCostActive = false;
1686 13530 : VacuumCostBalance = 0;
1687 : }
1688 :
1689 : /*
1690 : * Since the cost logging requires a lock, avoid rendering the log message
1691 : * in case we are using a message level where the log wouldn't be emitted.
1692 : */
1693 199174 : if (MyWorkerInfo && message_level_is_interesting(DEBUG2))
1694 : {
1695 : Oid dboid,
1696 : tableoid;
1697 :
1698 : Assert(!LWLockHeldByMe(AutovacuumLock));
1699 :
1700 0 : LWLockAcquire(AutovacuumLock, LW_SHARED);
1701 0 : dboid = MyWorkerInfo->wi_dboid;
1702 0 : tableoid = MyWorkerInfo->wi_tableoid;
1703 0 : LWLockRelease(AutovacuumLock);
1704 :
1705 0 : elog(DEBUG2,
1706 : "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
1707 : dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
1708 : vacuum_cost_limit, vacuum_cost_delay,
1709 : vacuum_cost_delay > 0 ? "yes" : "no",
1710 : VacuumFailsafeActive ? "yes" : "no");
1711 : }
1712 199174 : }
1713 :
1714 : /*
1715 : * Update vacuum_cost_limit with the correct value for an autovacuum worker,
1716 : * given the value of other relevant cost limit parameters and the number of
1717 : * workers across which the limit must be balanced. Autovacuum workers must
1718 : * call this regularly in case av_nworkersForBalance has been updated by
1719 : * another worker or by the autovacuum launcher. They must also call it after a
1720 : * config reload.
1721 : */
1722 : void
1723 189208 : AutoVacuumUpdateCostLimit(void)
1724 : {
1725 189208 : if (!MyWorkerInfo)
1726 0 : return;
1727 :
1728 : /*
1729 : * note: in cost_limit, zero also means use value from elsewhere, because
1730 : * zero is not a valid value.
1731 : */
1732 :
1733 189208 : if (av_storage_param_cost_limit > 0)
1734 0 : vacuum_cost_limit = av_storage_param_cost_limit;
1735 : else
1736 : {
1737 : int nworkers_for_balance;
1738 :
1739 189208 : if (autovacuum_vac_cost_limit > 0)
1740 0 : vacuum_cost_limit = autovacuum_vac_cost_limit;
1741 : else
1742 189208 : vacuum_cost_limit = VacuumCostLimit;
1743 :
1744 : /* Only balance limit if no cost-related storage parameters specified */
1745 189208 : if (pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance))
1746 0 : return;
1747 :
1748 : Assert(vacuum_cost_limit > 0);
1749 :
1750 189208 : nworkers_for_balance = pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1751 :
1752 : /* There is at least 1 autovac worker (this worker) */
1753 189208 : if (nworkers_for_balance <= 0)
1754 0 : elog(ERROR, "nworkers_for_balance must be > 0");
1755 :
1756 189208 : vacuum_cost_limit = Max(vacuum_cost_limit / nworkers_for_balance, 1);
1757 : }
1758 : }
1759 :
1760 : /*
1761 : * autovac_recalculate_workers_for_balance
1762 : * Recalculate the number of workers to consider, given cost-related
1763 : * storage parameters and the current number of active workers.
1764 : *
1765 : * Caller must hold the AutovacuumLock in at least shared mode to access
1766 : * worker->wi_proc.
1767 : */
1768 : static void
1769 95178 : autovac_recalculate_workers_for_balance(void)
1770 : {
1771 : dlist_iter iter;
1772 : int orig_nworkers_for_balance;
1773 95178 : int nworkers_for_balance = 0;
1774 :
1775 : Assert(LWLockHeldByMe(AutovacuumLock));
1776 :
1777 95178 : orig_nworkers_for_balance =
1778 95178 : pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1779 :
1780 193330 : dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers)
1781 : {
1782 98152 : WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1783 :
1784 196304 : if (worker->wi_proc == NULL ||
1785 98152 : pg_atomic_unlocked_test_flag(&worker->wi_dobalance))
1786 332 : continue;
1787 :
1788 97820 : nworkers_for_balance++;
1789 : }
1790 :
1791 95178 : if (nworkers_for_balance != orig_nworkers_for_balance)
1792 1936 : pg_atomic_write_u32(&AutoVacuumShmem->av_nworkersForBalance,
1793 : nworkers_for_balance);
1794 95178 : }
1795 :
1796 : /*
1797 : * get_database_list
1798 : * Return a list of all databases found in pg_database.
1799 : *
1800 : * The list and associated data is allocated in the caller's memory context,
1801 : * which is in charge of ensuring that it's properly cleaned up afterwards.
1802 : *
1803 : * Note: this is the only function in which the autovacuum launcher uses a
1804 : * transaction. Although we aren't attached to any particular database and
1805 : * therefore can't access most catalogs, we do have enough infrastructure
1806 : * to do a seqscan on pg_database.
1807 : */
1808 : static List *
1809 3328 : get_database_list(void)
1810 : {
1811 3328 : List *dblist = NIL;
1812 : Relation rel;
1813 : TableScanDesc scan;
1814 : HeapTuple tup;
1815 : MemoryContext resultcxt;
1816 :
1817 : /* This is the context that we will allocate our output data in */
1818 3328 : resultcxt = CurrentMemoryContext;
1819 :
1820 : /*
1821 : * Start a transaction so we can access pg_database.
1822 : */
1823 3328 : StartTransactionCommand();
1824 :
1825 3328 : rel = table_open(DatabaseRelationId, AccessShareLock);
1826 3328 : scan = table_beginscan_catalog(rel, 0, NULL);
1827 :
1828 13686 : while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1829 : {
1830 10358 : Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
1831 : avw_dbase *avdb;
1832 : MemoryContext oldcxt;
1833 :
1834 : /*
1835 : * If database has partially been dropped, we can't, nor need to,
1836 : * vacuum it.
1837 : */
1838 10358 : if (database_is_invalid_form(pgdatabase))
1839 : {
1840 4 : elog(DEBUG2,
1841 : "autovacuum: skipping invalid database \"%s\"",
1842 : NameStr(pgdatabase->datname));
1843 4 : continue;
1844 : }
1845 :
1846 : /*
1847 : * Allocate our results in the caller's context, not the
1848 : * transaction's. We do this inside the loop, and restore the original
1849 : * context at the end, so that leaky things like heap_getnext() are
1850 : * not called in a potentially long-lived context.
1851 : */
1852 10354 : oldcxt = MemoryContextSwitchTo(resultcxt);
1853 :
1854 10354 : avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1855 :
1856 10354 : avdb->adw_datid = pgdatabase->oid;
1857 10354 : avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1858 10354 : avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1859 10354 : avdb->adw_minmulti = pgdatabase->datminmxid;
1860 : /* this gets set later: */
1861 10354 : avdb->adw_entry = NULL;
1862 :
1863 10354 : dblist = lappend(dblist, avdb);
1864 10354 : MemoryContextSwitchTo(oldcxt);
1865 : }
1866 :
1867 3328 : table_endscan(scan);
1868 3328 : table_close(rel, AccessShareLock);
1869 :
1870 3328 : CommitTransactionCommand();
1871 :
1872 : /* Be sure to restore caller's memory context */
1873 3328 : MemoryContextSwitchTo(resultcxt);
1874 :
1875 3328 : return dblist;
1876 : }
1877 :
1878 : /*
1879 : * Process a database table-by-table
1880 : *
1881 : * Note that CHECK_FOR_INTERRUPTS is supposed to be used in certain spots in
1882 : * order not to ignore shutdown commands for too long.
1883 : */
1884 : static void
1885 2384 : do_autovacuum(void)
1886 : {
1887 : Relation classRel;
1888 : HeapTuple tuple;
1889 : TableScanDesc relScan;
1890 : Form_pg_database dbForm;
1891 2384 : List *table_oids = NIL;
1892 2384 : List *orphan_oids = NIL;
1893 : HASHCTL ctl;
1894 : HTAB *table_toast_map;
1895 : ListCell *volatile cell;
1896 : BufferAccessStrategy bstrategy;
1897 : ScanKeyData key;
1898 : TupleDesc pg_class_desc;
1899 : int effective_multixact_freeze_max_age;
1900 2384 : bool did_vacuum = false;
1901 2384 : bool found_concurrent_worker = false;
1902 : int i;
1903 :
1904 : /*
1905 : * StartTransactionCommand and CommitTransactionCommand will automatically
1906 : * switch to other contexts. We need this one to keep the list of
1907 : * relations to vacuum/analyze across transactions.
1908 : */
1909 2384 : AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
1910 : "Autovacuum worker",
1911 : ALLOCSET_DEFAULT_SIZES);
1912 2384 : MemoryContextSwitchTo(AutovacMemCxt);
1913 :
1914 : /* Start a transaction so our commands have one to play into. */
1915 2384 : StartTransactionCommand();
1916 :
1917 : /*
1918 : * This injection point is put in a transaction block to work with a wait
1919 : * that uses a condition variable.
1920 : */
1921 2384 : INJECTION_POINT("autovacuum-worker-start");
1922 :
1923 : /*
1924 : * Compute the multixact age for which freezing is urgent. This is
1925 : * normally autovacuum_multixact_freeze_max_age, but may be less if we are
1926 : * short of multixact member space.
1927 : */
1928 2382 : effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
1929 :
1930 : /*
1931 : * Find the pg_database entry and select the default freeze ages. We use
1932 : * zero in template and nonconnectable databases, else the system-wide
1933 : * default.
1934 : */
1935 2382 : tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
1936 2382 : if (!HeapTupleIsValid(tuple))
1937 0 : elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1938 2382 : dbForm = (Form_pg_database) GETSTRUCT(tuple);
1939 :
1940 2382 : if (dbForm->datistemplate || !dbForm->datallowconn)
1941 : {
1942 1216 : default_freeze_min_age = 0;
1943 1216 : default_freeze_table_age = 0;
1944 1216 : default_multixact_freeze_min_age = 0;
1945 1216 : default_multixact_freeze_table_age = 0;
1946 : }
1947 : else
1948 : {
1949 1166 : default_freeze_min_age = vacuum_freeze_min_age;
1950 1166 : default_freeze_table_age = vacuum_freeze_table_age;
1951 1166 : default_multixact_freeze_min_age = vacuum_multixact_freeze_min_age;
1952 1166 : default_multixact_freeze_table_age = vacuum_multixact_freeze_table_age;
1953 : }
1954 :
1955 2382 : ReleaseSysCache(tuple);
1956 :
1957 : /* StartTransactionCommand changed elsewhere */
1958 2382 : MemoryContextSwitchTo(AutovacMemCxt);
1959 :
1960 2382 : classRel = table_open(RelationRelationId, AccessShareLock);
1961 :
1962 : /* create a copy so we can use it after closing pg_class */
1963 2382 : pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
1964 :
1965 : /* create hash table for toast <-> main relid mapping */
1966 2382 : ctl.keysize = sizeof(Oid);
1967 2382 : ctl.entrysize = sizeof(av_relation);
1968 :
1969 2382 : table_toast_map = hash_create("TOAST to main relid map",
1970 : 100,
1971 : &ctl,
1972 : HASH_ELEM | HASH_BLOBS);
1973 :
1974 : /*
1975 : * Scan pg_class to determine which tables to vacuum.
1976 : *
1977 : * We do this in two passes: on the first one we collect the list of plain
1978 : * relations and materialized views, and on the second one we collect
1979 : * TOAST tables. The reason for doing the second pass is that during it we
1980 : * want to use the main relation's pg_class.reloptions entry if the TOAST
1981 : * table does not have any, and we cannot obtain it unless we know
1982 : * beforehand what's the main table OID.
1983 : *
1984 : * We need to check TOAST tables separately because in cases with short,
1985 : * wide tables there might be proportionally much more activity in the
1986 : * TOAST table than in its parent.
1987 : */
1988 2382 : relScan = table_beginscan_catalog(classRel, 0, NULL);
1989 :
1990 : /*
1991 : * On the first pass, we collect main tables to vacuum, and also the main
1992 : * table relid to TOAST relid mapping.
1993 : */
1994 999910 : while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
1995 : {
1996 997528 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
1997 : PgStat_StatTabEntry *tabentry;
1998 : AutoVacOpts *relopts;
1999 : Oid relid;
2000 : bool dovacuum;
2001 : bool doanalyze;
2002 : bool wraparound;
2003 :
2004 997528 : if (classForm->relkind != RELKIND_RELATION &&
2005 832986 : classForm->relkind != RELKIND_MATVIEW)
2006 832952 : continue;
2007 :
2008 164576 : relid = classForm->oid;
2009 :
2010 : /*
2011 : * Check if it is a temp table (presumably, of some other backend's).
2012 : * We cannot safely process other backends' temp tables.
2013 : */
2014 164576 : if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2015 : {
2016 : /*
2017 : * We just ignore it if the owning backend is still active and
2018 : * using the temporary schema. Also, for safety, ignore it if the
2019 : * namespace doesn't exist or isn't a temp namespace after all.
2020 : */
2021 0 : if (checkTempNamespaceStatus(classForm->relnamespace) == TEMP_NAMESPACE_IDLE)
2022 : {
2023 : /*
2024 : * The table seems to be orphaned -- although it might be that
2025 : * the owning backend has already deleted it and exited; our
2026 : * pg_class scan snapshot is not necessarily up-to-date
2027 : * anymore, so we could be looking at a committed-dead entry.
2028 : * Remember it so we can try to delete it later.
2029 : */
2030 0 : orphan_oids = lappend_oid(orphan_oids, relid);
2031 : }
2032 0 : continue;
2033 : }
2034 :
2035 : /* Fetch reloptions and the pgstat entry for this table */
2036 164576 : relopts = extract_autovac_opts(tuple, pg_class_desc);
2037 164576 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2038 : relid);
2039 :
2040 : /* Check if it needs vacuum or analyze */
2041 164576 : relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2042 : effective_multixact_freeze_max_age,
2043 : &dovacuum, &doanalyze, &wraparound);
2044 :
2045 : /* Relations that need work are added to table_oids */
2046 164576 : if (dovacuum || doanalyze)
2047 58312 : table_oids = lappend_oid(table_oids, relid);
2048 :
2049 : /*
2050 : * Remember TOAST associations for the second pass. Note: we must do
2051 : * this whether or not the table is going to be vacuumed, because we
2052 : * don't automatically vacuum toast tables along the parent table.
2053 : */
2054 164576 : if (OidIsValid(classForm->reltoastrelid))
2055 : {
2056 : av_relation *hentry;
2057 : bool found;
2058 :
2059 194704 : hentry = hash_search(table_toast_map,
2060 97352 : &classForm->reltoastrelid,
2061 : HASH_ENTER, &found);
2062 :
2063 97352 : if (!found)
2064 : {
2065 : /* hash_search already filled in the key */
2066 97352 : hentry->ar_relid = relid;
2067 97352 : hentry->ar_hasrelopts = false;
2068 97352 : if (relopts != NULL)
2069 : {
2070 1780 : hentry->ar_hasrelopts = true;
2071 1780 : memcpy(&hentry->ar_reloptions, relopts,
2072 : sizeof(AutoVacOpts));
2073 : }
2074 : }
2075 : }
2076 : }
2077 :
2078 2382 : table_endscan(relScan);
2079 :
2080 : /* second pass: check TOAST tables */
2081 2382 : ScanKeyInit(&key,
2082 : Anum_pg_class_relkind,
2083 : BTEqualStrategyNumber, F_CHAREQ,
2084 : CharGetDatum(RELKIND_TOASTVALUE));
2085 :
2086 2382 : relScan = table_beginscan_catalog(classRel, 1, &key);
2087 99734 : while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2088 : {
2089 97352 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2090 : PgStat_StatTabEntry *tabentry;
2091 : Oid relid;
2092 97352 : AutoVacOpts *relopts = NULL;
2093 : bool dovacuum;
2094 : bool doanalyze;
2095 : bool wraparound;
2096 :
2097 : /*
2098 : * We cannot safely process other backends' temp tables, so skip 'em.
2099 : */
2100 97352 : if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2101 0 : continue;
2102 :
2103 97352 : relid = classForm->oid;
2104 :
2105 : /*
2106 : * fetch reloptions -- if this toast table does not have them, try the
2107 : * main rel
2108 : */
2109 97352 : relopts = extract_autovac_opts(tuple, pg_class_desc);
2110 97352 : if (relopts == NULL)
2111 : {
2112 : av_relation *hentry;
2113 : bool found;
2114 :
2115 97352 : hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2116 97352 : if (found && hentry->ar_hasrelopts)
2117 1780 : relopts = &hentry->ar_reloptions;
2118 : }
2119 :
2120 : /* Fetch the pgstat entry for this table */
2121 97352 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2122 : relid);
2123 :
2124 97352 : relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2125 : effective_multixact_freeze_max_age,
2126 : &dovacuum, &doanalyze, &wraparound);
2127 :
2128 : /* ignore analyze for toast tables */
2129 97352 : if (dovacuum)
2130 34510 : table_oids = lappend_oid(table_oids, relid);
2131 : }
2132 :
2133 2382 : table_endscan(relScan);
2134 2382 : table_close(classRel, AccessShareLock);
2135 :
2136 : /*
2137 : * Recheck orphan temporary tables, and if they still seem orphaned, drop
2138 : * them. We'll eat a transaction per dropped table, which might seem
2139 : * excessive, but we should only need to do anything as a result of a
2140 : * previous backend crash, so this should not happen often enough to
2141 : * justify "optimizing". Using separate transactions ensures that we
2142 : * don't bloat the lock table if there are many temp tables to be dropped,
2143 : * and it ensures that we don't lose work if a deletion attempt fails.
2144 : */
2145 2382 : foreach(cell, orphan_oids)
2146 : {
2147 0 : Oid relid = lfirst_oid(cell);
2148 : Form_pg_class classForm;
2149 : ObjectAddress object;
2150 :
2151 : /*
2152 : * Check for user-requested abort.
2153 : */
2154 0 : CHECK_FOR_INTERRUPTS();
2155 :
2156 : /*
2157 : * Try to lock the table. If we can't get the lock immediately,
2158 : * somebody else is using (or dropping) the table, so it's not our
2159 : * concern anymore. Having the lock prevents race conditions below.
2160 : */
2161 0 : if (!ConditionalLockRelationOid(relid, AccessExclusiveLock))
2162 0 : continue;
2163 :
2164 : /*
2165 : * Re-fetch the pg_class tuple and re-check whether it still seems to
2166 : * be an orphaned temp table. If it's not there or no longer the same
2167 : * relation, ignore it.
2168 : */
2169 0 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2170 0 : if (!HeapTupleIsValid(tuple))
2171 : {
2172 : /* be sure to drop useless lock so we don't bloat lock table */
2173 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2174 0 : continue;
2175 : }
2176 0 : classForm = (Form_pg_class) GETSTRUCT(tuple);
2177 :
2178 : /*
2179 : * Make all the same tests made in the loop above. In event of OID
2180 : * counter wraparound, the pg_class entry we have now might be
2181 : * completely unrelated to the one we saw before.
2182 : */
2183 0 : if (!((classForm->relkind == RELKIND_RELATION ||
2184 0 : classForm->relkind == RELKIND_MATVIEW) &&
2185 0 : classForm->relpersistence == RELPERSISTENCE_TEMP))
2186 : {
2187 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2188 0 : continue;
2189 : }
2190 :
2191 0 : if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE)
2192 : {
2193 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2194 0 : continue;
2195 : }
2196 :
2197 : /*
2198 : * Try to lock the temp namespace, too. Even though we have lock on
2199 : * the table itself, there's a risk of deadlock against an incoming
2200 : * backend trying to clean out the temp namespace, in case this table
2201 : * has dependencies (such as sequences) that the backend's
2202 : * performDeletion call might visit in a different order. If we can
2203 : * get AccessShareLock on the namespace, that's sufficient to ensure
2204 : * we're not running concurrently with RemoveTempRelations. If we
2205 : * can't, back off and let RemoveTempRelations do its thing.
2206 : */
2207 0 : if (!ConditionalLockDatabaseObject(NamespaceRelationId,
2208 : classForm->relnamespace, 0,
2209 : AccessShareLock))
2210 : {
2211 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2212 0 : continue;
2213 : }
2214 :
2215 : /* OK, let's delete it */
2216 0 : ereport(LOG,
2217 : (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2218 : get_database_name(MyDatabaseId),
2219 : get_namespace_name(classForm->relnamespace),
2220 : NameStr(classForm->relname))));
2221 :
2222 0 : object.classId = RelationRelationId;
2223 0 : object.objectId = relid;
2224 0 : object.objectSubId = 0;
2225 0 : performDeletion(&object, DROP_CASCADE,
2226 : PERFORM_DELETION_INTERNAL |
2227 : PERFORM_DELETION_QUIETLY |
2228 : PERFORM_DELETION_SKIP_EXTENSIONS);
2229 :
2230 : /*
2231 : * To commit the deletion, end current transaction and start a new
2232 : * one. Note this also releases the locks we took.
2233 : */
2234 0 : CommitTransactionCommand();
2235 0 : StartTransactionCommand();
2236 :
2237 : /* StartTransactionCommand changed current memory context */
2238 0 : MemoryContextSwitchTo(AutovacMemCxt);
2239 : }
2240 :
2241 : /*
2242 : * Optionally, create a buffer access strategy object for VACUUM to use.
2243 : * We use the same BufferAccessStrategy object for all tables VACUUMed by
2244 : * this worker to prevent autovacuum from blowing out shared buffers.
2245 : *
2246 : * VacuumBufferUsageLimit being set to 0 results in
2247 : * GetAccessStrategyWithSize returning NULL, effectively meaning we can
2248 : * use up to all of shared buffers.
2249 : *
2250 : * If we later enter failsafe mode on any of the tables being vacuumed, we
2251 : * will cease use of the BufferAccessStrategy only for that table.
2252 : *
2253 : * XXX should we consider adding code to adjust the size of this if
2254 : * VacuumBufferUsageLimit changes?
2255 : */
2256 2382 : bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, VacuumBufferUsageLimit);
2257 :
2258 : /*
2259 : * create a memory context to act as fake PortalContext, so that the
2260 : * contexts created in the vacuum code are cleaned up for each table.
2261 : */
2262 2382 : PortalContext = AllocSetContextCreate(AutovacMemCxt,
2263 : "Autovacuum Portal",
2264 : ALLOCSET_DEFAULT_SIZES);
2265 :
2266 : /*
2267 : * Perform operations on collected tables.
2268 : */
2269 95204 : foreach(cell, table_oids)
2270 : {
2271 92822 : Oid relid = lfirst_oid(cell);
2272 : HeapTuple classTup;
2273 : autovac_table *tab;
2274 : bool isshared;
2275 : bool skipit;
2276 : dlist_iter iter;
2277 :
2278 92822 : CHECK_FOR_INTERRUPTS();
2279 :
2280 : /*
2281 : * Check for config changes before processing each collected table.
2282 : */
2283 92822 : if (ConfigReloadPending)
2284 : {
2285 0 : ConfigReloadPending = false;
2286 0 : ProcessConfigFile(PGC_SIGHUP);
2287 :
2288 : /*
2289 : * You might be tempted to bail out if we see autovacuum is now
2290 : * disabled. Must resist that temptation -- this might be a
2291 : * for-wraparound emergency worker, in which case that would be
2292 : * entirely inappropriate.
2293 : */
2294 : }
2295 :
2296 : /*
2297 : * Find out whether the table is shared or not. (It's slightly
2298 : * annoying to fetch the syscache entry just for this, but in typical
2299 : * cases it adds little cost because table_recheck_autovac would
2300 : * refetch the entry anyway. We could buy that back by copying the
2301 : * tuple here and passing it to table_recheck_autovac, but that
2302 : * increases the odds of that function working with stale data.)
2303 : */
2304 92822 : classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2305 92822 : if (!HeapTupleIsValid(classTup))
2306 0 : continue; /* somebody deleted the rel, forget it */
2307 92822 : isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared;
2308 92822 : ReleaseSysCache(classTup);
2309 :
2310 : /*
2311 : * Hold schedule lock from here until we've claimed the table. We
2312 : * also need the AutovacuumLock to walk the worker array, but that one
2313 : * can just be a shared lock.
2314 : */
2315 92822 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2316 92822 : LWLockAcquire(AutovacuumLock, LW_SHARED);
2317 :
2318 : /*
2319 : * Check whether the table is being vacuumed concurrently by another
2320 : * worker.
2321 : */
2322 92822 : skipit = false;
2323 190888 : dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers)
2324 : {
2325 98066 : WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2326 :
2327 : /* ignore myself */
2328 98066 : if (worker == MyWorkerInfo)
2329 92822 : continue;
2330 :
2331 : /* ignore workers in other databases (unless table is shared) */
2332 5244 : if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2333 0 : continue;
2334 :
2335 5244 : if (worker->wi_tableoid == relid)
2336 : {
2337 0 : skipit = true;
2338 0 : found_concurrent_worker = true;
2339 0 : break;
2340 : }
2341 : }
2342 92822 : LWLockRelease(AutovacuumLock);
2343 92822 : if (skipit)
2344 : {
2345 0 : LWLockRelease(AutovacuumScheduleLock);
2346 0 : continue;
2347 : }
2348 :
2349 : /*
2350 : * Store the table's OID in shared memory before releasing the
2351 : * schedule lock, so that other workers don't try to vacuum it
2352 : * concurrently. (We claim it here so as not to hold
2353 : * AutovacuumScheduleLock while rechecking the stats.)
2354 : */
2355 92822 : MyWorkerInfo->wi_tableoid = relid;
2356 92822 : MyWorkerInfo->wi_sharedrel = isshared;
2357 92822 : LWLockRelease(AutovacuumScheduleLock);
2358 :
2359 : /*
2360 : * Check whether pgstat data still says we need to vacuum this table.
2361 : * It could have changed if something else processed the table while
2362 : * we weren't looking. This doesn't entirely close the race condition,
2363 : * but it is very small.
2364 : */
2365 92822 : MemoryContextSwitchTo(AutovacMemCxt);
2366 92822 : tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
2367 : effective_multixact_freeze_max_age);
2368 92822 : if (tab == NULL)
2369 : {
2370 : /* someone else vacuumed the table, or it went away */
2371 0 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2372 0 : MyWorkerInfo->wi_tableoid = InvalidOid;
2373 0 : MyWorkerInfo->wi_sharedrel = false;
2374 0 : LWLockRelease(AutovacuumScheduleLock);
2375 0 : continue;
2376 : }
2377 :
2378 : /*
2379 : * Save the cost-related storage parameter values in global variables
2380 : * for reference when updating vacuum_cost_delay and vacuum_cost_limit
2381 : * during vacuuming this table.
2382 : */
2383 92822 : av_storage_param_cost_delay = tab->at_storage_param_vac_cost_delay;
2384 92822 : av_storage_param_cost_limit = tab->at_storage_param_vac_cost_limit;
2385 :
2386 : /*
2387 : * We only expect this worker to ever set the flag, so don't bother
2388 : * checking the return value. We shouldn't have to retry.
2389 : */
2390 92822 : if (tab->at_dobalance)
2391 92822 : pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance);
2392 : else
2393 0 : pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance);
2394 :
2395 92822 : LWLockAcquire(AutovacuumLock, LW_SHARED);
2396 92822 : autovac_recalculate_workers_for_balance();
2397 92822 : LWLockRelease(AutovacuumLock);
2398 :
2399 : /*
2400 : * We wait until this point to update cost delay and cost limit
2401 : * values, even though we reloaded the configuration file above, so
2402 : * that we can take into account the cost-related storage parameters.
2403 : */
2404 92822 : VacuumUpdateCosts();
2405 :
2406 :
2407 : /* clean up memory before each iteration */
2408 92822 : MemoryContextReset(PortalContext);
2409 :
2410 : /*
2411 : * Save the relation name for a possible error message, to avoid a
2412 : * catalog lookup in case of an error. If any of these return NULL,
2413 : * then the relation has been dropped since last we checked; skip it.
2414 : * Note: they must live in a long-lived memory context because we call
2415 : * vacuum and analyze in different transactions.
2416 : */
2417 :
2418 92822 : tab->at_relname = get_rel_name(tab->at_relid);
2419 92822 : tab->at_nspname = get_namespace_name(get_rel_namespace(tab->at_relid));
2420 92822 : tab->at_datname = get_database_name(MyDatabaseId);
2421 92822 : if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2422 0 : goto deleted;
2423 :
2424 : /*
2425 : * We will abort vacuuming the current table if something errors out,
2426 : * and continue with the next one in schedule; in particular, this
2427 : * happens if we are interrupted with SIGINT.
2428 : */
2429 92822 : PG_TRY();
2430 : {
2431 : /* Use PortalContext for any per-table allocations */
2432 92822 : MemoryContextSwitchTo(PortalContext);
2433 :
2434 : /* have at it */
2435 92822 : autovacuum_do_vac_analyze(tab, bstrategy);
2436 :
2437 : /*
2438 : * Clear a possible query-cancel signal, to avoid a late reaction
2439 : * to an automatically-sent signal because of vacuuming the
2440 : * current table (we're done with it, so it would make no sense to
2441 : * cancel at this point.)
2442 : */
2443 92822 : QueryCancelPending = false;
2444 : }
2445 0 : PG_CATCH();
2446 : {
2447 : /*
2448 : * Abort the transaction, start a new one, and proceed with the
2449 : * next table in our list.
2450 : */
2451 0 : HOLD_INTERRUPTS();
2452 0 : if (tab->at_params.options & VACOPT_VACUUM)
2453 0 : errcontext("automatic vacuum of table \"%s.%s.%s\"",
2454 : tab->at_datname, tab->at_nspname, tab->at_relname);
2455 : else
2456 0 : errcontext("automatic analyze of table \"%s.%s.%s\"",
2457 : tab->at_datname, tab->at_nspname, tab->at_relname);
2458 0 : EmitErrorReport();
2459 :
2460 : /* this resets ProcGlobal->statusFlags[i] too */
2461 0 : AbortOutOfAnyTransaction();
2462 0 : FlushErrorState();
2463 0 : MemoryContextReset(PortalContext);
2464 :
2465 : /* restart our transaction for the following operations */
2466 0 : StartTransactionCommand();
2467 0 : RESUME_INTERRUPTS();
2468 : }
2469 92822 : PG_END_TRY();
2470 :
2471 : /* Make sure we're back in AutovacMemCxt */
2472 92822 : MemoryContextSwitchTo(AutovacMemCxt);
2473 :
2474 92822 : did_vacuum = true;
2475 :
2476 : /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2477 :
2478 : /* be tidy */
2479 92822 : deleted:
2480 92822 : if (tab->at_datname != NULL)
2481 92822 : pfree(tab->at_datname);
2482 92822 : if (tab->at_nspname != NULL)
2483 92822 : pfree(tab->at_nspname);
2484 92822 : if (tab->at_relname != NULL)
2485 92822 : pfree(tab->at_relname);
2486 92822 : pfree(tab);
2487 :
2488 : /*
2489 : * Remove my info from shared memory. We set wi_dobalance on the
2490 : * assumption that we are more likely than not to vacuum a table with
2491 : * no cost-related storage parameters next, so we want to claim our
2492 : * share of I/O as soon as possible to avoid thrashing the global
2493 : * balance.
2494 : */
2495 92822 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2496 92822 : MyWorkerInfo->wi_tableoid = InvalidOid;
2497 92822 : MyWorkerInfo->wi_sharedrel = false;
2498 92822 : LWLockRelease(AutovacuumScheduleLock);
2499 92822 : pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance);
2500 : }
2501 :
2502 : /*
2503 : * Perform additional work items, as requested by backends.
2504 : */
2505 2382 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2506 612174 : for (i = 0; i < NUM_WORKITEMS; i++)
2507 : {
2508 609792 : AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i];
2509 :
2510 609792 : if (!workitem->avw_used)
2511 609786 : continue;
2512 6 : if (workitem->avw_active)
2513 0 : continue;
2514 6 : if (workitem->avw_database != MyDatabaseId)
2515 0 : continue;
2516 :
2517 : /* claim this one, and release lock while performing it */
2518 6 : workitem->avw_active = true;
2519 6 : LWLockRelease(AutovacuumLock);
2520 :
2521 6 : perform_work_item(workitem);
2522 :
2523 : /*
2524 : * Check for config changes before acquiring lock for further jobs.
2525 : */
2526 6 : CHECK_FOR_INTERRUPTS();
2527 6 : if (ConfigReloadPending)
2528 : {
2529 0 : ConfigReloadPending = false;
2530 0 : ProcessConfigFile(PGC_SIGHUP);
2531 0 : VacuumUpdateCosts();
2532 : }
2533 :
2534 6 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2535 :
2536 : /* and mark it done */
2537 6 : workitem->avw_active = false;
2538 6 : workitem->avw_used = false;
2539 : }
2540 2382 : LWLockRelease(AutovacuumLock);
2541 :
2542 : /*
2543 : * We leak table_toast_map here (among other things), but since we're
2544 : * going away soon, it's not a problem.
2545 : */
2546 :
2547 : /*
2548 : * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2549 : * only need to do this once, not after each table.
2550 : *
2551 : * Even if we didn't vacuum anything, it may still be important to do
2552 : * this, because one indirect effect of vac_update_datfrozenxid() is to
2553 : * update TransamVariables->xidVacLimit. That might need to be done even
2554 : * if we haven't vacuumed anything, because relations with older
2555 : * relfrozenxid values or other databases with older datfrozenxid values
2556 : * might have been dropped, allowing xidVacLimit to advance.
2557 : *
2558 : * However, it's also important not to do this blindly in all cases,
2559 : * because when autovacuum=off this will restart the autovacuum launcher.
2560 : * If we're not careful, an infinite loop can result, where workers find
2561 : * no work to do and restart the launcher, which starts another worker in
2562 : * the same database that finds no work to do. To prevent that, we skip
2563 : * this if (1) we found no work to do and (2) we skipped at least one
2564 : * table due to concurrent autovacuum activity. In that case, the other
2565 : * worker has already done it, or will do so when it finishes.
2566 : */
2567 2382 : if (did_vacuum || !found_concurrent_worker)
2568 2382 : vac_update_datfrozenxid();
2569 :
2570 : /* Finally close out the last transaction. */
2571 2382 : CommitTransactionCommand();
2572 2382 : }
2573 :
2574 : /*
2575 : * Execute a previously registered work item.
2576 : */
2577 : static void
2578 6 : perform_work_item(AutoVacuumWorkItem *workitem)
2579 : {
2580 6 : char *cur_datname = NULL;
2581 6 : char *cur_nspname = NULL;
2582 6 : char *cur_relname = NULL;
2583 :
2584 : /*
2585 : * Note we do not store table info in MyWorkerInfo, since this is not
2586 : * vacuuming proper.
2587 : */
2588 :
2589 : /*
2590 : * Save the relation name for a possible error message, to avoid a catalog
2591 : * lookup in case of an error. If any of these return NULL, then the
2592 : * relation has been dropped since last we checked; skip it.
2593 : */
2594 : Assert(CurrentMemoryContext == AutovacMemCxt);
2595 :
2596 6 : cur_relname = get_rel_name(workitem->avw_relation);
2597 6 : cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2598 6 : cur_datname = get_database_name(MyDatabaseId);
2599 6 : if (!cur_relname || !cur_nspname || !cur_datname)
2600 0 : goto deleted2;
2601 :
2602 6 : autovac_report_workitem(workitem, cur_nspname, cur_relname);
2603 :
2604 : /* clean up memory before each work item */
2605 6 : MemoryContextReset(PortalContext);
2606 :
2607 : /*
2608 : * We will abort the current work item if something errors out, and
2609 : * continue with the next one; in particular, this happens if we are
2610 : * interrupted with SIGINT. Note that this means that the work item list
2611 : * can be lossy.
2612 : */
2613 6 : PG_TRY();
2614 : {
2615 : /* Use PortalContext for any per-work-item allocations */
2616 6 : MemoryContextSwitchTo(PortalContext);
2617 :
2618 : /*
2619 : * Have at it. Functions called here are responsible for any required
2620 : * user switch and sandbox.
2621 : */
2622 6 : switch (workitem->avw_type)
2623 : {
2624 6 : case AVW_BRINSummarizeRange:
2625 6 : DirectFunctionCall2(brin_summarize_range,
2626 : ObjectIdGetDatum(workitem->avw_relation),
2627 : Int64GetDatum((int64) workitem->avw_blockNumber));
2628 6 : break;
2629 0 : default:
2630 0 : elog(WARNING, "unrecognized work item found: type %d",
2631 : workitem->avw_type);
2632 0 : break;
2633 : }
2634 :
2635 : /*
2636 : * Clear a possible query-cancel signal, to avoid a late reaction to
2637 : * an automatically-sent signal because of vacuuming the current table
2638 : * (we're done with it, so it would make no sense to cancel at this
2639 : * point.)
2640 : */
2641 6 : QueryCancelPending = false;
2642 : }
2643 0 : PG_CATCH();
2644 : {
2645 : /*
2646 : * Abort the transaction, start a new one, and proceed with the next
2647 : * table in our list.
2648 : */
2649 0 : HOLD_INTERRUPTS();
2650 0 : errcontext("processing work entry for relation \"%s.%s.%s\"",
2651 : cur_datname, cur_nspname, cur_relname);
2652 0 : EmitErrorReport();
2653 :
2654 : /* this resets ProcGlobal->statusFlags[i] too */
2655 0 : AbortOutOfAnyTransaction();
2656 0 : FlushErrorState();
2657 0 : MemoryContextReset(PortalContext);
2658 :
2659 : /* restart our transaction for the following operations */
2660 0 : StartTransactionCommand();
2661 0 : RESUME_INTERRUPTS();
2662 : }
2663 6 : PG_END_TRY();
2664 :
2665 : /* Make sure we're back in AutovacMemCxt */
2666 6 : MemoryContextSwitchTo(AutovacMemCxt);
2667 :
2668 : /* We intentionally do not set did_vacuum here */
2669 :
2670 : /* be tidy */
2671 6 : deleted2:
2672 6 : if (cur_datname)
2673 6 : pfree(cur_datname);
2674 6 : if (cur_nspname)
2675 6 : pfree(cur_nspname);
2676 6 : if (cur_relname)
2677 6 : pfree(cur_relname);
2678 6 : }
2679 :
2680 : /*
2681 : * extract_autovac_opts
2682 : *
2683 : * Given a relation's pg_class tuple, return the AutoVacOpts portion of
2684 : * reloptions, if set; otherwise, return NULL.
2685 : *
2686 : * Note: callers do not have a relation lock on the table at this point,
2687 : * so the table could have been dropped, and its catalog rows gone, after
2688 : * we acquired the pg_class row. If pg_class had a TOAST table, this would
2689 : * be a risk; fortunately, it doesn't.
2690 : */
2691 : static AutoVacOpts *
2692 354750 : extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
2693 : {
2694 : bytea *relopts;
2695 : AutoVacOpts *av;
2696 :
2697 : Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2698 : ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2699 : ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2700 :
2701 354750 : relopts = extractRelOptions(tup, pg_class_desc, NULL);
2702 354750 : if (relopts == NULL)
2703 351726 : return NULL;
2704 :
2705 3024 : av = palloc(sizeof(AutoVacOpts));
2706 3024 : memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2707 3024 : pfree(relopts);
2708 :
2709 3024 : return av;
2710 : }
2711 :
2712 :
2713 : /*
2714 : * table_recheck_autovac
2715 : *
2716 : * Recheck whether a table still needs vacuum or analyze. Return value is a
2717 : * valid autovac_table pointer if it does, NULL otherwise.
2718 : *
2719 : * Note that the returned autovac_table does not have the name fields set.
2720 : */
2721 : static autovac_table *
2722 92822 : table_recheck_autovac(Oid relid, HTAB *table_toast_map,
2723 : TupleDesc pg_class_desc,
2724 : int effective_multixact_freeze_max_age)
2725 : {
2726 : Form_pg_class classForm;
2727 : HeapTuple classTup;
2728 : bool dovacuum;
2729 : bool doanalyze;
2730 92822 : autovac_table *tab = NULL;
2731 : bool wraparound;
2732 : AutoVacOpts *avopts;
2733 :
2734 : /* fetch the relation's relcache entry */
2735 92822 : classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2736 92822 : if (!HeapTupleIsValid(classTup))
2737 0 : return NULL;
2738 92822 : classForm = (Form_pg_class) GETSTRUCT(classTup);
2739 :
2740 : /*
2741 : * Get the applicable reloptions. If it is a TOAST table, try to get the
2742 : * main table reloptions if the toast table itself doesn't have.
2743 : */
2744 92822 : avopts = extract_autovac_opts(classTup, pg_class_desc);
2745 92822 : if (classForm->relkind == RELKIND_TOASTVALUE &&
2746 34510 : avopts == NULL && table_toast_map != NULL)
2747 : {
2748 : av_relation *hentry;
2749 : bool found;
2750 :
2751 34510 : hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2752 34510 : if (found && hentry->ar_hasrelopts)
2753 1220 : avopts = &hentry->ar_reloptions;
2754 : }
2755 :
2756 92822 : recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2757 : effective_multixact_freeze_max_age,
2758 : &dovacuum, &doanalyze, &wraparound);
2759 :
2760 : /* OK, it needs something done */
2761 92822 : if (doanalyze || dovacuum)
2762 : {
2763 : int freeze_min_age;
2764 : int freeze_table_age;
2765 : int multixact_freeze_min_age;
2766 : int multixact_freeze_table_age;
2767 : int log_min_duration;
2768 :
2769 : /*
2770 : * Calculate the vacuum cost parameters and the freeze ages. If there
2771 : * are options set in pg_class.reloptions, use them; in the case of a
2772 : * toast table, try the main table too. Otherwise use the GUC
2773 : * defaults, autovacuum's own first and plain vacuum second.
2774 : */
2775 :
2776 : /* -1 in autovac setting means use log_autovacuum_min_duration */
2777 2446 : log_min_duration = (avopts && avopts->log_min_duration >= 0)
2778 : ? avopts->log_min_duration
2779 95268 : : Log_autovacuum_min_duration;
2780 :
2781 : /* these do not have autovacuum-specific settings */
2782 2446 : freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2783 : ? avopts->freeze_min_age
2784 95268 : : default_freeze_min_age;
2785 :
2786 2446 : freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2787 : ? avopts->freeze_table_age
2788 95268 : : default_freeze_table_age;
2789 :
2790 95268 : multixact_freeze_min_age = (avopts &&
2791 2446 : avopts->multixact_freeze_min_age >= 0)
2792 : ? avopts->multixact_freeze_min_age
2793 95268 : : default_multixact_freeze_min_age;
2794 :
2795 95268 : multixact_freeze_table_age = (avopts &&
2796 2446 : avopts->multixact_freeze_table_age >= 0)
2797 : ? avopts->multixact_freeze_table_age
2798 95268 : : default_multixact_freeze_table_age;
2799 :
2800 92822 : tab = palloc(sizeof(autovac_table));
2801 92822 : tab->at_relid = relid;
2802 92822 : tab->at_sharedrel = classForm->relisshared;
2803 :
2804 : /*
2805 : * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2806 : * that vacuum() skips toast relations. Also note we tell vacuum() to
2807 : * skip vac_update_datfrozenxid(); we'll do that separately.
2808 : */
2809 92822 : tab->at_params.options =
2810 92822 : (dovacuum ? (VACOPT_VACUUM |
2811 : VACOPT_PROCESS_MAIN |
2812 92822 : VACOPT_SKIP_DATABASE_STATS) : 0) |
2813 92822 : (doanalyze ? VACOPT_ANALYZE : 0) |
2814 92822 : (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2815 :
2816 : /*
2817 : * index_cleanup and truncate are unspecified at first in autovacuum.
2818 : * They will be filled in with usable values using their reloptions
2819 : * (or reloption defaults) later.
2820 : */
2821 92822 : tab->at_params.index_cleanup = VACOPTVALUE_UNSPECIFIED;
2822 92822 : tab->at_params.truncate = VACOPTVALUE_UNSPECIFIED;
2823 : /* As of now, we don't support parallel vacuum for autovacuum */
2824 92822 : tab->at_params.nworkers = -1;
2825 92822 : tab->at_params.freeze_min_age = freeze_min_age;
2826 92822 : tab->at_params.freeze_table_age = freeze_table_age;
2827 92822 : tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2828 92822 : tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2829 92822 : tab->at_params.is_wraparound = wraparound;
2830 92822 : tab->at_params.log_min_duration = log_min_duration;
2831 92822 : tab->at_params.toast_parent = InvalidOid;
2832 :
2833 : /*
2834 : * Later, in vacuum_rel(), we check reloptions for any
2835 : * vacuum_max_eager_freeze_failure_rate override.
2836 : */
2837 92822 : tab->at_params.max_eager_freeze_failure_rate = vacuum_max_eager_freeze_failure_rate;
2838 92822 : tab->at_storage_param_vac_cost_limit = avopts ?
2839 92822 : avopts->vacuum_cost_limit : 0;
2840 92822 : tab->at_storage_param_vac_cost_delay = avopts ?
2841 92822 : avopts->vacuum_cost_delay : -1;
2842 92822 : tab->at_relname = NULL;
2843 92822 : tab->at_nspname = NULL;
2844 92822 : tab->at_datname = NULL;
2845 :
2846 : /*
2847 : * If any of the cost delay parameters has been set individually for
2848 : * this table, disable the balancing algorithm.
2849 : */
2850 92822 : tab->at_dobalance =
2851 95268 : !(avopts && (avopts->vacuum_cost_limit > 0 ||
2852 2446 : avopts->vacuum_cost_delay >= 0));
2853 : }
2854 :
2855 92822 : heap_freetuple(classTup);
2856 92822 : return tab;
2857 : }
2858 :
2859 : /*
2860 : * recheck_relation_needs_vacanalyze
2861 : *
2862 : * Subroutine for table_recheck_autovac.
2863 : *
2864 : * Fetch the pgstat of a relation and recheck whether a relation
2865 : * needs to be vacuumed or analyzed.
2866 : */
2867 : static void
2868 92822 : recheck_relation_needs_vacanalyze(Oid relid,
2869 : AutoVacOpts *avopts,
2870 : Form_pg_class classForm,
2871 : int effective_multixact_freeze_max_age,
2872 : bool *dovacuum,
2873 : bool *doanalyze,
2874 : bool *wraparound)
2875 : {
2876 : PgStat_StatTabEntry *tabentry;
2877 :
2878 : /* fetch the pgstat table entry */
2879 92822 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2880 : relid);
2881 :
2882 92822 : relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2883 : effective_multixact_freeze_max_age,
2884 : dovacuum, doanalyze, wraparound);
2885 :
2886 : /* ignore ANALYZE for toast tables */
2887 92822 : if (classForm->relkind == RELKIND_TOASTVALUE)
2888 34510 : *doanalyze = false;
2889 92822 : }
2890 :
2891 : /*
2892 : * relation_needs_vacanalyze
2893 : *
2894 : * Check whether a relation needs to be vacuumed or analyzed; return each into
2895 : * "dovacuum" and "doanalyze", respectively. Also return whether the vacuum is
2896 : * being forced because of Xid or multixact wraparound.
2897 : *
2898 : * relopts is a pointer to the AutoVacOpts options (either for itself in the
2899 : * case of a plain table, or for either itself or its parent table in the case
2900 : * of a TOAST table), NULL if none; tabentry is the pgstats entry, which can be
2901 : * NULL.
2902 : *
2903 : * A table needs to be vacuumed if the number of dead tuples exceeds a
2904 : * threshold. This threshold is calculated as
2905 : *
2906 : * threshold = vac_base_thresh + vac_scale_factor * reltuples
2907 : * if (threshold > vac_max_thresh)
2908 : * threshold = vac_max_thresh;
2909 : *
2910 : * For analyze, the analysis done is that the number of tuples inserted,
2911 : * deleted and updated since the last analyze exceeds a threshold calculated
2912 : * in the same fashion as above. Note that the cumulative stats system stores
2913 : * the number of tuples (both live and dead) that there were as of the last
2914 : * analyze. This is asymmetric to the VACUUM case.
2915 : *
2916 : * We also force vacuum if the table's relfrozenxid is more than freeze_max_age
2917 : * transactions back, and if its relminmxid is more than
2918 : * multixact_freeze_max_age multixacts back.
2919 : *
2920 : * A table whose autovacuum_enabled option is false is
2921 : * automatically skipped (unless we have to vacuum it due to freeze_max_age).
2922 : * Thus autovacuum can be disabled for specific tables. Also, when the cumulative
2923 : * stats system does not have data about a table, it will be skipped.
2924 : *
2925 : * A table whose vac_base_thresh value is < 0 takes the base value from the
2926 : * autovacuum_vacuum_threshold GUC variable. Similarly, a vac_scale_factor
2927 : * value < 0 is substituted with the value of
2928 : * autovacuum_vacuum_scale_factor GUC variable. Ditto for analyze.
2929 : */
2930 : static void
2931 354750 : relation_needs_vacanalyze(Oid relid,
2932 : AutoVacOpts *relopts,
2933 : Form_pg_class classForm,
2934 : PgStat_StatTabEntry *tabentry,
2935 : int effective_multixact_freeze_max_age,
2936 : /* output params below */
2937 : bool *dovacuum,
2938 : bool *doanalyze,
2939 : bool *wraparound)
2940 : {
2941 : bool force_vacuum;
2942 : bool av_enabled;
2943 :
2944 : /* constants from reloptions or GUC variables */
2945 : int vac_base_thresh,
2946 : vac_max_thresh,
2947 : vac_ins_base_thresh,
2948 : anl_base_thresh;
2949 : float4 vac_scale_factor,
2950 : vac_ins_scale_factor,
2951 : anl_scale_factor;
2952 :
2953 : /* thresholds calculated from above constants */
2954 : float4 vacthresh,
2955 : vacinsthresh,
2956 : anlthresh;
2957 :
2958 : /* number of vacuum (resp. analyze) tuples at this time */
2959 : float4 vactuples,
2960 : instuples,
2961 : anltuples;
2962 :
2963 : /* freeze parameters */
2964 : int freeze_max_age;
2965 : int multixact_freeze_max_age;
2966 : TransactionId xidForceLimit;
2967 : TransactionId relfrozenxid;
2968 : MultiXactId multiForceLimit;
2969 :
2970 : Assert(classForm != NULL);
2971 : Assert(OidIsValid(relid));
2972 :
2973 : /*
2974 : * Determine vacuum/analyze equation parameters. We have two possible
2975 : * sources: the passed reloptions (which could be a main table or a toast
2976 : * table), or the autovacuum GUC variables.
2977 : */
2978 :
2979 : /* -1 in autovac setting means use plain vacuum_scale_factor */
2980 6024 : vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
2981 0 : ? relopts->vacuum_scale_factor
2982 360774 : : autovacuum_vac_scale;
2983 :
2984 6024 : vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
2985 : ? relopts->vacuum_threshold
2986 360774 : : autovacuum_vac_thresh;
2987 :
2988 : /* -1 is used to disable max threshold */
2989 6024 : vac_max_thresh = (relopts && relopts->vacuum_max_threshold >= -1)
2990 : ? relopts->vacuum_max_threshold
2991 360774 : : autovacuum_vac_max_thresh;
2992 :
2993 6024 : vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
2994 0 : ? relopts->vacuum_ins_scale_factor
2995 360774 : : autovacuum_vac_ins_scale;
2996 :
2997 : /* -1 is used to disable insert vacuums */
2998 6024 : vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
2999 : ? relopts->vacuum_ins_threshold
3000 360774 : : autovacuum_vac_ins_thresh;
3001 :
3002 6024 : anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3003 0 : ? relopts->analyze_scale_factor
3004 360774 : : autovacuum_anl_scale;
3005 :
3006 6024 : anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3007 : ? relopts->analyze_threshold
3008 360774 : : autovacuum_anl_thresh;
3009 :
3010 6024 : freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3011 0 : ? Min(relopts->freeze_max_age, autovacuum_freeze_max_age)
3012 360774 : : autovacuum_freeze_max_age;
3013 :
3014 6024 : multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3015 0 : ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3016 360774 : : effective_multixact_freeze_max_age;
3017 :
3018 354750 : av_enabled = (relopts ? relopts->enabled : true);
3019 :
3020 : /* Force vacuum if table is at risk of wraparound */
3021 354750 : xidForceLimit = recentXid - freeze_max_age;
3022 354750 : if (xidForceLimit < FirstNormalTransactionId)
3023 0 : xidForceLimit -= FirstNormalTransactionId;
3024 354750 : relfrozenxid = classForm->relfrozenxid;
3025 709500 : force_vacuum = (TransactionIdIsNormal(relfrozenxid) &&
3026 354750 : TransactionIdPrecedes(relfrozenxid, xidForceLimit));
3027 354750 : if (!force_vacuum)
3028 : {
3029 169846 : MultiXactId relminmxid = classForm->relminmxid;
3030 :
3031 169846 : multiForceLimit = recentMulti - multixact_freeze_max_age;
3032 169846 : if (multiForceLimit < FirstMultiXactId)
3033 0 : multiForceLimit -= FirstMultiXactId;
3034 339692 : force_vacuum = MultiXactIdIsValid(relminmxid) &&
3035 169846 : MultiXactIdPrecedes(relminmxid, multiForceLimit);
3036 : }
3037 354750 : *wraparound = force_vacuum;
3038 :
3039 : /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3040 354750 : if (!av_enabled && !force_vacuum)
3041 : {
3042 1124 : *doanalyze = false;
3043 1124 : *dovacuum = false;
3044 1124 : return;
3045 : }
3046 :
3047 : /*
3048 : * If we found stats for the table, and autovacuum is currently enabled,
3049 : * make a threshold-based decision whether to vacuum and/or analyze. If
3050 : * autovacuum is currently disabled, we must be here for anti-wraparound
3051 : * vacuuming only, so don't vacuum (or analyze) anything that's not being
3052 : * forced.
3053 : */
3054 353626 : if (PointerIsValid(tabentry) && AutoVacuumingActive())
3055 346794 : {
3056 346794 : float4 pcnt_unfrozen = 1;
3057 346794 : float4 reltuples = classForm->reltuples;
3058 346794 : int32 relpages = classForm->relpages;
3059 346794 : int32 relallfrozen = classForm->relallfrozen;
3060 :
3061 346794 : vactuples = tabentry->dead_tuples;
3062 346794 : instuples = tabentry->ins_since_vacuum;
3063 346794 : anltuples = tabentry->mod_since_analyze;
3064 :
3065 : /* If the table hasn't yet been vacuumed, take reltuples as zero */
3066 346794 : if (reltuples < 0)
3067 634 : reltuples = 0;
3068 :
3069 : /*
3070 : * If we have data for relallfrozen, calculate the unfrozen percentage
3071 : * of the table to modify insert scale factor. This helps us decide
3072 : * whether or not to vacuum an insert-heavy table based on the number
3073 : * of inserts to the more "active" part of the table.
3074 : */
3075 346794 : if (relpages > 0 && relallfrozen > 0)
3076 : {
3077 : /*
3078 : * It could be the stats were updated manually and relallfrozen >
3079 : * relpages. Clamp relallfrozen to relpages to avoid nonsensical
3080 : * calculations.
3081 : */
3082 134908 : relallfrozen = Min(relallfrozen, relpages);
3083 134908 : pcnt_unfrozen = 1 - ((float4) relallfrozen / relpages);
3084 : }
3085 :
3086 346794 : vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3087 346794 : if (vac_max_thresh >= 0 && vacthresh > (float4) vac_max_thresh)
3088 0 : vacthresh = (float4) vac_max_thresh;
3089 :
3090 346794 : vacinsthresh = (float4) vac_ins_base_thresh +
3091 346794 : vac_ins_scale_factor * reltuples * pcnt_unfrozen;
3092 346794 : anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3093 :
3094 : /*
3095 : * Note that we don't need to take special consideration for stat
3096 : * reset, because if that happens, the last vacuum and analyze counts
3097 : * will be reset too.
3098 : */
3099 346794 : if (vac_ins_base_thresh >= 0)
3100 346794 : elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3101 : NameStr(classForm->relname),
3102 : vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3103 : else
3104 0 : elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3105 : NameStr(classForm->relname),
3106 : vactuples, vacthresh, anltuples, anlthresh);
3107 :
3108 : /* Determine if this table needs vacuum or analyze. */
3109 510322 : *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3110 163528 : (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3111 346794 : *doanalyze = (anltuples > anlthresh);
3112 : }
3113 : else
3114 : {
3115 : /*
3116 : * Skip a table not found in stat hash, unless we have to force vacuum
3117 : * for anti-wrap purposes. If it's not acted upon, there's no need to
3118 : * vacuum it.
3119 : */
3120 6832 : *dovacuum = force_vacuum;
3121 6832 : *doanalyze = false;
3122 : }
3123 :
3124 : /* ANALYZE refuses to work with pg_statistic */
3125 353626 : if (relid == StatisticRelationId)
3126 3224 : *doanalyze = false;
3127 : }
3128 :
3129 : /*
3130 : * autovacuum_do_vac_analyze
3131 : * Vacuum and/or analyze the specified table
3132 : *
3133 : * We expect the caller to have switched into a memory context that won't
3134 : * disappear at transaction commit.
3135 : */
3136 : static void
3137 92822 : autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
3138 : {
3139 : RangeVar *rangevar;
3140 : VacuumRelation *rel;
3141 : List *rel_list;
3142 : MemoryContext vac_context;
3143 :
3144 : /* Let pgstat know what we're doing */
3145 92822 : autovac_report_activity(tab);
3146 :
3147 : /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3148 92822 : rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3149 92822 : rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3150 92822 : rel_list = list_make1(rel);
3151 :
3152 92822 : vac_context = AllocSetContextCreate(CurrentMemoryContext,
3153 : "Vacuum",
3154 : ALLOCSET_DEFAULT_SIZES);
3155 :
3156 92822 : vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3157 :
3158 92822 : MemoryContextDelete(vac_context);
3159 92822 : }
3160 :
3161 : /*
3162 : * autovac_report_activity
3163 : * Report to pgstat what autovacuum is doing
3164 : *
3165 : * We send a SQL string corresponding to what the user would see if the
3166 : * equivalent command was to be issued manually.
3167 : *
3168 : * Note we assume that we are going to report the next command as soon as we're
3169 : * done with the current one, and exit right after the last one, so we don't
3170 : * bother to report "<IDLE>" or some such.
3171 : */
3172 : static void
3173 92822 : autovac_report_activity(autovac_table *tab)
3174 : {
3175 : #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3176 : char activity[MAX_AUTOVAC_ACTIV_LEN];
3177 : int len;
3178 :
3179 : /* Report the command and possible options */
3180 92822 : if (tab->at_params.options & VACOPT_VACUUM)
3181 92624 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3182 : "autovacuum: VACUUM%s",
3183 92624 : tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3184 : else
3185 198 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3186 : "autovacuum: ANALYZE");
3187 :
3188 : /*
3189 : * Report the qualified name of the relation.
3190 : */
3191 92822 : len = strlen(activity);
3192 :
3193 92822 : snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3194 : " %s.%s%s", tab->at_nspname, tab->at_relname,
3195 92822 : tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3196 :
3197 : /* Set statement_timestamp() to current time for pg_stat_activity */
3198 92822 : SetCurrentStatementStartTimestamp();
3199 :
3200 92822 : pgstat_report_activity(STATE_RUNNING, activity);
3201 92822 : }
3202 :
3203 : /*
3204 : * autovac_report_workitem
3205 : * Report to pgstat that autovacuum is processing a work item
3206 : */
3207 : static void
3208 6 : autovac_report_workitem(AutoVacuumWorkItem *workitem,
3209 : const char *nspname, const char *relname)
3210 : {
3211 : char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3212 : char blk[12 + 2];
3213 : int len;
3214 :
3215 6 : switch (workitem->avw_type)
3216 : {
3217 6 : case AVW_BRINSummarizeRange:
3218 6 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3219 : "autovacuum: BRIN summarize");
3220 6 : break;
3221 : }
3222 :
3223 : /*
3224 : * Report the qualified name of the relation, and the block number if any
3225 : */
3226 6 : len = strlen(activity);
3227 :
3228 6 : if (BlockNumberIsValid(workitem->avw_blockNumber))
3229 6 : snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3230 : else
3231 0 : blk[0] = '\0';
3232 :
3233 6 : snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3234 : " %s.%s%s", nspname, relname, blk);
3235 :
3236 : /* Set statement_timestamp() to current time for pg_stat_activity */
3237 6 : SetCurrentStatementStartTimestamp();
3238 :
3239 6 : pgstat_report_activity(STATE_RUNNING, activity);
3240 6 : }
3241 :
3242 : /*
3243 : * AutoVacuumingActive
3244 : * Check GUC vars and report whether the autovacuum process should be
3245 : * running.
3246 : */
3247 : bool
3248 417764 : AutoVacuumingActive(void)
3249 : {
3250 417764 : if (!autovacuum_start_daemon || !pgstat_track_counts)
3251 8850 : return false;
3252 408914 : return true;
3253 : }
3254 :
3255 : /*
3256 : * Request one work item to the next autovacuum run processing our database.
3257 : * Return false if the request can't be recorded.
3258 : */
3259 : bool
3260 6 : AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId,
3261 : BlockNumber blkno)
3262 : {
3263 : int i;
3264 6 : bool result = false;
3265 :
3266 6 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3267 :
3268 : /*
3269 : * Locate an unused work item and fill it with the given data.
3270 : */
3271 12 : for (i = 0; i < NUM_WORKITEMS; i++)
3272 : {
3273 12 : AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i];
3274 :
3275 12 : if (workitem->avw_used)
3276 6 : continue;
3277 :
3278 6 : workitem->avw_used = true;
3279 6 : workitem->avw_active = false;
3280 6 : workitem->avw_type = type;
3281 6 : workitem->avw_database = MyDatabaseId;
3282 6 : workitem->avw_relation = relationId;
3283 6 : workitem->avw_blockNumber = blkno;
3284 6 : result = true;
3285 :
3286 : /* done */
3287 6 : break;
3288 : }
3289 :
3290 6 : LWLockRelease(AutovacuumLock);
3291 :
3292 6 : return result;
3293 : }
3294 :
3295 : /*
3296 : * autovac_init
3297 : * This is called at postmaster initialization.
3298 : *
3299 : * All we do here is annoy the user if he got it wrong.
3300 : */
3301 : void
3302 1644 : autovac_init(void)
3303 : {
3304 1644 : if (!autovacuum_start_daemon)
3305 222 : return;
3306 1422 : else if (!pgstat_track_counts)
3307 0 : ereport(WARNING,
3308 : (errmsg("autovacuum not started because of misconfiguration"),
3309 : errhint("Enable the \"track_counts\" option.")));
3310 : else
3311 1422 : check_av_worker_gucs();
3312 : }
3313 :
3314 : /*
3315 : * AutoVacuumShmemSize
3316 : * Compute space needed for autovacuum-related shared memory
3317 : */
3318 : Size
3319 5826 : AutoVacuumShmemSize(void)
3320 : {
3321 : Size size;
3322 :
3323 : /*
3324 : * Need the fixed struct and the array of WorkerInfoData.
3325 : */
3326 5826 : size = sizeof(AutoVacuumShmemStruct);
3327 5826 : size = MAXALIGN(size);
3328 5826 : size = add_size(size, mul_size(autovacuum_worker_slots,
3329 : sizeof(WorkerInfoData)));
3330 5826 : return size;
3331 : }
3332 :
3333 : /*
3334 : * AutoVacuumShmemInit
3335 : * Allocate and initialize autovacuum-related shared memory
3336 : */
3337 : void
3338 2032 : AutoVacuumShmemInit(void)
3339 : {
3340 : bool found;
3341 :
3342 2032 : AutoVacuumShmem = (AutoVacuumShmemStruct *)
3343 2032 : ShmemInitStruct("AutoVacuum Data",
3344 : AutoVacuumShmemSize(),
3345 : &found);
3346 :
3347 2032 : if (!IsUnderPostmaster)
3348 : {
3349 : WorkerInfo worker;
3350 : int i;
3351 :
3352 : Assert(!found);
3353 :
3354 2032 : AutoVacuumShmem->av_launcherpid = 0;
3355 2032 : dclist_init(&AutoVacuumShmem->av_freeWorkers);
3356 2032 : dlist_init(&AutoVacuumShmem->av_runningWorkers);
3357 2032 : AutoVacuumShmem->av_startingWorker = NULL;
3358 2032 : memset(AutoVacuumShmem->av_workItems, 0,
3359 : sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3360 :
3361 2032 : worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3362 : MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3363 :
3364 : /* initialize the WorkerInfo free list */
3365 24534 : for (i = 0; i < autovacuum_worker_slots; i++)
3366 : {
3367 22502 : dclist_push_head(&AutoVacuumShmem->av_freeWorkers,
3368 22502 : &worker[i].wi_links);
3369 22502 : pg_atomic_init_flag(&worker[i].wi_dobalance);
3370 : }
3371 :
3372 2032 : pg_atomic_init_u32(&AutoVacuumShmem->av_nworkersForBalance, 0);
3373 :
3374 : }
3375 : else
3376 : Assert(found);
3377 2032 : }
3378 :
3379 : /*
3380 : * GUC check_hook for autovacuum_work_mem
3381 : */
3382 : bool
3383 2102 : check_autovacuum_work_mem(int *newval, void **extra, GucSource source)
3384 : {
3385 : /*
3386 : * -1 indicates fallback.
3387 : *
3388 : * If we haven't yet changed the boot_val default of -1, just let it be.
3389 : * Autovacuum will look to maintenance_work_mem instead.
3390 : */
3391 2102 : if (*newval == -1)
3392 2098 : return true;
3393 :
3394 : /*
3395 : * We clamp manually-set values to at least 64kB. Since
3396 : * maintenance_work_mem is always set to at least this value, do the same
3397 : * here.
3398 : */
3399 4 : if (*newval < 64)
3400 4 : *newval = 64;
3401 :
3402 4 : return true;
3403 : }
3404 :
3405 : /*
3406 : * Returns whether there is a free autovacuum worker slot available.
3407 : */
3408 : static bool
3409 21432 : av_worker_available(void)
3410 : {
3411 : int free_slots;
3412 : int reserved_slots;
3413 :
3414 21432 : free_slots = dclist_count(&AutoVacuumShmem->av_freeWorkers);
3415 :
3416 21432 : reserved_slots = autovacuum_worker_slots - autovacuum_max_workers;
3417 21432 : reserved_slots = Max(0, reserved_slots);
3418 :
3419 21432 : return free_slots > reserved_slots;
3420 : }
3421 :
3422 : /*
3423 : * Emits a WARNING if autovacuum_worker_slots < autovacuum_max_workers.
3424 : */
3425 : static void
3426 1422 : check_av_worker_gucs(void)
3427 : {
3428 1422 : if (autovacuum_worker_slots < autovacuum_max_workers)
3429 0 : ereport(WARNING,
3430 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3431 : errmsg("\"autovacuum_max_workers\" (%d) should be less than or equal to \"autovacuum_worker_slots\" (%d)",
3432 : autovacuum_max_workers, autovacuum_worker_slots),
3433 : errdetail("The server will only start up to \"autovacuum_worker_slots\" (%d) autovacuum workers at a given time.",
3434 : autovacuum_worker_slots)));
3435 1422 : }
|