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