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 748 : 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 748 : if (PostmasterContext)
376 : {
377 748 : MemoryContextDelete(PostmasterContext);
378 748 : PostmasterContext = NULL;
379 : }
380 :
381 748 : MyBackendType = B_AUTOVAC_LAUNCHER;
382 748 : init_ps_display(NULL);
383 :
384 748 : ereport(DEBUG1,
385 : (errmsg_internal("autovacuum launcher started")));
386 :
387 748 : 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 748 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
398 748 : pqsignal(SIGINT, StatementCancelHandler);
399 748 : pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
400 : /* SIGQUIT handler was already set up by InitPostmasterChild */
401 :
402 748 : InitializeTimeouts(); /* establishes SIGALRM handler */
403 :
404 748 : pqsignal(SIGPIPE, SIG_IGN);
405 748 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
406 748 : pqsignal(SIGUSR2, avl_sigusr2_handler);
407 748 : pqsignal(SIGFPE, FloatExceptionHandler);
408 748 : 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 748 : InitProcess();
415 :
416 : /* Early initialization */
417 748 : BaseInit();
418 :
419 748 : InitPostgres(NULL, InvalidOid, NULL, InvalidOid, 0, NULL);
420 :
421 748 : 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 748 : AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
429 : "Autovacuum Launcher",
430 : ALLOCSET_DEFAULT_SIZES);
431 748 : 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 748 : 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 748 : PG_exception_stack = &local_sigjmp_buf;
509 :
510 : /* must unblock signals before calling rebuild_database_list */
511 748 : 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 748 : 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 748 : 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 748 : SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
531 748 : SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
532 748 : SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
533 748 : 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 748 : 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 748 : 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 748 : if (!AutoVacuumingActive())
555 : {
556 0 : if (!ShutdownRequestPending)
557 0 : do_start_worker();
558 0 : proc_exit(0); /* done */
559 : }
560 :
561 748 : 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 748 : rebuild_database_list(InvalidOid);
571 :
572 : /* loop until shutdown request */
573 11652 : while (!ShutdownRequestPending)
574 : {
575 : struct timeval nap;
576 11648 : 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 11648 : 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 11648 : (void) WaitLatch(MyLatch,
593 : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
594 11648 : (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
595 : WAIT_EVENT_AUTOVACUUM_MAIN);
596 :
597 11642 : ResetLatch(MyLatch);
598 :
599 11642 : ProcessAutoVacLauncherInterrupts();
600 :
601 : /*
602 : * a worker finished, or postmaster signaled failure to start a worker
603 : */
604 10904 : if (got_SIGUSR2)
605 : {
606 6824 : got_SIGUSR2 = false;
607 :
608 : /* rebalance cost limits, if needed */
609 6824 : if (AutoVacuumShmem->av_signal[AutoVacRebalance])
610 : {
611 3406 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
612 3406 : AutoVacuumShmem->av_signal[AutoVacRebalance] = false;
613 3406 : autovac_recalculate_workers_for_balance();
614 3406 : LWLockRelease(AutovacuumLock);
615 : }
616 :
617 6824 : 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 3930 : 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 10904 : current_time = GetCurrentTimestamp();
644 10904 : LWLockAcquire(AutovacuumLock, LW_SHARED);
645 :
646 10904 : can_launch = av_worker_available();
647 :
648 10904 : if (AutoVacuumShmem->av_startingWorker != NULL)
649 : {
650 : int waittime;
651 68 : 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 68 : waittime = Min(autovacuum_naptime, 60) * 1000;
669 68 : 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 68 : can_launch = false;
698 : }
699 10904 : LWLockRelease(AutovacuumLock); /* either shared or exclusive */
700 :
701 : /* if we can't do anything, just go back to sleep */
702 10904 : if (!can_launch)
703 3930 : continue;
704 :
705 : /* We're OK to start a new worker */
706 :
707 6974 : 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 6 : 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 6968 : 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 6968 : if (TimestampDifferenceExceeds(avdb->adl_next_worker,
735 : current_time, 0))
736 3422 : launch_worker(current_time);
737 : }
738 : }
739 :
740 4 : AutoVacLauncherShutdown();
741 : }
742 :
743 : /*
744 : * Process any new interrupts.
745 : */
746 : static void
747 11642 : ProcessAutoVacLauncherInterrupts(void)
748 : {
749 : /* the normal shutdown case */
750 11642 : if (ShutdownRequestPending)
751 738 : AutoVacLauncherShutdown();
752 :
753 10904 : if (ConfigReloadPending)
754 : {
755 72 : int autovacuum_max_workers_prev = autovacuum_max_workers;
756 :
757 72 : ConfigReloadPending = false;
758 72 : ProcessConfigFile(PGC_SIGHUP);
759 :
760 : /* shutdown requested in config file? */
761 72 : 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 72 : 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 72 : rebuild_database_list(InvalidOid);
774 : }
775 :
776 : /* Process barrier events */
777 10904 : if (ProcSignalBarrierPending)
778 52 : ProcessProcSignalBarrier();
779 :
780 : /* Perform logging of memory contexts of this process */
781 10904 : if (LogMemoryContextPending)
782 0 : ProcessLogMemoryContextInterrupt();
783 :
784 : /* Process sinval catchup interrupts that happened while sleeping */
785 10904 : ProcessCatchupInterrupt();
786 10904 : }
787 :
788 : /*
789 : * Perform a normal exit from the autovac launcher.
790 : */
791 : static void
792 742 : AutoVacLauncherShutdown(void)
793 : {
794 742 : ereport(DEBUG1,
795 : (errmsg_internal("autovacuum launcher shutting down")));
796 742 : AutoVacuumShmem->av_launcherpid = 0;
797 :
798 742 : 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 11770 : 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 11770 : if (!canlaunch)
818 : {
819 7088 : nap->tv_sec = autovacuum_naptime;
820 7088 : nap->tv_usec = 0;
821 : }
822 4682 : else if (!dlist_is_empty(&DatabaseList))
823 : {
824 4638 : TimestampTz current_time = GetCurrentTimestamp();
825 : TimestampTz next_wakeup;
826 : avl_dbase *avdb;
827 : long secs;
828 : int usecs;
829 :
830 4638 : avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
831 :
832 4638 : next_wakeup = avdb->adl_next_worker;
833 4638 : TimestampDifference(current_time, next_wakeup, &secs, &usecs);
834 :
835 4638 : nap->tv_sec = secs;
836 4638 : nap->tv_usec = usecs;
837 : }
838 : else
839 : {
840 : /* list is empty, sleep for whole autovacuum_naptime seconds */
841 44 : nap->tv_sec = autovacuum_naptime;
842 44 : 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 11770 : if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
856 : {
857 122 : rebuild_database_list(InvalidOid);
858 122 : launcher_determine_sleep(canlaunch, true, nap);
859 122 : return;
860 : }
861 :
862 : /* The smallest time we'll allow the launcher to sleep. */
863 11648 : if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
864 : {
865 480 : nap->tv_sec = 0;
866 480 : 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 11648 : if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME)
876 20 : 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 30 : entry = pgstat_fetch_stat_dbentry(newdb);
946 30 : if (entry != NULL)
947 : {
948 : /* we assume it isn't found because the hash was just created */
949 24 : db = hash_search(dbhash, &newdb, HASH_ENTER, NULL);
950 :
951 : /* hash_search already filled in the key */
952 24 : db->adl_score = score++;
953 : /* next_worker is filled in later */
954 : }
955 : }
956 :
957 : /* Now insert the databases from the existing list */
958 1486 : dlist_foreach(iter, &DatabaseList)
959 : {
960 514 : 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 514 : entry = pgstat_fetch_stat_dbentry(avdb->adl_datid);
970 514 : if (entry == NULL)
971 0 : continue;
972 :
973 514 : db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found);
974 :
975 514 : if (!found)
976 : {
977 : /* hash_search already filled in the key */
978 514 : 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 1636 : continue;
996 :
997 1592 : 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 1592 : if (!found)
1000 : {
1001 : /* hash_search already filled in the key */
1002 1054 : 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 934 : dbary = palloc(nelems * sizeof(avl_dbase));
1023 :
1024 934 : i = 0;
1025 934 : hash_seq_init(&seq, dbhash);
1026 2526 : while ((db = hash_seq_search(&seq)) != NULL)
1027 1592 : memcpy(&(dbary[i++]), db, sizeof(avl_dbase));
1028 :
1029 : /* sort the array */
1030 934 : 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 934 : millis_increment = 1000.0 * autovacuum_naptime / nelems;
1040 934 : if (millis_increment <= MIN_AUTOVAC_SLEEPTIME)
1041 0 : millis_increment = MIN_AUTOVAC_SLEEPTIME * 1.1;
1042 :
1043 934 : 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 2526 : for (i = 0; i < nelems; i++)
1050 : {
1051 1592 : db = &(dbary[i]);
1052 :
1053 1592 : current_time = TimestampTzPlusMilliseconds(current_time,
1054 : millis_increment);
1055 1592 : db->adl_next_worker = current_time;
1056 :
1057 : /* later elements should go closer to the head of the list */
1058 1592 : dlist_push_head(&DatabaseList, &db->adl_node);
1059 : }
1060 : }
1061 :
1062 : /* all done, clean up memory */
1063 972 : if (DatabaseListCxt != NULL)
1064 224 : 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 938 : db_comparator(const void *a, const void *b)
1073 : {
1074 1876 : return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
1075 938 : ((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 3428 : 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 3428 : bool skipit = false;
1101 3428 : Oid retval = InvalidOid;
1102 : MemoryContext tmpcxt,
1103 : oldcxt;
1104 :
1105 : /* return quickly when there are no free workers */
1106 3428 : LWLockAcquire(AutovacuumLock, LW_SHARED);
1107 3428 : if (!av_worker_available())
1108 : {
1109 0 : LWLockRelease(AutovacuumLock);
1110 0 : return InvalidOid;
1111 : }
1112 3428 : 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 3428 : tmpcxt = AllocSetContextCreate(CurrentMemoryContext,
1119 : "Autovacuum start worker (tmp)",
1120 : ALLOCSET_DEFAULT_SIZES);
1121 3428 : oldcxt = MemoryContextSwitchTo(tmpcxt);
1122 :
1123 : /* Get a list of databases */
1124 3428 : 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 3428 : recentXid = ReadNextTransactionId();
1132 3428 : 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 3428 : if (xidForceLimit < FirstNormalTransactionId)
1136 0 : xidForceLimit -= FirstNormalTransactionId;
1137 :
1138 : /* Also determine the oldest datminmxid we will consider. */
1139 3428 : recentMulti = ReadNextMultiXactId();
1140 3428 : multiForceLimit = recentMulti - MultiXactMemberFreezeThreshold();
1141 3428 : 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 3428 : avdb = NULL;
1166 3428 : for_xid_wrap = false;
1167 3428 : for_multi_wrap = false;
1168 3428 : current_time = GetCurrentTimestamp();
1169 13802 : foreach(cell, dblist)
1170 : {
1171 10374 : avw_dbase *tmp = lfirst(cell);
1172 : dlist_iter iter;
1173 :
1174 : /* Check to see if this one is at risk of wraparound */
1175 10374 : if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit))
1176 : {
1177 8634 : if (avdb == NULL ||
1178 3378 : TransactionIdPrecedes(tmp->adw_frozenxid,
1179 : avdb->adw_frozenxid))
1180 2002 : avdb = tmp;
1181 5256 : for_xid_wrap = true;
1182 7850 : continue;
1183 : }
1184 5118 : else if (for_xid_wrap)
1185 202 : continue; /* ignore not-at-risk DBs */
1186 4916 : 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 4916 : else if (for_multi_wrap)
1195 0 : continue; /* ignore not-at-risk DBs */
1196 :
1197 : /* Find pgstat entry if any */
1198 4916 : 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 4916 : if (!tmp->adw_entry)
1205 128 : 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 4788 : skipit = false;
1215 :
1216 9770 : dlist_reverse_foreach(iter, &DatabaseList)
1217 : {
1218 9720 : avl_dbase *dbp = dlist_container(avl_dbase, adl_node, iter.cur);
1219 :
1220 9720 : 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 4738 : if (!TimestampDifferenceExceeds(dbp->adl_next_worker,
1227 2264 : current_time, 0) &&
1228 2264 : !TimestampDifferenceExceeds(current_time,
1229 : dbp->adl_next_worker,
1230 : autovacuum_naptime * 1000))
1231 2264 : skipit = true;
1232 :
1233 4738 : break;
1234 : }
1235 : }
1236 4788 : if (skipit)
1237 2264 : 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 2524 : if (avdb == NULL ||
1244 980 : tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time)
1245 1868 : avdb = tmp;
1246 : }
1247 :
1248 : /* Found a database -- process it */
1249 3428 : if (avdb != NULL)
1250 : {
1251 : WorkerInfo worker;
1252 : dlist_node *wptr;
1253 :
1254 3422 : 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 3422 : wptr = dclist_pop_head_node(&AutoVacuumShmem->av_freeWorkers);
1261 :
1262 3422 : worker = dlist_container(WorkerInfoData, wi_links, wptr);
1263 3422 : worker->wi_dboid = avdb->adw_datid;
1264 3422 : worker->wi_proc = NULL;
1265 3422 : worker->wi_launchtime = GetCurrentTimestamp();
1266 :
1267 3422 : AutoVacuumShmem->av_startingWorker = worker;
1268 :
1269 3422 : LWLockRelease(AutovacuumLock);
1270 :
1271 3422 : SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
1272 :
1273 3422 : retval = avdb->adw_datid;
1274 : }
1275 6 : 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 3428 : MemoryContextSwitchTo(oldcxt);
1285 3428 : MemoryContextDelete(tmpcxt);
1286 :
1287 3428 : 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 3428 : launch_worker(TimestampTz now)
1303 : {
1304 : Oid dbid;
1305 : dlist_iter iter;
1306 :
1307 3428 : dbid = do_start_worker();
1308 3428 : if (OidIsValid(dbid))
1309 : {
1310 3422 : 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 7236 : dlist_foreach(iter, &DatabaseList)
1317 : {
1318 7206 : avl_dbase *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
1319 :
1320 7206 : if (avdb->adl_datid == dbid)
1321 : {
1322 3392 : 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 3392 : avdb->adl_next_worker =
1329 3392 : TimestampTzPlusMilliseconds(now, autovacuum_naptime * 1000);
1330 :
1331 3392 : dlist_move_head(&DatabaseList, iter.cur);
1332 3392 : 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 3422 : if (!found)
1344 30 : rebuild_database_list(dbid);
1345 : }
1346 3428 : }
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 6824 : avl_sigusr2_handler(SIGNAL_ARGS)
1362 : {
1363 6824 : got_SIGUSR2 = true;
1364 6824 : SetLatch(MyLatch);
1365 6824 : }
1366 :
1367 :
1368 : /********************************************************************
1369 : * AUTOVACUUM WORKER CODE
1370 : ********************************************************************/
1371 :
1372 : /*
1373 : * Main entry point for autovacuum worker processes.
1374 : */
1375 : void
1376 3424 : 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 3424 : if (PostmasterContext)
1385 : {
1386 3424 : MemoryContextDelete(PostmasterContext);
1387 3424 : PostmasterContext = NULL;
1388 : }
1389 :
1390 3424 : MyBackendType = B_AUTOVAC_WORKER;
1391 3424 : 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 3424 : 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 3424 : pqsignal(SIGINT, StatementCancelHandler);
1407 3424 : pqsignal(SIGTERM, die);
1408 : /* SIGQUIT handler was already set up by InitPostmasterChild */
1409 :
1410 3424 : InitializeTimeouts(); /* establishes SIGALRM handler */
1411 :
1412 3424 : pqsignal(SIGPIPE, SIG_IGN);
1413 3424 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
1414 3424 : pqsignal(SIGUSR2, SIG_IGN);
1415 3424 : pqsignal(SIGFPE, FloatExceptionHandler);
1416 3424 : 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 3424 : InitProcess();
1423 :
1424 : /* Early initialization */
1425 3424 : 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 3424 : 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 3424 : PG_exception_stack = &local_sigjmp_buf;
1461 :
1462 3424 : 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 3424 : 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 3424 : 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 3424 : SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1484 3424 : SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1485 3424 : SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1486 3424 : 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 3424 : 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 3424 : if (synchronous_commit > SYNCHRONOUS_COMMIT_LOCAL_FLUSH)
1503 3424 : 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 3424 : 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 3424 : 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 3424 : if (AutoVacuumShmem->av_startingWorker != NULL)
1524 : {
1525 3424 : MyWorkerInfo = AutoVacuumShmem->av_startingWorker;
1526 3424 : dbid = MyWorkerInfo->wi_dboid;
1527 3424 : MyWorkerInfo->wi_proc = MyProc;
1528 :
1529 : /* insert into the running list */
1530 3424 : dlist_push_head(&AutoVacuumShmem->av_runningWorkers,
1531 3424 : &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 3424 : AutoVacuumShmem->av_startingWorker = NULL;
1538 3424 : LWLockRelease(AutovacuumLock);
1539 :
1540 3424 : on_shmem_exit(FreeWorkerInfo, 0);
1541 :
1542 : /* wake up the launcher */
1543 3424 : if (AutoVacuumShmem->av_launcherpid != 0)
1544 3424 : 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 3424 : 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 3424 : 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 3424 : InitPostgres(NULL, dbid, NULL, InvalidOid,
1577 : INIT_PG_OVERRIDE_ALLOW_CONNS,
1578 : dbname);
1579 3424 : SetProcessingMode(NormalProcessing);
1580 3424 : set_ps_display(dbname);
1581 3424 : ereport(DEBUG1,
1582 : (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
1583 :
1584 3424 : if (PostAuthDelay)
1585 0 : pg_usleep(PostAuthDelay * 1000000L);
1586 :
1587 : /* And do an appropriate amount of work */
1588 3424 : recentXid = ReadNextTransactionId();
1589 3424 : recentMulti = ReadNextMultiXactId();
1590 3424 : 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 3420 : proc_exit(0);
1600 : }
1601 :
1602 : /*
1603 : * Return a WorkerInfo to the free list
1604 : */
1605 : static void
1606 3424 : FreeWorkerInfo(int code, Datum arg)
1607 : {
1608 3424 : if (MyWorkerInfo != NULL)
1609 : {
1610 3424 : 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 3424 : AutovacuumLauncherPid = AutoVacuumShmem->av_launcherpid;
1625 :
1626 3424 : dlist_delete(&MyWorkerInfo->wi_links);
1627 3424 : MyWorkerInfo->wi_dboid = InvalidOid;
1628 3424 : MyWorkerInfo->wi_tableoid = InvalidOid;
1629 3424 : MyWorkerInfo->wi_sharedrel = false;
1630 3424 : MyWorkerInfo->wi_proc = NULL;
1631 3424 : MyWorkerInfo->wi_launchtime = 0;
1632 3424 : pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance);
1633 3424 : dclist_push_head(&AutoVacuumShmem->av_freeWorkers,
1634 3424 : &MyWorkerInfo->wi_links);
1635 : /* not mine anymore */
1636 3424 : MyWorkerInfo = NULL;
1637 :
1638 : /*
1639 : * now that we're inactive, cause a rebalancing of the surviving
1640 : * workers
1641 : */
1642 3424 : AutoVacuumShmem->av_signal[AutoVacRebalance] = true;
1643 3424 : LWLockRelease(AutovacuumLock);
1644 : }
1645 3424 : }
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 415888 : VacuumUpdateCosts(void)
1655 : {
1656 415888 : if (MyWorkerInfo)
1657 : {
1658 402288 : if (av_storage_param_cost_delay >= 0)
1659 0 : vacuum_cost_delay = av_storage_param_cost_delay;
1660 402288 : else if (autovacuum_vac_cost_delay >= 0)
1661 402288 : vacuum_cost_delay = autovacuum_vac_cost_delay;
1662 : else
1663 : /* fall back to VacuumCostDelay */
1664 0 : vacuum_cost_delay = VacuumCostDelay;
1665 :
1666 402288 : AutoVacuumUpdateCostLimit();
1667 : }
1668 : else
1669 : {
1670 : /* Must be explicit VACUUM or ANALYZE */
1671 13600 : vacuum_cost_delay = VacuumCostDelay;
1672 13600 : vacuum_cost_limit = VacuumCostLimit;
1673 : }
1674 :
1675 : /*
1676 : * If configuration changes are allowed to impact VacuumCostActive, make
1677 : * sure it is updated.
1678 : */
1679 415888 : if (VacuumFailsafeActive)
1680 : Assert(!VacuumCostActive);
1681 415888 : else if (vacuum_cost_delay > 0)
1682 402288 : VacuumCostActive = true;
1683 : else
1684 : {
1685 13600 : VacuumCostActive = false;
1686 13600 : 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 415888 : 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 415888 : }
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 408012 : AutoVacuumUpdateCostLimit(void)
1724 : {
1725 408012 : 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 408012 : 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 408012 : if (autovacuum_vac_cost_limit > 0)
1740 0 : vacuum_cost_limit = autovacuum_vac_cost_limit;
1741 : else
1742 408012 : vacuum_cost_limit = VacuumCostLimit;
1743 :
1744 : /* Only balance limit if no cost-related storage parameters specified */
1745 408012 : if (pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance))
1746 0 : return;
1747 :
1748 : Assert(vacuum_cost_limit > 0);
1749 :
1750 408012 : nworkers_for_balance = pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1751 :
1752 : /* There is at least 1 autovac worker (this worker) */
1753 408012 : if (nworkers_for_balance <= 0)
1754 0 : elog(ERROR, "nworkers_for_balance must be > 0");
1755 :
1756 408012 : 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 204550 : autovac_recalculate_workers_for_balance(void)
1770 : {
1771 : dlist_iter iter;
1772 : int orig_nworkers_for_balance;
1773 204550 : int nworkers_for_balance = 0;
1774 :
1775 : Assert(LWLockHeldByMe(AutovacuumLock));
1776 :
1777 204550 : orig_nworkers_for_balance =
1778 204550 : pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
1779 :
1780 658484 : dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers)
1781 : {
1782 453934 : WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
1783 :
1784 907868 : if (worker->wi_proc == NULL ||
1785 453934 : pg_atomic_unlocked_test_flag(&worker->wi_dobalance))
1786 8916 : continue;
1787 :
1788 445018 : nworkers_for_balance++;
1789 : }
1790 :
1791 204550 : if (nworkers_for_balance != orig_nworkers_for_balance)
1792 4090 : pg_atomic_write_u32(&AutoVacuumShmem->av_nworkersForBalance,
1793 : nworkers_for_balance);
1794 204550 : }
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 4400 : get_database_list(void)
1810 : {
1811 4400 : 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 4400 : resultcxt = CurrentMemoryContext;
1819 :
1820 : /*
1821 : * Start a transaction so we can access pg_database.
1822 : */
1823 4400 : StartTransactionCommand();
1824 :
1825 4400 : rel = table_open(DatabaseRelationId, AccessShareLock);
1826 4400 : scan = table_beginscan_catalog(rel, 0, NULL);
1827 :
1828 18008 : while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1829 : {
1830 13608 : 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 13608 : if (database_is_invalid_form(pgdatabase))
1839 : {
1840 6 : elog(DEBUG2,
1841 : "autovacuum: skipping invalid database \"%s\"",
1842 : NameStr(pgdatabase->datname));
1843 6 : 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 13602 : oldcxt = MemoryContextSwitchTo(resultcxt);
1853 :
1854 13602 : avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1855 :
1856 13602 : avdb->adw_datid = pgdatabase->oid;
1857 13602 : avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
1858 13602 : avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1859 13602 : avdb->adw_minmulti = pgdatabase->datminmxid;
1860 : /* this gets set later: */
1861 13602 : avdb->adw_entry = NULL;
1862 :
1863 13602 : dblist = lappend(dblist, avdb);
1864 13602 : MemoryContextSwitchTo(oldcxt);
1865 : }
1866 :
1867 4400 : table_endscan(scan);
1868 4400 : table_close(rel, AccessShareLock);
1869 :
1870 4400 : CommitTransactionCommand();
1871 :
1872 : /* Be sure to restore caller's memory context */
1873 4400 : MemoryContextSwitchTo(resultcxt);
1874 :
1875 4400 : 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 3424 : do_autovacuum(void)
1886 : {
1887 : Relation classRel;
1888 : HeapTuple tuple;
1889 : TableScanDesc relScan;
1890 : Form_pg_database dbForm;
1891 3424 : List *table_oids = NIL;
1892 3424 : 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 3424 : bool did_vacuum = false;
1901 3424 : 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 3424 : AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
1910 : "Autovacuum worker",
1911 : ALLOCSET_DEFAULT_SIZES);
1912 3424 : MemoryContextSwitchTo(AutovacMemCxt);
1913 :
1914 : /* Start a transaction so our commands have one to play into. */
1915 3424 : 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 3424 : INJECTION_POINT("autovacuum-worker-start", NULL);
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 3422 : 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 3422 : tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
1936 3422 : if (!HeapTupleIsValid(tuple))
1937 0 : elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
1938 3422 : dbForm = (Form_pg_database) GETSTRUCT(tuple);
1939 :
1940 3422 : if (dbForm->datistemplate || !dbForm->datallowconn)
1941 : {
1942 1234 : default_freeze_min_age = 0;
1943 1234 : default_freeze_table_age = 0;
1944 1234 : default_multixact_freeze_min_age = 0;
1945 1234 : default_multixact_freeze_table_age = 0;
1946 : }
1947 : else
1948 : {
1949 2188 : default_freeze_min_age = vacuum_freeze_min_age;
1950 2188 : default_freeze_table_age = vacuum_freeze_table_age;
1951 2188 : default_multixact_freeze_min_age = vacuum_multixact_freeze_min_age;
1952 2188 : default_multixact_freeze_table_age = vacuum_multixact_freeze_table_age;
1953 : }
1954 :
1955 3422 : ReleaseSysCache(tuple);
1956 :
1957 : /* StartTransactionCommand changed elsewhere */
1958 3422 : MemoryContextSwitchTo(AutovacMemCxt);
1959 :
1960 3422 : classRel = table_open(RelationRelationId, AccessShareLock);
1961 :
1962 : /* create a copy so we can use it after closing pg_class */
1963 3422 : pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
1964 :
1965 : /* create hash table for toast <-> main relid mapping */
1966 3422 : ctl.keysize = sizeof(Oid);
1967 3422 : ctl.entrysize = sizeof(av_relation);
1968 :
1969 3422 : 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 3422 : 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 1443100 : while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
1995 : {
1996 1439678 : 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 1439678 : if (classForm->relkind != RELKIND_RELATION &&
2005 1200480 : classForm->relkind != RELKIND_MATVIEW)
2006 1200410 : continue;
2007 :
2008 239286 : 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 239286 : 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 18 : 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 18 : continue;
2033 : }
2034 :
2035 : /* Fetch reloptions and the pgstat entry for this table */
2036 239268 : relopts = extract_autovac_opts(tuple, pg_class_desc);
2037 239268 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2038 : relid);
2039 :
2040 : /* Check if it needs vacuum or analyze */
2041 239268 : 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 239268 : if (dovacuum || doanalyze)
2047 128692 : 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 239268 : if (OidIsValid(classForm->reltoastrelid))
2055 : {
2056 : av_relation *hentry;
2057 : bool found;
2058 :
2059 275448 : hentry = hash_search(table_toast_map,
2060 137724 : &classForm->reltoastrelid,
2061 : HASH_ENTER, &found);
2062 :
2063 137724 : if (!found)
2064 : {
2065 : /* hash_search already filled in the key */
2066 137724 : hentry->ar_relid = relid;
2067 137724 : hentry->ar_hasrelopts = false;
2068 137724 : if (relopts != NULL)
2069 : {
2070 2838 : hentry->ar_hasrelopts = true;
2071 2838 : memcpy(&hentry->ar_reloptions, relopts,
2072 : sizeof(AutoVacOpts));
2073 : }
2074 : }
2075 : }
2076 :
2077 : /* Release stuff to avoid per-relation leakage */
2078 239268 : if (relopts)
2079 2898 : pfree(relopts);
2080 239268 : if (tabentry)
2081 235336 : pfree(tabentry);
2082 : }
2083 :
2084 3422 : table_endscan(relScan);
2085 :
2086 : /* second pass: check TOAST tables */
2087 3422 : ScanKeyInit(&key,
2088 : Anum_pg_class_relkind,
2089 : BTEqualStrategyNumber, F_CHAREQ,
2090 : CharGetDatum(RELKIND_TOASTVALUE));
2091 :
2092 3422 : relScan = table_beginscan_catalog(classRel, 1, &key);
2093 141148 : while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2094 : {
2095 137726 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
2096 : PgStat_StatTabEntry *tabentry;
2097 : Oid relid;
2098 : AutoVacOpts *relopts;
2099 137726 : bool free_relopts = false;
2100 : bool dovacuum;
2101 : bool doanalyze;
2102 : bool wraparound;
2103 :
2104 : /*
2105 : * We cannot safely process other backends' temp tables, so skip 'em.
2106 : */
2107 137726 : if (classForm->relpersistence == RELPERSISTENCE_TEMP)
2108 2 : continue;
2109 :
2110 137724 : relid = classForm->oid;
2111 :
2112 : /*
2113 : * fetch reloptions -- if this toast table does not have them, try the
2114 : * main rel
2115 : */
2116 137724 : relopts = extract_autovac_opts(tuple, pg_class_desc);
2117 137724 : if (relopts)
2118 4 : free_relopts = true;
2119 : else
2120 : {
2121 : av_relation *hentry;
2122 : bool found;
2123 :
2124 137720 : hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2125 137720 : if (found && hentry->ar_hasrelopts)
2126 2834 : relopts = &hentry->ar_reloptions;
2127 : }
2128 :
2129 : /* Fetch the pgstat entry for this table */
2130 137724 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2131 : relid);
2132 :
2133 137724 : relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2134 : effective_multixact_freeze_max_age,
2135 : &dovacuum, &doanalyze, &wraparound);
2136 :
2137 : /* ignore analyze for toast tables */
2138 137724 : if (dovacuum)
2139 73748 : table_oids = lappend_oid(table_oids, relid);
2140 :
2141 : /* Release stuff to avoid leakage */
2142 137724 : if (free_relopts)
2143 4 : pfree(relopts);
2144 137724 : if (tabentry)
2145 134796 : pfree(tabentry);
2146 : }
2147 :
2148 3422 : table_endscan(relScan);
2149 3422 : table_close(classRel, AccessShareLock);
2150 :
2151 : /*
2152 : * Recheck orphan temporary tables, and if they still seem orphaned, drop
2153 : * them. We'll eat a transaction per dropped table, which might seem
2154 : * excessive, but we should only need to do anything as a result of a
2155 : * previous backend crash, so this should not happen often enough to
2156 : * justify "optimizing". Using separate transactions ensures that we
2157 : * don't bloat the lock table if there are many temp tables to be dropped,
2158 : * and it ensures that we don't lose work if a deletion attempt fails.
2159 : */
2160 3422 : foreach(cell, orphan_oids)
2161 : {
2162 0 : Oid relid = lfirst_oid(cell);
2163 : Form_pg_class classForm;
2164 : ObjectAddress object;
2165 :
2166 : /*
2167 : * Check for user-requested abort.
2168 : */
2169 0 : CHECK_FOR_INTERRUPTS();
2170 :
2171 : /*
2172 : * Try to lock the table. If we can't get the lock immediately,
2173 : * somebody else is using (or dropping) the table, so it's not our
2174 : * concern anymore. Having the lock prevents race conditions below.
2175 : */
2176 0 : if (!ConditionalLockRelationOid(relid, AccessExclusiveLock))
2177 0 : continue;
2178 :
2179 : /*
2180 : * Re-fetch the pg_class tuple and re-check whether it still seems to
2181 : * be an orphaned temp table. If it's not there or no longer the same
2182 : * relation, ignore it.
2183 : */
2184 0 : tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2185 0 : if (!HeapTupleIsValid(tuple))
2186 : {
2187 : /* be sure to drop useless lock so we don't bloat lock table */
2188 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2189 0 : continue;
2190 : }
2191 0 : classForm = (Form_pg_class) GETSTRUCT(tuple);
2192 :
2193 : /*
2194 : * Make all the same tests made in the loop above. In event of OID
2195 : * counter wraparound, the pg_class entry we have now might be
2196 : * completely unrelated to the one we saw before.
2197 : */
2198 0 : if (!((classForm->relkind == RELKIND_RELATION ||
2199 0 : classForm->relkind == RELKIND_MATVIEW) &&
2200 0 : classForm->relpersistence == RELPERSISTENCE_TEMP))
2201 : {
2202 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2203 0 : continue;
2204 : }
2205 :
2206 0 : if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE)
2207 : {
2208 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2209 0 : continue;
2210 : }
2211 :
2212 : /*
2213 : * Try to lock the temp namespace, too. Even though we have lock on
2214 : * the table itself, there's a risk of deadlock against an incoming
2215 : * backend trying to clean out the temp namespace, in case this table
2216 : * has dependencies (such as sequences) that the backend's
2217 : * performDeletion call might visit in a different order. If we can
2218 : * get AccessShareLock on the namespace, that's sufficient to ensure
2219 : * we're not running concurrently with RemoveTempRelations. If we
2220 : * can't, back off and let RemoveTempRelations do its thing.
2221 : */
2222 0 : if (!ConditionalLockDatabaseObject(NamespaceRelationId,
2223 : classForm->relnamespace, 0,
2224 : AccessShareLock))
2225 : {
2226 0 : UnlockRelationOid(relid, AccessExclusiveLock);
2227 0 : continue;
2228 : }
2229 :
2230 : /* OK, let's delete it */
2231 0 : ereport(LOG,
2232 : (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
2233 : get_database_name(MyDatabaseId),
2234 : get_namespace_name(classForm->relnamespace),
2235 : NameStr(classForm->relname))));
2236 :
2237 : /*
2238 : * Deletion might involve TOAST table access, so ensure we have a
2239 : * valid snapshot.
2240 : */
2241 0 : PushActiveSnapshot(GetTransactionSnapshot());
2242 :
2243 0 : object.classId = RelationRelationId;
2244 0 : object.objectId = relid;
2245 0 : object.objectSubId = 0;
2246 0 : performDeletion(&object, DROP_CASCADE,
2247 : PERFORM_DELETION_INTERNAL |
2248 : PERFORM_DELETION_QUIETLY |
2249 : PERFORM_DELETION_SKIP_EXTENSIONS);
2250 :
2251 : /*
2252 : * To commit the deletion, end current transaction and start a new
2253 : * one. Note this also releases the locks we took.
2254 : */
2255 0 : PopActiveSnapshot();
2256 0 : CommitTransactionCommand();
2257 0 : StartTransactionCommand();
2258 :
2259 : /* StartTransactionCommand changed current memory context */
2260 0 : MemoryContextSwitchTo(AutovacMemCxt);
2261 : }
2262 :
2263 : /*
2264 : * Optionally, create a buffer access strategy object for VACUUM to use.
2265 : * We use the same BufferAccessStrategy object for all tables VACUUMed by
2266 : * this worker to prevent autovacuum from blowing out shared buffers.
2267 : *
2268 : * VacuumBufferUsageLimit being set to 0 results in
2269 : * GetAccessStrategyWithSize returning NULL, effectively meaning we can
2270 : * use up to all of shared buffers.
2271 : *
2272 : * If we later enter failsafe mode on any of the tables being vacuumed, we
2273 : * will cease use of the BufferAccessStrategy only for that table.
2274 : *
2275 : * XXX should we consider adding code to adjust the size of this if
2276 : * VacuumBufferUsageLimit changes?
2277 : */
2278 3422 : bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, VacuumBufferUsageLimit);
2279 :
2280 : /*
2281 : * create a memory context to act as fake PortalContext, so that the
2282 : * contexts created in the vacuum code are cleaned up for each table.
2283 : */
2284 3422 : PortalContext = AllocSetContextCreate(AutovacMemCxt,
2285 : "Autovacuum Portal",
2286 : ALLOCSET_DEFAULT_SIZES);
2287 :
2288 : /*
2289 : * Perform operations on collected tables.
2290 : */
2291 205816 : foreach(cell, table_oids)
2292 : {
2293 202396 : Oid relid = lfirst_oid(cell);
2294 : HeapTuple classTup;
2295 : autovac_table *tab;
2296 : bool isshared;
2297 : bool skipit;
2298 : dlist_iter iter;
2299 :
2300 202396 : CHECK_FOR_INTERRUPTS();
2301 :
2302 : /*
2303 : * Check for config changes before processing each collected table.
2304 : */
2305 202396 : if (ConfigReloadPending)
2306 : {
2307 0 : ConfigReloadPending = false;
2308 0 : ProcessConfigFile(PGC_SIGHUP);
2309 :
2310 : /*
2311 : * You might be tempted to bail out if we see autovacuum is now
2312 : * disabled. Must resist that temptation -- this might be a
2313 : * for-wraparound emergency worker, in which case that would be
2314 : * entirely inappropriate.
2315 : */
2316 : }
2317 :
2318 : /*
2319 : * Find out whether the table is shared or not. (It's slightly
2320 : * annoying to fetch the syscache entry just for this, but in typical
2321 : * cases it adds little cost because table_recheck_autovac would
2322 : * refetch the entry anyway. We could buy that back by copying the
2323 : * tuple here and passing it to table_recheck_autovac, but that
2324 : * increases the odds of that function working with stale data.)
2325 : */
2326 202396 : classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
2327 202396 : if (!HeapTupleIsValid(classTup))
2328 1252 : continue; /* somebody deleted the rel, forget it */
2329 202396 : isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared;
2330 202396 : ReleaseSysCache(classTup);
2331 :
2332 : /*
2333 : * Hold schedule lock from here until we've claimed the table. We
2334 : * also need the AutovacuumLock to walk the worker array, but that one
2335 : * can just be a shared lock.
2336 : */
2337 202396 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2338 202396 : LWLockAcquire(AutovacuumLock, LW_SHARED);
2339 :
2340 : /*
2341 : * Check whether the table is being vacuumed concurrently by another
2342 : * worker.
2343 : */
2344 202396 : skipit = false;
2345 655164 : dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers)
2346 : {
2347 453948 : WorkerInfo worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
2348 :
2349 : /* ignore myself */
2350 453948 : if (worker == MyWorkerInfo)
2351 201850 : continue;
2352 :
2353 : /* ignore workers in other databases (unless table is shared) */
2354 252098 : if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
2355 0 : continue;
2356 :
2357 252098 : if (worker->wi_tableoid == relid)
2358 : {
2359 1180 : skipit = true;
2360 1180 : found_concurrent_worker = true;
2361 1180 : break;
2362 : }
2363 : }
2364 202396 : LWLockRelease(AutovacuumLock);
2365 202396 : if (skipit)
2366 : {
2367 1180 : LWLockRelease(AutovacuumScheduleLock);
2368 1180 : continue;
2369 : }
2370 :
2371 : /*
2372 : * Store the table's OID in shared memory before releasing the
2373 : * schedule lock, so that other workers don't try to vacuum it
2374 : * concurrently. (We claim it here so as not to hold
2375 : * AutovacuumScheduleLock while rechecking the stats.)
2376 : */
2377 201216 : MyWorkerInfo->wi_tableoid = relid;
2378 201216 : MyWorkerInfo->wi_sharedrel = isshared;
2379 201216 : LWLockRelease(AutovacuumScheduleLock);
2380 :
2381 : /*
2382 : * Check whether pgstat data still says we need to vacuum this table.
2383 : * It could have changed if something else processed the table while
2384 : * we weren't looking. This doesn't entirely close the race condition,
2385 : * but it is very small.
2386 : */
2387 201216 : MemoryContextSwitchTo(AutovacMemCxt);
2388 201216 : tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
2389 : effective_multixact_freeze_max_age);
2390 201216 : if (tab == NULL)
2391 : {
2392 : /* someone else vacuumed the table, or it went away */
2393 72 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2394 72 : MyWorkerInfo->wi_tableoid = InvalidOid;
2395 72 : MyWorkerInfo->wi_sharedrel = false;
2396 72 : LWLockRelease(AutovacuumScheduleLock);
2397 72 : continue;
2398 : }
2399 :
2400 : /*
2401 : * Save the cost-related storage parameter values in global variables
2402 : * for reference when updating vacuum_cost_delay and vacuum_cost_limit
2403 : * during vacuuming this table.
2404 : */
2405 201144 : av_storage_param_cost_delay = tab->at_storage_param_vac_cost_delay;
2406 201144 : av_storage_param_cost_limit = tab->at_storage_param_vac_cost_limit;
2407 :
2408 : /*
2409 : * We only expect this worker to ever set the flag, so don't bother
2410 : * checking the return value. We shouldn't have to retry.
2411 : */
2412 201144 : if (tab->at_dobalance)
2413 201144 : pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance);
2414 : else
2415 0 : pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance);
2416 :
2417 201144 : LWLockAcquire(AutovacuumLock, LW_SHARED);
2418 201144 : autovac_recalculate_workers_for_balance();
2419 201144 : LWLockRelease(AutovacuumLock);
2420 :
2421 : /*
2422 : * We wait until this point to update cost delay and cost limit
2423 : * values, even though we reloaded the configuration file above, so
2424 : * that we can take into account the cost-related storage parameters.
2425 : */
2426 201144 : VacuumUpdateCosts();
2427 :
2428 :
2429 : /* clean up memory before each iteration */
2430 201144 : MemoryContextReset(PortalContext);
2431 :
2432 : /*
2433 : * Save the relation name for a possible error message, to avoid a
2434 : * catalog lookup in case of an error. If any of these return NULL,
2435 : * then the relation has been dropped since last we checked; skip it.
2436 : * Note: they must live in a long-lived memory context because we call
2437 : * vacuum and analyze in different transactions.
2438 : */
2439 :
2440 201144 : tab->at_relname = get_rel_name(tab->at_relid);
2441 201144 : tab->at_nspname = get_namespace_name(get_rel_namespace(tab->at_relid));
2442 201144 : tab->at_datname = get_database_name(MyDatabaseId);
2443 201144 : if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
2444 0 : goto deleted;
2445 :
2446 : /*
2447 : * We will abort vacuuming the current table if something errors out,
2448 : * and continue with the next one in schedule; in particular, this
2449 : * happens if we are interrupted with SIGINT.
2450 : */
2451 201144 : PG_TRY();
2452 : {
2453 : /* Use PortalContext for any per-table allocations */
2454 201144 : MemoryContextSwitchTo(PortalContext);
2455 :
2456 : /* have at it */
2457 201144 : autovacuum_do_vac_analyze(tab, bstrategy);
2458 :
2459 : /*
2460 : * Clear a possible query-cancel signal, to avoid a late reaction
2461 : * to an automatically-sent signal because of vacuuming the
2462 : * current table (we're done with it, so it would make no sense to
2463 : * cancel at this point.)
2464 : */
2465 201142 : QueryCancelPending = false;
2466 : }
2467 0 : PG_CATCH();
2468 : {
2469 : /*
2470 : * Abort the transaction, start a new one, and proceed with the
2471 : * next table in our list.
2472 : */
2473 0 : HOLD_INTERRUPTS();
2474 0 : if (tab->at_params.options & VACOPT_VACUUM)
2475 0 : errcontext("automatic vacuum of table \"%s.%s.%s\"",
2476 : tab->at_datname, tab->at_nspname, tab->at_relname);
2477 : else
2478 0 : errcontext("automatic analyze of table \"%s.%s.%s\"",
2479 : tab->at_datname, tab->at_nspname, tab->at_relname);
2480 0 : EmitErrorReport();
2481 :
2482 : /* this resets ProcGlobal->statusFlags[i] too */
2483 0 : AbortOutOfAnyTransaction();
2484 0 : FlushErrorState();
2485 0 : MemoryContextReset(PortalContext);
2486 :
2487 : /* restart our transaction for the following operations */
2488 0 : StartTransactionCommand();
2489 0 : RESUME_INTERRUPTS();
2490 : }
2491 201142 : PG_END_TRY();
2492 :
2493 : /* Make sure we're back in AutovacMemCxt */
2494 201142 : MemoryContextSwitchTo(AutovacMemCxt);
2495 :
2496 201142 : did_vacuum = true;
2497 :
2498 : /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
2499 :
2500 : /* be tidy */
2501 201142 : deleted:
2502 201142 : if (tab->at_datname != NULL)
2503 201142 : pfree(tab->at_datname);
2504 201142 : if (tab->at_nspname != NULL)
2505 201142 : pfree(tab->at_nspname);
2506 201142 : if (tab->at_relname != NULL)
2507 201142 : pfree(tab->at_relname);
2508 201142 : pfree(tab);
2509 :
2510 : /*
2511 : * Remove my info from shared memory. We set wi_dobalance on the
2512 : * assumption that we are more likely than not to vacuum a table with
2513 : * no cost-related storage parameters next, so we want to claim our
2514 : * share of I/O as soon as possible to avoid thrashing the global
2515 : * balance.
2516 : */
2517 201142 : LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
2518 201142 : MyWorkerInfo->wi_tableoid = InvalidOid;
2519 201142 : MyWorkerInfo->wi_sharedrel = false;
2520 201142 : LWLockRelease(AutovacuumScheduleLock);
2521 201142 : pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance);
2522 : }
2523 :
2524 3420 : list_free(table_oids);
2525 :
2526 : /*
2527 : * Perform additional work items, as requested by backends.
2528 : */
2529 3420 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2530 878940 : for (i = 0; i < NUM_WORKITEMS; i++)
2531 : {
2532 875520 : AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i];
2533 :
2534 875520 : if (!workitem->avw_used)
2535 875514 : continue;
2536 6 : if (workitem->avw_active)
2537 0 : continue;
2538 6 : if (workitem->avw_database != MyDatabaseId)
2539 0 : continue;
2540 :
2541 : /* claim this one, and release lock while performing it */
2542 6 : workitem->avw_active = true;
2543 6 : LWLockRelease(AutovacuumLock);
2544 :
2545 6 : perform_work_item(workitem);
2546 :
2547 : /*
2548 : * Check for config changes before acquiring lock for further jobs.
2549 : */
2550 6 : CHECK_FOR_INTERRUPTS();
2551 6 : if (ConfigReloadPending)
2552 : {
2553 0 : ConfigReloadPending = false;
2554 0 : ProcessConfigFile(PGC_SIGHUP);
2555 0 : VacuumUpdateCosts();
2556 : }
2557 :
2558 6 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2559 :
2560 : /* and mark it done */
2561 6 : workitem->avw_active = false;
2562 6 : workitem->avw_used = false;
2563 : }
2564 3420 : LWLockRelease(AutovacuumLock);
2565 :
2566 : /*
2567 : * We leak table_toast_map here (among other things), but since we're
2568 : * going away soon, it's not a problem.
2569 : */
2570 :
2571 : /*
2572 : * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
2573 : * only need to do this once, not after each table.
2574 : *
2575 : * Even if we didn't vacuum anything, it may still be important to do
2576 : * this, because one indirect effect of vac_update_datfrozenxid() is to
2577 : * update TransamVariables->xidVacLimit. That might need to be done even
2578 : * if we haven't vacuumed anything, because relations with older
2579 : * relfrozenxid values or other databases with older datfrozenxid values
2580 : * might have been dropped, allowing xidVacLimit to advance.
2581 : *
2582 : * However, it's also important not to do this blindly in all cases,
2583 : * because when autovacuum=off this will restart the autovacuum launcher.
2584 : * If we're not careful, an infinite loop can result, where workers find
2585 : * no work to do and restart the launcher, which starts another worker in
2586 : * the same database that finds no work to do. To prevent that, we skip
2587 : * this if (1) we found no work to do and (2) we skipped at least one
2588 : * table due to concurrent autovacuum activity. In that case, the other
2589 : * worker has already done it, or will do so when it finishes.
2590 : */
2591 3420 : if (did_vacuum || !found_concurrent_worker)
2592 3420 : vac_update_datfrozenxid();
2593 :
2594 : /* Finally close out the last transaction. */
2595 3420 : CommitTransactionCommand();
2596 3420 : }
2597 :
2598 : /*
2599 : * Execute a previously registered work item.
2600 : */
2601 : static void
2602 6 : perform_work_item(AutoVacuumWorkItem *workitem)
2603 : {
2604 6 : char *cur_datname = NULL;
2605 6 : char *cur_nspname = NULL;
2606 6 : char *cur_relname = NULL;
2607 :
2608 : /*
2609 : * Note we do not store table info in MyWorkerInfo, since this is not
2610 : * vacuuming proper.
2611 : */
2612 :
2613 : /*
2614 : * Save the relation name for a possible error message, to avoid a catalog
2615 : * lookup in case of an error. If any of these return NULL, then the
2616 : * relation has been dropped since last we checked; skip it.
2617 : */
2618 : Assert(CurrentMemoryContext == AutovacMemCxt);
2619 :
2620 6 : cur_relname = get_rel_name(workitem->avw_relation);
2621 6 : cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
2622 6 : cur_datname = get_database_name(MyDatabaseId);
2623 6 : if (!cur_relname || !cur_nspname || !cur_datname)
2624 0 : goto deleted2;
2625 :
2626 6 : autovac_report_workitem(workitem, cur_nspname, cur_relname);
2627 :
2628 : /* clean up memory before each work item */
2629 6 : MemoryContextReset(PortalContext);
2630 :
2631 : /*
2632 : * We will abort the current work item if something errors out, and
2633 : * continue with the next one; in particular, this happens if we are
2634 : * interrupted with SIGINT. Note that this means that the work item list
2635 : * can be lossy.
2636 : */
2637 6 : PG_TRY();
2638 : {
2639 : /* Use PortalContext for any per-work-item allocations */
2640 6 : MemoryContextSwitchTo(PortalContext);
2641 :
2642 : /*
2643 : * Have at it. Functions called here are responsible for any required
2644 : * user switch and sandbox.
2645 : */
2646 6 : switch (workitem->avw_type)
2647 : {
2648 6 : case AVW_BRINSummarizeRange:
2649 6 : DirectFunctionCall2(brin_summarize_range,
2650 : ObjectIdGetDatum(workitem->avw_relation),
2651 : Int64GetDatum((int64) workitem->avw_blockNumber));
2652 6 : break;
2653 0 : default:
2654 0 : elog(WARNING, "unrecognized work item found: type %d",
2655 : workitem->avw_type);
2656 0 : break;
2657 : }
2658 :
2659 : /*
2660 : * Clear a possible query-cancel signal, to avoid a late reaction to
2661 : * an automatically-sent signal because of vacuuming the current table
2662 : * (we're done with it, so it would make no sense to cancel at this
2663 : * point.)
2664 : */
2665 6 : QueryCancelPending = false;
2666 : }
2667 0 : PG_CATCH();
2668 : {
2669 : /*
2670 : * Abort the transaction, start a new one, and proceed with the next
2671 : * table in our list.
2672 : */
2673 0 : HOLD_INTERRUPTS();
2674 0 : errcontext("processing work entry for relation \"%s.%s.%s\"",
2675 : cur_datname, cur_nspname, cur_relname);
2676 0 : EmitErrorReport();
2677 :
2678 : /* this resets ProcGlobal->statusFlags[i] too */
2679 0 : AbortOutOfAnyTransaction();
2680 0 : FlushErrorState();
2681 0 : MemoryContextReset(PortalContext);
2682 :
2683 : /* restart our transaction for the following operations */
2684 0 : StartTransactionCommand();
2685 0 : RESUME_INTERRUPTS();
2686 : }
2687 6 : PG_END_TRY();
2688 :
2689 : /* Make sure we're back in AutovacMemCxt */
2690 6 : MemoryContextSwitchTo(AutovacMemCxt);
2691 :
2692 : /* We intentionally do not set did_vacuum here */
2693 :
2694 : /* be tidy */
2695 6 : deleted2:
2696 6 : if (cur_datname)
2697 6 : pfree(cur_datname);
2698 6 : if (cur_nspname)
2699 6 : pfree(cur_nspname);
2700 6 : if (cur_relname)
2701 6 : pfree(cur_relname);
2702 6 : }
2703 :
2704 : /*
2705 : * extract_autovac_opts
2706 : *
2707 : * Given a relation's pg_class tuple, return a palloc'd copy of the
2708 : * AutoVacOpts portion of reloptions, if set; otherwise, return NULL.
2709 : *
2710 : * Note: callers do not have a relation lock on the table at this point,
2711 : * so the table could have been dropped, and its catalog rows gone, after
2712 : * we acquired the pg_class row. If pg_class had a TOAST table, this would
2713 : * be a risk; fortunately, it doesn't.
2714 : */
2715 : static AutoVacOpts *
2716 578208 : extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
2717 : {
2718 : bytea *relopts;
2719 : AutoVacOpts *av;
2720 :
2721 : Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
2722 : ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
2723 : ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2724 :
2725 578208 : relopts = extractRelOptions(tup, pg_class_desc, NULL);
2726 578208 : if (relopts == NULL)
2727 573158 : return NULL;
2728 :
2729 5050 : av = palloc(sizeof(AutoVacOpts));
2730 5050 : memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
2731 5050 : pfree(relopts);
2732 :
2733 5050 : return av;
2734 : }
2735 :
2736 :
2737 : /*
2738 : * table_recheck_autovac
2739 : *
2740 : * Recheck whether a table still needs vacuum or analyze. Return value is a
2741 : * valid autovac_table pointer if it does, NULL otherwise.
2742 : *
2743 : * Note that the returned autovac_table does not have the name fields set.
2744 : */
2745 : static autovac_table *
2746 201216 : table_recheck_autovac(Oid relid, HTAB *table_toast_map,
2747 : TupleDesc pg_class_desc,
2748 : int effective_multixact_freeze_max_age)
2749 : {
2750 : Form_pg_class classForm;
2751 : HeapTuple classTup;
2752 : bool dovacuum;
2753 : bool doanalyze;
2754 201216 : autovac_table *tab = NULL;
2755 : bool wraparound;
2756 : AutoVacOpts *avopts;
2757 201216 : bool free_avopts = false;
2758 :
2759 : /* fetch the relation's relcache entry */
2760 201216 : classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
2761 201216 : if (!HeapTupleIsValid(classTup))
2762 0 : return NULL;
2763 201216 : classForm = (Form_pg_class) GETSTRUCT(classTup);
2764 :
2765 : /*
2766 : * Get the applicable reloptions. If it is a TOAST table, try to get the
2767 : * main table reloptions if the toast table itself doesn't have.
2768 : */
2769 201216 : avopts = extract_autovac_opts(classTup, pg_class_desc);
2770 201216 : if (avopts)
2771 2148 : free_avopts = true;
2772 199068 : else if (classForm->relkind == RELKIND_TOASTVALUE &&
2773 : table_toast_map != NULL)
2774 : {
2775 : av_relation *hentry;
2776 : bool found;
2777 :
2778 73194 : hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
2779 73194 : if (found && hentry->ar_hasrelopts)
2780 2146 : avopts = &hentry->ar_reloptions;
2781 : }
2782 :
2783 201216 : recheck_relation_needs_vacanalyze(relid, avopts, classForm,
2784 : effective_multixact_freeze_max_age,
2785 : &dovacuum, &doanalyze, &wraparound);
2786 :
2787 : /* OK, it needs something done */
2788 201216 : if (doanalyze || dovacuum)
2789 : {
2790 : int freeze_min_age;
2791 : int freeze_table_age;
2792 : int multixact_freeze_min_age;
2793 : int multixact_freeze_table_age;
2794 : int log_min_duration;
2795 :
2796 : /*
2797 : * Calculate the vacuum cost parameters and the freeze ages. If there
2798 : * are options set in pg_class.reloptions, use them; in the case of a
2799 : * toast table, try the main table too. Otherwise use the GUC
2800 : * defaults, autovacuum's own first and plain vacuum second.
2801 : */
2802 :
2803 : /* -1 in autovac setting means use log_autovacuum_min_duration */
2804 4294 : log_min_duration = (avopts && avopts->log_min_duration >= 0)
2805 : ? avopts->log_min_duration
2806 205438 : : Log_autovacuum_min_duration;
2807 :
2808 : /* these do not have autovacuum-specific settings */
2809 4294 : freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
2810 : ? avopts->freeze_min_age
2811 205438 : : default_freeze_min_age;
2812 :
2813 4294 : freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
2814 : ? avopts->freeze_table_age
2815 205438 : : default_freeze_table_age;
2816 :
2817 205438 : multixact_freeze_min_age = (avopts &&
2818 4294 : avopts->multixact_freeze_min_age >= 0)
2819 : ? avopts->multixact_freeze_min_age
2820 205438 : : default_multixact_freeze_min_age;
2821 :
2822 205438 : multixact_freeze_table_age = (avopts &&
2823 4294 : avopts->multixact_freeze_table_age >= 0)
2824 : ? avopts->multixact_freeze_table_age
2825 205438 : : default_multixact_freeze_table_age;
2826 :
2827 201144 : tab = palloc(sizeof(autovac_table));
2828 201144 : tab->at_relid = relid;
2829 201144 : tab->at_sharedrel = classForm->relisshared;
2830 :
2831 : /*
2832 : * Select VACUUM options. Note we don't say VACOPT_PROCESS_TOAST, so
2833 : * that vacuum() skips toast relations. Also note we tell vacuum() to
2834 : * skip vac_update_datfrozenxid(); we'll do that separately.
2835 : */
2836 201144 : tab->at_params.options =
2837 201144 : (dovacuum ? (VACOPT_VACUUM |
2838 : VACOPT_PROCESS_MAIN |
2839 201144 : VACOPT_SKIP_DATABASE_STATS) : 0) |
2840 201144 : (doanalyze ? VACOPT_ANALYZE : 0) |
2841 201144 : (!wraparound ? VACOPT_SKIP_LOCKED : 0);
2842 :
2843 : /*
2844 : * index_cleanup and truncate are unspecified at first in autovacuum.
2845 : * They will be filled in with usable values using their reloptions
2846 : * (or reloption defaults) later.
2847 : */
2848 201144 : tab->at_params.index_cleanup = VACOPTVALUE_UNSPECIFIED;
2849 201144 : tab->at_params.truncate = VACOPTVALUE_UNSPECIFIED;
2850 : /* As of now, we don't support parallel vacuum for autovacuum */
2851 201144 : tab->at_params.nworkers = -1;
2852 201144 : tab->at_params.freeze_min_age = freeze_min_age;
2853 201144 : tab->at_params.freeze_table_age = freeze_table_age;
2854 201144 : tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
2855 201144 : tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
2856 201144 : tab->at_params.is_wraparound = wraparound;
2857 201144 : tab->at_params.log_min_duration = log_min_duration;
2858 201144 : tab->at_params.toast_parent = InvalidOid;
2859 :
2860 : /*
2861 : * Later, in vacuum_rel(), we check reloptions for any
2862 : * vacuum_max_eager_freeze_failure_rate override.
2863 : */
2864 201144 : tab->at_params.max_eager_freeze_failure_rate = vacuum_max_eager_freeze_failure_rate;
2865 201144 : tab->at_storage_param_vac_cost_limit = avopts ?
2866 201144 : avopts->vacuum_cost_limit : 0;
2867 201144 : tab->at_storage_param_vac_cost_delay = avopts ?
2868 201144 : avopts->vacuum_cost_delay : -1;
2869 201144 : tab->at_relname = NULL;
2870 201144 : tab->at_nspname = NULL;
2871 201144 : tab->at_datname = NULL;
2872 :
2873 : /*
2874 : * If any of the cost delay parameters has been set individually for
2875 : * this table, disable the balancing algorithm.
2876 : */
2877 201144 : tab->at_dobalance =
2878 205438 : !(avopts && (avopts->vacuum_cost_limit > 0 ||
2879 4294 : avopts->vacuum_cost_delay >= 0));
2880 : }
2881 :
2882 201216 : if (free_avopts)
2883 2148 : pfree(avopts);
2884 201216 : heap_freetuple(classTup);
2885 201216 : return tab;
2886 : }
2887 :
2888 : /*
2889 : * recheck_relation_needs_vacanalyze
2890 : *
2891 : * Subroutine for table_recheck_autovac.
2892 : *
2893 : * Fetch the pgstat of a relation and recheck whether a relation
2894 : * needs to be vacuumed or analyzed.
2895 : */
2896 : static void
2897 201216 : recheck_relation_needs_vacanalyze(Oid relid,
2898 : AutoVacOpts *avopts,
2899 : Form_pg_class classForm,
2900 : int effective_multixact_freeze_max_age,
2901 : bool *dovacuum,
2902 : bool *doanalyze,
2903 : bool *wraparound)
2904 : {
2905 : PgStat_StatTabEntry *tabentry;
2906 :
2907 : /* fetch the pgstat table entry */
2908 201216 : tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
2909 : relid);
2910 :
2911 201216 : relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2912 : effective_multixact_freeze_max_age,
2913 : dovacuum, doanalyze, wraparound);
2914 :
2915 : /* Release tabentry to avoid leakage */
2916 201216 : if (tabentry)
2917 200296 : pfree(tabentry);
2918 :
2919 : /* ignore ANALYZE for toast tables */
2920 201216 : if (classForm->relkind == RELKIND_TOASTVALUE)
2921 73194 : *doanalyze = false;
2922 201216 : }
2923 :
2924 : /*
2925 : * relation_needs_vacanalyze
2926 : *
2927 : * Check whether a relation needs to be vacuumed or analyzed; return each into
2928 : * "dovacuum" and "doanalyze", respectively. Also return whether the vacuum is
2929 : * being forced because of Xid or multixact wraparound.
2930 : *
2931 : * relopts is a pointer to the AutoVacOpts options (either for itself in the
2932 : * case of a plain table, or for either itself or its parent table in the case
2933 : * of a TOAST table), NULL if none; tabentry is the pgstats entry, which can be
2934 : * NULL.
2935 : *
2936 : * A table needs to be vacuumed if the number of dead tuples exceeds a
2937 : * threshold. This threshold is calculated as
2938 : *
2939 : * threshold = vac_base_thresh + vac_scale_factor * reltuples
2940 : * if (threshold > vac_max_thresh)
2941 : * threshold = vac_max_thresh;
2942 : *
2943 : * For analyze, the analysis done is that the number of tuples inserted,
2944 : * deleted and updated since the last analyze exceeds a threshold calculated
2945 : * in the same fashion as above. Note that the cumulative stats system stores
2946 : * the number of tuples (both live and dead) that there were as of the last
2947 : * analyze. This is asymmetric to the VACUUM case.
2948 : *
2949 : * We also force vacuum if the table's relfrozenxid is more than freeze_max_age
2950 : * transactions back, and if its relminmxid is more than
2951 : * multixact_freeze_max_age multixacts back.
2952 : *
2953 : * A table whose autovacuum_enabled option is false is
2954 : * automatically skipped (unless we have to vacuum it due to freeze_max_age).
2955 : * Thus autovacuum can be disabled for specific tables. Also, when the cumulative
2956 : * stats system does not have data about a table, it will be skipped.
2957 : *
2958 : * A table whose vac_base_thresh value is < 0 takes the base value from the
2959 : * autovacuum_vacuum_threshold GUC variable. Similarly, a vac_scale_factor
2960 : * value < 0 is substituted with the value of
2961 : * autovacuum_vacuum_scale_factor GUC variable. Ditto for analyze.
2962 : */
2963 : static void
2964 578208 : relation_needs_vacanalyze(Oid relid,
2965 : AutoVacOpts *relopts,
2966 : Form_pg_class classForm,
2967 : PgStat_StatTabEntry *tabentry,
2968 : int effective_multixact_freeze_max_age,
2969 : /* output params below */
2970 : bool *dovacuum,
2971 : bool *doanalyze,
2972 : bool *wraparound)
2973 : {
2974 : bool force_vacuum;
2975 : bool av_enabled;
2976 :
2977 : /* constants from reloptions or GUC variables */
2978 : int vac_base_thresh,
2979 : vac_max_thresh,
2980 : vac_ins_base_thresh,
2981 : anl_base_thresh;
2982 : float4 vac_scale_factor,
2983 : vac_ins_scale_factor,
2984 : anl_scale_factor;
2985 :
2986 : /* thresholds calculated from above constants */
2987 : float4 vacthresh,
2988 : vacinsthresh,
2989 : anlthresh;
2990 :
2991 : /* number of vacuum (resp. analyze) tuples at this time */
2992 : float4 vactuples,
2993 : instuples,
2994 : anltuples;
2995 :
2996 : /* freeze parameters */
2997 : int freeze_max_age;
2998 : int multixact_freeze_max_age;
2999 : TransactionId xidForceLimit;
3000 : TransactionId relfrozenxid;
3001 : MultiXactId multiForceLimit;
3002 :
3003 : Assert(classForm != NULL);
3004 : Assert(OidIsValid(relid));
3005 :
3006 : /*
3007 : * Determine vacuum/analyze equation parameters. We have two possible
3008 : * sources: the passed reloptions (which could be a main table or a toast
3009 : * table), or the autovacuum GUC variables.
3010 : */
3011 :
3012 : /* -1 in autovac setting means use plain vacuum_scale_factor */
3013 10030 : vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
3014 0 : ? relopts->vacuum_scale_factor
3015 588238 : : autovacuum_vac_scale;
3016 :
3017 10030 : vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
3018 : ? relopts->vacuum_threshold
3019 588238 : : autovacuum_vac_thresh;
3020 :
3021 : /* -1 is used to disable max threshold */
3022 10030 : vac_max_thresh = (relopts && relopts->vacuum_max_threshold >= -1)
3023 : ? relopts->vacuum_max_threshold
3024 588238 : : autovacuum_vac_max_thresh;
3025 :
3026 10030 : vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
3027 0 : ? relopts->vacuum_ins_scale_factor
3028 588238 : : autovacuum_vac_ins_scale;
3029 :
3030 : /* -1 is used to disable insert vacuums */
3031 10030 : vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
3032 : ? relopts->vacuum_ins_threshold
3033 588238 : : autovacuum_vac_ins_thresh;
3034 :
3035 10030 : anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
3036 0 : ? relopts->analyze_scale_factor
3037 588238 : : autovacuum_anl_scale;
3038 :
3039 10030 : anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
3040 : ? relopts->analyze_threshold
3041 588238 : : autovacuum_anl_thresh;
3042 :
3043 10030 : freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
3044 0 : ? Min(relopts->freeze_max_age, autovacuum_freeze_max_age)
3045 588238 : : autovacuum_freeze_max_age;
3046 :
3047 10030 : multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
3048 0 : ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
3049 588238 : : effective_multixact_freeze_max_age;
3050 :
3051 578208 : av_enabled = (relopts ? relopts->enabled : true);
3052 :
3053 : /* Force vacuum if table is at risk of wraparound */
3054 578208 : xidForceLimit = recentXid - freeze_max_age;
3055 578208 : if (xidForceLimit < FirstNormalTransactionId)
3056 0 : xidForceLimit -= FirstNormalTransactionId;
3057 578208 : relfrozenxid = classForm->relfrozenxid;
3058 1156416 : force_vacuum = (TransactionIdIsNormal(relfrozenxid) &&
3059 578208 : TransactionIdPrecedes(relfrozenxid, xidForceLimit));
3060 578208 : if (!force_vacuum)
3061 : {
3062 175584 : MultiXactId relminmxid = classForm->relminmxid;
3063 :
3064 175584 : multiForceLimit = recentMulti - multixact_freeze_max_age;
3065 175584 : if (multiForceLimit < FirstMultiXactId)
3066 0 : multiForceLimit -= FirstMultiXactId;
3067 351168 : force_vacuum = MultiXactIdIsValid(relminmxid) &&
3068 175584 : MultiXactIdPrecedes(relminmxid, multiForceLimit);
3069 : }
3070 578208 : *wraparound = force_vacuum;
3071 :
3072 : /* User disabled it in pg_class.reloptions? (But ignore if at risk) */
3073 578208 : if (!av_enabled && !force_vacuum)
3074 : {
3075 1370 : *doanalyze = false;
3076 1370 : *dovacuum = false;
3077 1370 : return;
3078 : }
3079 :
3080 : /*
3081 : * If we found stats for the table, and autovacuum is currently enabled,
3082 : * make a threshold-based decision whether to vacuum and/or analyze. If
3083 : * autovacuum is currently disabled, we must be here for anti-wraparound
3084 : * vacuuming only, so don't vacuum (or analyze) anything that's not being
3085 : * forced.
3086 : */
3087 576838 : if (PointerIsValid(tabentry) && AutoVacuumingActive())
3088 569058 : {
3089 569058 : float4 pcnt_unfrozen = 1;
3090 569058 : float4 reltuples = classForm->reltuples;
3091 569058 : int32 relpages = classForm->relpages;
3092 569058 : int32 relallfrozen = classForm->relallfrozen;
3093 :
3094 569058 : vactuples = tabentry->dead_tuples;
3095 569058 : instuples = tabentry->ins_since_vacuum;
3096 569058 : anltuples = tabentry->mod_since_analyze;
3097 :
3098 : /* If the table hasn't yet been vacuumed, take reltuples as zero */
3099 569058 : if (reltuples < 0)
3100 2616 : reltuples = 0;
3101 :
3102 : /*
3103 : * If we have data for relallfrozen, calculate the unfrozen percentage
3104 : * of the table to modify insert scale factor. This helps us decide
3105 : * whether or not to vacuum an insert-heavy table based on the number
3106 : * of inserts to the more "active" part of the table.
3107 : */
3108 569058 : if (relpages > 0 && relallfrozen > 0)
3109 : {
3110 : /*
3111 : * It could be the stats were updated manually and relallfrozen >
3112 : * relpages. Clamp relallfrozen to relpages to avoid nonsensical
3113 : * calculations.
3114 : */
3115 220650 : relallfrozen = Min(relallfrozen, relpages);
3116 220650 : pcnt_unfrozen = 1 - ((float4) relallfrozen / relpages);
3117 : }
3118 :
3119 569058 : vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
3120 569058 : if (vac_max_thresh >= 0 && vacthresh > (float4) vac_max_thresh)
3121 0 : vacthresh = (float4) vac_max_thresh;
3122 :
3123 569058 : vacinsthresh = (float4) vac_ins_base_thresh +
3124 569058 : vac_ins_scale_factor * reltuples * pcnt_unfrozen;
3125 569058 : anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
3126 :
3127 : /*
3128 : * Note that we don't need to take special consideration for stat
3129 : * reset, because if that happens, the last vacuum and analyze counts
3130 : * will be reset too.
3131 : */
3132 569058 : if (vac_ins_base_thresh >= 0)
3133 569058 : elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
3134 : NameStr(classForm->relname),
3135 : vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
3136 : else
3137 0 : elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
3138 : NameStr(classForm->relname),
3139 : vactuples, vacthresh, anltuples, anlthresh);
3140 :
3141 : /* Determine if this table needs vacuum or analyze. */
3142 737132 : *dovacuum = force_vacuum || (vactuples > vacthresh) ||
3143 168074 : (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
3144 569058 : *doanalyze = (anltuples > anlthresh);
3145 : }
3146 : else
3147 : {
3148 : /*
3149 : * Skip a table not found in stat hash, unless we have to force vacuum
3150 : * for anti-wrap purposes. If it's not acted upon, there's no need to
3151 : * vacuum it.
3152 : */
3153 7780 : *dovacuum = force_vacuum;
3154 7780 : *doanalyze = false;
3155 : }
3156 :
3157 : /* ANALYZE refuses to work with pg_statistic */
3158 576838 : if (relid == StatisticRelationId)
3159 5262 : *doanalyze = false;
3160 : }
3161 :
3162 : /*
3163 : * autovacuum_do_vac_analyze
3164 : * Vacuum and/or analyze the specified table
3165 : *
3166 : * We expect the caller to have switched into a memory context that won't
3167 : * disappear at transaction commit.
3168 : */
3169 : static void
3170 201144 : autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
3171 : {
3172 : RangeVar *rangevar;
3173 : VacuumRelation *rel;
3174 : List *rel_list;
3175 : MemoryContext vac_context;
3176 : MemoryContext old_context;
3177 :
3178 : /* Let pgstat know what we're doing */
3179 201144 : autovac_report_activity(tab);
3180 :
3181 : /* Create a context that vacuum() can use as cross-transaction storage */
3182 201144 : vac_context = AllocSetContextCreate(CurrentMemoryContext,
3183 : "Vacuum",
3184 : ALLOCSET_DEFAULT_SIZES);
3185 :
3186 : /* Set up one VacuumRelation target, identified by OID, for vacuum() */
3187 201144 : old_context = MemoryContextSwitchTo(vac_context);
3188 201144 : rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
3189 201144 : rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
3190 201144 : rel_list = list_make1(rel);
3191 201144 : MemoryContextSwitchTo(old_context);
3192 :
3193 201144 : vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
3194 :
3195 201142 : MemoryContextDelete(vac_context);
3196 201142 : }
3197 :
3198 : /*
3199 : * autovac_report_activity
3200 : * Report to pgstat what autovacuum is doing
3201 : *
3202 : * We send a SQL string corresponding to what the user would see if the
3203 : * equivalent command was to be issued manually.
3204 : *
3205 : * Note we assume that we are going to report the next command as soon as we're
3206 : * done with the current one, and exit right after the last one, so we don't
3207 : * bother to report "<IDLE>" or some such.
3208 : */
3209 : static void
3210 201144 : autovac_report_activity(autovac_table *tab)
3211 : {
3212 : #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
3213 : char activity[MAX_AUTOVAC_ACTIV_LEN];
3214 : int len;
3215 :
3216 : /* Report the command and possible options */
3217 201144 : if (tab->at_params.options & VACOPT_VACUUM)
3218 200868 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3219 : "autovacuum: VACUUM%s",
3220 200868 : tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
3221 : else
3222 276 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3223 : "autovacuum: ANALYZE");
3224 :
3225 : /*
3226 : * Report the qualified name of the relation.
3227 : */
3228 201144 : len = strlen(activity);
3229 :
3230 201144 : snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3231 : " %s.%s%s", tab->at_nspname, tab->at_relname,
3232 201144 : tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
3233 :
3234 : /* Set statement_timestamp() to current time for pg_stat_activity */
3235 201144 : SetCurrentStatementStartTimestamp();
3236 :
3237 201144 : pgstat_report_activity(STATE_RUNNING, activity);
3238 201144 : }
3239 :
3240 : /*
3241 : * autovac_report_workitem
3242 : * Report to pgstat that autovacuum is processing a work item
3243 : */
3244 : static void
3245 6 : autovac_report_workitem(AutoVacuumWorkItem *workitem,
3246 : const char *nspname, const char *relname)
3247 : {
3248 : char activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
3249 : char blk[12 + 2];
3250 : int len;
3251 :
3252 6 : switch (workitem->avw_type)
3253 : {
3254 6 : case AVW_BRINSummarizeRange:
3255 6 : snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
3256 : "autovacuum: BRIN summarize");
3257 6 : break;
3258 : }
3259 :
3260 : /*
3261 : * Report the qualified name of the relation, and the block number if any
3262 : */
3263 6 : len = strlen(activity);
3264 :
3265 6 : if (BlockNumberIsValid(workitem->avw_blockNumber))
3266 6 : snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
3267 : else
3268 0 : blk[0] = '\0';
3269 :
3270 6 : snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
3271 : " %s.%s%s", nspname, relname, blk);
3272 :
3273 : /* Set statement_timestamp() to current time for pg_stat_activity */
3274 6 : SetCurrentStatementStartTimestamp();
3275 :
3276 6 : pgstat_report_activity(STATE_RUNNING, activity);
3277 6 : }
3278 :
3279 : /*
3280 : * AutoVacuumingActive
3281 : * Check GUC vars and report whether the autovacuum process should be
3282 : * running.
3283 : */
3284 : bool
3285 643976 : AutoVacuumingActive(void)
3286 : {
3287 643976 : if (!autovacuum_start_daemon || !pgstat_track_counts)
3288 10902 : return false;
3289 633074 : return true;
3290 : }
3291 :
3292 : /*
3293 : * Request one work item to the next autovacuum run processing our database.
3294 : * Return false if the request can't be recorded.
3295 : */
3296 : bool
3297 6 : AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId,
3298 : BlockNumber blkno)
3299 : {
3300 : int i;
3301 6 : bool result = false;
3302 :
3303 6 : LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
3304 :
3305 : /*
3306 : * Locate an unused work item and fill it with the given data.
3307 : */
3308 12 : for (i = 0; i < NUM_WORKITEMS; i++)
3309 : {
3310 12 : AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i];
3311 :
3312 12 : if (workitem->avw_used)
3313 6 : continue;
3314 :
3315 6 : workitem->avw_used = true;
3316 6 : workitem->avw_active = false;
3317 6 : workitem->avw_type = type;
3318 6 : workitem->avw_database = MyDatabaseId;
3319 6 : workitem->avw_relation = relationId;
3320 6 : workitem->avw_blockNumber = blkno;
3321 6 : result = true;
3322 :
3323 : /* done */
3324 6 : break;
3325 : }
3326 :
3327 6 : LWLockRelease(AutovacuumLock);
3328 :
3329 6 : return result;
3330 : }
3331 :
3332 : /*
3333 : * autovac_init
3334 : * This is called at postmaster initialization.
3335 : *
3336 : * All we do here is annoy the user if he got it wrong.
3337 : */
3338 : void
3339 1676 : autovac_init(void)
3340 : {
3341 1676 : if (!autovacuum_start_daemon)
3342 224 : return;
3343 1452 : else if (!pgstat_track_counts)
3344 0 : ereport(WARNING,
3345 : (errmsg("autovacuum not started because of misconfiguration"),
3346 : errhint("Enable the \"track_counts\" option.")));
3347 : else
3348 1452 : check_av_worker_gucs();
3349 : }
3350 :
3351 : /*
3352 : * AutoVacuumShmemSize
3353 : * Compute space needed for autovacuum-related shared memory
3354 : */
3355 : Size
3356 5994 : AutoVacuumShmemSize(void)
3357 : {
3358 : Size size;
3359 :
3360 : /*
3361 : * Need the fixed struct and the array of WorkerInfoData.
3362 : */
3363 5994 : size = sizeof(AutoVacuumShmemStruct);
3364 5994 : size = MAXALIGN(size);
3365 5994 : size = add_size(size, mul_size(autovacuum_worker_slots,
3366 : sizeof(WorkerInfoData)));
3367 5994 : return size;
3368 : }
3369 :
3370 : /*
3371 : * AutoVacuumShmemInit
3372 : * Allocate and initialize autovacuum-related shared memory
3373 : */
3374 : void
3375 2096 : AutoVacuumShmemInit(void)
3376 : {
3377 : bool found;
3378 :
3379 2096 : AutoVacuumShmem = (AutoVacuumShmemStruct *)
3380 2096 : ShmemInitStruct("AutoVacuum Data",
3381 : AutoVacuumShmemSize(),
3382 : &found);
3383 :
3384 2096 : if (!IsUnderPostmaster)
3385 : {
3386 : WorkerInfo worker;
3387 : int i;
3388 :
3389 : Assert(!found);
3390 :
3391 2096 : AutoVacuumShmem->av_launcherpid = 0;
3392 2096 : dclist_init(&AutoVacuumShmem->av_freeWorkers);
3393 2096 : dlist_init(&AutoVacuumShmem->av_runningWorkers);
3394 2096 : AutoVacuumShmem->av_startingWorker = NULL;
3395 2096 : memset(AutoVacuumShmem->av_workItems, 0,
3396 : sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
3397 :
3398 2096 : worker = (WorkerInfo) ((char *) AutoVacuumShmem +
3399 : MAXALIGN(sizeof(AutoVacuumShmemStruct)));
3400 :
3401 : /* initialize the WorkerInfo free list */
3402 25544 : for (i = 0; i < autovacuum_worker_slots; i++)
3403 : {
3404 23448 : dclist_push_head(&AutoVacuumShmem->av_freeWorkers,
3405 23448 : &worker[i].wi_links);
3406 23448 : pg_atomic_init_flag(&worker[i].wi_dobalance);
3407 : }
3408 :
3409 2096 : pg_atomic_init_u32(&AutoVacuumShmem->av_nworkersForBalance, 0);
3410 :
3411 : }
3412 : else
3413 : Assert(found);
3414 2096 : }
3415 :
3416 : /*
3417 : * GUC check_hook for autovacuum_work_mem
3418 : */
3419 : bool
3420 2168 : check_autovacuum_work_mem(int *newval, void **extra, GucSource source)
3421 : {
3422 : /*
3423 : * -1 indicates fallback.
3424 : *
3425 : * If we haven't yet changed the boot_val default of -1, just let it be.
3426 : * Autovacuum will look to maintenance_work_mem instead.
3427 : */
3428 2168 : if (*newval == -1)
3429 2164 : return true;
3430 :
3431 : /*
3432 : * We clamp manually-set values to at least 64kB. Since
3433 : * maintenance_work_mem is always set to at least this value, do the same
3434 : * here.
3435 : */
3436 4 : if (*newval < 64)
3437 4 : *newval = 64;
3438 :
3439 4 : return true;
3440 : }
3441 :
3442 : /*
3443 : * Returns whether there is a free autovacuum worker slot available.
3444 : */
3445 : static bool
3446 25980 : av_worker_available(void)
3447 : {
3448 : int free_slots;
3449 : int reserved_slots;
3450 :
3451 25980 : free_slots = dclist_count(&AutoVacuumShmem->av_freeWorkers);
3452 :
3453 25980 : reserved_slots = autovacuum_worker_slots - autovacuum_max_workers;
3454 25980 : reserved_slots = Max(0, reserved_slots);
3455 :
3456 25980 : return free_slots > reserved_slots;
3457 : }
3458 :
3459 : /*
3460 : * Emits a WARNING if autovacuum_worker_slots < autovacuum_max_workers.
3461 : */
3462 : static void
3463 1452 : check_av_worker_gucs(void)
3464 : {
3465 1452 : if (autovacuum_worker_slots < autovacuum_max_workers)
3466 0 : ereport(WARNING,
3467 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3468 : errmsg("\"autovacuum_max_workers\" (%d) should be less than or equal to \"autovacuum_worker_slots\" (%d)",
3469 : autovacuum_max_workers, autovacuum_worker_slots),
3470 : errdetail("The server will only start up to \"autovacuum_worker_slots\" (%d) autovacuum workers at a given time.",
3471 : autovacuum_worker_slots)));
3472 1452 : }
|