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