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