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