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