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