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