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