/src/postgres/src/backend/commands/vacuum.c
Line | Count | Source |
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 | 0 | #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 | | check_vacuum_buffer_usage_limit(int *newval, void **extra, |
142 | | GucSource source) |
143 | 2 | { |
144 | | /* Value upper and lower hard limits are inclusive */ |
145 | 2 | if (*newval == 0 || (*newval >= MIN_BAS_VAC_RING_SIZE_KB && |
146 | 2 | *newval <= MAX_BAS_VAC_RING_SIZE_KB)) |
147 | 2 | 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 | 0 | "vacuum_buffer_usage_limit", |
152 | 0 | MIN_BAS_VAC_RING_SIZE_KB, MAX_BAS_VAC_RING_SIZE_KB); |
153 | |
|
154 | 0 | return false; |
155 | 2 | } |
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 | | ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel) |
165 | 0 | { |
166 | 0 | VacuumParams params; |
167 | 0 | BufferAccessStrategy bstrategy = NULL; |
168 | 0 | bool verbose = false; |
169 | 0 | bool skip_locked = false; |
170 | 0 | bool analyze = false; |
171 | 0 | bool freeze = false; |
172 | 0 | bool full = false; |
173 | 0 | bool disable_page_skipping = false; |
174 | 0 | bool process_main = true; |
175 | 0 | bool process_toast = true; |
176 | 0 | int ring_size; |
177 | 0 | bool skip_database_stats = false; |
178 | 0 | bool only_database_stats = false; |
179 | 0 | MemoryContext vac_context; |
180 | 0 | ListCell *lc; |
181 | | |
182 | | /* index_cleanup and truncate values unspecified for now */ |
183 | 0 | params.index_cleanup = VACOPTVALUE_UNSPECIFIED; |
184 | 0 | params.truncate = VACOPTVALUE_UNSPECIFIED; |
185 | | |
186 | | /* By default parallel vacuum is enabled */ |
187 | 0 | params.nworkers = 0; |
188 | | |
189 | | /* Will be set later if we recurse to a TOAST table. */ |
190 | 0 | params.toast_parent = InvalidOid; |
191 | 0 | 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 | 0 | ring_size = -1; |
198 | | |
199 | | /* Parse options list */ |
200 | 0 | foreach(lc, vacstmt->options) |
201 | 0 | { |
202 | 0 | DefElem *opt = (DefElem *) lfirst(lc); |
203 | | |
204 | | /* Parse common options for VACUUM and ANALYZE */ |
205 | 0 | if (strcmp(opt->defname, "verbose") == 0) |
206 | 0 | verbose = defGetBoolean(opt); |
207 | 0 | else if (strcmp(opt->defname, "skip_locked") == 0) |
208 | 0 | skip_locked = defGetBoolean(opt); |
209 | 0 | else if (strcmp(opt->defname, "buffer_usage_limit") == 0) |
210 | 0 | { |
211 | 0 | const char *hintmsg; |
212 | 0 | int result; |
213 | 0 | char *vac_buffer_size; |
214 | |
|
215 | 0 | 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 | 0 | if (!parse_int(vac_buffer_size, &result, GUC_UNIT_KB, &hintmsg) || |
222 | 0 | (result != 0 && |
223 | 0 | (result < MIN_BAS_VAC_RING_SIZE_KB || result > MAX_BAS_VAC_RING_SIZE_KB))) |
224 | 0 | { |
225 | 0 | ereport(ERROR, |
226 | 0 | (errcode(ERRCODE_INVALID_PARAMETER_VALUE), |
227 | 0 | errmsg("%s option must be 0 or between %d kB and %d kB", |
228 | 0 | "BUFFER_USAGE_LIMIT", |
229 | 0 | MIN_BAS_VAC_RING_SIZE_KB, MAX_BAS_VAC_RING_SIZE_KB), |
230 | 0 | hintmsg ? errhint_internal("%s", _(hintmsg)) : 0)); |
231 | 0 | } |
232 | | |
233 | 0 | ring_size = result; |
234 | 0 | } |
235 | 0 | else if (!vacstmt->is_vacuumcmd) |
236 | 0 | ereport(ERROR, |
237 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
238 | 0 | errmsg("unrecognized %s option \"%s\"", |
239 | 0 | "ANALYZE", opt->defname), |
240 | 0 | parser_errposition(pstate, opt->location))); |
241 | | |
242 | | /* Parse options available on VACUUM */ |
243 | 0 | else if (strcmp(opt->defname, "analyze") == 0) |
244 | 0 | analyze = defGetBoolean(opt); |
245 | 0 | else if (strcmp(opt->defname, "freeze") == 0) |
246 | 0 | freeze = defGetBoolean(opt); |
247 | 0 | else if (strcmp(opt->defname, "full") == 0) |
248 | 0 | full = defGetBoolean(opt); |
249 | 0 | else if (strcmp(opt->defname, "disable_page_skipping") == 0) |
250 | 0 | disable_page_skipping = defGetBoolean(opt); |
251 | 0 | else if (strcmp(opt->defname, "index_cleanup") == 0) |
252 | 0 | { |
253 | | /* Interpret no string as the default, which is 'auto' */ |
254 | 0 | if (!opt->arg) |
255 | 0 | params.index_cleanup = VACOPTVALUE_AUTO; |
256 | 0 | else |
257 | 0 | { |
258 | 0 | char *sval = defGetString(opt); |
259 | | |
260 | | /* Try matching on 'auto' string, or fall back on boolean */ |
261 | 0 | if (pg_strcasecmp(sval, "auto") == 0) |
262 | 0 | params.index_cleanup = VACOPTVALUE_AUTO; |
263 | 0 | else |
264 | 0 | params.index_cleanup = get_vacoptval_from_boolean(opt); |
265 | 0 | } |
266 | 0 | } |
267 | 0 | else if (strcmp(opt->defname, "process_main") == 0) |
268 | 0 | process_main = defGetBoolean(opt); |
269 | 0 | else if (strcmp(opt->defname, "process_toast") == 0) |
270 | 0 | process_toast = defGetBoolean(opt); |
271 | 0 | else if (strcmp(opt->defname, "truncate") == 0) |
272 | 0 | params.truncate = get_vacoptval_from_boolean(opt); |
273 | 0 | else if (strcmp(opt->defname, "parallel") == 0) |
274 | 0 | { |
275 | 0 | int nworkers = defGetInt32(opt); |
276 | |
|
277 | 0 | if (nworkers < 0 || nworkers > MAX_PARALLEL_WORKER_LIMIT) |
278 | 0 | ereport(ERROR, |
279 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
280 | 0 | errmsg("%s option must be between 0 and %d", |
281 | 0 | "PARALLEL", |
282 | 0 | MAX_PARALLEL_WORKER_LIMIT), |
283 | 0 | parser_errposition(pstate, opt->location))); |
284 | | |
285 | | /* |
286 | | * Disable parallel vacuum, if user has specified parallel degree |
287 | | * as zero. |
288 | | */ |
289 | 0 | if (nworkers == 0) |
290 | 0 | params.nworkers = -1; |
291 | 0 | else |
292 | 0 | params.nworkers = nworkers; |
293 | 0 | } |
294 | 0 | else if (strcmp(opt->defname, "skip_database_stats") == 0) |
295 | 0 | skip_database_stats = defGetBoolean(opt); |
296 | 0 | else if (strcmp(opt->defname, "only_database_stats") == 0) |
297 | 0 | only_database_stats = defGetBoolean(opt); |
298 | 0 | else |
299 | 0 | ereport(ERROR, |
300 | 0 | (errcode(ERRCODE_SYNTAX_ERROR), |
301 | 0 | errmsg("unrecognized %s option \"%s\"", |
302 | 0 | "VACUUM", opt->defname), |
303 | 0 | parser_errposition(pstate, opt->location))); |
304 | 0 | } |
305 | | |
306 | | /* Set vacuum options */ |
307 | 0 | params.options = |
308 | 0 | (vacstmt->is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE) | |
309 | 0 | (verbose ? VACOPT_VERBOSE : 0) | |
310 | 0 | (skip_locked ? VACOPT_SKIP_LOCKED : 0) | |
311 | 0 | (analyze ? VACOPT_ANALYZE : 0) | |
312 | 0 | (freeze ? VACOPT_FREEZE : 0) | |
313 | 0 | (full ? VACOPT_FULL : 0) | |
314 | 0 | (disable_page_skipping ? VACOPT_DISABLE_PAGE_SKIPPING : 0) | |
315 | 0 | (process_main ? VACOPT_PROCESS_MAIN : 0) | |
316 | 0 | (process_toast ? VACOPT_PROCESS_TOAST : 0) | |
317 | 0 | (skip_database_stats ? VACOPT_SKIP_DATABASE_STATS : 0) | |
318 | 0 | (only_database_stats ? VACOPT_ONLY_DATABASE_STATS : 0); |
319 | | |
320 | | /* sanity checks on options */ |
321 | 0 | Assert(params.options & (VACOPT_VACUUM | VACOPT_ANALYZE)); |
322 | 0 | Assert((params.options & VACOPT_VACUUM) || |
323 | 0 | !(params.options & (VACOPT_FULL | VACOPT_FREEZE))); |
324 | |
|
325 | 0 | if ((params.options & VACOPT_FULL) && params.nworkers > 0) |
326 | 0 | ereport(ERROR, |
327 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
328 | 0 | 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 | 0 | if (ring_size != -1 && (params.options & VACOPT_FULL) && |
336 | 0 | !(params.options & VACOPT_ANALYZE)) |
337 | 0 | ereport(ERROR, |
338 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
339 | 0 | 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 | 0 | if (!(params.options & VACOPT_ANALYZE)) |
345 | 0 | { |
346 | 0 | foreach(lc, vacstmt->rels) |
347 | 0 | { |
348 | 0 | VacuumRelation *vrel = lfirst_node(VacuumRelation, lc); |
349 | |
|
350 | 0 | if (vrel->va_cols != NIL) |
351 | 0 | ereport(ERROR, |
352 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
353 | 0 | errmsg("ANALYZE option must be specified when a column list is provided"))); |
354 | 0 | } |
355 | 0 | } |
356 | | |
357 | | /* |
358 | | * Sanity check DISABLE_PAGE_SKIPPING option. |
359 | | */ |
360 | 0 | if ((params.options & VACOPT_FULL) != 0 && |
361 | 0 | (params.options & VACOPT_DISABLE_PAGE_SKIPPING) != 0) |
362 | 0 | ereport(ERROR, |
363 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
364 | 0 | errmsg("VACUUM option DISABLE_PAGE_SKIPPING cannot be used with FULL"))); |
365 | | |
366 | | /* sanity check for PROCESS_TOAST */ |
367 | 0 | if ((params.options & VACOPT_FULL) != 0 && |
368 | 0 | (params.options & VACOPT_PROCESS_TOAST) == 0) |
369 | 0 | ereport(ERROR, |
370 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
371 | 0 | errmsg("PROCESS_TOAST required with VACUUM FULL"))); |
372 | | |
373 | | /* sanity check for ONLY_DATABASE_STATS */ |
374 | 0 | if (params.options & VACOPT_ONLY_DATABASE_STATS) |
375 | 0 | { |
376 | 0 | Assert(params.options & VACOPT_VACUUM); |
377 | 0 | if (vacstmt->rels != NIL) |
378 | 0 | ereport(ERROR, |
379 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
380 | 0 | 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 | 0 | if (params.options & ~(VACOPT_VACUUM | |
383 | 0 | VACOPT_VERBOSE | |
384 | 0 | VACOPT_PROCESS_MAIN | |
385 | 0 | VACOPT_PROCESS_TOAST | |
386 | 0 | VACOPT_ONLY_DATABASE_STATS)) |
387 | 0 | ereport(ERROR, |
388 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
389 | 0 | errmsg("ONLY_DATABASE_STATS cannot be specified with other VACUUM options"))); |
390 | 0 | } |
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 | 0 | if (params.options & VACOPT_FREEZE) |
397 | 0 | { |
398 | 0 | params.freeze_min_age = 0; |
399 | 0 | params.freeze_table_age = 0; |
400 | 0 | params.multixact_freeze_min_age = 0; |
401 | 0 | params.multixact_freeze_table_age = 0; |
402 | 0 | } |
403 | 0 | else |
404 | 0 | { |
405 | 0 | params.freeze_min_age = -1; |
406 | 0 | params.freeze_table_age = -1; |
407 | 0 | params.multixact_freeze_min_age = -1; |
408 | 0 | params.multixact_freeze_table_age = -1; |
409 | 0 | } |
410 | | |
411 | | /* user-invoked vacuum is never "for wraparound" */ |
412 | 0 | 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 | 0 | params.log_vacuum_min_duration = -1; |
419 | 0 | params.log_analyze_min_duration = -1; |
420 | | |
421 | | /* |
422 | | * Later, in vacuum_rel(), we check if a reloption override was specified. |
423 | | */ |
424 | 0 | 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 | 0 | vac_context = AllocSetContextCreate(PortalContext, |
433 | 0 | "Vacuum", |
434 | 0 | 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 | 0 | if ((params.options & (VACOPT_ONLY_DATABASE_STATS | |
444 | 0 | VACOPT_FULL)) == 0 || |
445 | 0 | (params.options & VACOPT_ANALYZE) != 0) |
446 | 0 | { |
447 | |
|
448 | 0 | MemoryContext old_context = MemoryContextSwitchTo(vac_context); |
449 | |
|
450 | 0 | 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 | 0 | if (ring_size == -1) |
459 | 0 | ring_size = VacuumBufferUsageLimit; |
460 | |
|
461 | 0 | bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, ring_size); |
462 | |
|
463 | 0 | MemoryContextSwitchTo(old_context); |
464 | 0 | } |
465 | | |
466 | | /* Now go through the common routine */ |
467 | 0 | vacuum(vacstmt->rels, ¶ms, bstrategy, vac_context, isTopLevel); |
468 | | |
469 | | /* Finally, clean up the vacuum memory context */ |
470 | 0 | MemoryContextDelete(vac_context); |
471 | 0 | } |
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 | | vacuum(List *relations, const VacuumParams *params, BufferAccessStrategy bstrategy, |
497 | | MemoryContext vac_context, bool isTopLevel) |
498 | 0 | { |
499 | 0 | static bool in_vacuum = false; |
500 | |
|
501 | 0 | const char *stmttype; |
502 | 0 | volatile bool in_outer_xact, |
503 | 0 | use_own_xacts; |
504 | |
|
505 | 0 | 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 | 0 | if (params->options & VACOPT_VACUUM) |
516 | 0 | { |
517 | 0 | PreventInTransactionBlock(isTopLevel, stmttype); |
518 | 0 | in_outer_xact = false; |
519 | 0 | } |
520 | 0 | else |
521 | 0 | 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 | 0 | if (in_vacuum) |
529 | 0 | ereport(ERROR, |
530 | 0 | (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), |
531 | 0 | errmsg("%s cannot be executed from VACUUM or ANALYZE", |
532 | 0 | stmttype))); |
533 | | |
534 | | /* |
535 | | * Build list of relation(s) to process, putting any new data in |
536 | | * vac_context for safekeeping. |
537 | | */ |
538 | 0 | if (params->options & VACOPT_ONLY_DATABASE_STATS) |
539 | 0 | { |
540 | | /* We don't process any tables in this case */ |
541 | 0 | Assert(relations == NIL); |
542 | 0 | } |
543 | 0 | else if (relations != NIL) |
544 | 0 | { |
545 | 0 | List *newrels = NIL; |
546 | 0 | ListCell *lc; |
547 | |
|
548 | 0 | foreach(lc, relations) |
549 | 0 | { |
550 | 0 | VacuumRelation *vrel = lfirst_node(VacuumRelation, lc); |
551 | 0 | List *sublist; |
552 | 0 | MemoryContext old_context; |
553 | |
|
554 | 0 | sublist = expand_vacuum_rel(vrel, vac_context, params->options); |
555 | 0 | old_context = MemoryContextSwitchTo(vac_context); |
556 | 0 | newrels = list_concat(newrels, sublist); |
557 | 0 | MemoryContextSwitchTo(old_context); |
558 | 0 | } |
559 | 0 | relations = newrels; |
560 | 0 | } |
561 | 0 | else |
562 | 0 | 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 | 0 | if (params->options & VACOPT_VACUUM) |
579 | 0 | use_own_xacts = true; |
580 | 0 | else |
581 | 0 | { |
582 | 0 | Assert(params->options & VACOPT_ANALYZE); |
583 | 0 | if (AmAutoVacuumWorkerProcess()) |
584 | 0 | use_own_xacts = true; |
585 | 0 | else if (in_outer_xact) |
586 | 0 | use_own_xacts = false; |
587 | 0 | else if (list_length(relations) > 1) |
588 | 0 | use_own_xacts = true; |
589 | 0 | else |
590 | 0 | use_own_xacts = false; |
591 | 0 | } |
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 | 0 | if (use_own_xacts) |
602 | 0 | { |
603 | 0 | Assert(!in_outer_xact); |
604 | | |
605 | | /* ActiveSnapshot is not set by autovacuum */ |
606 | 0 | if (ActiveSnapshotSet()) |
607 | 0 | PopActiveSnapshot(); |
608 | | |
609 | | /* matches the StartTransaction in PostgresMain() */ |
610 | 0 | CommitTransactionCommand(); |
611 | 0 | } |
612 | | |
613 | | /* Turn vacuum cost accounting on or off, and set/clear in_vacuum */ |
614 | 0 | PG_TRY(); |
615 | 0 | { |
616 | 0 | ListCell *cur; |
617 | |
|
618 | 0 | in_vacuum = true; |
619 | 0 | VacuumFailsafeActive = false; |
620 | 0 | VacuumUpdateCosts(); |
621 | 0 | VacuumCostBalance = 0; |
622 | 0 | VacuumCostBalanceLocal = 0; |
623 | 0 | VacuumSharedCostBalance = NULL; |
624 | 0 | VacuumActiveNWorkers = NULL; |
625 | | |
626 | | /* |
627 | | * Loop to process each selected relation. |
628 | | */ |
629 | 0 | foreach(cur, relations) |
630 | 0 | { |
631 | 0 | VacuumRelation *vrel = lfirst_node(VacuumRelation, cur); |
632 | |
|
633 | 0 | if (params->options & VACOPT_VACUUM) |
634 | 0 | { |
635 | 0 | if (!vacuum_rel(vrel->oid, vrel->relation, *params, bstrategy, |
636 | 0 | isTopLevel)) |
637 | 0 | continue; |
638 | 0 | } |
639 | | |
640 | 0 | if (params->options & VACOPT_ANALYZE) |
641 | 0 | { |
642 | | /* |
643 | | * If using separate xacts, start one for analyze. Otherwise, |
644 | | * we can use the outer transaction. |
645 | | */ |
646 | 0 | if (use_own_xacts) |
647 | 0 | { |
648 | 0 | StartTransactionCommand(); |
649 | | /* functions in indexes may want a snapshot set */ |
650 | 0 | PushActiveSnapshot(GetTransactionSnapshot()); |
651 | 0 | } |
652 | |
|
653 | 0 | analyze_rel(vrel->oid, vrel->relation, params, |
654 | 0 | vrel->va_cols, in_outer_xact, bstrategy); |
655 | |
|
656 | 0 | if (use_own_xacts) |
657 | 0 | { |
658 | 0 | PopActiveSnapshot(); |
659 | | /* standard_ProcessUtility() does CCI if !use_own_xacts */ |
660 | 0 | CommandCounterIncrement(); |
661 | 0 | CommitTransactionCommand(); |
662 | 0 | } |
663 | 0 | else |
664 | 0 | { |
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 | 0 | CommandCounterIncrement(); |
671 | 0 | } |
672 | 0 | } |
673 | | |
674 | | /* |
675 | | * Ensure VacuumFailsafeActive has been reset before vacuuming the |
676 | | * next relation. |
677 | | */ |
678 | 0 | VacuumFailsafeActive = false; |
679 | 0 | } |
680 | 0 | } |
681 | 0 | PG_FINALLY(); |
682 | 0 | { |
683 | 0 | in_vacuum = false; |
684 | 0 | VacuumCostActive = false; |
685 | 0 | VacuumFailsafeActive = false; |
686 | 0 | VacuumCostBalance = 0; |
687 | 0 | VacuumCostBalanceLocal = 0; |
688 | 0 | VacuumSharedCostBalance = NULL; |
689 | 0 | VacuumActiveNWorkers = NULL; |
690 | 0 | } |
691 | 0 | PG_END_TRY(); |
692 | | |
693 | | /* |
694 | | * Finish up processing. |
695 | | */ |
696 | 0 | if (use_own_xacts) |
697 | 0 | { |
698 | | /* here, we are not in a transaction */ |
699 | | |
700 | | /* |
701 | | * This matches the CommitTransaction waiting for us in |
702 | | * PostgresMain(). |
703 | | */ |
704 | 0 | StartTransactionCommand(); |
705 | 0 | } |
706 | |
|
707 | 0 | if ((params->options & VACOPT_VACUUM) && |
708 | 0 | !(params->options & VACOPT_SKIP_DATABASE_STATS)) |
709 | 0 | { |
710 | | /* |
711 | | * Update pg_database.datfrozenxid, and truncate pg_xact if possible. |
712 | | */ |
713 | 0 | vac_update_datfrozenxid(); |
714 | 0 | } |
715 | |
|
716 | 0 | } |
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 | | vacuum_is_permitted_for_relation(Oid relid, Form_pg_class reltuple, |
730 | | uint32 options, bool missing_ok) |
731 | | { |
732 | | char *relname; |
733 | | 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 | | if ((object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()) && |
747 | | !reltuple->relisshared) || |
748 | | pg_class_aclcheck_ext(relid, GetUserId(), ACL_MAINTAIN, |
749 | | missing_ok ? &is_missing : NULL) == ACLCHECK_OK) |
750 | | 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 | | if (is_missing) |
757 | | { |
758 | | Assert(missing_ok); |
759 | | return false; |
760 | | } |
761 | | |
762 | | relname = NameStr(reltuple->relname); |
763 | | |
764 | | if ((options & VACOPT_VACUUM) != 0) |
765 | | { |
766 | | 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 | | return false; |
776 | | } |
777 | | |
778 | | if ((options & VACOPT_ANALYZE) != 0) |
779 | | ereport(WARNING, |
780 | | (errmsg("permission denied to analyze \"%s\", skipping it", |
781 | | relname))); |
782 | | |
783 | | 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 | | vacuum_open_relation(Oid relid, RangeVar *relation, uint32 options, |
796 | | bool verbose, LOCKMODE lmode) |
797 | 0 | { |
798 | 0 | Relation rel; |
799 | 0 | bool rel_lock = true; |
800 | 0 | int elevel; |
801 | |
|
802 | 0 | 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 | 0 | if (!(options & VACOPT_SKIP_LOCKED)) |
814 | 0 | rel = try_relation_open(relid, lmode); |
815 | 0 | else if (ConditionalLockRelationOid(relid, lmode)) |
816 | 0 | rel = try_relation_open(relid, NoLock); |
817 | 0 | else |
818 | 0 | { |
819 | 0 | rel = NULL; |
820 | 0 | rel_lock = false; |
821 | 0 | } |
822 | | |
823 | | /* if relation is opened, leave */ |
824 | 0 | if (rel) |
825 | 0 | 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 | 0 | if (relation == NULL) |
837 | 0 | 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 | 0 | if (!AmAutoVacuumWorkerProcess()) |
847 | 0 | elevel = WARNING; |
848 | 0 | else if (verbose) |
849 | 0 | elevel = LOG; |
850 | 0 | else |
851 | 0 | return NULL; |
852 | | |
853 | 0 | if ((options & VACOPT_VACUUM) != 0) |
854 | 0 | { |
855 | 0 | if (!rel_lock) |
856 | 0 | ereport(elevel, |
857 | 0 | (errcode(ERRCODE_LOCK_NOT_AVAILABLE), |
858 | 0 | errmsg("skipping vacuum of \"%s\" --- lock not available", |
859 | 0 | relation->relname))); |
860 | 0 | else |
861 | 0 | ereport(elevel, |
862 | 0 | (errcode(ERRCODE_UNDEFINED_TABLE), |
863 | 0 | errmsg("skipping vacuum of \"%s\" --- relation no longer exists", |
864 | 0 | 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 | 0 | return NULL; |
872 | 0 | } |
873 | | |
874 | 0 | if ((options & VACOPT_ANALYZE) != 0) |
875 | 0 | { |
876 | 0 | if (!rel_lock) |
877 | 0 | ereport(elevel, |
878 | 0 | (errcode(ERRCODE_LOCK_NOT_AVAILABLE), |
879 | 0 | errmsg("skipping analyze of \"%s\" --- lock not available", |
880 | 0 | relation->relname))); |
881 | 0 | else |
882 | 0 | ereport(elevel, |
883 | 0 | (errcode(ERRCODE_UNDEFINED_TABLE), |
884 | 0 | errmsg("skipping analyze of \"%s\" --- relation no longer exists", |
885 | 0 | relation->relname))); |
886 | 0 | } |
887 | | |
888 | 0 | return NULL; |
889 | 0 | } |
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 | | expand_vacuum_rel(VacuumRelation *vrel, MemoryContext vac_context, |
908 | | int options) |
909 | 0 | { |
910 | 0 | List *vacrels = NIL; |
911 | 0 | MemoryContext oldcontext; |
912 | | |
913 | | /* If caller supplied OID, there's nothing we need do here. */ |
914 | 0 | if (OidIsValid(vrel->oid)) |
915 | 0 | { |
916 | 0 | oldcontext = MemoryContextSwitchTo(vac_context); |
917 | 0 | vacrels = lappend(vacrels, vrel); |
918 | 0 | MemoryContextSwitchTo(oldcontext); |
919 | 0 | } |
920 | 0 | else |
921 | 0 | { |
922 | | /* |
923 | | * Process a specific relation, and possibly partitions or child |
924 | | * tables thereof. |
925 | | */ |
926 | 0 | Oid relid; |
927 | 0 | HeapTuple tuple; |
928 | 0 | Form_pg_class classForm; |
929 | 0 | bool include_children; |
930 | 0 | bool is_partitioned_table; |
931 | 0 | int rvr_opts; |
932 | | |
933 | | /* |
934 | | * Since autovacuum workers supply OIDs when calling vacuum(), no |
935 | | * autovacuum worker should reach this code. |
936 | | */ |
937 | 0 | 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 | 0 | rvr_opts = (options & VACOPT_SKIP_LOCKED) ? RVR_SKIP_LOCKED : 0; |
945 | 0 | relid = RangeVarGetRelidExtended(vrel->relation, |
946 | 0 | AccessShareLock, |
947 | 0 | rvr_opts, |
948 | 0 | 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 | 0 | if (!OidIsValid(relid)) |
955 | 0 | { |
956 | 0 | if (options & VACOPT_VACUUM) |
957 | 0 | ereport(WARNING, |
958 | 0 | (errcode(ERRCODE_LOCK_NOT_AVAILABLE), |
959 | 0 | errmsg("skipping vacuum of \"%s\" --- lock not available", |
960 | 0 | vrel->relation->relname))); |
961 | 0 | else |
962 | 0 | ereport(WARNING, |
963 | 0 | (errcode(ERRCODE_LOCK_NOT_AVAILABLE), |
964 | 0 | errmsg("skipping analyze of \"%s\" --- lock not available", |
965 | 0 | vrel->relation->relname))); |
966 | 0 | return vacrels; |
967 | 0 | } |
968 | | |
969 | | /* |
970 | | * To check whether the relation is a partitioned table and its |
971 | | * ownership, fetch its syscache entry. |
972 | | */ |
973 | 0 | tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid)); |
974 | 0 | if (!HeapTupleIsValid(tuple)) |
975 | 0 | elog(ERROR, "cache lookup failed for relation %u", relid); |
976 | 0 | 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 | 0 | if (vacuum_is_permitted_for_relation(relid, classForm, options, false)) |
983 | 0 | { |
984 | 0 | oldcontext = MemoryContextSwitchTo(vac_context); |
985 | 0 | vacrels = lappend(vacrels, makeVacuumRelation(vrel->relation, |
986 | 0 | relid, |
987 | 0 | vrel->va_cols)); |
988 | 0 | MemoryContextSwitchTo(oldcontext); |
989 | 0 | } |
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 | 0 | include_children = vrel->relation->inh; |
997 | 0 | is_partitioned_table = (classForm->relkind == RELKIND_PARTITIONED_TABLE); |
998 | 0 | if ((options & VACOPT_VACUUM) && is_partitioned_table && !include_children) |
999 | 0 | ereport(WARNING, |
1000 | 0 | (errmsg("VACUUM ONLY of partitioned table \"%s\" has no effect", |
1001 | 0 | vrel->relation->relname))); |
1002 | | |
1003 | 0 | 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 | 0 | if (include_children) |
1016 | 0 | { |
1017 | 0 | List *part_oids = find_all_inheritors(relid, NoLock, NULL); |
1018 | 0 | ListCell *part_lc; |
1019 | |
|
1020 | 0 | foreach(part_lc, part_oids) |
1021 | 0 | { |
1022 | 0 | Oid part_oid = lfirst_oid(part_lc); |
1023 | |
|
1024 | 0 | if (part_oid == relid) |
1025 | 0 | 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 | 0 | oldcontext = MemoryContextSwitchTo(vac_context); |
1033 | 0 | vacrels = lappend(vacrels, makeVacuumRelation(NULL, |
1034 | 0 | part_oid, |
1035 | 0 | vrel->va_cols)); |
1036 | 0 | MemoryContextSwitchTo(oldcontext); |
1037 | 0 | } |
1038 | 0 | } |
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 | 0 | UnlockRelationOid(relid, AccessShareLock); |
1052 | 0 | } |
1053 | | |
1054 | 0 | return vacrels; |
1055 | 0 | } |
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 | | get_all_vacuum_rels(MemoryContext vac_context, int options) |
1063 | 0 | { |
1064 | 0 | List *vacrels = NIL; |
1065 | 0 | Relation pgclass; |
1066 | 0 | TableScanDesc scan; |
1067 | 0 | HeapTuple tuple; |
1068 | |
|
1069 | 0 | pgclass = table_open(RelationRelationId, AccessShareLock); |
1070 | |
|
1071 | 0 | scan = table_beginscan_catalog(pgclass, 0, NULL); |
1072 | |
|
1073 | 0 | while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) |
1074 | 0 | { |
1075 | 0 | Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple); |
1076 | 0 | MemoryContext oldcontext; |
1077 | 0 | 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 | 0 | if (classForm->relkind != RELKIND_RELATION && |
1085 | 0 | classForm->relkind != RELKIND_MATVIEW && |
1086 | 0 | classForm->relkind != RELKIND_PARTITIONED_TABLE) |
1087 | 0 | continue; |
1088 | | |
1089 | | /* Skip temp relations belonging to other sessions */ |
1090 | 0 | if (classForm->relpersistence == RELPERSISTENCE_TEMP && |
1091 | 0 | !isTempOrTempToastNamespace(classForm->relnamespace)) |
1092 | 0 | continue; |
1093 | | |
1094 | | /* check permissions of relation */ |
1095 | 0 | if (!vacuum_is_permitted_for_relation(relid, classForm, options, true)) |
1096 | 0 | 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 | 0 | oldcontext = MemoryContextSwitchTo(vac_context); |
1104 | 0 | vacrels = lappend(vacrels, makeVacuumRelation(NULL, |
1105 | 0 | relid, |
1106 | 0 | NIL)); |
1107 | 0 | MemoryContextSwitchTo(oldcontext); |
1108 | 0 | } |
1109 | |
|
1110 | 0 | table_endscan(scan); |
1111 | 0 | table_close(pgclass, AccessShareLock); |
1112 | |
|
1113 | 0 | return vacrels; |
1114 | 0 | } |
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 | | vacuum_get_cutoffs(Relation rel, const VacuumParams *params, |
1130 | | struct VacuumCutoffs *cutoffs) |
1131 | 0 | { |
1132 | 0 | int freeze_min_age, |
1133 | 0 | multixact_freeze_min_age, |
1134 | 0 | freeze_table_age, |
1135 | 0 | multixact_freeze_table_age, |
1136 | 0 | effective_multixact_freeze_max_age; |
1137 | 0 | TransactionId nextXID, |
1138 | 0 | safeOldestXmin, |
1139 | 0 | aggressiveXIDCutoff; |
1140 | 0 | MultiXactId nextMXID, |
1141 | 0 | safeOldestMxact, |
1142 | 0 | aggressiveMXIDCutoff; |
1143 | | |
1144 | | /* Use mutable copies of freeze age parameters */ |
1145 | 0 | freeze_min_age = params->freeze_min_age; |
1146 | 0 | multixact_freeze_min_age = params->multixact_freeze_min_age; |
1147 | 0 | freeze_table_age = params->freeze_table_age; |
1148 | 0 | multixact_freeze_table_age = params->multixact_freeze_table_age; |
1149 | | |
1150 | | /* Set pg_class fields in cutoffs */ |
1151 | 0 | cutoffs->relfrozenxid = rel->rd_rel->relfrozenxid; |
1152 | 0 | 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 | 0 | cutoffs->OldestXmin = GetOldestNonRemovableTransactionId(rel); |
1166 | |
|
1167 | 0 | Assert(TransactionIdIsNormal(cutoffs->OldestXmin)); |
1168 | | |
1169 | | /* Acquire OldestMxact */ |
1170 | 0 | cutoffs->OldestMxact = GetOldestMultiXactId(); |
1171 | 0 | Assert(MultiXactIdIsValid(cutoffs->OldestMxact)); |
1172 | | |
1173 | | /* Acquire next XID/next MXID values used to apply age-based settings */ |
1174 | 0 | nextXID = ReadNextTransactionId(); |
1175 | 0 | 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 | 0 | 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 | 0 | safeOldestXmin = nextXID - autovacuum_freeze_max_age; |
1189 | 0 | if (!TransactionIdIsNormal(safeOldestXmin)) |
1190 | 0 | safeOldestXmin = FirstNormalTransactionId; |
1191 | 0 | safeOldestMxact = nextMXID - effective_multixact_freeze_max_age; |
1192 | 0 | if (safeOldestMxact < FirstMultiXactId) |
1193 | 0 | safeOldestMxact = FirstMultiXactId; |
1194 | 0 | if (TransactionIdPrecedes(cutoffs->OldestXmin, safeOldestXmin)) |
1195 | 0 | ereport(WARNING, |
1196 | 0 | (errmsg("cutoff for removing and freezing tuples is far in the past"), |
1197 | 0 | errhint("Close open transactions soon to avoid wraparound problems.\n" |
1198 | 0 | "You might also need to commit or roll back old prepared transactions, or drop stale replication slots."))); |
1199 | 0 | if (MultiXactIdPrecedes(cutoffs->OldestMxact, safeOldestMxact)) |
1200 | 0 | ereport(WARNING, |
1201 | 0 | (errmsg("cutoff for freezing multixacts is far in the past"), |
1202 | 0 | errhint("Close open transactions soon to avoid wraparound problems.\n" |
1203 | 0 | "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 | 0 | if (freeze_min_age < 0) |
1212 | 0 | freeze_min_age = vacuum_freeze_min_age; |
1213 | 0 | freeze_min_age = Min(freeze_min_age, autovacuum_freeze_max_age / 2); |
1214 | 0 | Assert(freeze_min_age >= 0); |
1215 | | |
1216 | | /* Compute FreezeLimit, being careful to generate a normal XID */ |
1217 | 0 | cutoffs->FreezeLimit = nextXID - freeze_min_age; |
1218 | 0 | if (!TransactionIdIsNormal(cutoffs->FreezeLimit)) |
1219 | 0 | cutoffs->FreezeLimit = FirstNormalTransactionId; |
1220 | | /* FreezeLimit must always be <= OldestXmin */ |
1221 | 0 | if (TransactionIdPrecedes(cutoffs->OldestXmin, cutoffs->FreezeLimit)) |
1222 | 0 | 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 | 0 | if (multixact_freeze_min_age < 0) |
1231 | 0 | multixact_freeze_min_age = vacuum_multixact_freeze_min_age; |
1232 | 0 | multixact_freeze_min_age = Min(multixact_freeze_min_age, |
1233 | 0 | effective_multixact_freeze_max_age / 2); |
1234 | 0 | Assert(multixact_freeze_min_age >= 0); |
1235 | | |
1236 | | /* Compute MultiXactCutoff, being careful to generate a valid value */ |
1237 | 0 | cutoffs->MultiXactCutoff = nextMXID - multixact_freeze_min_age; |
1238 | 0 | if (cutoffs->MultiXactCutoff < FirstMultiXactId) |
1239 | 0 | cutoffs->MultiXactCutoff = FirstMultiXactId; |
1240 | | /* MultiXactCutoff must always be <= OldestMxact */ |
1241 | 0 | if (MultiXactIdPrecedes(cutoffs->OldestMxact, cutoffs->MultiXactCutoff)) |
1242 | 0 | 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 | 0 | if (freeze_table_age < 0) |
1254 | 0 | freeze_table_age = vacuum_freeze_table_age; |
1255 | 0 | freeze_table_age = Min(freeze_table_age, autovacuum_freeze_max_age * 0.95); |
1256 | 0 | Assert(freeze_table_age >= 0); |
1257 | 0 | aggressiveXIDCutoff = nextXID - freeze_table_age; |
1258 | 0 | if (!TransactionIdIsNormal(aggressiveXIDCutoff)) |
1259 | 0 | aggressiveXIDCutoff = FirstNormalTransactionId; |
1260 | 0 | if (TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid, |
1261 | 0 | aggressiveXIDCutoff)) |
1262 | 0 | 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 | 0 | if (multixact_freeze_table_age < 0) |
1273 | 0 | multixact_freeze_table_age = vacuum_multixact_freeze_table_age; |
1274 | 0 | multixact_freeze_table_age = |
1275 | 0 | Min(multixact_freeze_table_age, |
1276 | 0 | effective_multixact_freeze_max_age * 0.95); |
1277 | 0 | Assert(multixact_freeze_table_age >= 0); |
1278 | 0 | aggressiveMXIDCutoff = nextMXID - multixact_freeze_table_age; |
1279 | 0 | if (aggressiveMXIDCutoff < FirstMultiXactId) |
1280 | 0 | aggressiveMXIDCutoff = FirstMultiXactId; |
1281 | 0 | if (MultiXactIdPrecedesOrEquals(cutoffs->relminmxid, |
1282 | 0 | aggressiveMXIDCutoff)) |
1283 | 0 | return true; |
1284 | | |
1285 | | /* Non-aggressive VACUUM */ |
1286 | 0 | return false; |
1287 | 0 | } |
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 | | vacuum_xid_failsafe_check(const struct VacuumCutoffs *cutoffs) |
1298 | 0 | { |
1299 | 0 | TransactionId relfrozenxid = cutoffs->relfrozenxid; |
1300 | 0 | MultiXactId relminmxid = cutoffs->relminmxid; |
1301 | 0 | TransactionId xid_skip_limit; |
1302 | 0 | MultiXactId multi_skip_limit; |
1303 | 0 | int skip_index_vacuum; |
1304 | |
|
1305 | 0 | Assert(TransactionIdIsNormal(relfrozenxid)); |
1306 | 0 | 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 | 0 | skip_index_vacuum = Max(vacuum_failsafe_age, autovacuum_freeze_max_age * 1.05); |
1313 | |
|
1314 | 0 | xid_skip_limit = ReadNextTransactionId() - skip_index_vacuum; |
1315 | 0 | if (!TransactionIdIsNormal(xid_skip_limit)) |
1316 | 0 | xid_skip_limit = FirstNormalTransactionId; |
1317 | |
|
1318 | 0 | if (TransactionIdPrecedes(relfrozenxid, xid_skip_limit)) |
1319 | 0 | { |
1320 | | /* The table's relfrozenxid is too old */ |
1321 | 0 | return true; |
1322 | 0 | } |
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 | 0 | skip_index_vacuum = Max(vacuum_multixact_failsafe_age, |
1330 | 0 | autovacuum_multixact_freeze_max_age * 1.05); |
1331 | |
|
1332 | 0 | multi_skip_limit = ReadNextMultiXactId() - skip_index_vacuum; |
1333 | 0 | if (multi_skip_limit < FirstMultiXactId) |
1334 | 0 | multi_skip_limit = FirstMultiXactId; |
1335 | |
|
1336 | 0 | if (MultiXactIdPrecedes(relminmxid, multi_skip_limit)) |
1337 | 0 | { |
1338 | | /* The table's relminmxid is too old */ |
1339 | 0 | return true; |
1340 | 0 | } |
1341 | | |
1342 | 0 | return false; |
1343 | 0 | } |
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 | | vac_estimate_reltuples(Relation relation, |
1365 | | BlockNumber total_pages, |
1366 | | BlockNumber scanned_pages, |
1367 | | BlockNumber scanned_new_pages, |
1368 | | double scanned_tuples) |
1369 | 0 | { |
1370 | 0 | BlockNumber old_rel_pages = relation->rd_rel->relpages; |
1371 | 0 | BlockNumber sampled_pages; |
1372 | 0 | BlockNumber sampleable_pages; |
1373 | 0 | double old_rel_tuples = relation->rd_rel->reltuples; |
1374 | 0 | double old_density; |
1375 | 0 | double unscanned_pages; |
1376 | 0 | double total_tuples; |
1377 | |
|
1378 | 0 | Assert(scanned_new_pages <= scanned_pages); |
1379 | 0 | Assert(scanned_new_pages <= total_pages); |
1380 | | |
1381 | | /* If we did scan the whole table, just use the count as-is */ |
1382 | 0 | if (scanned_pages >= total_pages) |
1383 | 0 | return scanned_tuples; |
1384 | | |
1385 | 0 | sampled_pages = scanned_pages - scanned_new_pages; |
1386 | 0 | 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 | 0 | if (old_rel_tuples < 0 || old_rel_pages == 0) |
1394 | 0 | { |
1395 | 0 | if (sampled_pages <= 1 || |
1396 | 0 | sampled_pages < (double) sampleable_pages * 0.02) |
1397 | 0 | return -1; |
1398 | | |
1399 | 0 | return floor((scanned_tuples / sampled_pages) * sampleable_pages + 0.5); |
1400 | 0 | } |
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 | 0 | if (old_rel_pages == total_pages && |
1417 | 0 | (sampled_pages <= 1 || |
1418 | 0 | sampled_pages < (double) sampleable_pages * 0.02)) |
1419 | 0 | 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 | 0 | old_density = old_rel_tuples / old_rel_pages; |
1428 | 0 | unscanned_pages = (double) sampleable_pages - (double) sampled_pages; |
1429 | 0 | total_tuples = old_density * unscanned_pages + scanned_tuples; |
1430 | 0 | return floor(total_tuples + 0.5); |
1431 | 0 | } |
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 | | 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 | | 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 | | rd = table_open(RelationRelationId, RowExclusiveLock); |
1497 | | |
1498 | | /* Fetch a copy of the tuple to scribble on */ |
1499 | | ScanKeyInit(&key[0], |
1500 | | Anum_pg_class_oid, |
1501 | | BTEqualStrategyNumber, F_OIDEQ, |
1502 | | ObjectIdGetDatum(relid)); |
1503 | | systable_inplace_update_begin(rd, ClassOidIndexId, true, |
1504 | | NULL, 1, key, &ctup, &inplace_state); |
1505 | | if (!HeapTupleIsValid(ctup)) |
1506 | | elog(ERROR, "pg_class entry for relid %u vanished during vacuuming", |
1507 | | relid); |
1508 | | pgcform = (Form_pg_class) GETSTRUCT(ctup); |
1509 | | |
1510 | | /* Apply statistical updates, if any, to copied tuple */ |
1511 | | |
1512 | | dirty = false; |
1513 | | if (pgcform->relpages != (int32) num_pages) |
1514 | | { |
1515 | | pgcform->relpages = (int32) num_pages; |
1516 | | dirty = true; |
1517 | | } |
1518 | | if (pgcform->reltuples != (float4) num_tuples) |
1519 | | { |
1520 | | pgcform->reltuples = (float4) num_tuples; |
1521 | | dirty = true; |
1522 | | } |
1523 | | if (pgcform->relallvisible != (int32) num_all_visible_pages) |
1524 | | { |
1525 | | pgcform->relallvisible = (int32) num_all_visible_pages; |
1526 | | dirty = true; |
1527 | | } |
1528 | | if (pgcform->relallfrozen != (int32) num_all_frozen_pages) |
1529 | | { |
1530 | | pgcform->relallfrozen = (int32) num_all_frozen_pages; |
1531 | | dirty = true; |
1532 | | } |
1533 | | |
1534 | | /* Apply DDL updates, but not inside an outer transaction (see above) */ |
1535 | | |
1536 | | if (!in_outer_xact) |
1537 | | { |
1538 | | /* |
1539 | | * If we didn't find any indexes, reset relhasindex. |
1540 | | */ |
1541 | | if (pgcform->relhasindex && !hasindex) |
1542 | | { |
1543 | | pgcform->relhasindex = false; |
1544 | | dirty = true; |
1545 | | } |
1546 | | |
1547 | | /* We also clear relhasrules and relhastriggers if needed */ |
1548 | | if (pgcform->relhasrules && relation->rd_rules == NULL) |
1549 | | { |
1550 | | pgcform->relhasrules = false; |
1551 | | dirty = true; |
1552 | | } |
1553 | | if (pgcform->relhastriggers && relation->trigdesc == NULL) |
1554 | | { |
1555 | | pgcform->relhastriggers = false; |
1556 | | 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 | | oldfrozenxid = pgcform->relfrozenxid; |
1571 | | futurexid = false; |
1572 | | if (frozenxid_updated) |
1573 | | *frozenxid_updated = false; |
1574 | | if (TransactionIdIsNormal(frozenxid) && oldfrozenxid != frozenxid) |
1575 | | { |
1576 | | bool update = false; |
1577 | | |
1578 | | if (TransactionIdPrecedes(oldfrozenxid, frozenxid)) |
1579 | | update = true; |
1580 | | else if (TransactionIdPrecedes(ReadNextTransactionId(), oldfrozenxid)) |
1581 | | futurexid = update = true; |
1582 | | |
1583 | | if (update) |
1584 | | { |
1585 | | pgcform->relfrozenxid = frozenxid; |
1586 | | dirty = true; |
1587 | | if (frozenxid_updated) |
1588 | | *frozenxid_updated = true; |
1589 | | } |
1590 | | } |
1591 | | |
1592 | | /* Similarly for relminmxid */ |
1593 | | oldminmulti = pgcform->relminmxid; |
1594 | | futuremxid = false; |
1595 | | if (minmulti_updated) |
1596 | | *minmulti_updated = false; |
1597 | | if (MultiXactIdIsValid(minmulti) && oldminmulti != minmulti) |
1598 | | { |
1599 | | bool update = false; |
1600 | | |
1601 | | if (MultiXactIdPrecedes(oldminmulti, minmulti)) |
1602 | | update = true; |
1603 | | else if (MultiXactIdPrecedes(ReadNextMultiXactId(), oldminmulti)) |
1604 | | futuremxid = update = true; |
1605 | | |
1606 | | if (update) |
1607 | | { |
1608 | | pgcform->relminmxid = minmulti; |
1609 | | dirty = true; |
1610 | | if (minmulti_updated) |
1611 | | *minmulti_updated = true; |
1612 | | } |
1613 | | } |
1614 | | |
1615 | | /* If anything changed, write out the tuple. */ |
1616 | | if (dirty) |
1617 | | systable_inplace_update_finish(inplace_state, ctup); |
1618 | | else |
1619 | | systable_inplace_update_cancel(inplace_state); |
1620 | | |
1621 | | table_close(rd, RowExclusiveLock); |
1622 | | |
1623 | | if (futurexid) |
1624 | | 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 | | if (futuremxid) |
1630 | | 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 | | } |
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 | | vac_update_datfrozenxid(void) |
1658 | 0 | { |
1659 | 0 | HeapTuple tuple; |
1660 | 0 | Form_pg_database dbform; |
1661 | 0 | Relation relation; |
1662 | 0 | SysScanDesc scan; |
1663 | 0 | HeapTuple classTup; |
1664 | 0 | TransactionId newFrozenXid; |
1665 | 0 | MultiXactId newMinMulti; |
1666 | 0 | TransactionId lastSaneFrozenXid; |
1667 | 0 | MultiXactId lastSaneMinMulti; |
1668 | 0 | bool bogus = false; |
1669 | 0 | bool dirty = false; |
1670 | 0 | ScanKeyData key[1]; |
1671 | 0 | 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 | 0 | 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 | 0 | 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 | 0 | 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 | 0 | lastSaneFrozenXid = ReadNextTransactionId(); |
1702 | 0 | 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 | 0 | relation = table_open(RelationRelationId, AccessShareLock); |
1711 | |
|
1712 | 0 | scan = systable_beginscan(relation, InvalidOid, false, |
1713 | 0 | NULL, 0, NULL); |
1714 | |
|
1715 | 0 | while ((classTup = systable_getnext(scan)) != NULL) |
1716 | 0 | { |
1717 | 0 | Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup); |
1718 | 0 | volatile TransactionId *relfrozenxid_p = &classForm->relfrozenxid; |
1719 | 0 | volatile TransactionId *relminmxid_p = &classForm->relminmxid; |
1720 | 0 | TransactionId relfrozenxid = *relfrozenxid_p; |
1721 | 0 | 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 | 0 | if (classForm->relkind != RELKIND_RELATION && |
1728 | 0 | classForm->relkind != RELKIND_MATVIEW && |
1729 | 0 | classForm->relkind != RELKIND_TOASTVALUE) |
1730 | 0 | { |
1731 | 0 | Assert(!TransactionIdIsValid(relfrozenxid)); |
1732 | 0 | Assert(!MultiXactIdIsValid(relminmxid)); |
1733 | 0 | continue; |
1734 | 0 | } |
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 | 0 | if (TransactionIdIsValid(relfrozenxid)) |
1752 | 0 | { |
1753 | 0 | Assert(TransactionIdIsNormal(relfrozenxid)); |
1754 | | |
1755 | | /* check for values in the future */ |
1756 | 0 | if (TransactionIdPrecedes(lastSaneFrozenXid, relfrozenxid)) |
1757 | 0 | { |
1758 | 0 | bogus = true; |
1759 | 0 | break; |
1760 | 0 | } |
1761 | | |
1762 | | /* determine new horizon */ |
1763 | 0 | if (TransactionIdPrecedes(relfrozenxid, newFrozenXid)) |
1764 | 0 | newFrozenXid = relfrozenxid; |
1765 | 0 | } |
1766 | | |
1767 | 0 | if (MultiXactIdIsValid(relminmxid)) |
1768 | 0 | { |
1769 | | /* check for values in the future */ |
1770 | 0 | if (MultiXactIdPrecedes(lastSaneMinMulti, relminmxid)) |
1771 | 0 | { |
1772 | 0 | bogus = true; |
1773 | 0 | break; |
1774 | 0 | } |
1775 | | |
1776 | | /* determine new horizon */ |
1777 | 0 | if (MultiXactIdPrecedes(relminmxid, newMinMulti)) |
1778 | 0 | newMinMulti = relminmxid; |
1779 | 0 | } |
1780 | 0 | } |
1781 | | |
1782 | | /* we're done with pg_class */ |
1783 | 0 | systable_endscan(scan); |
1784 | 0 | table_close(relation, AccessShareLock); |
1785 | | |
1786 | | /* chicken out if bogus data found */ |
1787 | 0 | if (bogus) |
1788 | 0 | return; |
1789 | | |
1790 | 0 | Assert(TransactionIdIsNormal(newFrozenXid)); |
1791 | 0 | Assert(MultiXactIdIsValid(newMinMulti)); |
1792 | | |
1793 | | /* Now fetch the pg_database tuple we need to update. */ |
1794 | 0 | 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 | 0 | ScanKeyInit(&key[0], |
1803 | 0 | Anum_pg_database_oid, |
1804 | 0 | BTEqualStrategyNumber, F_OIDEQ, |
1805 | 0 | ObjectIdGetDatum(MyDatabaseId)); |
1806 | |
|
1807 | 0 | systable_inplace_update_begin(relation, DatabaseOidIndexId, true, |
1808 | 0 | NULL, 1, key, &tuple, &inplace_state); |
1809 | |
|
1810 | 0 | if (!HeapTupleIsValid(tuple)) |
1811 | 0 | elog(ERROR, "could not find tuple for database %u", MyDatabaseId); |
1812 | | |
1813 | 0 | 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 | 0 | if (dbform->datfrozenxid != newFrozenXid && |
1821 | 0 | (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) || |
1822 | 0 | TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid))) |
1823 | 0 | { |
1824 | 0 | dbform->datfrozenxid = newFrozenXid; |
1825 | 0 | dirty = true; |
1826 | 0 | } |
1827 | 0 | else |
1828 | 0 | newFrozenXid = dbform->datfrozenxid; |
1829 | | |
1830 | | /* Ditto for datminmxid */ |
1831 | 0 | if (dbform->datminmxid != newMinMulti && |
1832 | 0 | (MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) || |
1833 | 0 | MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid))) |
1834 | 0 | { |
1835 | 0 | dbform->datminmxid = newMinMulti; |
1836 | 0 | dirty = true; |
1837 | 0 | } |
1838 | 0 | else |
1839 | 0 | newMinMulti = dbform->datminmxid; |
1840 | |
|
1841 | 0 | if (dirty) |
1842 | 0 | systable_inplace_update_finish(inplace_state, tuple); |
1843 | 0 | else |
1844 | 0 | systable_inplace_update_cancel(inplace_state); |
1845 | |
|
1846 | 0 | heap_freetuple(tuple); |
1847 | 0 | 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 | 0 | if (dirty || ForceTransactionIdLimitUpdate()) |
1855 | 0 | vac_truncate_clog(newFrozenXid, newMinMulti, |
1856 | 0 | lastSaneFrozenXid, lastSaneMinMulti); |
1857 | 0 | } |
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 | | vac_truncate_clog(TransactionId frozenXID, |
1879 | | MultiXactId minMulti, |
1880 | | TransactionId lastSaneFrozenXid, |
1881 | | MultiXactId lastSaneMinMulti) |
1882 | 0 | { |
1883 | 0 | TransactionId nextXID = ReadNextTransactionId(); |
1884 | 0 | Relation relation; |
1885 | 0 | TableScanDesc scan; |
1886 | 0 | HeapTuple tuple; |
1887 | 0 | Oid oldestxid_datoid; |
1888 | 0 | Oid minmulti_datoid; |
1889 | 0 | bool bogus = false; |
1890 | 0 | bool frozenAlreadyWrapped = false; |
1891 | | |
1892 | | /* Restrict task to one backend per cluster; see SimpleLruTruncate(). */ |
1893 | 0 | LWLockAcquire(WrapLimitsVacuumLock, LW_EXCLUSIVE); |
1894 | | |
1895 | | /* init oldest datoids to sync with my frozenXID/minMulti values */ |
1896 | 0 | oldestxid_datoid = MyDatabaseId; |
1897 | 0 | 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 | 0 | relation = table_open(DatabaseRelationId, AccessShareLock); |
1918 | |
|
1919 | 0 | scan = table_beginscan_catalog(relation, 0, NULL); |
1920 | |
|
1921 | 0 | while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL) |
1922 | 0 | { |
1923 | 0 | Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple); |
1924 | 0 | volatile TransactionId *datfrozenxid_p = &dbform->datfrozenxid; |
1925 | 0 | volatile TransactionId *datminmxid_p = &dbform->datminmxid; |
1926 | 0 | TransactionId datfrozenxid = *datfrozenxid_p; |
1927 | 0 | TransactionId datminmxid = *datminmxid_p; |
1928 | |
|
1929 | 0 | Assert(TransactionIdIsNormal(datfrozenxid)); |
1930 | 0 | 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 | 0 | if (database_is_invalid_form((Form_pg_database) dbform)) |
1939 | 0 | { |
1940 | 0 | elog(DEBUG2, |
1941 | 0 | "skipping invalid database \"%s\" while computing relfrozenxid", |
1942 | 0 | NameStr(dbform->datname)); |
1943 | 0 | continue; |
1944 | 0 | } |
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 | 0 | if (TransactionIdPrecedes(lastSaneFrozenXid, datfrozenxid) || |
1956 | 0 | MultiXactIdPrecedes(lastSaneMinMulti, datminmxid)) |
1957 | 0 | bogus = true; |
1958 | |
|
1959 | 0 | if (TransactionIdPrecedes(nextXID, datfrozenxid)) |
1960 | 0 | frozenAlreadyWrapped = true; |
1961 | 0 | else if (TransactionIdPrecedes(datfrozenxid, frozenXID)) |
1962 | 0 | { |
1963 | 0 | frozenXID = datfrozenxid; |
1964 | 0 | oldestxid_datoid = dbform->oid; |
1965 | 0 | } |
1966 | |
|
1967 | 0 | if (MultiXactIdPrecedes(datminmxid, minMulti)) |
1968 | 0 | { |
1969 | 0 | minMulti = datminmxid; |
1970 | 0 | minmulti_datoid = dbform->oid; |
1971 | 0 | } |
1972 | 0 | } |
1973 | | |
1974 | 0 | table_endscan(scan); |
1975 | |
|
1976 | 0 | 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 | 0 | if (frozenAlreadyWrapped) |
1985 | 0 | { |
1986 | 0 | ereport(WARNING, |
1987 | 0 | (errmsg("some databases have not been vacuumed in over 2 billion transactions"), |
1988 | 0 | errdetail("You might have already suffered transaction-wraparound data loss."))); |
1989 | 0 | LWLockRelease(WrapLimitsVacuumLock); |
1990 | 0 | return; |
1991 | 0 | } |
1992 | | |
1993 | | /* chicken out if data is bogus in any other way */ |
1994 | 0 | if (bogus) |
1995 | 0 | { |
1996 | 0 | LWLockRelease(WrapLimitsVacuumLock); |
1997 | 0 | return; |
1998 | 0 | } |
1999 | | |
2000 | | /* |
2001 | | * Freeze any old transaction IDs in the async notification queue before |
2002 | | * CLOG truncation. |
2003 | | */ |
2004 | 0 | 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 | 0 | AdvanceOldestCommitTsXid(frozenXID); |
2014 | | |
2015 | | /* |
2016 | | * Truncate CLOG, multixact and CommitTs to the oldest computed value. |
2017 | | */ |
2018 | 0 | TruncateCLOG(frozenXID, oldestxid_datoid); |
2019 | 0 | TruncateCommitTs(frozenXID); |
2020 | 0 | 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 | 0 | SetTransactionIdLimit(frozenXID, oldestxid_datoid); |
2029 | 0 | SetMultiXactIdLimit(minMulti, minmulti_datoid); |
2030 | |
|
2031 | 0 | LWLockRelease(WrapLimitsVacuumLock); |
2032 | 0 | } |
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 | | vacuum_rel(Oid relid, RangeVar *relation, VacuumParams params, |
2056 | | BufferAccessStrategy bstrategy, bool isTopLevel) |
2057 | 0 | { |
2058 | 0 | LOCKMODE lmode; |
2059 | 0 | Relation rel; |
2060 | 0 | LockRelId lockrelid; |
2061 | 0 | Oid priv_relid; |
2062 | 0 | Oid toast_relid; |
2063 | 0 | Oid save_userid; |
2064 | 0 | int save_sec_context; |
2065 | 0 | int save_nestlevel; |
2066 | 0 | VacuumParams toast_vacuum_params; |
2067 | 0 | StdRdOptions *relopts; |
2068 | 0 | 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 | 0 | memcpy(&toast_vacuum_params, ¶ms, sizeof(VacuumParams)); |
2075 | | |
2076 | | /* Begin a transaction for vacuuming this relation */ |
2077 | 0 | StartTransactionCommand(); |
2078 | |
|
2079 | 0 | if (!(params.options & VACOPT_FULL)) |
2080 | 0 | { |
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 | 0 | LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE); |
2104 | 0 | MyProc->statusFlags |= PROC_IN_VACUUM; |
2105 | 0 | if (params.is_wraparound) |
2106 | 0 | MyProc->statusFlags |= PROC_VACUUM_FOR_WRAPAROUND; |
2107 | 0 | ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags; |
2108 | 0 | LWLockRelease(ProcArrayLock); |
2109 | 0 | } |
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 | 0 | 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 | 0 | 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 | 0 | lmode = (params.options & VACOPT_FULL) ? |
2130 | 0 | AccessExclusiveLock : ShareUpdateExclusiveLock; |
2131 | | |
2132 | | /* open the relation and get the appropriate lock on it */ |
2133 | 0 | rel = vacuum_open_relation(relid, relation, params.options, |
2134 | 0 | params.log_vacuum_min_duration >= 0, lmode); |
2135 | | |
2136 | | /* leave if relation could not be opened or locked */ |
2137 | 0 | if (!rel) |
2138 | 0 | { |
2139 | 0 | PopActiveSnapshot(); |
2140 | 0 | CommitTransactionCommand(); |
2141 | 0 | return false; |
2142 | 0 | } |
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 | 0 | if (OidIsValid(params.toast_parent)) |
2150 | 0 | priv_relid = params.toast_parent; |
2151 | 0 | else |
2152 | 0 | 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 | 0 | if (!vacuum_is_permitted_for_relation(priv_relid, |
2162 | 0 | rel->rd_rel, |
2163 | 0 | params.options & ~VACOPT_ANALYZE, |
2164 | 0 | false)) |
2165 | 0 | { |
2166 | 0 | relation_close(rel, lmode); |
2167 | 0 | PopActiveSnapshot(); |
2168 | 0 | CommitTransactionCommand(); |
2169 | 0 | return false; |
2170 | 0 | } |
2171 | | |
2172 | | /* |
2173 | | * Check that it's of a vacuumable relkind. |
2174 | | */ |
2175 | 0 | if (rel->rd_rel->relkind != RELKIND_RELATION && |
2176 | 0 | rel->rd_rel->relkind != RELKIND_MATVIEW && |
2177 | 0 | rel->rd_rel->relkind != RELKIND_TOASTVALUE && |
2178 | 0 | rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE) |
2179 | 0 | { |
2180 | 0 | ereport(WARNING, |
2181 | 0 | (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables", |
2182 | 0 | RelationGetRelationName(rel)))); |
2183 | 0 | relation_close(rel, lmode); |
2184 | 0 | PopActiveSnapshot(); |
2185 | 0 | CommitTransactionCommand(); |
2186 | 0 | return false; |
2187 | 0 | } |
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 | 0 | if (RELATION_IS_OTHER_TEMP(rel)) |
2197 | 0 | { |
2198 | 0 | relation_close(rel, lmode); |
2199 | 0 | PopActiveSnapshot(); |
2200 | 0 | CommitTransactionCommand(); |
2201 | 0 | return false; |
2202 | 0 | } |
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 | 0 | if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) |
2210 | 0 | { |
2211 | 0 | relation_close(rel, lmode); |
2212 | 0 | PopActiveSnapshot(); |
2213 | 0 | CommitTransactionCommand(); |
2214 | | /* It's OK to proceed with ANALYZE on this table */ |
2215 | 0 | return true; |
2216 | 0 | } |
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 | 0 | lockrelid = rel->rd_lockInfo.lockRelId; |
2229 | 0 | 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 | 0 | relopts = merge_toast_reloptions((StdRdOptions *) rel->rd_options, |
2238 | 0 | 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 | 0 | if (params.index_cleanup == VACOPTVALUE_UNSPECIFIED) |
2245 | 0 | { |
2246 | 0 | StdRdOptIndexCleanup vacuum_index_cleanup; |
2247 | |
|
2248 | 0 | if (relopts == NULL) |
2249 | 0 | vacuum_index_cleanup = STDRD_OPTION_VACUUM_INDEX_CLEANUP_NOT_SET; |
2250 | 0 | else |
2251 | 0 | vacuum_index_cleanup = relopts->vacuum_index_cleanup; |
2252 | |
|
2253 | 0 | switch (vacuum_index_cleanup) |
2254 | 0 | { |
2255 | 0 | case STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON: |
2256 | 0 | params.index_cleanup = VACOPTVALUE_ENABLED; |
2257 | 0 | break; |
2258 | 0 | case STDRD_OPTION_VACUUM_INDEX_CLEANUP_OFF: |
2259 | 0 | params.index_cleanup = VACOPTVALUE_DISABLED; |
2260 | 0 | break; |
2261 | 0 | case STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO: |
2262 | 0 | params.index_cleanup = VACOPTVALUE_AUTO; |
2263 | 0 | break; |
2264 | 0 | case STDRD_OPTION_VACUUM_INDEX_CLEANUP_NOT_SET: |
2265 | 0 | params.index_cleanup = VACOPTVALUE_AUTO; |
2266 | 0 | break; |
2267 | 0 | } |
2268 | 0 | } |
2269 | | |
2270 | | #ifdef USE_INJECTION_POINTS |
2271 | | if (params.index_cleanup == VACOPTVALUE_AUTO) |
2272 | | INJECTION_POINT("vacuum-index-cleanup-auto", NULL); |
2273 | | else if (params.index_cleanup == VACOPTVALUE_DISABLED) |
2274 | | INJECTION_POINT("vacuum-index-cleanup-disabled", NULL); |
2275 | | else if (params.index_cleanup == VACOPTVALUE_ENABLED) |
2276 | | 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 | 0 | 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 | 0 | if (params.truncate == VACOPTVALUE_UNSPECIFIED) |
2291 | 0 | { |
2292 | 0 | if (relopts && relopts->vacuum_truncate != PG_TERNARY_UNSET) |
2293 | 0 | { |
2294 | 0 | if (relopts->vacuum_truncate == PG_TERNARY_TRUE) |
2295 | 0 | params.truncate = VACOPTVALUE_ENABLED; |
2296 | 0 | else |
2297 | 0 | params.truncate = VACOPTVALUE_DISABLED; |
2298 | 0 | } |
2299 | 0 | else if (vacuum_truncate) |
2300 | 0 | params.truncate = VACOPTVALUE_ENABLED; |
2301 | 0 | else |
2302 | 0 | params.truncate = VACOPTVALUE_DISABLED; |
2303 | 0 | } |
2304 | |
|
2305 | | #ifdef USE_INJECTION_POINTS |
2306 | | if (params.truncate == VACOPTVALUE_AUTO) |
2307 | | INJECTION_POINT("vacuum-truncate-auto", NULL); |
2308 | | else if (params.truncate == VACOPTVALUE_DISABLED) |
2309 | | INJECTION_POINT("vacuum-truncate-disabled", NULL); |
2310 | | else if (params.truncate == VACOPTVALUE_ENABLED) |
2311 | | 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 | 0 | if ((params.options & VACOPT_PROCESS_TOAST) != 0 && |
2321 | 0 | ((params.options & VACOPT_FULL) == 0 || |
2322 | 0 | (params.options & VACOPT_PROCESS_MAIN) == 0)) |
2323 | 0 | toast_relid = rel->rd_rel->reltoastrelid; |
2324 | 0 | else |
2325 | 0 | 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 | 0 | if (OidIsValid(toast_relid) && rel->rd_options) |
2333 | 0 | { |
2334 | 0 | memcpy(&relopts_copy, rel->rd_options, sizeof(StdRdOptions)); |
2335 | 0 | toast_vacuum_params.main_relopts = &relopts_copy; |
2336 | 0 | } |
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 | 0 | GetUserIdAndSecContext(&save_userid, &save_sec_context); |
2345 | 0 | SetUserIdAndSecContext(rel->rd_rel->relowner, |
2346 | 0 | save_sec_context | SECURITY_RESTRICTED_OPERATION); |
2347 | 0 | save_nestlevel = NewGUCNestLevel(); |
2348 | 0 | 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 | 0 | if (params.options & VACOPT_PROCESS_MAIN) |
2357 | 0 | { |
2358 | | /* |
2359 | | * Do the actual work --- either FULL or "lazy" vacuum |
2360 | | */ |
2361 | 0 | if (params.options & VACOPT_FULL) |
2362 | 0 | { |
2363 | 0 | ClusterParams cluster_params = {0}; |
2364 | |
|
2365 | 0 | if ((params.options & VACOPT_VERBOSE) != 0) |
2366 | 0 | cluster_params.options |= CLUOPT_VERBOSE; |
2367 | | |
2368 | | /* VACUUM FULL is a variant of REPACK; see repack.c */ |
2369 | 0 | cluster_rel(REPACK_COMMAND_VACUUMFULL, rel, InvalidOid, |
2370 | 0 | &cluster_params, isTopLevel); |
2371 | | /* cluster_rel closes the relation, but keeps lock */ |
2372 | |
|
2373 | 0 | rel = NULL; |
2374 | 0 | } |
2375 | 0 | else |
2376 | 0 | table_relation_vacuum(rel, ¶ms, bstrategy); |
2377 | 0 | } |
2378 | | |
2379 | | /* Roll back any GUC changes executed by index functions */ |
2380 | 0 | AtEOXact_GUC(false, save_nestlevel); |
2381 | | |
2382 | | /* Restore userid and security context */ |
2383 | 0 | SetUserIdAndSecContext(save_userid, save_sec_context); |
2384 | | |
2385 | | /* all done with this class, but hold lock until commit */ |
2386 | 0 | if (rel) |
2387 | 0 | relation_close(rel, NoLock); |
2388 | | |
2389 | | /* |
2390 | | * Complete the transaction and free all temporary memory used. |
2391 | | */ |
2392 | 0 | PopActiveSnapshot(); |
2393 | 0 | 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 | 0 | if (toast_relid != InvalidOid) |
2403 | 0 | { |
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 | 0 | toast_vacuum_params.options |= VACOPT_PROCESS_MAIN; |
2411 | 0 | toast_vacuum_params.toast_parent = relid; |
2412 | |
|
2413 | 0 | vacuum_rel(toast_relid, NULL, toast_vacuum_params, bstrategy, |
2414 | 0 | isTopLevel); |
2415 | 0 | } |
2416 | | |
2417 | | /* |
2418 | | * Now release the session-level lock on the main table. |
2419 | | */ |
2420 | 0 | UnlockRelationIdForSession(&lockrelid, lmode); |
2421 | | |
2422 | | /* Report that we really did it. */ |
2423 | 0 | return true; |
2424 | 0 | } |
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 | | vac_open_indexes(Relation relation, LOCKMODE lockmode, |
2441 | | int *nindexes, Relation **Irel) |
2442 | 0 | { |
2443 | 0 | List *indexoidlist; |
2444 | 0 | ListCell *indexoidscan; |
2445 | 0 | int i; |
2446 | |
|
2447 | 0 | Assert(lockmode != NoLock); |
2448 | |
|
2449 | 0 | indexoidlist = RelationGetIndexList(relation); |
2450 | | |
2451 | | /* allocate enough memory for all indexes */ |
2452 | 0 | i = list_length(indexoidlist); |
2453 | |
|
2454 | 0 | if (i > 0) |
2455 | 0 | *Irel = palloc_array(Relation, i); |
2456 | 0 | else |
2457 | 0 | *Irel = NULL; |
2458 | | |
2459 | | /* collect just the ready indexes */ |
2460 | 0 | i = 0; |
2461 | 0 | foreach(indexoidscan, indexoidlist) |
2462 | 0 | { |
2463 | 0 | Oid indexoid = lfirst_oid(indexoidscan); |
2464 | 0 | Relation indrel; |
2465 | |
|
2466 | 0 | indrel = index_open(indexoid, lockmode); |
2467 | 0 | if (indrel->rd_index->indisready) |
2468 | 0 | (*Irel)[i++] = indrel; |
2469 | 0 | else |
2470 | 0 | index_close(indrel, lockmode); |
2471 | 0 | } |
2472 | |
|
2473 | 0 | *nindexes = i; |
2474 | |
|
2475 | 0 | list_free(indexoidlist); |
2476 | 0 | } |
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 | | vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode) |
2484 | 0 | { |
2485 | 0 | if (Irel == NULL) |
2486 | 0 | return; |
2487 | | |
2488 | 0 | while (nindexes--) |
2489 | 0 | { |
2490 | 0 | Relation ind = Irel[nindexes]; |
2491 | |
|
2492 | 0 | index_close(ind, lockmode); |
2493 | 0 | } |
2494 | 0 | pfree(Irel); |
2495 | 0 | } |
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 | | vacuum_delay_point(bool is_analyze) |
2505 | 0 | { |
2506 | 0 | 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 | 0 | if (!INTERRUPTS_CAN_BE_PROCESSED()) |
2514 | 0 | return; |
2515 | | |
2516 | | /* Always check for interrupts */ |
2517 | 0 | CHECK_FOR_INTERRUPTS(); |
2518 | |
|
2519 | 0 | if (InterruptPending) |
2520 | 0 | return; |
2521 | | |
2522 | 0 | if (IsParallelWorker()) |
2523 | 0 | { |
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 | 0 | parallel_vacuum_update_shared_delay_params(); |
2530 | 0 | } |
2531 | |
|
2532 | 0 | if (!VacuumCostActive && !ConfigReloadPending) |
2533 | 0 | 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 | 0 | if (ConfigReloadPending && AmAutoVacuumWorkerProcess()) |
2542 | 0 | { |
2543 | 0 | ConfigReloadPending = false; |
2544 | 0 | ProcessConfigFile(PGC_SIGHUP); |
2545 | 0 | 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 | 0 | parallel_vacuum_propagate_shared_delay_params(); |
2552 | 0 | } |
2553 | | |
2554 | | /* |
2555 | | * If we disabled cost-based delays after reloading the config file, |
2556 | | * return. |
2557 | | */ |
2558 | 0 | 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 | 0 | if (VacuumSharedCostBalance != NULL) |
2566 | 0 | msec = compute_parallel_delay(); |
2567 | 0 | else if (VacuumCostBalance >= vacuum_cost_limit) |
2568 | 0 | { |
2569 | 0 | 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 | 0 | msec = Min(msec, vacuum_cost_delay * 4); |
2577 | 0 | } |
2578 | | |
2579 | | /* Nap if appropriate */ |
2580 | 0 | if (msec > 0) |
2581 | 0 | { |
2582 | 0 | instr_time delay_start; |
2583 | |
|
2584 | 0 | if (track_cost_delay_timing) |
2585 | 0 | INSTR_TIME_SET_CURRENT(delay_start); |
2586 | |
|
2587 | 0 | pgstat_report_wait_start(WAIT_EVENT_VACUUM_DELAY); |
2588 | 0 | pg_usleep(msec * 1000); |
2589 | 0 | pgstat_report_wait_end(); |
2590 | |
|
2591 | 0 | if (track_cost_delay_timing) |
2592 | 0 | { |
2593 | 0 | instr_time delay_end; |
2594 | 0 | instr_time delay; |
2595 | |
|
2596 | 0 | INSTR_TIME_SET_CURRENT(delay_end); |
2597 | 0 | INSTR_TIME_SET_ZERO(delay); |
2598 | 0 | 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 | 0 | if (IsParallelWorker()) |
2606 | 0 | { |
2607 | 0 | static instr_time last_report_time; |
2608 | 0 | instr_time time_since_last_report; |
2609 | |
|
2610 | 0 | Assert(!is_analyze); |
2611 | | |
2612 | | /* Accumulate the delay time */ |
2613 | 0 | parallel_vacuum_worker_delay_ns += INSTR_TIME_GET_NANOSEC(delay); |
2614 | | |
2615 | | /* Calculate interval since last report */ |
2616 | 0 | INSTR_TIME_SET_ZERO(time_since_last_report); |
2617 | 0 | 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 | 0 | if (INSTR_TIME_GET_NANOSEC(time_since_last_report) >= |
2621 | 0 | PARALLEL_VACUUM_DELAY_REPORT_INTERVAL_NS) |
2622 | 0 | { |
2623 | 0 | pgstat_progress_parallel_incr_param(PROGRESS_VACUUM_DELAY_TIME, |
2624 | 0 | parallel_vacuum_worker_delay_ns); |
2625 | | |
2626 | | /* Reset variables */ |
2627 | 0 | last_report_time = delay_end; |
2628 | 0 | parallel_vacuum_worker_delay_ns = 0; |
2629 | 0 | } |
2630 | 0 | } |
2631 | 0 | else if (is_analyze) |
2632 | 0 | pgstat_progress_incr_param(PROGRESS_ANALYZE_DELAY_TIME, |
2633 | 0 | INSTR_TIME_GET_NANOSEC(delay)); |
2634 | 0 | else |
2635 | 0 | pgstat_progress_incr_param(PROGRESS_VACUUM_DELAY_TIME, |
2636 | 0 | INSTR_TIME_GET_NANOSEC(delay)); |
2637 | 0 | } |
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 | 0 | if (IsUnderPostmaster && !PostmasterIsAlive()) |
2646 | 0 | exit(1); |
2647 | | |
2648 | 0 | 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 | 0 | AutoVacuumUpdateCostLimit(); |
2659 | |
|
2660 | 0 | if (AmAutoVacuumWorkerProcess()) |
2661 | 0 | parallel_vacuum_propagate_shared_delay_params(); |
2662 | | |
2663 | | /* Might have gotten an interrupt while sleeping */ |
2664 | 0 | CHECK_FOR_INTERRUPTS(); |
2665 | 0 | } |
2666 | 0 | } |
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 | | compute_parallel_delay(void) |
2693 | 0 | { |
2694 | 0 | double msec = 0; |
2695 | 0 | uint32 shared_balance; |
2696 | 0 | int nworkers; |
2697 | | |
2698 | | /* Parallel vacuum must be active */ |
2699 | 0 | Assert(VacuumSharedCostBalance); |
2700 | |
|
2701 | 0 | nworkers = pg_atomic_read_u32(VacuumActiveNWorkers); |
2702 | | |
2703 | | /* At least count itself */ |
2704 | 0 | Assert(nworkers >= 1); |
2705 | | |
2706 | | /* Update the shared cost balance value atomically */ |
2707 | 0 | shared_balance = pg_atomic_add_fetch_u32(VacuumSharedCostBalance, VacuumCostBalance); |
2708 | | |
2709 | | /* Compute the total local balance for the current worker */ |
2710 | 0 | VacuumCostBalanceLocal += VacuumCostBalance; |
2711 | |
|
2712 | 0 | if ((shared_balance >= vacuum_cost_limit) && |
2713 | 0 | (VacuumCostBalanceLocal > 0.5 * ((double) vacuum_cost_limit / nworkers))) |
2714 | 0 | { |
2715 | | /* Compute sleep time based on the local cost balance and nworkers */ |
2716 | 0 | msec = vacuum_cost_delay * VacuumCostBalanceLocal * nworkers / |
2717 | 0 | 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 | 0 | msec = Min(msec, Min(vacuum_cost_delay * 4 * nworkers, 1000)); |
2726 | |
|
2727 | 0 | pg_atomic_sub_fetch_u32(VacuumSharedCostBalance, VacuumCostBalanceLocal); |
2728 | 0 | VacuumCostBalanceLocal = 0; |
2729 | 0 | } |
2730 | | |
2731 | | /* |
2732 | | * Reset the local balance as we accumulated it into the shared value. |
2733 | | */ |
2734 | 0 | VacuumCostBalance = 0; |
2735 | |
|
2736 | 0 | return msec; |
2737 | 0 | } |
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 | | get_vacoptval_from_boolean(DefElem *def) |
2747 | 0 | { |
2748 | 0 | return defGetBoolean(def) ? VACOPTVALUE_ENABLED : VACOPTVALUE_DISABLED; |
2749 | 0 | } |
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 | | vac_bulkdel_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat, |
2758 | | TidStore *dead_items, VacDeadItemsInfo *dead_items_info) |
2759 | 0 | { |
2760 | | /* Do bulk deletion */ |
2761 | 0 | istat = index_bulk_delete(ivinfo, istat, vac_tid_reaped, |
2762 | 0 | dead_items); |
2763 | |
|
2764 | 0 | ereport(ivinfo->message_level, |
2765 | 0 | (errmsg("scanned index \"%s\" to remove %" PRId64 " row versions", |
2766 | 0 | RelationGetRelationName(ivinfo->index), |
2767 | 0 | dead_items_info->num_items))); |
2768 | | |
2769 | 0 | return istat; |
2770 | 0 | } |
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 | | vac_cleanup_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat) |
2779 | 0 | { |
2780 | 0 | istat = index_vacuum_cleanup(ivinfo, istat); |
2781 | |
|
2782 | 0 | if (istat) |
2783 | 0 | ereport(ivinfo->message_level, |
2784 | 0 | (errmsg("index \"%s\" now contains %.0f row versions in %u pages", |
2785 | 0 | RelationGetRelationName(ivinfo->index), |
2786 | 0 | istat->num_index_tuples, |
2787 | 0 | istat->num_pages), |
2788 | 0 | errdetail("%.0f index row versions were removed.\n" |
2789 | 0 | "%u index pages were newly deleted.\n" |
2790 | 0 | "%u index pages are currently deleted, of which %u are currently reusable.", |
2791 | 0 | istat->tuples_removed, |
2792 | 0 | istat->pages_newly_deleted, |
2793 | 0 | istat->pages_deleted, istat->pages_free))); |
2794 | | |
2795 | 0 | return istat; |
2796 | 0 | } |
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 | | vac_tid_reaped(ItemPointer itemptr, void *state) |
2805 | 0 | { |
2806 | 0 | TidStore *dead_items = (TidStore *) state; |
2807 | |
|
2808 | 0 | return TidStoreIsMember(dead_items, itemptr); |
2809 | 0 | } |