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