Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * vacuum.c
4 : : * The postgres vacuum cleaner.
5 : : *
6 : : * This file includes (a) control and dispatch code for VACUUM and ANALYZE
7 : : * commands, (b) code to compute various vacuum thresholds, and (c) index
8 : : * vacuum code.
9 : : *
10 : : * VACUUM for heap AM is implemented in vacuumlazy.c, parallel vacuum in
11 : : * vacuumparallel.c, ANALYZE in analyze.c, and VACUUM FULL is a variant of
12 : : * REPACK, handled in repack.c.
13 : : *
14 : : *
15 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
16 : : * Portions Copyright (c) 1994, Regents of the University of California
17 : : *
18 : : *
19 : : * IDENTIFICATION
20 : : * src/backend/commands/vacuum.c
21 : : *
22 : : *-------------------------------------------------------------------------
23 : : */
24 : : #include "postgres.h"
25 : :
26 : : #include <math.h>
27 : :
28 : : #include "access/clog.h"
29 : : #include "access/commit_ts.h"
30 : : #include "access/genam.h"
31 : : #include "access/heapam.h"
32 : : #include "access/htup_details.h"
33 : : #include "access/multixact.h"
34 : : #include "access/reloptions.h"
35 : : #include "access/tableam.h"
36 : : #include "access/transam.h"
37 : : #include "access/xact.h"
38 : : #include "catalog/namespace.h"
39 : : #include "catalog/pg_database.h"
40 : : #include "catalog/pg_inherits.h"
41 : : #include "commands/async.h"
42 : : #include "commands/defrem.h"
43 : : #include "commands/progress.h"
44 : : #include "commands/repack.h"
45 : : #include "commands/vacuum.h"
46 : : #include "miscadmin.h"
47 : : #include "nodes/makefuncs.h"
48 : : #include "pgstat.h"
49 : : #include "postmaster/autovacuum.h"
50 : : #include "postmaster/bgworker_internals.h"
51 : : #include "postmaster/interrupt.h"
52 : : #include "storage/bufmgr.h"
53 : : #include "storage/lmgr.h"
54 : : #include "storage/pmsignal.h"
55 : : #include "storage/proc.h"
56 : : #include "storage/procarray.h"
57 : : #include "utils/acl.h"
58 : : #include "utils/fmgroids.h"
59 : : #include "utils/guc.h"
60 : : #include "utils/guc_hooks.h"
61 : : #include "utils/injection_point.h"
62 : : #include "utils/memutils.h"
63 : : #include "utils/snapmgr.h"
64 : : #include "utils/syscache.h"
65 : : #include "utils/wait_event.h"
66 : :
67 : : /*
68 : : * Minimum interval for cost-based vacuum delay reports from a parallel worker.
69 : : * This aims to avoid sending too many messages and waking up the leader too
70 : : * frequently.
71 : : */
72 : : #define PARALLEL_VACUUM_DELAY_REPORT_INTERVAL_NS (NS_PER_S)
73 : :
74 : : /*
75 : : * GUC parameters
76 : : */
77 : : int vacuum_freeze_min_age;
78 : : int vacuum_freeze_table_age;
79 : : int vacuum_multixact_freeze_min_age;
80 : : int vacuum_multixact_freeze_table_age;
81 : : int vacuum_failsafe_age;
82 : : int vacuum_multixact_failsafe_age;
83 : : double vacuum_max_eager_freeze_failure_rate;
84 : : bool track_cost_delay_timing;
85 : : bool vacuum_truncate;
86 : :
87 : : /*
88 : : * Variables for cost-based vacuum delay. The defaults differ between
89 : : * autovacuum and vacuum. They should be set with the appropriate GUC value in
90 : : * vacuum code. They are initialized here to the defaults for client backends
91 : : * executing VACUUM or ANALYZE.
92 : : */
93 : : double vacuum_cost_delay = 0;
94 : : int vacuum_cost_limit = 200;
95 : :
96 : : /* Variable for reporting cost-based vacuum delay from parallel workers. */
97 : : int64 parallel_vacuum_worker_delay_ns = 0;
98 : :
99 : : /*
100 : : * VacuumFailsafeActive is a defined as a global so that we can determine
101 : : * whether or not to re-enable cost-based vacuum delay when vacuuming a table.
102 : : * If failsafe mode has been engaged, we will not re-enable cost-based delay
103 : : * for the table until after vacuuming has completed, regardless of other
104 : : * settings.
105 : : *
106 : : * Only VACUUM code should inspect this variable and only table access methods
107 : : * should set it to true. In Table AM-agnostic VACUUM code, this variable is
108 : : * inspected to determine whether or not to allow cost-based delays. Table AMs
109 : : * are free to set it if they desire this behavior, but it is false by default
110 : : * and reset to false in between vacuuming each relation.
111 : : */
112 : : bool VacuumFailsafeActive = false;
113 : :
114 : : /*
115 : : * Variables for cost-based parallel vacuum. See comments atop
116 : : * compute_parallel_delay to understand how it works.
117 : : */
118 : : pg_atomic_uint32 *VacuumSharedCostBalance = NULL;
119 : : pg_atomic_uint32 *VacuumActiveNWorkers = NULL;
120 : : int VacuumCostBalanceLocal = 0;
121 : :
122 : : /* non-export function prototypes */
123 : : static List *expand_vacuum_rel(VacuumRelation *vrel,
124 : : MemoryContext vac_context, int options);
125 : : static List *get_all_vacuum_rels(MemoryContext vac_context, int options);
126 : : static void vac_truncate_clog(TransactionId frozenXID,
127 : : MultiXactId minMulti,
128 : : TransactionId lastSaneFrozenXid,
129 : : MultiXactId lastSaneMinMulti);
130 : : static bool vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params,
131 : : BufferAccessStrategy bstrategy, bool isTopLevel);
132 : : static double compute_parallel_delay(void);
133 : : static VacOptValue get_vacoptval_from_boolean(DefElem *def);
134 : : static bool vac_tid_reaped(ItemPointer itemptr, void *state);
135 : :
136 : : /*
137 : : * GUC check function to ensure GUC value specified is within the allowable
138 : : * range.
139 : : */
140 : : bool
141 : 1371 : check_vacuum_buffer_usage_limit(int *newval, void **extra,
142 : : GucSource source)
143 : : {
144 : : /* Value upper and lower hard limits are inclusive */
145 [ + - + - ]: 1371 : if (*newval == 0 || (*newval >= MIN_BAS_VAC_RING_SIZE_KB &&
146 [ + - ]: 1371 : *newval <= MAX_BAS_VAC_RING_SIZE_KB))
147 : 1371 : return true;
148 : :
149 : : /* Value does not fall within any allowable range */
150 : 0 : GUC_check_errdetail("\"%s\" must be 0 or between %d kB and %d kB.",
151 : : "vacuum_buffer_usage_limit",
152 : : MIN_BAS_VAC_RING_SIZE_KB, MAX_BAS_VAC_RING_SIZE_KB);
153 : :
154 : 0 : return false;
155 : : }
156 : :
157 : : /*
158 : : * Primary entry point for manual VACUUM and ANALYZE commands
159 : : *
160 : : * This is mainly a preparation wrapper for the real operations that will
161 : : * happen in vacuum().
162 : : */
163 : : void
164 : 8669 : ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)
165 : : {
166 : : VacuumParams params;
167 : 8669 : BufferAccessStrategy bstrategy = NULL;
168 : 8669 : bool verbose = false;
169 : 8669 : bool skip_locked = false;
170 : 8669 : bool analyze = false;
171 : 8669 : bool freeze = false;
172 : 8669 : bool full = false;
173 : 8669 : bool disable_page_skipping = false;
174 : 8669 : bool process_main = true;
175 : 8669 : bool process_toast = true;
176 : : int ring_size;
177 : 8669 : bool skip_database_stats = false;
178 : 8669 : bool only_database_stats = false;
179 : : MemoryContext vac_context;
180 : : ListCell *lc;
181 : :
182 : : /* index_cleanup and truncate values unspecified for now */
183 : 8669 : params.index_cleanup = VACOPTVALUE_UNSPECIFIED;
184 : 8669 : params.truncate = VACOPTVALUE_UNSPECIFIED;
185 : :
186 : : /* By default parallel vacuum is enabled */
187 : 8669 : params.nworkers = 0;
188 : :
189 : : /* Will be set later if we recurse to a TOAST table. */
190 : 8669 : params.toast_parent = InvalidOid;
191 : 8669 : params.main_relopts = NULL;
192 : :
193 : : /*
194 : : * Set this to an invalid value so it is clear whether or not a
195 : : * BUFFER_USAGE_LIMIT was specified when making the access strategy.
196 : : */
197 : 8669 : ring_size = -1;
198 : :
199 : : /* Parse options list */
200 [ + + + + : 17703 : foreach(lc, vacstmt->options)
+ + ]
201 : : {
202 : 9058 : DefElem *opt = (DefElem *) lfirst(lc);
203 : :
204 : : /* Parse common options for VACUUM and ANALYZE */
205 [ + + ]: 9058 : if (strcmp(opt->defname, "verbose") == 0)
206 : 33 : verbose = defGetBoolean(opt);
207 [ + + ]: 9025 : else if (strcmp(opt->defname, "skip_locked") == 0)
208 : 172 : skip_locked = defGetBoolean(opt);
209 [ + + ]: 8853 : else if (strcmp(opt->defname, "buffer_usage_limit") == 0)
210 : : {
211 : : const char *hintmsg;
212 : : int result;
213 : : char *vac_buffer_size;
214 : :
215 : 36 : vac_buffer_size = defGetString(opt);
216 : :
217 : : /*
218 : : * Check that the specified value is valid and the size falls
219 : : * within the hard upper and lower limits if it is not 0.
220 : : */
221 [ + + ]: 36 : if (!parse_int(vac_buffer_size, &result, GUC_UNIT_KB, &hintmsg) ||
222 [ + + ]: 32 : (result != 0 &&
223 [ + + + + ]: 24 : (result < MIN_BAS_VAC_RING_SIZE_KB || result > MAX_BAS_VAC_RING_SIZE_KB)))
224 : : {
225 [ + - + + ]: 12 : ereport(ERROR,
226 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
227 : : errmsg("%s option must be 0 or between %d kB and %d kB",
228 : : "BUFFER_USAGE_LIMIT",
229 : : MIN_BAS_VAC_RING_SIZE_KB, MAX_BAS_VAC_RING_SIZE_KB),
230 : : hintmsg ? errhint_internal("%s", _(hintmsg)) : 0));
231 : : }
232 : :
233 : 24 : ring_size = result;
234 : : }
235 [ + + ]: 8817 : else if (!vacstmt->is_vacuumcmd)
236 [ + - ]: 4 : ereport(ERROR,
237 : : (errcode(ERRCODE_SYNTAX_ERROR),
238 : : errmsg("unrecognized %s option \"%s\"",
239 : : "ANALYZE", opt->defname),
240 : : parser_errposition(pstate, opt->location)));
241 : :
242 : : /* Parse options available on VACUUM */
243 [ + + ]: 8813 : else if (strcmp(opt->defname, "analyze") == 0)
244 : 1749 : analyze = defGetBoolean(opt);
245 [ + + ]: 7064 : else if (strcmp(opt->defname, "freeze") == 0)
246 : 1782 : freeze = defGetBoolean(opt);
247 [ + + ]: 5282 : else if (strcmp(opt->defname, "full") == 0)
248 : 245 : full = defGetBoolean(opt);
249 [ + + ]: 5037 : else if (strcmp(opt->defname, "disable_page_skipping") == 0)
250 : 119 : disable_page_skipping = defGetBoolean(opt);
251 [ + + ]: 4918 : else if (strcmp(opt->defname, "index_cleanup") == 0)
252 : : {
253 : : /* Interpret no string as the default, which is 'auto' */
254 [ - + ]: 95 : if (!opt->arg)
255 : 0 : params.index_cleanup = VACOPTVALUE_AUTO;
256 : : else
257 : : {
258 : 95 : char *sval = defGetString(opt);
259 : :
260 : : /* Try matching on 'auto' string, or fall back on boolean */
261 [ + + ]: 95 : if (pg_strcasecmp(sval, "auto") == 0)
262 : 4 : params.index_cleanup = VACOPTVALUE_AUTO;
263 : : else
264 : 91 : params.index_cleanup = get_vacoptval_from_boolean(opt);
265 : : }
266 : : }
267 [ + + ]: 4823 : else if (strcmp(opt->defname, "process_main") == 0)
268 : 80 : process_main = defGetBoolean(opt);
269 [ + + ]: 4743 : else if (strcmp(opt->defname, "process_toast") == 0)
270 : 84 : process_toast = defGetBoolean(opt);
271 [ + + ]: 4659 : else if (strcmp(opt->defname, "truncate") == 0)
272 : 83 : params.truncate = get_vacoptval_from_boolean(opt);
273 [ + + ]: 4576 : else if (strcmp(opt->defname, "parallel") == 0)
274 : : {
275 : 189 : int nworkers = defGetInt32(opt);
276 : :
277 [ + + - + ]: 185 : if (nworkers < 0 || nworkers > MAX_PARALLEL_WORKER_LIMIT)
278 [ + - ]: 4 : ereport(ERROR,
279 : : (errcode(ERRCODE_SYNTAX_ERROR),
280 : : errmsg("%s option must be between 0 and %d",
281 : : "PARALLEL",
282 : : MAX_PARALLEL_WORKER_LIMIT),
283 : : parser_errposition(pstate, opt->location)));
284 : :
285 : : /*
286 : : * Disable parallel vacuum, if user has specified parallel degree
287 : : * as zero.
288 : : */
289 [ + + ]: 181 : if (nworkers == 0)
290 : 81 : params.nworkers = -1;
291 : : else
292 : 100 : params.nworkers = nworkers;
293 : : }
294 [ + + ]: 4387 : else if (strcmp(opt->defname, "skip_database_stats") == 0)
295 : 4308 : skip_database_stats = defGetBoolean(opt);
296 [ + - ]: 79 : else if (strcmp(opt->defname, "only_database_stats") == 0)
297 : 79 : only_database_stats = defGetBoolean(opt);
298 : : else
299 [ # # ]: 0 : ereport(ERROR,
300 : : (errcode(ERRCODE_SYNTAX_ERROR),
301 : : errmsg("unrecognized %s option \"%s\"",
302 : : "VACUUM", opt->defname),
303 : : parser_errposition(pstate, opt->location)));
304 : : }
305 : :
306 : : /* Set vacuum options */
307 : 8645 : params.options =
308 [ + + ]: 8645 : (vacstmt->is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE) |
309 [ + + ]: 8645 : (verbose ? VACOPT_VERBOSE : 0) |
310 [ + + ]: 8645 : (skip_locked ? VACOPT_SKIP_LOCKED : 0) |
311 [ + + ]: 8645 : (analyze ? VACOPT_ANALYZE : 0) |
312 [ + + ]: 8645 : (freeze ? VACOPT_FREEZE : 0) |
313 [ + + ]: 8645 : (full ? VACOPT_FULL : 0) |
314 [ + + ]: 8645 : (disable_page_skipping ? VACOPT_DISABLE_PAGE_SKIPPING : 0) |
315 [ + + ]: 8645 : (process_main ? VACOPT_PROCESS_MAIN : 0) |
316 [ + + ]: 8645 : (process_toast ? VACOPT_PROCESS_TOAST : 0) |
317 [ + + ]: 8645 : (skip_database_stats ? VACOPT_SKIP_DATABASE_STATS : 0) |
318 [ + + ]: 8645 : (only_database_stats ? VACOPT_ONLY_DATABASE_STATS : 0);
319 : :
320 : : /* sanity checks on options */
321 : : Assert(params.options & (VACOPT_VACUUM | VACOPT_ANALYZE));
322 : : Assert((params.options & VACOPT_VACUUM) ||
323 : : !(params.options & (VACOPT_FULL | VACOPT_FREEZE)));
324 : :
325 [ + + + + ]: 8645 : if ((params.options & VACOPT_FULL) && params.nworkers > 0)
326 [ + - ]: 4 : ereport(ERROR,
327 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
328 : : errmsg("VACUUM FULL cannot be performed in parallel")));
329 : :
330 : : /*
331 : : * BUFFER_USAGE_LIMIT does nothing for VACUUM (FULL) so just raise an
332 : : * ERROR for that case. VACUUM (FULL, ANALYZE) does make use of it, so
333 : : * we'll permit that.
334 : : */
335 [ + + + + ]: 8641 : if (ring_size != -1 && (params.options & VACOPT_FULL) &&
336 [ + - ]: 4 : !(params.options & VACOPT_ANALYZE))
337 [ + - ]: 4 : ereport(ERROR,
338 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
339 : : errmsg("BUFFER_USAGE_LIMIT cannot be specified for VACUUM FULL")));
340 : :
341 : : /*
342 : : * Make sure VACOPT_ANALYZE is specified if any column lists are present.
343 : : */
344 [ + + ]: 8637 : if (!(params.options & VACOPT_ANALYZE))
345 : : {
346 [ + + + + : 7477 : foreach(lc, vacstmt->rels)
+ + ]
347 : : {
348 : 3682 : VacuumRelation *vrel = lfirst_node(VacuumRelation, lc);
349 : :
350 [ + + ]: 3682 : if (vrel->va_cols != NIL)
351 [ + - ]: 4 : ereport(ERROR,
352 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
353 : : errmsg("ANALYZE option must be specified when a column list is provided")));
354 : : }
355 : : }
356 : :
357 : : /*
358 : : * Sanity check DISABLE_PAGE_SKIPPING option.
359 : : */
360 [ + + ]: 8633 : if ((params.options & VACOPT_FULL) != 0 &&
361 [ - + ]: 229 : (params.options & VACOPT_DISABLE_PAGE_SKIPPING) != 0)
362 [ # # ]: 0 : ereport(ERROR,
363 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
364 : : errmsg("VACUUM option DISABLE_PAGE_SKIPPING cannot be used with FULL")));
365 : :
366 : : /* sanity check for PROCESS_TOAST */
367 [ + + ]: 8633 : if ((params.options & VACOPT_FULL) != 0 &&
368 [ + + ]: 229 : (params.options & VACOPT_PROCESS_TOAST) == 0)
369 [ + - ]: 4 : ereport(ERROR,
370 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
371 : : errmsg("PROCESS_TOAST required with VACUUM FULL")));
372 : :
373 : : /* sanity check for ONLY_DATABASE_STATS */
374 [ + + ]: 8629 : if (params.options & VACOPT_ONLY_DATABASE_STATS)
375 : : {
376 : : Assert(params.options & VACOPT_VACUUM);
377 [ + + ]: 79 : if (vacstmt->rels != NIL)
378 [ + - ]: 4 : ereport(ERROR,
379 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
380 : : errmsg("ONLY_DATABASE_STATS cannot be specified with a list of tables")));
381 : : /* don't require people to turn off PROCESS_TOAST/MAIN explicitly */
382 [ - + ]: 75 : if (params.options & ~(VACOPT_VACUUM |
383 : : VACOPT_VERBOSE |
384 : : VACOPT_PROCESS_MAIN |
385 : : VACOPT_PROCESS_TOAST |
386 : : VACOPT_ONLY_DATABASE_STATS))
387 [ # # ]: 0 : ereport(ERROR,
388 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
389 : : errmsg("ONLY_DATABASE_STATS cannot be specified with other VACUUM options")));
390 : : }
391 : :
392 : : /*
393 : : * All freeze ages are zero if the FREEZE option is given; otherwise pass
394 : : * them as -1 which means to use the default values.
395 : : */
396 [ + + ]: 8625 : if (params.options & VACOPT_FREEZE)
397 : : {
398 : 1782 : params.freeze_min_age = 0;
399 : 1782 : params.freeze_table_age = 0;
400 : 1782 : params.multixact_freeze_min_age = 0;
401 : 1782 : params.multixact_freeze_table_age = 0;
402 : : }
403 : : else
404 : : {
405 : 6843 : params.freeze_min_age = -1;
406 : 6843 : params.freeze_table_age = -1;
407 : 6843 : params.multixact_freeze_min_age = -1;
408 : 6843 : params.multixact_freeze_table_age = -1;
409 : : }
410 : :
411 : : /* user-invoked vacuum is never "for wraparound" */
412 : 8625 : params.is_wraparound = false;
413 : :
414 : : /*
415 : : * user-invoked vacuum uses VACOPT_VERBOSE instead of
416 : : * log_vacuum_min_duration and log_analyze_min_duration
417 : : */
418 : 8625 : params.log_vacuum_min_duration = -1;
419 : 8625 : params.log_analyze_min_duration = -1;
420 : :
421 : : /*
422 : : * Later, in vacuum_rel(), we check if a reloption override was specified.
423 : : */
424 : 8625 : params.max_eager_freeze_failure_rate = vacuum_max_eager_freeze_failure_rate;
425 : :
426 : : /*
427 : : * Create special memory context for cross-transaction storage.
428 : : *
429 : : * Since it is a child of PortalContext, it will go away eventually even
430 : : * if we suffer an error; there's no need for special abort cleanup logic.
431 : : */
432 : 8625 : vac_context = AllocSetContextCreate(PortalContext,
433 : : "Vacuum",
434 : : ALLOCSET_DEFAULT_SIZES);
435 : :
436 : : /*
437 : : * Make a buffer strategy object in the cross-transaction memory context.
438 : : * We needn't bother making this for VACUUM (FULL) or VACUUM
439 : : * (ONLY_DATABASE_STATS) as they'll not make use of it. VACUUM (FULL,
440 : : * ANALYZE) is possible, so we'd better ensure that we make a strategy
441 : : * when we see ANALYZE.
442 : : */
443 [ + + ]: 8625 : if ((params.options & (VACOPT_ONLY_DATABASE_STATS |
444 : 300 : VACOPT_FULL)) == 0 ||
445 [ + + ]: 300 : (params.options & VACOPT_ANALYZE) != 0)
446 : : {
447 : :
448 : 8329 : MemoryContext old_context = MemoryContextSwitchTo(vac_context);
449 : :
450 : : Assert(ring_size >= -1);
451 : :
452 : : /*
453 : : * If BUFFER_USAGE_LIMIT was specified by the VACUUM or ANALYZE
454 : : * command, it overrides the value of VacuumBufferUsageLimit. Either
455 : : * value may be 0, in which case GetAccessStrategyWithSize() will
456 : : * return NULL, effectively allowing full use of shared buffers.
457 : : */
458 [ + + ]: 8329 : if (ring_size == -1)
459 : 8309 : ring_size = VacuumBufferUsageLimit;
460 : :
461 : 8329 : bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, ring_size);
462 : :
463 : 8329 : MemoryContextSwitchTo(old_context);
464 : : }
465 : :
466 : : /* Now go through the common routine */
467 : 8625 : vacuum(vacstmt->rels, ¶ms, bstrategy, vac_context, isTopLevel);
468 : :
469 : : /* Finally, clean up the vacuum memory context */
470 : 8535 : MemoryContextDelete(vac_context);
471 : 8535 : }
472 : :
473 : : /*
474 : : * Internal entry point for autovacuum and the VACUUM / ANALYZE commands.
475 : : *
476 : : * relations, if not NIL, is a list of VacuumRelation to process; otherwise,
477 : : * we process all relevant tables in the database. For each VacuumRelation,
478 : : * if a valid OID is supplied, the table with that OID is what to process;
479 : : * otherwise, the VacuumRelation's RangeVar indicates what to process.
480 : : *
481 : : * params contains a set of parameters that can be used to customize the
482 : : * behavior.
483 : : *
484 : : * bstrategy may be passed in as NULL when the caller does not want to
485 : : * restrict the number of shared_buffers that VACUUM / ANALYZE can use,
486 : : * otherwise, the caller must build a BufferAccessStrategy with the number of
487 : : * shared_buffers that VACUUM / ANALYZE should try to limit themselves to
488 : : * using.
489 : : *
490 : : * isTopLevel should be passed down from ProcessUtility.
491 : : *
492 : : * It is the caller's responsibility that all parameters are allocated in a
493 : : * memory context that will not disappear at transaction commit.
494 : : */
495 : : void
496 : 117542 : vacuum(List *relations, const VacuumParams *params, BufferAccessStrategy bstrategy,
497 : : MemoryContext vac_context, bool isTopLevel)
498 : : {
499 : : static bool in_vacuum = false;
500 : :
501 : : const char *stmttype;
502 : : volatile bool in_outer_xact,
503 : : use_own_xacts;
504 : :
505 [ + + ]: 117542 : stmttype = (params->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
506 : :
507 : : /*
508 : : * We cannot run VACUUM inside a user transaction block; if we were inside
509 : : * a transaction, then our commit- and start-transaction-command calls
510 : : * would not have the intended effect! There are numerous other subtle
511 : : * dependencies on this, too.
512 : : *
513 : : * ANALYZE (without VACUUM) can run either way.
514 : : */
515 [ + + ]: 117542 : if (params->options & VACOPT_VACUUM)
516 : : {
517 : 114228 : PreventInTransactionBlock(isTopLevel, stmttype);
518 : 114215 : in_outer_xact = false;
519 : : }
520 : : else
521 : 3314 : in_outer_xact = IsInTransactionBlock(isTopLevel);
522 : :
523 : : /*
524 : : * Check for and disallow recursive calls. This could happen when VACUUM
525 : : * FULL or ANALYZE calls a hostile index expression that itself calls
526 : : * ANALYZE.
527 : : */
528 [ + + ]: 117529 : if (in_vacuum)
529 [ + - ]: 8 : ereport(ERROR,
530 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
531 : : errmsg("%s cannot be executed from VACUUM or ANALYZE",
532 : : stmttype)));
533 : :
534 : : /*
535 : : * Build list of relation(s) to process, putting any new data in
536 : : * vac_context for safekeeping.
537 : : */
538 [ + + ]: 117521 : if (params->options & VACOPT_ONLY_DATABASE_STATS)
539 : : {
540 : : /* We don't process any tables in this case */
541 : : Assert(relations == NIL);
542 : : }
543 [ + + ]: 117446 : else if (relations != NIL)
544 : : {
545 : 117317 : List *newrels = NIL;
546 : : ListCell *lc;
547 : :
548 [ + - + + : 234723 : foreach(lc, relations)
+ + ]
549 : : {
550 : 117430 : VacuumRelation *vrel = lfirst_node(VacuumRelation, lc);
551 : : List *sublist;
552 : : MemoryContext old_context;
553 : :
554 : 117430 : sublist = expand_vacuum_rel(vrel, vac_context, params->options);
555 : 117406 : old_context = MemoryContextSwitchTo(vac_context);
556 : 117406 : newrels = list_concat(newrels, sublist);
557 : 117406 : MemoryContextSwitchTo(old_context);
558 : : }
559 : 117293 : relations = newrels;
560 : : }
561 : : else
562 : 129 : relations = get_all_vacuum_rels(vac_context, params->options);
563 : :
564 : : /*
565 : : * Decide whether we need to start/commit our own transactions.
566 : : *
567 : : * For VACUUM (with or without ANALYZE): always do so, so that we can
568 : : * release locks as soon as possible. (We could possibly use the outer
569 : : * transaction for a one-table VACUUM, but handling TOAST tables would be
570 : : * problematic.)
571 : : *
572 : : * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
573 : : * start/commit our own transactions. Also, there's no need to do so if
574 : : * only processing one relation. For multiple relations when not within a
575 : : * transaction block, and also in an autovacuum worker, use own
576 : : * transactions so we can release locks sooner.
577 : : */
578 [ + + ]: 117497 : if (params->options & VACOPT_VACUUM)
579 : 114207 : use_own_xacts = true;
580 : : else
581 : : {
582 : : Assert(params->options & VACOPT_ANALYZE);
583 [ + + ]: 3290 : if (AmAutoVacuumWorkerProcess())
584 : 225 : use_own_xacts = true;
585 [ + + ]: 3065 : else if (in_outer_xact)
586 : 172 : use_own_xacts = false;
587 [ + + ]: 2893 : else if (list_length(relations) > 1)
588 : 541 : use_own_xacts = true;
589 : : else
590 : 2352 : use_own_xacts = false;
591 : : }
592 : :
593 : : /*
594 : : * vacuum_rel expects to be entered with no transaction active; it will
595 : : * start and commit its own transaction. But we are called by an SQL
596 : : * command, and so we are executing inside a transaction already. We
597 : : * commit the transaction started in PostgresMain() here, and start
598 : : * another one before exiting to match the commit waiting for us back in
599 : : * PostgresMain().
600 : : */
601 [ + + ]: 117497 : if (use_own_xacts)
602 : : {
603 : : Assert(!in_outer_xact);
604 : :
605 : : /* ActiveSnapshot is not set by autovacuum */
606 [ + + ]: 114973 : if (ActiveSnapshotSet())
607 : 6056 : PopActiveSnapshot();
608 : :
609 : : /* matches the StartTransaction in PostgresMain() */
610 : 114973 : CommitTransactionCommand();
611 : : }
612 : :
613 : : /* Turn vacuum cost accounting on or off, and set/clear in_vacuum */
614 [ + + ]: 117497 : PG_TRY();
615 : : {
616 : : ListCell *cur;
617 : :
618 : 117497 : in_vacuum = true;
619 : 117497 : VacuumFailsafeActive = false;
620 : 117497 : VacuumUpdateCosts();
621 : 117497 : VacuumCostBalance = 0;
622 : 117497 : VacuumCostBalanceLocal = 0;
623 : 117497 : VacuumSharedCostBalance = NULL;
624 : 117497 : VacuumActiveNWorkers = NULL;
625 : :
626 : : /*
627 : : * Loop to process each selected relation.
628 : : */
629 [ + + + + : 245339 : foreach(cur, relations)
+ + ]
630 : : {
631 : 127889 : VacuumRelation *vrel = lfirst_node(VacuumRelation, cur);
632 : :
633 [ + + ]: 127889 : if (params->options & VACOPT_VACUUM)
634 : : {
635 [ + + ]: 119486 : if (!vacuum_rel(vrel->oid, vrel->relation, *params, bstrategy,
636 : : isTopLevel))
637 : 63 : continue;
638 : : }
639 : :
640 [ + + ]: 127820 : if (params->options & VACOPT_ANALYZE)
641 : : {
642 : : /*
643 : : * If using separate xacts, start one for analyze. Otherwise,
644 : : * we can use the outer transaction.
645 : : */
646 [ + + ]: 10401 : if (use_own_xacts)
647 : : {
648 : 7889 : StartTransactionCommand();
649 : : /* functions in indexes may want a snapshot set */
650 : 7889 : PushActiveSnapshot(GetTransactionSnapshot());
651 : : }
652 : :
653 : 10401 : analyze_rel(vrel->oid, vrel->relation, params,
654 : : vrel->va_cols, in_outer_xact, bstrategy);
655 : :
656 [ + + ]: 10360 : if (use_own_xacts)
657 : : {
658 : 7863 : PopActiveSnapshot();
659 : : /* standard_ProcessUtility() does CCI if !use_own_xacts */
660 : 7863 : CommandCounterIncrement();
661 : 7863 : CommitTransactionCommand();
662 : : }
663 : : else
664 : : {
665 : : /*
666 : : * If we're not using separate xacts, better separate the
667 : : * ANALYZE actions with CCIs. This avoids trouble if user
668 : : * says "ANALYZE t, t".
669 : : */
670 : 2497 : CommandCounterIncrement();
671 : : }
672 : : }
673 : :
674 : : /*
675 : : * Ensure VacuumFailsafeActive has been reset before vacuuming the
676 : : * next relation.
677 : : */
678 : 127779 : VacuumFailsafeActive = false;
679 : : }
680 : : }
681 : 45 : PG_FINALLY();
682 : : {
683 : 117495 : in_vacuum = false;
684 : 117495 : VacuumCostActive = false;
685 : 117495 : VacuumFailsafeActive = false;
686 : 117495 : VacuumCostBalance = 0;
687 : 117495 : VacuumCostBalanceLocal = 0;
688 : 117495 : VacuumSharedCostBalance = NULL;
689 : 117495 : VacuumActiveNWorkers = NULL;
690 : : }
691 [ + + ]: 117495 : PG_END_TRY();
692 : :
693 : : /*
694 : : * Finish up processing.
695 : : */
696 [ + + ]: 117450 : if (use_own_xacts)
697 : : {
698 : : /* here, we are not in a transaction */
699 : :
700 : : /*
701 : : * This matches the CommitTransaction waiting for us in
702 : : * PostgresMain().
703 : : */
704 : 114941 : StartTransactionCommand();
705 : : }
706 : :
707 [ + + ]: 117450 : if ((params->options & VACOPT_VACUUM) &&
708 [ + + ]: 114184 : !(params->options & VACOPT_SKIP_DATABASE_STATS))
709 : : {
710 : : /*
711 : : * Update pg_database.datfrozenxid, and truncate pg_xact if possible.
712 : : */
713 : 1186 : vac_update_datfrozenxid();
714 : : }
715 : :
716 : 117450 : }
717 : :
718 : : /*
719 : : * Check if the current user has privileges to vacuum or analyze the relation.
720 : : * If not, issue a WARNING log message and return false to let the caller
721 : : * decide what to do with this relation. This routine is used to decide if a
722 : : * relation can be processed for VACUUM or ANALYZE.
723 : : *
724 : : * If missing_ok is true, we silently return false if the relation is
725 : : * concurrently dropped. Callers without a lock on the relation must specify
726 : : * missing_ok; all others must hold at least AccessShareLock.
727 : : */
728 : : bool
729 : 155017 : vacuum_is_permitted_for_relation(Oid relid, Form_pg_class reltuple,
730 : : uint32 options, bool missing_ok)
731 : : {
732 : : char *relname;
733 : 155017 : bool is_missing = false;
734 : :
735 : : Assert((options & (VACOPT_VACUUM | VACOPT_ANALYZE)) != 0);
736 : : Assert(missing_ok ||
737 : : CheckRelationOidLockedByMe(relid, AccessShareLock, true));
738 : :
739 : : /*----------
740 : : * A role has privileges to vacuum or analyze the relation if any of the
741 : : * following are true:
742 : : * - the role owns the current database and the relation is not shared
743 : : * - the role has the MAINTAIN privilege on the relation
744 : : *----------
745 : : */
746 [ + + ]: 155017 : if ((object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()) &&
747 [ + + + + ]: 178891 : !reltuple->relisshared) ||
748 [ + + ]: 26286 : pg_class_aclcheck_ext(relid, GetUserId(), ACL_MAINTAIN,
749 : : missing_ok ? &is_missing : NULL) == ACLCHECK_OK)
750 : 152917 : return true;
751 : :
752 : : /*
753 : : * If the relation was concurrently dropped, nothing to do. Note that
754 : : * this is only reachable when the caller specified missing_ok.
755 : : */
756 [ - + ]: 2100 : if (is_missing)
757 : : {
758 : : Assert(missing_ok);
759 : 0 : return false;
760 : : }
761 : :
762 : 2100 : relname = NameStr(reltuple->relname);
763 : :
764 [ + + ]: 2100 : if ((options & VACOPT_VACUUM) != 0)
765 : : {
766 [ + - ]: 148 : ereport(WARNING,
767 : : (errmsg("permission denied to vacuum \"%s\", skipping it",
768 : : relname)));
769 : :
770 : : /*
771 : : * For VACUUM ANALYZE, both logs could show up, but just generate
772 : : * information for VACUUM as that would be the first one to be
773 : : * processed.
774 : : */
775 : 148 : return false;
776 : : }
777 : :
778 [ + - ]: 1952 : if ((options & VACOPT_ANALYZE) != 0)
779 [ + - ]: 1952 : ereport(WARNING,
780 : : (errmsg("permission denied to analyze \"%s\", skipping it",
781 : : relname)));
782 : :
783 : 1952 : return false;
784 : : }
785 : :
786 : :
787 : : /*
788 : : * vacuum_open_relation
789 : : *
790 : : * This routine is used for attempting to open and lock a relation which
791 : : * is going to be vacuumed or analyzed. If the relation cannot be opened
792 : : * or locked, a log is emitted if possible.
793 : : */
794 : : Relation
795 : 135495 : vacuum_open_relation(Oid relid, RangeVar *relation, uint32 options,
796 : : bool verbose, LOCKMODE lmode)
797 : : {
798 : : Relation rel;
799 : 135495 : bool rel_lock = true;
800 : : int elevel;
801 : :
802 : : Assert((options & (VACOPT_VACUUM | VACOPT_ANALYZE)) != 0);
803 : :
804 : : /*
805 : : * Open the relation and get the appropriate lock on it.
806 : : *
807 : : * There's a race condition here: the relation may have gone away since
808 : : * the last time we saw it. If so, we don't need to vacuum or analyze it.
809 : : *
810 : : * If we've been asked not to wait for the relation lock, acquire it first
811 : : * in non-blocking mode, before calling try_relation_open().
812 : : */
813 [ + + ]: 135495 : if (!(options & VACOPT_SKIP_LOCKED))
814 : 134597 : rel = try_relation_open(relid, lmode);
815 [ + + ]: 898 : else if (ConditionalLockRelationOid(relid, lmode))
816 : 881 : rel = try_relation_open(relid, NoLock);
817 : : else
818 : : {
819 : 17 : rel = NULL;
820 : 17 : rel_lock = false;
821 : : }
822 : :
823 : : /* if relation is opened, leave */
824 [ + + ]: 135495 : if (rel)
825 : 135472 : return rel;
826 : :
827 : : /*
828 : : * Relation could not be opened, hence generate if possible a log
829 : : * informing on the situation.
830 : : *
831 : : * If the RangeVar is not defined, we do not have enough information to
832 : : * provide a meaningful log statement. Chances are that the caller has
833 : : * intentionally not provided this information so that this logging is
834 : : * skipped, anyway.
835 : : */
836 [ + + ]: 23 : if (relation == NULL)
837 : 9 : return NULL;
838 : :
839 : : /*
840 : : * Determine the log level.
841 : : *
842 : : * For manual VACUUM or ANALYZE, we emit a WARNING to match the log
843 : : * statements in the permission checks; otherwise, only log if the caller
844 : : * so requested.
845 : : */
846 [ + + ]: 14 : if (!AmAutoVacuumWorkerProcess())
847 : 7 : elevel = WARNING;
848 [ + - ]: 7 : else if (verbose)
849 : 7 : elevel = LOG;
850 : : else
851 : 0 : return NULL;
852 : :
853 [ + + ]: 14 : if ((options & VACOPT_VACUUM) != 0)
854 : : {
855 [ + + ]: 6 : if (!rel_lock)
856 [ + - ]: 4 : ereport(elevel,
857 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
858 : : errmsg("skipping vacuum of \"%s\" --- lock not available",
859 : : relation->relname)));
860 : : else
861 [ + - ]: 2 : ereport(elevel,
862 : : (errcode(ERRCODE_UNDEFINED_TABLE),
863 : : errmsg("skipping vacuum of \"%s\" --- relation no longer exists",
864 : : relation->relname)));
865 : :
866 : : /*
867 : : * For VACUUM ANALYZE, both logs could show up, but just generate
868 : : * information for VACUUM as that would be the first one to be
869 : : * processed.
870 : : */
871 : 6 : return NULL;
872 : : }
873 : :
874 [ + - ]: 8 : if ((options & VACOPT_ANALYZE) != 0)
875 : : {
876 [ + + ]: 8 : if (!rel_lock)
877 [ + - ]: 7 : ereport(elevel,
878 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
879 : : errmsg("skipping analyze of \"%s\" --- lock not available",
880 : : relation->relname)));
881 : : else
882 [ + - ]: 1 : ereport(elevel,
883 : : (errcode(ERRCODE_UNDEFINED_TABLE),
884 : : errmsg("skipping analyze of \"%s\" --- relation no longer exists",
885 : : relation->relname)));
886 : : }
887 : :
888 : 8 : return NULL;
889 : : }
890 : :
891 : :
892 : : /*
893 : : * Given a VacuumRelation, fill in the table OID if it wasn't specified,
894 : : * and optionally add VacuumRelations for partitions or inheritance children.
895 : : *
896 : : * If a VacuumRelation does not have an OID supplied and is a partitioned
897 : : * table, an extra entry will be added to the output for each partition.
898 : : * Presently, only autovacuum supplies OIDs when calling vacuum(), and
899 : : * it does not want us to expand partitioned tables.
900 : : *
901 : : * We take care not to modify the input data structure, but instead build
902 : : * new VacuumRelation(s) to return. (But note that they will reference
903 : : * unmodified parts of the input, eg column lists.) New data structures
904 : : * are made in vac_context.
905 : : */
906 : : static List *
907 : 117430 : expand_vacuum_rel(VacuumRelation *vrel, MemoryContext vac_context,
908 : : int options)
909 : : {
910 : 117430 : List *vacrels = NIL;
911 : : MemoryContext oldcontext;
912 : :
913 : : /* If caller supplied OID, there's nothing we need do here. */
914 [ + + ]: 117430 : if (OidIsValid(vrel->oid))
915 : : {
916 : 108917 : oldcontext = MemoryContextSwitchTo(vac_context);
917 : 108917 : vacrels = lappend(vacrels, vrel);
918 : 108917 : MemoryContextSwitchTo(oldcontext);
919 : : }
920 : : else
921 : : {
922 : : /*
923 : : * Process a specific relation, and possibly partitions or child
924 : : * tables thereof.
925 : : */
926 : : Oid relid;
927 : : HeapTuple tuple;
928 : : Form_pg_class classForm;
929 : : bool include_children;
930 : : bool is_partitioned_table;
931 : : int rvr_opts;
932 : :
933 : : /*
934 : : * Since autovacuum workers supply OIDs when calling vacuum(), no
935 : : * autovacuum worker should reach this code.
936 : : */
937 : : Assert(!AmAutoVacuumWorkerProcess());
938 : :
939 : : /*
940 : : * We transiently take AccessShareLock to protect the syscache lookup
941 : : * below, as well as find_all_inheritors's expectation that the caller
942 : : * holds some lock on the starting relation.
943 : : */
944 : 8513 : rvr_opts = (options & VACOPT_SKIP_LOCKED) ? RVR_SKIP_LOCKED : 0;
945 : 8513 : relid = RangeVarGetRelidExtended(vrel->relation,
946 : : AccessShareLock,
947 : : rvr_opts,
948 : : NULL, NULL);
949 : :
950 : : /*
951 : : * If the lock is unavailable, emit the same log statement that
952 : : * vacuum_rel() and analyze_rel() would.
953 : : */
954 [ + + ]: 8489 : if (!OidIsValid(relid))
955 : : {
956 [ + + ]: 4 : if (options & VACOPT_VACUUM)
957 [ + - ]: 3 : ereport(WARNING,
958 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
959 : : errmsg("skipping vacuum of \"%s\" --- lock not available",
960 : : vrel->relation->relname)));
961 : : else
962 [ + - ]: 1 : ereport(WARNING,
963 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
964 : : errmsg("skipping analyze of \"%s\" --- lock not available",
965 : : vrel->relation->relname)));
966 : 4 : return vacrels;
967 : : }
968 : :
969 : : /*
970 : : * To check whether the relation is a partitioned table and its
971 : : * ownership, fetch its syscache entry.
972 : : */
973 : 8485 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
974 [ - + ]: 8485 : if (!HeapTupleIsValid(tuple))
975 [ # # ]: 0 : elog(ERROR, "cache lookup failed for relation %u", relid);
976 : 8485 : classForm = (Form_pg_class) GETSTRUCT(tuple);
977 : :
978 : : /*
979 : : * Make a returnable VacuumRelation for this rel if the user has the
980 : : * required privileges.
981 : : */
982 [ + + ]: 8485 : if (vacuum_is_permitted_for_relation(relid, classForm, options, false))
983 : : {
984 : 8333 : oldcontext = MemoryContextSwitchTo(vac_context);
985 : 8333 : vacrels = lappend(vacrels, makeVacuumRelation(vrel->relation,
986 : : relid,
987 : : vrel->va_cols));
988 : 8333 : MemoryContextSwitchTo(oldcontext);
989 : : }
990 : :
991 : : /*
992 : : * Vacuuming a partitioned table with ONLY will not do anything since
993 : : * the partitioned table itself is empty. Issue a warning if the user
994 : : * requests this.
995 : : */
996 : 8485 : include_children = vrel->relation->inh;
997 : 8485 : is_partitioned_table = (classForm->relkind == RELKIND_PARTITIONED_TABLE);
998 [ + + + + : 8485 : if ((options & VACOPT_VACUUM) && is_partitioned_table && !include_children)
+ + ]
999 [ + - ]: 4 : ereport(WARNING,
1000 : : (errmsg("VACUUM ONLY of partitioned table \"%s\" has no effect",
1001 : : vrel->relation->relname)));
1002 : :
1003 : 8485 : ReleaseSysCache(tuple);
1004 : :
1005 : : /*
1006 : : * Unless the user has specified ONLY, make relation list entries for
1007 : : * its partitions or inheritance child tables. Note that the list
1008 : : * returned by find_all_inheritors() includes the passed-in OID, so we
1009 : : * have to skip that. There's no point in taking locks on the
1010 : : * individual partitions or child tables yet, and doing so would just
1011 : : * add unnecessary deadlock risk. For this last reason, we do not yet
1012 : : * check the ownership of the partitions/tables, which get added to
1013 : : * the list to process. Ownership will be checked later on anyway.
1014 : : */
1015 [ + + ]: 8485 : if (include_children)
1016 : : {
1017 : 8457 : List *part_oids = find_all_inheritors(relid, NoLock, NULL);
1018 : : ListCell *part_lc;
1019 : :
1020 [ + - + + : 18401 : foreach(part_lc, part_oids)
+ + ]
1021 : : {
1022 : 9944 : Oid part_oid = lfirst_oid(part_lc);
1023 : :
1024 [ + + ]: 9944 : if (part_oid == relid)
1025 : 8457 : continue; /* ignore original table */
1026 : :
1027 : : /*
1028 : : * We omit a RangeVar since it wouldn't be appropriate to
1029 : : * complain about failure to open one of these relations
1030 : : * later.
1031 : : */
1032 : 1487 : oldcontext = MemoryContextSwitchTo(vac_context);
1033 : 1487 : vacrels = lappend(vacrels, makeVacuumRelation(NULL,
1034 : : part_oid,
1035 : : vrel->va_cols));
1036 : 1487 : MemoryContextSwitchTo(oldcontext);
1037 : : }
1038 : : }
1039 : :
1040 : : /*
1041 : : * Release lock again. This means that by the time we actually try to
1042 : : * process the table, it might be gone or renamed. In the former case
1043 : : * we'll silently ignore it; in the latter case we'll process it
1044 : : * anyway, but we must beware that the RangeVar doesn't necessarily
1045 : : * identify it anymore. This isn't ideal, perhaps, but there's little
1046 : : * practical alternative, since we're typically going to commit this
1047 : : * transaction and begin a new one between now and then. Moreover,
1048 : : * holding locks on multiple relations would create significant risk
1049 : : * of deadlock.
1050 : : */
1051 : 8485 : UnlockRelationOid(relid, AccessShareLock);
1052 : : }
1053 : :
1054 : 117402 : return vacrels;
1055 : : }
1056 : :
1057 : : /*
1058 : : * Construct a list of VacuumRelations for all vacuumable rels in
1059 : : * the current database. The list is built in vac_context.
1060 : : */
1061 : : static List *
1062 : 129 : get_all_vacuum_rels(MemoryContext vac_context, int options)
1063 : : {
1064 : 129 : List *vacrels = NIL;
1065 : : Relation pgclass;
1066 : : TableScanDesc scan;
1067 : : HeapTuple tuple;
1068 : :
1069 : 129 : pgclass = table_open(RelationRelationId, AccessShareLock);
1070 : :
1071 : 129 : scan = table_beginscan_catalog(pgclass, 0, NULL);
1072 : :
1073 [ + + ]: 59909 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1074 : : {
1075 : 59780 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
1076 : : MemoryContext oldcontext;
1077 : 59780 : Oid relid = classForm->oid;
1078 : :
1079 : : /*
1080 : : * We include partitioned tables here; depending on which operation is
1081 : : * to be performed, caller will decide whether to process or ignore
1082 : : * them.
1083 : : */
1084 [ + + ]: 59780 : if (classForm->relkind != RELKIND_RELATION &&
1085 [ + + ]: 48864 : classForm->relkind != RELKIND_MATVIEW &&
1086 [ + + ]: 48832 : classForm->relkind != RELKIND_PARTITIONED_TABLE)
1087 : 48719 : continue;
1088 : :
1089 : : /* Skip temp relations belonging to other sessions */
1090 [ + + ]: 11061 : if (classForm->relpersistence == RELPERSISTENCE_TEMP &&
1091 [ + + ]: 9 : !isTempOrTempToastNamespace(classForm->relnamespace))
1092 : 1 : continue;
1093 : :
1094 : : /* check permissions of relation */
1095 [ + + ]: 11060 : if (!vacuum_is_permitted_for_relation(relid, classForm, options, true))
1096 : 1876 : continue;
1097 : :
1098 : : /*
1099 : : * Build VacuumRelation(s) specifying the table OIDs to be processed.
1100 : : * We omit a RangeVar since it wouldn't be appropriate to complain
1101 : : * about failure to open one of these relations later.
1102 : : */
1103 : 9184 : oldcontext = MemoryContextSwitchTo(vac_context);
1104 : 9184 : vacrels = lappend(vacrels, makeVacuumRelation(NULL,
1105 : : relid,
1106 : : NIL));
1107 : 9184 : MemoryContextSwitchTo(oldcontext);
1108 : : }
1109 : :
1110 : 129 : table_endscan(scan);
1111 : 129 : table_close(pgclass, AccessShareLock);
1112 : :
1113 : 129 : return vacrels;
1114 : : }
1115 : :
1116 : : /*
1117 : : * vacuum_get_cutoffs() -- compute OldestXmin and freeze cutoff points
1118 : : *
1119 : : * The target relation and VACUUM parameters are our inputs.
1120 : : *
1121 : : * Output parameters are the cutoffs that VACUUM caller should use.
1122 : : *
1123 : : * Return value indicates if vacuumlazy.c caller should make its VACUUM
1124 : : * operation aggressive. An aggressive VACUUM must advance relfrozenxid up to
1125 : : * FreezeLimit (at a minimum), and relminmxid up to MultiXactCutoff (at a
1126 : : * minimum).
1127 : : */
1128 : : bool
1129 : 125021 : vacuum_get_cutoffs(Relation rel, const VacuumParams *params,
1130 : : struct VacuumCutoffs *cutoffs)
1131 : : {
1132 : : int freeze_min_age,
1133 : : multixact_freeze_min_age,
1134 : : freeze_table_age,
1135 : : multixact_freeze_table_age,
1136 : : effective_multixact_freeze_max_age;
1137 : : TransactionId nextXID,
1138 : : safeOldestXmin,
1139 : : aggressiveXIDCutoff;
1140 : : MultiXactId nextMXID,
1141 : : safeOldestMxact,
1142 : : aggressiveMXIDCutoff;
1143 : :
1144 : : /* Use mutable copies of freeze age parameters */
1145 : 125021 : freeze_min_age = params->freeze_min_age;
1146 : 125021 : multixact_freeze_min_age = params->multixact_freeze_min_age;
1147 : 125021 : freeze_table_age = params->freeze_table_age;
1148 : 125021 : multixact_freeze_table_age = params->multixact_freeze_table_age;
1149 : :
1150 : : /* Set pg_class fields in cutoffs */
1151 : 125021 : cutoffs->relfrozenxid = rel->rd_rel->relfrozenxid;
1152 : 125021 : cutoffs->relminmxid = rel->rd_rel->relminmxid;
1153 : :
1154 : : /*
1155 : : * Acquire OldestXmin.
1156 : : *
1157 : : * We can always ignore processes running lazy vacuum. This is because we
1158 : : * use these values only for deciding which tuples we must keep in the
1159 : : * tables. Since lazy vacuum doesn't write its XID anywhere (usually no
1160 : : * XID assigned), it's safe to ignore it. In theory it could be
1161 : : * problematic to ignore lazy vacuums in a full vacuum, but keep in mind
1162 : : * that only one vacuum process can be working on a particular table at
1163 : : * any time, and that each vacuum is always an independent transaction.
1164 : : */
1165 : 125021 : cutoffs->OldestXmin = GetOldestNonRemovableTransactionId(rel);
1166 : :
1167 : : Assert(TransactionIdIsNormal(cutoffs->OldestXmin));
1168 : :
1169 : : /* Acquire OldestMxact */
1170 : 125021 : cutoffs->OldestMxact = GetOldestMultiXactId();
1171 : : Assert(MultiXactIdIsValid(cutoffs->OldestMxact));
1172 : :
1173 : : /* Acquire next XID/next MXID values used to apply age-based settings */
1174 : 125021 : nextXID = ReadNextTransactionId();
1175 : 125021 : nextMXID = ReadNextMultiXactId();
1176 : :
1177 : : /*
1178 : : * Also compute the multixact age for which freezing is urgent. This is
1179 : : * normally autovacuum_multixact_freeze_max_age, but may be less if
1180 : : * multixact members are bloated.
1181 : : */
1182 : 125021 : effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
1183 : :
1184 : : /*
1185 : : * Almost ready to set freeze output parameters; check if OldestXmin or
1186 : : * OldestMxact are held back to an unsafe degree before we start on that
1187 : : */
1188 : 125021 : safeOldestXmin = nextXID - autovacuum_freeze_max_age;
1189 [ - + ]: 125021 : if (!TransactionIdIsNormal(safeOldestXmin))
1190 : 0 : safeOldestXmin = FirstNormalTransactionId;
1191 : 125021 : safeOldestMxact = nextMXID - effective_multixact_freeze_max_age;
1192 [ - + ]: 125021 : if (safeOldestMxact < FirstMultiXactId)
1193 : 0 : safeOldestMxact = FirstMultiXactId;
1194 [ + + ]: 125021 : if (TransactionIdPrecedes(cutoffs->OldestXmin, safeOldestXmin))
1195 [ + - ]: 91272 : ereport(WARNING,
1196 : : (errmsg("cutoff for removing and freezing tuples is far in the past"),
1197 : : errhint("Close open transactions soon to avoid wraparound problems.\n"
1198 : : "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1199 [ - + ]: 125021 : if (MultiXactIdPrecedes(cutoffs->OldestMxact, safeOldestMxact))
1200 [ # # ]: 0 : ereport(WARNING,
1201 : : (errmsg("cutoff for freezing multixacts is far in the past"),
1202 : : errhint("Close open transactions soon to avoid wraparound problems.\n"
1203 : : "You might also need to commit or roll back old prepared transactions.")));
1204 : :
1205 : : /*
1206 : : * Determine the minimum freeze age to use: as specified by the caller, or
1207 : : * vacuum_freeze_min_age, but in any case not more than half
1208 : : * autovacuum_freeze_max_age, so that autovacuums to prevent XID
1209 : : * wraparound won't occur too frequently.
1210 : : */
1211 [ + + ]: 125021 : if (freeze_min_age < 0)
1212 : 6665 : freeze_min_age = vacuum_freeze_min_age;
1213 : 125021 : freeze_min_age = Min(freeze_min_age, autovacuum_freeze_max_age / 2);
1214 : : Assert(freeze_min_age >= 0);
1215 : :
1216 : : /* Compute FreezeLimit, being careful to generate a normal XID */
1217 : 125021 : cutoffs->FreezeLimit = nextXID - freeze_min_age;
1218 [ - + ]: 125021 : if (!TransactionIdIsNormal(cutoffs->FreezeLimit))
1219 : 0 : cutoffs->FreezeLimit = FirstNormalTransactionId;
1220 : : /* FreezeLimit must always be <= OldestXmin */
1221 [ + + ]: 125021 : if (TransactionIdPrecedes(cutoffs->OldestXmin, cutoffs->FreezeLimit))
1222 : 103392 : cutoffs->FreezeLimit = cutoffs->OldestXmin;
1223 : :
1224 : : /*
1225 : : * Determine the minimum multixact freeze age to use: as specified by
1226 : : * caller, or vacuum_multixact_freeze_min_age, but in any case not more
1227 : : * than half effective_multixact_freeze_max_age, so that autovacuums to
1228 : : * prevent MultiXact wraparound won't occur too frequently.
1229 : : */
1230 [ + + ]: 125021 : if (multixact_freeze_min_age < 0)
1231 : 6665 : multixact_freeze_min_age = vacuum_multixact_freeze_min_age;
1232 : 125021 : multixact_freeze_min_age = Min(multixact_freeze_min_age,
1233 : : effective_multixact_freeze_max_age / 2);
1234 : : Assert(multixact_freeze_min_age >= 0);
1235 : :
1236 : : /* Compute MultiXactCutoff, being careful to generate a valid value */
1237 : 125021 : cutoffs->MultiXactCutoff = nextMXID - multixact_freeze_min_age;
1238 [ - + ]: 125021 : if (cutoffs->MultiXactCutoff < FirstMultiXactId)
1239 : 0 : cutoffs->MultiXactCutoff = FirstMultiXactId;
1240 : : /* MultiXactCutoff must always be <= OldestMxact */
1241 [ + + ]: 125021 : if (MultiXactIdPrecedes(cutoffs->OldestMxact, cutoffs->MultiXactCutoff))
1242 : 2 : cutoffs->MultiXactCutoff = cutoffs->OldestMxact;
1243 : :
1244 : : /*
1245 : : * Finally, figure out if caller needs to do an aggressive VACUUM or not.
1246 : : *
1247 : : * Determine the table freeze age to use: as specified by the caller, or
1248 : : * the value of the vacuum_freeze_table_age GUC, but in any case not more
1249 : : * than autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
1250 : : * VACUUM schedule, the nightly VACUUM gets a chance to freeze XIDs before
1251 : : * anti-wraparound autovacuum is launched.
1252 : : */
1253 [ + + ]: 125021 : if (freeze_table_age < 0)
1254 : 6665 : freeze_table_age = vacuum_freeze_table_age;
1255 [ + - ]: 125021 : freeze_table_age = Min(freeze_table_age, autovacuum_freeze_max_age * 0.95);
1256 : : Assert(freeze_table_age >= 0);
1257 : 125021 : aggressiveXIDCutoff = nextXID - freeze_table_age;
1258 [ - + ]: 125021 : if (!TransactionIdIsNormal(aggressiveXIDCutoff))
1259 : 0 : aggressiveXIDCutoff = FirstNormalTransactionId;
1260 [ + + ]: 125021 : if (TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid,
1261 : : aggressiveXIDCutoff))
1262 : 118268 : return true;
1263 : :
1264 : : /*
1265 : : * Similar to the above, determine the table freeze age to use for
1266 : : * multixacts: as specified by the caller, or the value of the
1267 : : * vacuum_multixact_freeze_table_age GUC, but in any case not more than
1268 : : * effective_multixact_freeze_max_age * 0.95, so that if you have e.g.
1269 : : * nightly VACUUM schedule, the nightly VACUUM gets a chance to freeze
1270 : : * multixacts before anti-wraparound autovacuum is launched.
1271 : : */
1272 [ + + ]: 6753 : if (multixact_freeze_table_age < 0)
1273 : 6556 : multixact_freeze_table_age = vacuum_multixact_freeze_table_age;
1274 : 6753 : multixact_freeze_table_age =
1275 [ + - ]: 6753 : Min(multixact_freeze_table_age,
1276 : : effective_multixact_freeze_max_age * 0.95);
1277 : : Assert(multixact_freeze_table_age >= 0);
1278 : 6753 : aggressiveMXIDCutoff = nextMXID - multixact_freeze_table_age;
1279 [ - + ]: 6753 : if (aggressiveMXIDCutoff < FirstMultiXactId)
1280 : 0 : aggressiveMXIDCutoff = FirstMultiXactId;
1281 [ - + ]: 6753 : if (MultiXactIdPrecedesOrEquals(cutoffs->relminmxid,
1282 : : aggressiveMXIDCutoff))
1283 : 0 : return true;
1284 : :
1285 : : /* Non-aggressive VACUUM */
1286 : 6753 : return false;
1287 : : }
1288 : :
1289 : : /*
1290 : : * vacuum_xid_failsafe_check() -- Used by VACUUM's wraparound failsafe
1291 : : * mechanism to determine if its table's relfrozenxid and relminmxid are now
1292 : : * dangerously far in the past.
1293 : : *
1294 : : * When we return true, VACUUM caller triggers the failsafe.
1295 : : */
1296 : : bool
1297 : 126990 : vacuum_xid_failsafe_check(const struct VacuumCutoffs *cutoffs)
1298 : : {
1299 : 126990 : TransactionId relfrozenxid = cutoffs->relfrozenxid;
1300 : 126990 : MultiXactId relminmxid = cutoffs->relminmxid;
1301 : : TransactionId xid_skip_limit;
1302 : : MultiXactId multi_skip_limit;
1303 : : int skip_index_vacuum;
1304 : :
1305 : : Assert(TransactionIdIsNormal(relfrozenxid));
1306 : : Assert(MultiXactIdIsValid(relminmxid));
1307 : :
1308 : : /*
1309 : : * Determine the index skipping age to use. In any case no less than
1310 : : * autovacuum_freeze_max_age * 1.05.
1311 : : */
1312 [ + - ]: 126990 : skip_index_vacuum = Max(vacuum_failsafe_age, autovacuum_freeze_max_age * 1.05);
1313 : :
1314 : 126990 : xid_skip_limit = ReadNextTransactionId() - skip_index_vacuum;
1315 [ - + ]: 126990 : if (!TransactionIdIsNormal(xid_skip_limit))
1316 : 0 : xid_skip_limit = FirstNormalTransactionId;
1317 : :
1318 [ + + ]: 126990 : if (TransactionIdPrecedes(relfrozenxid, xid_skip_limit))
1319 : : {
1320 : : /* The table's relfrozenxid is too old */
1321 : 25436 : return true;
1322 : : }
1323 : :
1324 : : /*
1325 : : * Similar to above, determine the index skipping age to use for
1326 : : * multixact. In any case no less than autovacuum_multixact_freeze_max_age *
1327 : : * 1.05.
1328 : : */
1329 [ + - ]: 101554 : skip_index_vacuum = Max(vacuum_multixact_failsafe_age,
1330 : : autovacuum_multixact_freeze_max_age * 1.05);
1331 : :
1332 : 101554 : multi_skip_limit = ReadNextMultiXactId() - skip_index_vacuum;
1333 [ - + ]: 101554 : if (multi_skip_limit < FirstMultiXactId)
1334 : 0 : multi_skip_limit = FirstMultiXactId;
1335 : :
1336 [ - + ]: 101554 : if (MultiXactIdPrecedes(relminmxid, multi_skip_limit))
1337 : : {
1338 : : /* The table's relminmxid is too old */
1339 : 0 : return true;
1340 : : }
1341 : :
1342 : 101554 : return false;
1343 : : }
1344 : :
1345 : : /*
1346 : : * vac_estimate_reltuples() -- estimate the new value for pg_class.reltuples
1347 : : *
1348 : : * If we scanned the whole relation then we should just use the count of
1349 : : * live tuples seen; but if we did not, we should not blindly extrapolate
1350 : : * from that number, since VACUUM may have scanned a quite nonrandom
1351 : : * subset of the table. When we have only partial information, we take
1352 : : * the old value of pg_class.reltuples/pg_class.relpages as a measurement
1353 : : * of the tuple density in the unscanned pages.
1354 : : *
1355 : : * Note: scanned_tuples should count only *live* tuples, since
1356 : : * pg_class.reltuples is defined that way.
1357 : : */
1358 : : double
1359 : 124581 : vac_estimate_reltuples(Relation relation,
1360 : : BlockNumber total_pages,
1361 : : BlockNumber scanned_pages,
1362 : : double scanned_tuples)
1363 : : {
1364 : 124581 : BlockNumber old_rel_pages = relation->rd_rel->relpages;
1365 : 124581 : double old_rel_tuples = relation->rd_rel->reltuples;
1366 : : double old_density;
1367 : : double unscanned_pages;
1368 : : double total_tuples;
1369 : :
1370 : : /* If we did scan the whole table, just use the count as-is */
1371 [ + + ]: 124581 : if (scanned_pages >= total_pages)
1372 : 120150 : return scanned_tuples;
1373 : :
1374 : : /*
1375 : : * When successive VACUUM commands scan the same few pages again and
1376 : : * again, without anything from the table really changing, there is a risk
1377 : : * that our beliefs about tuple density will gradually become distorted.
1378 : : * This might be caused by vacuumlazy.c implementation details, such as
1379 : : * its tendency to always scan the last heap page. Handle that here.
1380 : : *
1381 : : * If the relation is _exactly_ the same size according to the existing
1382 : : * pg_class entry, and only a few of its pages (less than 2%) were
1383 : : * scanned, keep the existing value of reltuples. Also keep the existing
1384 : : * value when only a subset of rel's pages <= a single page were scanned.
1385 : : *
1386 : : * (Note: we might be returning -1 here.)
1387 : : */
1388 [ + + ]: 4431 : if (old_rel_pages == total_pages &&
1389 [ + + ]: 4406 : scanned_pages < (double) total_pages * 0.02)
1390 : 3180 : return old_rel_tuples;
1391 [ + + ]: 1251 : if (scanned_pages <= 1)
1392 : 1098 : return old_rel_tuples;
1393 : :
1394 : : /*
1395 : : * If old density is unknown, we can't do much except scale up
1396 : : * scanned_tuples to match total_pages.
1397 : : */
1398 [ + + - + ]: 153 : if (old_rel_tuples < 0 || old_rel_pages == 0)
1399 : 5 : return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
1400 : :
1401 : : /*
1402 : : * Okay, we've covered the corner cases. The normal calculation is to
1403 : : * convert the old measurement to a density (tuples per page), then
1404 : : * estimate the number of tuples in the unscanned pages using that figure,
1405 : : * and finally add on the number of tuples in the scanned pages.
1406 : : */
1407 : 148 : old_density = old_rel_tuples / old_rel_pages;
1408 : 148 : unscanned_pages = (double) total_pages - (double) scanned_pages;
1409 : 148 : total_tuples = old_density * unscanned_pages + scanned_tuples;
1410 : 148 : return floor(total_tuples + 0.5);
1411 : : }
1412 : :
1413 : :
1414 : : /*
1415 : : * vac_update_relstats() -- update statistics for one relation
1416 : : *
1417 : : * Update the whole-relation statistics that are kept in its pg_class
1418 : : * row. There are additional stats that will be updated if we are
1419 : : * doing ANALYZE, but we always update these stats. This routine works
1420 : : * for both index and heap relation entries in pg_class.
1421 : : *
1422 : : * We violate transaction semantics here by overwriting the rel's
1423 : : * existing pg_class tuple with the new values. This is reasonably
1424 : : * safe as long as we're sure that the new values are correct whether or
1425 : : * not this transaction commits. The reason for doing this is that if
1426 : : * we updated these tuples in the usual way, vacuuming pg_class itself
1427 : : * wouldn't work very well --- by the time we got done with a vacuum
1428 : : * cycle, most of the tuples in pg_class would've been obsoleted. Of
1429 : : * course, this only works for fixed-size not-null columns, but these are.
1430 : : *
1431 : : * Another reason for doing it this way is that when we are in a lazy
1432 : : * VACUUM and have PROC_IN_VACUUM set, we mustn't do any regular updates.
1433 : : * Somebody vacuuming pg_class might think they could delete a tuple
1434 : : * marked with xmin = our xid.
1435 : : *
1436 : : * In addition to fundamentally nontransactional statistics such as
1437 : : * relpages and relallvisible, we try to maintain certain lazily-updated
1438 : : * DDL flags such as relhasindex, by clearing them if no longer correct.
1439 : : * It's safe to do this in VACUUM, which can't run in parallel with
1440 : : * CREATE INDEX/RULE/TRIGGER and can't be part of a transaction block.
1441 : : * However, it's *not* safe to do it in an ANALYZE that's within an
1442 : : * outer transaction, because for example the current transaction might
1443 : : * have dropped the last index; then we'd think relhasindex should be
1444 : : * cleared, but if the transaction later rolls back this would be wrong.
1445 : : * So we refrain from updating the DDL flags if we're inside an outer
1446 : : * transaction. This is OK since postponing the flag maintenance is
1447 : : * always allowable.
1448 : : *
1449 : : * Note: num_tuples should count only *live* tuples, since
1450 : : * pg_class.reltuples is defined that way.
1451 : : *
1452 : : * This routine is shared by VACUUM and ANALYZE.
1453 : : */
1454 : : void
1455 : 150414 : vac_update_relstats(Relation relation,
1456 : : BlockNumber num_pages, double num_tuples,
1457 : : BlockNumber num_all_visible_pages,
1458 : : BlockNumber num_all_frozen_pages,
1459 : : bool hasindex, TransactionId frozenxid,
1460 : : MultiXactId minmulti,
1461 : : bool *frozenxid_updated, bool *minmulti_updated,
1462 : : bool in_outer_xact)
1463 : : {
1464 : 150414 : Oid relid = RelationGetRelid(relation);
1465 : : Relation rd;
1466 : : ScanKeyData key[1];
1467 : : HeapTuple ctup;
1468 : : void *inplace_state;
1469 : : Form_pg_class pgcform;
1470 : : bool dirty,
1471 : : futurexid,
1472 : : futuremxid;
1473 : : TransactionId oldfrozenxid;
1474 : : MultiXactId oldminmulti;
1475 : :
1476 : 150414 : rd = table_open(RelationRelationId, RowExclusiveLock);
1477 : :
1478 : : /* Fetch a copy of the tuple to scribble on */
1479 : 150414 : ScanKeyInit(&key[0],
1480 : : Anum_pg_class_oid,
1481 : : BTEqualStrategyNumber, F_OIDEQ,
1482 : : ObjectIdGetDatum(relid));
1483 : 150414 : systable_inplace_update_begin(rd, ClassOidIndexId, true,
1484 : : NULL, 1, key, &ctup, &inplace_state);
1485 [ - + ]: 150414 : if (!HeapTupleIsValid(ctup))
1486 [ # # ]: 0 : elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
1487 : : relid);
1488 : 150414 : pgcform = (Form_pg_class) GETSTRUCT(ctup);
1489 : :
1490 : : /* Apply statistical updates, if any, to copied tuple */
1491 : :
1492 : 150414 : dirty = false;
1493 [ + + ]: 150414 : if (pgcform->relpages != (int32) num_pages)
1494 : : {
1495 : 5981 : pgcform->relpages = (int32) num_pages;
1496 : 5981 : dirty = true;
1497 : : }
1498 [ + + ]: 150414 : if (pgcform->reltuples != (float4) num_tuples)
1499 : : {
1500 : 12482 : pgcform->reltuples = (float4) num_tuples;
1501 : 12482 : dirty = true;
1502 : : }
1503 [ + + ]: 150414 : if (pgcform->relallvisible != (int32) num_all_visible_pages)
1504 : : {
1505 : 4011 : pgcform->relallvisible = (int32) num_all_visible_pages;
1506 : 4011 : dirty = true;
1507 : : }
1508 [ + + ]: 150414 : if (pgcform->relallfrozen != (int32) num_all_frozen_pages)
1509 : : {
1510 : 3384 : pgcform->relallfrozen = (int32) num_all_frozen_pages;
1511 : 3384 : dirty = true;
1512 : : }
1513 : :
1514 : : /* Apply DDL updates, but not inside an outer transaction (see above) */
1515 : :
1516 [ + + ]: 150414 : if (!in_outer_xact)
1517 : : {
1518 : : /*
1519 : : * If we didn't find any indexes, reset relhasindex.
1520 : : */
1521 [ + + + + ]: 150116 : if (pgcform->relhasindex && !hasindex)
1522 : : {
1523 : 13 : pgcform->relhasindex = false;
1524 : 13 : dirty = true;
1525 : : }
1526 : :
1527 : : /* We also clear relhasrules and relhastriggers if needed */
1528 [ + + - + ]: 150116 : if (pgcform->relhasrules && relation->rd_rules == NULL)
1529 : : {
1530 : 0 : pgcform->relhasrules = false;
1531 : 0 : dirty = true;
1532 : : }
1533 [ + + + + ]: 150116 : if (pgcform->relhastriggers && relation->trigdesc == NULL)
1534 : : {
1535 : 4 : pgcform->relhastriggers = false;
1536 : 4 : dirty = true;
1537 : : }
1538 : : }
1539 : :
1540 : : /*
1541 : : * Update relfrozenxid, unless caller passed InvalidTransactionId
1542 : : * indicating it has no new data.
1543 : : *
1544 : : * Ordinarily, we don't let relfrozenxid go backwards. However, if the
1545 : : * stored relfrozenxid is "in the future" then it seems best to assume
1546 : : * it's corrupt, and overwrite with the oldest remaining XID in the table.
1547 : : * This should match vac_update_datfrozenxid() concerning what we consider
1548 : : * to be "in the future".
1549 : : */
1550 : 150414 : oldfrozenxid = pgcform->relfrozenxid;
1551 : 150414 : futurexid = false;
1552 [ + + ]: 150414 : if (frozenxid_updated)
1553 : 124577 : *frozenxid_updated = false;
1554 [ + + + + ]: 150414 : if (TransactionIdIsNormal(frozenxid) && oldfrozenxid != frozenxid)
1555 : : {
1556 : 32062 : bool update = false;
1557 : :
1558 [ + + ]: 32062 : if (TransactionIdPrecedes(oldfrozenxid, frozenxid))
1559 : 32005 : update = true;
1560 [ - + ]: 57 : else if (TransactionIdPrecedes(ReadNextTransactionId(), oldfrozenxid))
1561 : 0 : futurexid = update = true;
1562 : :
1563 [ + + ]: 32062 : if (update)
1564 : : {
1565 : 32005 : pgcform->relfrozenxid = frozenxid;
1566 : 32005 : dirty = true;
1567 [ + - ]: 32005 : if (frozenxid_updated)
1568 : 32005 : *frozenxid_updated = true;
1569 : : }
1570 : : }
1571 : :
1572 : : /* Similarly for relminmxid */
1573 : 150414 : oldminmulti = pgcform->relminmxid;
1574 : 150414 : futuremxid = false;
1575 [ + + ]: 150414 : if (minmulti_updated)
1576 : 124577 : *minmulti_updated = false;
1577 [ + + + + ]: 150414 : if (MultiXactIdIsValid(minmulti) && oldminmulti != minmulti)
1578 : : {
1579 : 232 : bool update = false;
1580 : :
1581 [ + - ]: 232 : if (MultiXactIdPrecedes(oldminmulti, minmulti))
1582 : 232 : update = true;
1583 [ # # ]: 0 : else if (MultiXactIdPrecedes(ReadNextMultiXactId(), oldminmulti))
1584 : 0 : futuremxid = update = true;
1585 : :
1586 [ + - ]: 232 : if (update)
1587 : : {
1588 : 232 : pgcform->relminmxid = minmulti;
1589 : 232 : dirty = true;
1590 [ + - ]: 232 : if (minmulti_updated)
1591 : 232 : *minmulti_updated = true;
1592 : : }
1593 : : }
1594 : :
1595 : : /* If anything changed, write out the tuple. */
1596 [ + + ]: 150414 : if (dirty)
1597 : 40963 : systable_inplace_update_finish(inplace_state, ctup);
1598 : : else
1599 : 109451 : systable_inplace_update_cancel(inplace_state);
1600 : :
1601 : 150414 : table_close(rd, RowExclusiveLock);
1602 : :
1603 [ - + ]: 150414 : if (futurexid)
1604 [ # # ]: 0 : ereport(WARNING,
1605 : : (errcode(ERRCODE_DATA_CORRUPTED),
1606 : : errmsg_internal("overwrote invalid relfrozenxid value %u with new value %u for table \"%s\"",
1607 : : oldfrozenxid, frozenxid,
1608 : : RelationGetRelationName(relation))));
1609 [ - + ]: 150414 : if (futuremxid)
1610 [ # # ]: 0 : ereport(WARNING,
1611 : : (errcode(ERRCODE_DATA_CORRUPTED),
1612 : : errmsg_internal("overwrote invalid relminmxid value %u with new value %u for table \"%s\"",
1613 : : oldminmulti, minmulti,
1614 : : RelationGetRelationName(relation))));
1615 : 150414 : }
1616 : :
1617 : :
1618 : : /*
1619 : : * vac_update_datfrozenxid() -- update pg_database.datfrozenxid for our DB
1620 : : *
1621 : : * Update pg_database's datfrozenxid entry for our database to be the
1622 : : * minimum of the pg_class.relfrozenxid values.
1623 : : *
1624 : : * Similarly, update our datminmxid to be the minimum of the
1625 : : * pg_class.relminmxid values.
1626 : : *
1627 : : * If we are able to advance either pg_database value, also try to
1628 : : * truncate pg_xact and pg_multixact.
1629 : : *
1630 : : * We violate transaction semantics here by overwriting the database's
1631 : : * existing pg_database tuple with the new values. This is reasonably
1632 : : * safe since the new values are correct whether or not this transaction
1633 : : * commits. As with vac_update_relstats, this avoids leaving dead tuples
1634 : : * behind after a VACUUM.
1635 : : */
1636 : : void
1637 : 2803 : vac_update_datfrozenxid(void)
1638 : : {
1639 : : HeapTuple tuple;
1640 : : Form_pg_database dbform;
1641 : : Relation relation;
1642 : : SysScanDesc scan;
1643 : : HeapTuple classTup;
1644 : : TransactionId newFrozenXid;
1645 : : MultiXactId newMinMulti;
1646 : : TransactionId lastSaneFrozenXid;
1647 : : MultiXactId lastSaneMinMulti;
1648 : 2803 : bool bogus = false;
1649 : 2803 : bool dirty = false;
1650 : : ScanKeyData key[1];
1651 : : void *inplace_state;
1652 : :
1653 : : /*
1654 : : * Restrict this task to one backend per database. This avoids race
1655 : : * conditions that would move datfrozenxid or datminmxid backward. It
1656 : : * avoids calling vac_truncate_clog() with a datfrozenxid preceding a
1657 : : * datfrozenxid passed to an earlier vac_truncate_clog() call.
1658 : : */
1659 : 2803 : LockDatabaseFrozenIds(ExclusiveLock);
1660 : :
1661 : : /*
1662 : : * Initialize the "min" calculation with
1663 : : * GetOldestNonRemovableTransactionId(), which is a reasonable
1664 : : * approximation to the minimum relfrozenxid for not-yet-committed
1665 : : * pg_class entries for new tables; see AddNewRelationTuple(). So we
1666 : : * cannot produce a wrong minimum by starting with this.
1667 : : */
1668 : 2803 : newFrozenXid = GetOldestNonRemovableTransactionId(NULL);
1669 : :
1670 : : /*
1671 : : * Similarly, initialize the MultiXact "min" with the value that would be
1672 : : * used on pg_class for new tables. See AddNewRelationTuple().
1673 : : */
1674 : 2803 : newMinMulti = GetOldestMultiXactId();
1675 : :
1676 : : /*
1677 : : * Identify the latest relfrozenxid and relminmxid values that we could
1678 : : * validly see during the scan. These are conservative values, but it's
1679 : : * not really worth trying to be more exact.
1680 : : */
1681 : 2803 : lastSaneFrozenXid = ReadNextTransactionId();
1682 : 2803 : lastSaneMinMulti = ReadNextMultiXactId();
1683 : :
1684 : : /*
1685 : : * We must seqscan pg_class to find the minimum Xid, because there is no
1686 : : * index that can help us here.
1687 : : *
1688 : : * See vac_truncate_clog() for the race condition to prevent.
1689 : : */
1690 : 2803 : relation = table_open(RelationRelationId, AccessShareLock);
1691 : :
1692 : 2803 : scan = systable_beginscan(relation, InvalidOid, false,
1693 : : NULL, 0, NULL);
1694 : :
1695 [ + + ]: 1510029 : while ((classTup = systable_getnext(scan)) != NULL)
1696 : : {
1697 : 1507226 : Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
1698 : 1507226 : volatile TransactionId *relfrozenxid_p = &classForm->relfrozenxid;
1699 : 1507226 : volatile TransactionId *relminmxid_p = &classForm->relminmxid;
1700 : 1507226 : TransactionId relfrozenxid = *relfrozenxid_p;
1701 : 1507226 : TransactionId relminmxid = *relminmxid_p;
1702 : :
1703 : : /*
1704 : : * Only consider relations able to hold unfrozen XIDs (anything else
1705 : : * should have InvalidTransactionId in relfrozenxid anyway).
1706 : : */
1707 [ + + ]: 1507226 : if (classForm->relkind != RELKIND_RELATION &&
1708 [ + + ]: 1188845 : classForm->relkind != RELKIND_MATVIEW &&
1709 [ + + ]: 1187183 : classForm->relkind != RELKIND_TOASTVALUE)
1710 : : {
1711 : : Assert(!TransactionIdIsValid(relfrozenxid));
1712 : : Assert(!MultiXactIdIsValid(relminmxid));
1713 : 1025360 : continue;
1714 : : }
1715 : :
1716 : : /*
1717 : : * Some table AMs might not need per-relation xid / multixid horizons.
1718 : : * It therefore seems reasonable to allow relfrozenxid and relminmxid
1719 : : * to not be set (i.e. set to their respective Invalid*Id)
1720 : : * independently. Thus validate and compute horizon for each only if
1721 : : * set.
1722 : : *
1723 : : * If things are working properly, no relation should have a
1724 : : * relfrozenxid or relminmxid that is "in the future". However, such
1725 : : * cases have been known to arise due to bugs in pg_upgrade. If we
1726 : : * see any entries that are "in the future", chicken out and don't do
1727 : : * anything. This ensures we won't truncate clog & multixact SLRUs
1728 : : * before those relations have been scanned and cleaned up.
1729 : : */
1730 : :
1731 [ + - ]: 481866 : if (TransactionIdIsValid(relfrozenxid))
1732 : : {
1733 : : Assert(TransactionIdIsNormal(relfrozenxid));
1734 : :
1735 : : /* check for values in the future */
1736 [ - + ]: 481866 : if (TransactionIdPrecedes(lastSaneFrozenXid, relfrozenxid))
1737 : : {
1738 : 0 : bogus = true;
1739 : 0 : break;
1740 : : }
1741 : :
1742 : : /* determine new horizon */
1743 [ + + ]: 481866 : if (TransactionIdPrecedes(relfrozenxid, newFrozenXid))
1744 : 2613 : newFrozenXid = relfrozenxid;
1745 : : }
1746 : :
1747 [ + - ]: 481866 : if (MultiXactIdIsValid(relminmxid))
1748 : : {
1749 : : /* check for values in the future */
1750 [ - + ]: 481866 : if (MultiXactIdPrecedes(lastSaneMinMulti, relminmxid))
1751 : : {
1752 : 0 : bogus = true;
1753 : 0 : break;
1754 : : }
1755 : :
1756 : : /* determine new horizon */
1757 [ + + ]: 481866 : if (MultiXactIdPrecedes(relminmxid, newMinMulti))
1758 : 225 : newMinMulti = relminmxid;
1759 : : }
1760 : : }
1761 : :
1762 : : /* we're done with pg_class */
1763 : 2803 : systable_endscan(scan);
1764 : 2803 : table_close(relation, AccessShareLock);
1765 : :
1766 : : /* chicken out if bogus data found */
1767 [ - + ]: 2803 : if (bogus)
1768 : 0 : return;
1769 : :
1770 : : Assert(TransactionIdIsNormal(newFrozenXid));
1771 : : Assert(MultiXactIdIsValid(newMinMulti));
1772 : :
1773 : : /* Now fetch the pg_database tuple we need to update. */
1774 : 2803 : relation = table_open(DatabaseRelationId, RowExclusiveLock);
1775 : :
1776 : : /*
1777 : : * Fetch a copy of the tuple to scribble on. We could check the syscache
1778 : : * tuple first. If that concluded !dirty, we'd avoid waiting on
1779 : : * concurrent heap_update() and would avoid exclusive-locking the buffer.
1780 : : * For now, don't optimize that.
1781 : : */
1782 : 2803 : ScanKeyInit(&key[0],
1783 : : Anum_pg_database_oid,
1784 : : BTEqualStrategyNumber, F_OIDEQ,
1785 : : ObjectIdGetDatum(MyDatabaseId));
1786 : :
1787 : 2803 : systable_inplace_update_begin(relation, DatabaseOidIndexId, true,
1788 : : NULL, 1, key, &tuple, &inplace_state);
1789 : :
1790 [ - + ]: 2803 : if (!HeapTupleIsValid(tuple))
1791 [ # # ]: 0 : elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
1792 : :
1793 : 2803 : dbform = (Form_pg_database) GETSTRUCT(tuple);
1794 : :
1795 : : /*
1796 : : * As in vac_update_relstats(), we ordinarily don't want to let
1797 : : * datfrozenxid go backward; but if it's "in the future" then it must be
1798 : : * corrupt and it seems best to overwrite it.
1799 : : */
1800 [ + + - + ]: 3157 : if (dbform->datfrozenxid != newFrozenXid &&
1801 [ - - ]: 354 : (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) ||
1802 : 0 : TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid)))
1803 : : {
1804 : 354 : dbform->datfrozenxid = newFrozenXid;
1805 : 354 : dirty = true;
1806 : : }
1807 : : else
1808 : 2449 : newFrozenXid = dbform->datfrozenxid;
1809 : :
1810 : : /* Ditto for datminmxid */
1811 [ + + - + ]: 2804 : if (dbform->datminmxid != newMinMulti &&
1812 [ - - ]: 1 : (MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) ||
1813 : 0 : MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid)))
1814 : : {
1815 : 1 : dbform->datminmxid = newMinMulti;
1816 : 1 : dirty = true;
1817 : : }
1818 : : else
1819 : 2802 : newMinMulti = dbform->datminmxid;
1820 : :
1821 [ + + ]: 2803 : if (dirty)
1822 : 354 : systable_inplace_update_finish(inplace_state, tuple);
1823 : : else
1824 : 2449 : systable_inplace_update_cancel(inplace_state);
1825 : :
1826 : 2803 : heap_freetuple(tuple);
1827 : 2803 : table_close(relation, RowExclusiveLock);
1828 : :
1829 : : /*
1830 : : * If we were able to advance datfrozenxid or datminmxid, see if we can
1831 : : * truncate pg_xact and/or pg_multixact. Also do it if the shared
1832 : : * XID-wrap-limit info is stale, since this action will update that too.
1833 : : */
1834 [ + + + + ]: 2803 : if (dirty || ForceTransactionIdLimitUpdate())
1835 : 1221 : vac_truncate_clog(newFrozenXid, newMinMulti,
1836 : : lastSaneFrozenXid, lastSaneMinMulti);
1837 : : }
1838 : :
1839 : :
1840 : : /*
1841 : : * vac_truncate_clog() -- attempt to truncate the commit log
1842 : : *
1843 : : * Scan pg_database to determine the system-wide oldest datfrozenxid,
1844 : : * and use it to truncate the transaction commit log (pg_xact).
1845 : : * Also update the XID wrap limit info maintained by varsup.c.
1846 : : * Likewise for datminmxid.
1847 : : *
1848 : : * The passed frozenXID and minMulti are the updated values for my own
1849 : : * pg_database entry. They're used to initialize the "min" calculations.
1850 : : * The caller also passes the "last sane" XID and MXID, since it has
1851 : : * those at hand already.
1852 : : *
1853 : : * This routine is only invoked when we've managed to change our
1854 : : * DB's datfrozenxid/datminmxid values, or we found that the shared
1855 : : * XID-wrap-limit info is stale.
1856 : : */
1857 : : static void
1858 : 1221 : vac_truncate_clog(TransactionId frozenXID,
1859 : : MultiXactId minMulti,
1860 : : TransactionId lastSaneFrozenXid,
1861 : : MultiXactId lastSaneMinMulti)
1862 : : {
1863 : 1221 : TransactionId nextXID = ReadNextTransactionId();
1864 : : Relation relation;
1865 : : TableScanDesc scan;
1866 : : HeapTuple tuple;
1867 : : Oid oldestxid_datoid;
1868 : : Oid minmulti_datoid;
1869 : 1221 : bool bogus = false;
1870 : 1221 : bool frozenAlreadyWrapped = false;
1871 : :
1872 : : /* Restrict task to one backend per cluster; see SimpleLruTruncate(). */
1873 : 1221 : LWLockAcquire(WrapLimitsVacuumLock, LW_EXCLUSIVE);
1874 : :
1875 : : /* init oldest datoids to sync with my frozenXID/minMulti values */
1876 : 1221 : oldestxid_datoid = MyDatabaseId;
1877 : 1221 : minmulti_datoid = MyDatabaseId;
1878 : :
1879 : : /*
1880 : : * Scan pg_database to compute the minimum datfrozenxid/datminmxid
1881 : : *
1882 : : * Since vac_update_datfrozenxid updates datfrozenxid/datminmxid in-place,
1883 : : * the values could change while we look at them. Fetch each one just
1884 : : * once to ensure sane behavior of the comparison logic. (Here, as in
1885 : : * many other places, we assume that fetching or updating an XID in shared
1886 : : * storage is atomic.)
1887 : : *
1888 : : * Note: we need not worry about a race condition with new entries being
1889 : : * inserted by CREATE DATABASE. Any such entry will have a copy of some
1890 : : * existing DB's datfrozenxid, and that source DB cannot be ours because
1891 : : * of the interlock against copying a DB containing an active backend.
1892 : : * Hence the new entry will not reduce the minimum. Also, if two VACUUMs
1893 : : * concurrently modify the datfrozenxid's of different databases, the
1894 : : * worst possible outcome is that pg_xact is not truncated as aggressively
1895 : : * as it could be.
1896 : : */
1897 : 1221 : relation = table_open(DatabaseRelationId, AccessShareLock);
1898 : :
1899 : 1221 : scan = table_beginscan_catalog(relation, 0, NULL);
1900 : :
1901 [ + + ]: 4782 : while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1902 : : {
1903 : 3561 : Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1904 : 3561 : volatile TransactionId *datfrozenxid_p = &dbform->datfrozenxid;
1905 : 3561 : volatile TransactionId *datminmxid_p = &dbform->datminmxid;
1906 : 3561 : TransactionId datfrozenxid = *datfrozenxid_p;
1907 : 3561 : TransactionId datminmxid = *datminmxid_p;
1908 : :
1909 : : Assert(TransactionIdIsNormal(datfrozenxid));
1910 : : Assert(MultiXactIdIsValid(datminmxid));
1911 : :
1912 : : /*
1913 : : * If database is in the process of getting dropped, or has been
1914 : : * interrupted while doing so, no connections to it are possible
1915 : : * anymore. Therefore we don't need to take it into account here.
1916 : : * Which is good, because it can't be processed by autovacuum either.
1917 : : */
1918 [ + + ]: 3561 : if (database_is_invalid_form((Form_pg_database) dbform))
1919 : : {
1920 [ - + ]: 3 : elog(DEBUG2,
1921 : : "skipping invalid database \"%s\" while computing relfrozenxid",
1922 : : NameStr(dbform->datname));
1923 : 3 : continue;
1924 : : }
1925 : :
1926 : : /*
1927 : : * If things are working properly, no database should have a
1928 : : * datfrozenxid or datminmxid that is "in the future". However, such
1929 : : * cases have been known to arise due to bugs in pg_upgrade. If we
1930 : : * see any entries that are "in the future", chicken out and don't do
1931 : : * anything. This ensures we won't truncate clog before those
1932 : : * databases have been scanned and cleaned up. (We will issue the
1933 : : * "already wrapped" warning if appropriate, though.)
1934 : : */
1935 [ + - - + ]: 7116 : if (TransactionIdPrecedes(lastSaneFrozenXid, datfrozenxid) ||
1936 : 3558 : MultiXactIdPrecedes(lastSaneMinMulti, datminmxid))
1937 : 0 : bogus = true;
1938 : :
1939 [ - + ]: 3558 : if (TransactionIdPrecedes(nextXID, datfrozenxid))
1940 : 0 : frozenAlreadyWrapped = true;
1941 [ + + ]: 3558 : else if (TransactionIdPrecedes(datfrozenxid, frozenXID))
1942 : : {
1943 : 262 : frozenXID = datfrozenxid;
1944 : 262 : oldestxid_datoid = dbform->oid;
1945 : : }
1946 : :
1947 [ + + ]: 3558 : if (MultiXactIdPrecedes(datminmxid, minMulti))
1948 : : {
1949 : 2 : minMulti = datminmxid;
1950 : 2 : minmulti_datoid = dbform->oid;
1951 : : }
1952 : : }
1953 : :
1954 : 1221 : table_endscan(scan);
1955 : :
1956 : 1221 : table_close(relation, AccessShareLock);
1957 : :
1958 : : /*
1959 : : * Do not truncate CLOG if we seem to have suffered wraparound already;
1960 : : * the computed minimum XID might be bogus. This case should now be
1961 : : * impossible due to the defenses in GetNewTransactionId, but we keep the
1962 : : * test anyway.
1963 : : */
1964 [ - + ]: 1221 : if (frozenAlreadyWrapped)
1965 : : {
1966 [ # # ]: 0 : ereport(WARNING,
1967 : : (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
1968 : : errdetail("You might have already suffered transaction-wraparound data loss.")));
1969 : 0 : LWLockRelease(WrapLimitsVacuumLock);
1970 : 0 : return;
1971 : : }
1972 : :
1973 : : /* chicken out if data is bogus in any other way */
1974 [ - + ]: 1221 : if (bogus)
1975 : : {
1976 : 0 : LWLockRelease(WrapLimitsVacuumLock);
1977 : 0 : return;
1978 : : }
1979 : :
1980 : : /*
1981 : : * Freeze any old transaction IDs in the async notification queue before
1982 : : * CLOG truncation.
1983 : : */
1984 : 1221 : AsyncNotifyFreezeXids(frozenXID);
1985 : :
1986 : : /*
1987 : : * Advance the oldest value for commit timestamps before truncating, so
1988 : : * that if a user requests a timestamp for a transaction we're truncating
1989 : : * away right after this point, they get NULL instead of an ugly "file not
1990 : : * found" error from slru.c. This doesn't matter for xact/multixact
1991 : : * because they are not subject to arbitrary lookups from users.
1992 : : */
1993 : 1221 : AdvanceOldestCommitTsXid(frozenXID);
1994 : :
1995 : : /*
1996 : : * Truncate CLOG, multixact and CommitTs to the oldest computed value.
1997 : : */
1998 : 1221 : TruncateCLOG(frozenXID, oldestxid_datoid);
1999 : 1221 : TruncateCommitTs(frozenXID);
2000 : 1221 : TruncateMultiXact(minMulti, minmulti_datoid);
2001 : :
2002 : : /*
2003 : : * Update the wrap limit for GetNewTransactionId and creation of new
2004 : : * MultiXactIds. Note: these functions will also signal the postmaster
2005 : : * for an(other) autovac cycle if needed. XXX should we avoid possibly
2006 : : * signaling twice?
2007 : : */
2008 : 1221 : SetTransactionIdLimit(frozenXID, oldestxid_datoid);
2009 : 1221 : SetMultiXactIdLimit(minMulti, minmulti_datoid);
2010 : :
2011 : 1221 : LWLockRelease(WrapLimitsVacuumLock);
2012 : : }
2013 : :
2014 : :
2015 : : /*
2016 : : * vacuum_rel() -- vacuum one heap relation
2017 : : *
2018 : : * relid identifies the relation to vacuum. If relation is supplied,
2019 : : * use the name therein for reporting any failure to open/lock the rel;
2020 : : * do not use it once we've successfully opened the rel, since it might
2021 : : * be stale.
2022 : : *
2023 : : * Returns true if it's okay to proceed with a requested ANALYZE
2024 : : * operation on this table.
2025 : : *
2026 : : * Doing one heap at a time incurs extra overhead, since we need to
2027 : : * check that the heap exists again just before we vacuum it. The
2028 : : * reason that we do this is so that vacuuming can be spread across
2029 : : * many small transactions. Otherwise, two-phase locking would require
2030 : : * us to lock the entire database during one pass of the vacuum cleaner.
2031 : : *
2032 : : * At entry and exit, we are not inside a transaction.
2033 : : */
2034 : : static bool
2035 : 125086 : vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params,
2036 : : BufferAccessStrategy bstrategy, bool isTopLevel)
2037 : : {
2038 : : LOCKMODE lmode;
2039 : : Relation rel;
2040 : : LockRelId lockrelid;
2041 : : Oid priv_relid;
2042 : : Oid toast_relid;
2043 : : Oid save_userid;
2044 : : int save_sec_context;
2045 : : int save_nestlevel;
2046 : : VacuumParams toast_vacuum_params;
2047 : : StdRdOptions *relopts;
2048 : : StdRdOptions relopts_copy;
2049 : :
2050 : : /*
2051 : : * This function scribbles on the parameters, so make a copy early to
2052 : : * avoid affecting the TOAST table (if we do end up recursing to it).
2053 : : */
2054 : 125086 : memcpy(&toast_vacuum_params, ¶ms, sizeof(VacuumParams));
2055 : :
2056 : : /* Begin a transaction for vacuuming this relation */
2057 : 125086 : StartTransactionCommand();
2058 : :
2059 [ + + ]: 125086 : if (!(params.options & VACOPT_FULL))
2060 : : {
2061 : : /*
2062 : : * In lazy vacuum, we can set the PROC_IN_VACUUM flag, which lets
2063 : : * other concurrent VACUUMs know that they can ignore this one while
2064 : : * determining their OldestXmin. (The reason we don't set it during a
2065 : : * full VACUUM is exactly that we may have to run user-defined
2066 : : * functions for functional indexes, and we want to make sure that if
2067 : : * they use the snapshot set above, any tuples it requires can't get
2068 : : * removed from other tables. An index function that depends on the
2069 : : * contents of other tables is arguably broken, but we won't break it
2070 : : * here by violating transaction semantics.)
2071 : : *
2072 : : * We also set the VACUUM_FOR_WRAPAROUND flag, which is passed down by
2073 : : * autovacuum; it's used to avoid canceling a vacuum that was invoked
2074 : : * in an emergency.
2075 : : *
2076 : : * Note: these flags remain set until CommitTransaction or
2077 : : * AbortTransaction. We don't want to clear them until we reset
2078 : : * MyProc->xid/xmin, otherwise GetOldestNonRemovableTransactionId()
2079 : : * might appear to go backwards, which is probably Not Good. (We also
2080 : : * set PROC_IN_VACUUM *before* taking our own snapshot, so that our
2081 : : * xmin doesn't become visible ahead of setting the flag.)
2082 : : */
2083 : 124828 : LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
2084 : 124828 : MyProc->statusFlags |= PROC_IN_VACUUM;
2085 [ + + ]: 124828 : if (params.is_wraparound)
2086 : 108458 : MyProc->statusFlags |= PROC_VACUUM_FOR_WRAPAROUND;
2087 : 124828 : ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
2088 : 124828 : LWLockRelease(ProcArrayLock);
2089 : : }
2090 : :
2091 : : /*
2092 : : * Need to acquire a snapshot to prevent pg_subtrans from being truncated,
2093 : : * cutoff xids in local memory wrapping around, and to have updated xmin
2094 : : * horizons.
2095 : : */
2096 : 125086 : PushActiveSnapshot(GetTransactionSnapshot());
2097 : :
2098 : : /*
2099 : : * Check for user-requested abort. Note we want this to be inside a
2100 : : * transaction, so xact.c doesn't issue useless WARNING.
2101 : : */
2102 [ - + ]: 125086 : CHECK_FOR_INTERRUPTS();
2103 : :
2104 : : /*
2105 : : * Determine the type of lock we want --- hard exclusive lock for a FULL
2106 : : * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either
2107 : : * way, we can be sure that no other backend is vacuuming the same table.
2108 : : */
2109 : 250172 : lmode = (params.options & VACOPT_FULL) ?
2110 [ + + ]: 125086 : AccessExclusiveLock : ShareUpdateExclusiveLock;
2111 : :
2112 : : /* open the relation and get the appropriate lock on it */
2113 : 125086 : rel = vacuum_open_relation(relid, relation, params.options,
2114 : 125086 : params.log_vacuum_min_duration >= 0, lmode);
2115 : :
2116 : : /* leave if relation could not be opened or locked */
2117 [ + + ]: 125086 : if (!rel)
2118 : : {
2119 : 13 : PopActiveSnapshot();
2120 : 13 : CommitTransactionCommand();
2121 : 13 : return false;
2122 : : }
2123 : :
2124 : : /*
2125 : : * When recursing to a TOAST table, check privileges on the parent. NB:
2126 : : * This is only safe to do because we hold a session lock on the main
2127 : : * relation that prevents concurrent deletion.
2128 : : */
2129 [ + + ]: 125073 : if (OidIsValid(params.toast_parent))
2130 : 5600 : priv_relid = params.toast_parent;
2131 : : else
2132 : 119473 : priv_relid = RelationGetRelid(rel);
2133 : :
2134 : : /*
2135 : : * Check if relation needs to be skipped based on privileges. This check
2136 : : * happens also when building the relation list to vacuum for a manual
2137 : : * operation, and needs to be done additionally here as VACUUM could
2138 : : * happen across multiple transactions where privileges could have changed
2139 : : * in-between. Make sure to only generate logs for VACUUM in this case.
2140 : : */
2141 [ + + ]: 125073 : if (!vacuum_is_permitted_for_relation(priv_relid,
2142 : : rel->rd_rel,
2143 : 125073 : params.options & ~VACOPT_ANALYZE,
2144 : : false))
2145 : : {
2146 : 48 : relation_close(rel, lmode);
2147 : 48 : PopActiveSnapshot();
2148 : 48 : CommitTransactionCommand();
2149 : 48 : return false;
2150 : : }
2151 : :
2152 : : /*
2153 : : * Check that it's of a vacuumable relkind.
2154 : : */
2155 [ + + ]: 125025 : if (rel->rd_rel->relkind != RELKIND_RELATION &&
2156 [ + + ]: 45482 : rel->rd_rel->relkind != RELKIND_MATVIEW &&
2157 [ + + ]: 45477 : rel->rd_rel->relkind != RELKIND_TOASTVALUE &&
2158 [ + + ]: 128 : rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2159 : : {
2160 [ + - ]: 1 : ereport(WARNING,
2161 : : (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
2162 : : RelationGetRelationName(rel))));
2163 : 1 : relation_close(rel, lmode);
2164 : 1 : PopActiveSnapshot();
2165 : 1 : CommitTransactionCommand();
2166 : 1 : return false;
2167 : : }
2168 : :
2169 : : /*
2170 : : * Silently ignore tables that are temp tables of other backends ---
2171 : : * trying to vacuum these will lead to great unhappiness, since their
2172 : : * contents are probably not up-to-date on disk. (We don't throw a
2173 : : * warning here; it would just lead to chatter during a database-wide
2174 : : * VACUUM.)
2175 : : */
2176 [ + + + + ]: 125024 : if (RELATION_IS_OTHER_TEMP(rel))
2177 : : {
2178 : 1 : relation_close(rel, lmode);
2179 : 1 : PopActiveSnapshot();
2180 : 1 : CommitTransactionCommand();
2181 : 1 : return false;
2182 : : }
2183 : :
2184 : : /*
2185 : : * Silently ignore partitioned tables as there is no work to be done. The
2186 : : * useful work is on their child partitions, which have been queued up for
2187 : : * us separately.
2188 : : */
2189 [ + + ]: 125023 : if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2190 : : {
2191 : 127 : relation_close(rel, lmode);
2192 : 127 : PopActiveSnapshot();
2193 : 127 : CommitTransactionCommand();
2194 : : /* It's OK to proceed with ANALYZE on this table */
2195 : 127 : return true;
2196 : : }
2197 : :
2198 : : /*
2199 : : * Get a session-level lock too. This will protect our access to the
2200 : : * relation across multiple transactions, so that we can vacuum the
2201 : : * relation's TOAST table (if any) secure in the knowledge that no one is
2202 : : * deleting the parent relation.
2203 : : *
2204 : : * NOTE: this cannot block, even if someone else is waiting for access,
2205 : : * because the lock manager knows that both lock requests are from the
2206 : : * same process.
2207 : : */
2208 : 124896 : lockrelid = rel->rd_lockInfo.lockRelId;
2209 : 124896 : LockRelationIdForSession(&lockrelid, lmode);
2210 : :
2211 : : /*
2212 : : * Determine the storage parameters to use. A TOAST table takes any
2213 : : * storage parameter it accepts but does not set from its main table,
2214 : : * whose parameters the caller handed down for that purpose. For anything
2215 : : * else, params.main_relopts is NULL, and this just copies our own.
2216 : : */
2217 : 124896 : relopts = merge_toast_reloptions((StdRdOptions *) rel->rd_options,
2218 : : params.main_relopts);
2219 : :
2220 : : /*
2221 : : * Set index_cleanup option based on index_cleanup reloption if it wasn't
2222 : : * specified in VACUUM command, or when running in an autovacuum worker
2223 : : */
2224 [ + + ]: 124896 : if (params.index_cleanup == VACOPTVALUE_UNSPECIFIED)
2225 : : {
2226 : : StdRdOptIndexCleanup vacuum_index_cleanup;
2227 : :
2228 [ + + ]: 124756 : if (relopts == NULL)
2229 : 121977 : vacuum_index_cleanup = STDRD_OPTION_VACUUM_INDEX_CLEANUP_NOT_SET;
2230 : : else
2231 : 2779 : vacuum_index_cleanup = relopts->vacuum_index_cleanup;
2232 : :
2233 [ + + + + : 124756 : switch (vacuum_index_cleanup)
- ]
2234 : : {
2235 : 18 : case STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON:
2236 : 18 : params.index_cleanup = VACOPTVALUE_ENABLED;
2237 : 18 : break;
2238 : 20 : case STDRD_OPTION_VACUUM_INDEX_CLEANUP_OFF:
2239 : 20 : params.index_cleanup = VACOPTVALUE_DISABLED;
2240 : 20 : break;
2241 : 12 : case STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO:
2242 : 12 : params.index_cleanup = VACOPTVALUE_AUTO;
2243 : 12 : break;
2244 : 124706 : case STDRD_OPTION_VACUUM_INDEX_CLEANUP_NOT_SET:
2245 : 124706 : params.index_cleanup = VACOPTVALUE_AUTO;
2246 : 124706 : break;
2247 : : }
2248 : : }
2249 : :
2250 : : #ifdef USE_INJECTION_POINTS
2251 [ + + ]: 124896 : if (params.index_cleanup == VACOPTVALUE_AUTO)
2252 : 124722 : INJECTION_POINT("vacuum-index-cleanup-auto", NULL);
2253 [ + + ]: 174 : else if (params.index_cleanup == VACOPTVALUE_DISABLED)
2254 : 143 : INJECTION_POINT("vacuum-index-cleanup-disabled", NULL);
2255 [ + - ]: 31 : else if (params.index_cleanup == VACOPTVALUE_ENABLED)
2256 : 31 : INJECTION_POINT("vacuum-index-cleanup-enabled", NULL);
2257 : : #endif
2258 : :
2259 : : /*
2260 : : * Check if the vacuum_max_eager_freeze_failure_rate table storage
2261 : : * parameter was specified. This overrides the GUC value.
2262 : : */
2263 [ + + - + ]: 124896 : if (relopts != NULL && relopts->vacuum_max_eager_freeze_failure_rate >= 0)
2264 : 0 : params.max_eager_freeze_failure_rate = relopts->vacuum_max_eager_freeze_failure_rate;
2265 : :
2266 : : /*
2267 : : * Set truncate option based on truncate reloption or GUC if it wasn't
2268 : : * specified in VACUUM command, or when running in an autovacuum worker
2269 : : */
2270 [ + + ]: 124896 : if (params.truncate == VACOPTVALUE_UNSPECIFIED)
2271 : : {
2272 [ + + + + ]: 124764 : if (relopts && relopts->vacuum_truncate != PG_TERNARY_UNSET)
2273 : : {
2274 [ + + ]: 27 : if (relopts->vacuum_truncate == PG_TERNARY_TRUE)
2275 : 11 : params.truncate = VACOPTVALUE_ENABLED;
2276 : : else
2277 : 16 : params.truncate = VACOPTVALUE_DISABLED;
2278 : : }
2279 [ + + ]: 124737 : else if (vacuum_truncate)
2280 : 124727 : params.truncate = VACOPTVALUE_ENABLED;
2281 : : else
2282 : 10 : params.truncate = VACOPTVALUE_DISABLED;
2283 : : }
2284 : :
2285 : : #ifdef USE_INJECTION_POINTS
2286 [ - + ]: 124896 : if (params.truncate == VACOPTVALUE_AUTO)
2287 : 0 : INJECTION_POINT("vacuum-truncate-auto", NULL);
2288 [ + + ]: 124896 : else if (params.truncate == VACOPTVALUE_DISABLED)
2289 : 157 : INJECTION_POINT("vacuum-truncate-disabled", NULL);
2290 [ + - ]: 124739 : else if (params.truncate == VACOPTVALUE_ENABLED)
2291 : 124739 : INJECTION_POINT("vacuum-truncate-enabled", NULL);
2292 : : #endif
2293 : :
2294 : : /*
2295 : : * Remember the relation's TOAST relation for later, if the caller asked
2296 : : * us to process it. In VACUUM FULL, though, the toast table is
2297 : : * automatically rebuilt by cluster_rel so we shouldn't recurse to it,
2298 : : * unless PROCESS_MAIN is disabled.
2299 : : */
2300 [ + + ]: 124896 : if ((params.options & VACOPT_PROCESS_TOAST) != 0 &&
2301 [ + + ]: 16129 : ((params.options & VACOPT_FULL) == 0 ||
2302 [ + + ]: 241 : (params.options & VACOPT_PROCESS_MAIN) == 0))
2303 : 15892 : toast_relid = rel->rd_rel->reltoastrelid;
2304 : : else
2305 : 109004 : toast_relid = InvalidOid;
2306 : :
2307 : : /*
2308 : : * Hand our storage parameters down for the TOAST table to inherit. Take
2309 : : * a copy while we still have the relation open; the relcache entry can go
2310 : : * away once we close it.
2311 : : */
2312 [ + + + + ]: 124896 : if (OidIsValid(toast_relid) && rel->rd_options)
2313 : : {
2314 : 128 : memcpy(&relopts_copy, rel->rd_options, sizeof(StdRdOptions));
2315 : 128 : toast_vacuum_params.main_relopts = &relopts_copy;
2316 : : }
2317 : :
2318 : : /*
2319 : : * Switch to the table owner's userid, so that any index functions are run
2320 : : * as that user. Also lock down security-restricted operations and
2321 : : * arrange to make GUC variable changes local to this command. (This is
2322 : : * unnecessary, but harmless, for lazy VACUUM.)
2323 : : */
2324 : 124896 : GetUserIdAndSecContext(&save_userid, &save_sec_context);
2325 : 124896 : SetUserIdAndSecContext(rel->rd_rel->relowner,
2326 : : save_sec_context | SECURITY_RESTRICTED_OPERATION);
2327 : 124896 : save_nestlevel = NewGUCNestLevel();
2328 : 124896 : RestrictSearchPath();
2329 : :
2330 : : /*
2331 : : * If PROCESS_MAIN is set (the default), it's time to vacuum the main
2332 : : * relation. Otherwise, we can skip this part. If processing the TOAST
2333 : : * table is required (e.g., PROCESS_TOAST is set), we force PROCESS_MAIN
2334 : : * to be set when we recurse to the TOAST table.
2335 : : */
2336 [ + + ]: 124896 : if (params.options & VACOPT_PROCESS_MAIN)
2337 : : {
2338 : : /*
2339 : : * Do the actual work --- either FULL or "lazy" vacuum
2340 : : */
2341 [ + + ]: 124816 : if (params.options & VACOPT_FULL)
2342 : : {
2343 : 237 : ClusterParams cluster_params = {0};
2344 : :
2345 [ + + ]: 237 : if ((params.options & VACOPT_VERBOSE) != 0)
2346 : 1 : cluster_params.options |= CLUOPT_VERBOSE;
2347 : :
2348 : : /* VACUUM FULL is a variant of REPACK; see repack.c */
2349 : 237 : cluster_rel(REPACK_COMMAND_VACUUMFULL, rel, InvalidOid,
2350 : : &cluster_params, isTopLevel);
2351 : : /* cluster_rel closes the relation, but keeps lock */
2352 : :
2353 : 233 : rel = NULL;
2354 : : }
2355 : : else
2356 : 124579 : table_relation_vacuum(rel, ¶ms, bstrategy);
2357 : : }
2358 : :
2359 : : /* Roll back any GUC changes executed by index functions */
2360 : 124890 : AtEOXact_GUC(false, save_nestlevel);
2361 : :
2362 : : /* Restore userid and security context */
2363 : 124890 : SetUserIdAndSecContext(save_userid, save_sec_context);
2364 : :
2365 : : /* all done with this class, but hold lock until commit */
2366 [ + + ]: 124890 : if (rel)
2367 : 124657 : relation_close(rel, NoLock);
2368 : :
2369 : : /*
2370 : : * Complete the transaction and free all temporary memory used.
2371 : : */
2372 : 124890 : PopActiveSnapshot();
2373 : 124890 : CommitTransactionCommand();
2374 : :
2375 : : /*
2376 : : * If the relation has a secondary toast rel, vacuum that too while we
2377 : : * still hold the session lock on the main table. Note however that
2378 : : * "analyze" will not get done on the toast table. This is good, because
2379 : : * the toaster always uses hardcoded index access and statistics are
2380 : : * totally unimportant for toast relations.
2381 : : */
2382 [ + + ]: 124890 : if (toast_relid != InvalidOid)
2383 : : {
2384 : : /*
2385 : : * Force VACOPT_PROCESS_MAIN so vacuum_rel() processes it. Likewise,
2386 : : * set toast_parent so that the privilege checks are done on the main
2387 : : * relation. NB: This is only safe to do because we hold a session
2388 : : * lock on the main relation that prevents concurrent deletion.
2389 : : */
2390 : 5600 : toast_vacuum_params.options |= VACOPT_PROCESS_MAIN;
2391 : 5600 : toast_vacuum_params.toast_parent = relid;
2392 : :
2393 : 5600 : vacuum_rel(toast_relid, NULL, toast_vacuum_params, bstrategy,
2394 : : isTopLevel);
2395 : : }
2396 : :
2397 : : /*
2398 : : * Now release the session-level lock on the main table.
2399 : : */
2400 : 124890 : UnlockRelationIdForSession(&lockrelid, lmode);
2401 : :
2402 : : /* Report that we really did it. */
2403 : 124890 : return true;
2404 : : }
2405 : :
2406 : :
2407 : : /*
2408 : : * Open all the vacuumable indexes of the given relation, obtaining the
2409 : : * specified kind of lock on each. Return an array of Relation pointers for
2410 : : * the indexes into *Irel, and the number of indexes into *nindexes.
2411 : : *
2412 : : * We consider an index vacuumable if it is marked insertable (indisready).
2413 : : * If it isn't, probably a CREATE INDEX CONCURRENTLY command failed early in
2414 : : * execution, and what we have is too corrupt to be processable. We will
2415 : : * vacuum even if the index isn't indisvalid; this is important because in a
2416 : : * unique index, uniqueness checks will be performed anyway and had better not
2417 : : * hit dangling index pointers.
2418 : : */
2419 : : void
2420 : 134339 : vac_open_indexes(Relation relation, LOCKMODE lockmode,
2421 : : int *nindexes, Relation **Irel)
2422 : : {
2423 : : List *indexoidlist;
2424 : : ListCell *indexoidscan;
2425 : : int i;
2426 : :
2427 : : Assert(lockmode != NoLock);
2428 : :
2429 : 134339 : indexoidlist = RelationGetIndexList(relation);
2430 : :
2431 : : /* allocate enough memory for all indexes */
2432 : 134339 : i = list_length(indexoidlist);
2433 : :
2434 [ + + ]: 134339 : if (i > 0)
2435 : 125925 : *Irel = palloc_array(Relation, i);
2436 : : else
2437 : 8414 : *Irel = NULL;
2438 : :
2439 : : /* collect just the ready indexes */
2440 : 134339 : i = 0;
2441 [ + + + + : 334664 : foreach(indexoidscan, indexoidlist)
+ + ]
2442 : : {
2443 : 200325 : Oid indexoid = lfirst_oid(indexoidscan);
2444 : : Relation indrel;
2445 : :
2446 : 200325 : indrel = index_open(indexoid, lockmode);
2447 [ + - ]: 200325 : if (indrel->rd_index->indisready)
2448 : 200325 : (*Irel)[i++] = indrel;
2449 : : else
2450 : 0 : index_close(indrel, lockmode);
2451 : : }
2452 : :
2453 : 134339 : *nindexes = i;
2454 : :
2455 : 134339 : list_free(indexoidlist);
2456 : 134339 : }
2457 : :
2458 : : /*
2459 : : * Release the resources acquired by vac_open_indexes. Optionally release
2460 : : * the locks (say NoLock to keep 'em).
2461 : : */
2462 : : void
2463 : 134945 : vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
2464 : : {
2465 [ + + ]: 134945 : if (Irel == NULL)
2466 : 9027 : return;
2467 : :
2468 [ + + ]: 326231 : while (nindexes--)
2469 : : {
2470 : 200313 : Relation ind = Irel[nindexes];
2471 : :
2472 : 200313 : index_close(ind, lockmode);
2473 : : }
2474 : 125918 : pfree(Irel);
2475 : : }
2476 : :
2477 : : /*
2478 : : * vacuum_delay_point --- check for interrupts and cost-based delay.
2479 : : *
2480 : : * This should be called in each major loop of VACUUM processing,
2481 : : * typically once per page processed.
2482 : : */
2483 : : void
2484 : 54979227 : vacuum_delay_point(bool is_analyze)
2485 : : {
2486 : 54979227 : double msec = 0;
2487 : :
2488 : : /*
2489 : : * If we're holding locks or holding interrupts for some other reason,
2490 : : * don't sleep, because we don't want to hold locks any longer than
2491 : : * necessary.
2492 : : */
2493 [ + - + - : 54979227 : if (!INTERRUPTS_CAN_BE_PROCESSED())
- + ]
2494 : 0 : return;
2495 : :
2496 : : /* Always check for interrupts */
2497 [ + + ]: 54979227 : CHECK_FOR_INTERRUPTS();
2498 : :
2499 [ - + ]: 54979226 : if (InterruptPending)
2500 : 0 : return;
2501 : :
2502 [ + + ]: 54979226 : if (IsParallelWorker())
2503 : : {
2504 : : /*
2505 : : * Update cost-based vacuum delay parameters for a parallel autovacuum
2506 : : * worker if any changes are detected. It might enable cost-based
2507 : : * delay so it needs to be called before VacuumCostActive check.
2508 : : */
2509 : 359 : parallel_vacuum_update_shared_delay_params();
2510 : : }
2511 : :
2512 [ + + + - ]: 54979226 : if (!VacuumCostActive && !ConfigReloadPending)
2513 : 47321153 : return;
2514 : :
2515 : : /*
2516 : : * Autovacuum workers should reload the configuration file if requested.
2517 : : * This allows changes to [autovacuum_]vacuum_cost_limit and
2518 : : * [autovacuum_]vacuum_cost_delay to take effect while a table is being
2519 : : * vacuumed or analyzed.
2520 : : */
2521 [ + + + - ]: 7658073 : if (ConfigReloadPending && AmAutoVacuumWorkerProcess())
2522 : : {
2523 : 1 : ConfigReloadPending = false;
2524 : 1 : ProcessConfigFile(PGC_SIGHUP);
2525 : 1 : VacuumUpdateCosts();
2526 : :
2527 : : /*
2528 : : * Propagate cost-based vacuum delay parameters to shared memory if
2529 : : * any of them have changed during the config reload.
2530 : : */
2531 : 1 : parallel_vacuum_propagate_shared_delay_params();
2532 : : }
2533 : :
2534 : : /*
2535 : : * If we disabled cost-based delays after reloading the config file,
2536 : : * return.
2537 : : */
2538 [ - + ]: 7658073 : if (!VacuumCostActive)
2539 : 0 : return;
2540 : :
2541 : : /*
2542 : : * For parallel vacuum, the delay is computed based on the shared cost
2543 : : * balance. See compute_parallel_delay.
2544 : : */
2545 [ + + ]: 7658073 : if (VacuumSharedCostBalance != NULL)
2546 : 648 : msec = compute_parallel_delay();
2547 [ + + ]: 7657425 : else if (VacuumCostBalance >= vacuum_cost_limit)
2548 : 3707 : msec = vacuum_cost_delay * VacuumCostBalance / vacuum_cost_limit;
2549 : :
2550 : : /* Nap if appropriate */
2551 [ + + ]: 7658073 : if (msec > 0)
2552 : : {
2553 : : instr_time delay_start;
2554 : :
2555 [ + + ]: 3752 : if (msec > vacuum_cost_delay * 4)
2556 : 12 : msec = vacuum_cost_delay * 4;
2557 : :
2558 [ + + ]: 3752 : if (track_cost_delay_timing)
2559 : 56 : INSTR_TIME_SET_CURRENT(delay_start);
2560 : :
2561 : 3752 : pgstat_report_wait_start(WAIT_EVENT_VACUUM_DELAY);
2562 : 3752 : pg_usleep(msec * 1000);
2563 : 3752 : pgstat_report_wait_end();
2564 : :
2565 [ + + ]: 3752 : if (track_cost_delay_timing)
2566 : : {
2567 : : instr_time delay_end;
2568 : : instr_time delay;
2569 : :
2570 : 56 : INSTR_TIME_SET_CURRENT(delay_end);
2571 : 56 : INSTR_TIME_SET_ZERO(delay);
2572 : 56 : INSTR_TIME_ACCUM_DIFF(delay, delay_end, delay_start);
2573 : :
2574 : : /*
2575 : : * For parallel workers, we only report the delay time every once
2576 : : * in a while to avoid overloading the leader with messages and
2577 : : * interrupts.
2578 : : */
2579 [ + + ]: 56 : if (IsParallelWorker())
2580 : : {
2581 : : static instr_time last_report_time;
2582 : : instr_time time_since_last_report;
2583 : :
2584 : : Assert(!is_analyze);
2585 : :
2586 : : /* Accumulate the delay time */
2587 : 25 : parallel_vacuum_worker_delay_ns += INSTR_TIME_GET_NANOSEC(delay);
2588 : :
2589 : : /* Calculate interval since last report */
2590 : 25 : INSTR_TIME_SET_ZERO(time_since_last_report);
2591 : 25 : INSTR_TIME_ACCUM_DIFF(time_since_last_report, delay_end, last_report_time);
2592 : :
2593 : : /* If we haven't reported in a while, do so now */
2594 [ + + ]: 25 : if (INSTR_TIME_GET_NANOSEC(time_since_last_report) >=
2595 : : PARALLEL_VACUUM_DELAY_REPORT_INTERVAL_NS)
2596 : : {
2597 : 2 : pgstat_progress_parallel_incr_param(PROGRESS_VACUUM_DELAY_TIME,
2598 : : parallel_vacuum_worker_delay_ns);
2599 : :
2600 : : /* Reset variables */
2601 : 2 : last_report_time = delay_end;
2602 : 2 : parallel_vacuum_worker_delay_ns = 0;
2603 : : }
2604 : : }
2605 [ - + ]: 31 : else if (is_analyze)
2606 : 0 : pgstat_progress_incr_param(PROGRESS_ANALYZE_DELAY_TIME,
2607 : : INSTR_TIME_GET_NANOSEC(delay));
2608 : : else
2609 : 31 : pgstat_progress_incr_param(PROGRESS_VACUUM_DELAY_TIME,
2610 : : INSTR_TIME_GET_NANOSEC(delay));
2611 : : }
2612 : :
2613 : : /*
2614 : : * We don't want to ignore postmaster death during very long vacuums
2615 : : * with vacuum_cost_delay configured. We can't use the usual
2616 : : * WaitLatch() approach here because we want microsecond-based sleep
2617 : : * durations above.
2618 : : */
2619 [ + - - + ]: 3752 : if (IsUnderPostmaster && !PostmasterIsAlive())
2620 : 0 : exit(1);
2621 : :
2622 : 3752 : VacuumCostBalance = 0;
2623 : :
2624 : : /*
2625 : : * Balance and update limit values for autovacuum workers. We must do
2626 : : * this periodically, as the number of workers across which we are
2627 : : * balancing the limit may have changed.
2628 : : *
2629 : : * TODO: There may be better criteria for determining when to do this
2630 : : * besides "check after napping".
2631 : : */
2632 : 3752 : AutoVacuumUpdateCostLimit();
2633 : :
2634 [ + + ]: 3752 : if (AmAutoVacuumWorkerProcess())
2635 : 3720 : parallel_vacuum_propagate_shared_delay_params();
2636 : :
2637 : : /* Might have gotten an interrupt while sleeping */
2638 [ + + ]: 3752 : CHECK_FOR_INTERRUPTS();
2639 : : }
2640 : : }
2641 : :
2642 : : /*
2643 : : * Computes the vacuum delay for parallel workers.
2644 : : *
2645 : : * The basic idea of a cost-based delay for parallel vacuum is to allow each
2646 : : * worker to sleep in proportion to the share of work it's done. We achieve this
2647 : : * by allowing all parallel vacuum workers including the leader process to
2648 : : * have a shared view of cost related parameters (mainly VacuumCostBalance).
2649 : : * We allow each worker to update it as and when it has incurred any cost and
2650 : : * then based on that decide whether it needs to sleep. We compute the time
2651 : : * to sleep for a worker based on the cost it has incurred
2652 : : * (VacuumCostBalanceLocal) and then reduce the VacuumSharedCostBalance by
2653 : : * that amount. This avoids putting to sleep those workers which have done less
2654 : : * I/O than other workers and therefore ensure that workers
2655 : : * which are doing more I/O got throttled more.
2656 : : *
2657 : : * We allow a worker to sleep only if it has performed I/O above a certain
2658 : : * threshold, which is calculated based on the number of active workers
2659 : : * (VacuumActiveNWorkers), and the overall cost balance is more than
2660 : : * VacuumCostLimit set by the system. Testing reveals that we achieve
2661 : : * the required throttling if we force a worker that has done more than 50%
2662 : : * of its share of work to sleep.
2663 : : */
2664 : : static double
2665 : 648 : compute_parallel_delay(void)
2666 : : {
2667 : 648 : double msec = 0;
2668 : : uint32 shared_balance;
2669 : : int nworkers;
2670 : :
2671 : : /* Parallel vacuum must be active */
2672 : : Assert(VacuumSharedCostBalance);
2673 : :
2674 : 648 : nworkers = pg_atomic_read_u32(VacuumActiveNWorkers);
2675 : :
2676 : : /* At least count itself */
2677 : : Assert(nworkers >= 1);
2678 : :
2679 : : /* Update the shared cost balance value atomically */
2680 : 648 : shared_balance = pg_atomic_add_fetch_u32(VacuumSharedCostBalance, VacuumCostBalance);
2681 : :
2682 : : /* Compute the total local balance for the current worker */
2683 : 648 : VacuumCostBalanceLocal += VacuumCostBalance;
2684 : :
2685 [ + + ]: 648 : if ((shared_balance >= vacuum_cost_limit) &&
2686 [ + + ]: 116 : (VacuumCostBalanceLocal > 0.5 * ((double) vacuum_cost_limit / nworkers)))
2687 : : {
2688 : : /* Compute sleep time based on the local cost balance */
2689 : 45 : msec = vacuum_cost_delay * VacuumCostBalanceLocal / vacuum_cost_limit;
2690 : 45 : pg_atomic_sub_fetch_u32(VacuumSharedCostBalance, VacuumCostBalanceLocal);
2691 : 45 : VacuumCostBalanceLocal = 0;
2692 : : }
2693 : :
2694 : : /*
2695 : : * Reset the local balance as we accumulated it into the shared value.
2696 : : */
2697 : 648 : VacuumCostBalance = 0;
2698 : :
2699 : 648 : return msec;
2700 : : }
2701 : :
2702 : : /*
2703 : : * A wrapper function of defGetBoolean().
2704 : : *
2705 : : * This function returns VACOPTVALUE_ENABLED and VACOPTVALUE_DISABLED instead
2706 : : * of true and false.
2707 : : */
2708 : : static VacOptValue
2709 : 174 : get_vacoptval_from_boolean(DefElem *def)
2710 : : {
2711 [ + + ]: 174 : return defGetBoolean(def) ? VACOPTVALUE_ENABLED : VACOPTVALUE_DISABLED;
2712 : : }
2713 : :
2714 : : /*
2715 : : * vac_bulkdel_one_index() -- bulk-deletion for index relation.
2716 : : *
2717 : : * Returns bulk delete stats derived from input stats
2718 : : */
2719 : : IndexBulkDeleteResult *
2720 : 1616 : vac_bulkdel_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat,
2721 : : TidStore *dead_items, VacDeadItemsInfo *dead_items_info)
2722 : : {
2723 : : /* Do bulk deletion */
2724 : 1616 : istat = index_bulk_delete(ivinfo, istat, vac_tid_reaped,
2725 : : dead_items);
2726 : :
2727 [ + + ]: 1615 : ereport(ivinfo->message_level,
2728 : : (errmsg("scanned index \"%s\" to remove %" PRId64 " row versions",
2729 : : RelationGetRelationName(ivinfo->index),
2730 : : dead_items_info->num_items)));
2731 : :
2732 : 1615 : return istat;
2733 : : }
2734 : :
2735 : : /*
2736 : : * vac_cleanup_one_index() -- do post-vacuum cleanup for index relation.
2737 : : *
2738 : : * Returns bulk delete stats derived from input stats
2739 : : */
2740 : : IndexBulkDeleteResult *
2741 : 147887 : vac_cleanup_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat)
2742 : : {
2743 : 147887 : istat = index_vacuum_cleanup(ivinfo, istat);
2744 : :
2745 [ + + ]: 147887 : if (istat)
2746 [ + + ]: 1794 : ereport(ivinfo->message_level,
2747 : : (errmsg("index \"%s\" now contains %.0f row versions in %u pages",
2748 : : RelationGetRelationName(ivinfo->index),
2749 : : istat->num_index_tuples,
2750 : : istat->num_pages),
2751 : : errdetail("%.0f index row versions were removed.\n"
2752 : : "%u index pages were newly deleted.\n"
2753 : : "%u index pages are currently deleted, of which %u are currently reusable.",
2754 : : istat->tuples_removed,
2755 : : istat->pages_newly_deleted,
2756 : : istat->pages_deleted, istat->pages_free)));
2757 : :
2758 : 147887 : return istat;
2759 : : }
2760 : :
2761 : : /*
2762 : : * vac_tid_reaped() -- is a particular tid deletable?
2763 : : *
2764 : : * This has the right signature to be an IndexBulkDeleteCallback.
2765 : : */
2766 : : static bool
2767 : 5079619 : vac_tid_reaped(ItemPointer itemptr, void *state)
2768 : : {
2769 : 5079619 : TidStore *dead_items = (TidStore *) state;
2770 : :
2771 : 5079619 : return TidStoreIsMember(dead_items, itemptr);
2772 : : }
|