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