PostgreSQL Source Code  git master
vacuum.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/clog.h"
#include "access/commit_ts.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/multixact.h"
#include "access/tableam.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/index.h"
#include "catalog/pg_database.h"
#include "catalog/pg_inherits.h"
#include "commands/cluster.h"
#include "commands/defrem.h"
#include "commands/vacuum.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/bgworker_internals.h"
#include "postmaster/interrupt.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/guc_hooks.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for vacuum.c:

Go to the source code of this file.

Functions

static Listexpand_vacuum_rel (VacuumRelation *vrel, MemoryContext vac_context, int options)
 
static Listget_all_vacuum_rels (MemoryContext vac_context, int options)
 
static void vac_truncate_clog (TransactionId frozenXID, MultiXactId minMulti, TransactionId lastSaneFrozenXid, MultiXactId lastSaneMinMulti)
 
static bool vacuum_rel (Oid relid, RangeVar *relation, VacuumParams *params, BufferAccessStrategy bstrategy)
 
static double compute_parallel_delay (void)
 
static VacOptValue get_vacoptval_from_boolean (DefElem *def)
 
static bool vac_tid_reaped (ItemPointer itemptr, void *state)
 
static int vac_cmp_itemptr (const void *left, const void *right)
 
bool check_vacuum_buffer_usage_limit (int *newval, void **extra, GucSource source)
 
void ExecVacuum (ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)
 
void vacuum (List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, MemoryContext vac_context, bool isTopLevel)
 
bool vacuum_is_relation_owner (Oid relid, Form_pg_class reltuple, bits32 options)
 
Relation vacuum_open_relation (Oid relid, RangeVar *relation, bits32 options, bool verbose, LOCKMODE lmode)
 
bool vacuum_get_cutoffs (Relation rel, const VacuumParams *params, struct VacuumCutoffs *cutoffs)
 
bool vacuum_xid_failsafe_check (const struct VacuumCutoffs *cutoffs)
 
double vac_estimate_reltuples (Relation relation, BlockNumber total_pages, BlockNumber scanned_pages, double scanned_tuples)
 
void vac_update_relstats (Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool *frozenxid_updated, bool *minmulti_updated, bool in_outer_xact)
 
void vac_update_datfrozenxid (void)
 
void vac_open_indexes (Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
 
void vac_close_indexes (int nindexes, Relation *Irel, LOCKMODE lockmode)
 
void vacuum_delay_point (void)
 
IndexBulkDeleteResultvac_bulkdel_one_index (IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat, VacDeadItems *dead_items)
 
IndexBulkDeleteResultvac_cleanup_one_index (IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat)
 
Size vac_max_items_to_alloc_size (int max_items)
 

Variables

int vacuum_freeze_min_age
 
int vacuum_freeze_table_age
 
int vacuum_multixact_freeze_min_age
 
int vacuum_multixact_freeze_table_age
 
int vacuum_failsafe_age
 
int vacuum_multixact_failsafe_age
 
double vacuum_cost_delay = 0
 
int vacuum_cost_limit = 200
 
bool VacuumFailsafeActive = false
 
pg_atomic_uint32VacuumSharedCostBalance = NULL
 
pg_atomic_uint32VacuumActiveNWorkers = NULL
 
int VacuumCostBalanceLocal = 0
 

Function Documentation

◆ check_vacuum_buffer_usage_limit()

bool check_vacuum_buffer_usage_limit ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 126 of file vacuum.c.

128 {
129  /* Value upper and lower hard limits are inclusive */
130  if (*newval == 0 || (*newval >= MIN_BAS_VAC_RING_SIZE_KB &&
132  return true;
133 
134  /* Value does not fall within any allowable range */
135  GUC_check_errdetail("vacuum_buffer_usage_limit must be 0 or between %d kB and %d kB",
137 
138  return false;
139 }
#define newval
#define GUC_check_errdetail
Definition: guc.h:446
#define MIN_BAS_VAC_RING_SIZE_KB
Definition: miscadmin.h:276
#define MAX_BAS_VAC_RING_SIZE_KB
Definition: miscadmin.h:277

References GUC_check_errdetail, MAX_BAS_VAC_RING_SIZE_KB, MIN_BAS_VAC_RING_SIZE_KB, and newval.

◆ compute_parallel_delay()

static double compute_parallel_delay ( void  )
static

Definition at line 2419 of file vacuum.c.

2420 {
2421  double msec = 0;
2422  uint32 shared_balance;
2423  int nworkers;
2424 
2425  /* Parallel vacuum must be active */
2427 
2429 
2430  /* At least count itself */
2431  Assert(nworkers >= 1);
2432 
2433  /* Update the shared cost balance value atomically */
2435 
2436  /* Compute the total local balance for the current worker */
2438 
2439  if ((shared_balance >= vacuum_cost_limit) &&
2440  (VacuumCostBalanceLocal > 0.5 * ((double) vacuum_cost_limit / nworkers)))
2441  {
2442  /* Compute sleep time based on the local cost balance */
2446  }
2447 
2448  /*
2449  * Reset the local balance as we accumulated it into the shared value.
2450  */
2451  VacuumCostBalance = 0;
2452 
2453  return msec;
2454 }
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:434
static uint32 pg_atomic_add_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:419
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:234
unsigned int uint32
Definition: c.h:493
int VacuumCostBalance
Definition: globals.c:157
Assert(fmt[strlen(fmt) - 1] !='\n')
pg_atomic_uint32 * VacuumActiveNWorkers
Definition: vacuum.c:103
double vacuum_cost_delay
Definition: vacuum.c:80
int VacuumCostBalanceLocal
Definition: vacuum.c:104
pg_atomic_uint32 * VacuumSharedCostBalance
Definition: vacuum.c:102
int vacuum_cost_limit
Definition: vacuum.c:81

References Assert(), pg_atomic_add_fetch_u32(), pg_atomic_read_u32(), pg_atomic_sub_fetch_u32(), vacuum_cost_delay, vacuum_cost_limit, VacuumActiveNWorkers, VacuumCostBalance, VacuumCostBalanceLocal, and VacuumSharedCostBalance.

Referenced by vacuum_delay_point().

◆ ExecVacuum()

void ExecVacuum ( ParseState pstate,
VacuumStmt vacstmt,
bool  isTopLevel 
)

Definition at line 148 of file vacuum.c.

149 {
150  VacuumParams params;
151  BufferAccessStrategy bstrategy = NULL;
152  bool verbose = false;
153  bool skip_locked = false;
154  bool analyze = false;
155  bool freeze = false;
156  bool full = false;
157  bool disable_page_skipping = false;
158  bool process_main = true;
159  bool process_toast = true;
160  int ring_size;
161  bool skip_database_stats = false;
162  bool only_database_stats = false;
163  MemoryContext vac_context;
164  ListCell *lc;
165 
166  /* index_cleanup and truncate values unspecified for now */
169 
170  /* By default parallel vacuum is enabled */
171  params.nworkers = 0;
172 
173  /*
174  * Set this to an invalid value so it is clear whether or not a
175  * BUFFER_USAGE_LIMIT was specified when making the access strategy.
176  */
177  ring_size = -1;
178 
179  /* Parse options list */
180  foreach(lc, vacstmt->options)
181  {
182  DefElem *opt = (DefElem *) lfirst(lc);
183 
184  /* Parse common options for VACUUM and ANALYZE */
185  if (strcmp(opt->defname, "verbose") == 0)
186  verbose = defGetBoolean(opt);
187  else if (strcmp(opt->defname, "skip_locked") == 0)
188  skip_locked = defGetBoolean(opt);
189  else if (strcmp(opt->defname, "buffer_usage_limit") == 0)
190  {
191  const char *hintmsg;
192  int result;
193  char *vac_buffer_size;
194 
195  vac_buffer_size = defGetString(opt);
196 
197  /*
198  * Check that the specified value is valid and the size falls
199  * within the hard upper and lower limits if it is not 0.
200  */
201  if (!parse_int(vac_buffer_size, &result, GUC_UNIT_KB, &hintmsg) ||
202  (result != 0 &&
203  (result < MIN_BAS_VAC_RING_SIZE_KB || result > MAX_BAS_VAC_RING_SIZE_KB)))
204  {
205  ereport(ERROR,
206  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
207  errmsg("BUFFER_USAGE_LIMIT option must be 0 or between %d kB and %d kB",
209  hintmsg ? errhint("%s", _(hintmsg)) : 0));
210  }
211 
212  ring_size = result;
213  }
214  else if (!vacstmt->is_vacuumcmd)
215  ereport(ERROR,
216  (errcode(ERRCODE_SYNTAX_ERROR),
217  errmsg("unrecognized ANALYZE option \"%s\"", opt->defname),
218  parser_errposition(pstate, opt->location)));
219 
220  /* Parse options available on VACUUM */
221  else if (strcmp(opt->defname, "analyze") == 0)
222  analyze = defGetBoolean(opt);
223  else if (strcmp(opt->defname, "freeze") == 0)
224  freeze = defGetBoolean(opt);
225  else if (strcmp(opt->defname, "full") == 0)
226  full = defGetBoolean(opt);
227  else if (strcmp(opt->defname, "disable_page_skipping") == 0)
228  disable_page_skipping = defGetBoolean(opt);
229  else if (strcmp(opt->defname, "index_cleanup") == 0)
230  {
231  /* Interpret no string as the default, which is 'auto' */
232  if (!opt->arg)
234  else
235  {
236  char *sval = defGetString(opt);
237 
238  /* Try matching on 'auto' string, or fall back on boolean */
239  if (pg_strcasecmp(sval, "auto") == 0)
241  else
243  }
244  }
245  else if (strcmp(opt->defname, "process_main") == 0)
246  process_main = defGetBoolean(opt);
247  else if (strcmp(opt->defname, "process_toast") == 0)
248  process_toast = defGetBoolean(opt);
249  else if (strcmp(opt->defname, "truncate") == 0)
250  params.truncate = get_vacoptval_from_boolean(opt);
251  else if (strcmp(opt->defname, "parallel") == 0)
252  {
253  if (opt->arg == NULL)
254  {
255  ereport(ERROR,
256  (errcode(ERRCODE_SYNTAX_ERROR),
257  errmsg("parallel option requires a value between 0 and %d",
259  parser_errposition(pstate, opt->location)));
260  }
261  else
262  {
263  int nworkers;
264 
265  nworkers = defGetInt32(opt);
266  if (nworkers < 0 || nworkers > MAX_PARALLEL_WORKER_LIMIT)
267  ereport(ERROR,
268  (errcode(ERRCODE_SYNTAX_ERROR),
269  errmsg("parallel workers for vacuum must be between 0 and %d",
271  parser_errposition(pstate, opt->location)));
272 
273  /*
274  * Disable parallel vacuum, if user has specified parallel
275  * degree as zero.
276  */
277  if (nworkers == 0)
278  params.nworkers = -1;
279  else
280  params.nworkers = nworkers;
281  }
282  }
283  else if (strcmp(opt->defname, "skip_database_stats") == 0)
284  skip_database_stats = defGetBoolean(opt);
285  else if (strcmp(opt->defname, "only_database_stats") == 0)
286  only_database_stats = defGetBoolean(opt);
287  else
288  ereport(ERROR,
289  (errcode(ERRCODE_SYNTAX_ERROR),
290  errmsg("unrecognized VACUUM option \"%s\"", opt->defname),
291  parser_errposition(pstate, opt->location)));
292  }
293 
294  /* Set vacuum options */
295  params.options =
296  (vacstmt->is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE) |
297  (verbose ? VACOPT_VERBOSE : 0) |
298  (skip_locked ? VACOPT_SKIP_LOCKED : 0) |
299  (analyze ? VACOPT_ANALYZE : 0) |
300  (freeze ? VACOPT_FREEZE : 0) |
301  (full ? VACOPT_FULL : 0) |
302  (disable_page_skipping ? VACOPT_DISABLE_PAGE_SKIPPING : 0) |
303  (process_main ? VACOPT_PROCESS_MAIN : 0) |
304  (process_toast ? VACOPT_PROCESS_TOAST : 0) |
305  (skip_database_stats ? VACOPT_SKIP_DATABASE_STATS : 0) |
306  (only_database_stats ? VACOPT_ONLY_DATABASE_STATS : 0);
307 
308  /* sanity checks on options */
310  Assert((params.options & VACOPT_VACUUM) ||
311  !(params.options & (VACOPT_FULL | VACOPT_FREEZE)));
312 
313  if ((params.options & VACOPT_FULL) && params.nworkers > 0)
314  ereport(ERROR,
315  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
316  errmsg("VACUUM FULL cannot be performed in parallel")));
317 
318  /*
319  * BUFFER_USAGE_LIMIT does nothing for VACUUM (FULL) so just raise an
320  * ERROR for that case. VACUUM (FULL, ANALYZE) does make use of it, so
321  * we'll permit that.
322  */
323  if (ring_size != -1 && (params.options & VACOPT_FULL) &&
324  !(params.options & VACOPT_ANALYZE))
325  ereport(ERROR,
326  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
327  errmsg("BUFFER_USAGE_LIMIT cannot be specified for VACUUM FULL")));
328 
329  /*
330  * Make sure VACOPT_ANALYZE is specified if any column lists are present.
331  */
332  if (!(params.options & VACOPT_ANALYZE))
333  {
334  foreach(lc, vacstmt->rels)
335  {
337 
338  if (vrel->va_cols != NIL)
339  ereport(ERROR,
340  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
341  errmsg("ANALYZE option must be specified when a column list is provided")));
342  }
343  }
344 
345 
346  /*
347  * Sanity check DISABLE_PAGE_SKIPPING option.
348  */
349  if ((params.options & VACOPT_FULL) != 0 &&
350  (params.options & VACOPT_DISABLE_PAGE_SKIPPING) != 0)
351  ereport(ERROR,
352  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
353  errmsg("VACUUM option DISABLE_PAGE_SKIPPING cannot be used with FULL")));
354 
355  /* sanity check for PROCESS_TOAST */
356  if ((params.options & VACOPT_FULL) != 0 &&
357  (params.options & VACOPT_PROCESS_TOAST) == 0)
358  ereport(ERROR,
359  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
360  errmsg("PROCESS_TOAST required with VACUUM FULL")));
361 
362  /* sanity check for ONLY_DATABASE_STATS */
363  if (params.options & VACOPT_ONLY_DATABASE_STATS)
364  {
365  Assert(params.options & VACOPT_VACUUM);
366  if (vacstmt->rels != NIL)
367  ereport(ERROR,
368  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
369  errmsg("ONLY_DATABASE_STATS cannot be specified with a list of tables")));
370  /* don't require people to turn off PROCESS_TOAST/MAIN explicitly */
371  if (params.options & ~(VACOPT_VACUUM |
376  ereport(ERROR,
377  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
378  errmsg("ONLY_DATABASE_STATS cannot be specified with other VACUUM options")));
379  }
380 
381  /*
382  * All freeze ages are zero if the FREEZE option is given; otherwise pass
383  * them as -1 which means to use the default values.
384  */
385  if (params.options & VACOPT_FREEZE)
386  {
387  params.freeze_min_age = 0;
388  params.freeze_table_age = 0;
389  params.multixact_freeze_min_age = 0;
390  params.multixact_freeze_table_age = 0;
391  }
392  else
393  {
394  params.freeze_min_age = -1;
395  params.freeze_table_age = -1;
396  params.multixact_freeze_min_age = -1;
397  params.multixact_freeze_table_age = -1;
398  }
399 
400  /* user-invoked vacuum is never "for wraparound" */
401  params.is_wraparound = false;
402 
403  /* user-invoked vacuum uses VACOPT_VERBOSE instead of log_min_duration */
404  params.log_min_duration = -1;
405 
406  /*
407  * Create special memory context for cross-transaction storage.
408  *
409  * Since it is a child of PortalContext, it will go away eventually even
410  * if we suffer an error; there's no need for special abort cleanup logic.
411  */
412  vac_context = AllocSetContextCreate(PortalContext,
413  "Vacuum",
415 
416  /*
417  * Make a buffer strategy object in the cross-transaction memory context.
418  * We needn't bother making this for VACUUM (FULL) or VACUUM
419  * (ONLY_DATABASE_STATS) as they'll not make use of it. VACUUM (FULL,
420  * ANALYZE) is possible, so we'd better ensure that we make a strategy
421  * when we see ANALYZE.
422  */
423  if ((params.options & (VACOPT_ONLY_DATABASE_STATS |
424  VACOPT_FULL)) == 0 ||
425  (params.options & VACOPT_ANALYZE) != 0)
426  {
427 
428  MemoryContext old_context = MemoryContextSwitchTo(vac_context);
429 
430  Assert(ring_size >= -1);
431 
432  /*
433  * If BUFFER_USAGE_LIMIT was specified by the VACUUM or ANALYZE
434  * command, it overrides the value of VacuumBufferUsageLimit. Either
435  * value may be 0, in which case GetAccessStrategyWithSize() will
436  * return NULL, effectively allowing full use of shared buffers.
437  */
438  if (ring_size == -1)
439  ring_size = VacuumBufferUsageLimit;
440 
441  bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, ring_size);
442 
443  MemoryContextSwitchTo(old_context);
444  }
445 
446  /* Now go through the common routine */
447  vacuum(vacstmt->rels, &params, bstrategy, vac_context, isTopLevel);
448 
449  /* Finally, clean up the vacuum memory context */
450  MemoryContextDelete(vac_context);
451 }
#define MAX_PARALLEL_WORKER_LIMIT
@ BAS_VACUUM
Definition: bufmgr.h:38
int32 defGetInt32(DefElem *def)
Definition: define.c:162
bool defGetBoolean(DefElem *def)
Definition: define.c:107
char * defGetString(DefElem *def)
Definition: define.c:48
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define _(x)
Definition: elog.c:90
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
BufferAccessStrategy GetAccessStrategyWithSize(BufferAccessStrategyType btype, int ring_size_kb)
Definition: freelist.c:584
int VacuumBufferUsageLimit
Definition: globals.c:145
bool parse_int(const char *value, int *result, int flags, const char **hintmsg)
Definition: guc.c:2855
#define GUC_UNIT_KB
Definition: guc.h:227
int verbose
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:399
MemoryContext PortalContext
Definition: mcxt.c:146
#define AllocSetContextCreate
Definition: memutils.h:128
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:152
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
#define lfirst(lc)
Definition: pg_list.h:172
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
static long analyze(struct nfa *nfa)
Definition: regc_nfa.c:3016
char * defname
Definition: parsenodes.h:810
int location
Definition: parsenodes.h:814
Node * arg
Definition: parsenodes.h:811
int nworkers
Definition: vacuum.h:237
int freeze_table_age
Definition: vacuum.h:220
VacOptValue truncate
Definition: vacuum.h:230
bits32 options
Definition: vacuum.h:218
int freeze_min_age
Definition: vacuum.h:219
bool is_wraparound
Definition: vacuum.h:225
int multixact_freeze_min_age
Definition: vacuum.h:221
int multixact_freeze_table_age
Definition: vacuum.h:223
int log_min_duration
Definition: vacuum.h:226
VacOptValue index_cleanup
Definition: vacuum.h:229
List * options
Definition: parsenodes.h:3689
bool is_vacuumcmd
Definition: parsenodes.h:3691
List * rels
Definition: parsenodes.h:3690
static VacOptValue get_vacoptval_from_boolean(DefElem *def)
Definition: vacuum.c:2463
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, MemoryContext vac_context, bool isTopLevel)
Definition: vacuum.c:476
#define VACOPT_FREEZE
Definition: vacuum.h:182
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:184
#define VACOPT_VACUUM
Definition: vacuum.h:179
#define VACOPT_VERBOSE
Definition: vacuum.h:181
#define VACOPT_FULL
Definition: vacuum.h:183
#define VACOPT_SKIP_DATABASE_STATS
Definition: vacuum.h:188
@ VACOPTVALUE_AUTO
Definition: vacuum.h:202
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:201
#define VACOPT_PROCESS_TOAST
Definition: vacuum.h:186
#define VACOPT_DISABLE_PAGE_SKIPPING
Definition: vacuum.h:187
#define VACOPT_ONLY_DATABASE_STATS
Definition: vacuum.h:189
#define VACOPT_PROCESS_MAIN
Definition: vacuum.h:185
#define VACOPT_ANALYZE
Definition: vacuum.h:180

References _, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, analyze(), DefElem::arg, Assert(), BAS_VACUUM, defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, ereport, errcode(), errhint(), errmsg(), ERROR, VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, get_vacoptval_from_boolean(), GetAccessStrategyWithSize(), GUC_UNIT_KB, VacuumParams::index_cleanup, VacuumStmt::is_vacuumcmd, VacuumParams::is_wraparound, lfirst, lfirst_node, DefElem::location, VacuumParams::log_min_duration, MAX_BAS_VAC_RING_SIZE_KB, MAX_PARALLEL_WORKER_LIMIT, MemoryContextDelete(), MemoryContextSwitchTo(), MIN_BAS_VAC_RING_SIZE_KB, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, NIL, VacuumParams::nworkers, VacuumParams::options, VacuumStmt::options, parse_int(), parser_errposition(), pg_strcasecmp(), PortalContext, VacuumStmt::rels, VacuumParams::truncate, VacuumRelation::va_cols, VACOPT_ANALYZE, VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_FREEZE, VACOPT_FULL, VACOPT_ONLY_DATABASE_STATS, VACOPT_PROCESS_MAIN, VACOPT_PROCESS_TOAST, VACOPT_SKIP_DATABASE_STATS, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, VACOPT_VERBOSE, VACOPTVALUE_AUTO, VACOPTVALUE_UNSPECIFIED, vacuum(), VacuumBufferUsageLimit, and verbose.

Referenced by standard_ProcessUtility().

◆ expand_vacuum_rel()

static List * expand_vacuum_rel ( VacuumRelation vrel,
MemoryContext  vac_context,
int  options 
)
static

Definition at line 871 of file vacuum.c.

873 {
874  List *vacrels = NIL;
875  MemoryContext oldcontext;
876 
877  /* If caller supplied OID, there's nothing we need do here. */
878  if (OidIsValid(vrel->oid))
879  {
880  oldcontext = MemoryContextSwitchTo(vac_context);
881  vacrels = lappend(vacrels, vrel);
882  MemoryContextSwitchTo(oldcontext);
883  }
884  else
885  {
886  /* Process a specific relation, and possibly partitions thereof */
887  Oid relid;
888  HeapTuple tuple;
889  Form_pg_class classForm;
890  bool include_parts;
891  int rvr_opts;
892 
893  /*
894  * Since autovacuum workers supply OIDs when calling vacuum(), no
895  * autovacuum worker should reach this code.
896  */
898 
899  /*
900  * We transiently take AccessShareLock to protect the syscache lookup
901  * below, as well as find_all_inheritors's expectation that the caller
902  * holds some lock on the starting relation.
903  */
904  rvr_opts = (options & VACOPT_SKIP_LOCKED) ? RVR_SKIP_LOCKED : 0;
905  relid = RangeVarGetRelidExtended(vrel->relation,
907  rvr_opts,
908  NULL, NULL);
909 
910  /*
911  * If the lock is unavailable, emit the same log statement that
912  * vacuum_rel() and analyze_rel() would.
913  */
914  if (!OidIsValid(relid))
915  {
916  if (options & VACOPT_VACUUM)
918  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
919  errmsg("skipping vacuum of \"%s\" --- lock not available",
920  vrel->relation->relname)));
921  else
923  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
924  errmsg("skipping analyze of \"%s\" --- lock not available",
925  vrel->relation->relname)));
926  return vacrels;
927  }
928 
929  /*
930  * To check whether the relation is a partitioned table and its
931  * ownership, fetch its syscache entry.
932  */
933  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
934  if (!HeapTupleIsValid(tuple))
935  elog(ERROR, "cache lookup failed for relation %u", relid);
936  classForm = (Form_pg_class) GETSTRUCT(tuple);
937 
938  /*
939  * Make a returnable VacuumRelation for this rel if user is a proper
940  * owner.
941  */
942  if (vacuum_is_relation_owner(relid, classForm, options))
943  {
944  oldcontext = MemoryContextSwitchTo(vac_context);
945  vacrels = lappend(vacrels, makeVacuumRelation(vrel->relation,
946  relid,
947  vrel->va_cols));
948  MemoryContextSwitchTo(oldcontext);
949  }
950 
951 
952  include_parts = (classForm->relkind == RELKIND_PARTITIONED_TABLE);
953  ReleaseSysCache(tuple);
954 
955  /*
956  * If it is, make relation list entries for its partitions. Note that
957  * the list returned by find_all_inheritors() includes the passed-in
958  * OID, so we have to skip that. There's no point in taking locks on
959  * the individual partitions yet, and doing so would just add
960  * unnecessary deadlock risk. For this last reason we do not check
961  * yet the ownership of the partitions, which get added to the list to
962  * process. Ownership will be checked later on anyway.
963  */
964  if (include_parts)
965  {
966  List *part_oids = find_all_inheritors(relid, NoLock, NULL);
967  ListCell *part_lc;
968 
969  foreach(part_lc, part_oids)
970  {
971  Oid part_oid = lfirst_oid(part_lc);
972 
973  if (part_oid == relid)
974  continue; /* ignore original table */
975 
976  /*
977  * We omit a RangeVar since it wouldn't be appropriate to
978  * complain about failure to open one of these relations
979  * later.
980  */
981  oldcontext = MemoryContextSwitchTo(vac_context);
982  vacrels = lappend(vacrels, makeVacuumRelation(NULL,
983  part_oid,
984  vrel->va_cols));
985  MemoryContextSwitchTo(oldcontext);
986  }
987  }
988 
989  /*
990  * Release lock again. This means that by the time we actually try to
991  * process the table, it might be gone or renamed. In the former case
992  * we'll silently ignore it; in the latter case we'll process it
993  * anyway, but we must beware that the RangeVar doesn't necessarily
994  * identify it anymore. This isn't ideal, perhaps, but there's little
995  * practical alternative, since we're typically going to commit this
996  * transaction and begin a new one between now and then. Moreover,
997  * holding locks on multiple relations would create significant risk
998  * of deadlock.
999  */
1001  }
1002 
1003  return vacrels;
1004 }
#define OidIsValid(objectId)
Definition: c.h:762
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:224
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
List * lappend(List *list, void *datum)
Definition: list.c:339
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:227
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:816
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:372
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:426
@ RVR_SKIP_LOCKED
Definition: namespace.h:74
FormData_pg_class * Form_pg_class
Definition: pg_class.h:153
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
Definition: pg_inherits.c:255
#define lfirst_oid(lc)
Definition: pg_list.h:174
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
unsigned int Oid
Definition: postgres_ext.h:31
Definition: pg_list.h:54
char * relname
Definition: primnodes.h:82
RangeVar * relation
Definition: parsenodes.h:3704
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
bool vacuum_is_relation_owner(Oid relid, Form_pg_class reltuple, bits32 options)
Definition: vacuum.c:705

References AccessShareLock, AmAutoVacuumWorkerProcess, Assert(), elog, ereport, errcode(), errmsg(), ERROR, find_all_inheritors(), GETSTRUCT, HeapTupleIsValid, lappend(), lfirst_oid, makeVacuumRelation(), MemoryContextSwitchTo(), NIL, NoLock, ObjectIdGetDatum(), VacuumRelation::oid, OidIsValid, RangeVarGetRelidExtended(), VacuumRelation::relation, ReleaseSysCache(), RangeVar::relname, RVR_SKIP_LOCKED, SearchSysCache1(), UnlockRelationOid(), VacuumRelation::va_cols, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, vacuum_is_relation_owner(), and WARNING.

Referenced by vacuum().

◆ get_all_vacuum_rels()

static List * get_all_vacuum_rels ( MemoryContext  vac_context,
int  options 
)
static

Definition at line 1011 of file vacuum.c.

1012 {
1013  List *vacrels = NIL;
1014  Relation pgclass;
1015  TableScanDesc scan;
1016  HeapTuple tuple;
1017 
1018  pgclass = table_open(RelationRelationId, AccessShareLock);
1019 
1020  scan = table_beginscan_catalog(pgclass, 0, NULL);
1021 
1022  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1023  {
1024  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
1025  MemoryContext oldcontext;
1026  Oid relid = classForm->oid;
1027 
1028  /*
1029  * We include partitioned tables here; depending on which operation is
1030  * to be performed, caller will decide whether to process or ignore
1031  * them.
1032  */
1033  if (classForm->relkind != RELKIND_RELATION &&
1034  classForm->relkind != RELKIND_MATVIEW &&
1035  classForm->relkind != RELKIND_PARTITIONED_TABLE)
1036  continue;
1037 
1038  /* check permissions of relation */
1039  if (!vacuum_is_relation_owner(relid, classForm, options))
1040  continue;
1041 
1042  /*
1043  * Build VacuumRelation(s) specifying the table OIDs to be processed.
1044  * We omit a RangeVar since it wouldn't be appropriate to complain
1045  * about failure to open one of these relations later.
1046  */
1047  oldcontext = MemoryContextSwitchTo(vac_context);
1048  vacrels = lappend(vacrels, makeVacuumRelation(NULL,
1049  relid,
1050  NIL));
1051  MemoryContextSwitchTo(oldcontext);
1052  }
1053 
1054  table_endscan(scan);
1055  table_close(pgclass, AccessShareLock);
1056 
1057  return vacrels;
1058 }
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1082
@ ForwardScanDirection
Definition: sdir.h:28
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:1009

References AccessShareLock, ForwardScanDirection, GETSTRUCT, heap_getnext(), lappend(), makeVacuumRelation(), MemoryContextSwitchTo(), NIL, table_beginscan_catalog(), table_close(), table_endscan(), table_open(), and vacuum_is_relation_owner().

Referenced by vacuum().

◆ get_vacoptval_from_boolean()

static VacOptValue get_vacoptval_from_boolean ( DefElem def)
static

Definition at line 2463 of file vacuum.c.

2464 {
2466 }
@ VACOPTVALUE_ENABLED
Definition: vacuum.h:204
@ VACOPTVALUE_DISABLED
Definition: vacuum.h:203

References defGetBoolean(), VACOPTVALUE_DISABLED, and VACOPTVALUE_ENABLED.

Referenced by ExecVacuum().

◆ vac_bulkdel_one_index()

IndexBulkDeleteResult* vac_bulkdel_one_index ( IndexVacuumInfo ivinfo,
IndexBulkDeleteResult istat,
VacDeadItems dead_items 
)

Definition at line 2474 of file vacuum.c.

2476 {
2477  /* Do bulk deletion */
2478  istat = index_bulk_delete(ivinfo, istat, vac_tid_reaped,
2479  (void *) dead_items);
2480 
2481  ereport(ivinfo->message_level,
2482  (errmsg("scanned index \"%s\" to remove %d row versions",
2483  RelationGetRelationName(ivinfo->index),
2484  dead_items->num_items)));
2485 
2486  return istat;
2487 }
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *istat, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:751
#define RelationGetRelationName(relation)
Definition: rel.h:538
Relation index
Definition: genam.h:46
int message_level
Definition: genam.h:51
int num_items
Definition: vacuum.h:285
static bool vac_tid_reaped(ItemPointer itemptr, void *state)
Definition: vacuum.c:2535

References ereport, errmsg(), IndexVacuumInfo::index, index_bulk_delete(), IndexVacuumInfo::message_level, VacDeadItems::num_items, RelationGetRelationName, and vac_tid_reaped().

Referenced by lazy_vacuum_one_index(), and parallel_vacuum_process_one_index().

◆ vac_cleanup_one_index()

IndexBulkDeleteResult* vac_cleanup_one_index ( IndexVacuumInfo ivinfo,
IndexBulkDeleteResult istat 
)

Definition at line 2495 of file vacuum.c.

2496 {
2497  istat = index_vacuum_cleanup(ivinfo, istat);
2498 
2499  if (istat)
2500  ereport(ivinfo->message_level,
2501  (errmsg("index \"%s\" now contains %.0f row versions in %u pages",
2502  RelationGetRelationName(ivinfo->index),
2503  istat->num_index_tuples,
2504  istat->num_pages),
2505  errdetail("%.0f index row versions were removed.\n"
2506  "%u index pages were newly deleted.\n"
2507  "%u index pages are currently deleted, of which %u are currently reusable.",
2508  istat->tuples_removed,
2509  istat->pages_newly_deleted,
2510  istat->pages_deleted, istat->pages_free)));
2511 
2512  return istat;
2513 }
int errdetail(const char *fmt,...)
Definition: elog.c:1205
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *istat)
Definition: indexam.c:772
BlockNumber pages_deleted
Definition: genam.h:82
BlockNumber pages_newly_deleted
Definition: genam.h:81
BlockNumber pages_free
Definition: genam.h:83
BlockNumber num_pages
Definition: genam.h:77
double tuples_removed
Definition: genam.h:80
double num_index_tuples
Definition: genam.h:79

References ereport, errdetail(), errmsg(), IndexVacuumInfo::index, index_vacuum_cleanup(), IndexVacuumInfo::message_level, IndexBulkDeleteResult::num_index_tuples, IndexBulkDeleteResult::num_pages, IndexBulkDeleteResult::pages_deleted, IndexBulkDeleteResult::pages_free, IndexBulkDeleteResult::pages_newly_deleted, RelationGetRelationName, and IndexBulkDeleteResult::tuples_removed.

Referenced by lazy_cleanup_one_index(), and parallel_vacuum_process_one_index().

◆ vac_close_indexes()

void vac_close_indexes ( int  nindexes,
Relation Irel,
LOCKMODE  lockmode 
)

Definition at line 2299 of file vacuum.c.

2300 {
2301  if (Irel == NULL)
2302  return;
2303 
2304  while (nindexes--)
2305  {
2306  Relation ind = Irel[nindexes];
2307 
2308  index_close(ind, lockmode);
2309  }
2310  pfree(Irel);
2311 }
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:177
void pfree(void *pointer)
Definition: mcxt.c:1401

References index_close(), and pfree().

Referenced by do_analyze_rel(), heap_vacuum_rel(), and parallel_vacuum_main().

◆ vac_cmp_itemptr()

static int vac_cmp_itemptr ( const void *  left,
const void *  right 
)
static

Definition at line 2569 of file vacuum.c.

2570 {
2571  BlockNumber lblk,
2572  rblk;
2573  OffsetNumber loff,
2574  roff;
2575 
2576  lblk = ItemPointerGetBlockNumber((ItemPointer) left);
2577  rblk = ItemPointerGetBlockNumber((ItemPointer) right);
2578 
2579  if (lblk < rblk)
2580  return -1;
2581  if (lblk > rblk)
2582  return 1;
2583 
2584  loff = ItemPointerGetOffsetNumber((ItemPointer) left);
2585  roff = ItemPointerGetOffsetNumber((ItemPointer) right);
2586 
2587  if (loff < roff)
2588  return -1;
2589  if (loff > roff)
2590  return 1;
2591 
2592  return 0;
2593 }
uint32 BlockNumber
Definition: block.h:31
static OffsetNumber ItemPointerGetOffsetNumber(const ItemPointerData *pointer)
Definition: itemptr.h:124
static BlockNumber ItemPointerGetBlockNumber(const ItemPointerData *pointer)
Definition: itemptr.h:103
uint16 OffsetNumber
Definition: off.h:24

References ItemPointerGetBlockNumber(), and ItemPointerGetOffsetNumber().

Referenced by vac_tid_reaped().

◆ vac_estimate_reltuples()

double vac_estimate_reltuples ( Relation  relation,
BlockNumber  total_pages,
BlockNumber  scanned_pages,
double  scanned_tuples 
)

Definition at line 1303 of file vacuum.c.

1307 {
1308  BlockNumber old_rel_pages = relation->rd_rel->relpages;
1309  double old_rel_tuples = relation->rd_rel->reltuples;
1310  double old_density;
1311  double unscanned_pages;
1312  double total_tuples;
1313 
1314  /* If we did scan the whole table, just use the count as-is */
1315  if (scanned_pages >= total_pages)
1316  return scanned_tuples;
1317 
1318  /*
1319  * When successive VACUUM commands scan the same few pages again and
1320  * again, without anything from the table really changing, there is a risk
1321  * that our beliefs about tuple density will gradually become distorted.
1322  * This might be caused by vacuumlazy.c implementation details, such as
1323  * its tendency to always scan the last heap page. Handle that here.
1324  *
1325  * If the relation is _exactly_ the same size according to the existing
1326  * pg_class entry, and only a few of its pages (less than 2%) were
1327  * scanned, keep the existing value of reltuples. Also keep the existing
1328  * value when only a subset of rel's pages <= a single page were scanned.
1329  *
1330  * (Note: we might be returning -1 here.)
1331  */
1332  if (old_rel_pages == total_pages &&
1333  scanned_pages < (double) total_pages * 0.02)
1334  return old_rel_tuples;
1335  if (scanned_pages <= 1)
1336  return old_rel_tuples;
1337 
1338  /*
1339  * If old density is unknown, we can't do much except scale up
1340  * scanned_tuples to match total_pages.
1341  */
1342  if (old_rel_tuples < 0 || old_rel_pages == 0)
1343  return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
1344 
1345  /*
1346  * Okay, we've covered the corner cases. The normal calculation is to
1347  * convert the old measurement to a density (tuples per page), then
1348  * estimate the number of tuples in the unscanned pages using that figure,
1349  * and finally add on the number of tuples in the scanned pages.
1350  */
1351  old_density = old_rel_tuples / old_rel_pages;
1352  unscanned_pages = (double) total_pages - (double) scanned_pages;
1353  total_tuples = old_density * unscanned_pages + scanned_tuples;
1354  return floor(total_tuples + 0.5);
1355 }
Form_pg_class rd_rel
Definition: rel.h:111

References RelationData::rd_rel.

Referenced by lazy_scan_heap(), and statapprox_heap().

◆ vac_max_items_to_alloc_size()

Size vac_max_items_to_alloc_size ( int  max_items)

Definition at line 2520 of file vacuum.c.

2521 {
2522  Assert(max_items <= MAXDEADITEMS(MaxAllocSize));
2523 
2524  return offsetof(VacDeadItems, items) + sizeof(ItemPointerData) * max_items;
2525 }
struct ItemPointerData ItemPointerData
#define MaxAllocSize
Definition: memutils.h:40
#define MAXDEADITEMS(avail_mem)
Definition: vacuum.h:291

References Assert(), MaxAllocSize, and MAXDEADITEMS.

Referenced by dead_items_alloc(), and parallel_vacuum_init().

◆ vac_open_indexes()

void vac_open_indexes ( Relation  relation,
LOCKMODE  lockmode,
int *  nindexes,
Relation **  Irel 
)

Definition at line 2256 of file vacuum.c.

2258 {
2259  List *indexoidlist;
2260  ListCell *indexoidscan;
2261  int i;
2262 
2263  Assert(lockmode != NoLock);
2264 
2265  indexoidlist = RelationGetIndexList(relation);
2266 
2267  /* allocate enough memory for all indexes */
2268  i = list_length(indexoidlist);
2269 
2270  if (i > 0)
2271  *Irel = (Relation *) palloc(i * sizeof(Relation));
2272  else
2273  *Irel = NULL;
2274 
2275  /* collect just the ready indexes */
2276  i = 0;
2277  foreach(indexoidscan, indexoidlist)
2278  {
2279  Oid indexoid = lfirst_oid(indexoidscan);
2280  Relation indrel;
2281 
2282  indrel = index_open(indexoid, lockmode);
2283  if (indrel->rd_index->indisready)
2284  (*Irel)[i++] = indrel;
2285  else
2286  index_close(indrel, lockmode);
2287  }
2288 
2289  *nindexes = i;
2290 
2291  list_free(indexoidlist);
2292 }
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:133
int i
Definition: isn.c:73
void list_free(List *list)
Definition: list.c:1546
void * palloc(Size size)
Definition: mcxt.c:1197
static int list_length(const List *l)
Definition: pg_list.h:152
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4753
Form_pg_index rd_index
Definition: rel.h:191

References Assert(), i, index_close(), index_open(), lfirst_oid, list_free(), list_length(), NoLock, palloc(), RelationData::rd_index, and RelationGetIndexList().

Referenced by do_analyze_rel(), heap_vacuum_rel(), and parallel_vacuum_main().

◆ vac_tid_reaped()

static bool vac_tid_reaped ( ItemPointer  itemptr,
void *  state 
)
static

Definition at line 2535 of file vacuum.c.

2536 {
2537  VacDeadItems *dead_items = (VacDeadItems *) state;
2538  int64 litem,
2539  ritem,
2540  item;
2541  ItemPointer res;
2542 
2543  litem = itemptr_encode(&dead_items->items[0]);
2544  ritem = itemptr_encode(&dead_items->items[dead_items->num_items - 1]);
2545  item = itemptr_encode(itemptr);
2546 
2547  /*
2548  * Doing a simple bound check before bsearch() is useful to avoid the
2549  * extra cost of bsearch(), especially if dead items on the heap are
2550  * concentrated in a certain range. Since this function is called for
2551  * every index tuple, it pays to be really fast.
2552  */
2553  if (item < litem || item > ritem)
2554  return false;
2555 
2556  res = (ItemPointer) bsearch(itemptr,
2557  dead_items->items,
2558  dead_items->num_items,
2559  sizeof(ItemPointerData),
2560  vac_cmp_itemptr);
2561 
2562  return (res != NULL);
2563 }
static int64 itemptr_encode(ItemPointer itemptr)
Definition: index.h:189
ItemPointerData * ItemPointer
Definition: itemptr.h:49
ItemPointerData items[FLEXIBLE_ARRAY_MEMBER]
Definition: vacuum.h:288
Definition: regguts.h:323
static int vac_cmp_itemptr(const void *left, const void *right)
Definition: vacuum.c:2569

References itemptr_encode(), VacDeadItems::items, VacDeadItems::num_items, res, and vac_cmp_itemptr().

Referenced by vac_bulkdel_one_index().

◆ vac_truncate_clog()

static void vac_truncate_clog ( TransactionId  frozenXID,
MultiXactId  minMulti,
TransactionId  lastSaneFrozenXid,
MultiXactId  lastSaneMinMulti 
)
static

Definition at line 1780 of file vacuum.c.

1784 {
1786  Relation relation;
1787  TableScanDesc scan;
1788  HeapTuple tuple;
1789  Oid oldestxid_datoid;
1790  Oid minmulti_datoid;
1791  bool bogus = false;
1792  bool frozenAlreadyWrapped = false;
1793 
1794  /* Restrict task to one backend per cluster; see SimpleLruTruncate(). */
1795  LWLockAcquire(WrapLimitsVacuumLock, LW_EXCLUSIVE);
1796 
1797  /* init oldest datoids to sync with my frozenXID/minMulti values */
1798  oldestxid_datoid = MyDatabaseId;
1799  minmulti_datoid = MyDatabaseId;
1800 
1801  /*
1802  * Scan pg_database to compute the minimum datfrozenxid/datminmxid
1803  *
1804  * Since vac_update_datfrozenxid updates datfrozenxid/datminmxid in-place,
1805  * the values could change while we look at them. Fetch each one just
1806  * once to ensure sane behavior of the comparison logic. (Here, as in
1807  * many other places, we assume that fetching or updating an XID in shared
1808  * storage is atomic.)
1809  *
1810  * Note: we need not worry about a race condition with new entries being
1811  * inserted by CREATE DATABASE. Any such entry will have a copy of some
1812  * existing DB's datfrozenxid, and that source DB cannot be ours because
1813  * of the interlock against copying a DB containing an active backend.
1814  * Hence the new entry will not reduce the minimum. Also, if two VACUUMs
1815  * concurrently modify the datfrozenxid's of different databases, the
1816  * worst possible outcome is that pg_xact is not truncated as aggressively
1817  * as it could be.
1818  */
1819  relation = table_open(DatabaseRelationId, AccessShareLock);
1820 
1821  scan = table_beginscan_catalog(relation, 0, NULL);
1822 
1823  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1824  {
1825  volatile FormData_pg_database *dbform = (Form_pg_database) GETSTRUCT(tuple);
1826  TransactionId datfrozenxid = dbform->datfrozenxid;
1827  TransactionId datminmxid = dbform->datminmxid;
1828 
1831 
1832  /*
1833  * If database is in the process of getting dropped, or has been
1834  * interrupted while doing so, no connections to it are possible
1835  * anymore. Therefore we don't need to take it into account here.
1836  * Which is good, because it can't be processed by autovacuum either.
1837  */
1839  {
1840  elog(DEBUG2,
1841  "skipping invalid database \"%s\" while computing relfrozenxid",
1842  NameStr(dbform->datname));
1843  continue;
1844  }
1845 
1846  /*
1847  * If things are working properly, no database should have a
1848  * datfrozenxid or datminmxid that is "in the future". However, such
1849  * cases have been known to arise due to bugs in pg_upgrade. If we
1850  * see any entries that are "in the future", chicken out and don't do
1851  * anything. This ensures we won't truncate clog before those
1852  * databases have been scanned and cleaned up. (We will issue the
1853  * "already wrapped" warning if appropriate, though.)
1854  */
1855  if (TransactionIdPrecedes(lastSaneFrozenXid, datfrozenxid) ||
1856  MultiXactIdPrecedes(lastSaneMinMulti, datminmxid))
1857  bogus = true;
1858 
1859  if (TransactionIdPrecedes(nextXID, datfrozenxid))
1860  frozenAlreadyWrapped = true;
1861  else if (TransactionIdPrecedes(datfrozenxid, frozenXID))
1862  {
1863  frozenXID = datfrozenxid;
1864  oldestxid_datoid = dbform->oid;
1865  }
1866 
1867  if (MultiXactIdPrecedes(datminmxid, minMulti))
1868  {
1869  minMulti = datminmxid;
1870  minmulti_datoid = dbform->oid;
1871  }
1872  }
1873 
1874  table_endscan(scan);
1875 
1876  table_close(relation, AccessShareLock);
1877 
1878  /*
1879  * Do not truncate CLOG if we seem to have suffered wraparound already;
1880  * the computed minimum XID might be bogus. This case should now be
1881  * impossible due to the defenses in GetNewTransactionId, but we keep the
1882  * test anyway.
1883  */
1884  if (frozenAlreadyWrapped)
1885  {
1886  ereport(WARNING,
1887  (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
1888  errdetail("You might have already suffered transaction-wraparound data loss.")));
1889  LWLockRelease(WrapLimitsVacuumLock);
1890  return;
1891  }
1892 
1893  /* chicken out if data is bogus in any other way */
1894  if (bogus)
1895  {
1896  LWLockRelease(WrapLimitsVacuumLock);
1897  return;
1898  }
1899 
1900  /*
1901  * Advance the oldest value for commit timestamps before truncating, so
1902  * that if a user requests a timestamp for a transaction we're truncating
1903  * away right after this point, they get NULL instead of an ugly "file not
1904  * found" error from slru.c. This doesn't matter for xact/multixact
1905  * because they are not subject to arbitrary lookups from users.
1906  */
1907  AdvanceOldestCommitTsXid(frozenXID);
1908 
1909  /*
1910  * Truncate CLOG, multixact and CommitTs to the oldest computed value.
1911  */
1912  TruncateCLOG(frozenXID, oldestxid_datoid);
1913  TruncateCommitTs(frozenXID);
1914  TruncateMultiXact(minMulti, minmulti_datoid);
1915 
1916  /*
1917  * Update the wrap limit for GetNewTransactionId and creation of new
1918  * MultiXactIds. Note: these functions will also signal the postmaster
1919  * for an(other) autovac cycle if needed. XXX should we avoid possibly
1920  * signaling twice?
1921  */
1922  SetTransactionIdLimit(frozenXID, oldestxid_datoid);
1923  SetMultiXactIdLimit(minMulti, minmulti_datoid, false);
1924 
1925  LWLockRelease(WrapLimitsVacuumLock);
1926 }
#define NameStr(name)
Definition: c.h:733
uint32 TransactionId
Definition: c.h:639
void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid)
Definition: clog.c:1000
void AdvanceOldestCommitTsXid(TransactionId oldestXact)
Definition: commit_ts.c:936
void TruncateCommitTs(TransactionId oldestXact)
Definition: commit_ts.c:883
bool database_is_invalid_form(Form_pg_database datform)
Definition: dbcommands.c:3112
#define DEBUG2
Definition: elog.h:29
Oid MyDatabaseId
Definition: globals.c:90
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1172
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1785
@ LW_EXCLUSIVE
Definition: lwlock.h:116
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3243
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2296
void TruncateMultiXact(MultiXactId newOldestMulti, Oid newOldestMultiDB)
Definition: multixact.c:3028
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
TransactionId datfrozenxid
Definition: pg_database.h:62
TransactionId datminmxid
Definition: pg_database.h:65
FormData_pg_database * Form_pg_database
Definition: pg_database.h:96
FormData_pg_database
Definition: pg_database.h:89
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
static TransactionId ReadNextTransactionId(void)
Definition: transam.h:315
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
void SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
Definition: varsup.c:372

References AccessShareLock, AdvanceOldestCommitTsXid(), Assert(), database_is_invalid_form(), datfrozenxid, datminmxid, DEBUG2, elog, ereport, errdetail(), errmsg(), FormData_pg_database, ForwardScanDirection, GETSTRUCT, heap_getnext(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MultiXactIdIsValid, MultiXactIdPrecedes(), MyDatabaseId, NameStr, ReadNextTransactionId(), SetMultiXactIdLimit(), SetTransactionIdLimit(), table_beginscan_catalog(), table_close(), table_endscan(), table_open(), TransactionIdIsNormal, TransactionIdPrecedes(), TruncateCLOG(), TruncateCommitTs(), TruncateMultiXact(), and WARNING.

Referenced by vac_update_datfrozenxid().

◆ vac_update_datfrozenxid()

void vac_update_datfrozenxid ( void  )

Definition at line 1566 of file vacuum.c.

1567 {
1568  HeapTuple tuple;
1569  Form_pg_database dbform;
1570  Relation relation;
1571  SysScanDesc scan;
1572  HeapTuple classTup;
1573  TransactionId newFrozenXid;
1574  MultiXactId newMinMulti;
1575  TransactionId lastSaneFrozenXid;
1576  MultiXactId lastSaneMinMulti;
1577  bool bogus = false;
1578  bool dirty = false;
1579  ScanKeyData key[1];
1580 
1581  /*
1582  * Restrict this task to one backend per database. This avoids race
1583  * conditions that would move datfrozenxid or datminmxid backward. It
1584  * avoids calling vac_truncate_clog() with a datfrozenxid preceding a
1585  * datfrozenxid passed to an earlier vac_truncate_clog() call.
1586  */
1588 
1589  /*
1590  * Initialize the "min" calculation with
1591  * GetOldestNonRemovableTransactionId(), which is a reasonable
1592  * approximation to the minimum relfrozenxid for not-yet-committed
1593  * pg_class entries for new tables; see AddNewRelationTuple(). So we
1594  * cannot produce a wrong minimum by starting with this.
1595  */
1596  newFrozenXid = GetOldestNonRemovableTransactionId(NULL);
1597 
1598  /*
1599  * Similarly, initialize the MultiXact "min" with the value that would be
1600  * used on pg_class for new tables. See AddNewRelationTuple().
1601  */
1602  newMinMulti = GetOldestMultiXactId();
1603 
1604  /*
1605  * Identify the latest relfrozenxid and relminmxid values that we could
1606  * validly see during the scan. These are conservative values, but it's
1607  * not really worth trying to be more exact.
1608  */
1609  lastSaneFrozenXid = ReadNextTransactionId();
1610  lastSaneMinMulti = ReadNextMultiXactId();
1611 
1612  /*
1613  * We must seqscan pg_class to find the minimum Xid, because there is no
1614  * index that can help us here.
1615  */
1616  relation = table_open(RelationRelationId, AccessShareLock);
1617 
1618  scan = systable_beginscan(relation, InvalidOid, false,
1619  NULL, 0, NULL);
1620 
1621  while ((classTup = systable_getnext(scan)) != NULL)
1622  {
1623  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
1624 
1625  /*
1626  * Only consider relations able to hold unfrozen XIDs (anything else
1627  * should have InvalidTransactionId in relfrozenxid anyway).
1628  */
1629  if (classForm->relkind != RELKIND_RELATION &&
1630  classForm->relkind != RELKIND_MATVIEW &&
1631  classForm->relkind != RELKIND_TOASTVALUE)
1632  {
1633  Assert(!TransactionIdIsValid(classForm->relfrozenxid));
1634  Assert(!MultiXactIdIsValid(classForm->relminmxid));
1635  continue;
1636  }
1637 
1638  /*
1639  * Some table AMs might not need per-relation xid / multixid horizons.
1640  * It therefore seems reasonable to allow relfrozenxid and relminmxid
1641  * to not be set (i.e. set to their respective Invalid*Id)
1642  * independently. Thus validate and compute horizon for each only if
1643  * set.
1644  *
1645  * If things are working properly, no relation should have a
1646  * relfrozenxid or relminmxid that is "in the future". However, such
1647  * cases have been known to arise due to bugs in pg_upgrade. If we
1648  * see any entries that are "in the future", chicken out and don't do
1649  * anything. This ensures we won't truncate clog & multixact SLRUs
1650  * before those relations have been scanned and cleaned up.
1651  */
1652 
1653  if (TransactionIdIsValid(classForm->relfrozenxid))
1654  {
1655  Assert(TransactionIdIsNormal(classForm->relfrozenxid));
1656 
1657  /* check for values in the future */
1658  if (TransactionIdPrecedes(lastSaneFrozenXid, classForm->relfrozenxid))
1659  {
1660  bogus = true;
1661  break;
1662  }
1663 
1664  /* determine new horizon */
1665  if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
1666  newFrozenXid = classForm->relfrozenxid;
1667  }
1668 
1669  if (MultiXactIdIsValid(classForm->relminmxid))
1670  {
1671  /* check for values in the future */
1672  if (MultiXactIdPrecedes(lastSaneMinMulti, classForm->relminmxid))
1673  {
1674  bogus = true;
1675  break;
1676  }
1677 
1678  /* determine new horizon */
1679  if (MultiXactIdPrecedes(classForm->relminmxid, newMinMulti))
1680  newMinMulti = classForm->relminmxid;
1681  }
1682  }
1683 
1684  /* we're done with pg_class */
1685  systable_endscan(scan);
1686  table_close(relation, AccessShareLock);
1687 
1688  /* chicken out if bogus data found */
1689  if (bogus)
1690  return;
1691 
1692  Assert(TransactionIdIsNormal(newFrozenXid));
1693  Assert(MultiXactIdIsValid(newMinMulti));
1694 
1695  /* Now fetch the pg_database tuple we need to update. */
1696  relation = table_open(DatabaseRelationId, RowExclusiveLock);
1697 
1698  /*
1699  * Get the pg_database tuple to scribble on. Note that this does not
1700  * directly rely on the syscache to avoid issues with flattened toast
1701  * values for the in-place update.
1702  */
1703  ScanKeyInit(&key[0],
1704  Anum_pg_database_oid,
1705  BTEqualStrategyNumber, F_OIDEQ,
1707 
1708  scan = systable_beginscan(relation, DatabaseOidIndexId, true,
1709  NULL, 1, key);
1710  tuple = systable_getnext(scan);
1711  tuple = heap_copytuple(tuple);
1712  systable_endscan(scan);
1713 
1714  if (!HeapTupleIsValid(tuple))
1715  elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
1716 
1717  dbform = (Form_pg_database) GETSTRUCT(tuple);
1718 
1719  /*
1720  * As in vac_update_relstats(), we ordinarily don't want to let
1721  * datfrozenxid go backward; but if it's "in the future" then it must be
1722  * corrupt and it seems best to overwrite it.
1723  */
1724  if (dbform->datfrozenxid != newFrozenXid &&
1725  (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) ||
1726  TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid)))
1727  {
1728  dbform->datfrozenxid = newFrozenXid;
1729  dirty = true;
1730  }
1731  else
1732  newFrozenXid = dbform->datfrozenxid;
1733 
1734  /* Ditto for datminmxid */
1735  if (dbform->datminmxid != newMinMulti &&
1736  (MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) ||
1737  MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid)))
1738  {
1739  dbform->datminmxid = newMinMulti;
1740  dirty = true;
1741  }
1742  else
1743  newMinMulti = dbform->datminmxid;
1744 
1745  if (dirty)
1746  heap_inplace_update(relation, tuple);
1747 
1748  heap_freetuple(tuple);
1749  table_close(relation, RowExclusiveLock);
1750 
1751  /*
1752  * If we were able to advance datfrozenxid or datminmxid, see if we can
1753  * truncate pg_xact and/or pg_multixact. Also do it if the shared
1754  * XID-wrap-limit info is stale, since this action will update that too.
1755  */
1756  if (dirty || ForceTransactionIdLimitUpdate())
1757  vac_truncate_clog(newFrozenXid, newMinMulti,
1758  lastSaneFrozenXid, lastSaneMinMulti);
1759 }
TransactionId MultiXactId
Definition: c.h:649
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:596
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:503
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:384
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:5889
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:776
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
void LockDatabaseFrozenIds(LOCKMODE lockmode)
Definition: lmgr.c:497
#define ExclusiveLock
Definition: lockdefs.h:42
#define RowExclusiveLock
Definition: lockdefs.h:38
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2594
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:722
#define InvalidOid
Definition: postgres_ext.h:36
TransactionId GetOldestNonRemovableTransactionId(Relation rel)
Definition: procarray.c:1993
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static void vac_truncate_clog(TransactionId frozenXID, MultiXactId minMulti, TransactionId lastSaneFrozenXid, MultiXactId lastSaneMinMulti)
Definition: vacuum.c:1780
bool ForceTransactionIdLimitUpdate(void)
Definition: varsup.c:517

References AccessShareLock, Assert(), BTEqualStrategyNumber, elog, ERROR, ExclusiveLock, ForceTransactionIdLimitUpdate(), GetOldestMultiXactId(), GetOldestNonRemovableTransactionId(), GETSTRUCT, heap_copytuple(), heap_freetuple(), heap_inplace_update(), HeapTupleIsValid, InvalidOid, sort-test::key, LockDatabaseFrozenIds(), MultiXactIdIsValid, MultiXactIdPrecedes(), MyDatabaseId, ObjectIdGetDatum(), ReadNextMultiXactId(), ReadNextTransactionId(), RowExclusiveLock, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), TransactionIdIsNormal, TransactionIdIsValid, TransactionIdPrecedes(), and vac_truncate_clog().

Referenced by do_autovacuum(), and vacuum().

◆ vac_update_relstats()

void vac_update_relstats ( Relation  relation,
BlockNumber  num_pages,
double  num_tuples,
BlockNumber  num_all_visible_pages,
bool  hasindex,
TransactionId  frozenxid,
MultiXactId  minmulti,
bool frozenxid_updated,
bool minmulti_updated,
bool  in_outer_xact 
)

Definition at line 1399 of file vacuum.c.

1406 {
1407  Oid relid = RelationGetRelid(relation);
1408  Relation rd;
1409  HeapTuple ctup;
1410  Form_pg_class pgcform;
1411  bool dirty,
1412  futurexid,
1413  futuremxid;
1414  TransactionId oldfrozenxid;
1415  MultiXactId oldminmulti;
1416 
1417  rd = table_open(RelationRelationId, RowExclusiveLock);
1418 
1419  /* Fetch a copy of the tuple to scribble on */
1420  ctup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
1421  if (!HeapTupleIsValid(ctup))
1422  elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
1423  relid);
1424  pgcform = (Form_pg_class) GETSTRUCT(ctup);
1425 
1426  /* Apply statistical updates, if any, to copied tuple */
1427 
1428  dirty = false;
1429  if (pgcform->relpages != (int32) num_pages)
1430  {
1431  pgcform->relpages = (int32) num_pages;
1432  dirty = true;
1433  }
1434  if (pgcform->reltuples != (float4) num_tuples)
1435  {
1436  pgcform->reltuples = (float4) num_tuples;
1437  dirty = true;
1438  }
1439  if (pgcform->relallvisible != (int32) num_all_visible_pages)
1440  {
1441  pgcform->relallvisible = (int32) num_all_visible_pages;
1442  dirty = true;
1443  }
1444 
1445  /* Apply DDL updates, but not inside an outer transaction (see above) */
1446 
1447  if (!in_outer_xact)
1448  {
1449  /*
1450  * If we didn't find any indexes, reset relhasindex.
1451  */
1452  if (pgcform->relhasindex && !hasindex)
1453  {
1454  pgcform->relhasindex = false;
1455  dirty = true;
1456  }
1457 
1458  /* We also clear relhasrules and relhastriggers if needed */
1459  if (pgcform->relhasrules && relation->rd_rules == NULL)
1460  {
1461  pgcform->relhasrules = false;
1462  dirty = true;
1463  }
1464  if (pgcform->relhastriggers && relation->trigdesc == NULL)
1465  {
1466  pgcform->relhastriggers = false;
1467  dirty = true;
1468  }
1469  }
1470 
1471  /*
1472  * Update relfrozenxid, unless caller passed InvalidTransactionId
1473  * indicating it has no new data.
1474  *
1475  * Ordinarily, we don't let relfrozenxid go backwards. However, if the
1476  * stored relfrozenxid is "in the future" then it seems best to assume
1477  * it's corrupt, and overwrite with the oldest remaining XID in the table.
1478  * This should match vac_update_datfrozenxid() concerning what we consider
1479  * to be "in the future".
1480  */
1481  oldfrozenxid = pgcform->relfrozenxid;
1482  futurexid = false;
1483  if (frozenxid_updated)
1484  *frozenxid_updated = false;
1485  if (TransactionIdIsNormal(frozenxid) && oldfrozenxid != frozenxid)
1486  {
1487  bool update = false;
1488 
1489  if (TransactionIdPrecedes(oldfrozenxid, frozenxid))
1490  update = true;
1491  else if (TransactionIdPrecedes(ReadNextTransactionId(), oldfrozenxid))
1492  futurexid = update = true;
1493 
1494  if (update)
1495  {
1496  pgcform->relfrozenxid = frozenxid;
1497  dirty = true;
1498  if (frozenxid_updated)
1499  *frozenxid_updated = true;
1500  }
1501  }
1502 
1503  /* Similarly for relminmxid */
1504  oldminmulti = pgcform->relminmxid;
1505  futuremxid = false;
1506  if (minmulti_updated)
1507  *minmulti_updated = false;
1508  if (MultiXactIdIsValid(minmulti) && oldminmulti != minmulti)
1509  {
1510  bool update = false;
1511 
1512  if (MultiXactIdPrecedes(oldminmulti, minmulti))
1513  update = true;
1514  else if (MultiXactIdPrecedes(ReadNextMultiXactId(), oldminmulti))
1515  futuremxid = update = true;
1516 
1517  if (update)
1518  {
1519  pgcform->relminmxid = minmulti;
1520  dirty = true;
1521  if (minmulti_updated)
1522  *minmulti_updated = true;
1523  }
1524  }
1525 
1526  /* If anything changed, write out the tuple. */
1527  if (dirty)
1528  heap_inplace_update(rd, ctup);
1529 
1531 
1532  if (futurexid)
1533  ereport(WARNING,
1535  errmsg_internal("overwrote invalid relfrozenxid value %u with new value %u for table \"%s\"",
1536  oldfrozenxid, frozenxid,
1537  RelationGetRelationName(relation))));
1538  if (futuremxid)
1539  ereport(WARNING,
1541  errmsg_internal("overwrote invalid relminmxid value %u with new value %u for table \"%s\"",
1542  oldminmulti, minmulti,
1543  RelationGetRelationName(relation))));
1544 }
signed int int32
Definition: c.h:481
float float4
Definition: c.h:616
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
#define RelationGetRelid(relation)
Definition: rel.h:504
TriggerDesc * trigdesc
Definition: rel.h:117
RuleLock * rd_rules
Definition: rel.h:115
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:86

References elog, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg_internal(), ERROR, GETSTRUCT, heap_inplace_update(), HeapTupleIsValid, MultiXactIdIsValid, MultiXactIdPrecedes(), ObjectIdGetDatum(), RelationData::rd_rules, ReadNextMultiXactId(), ReadNextTransactionId(), RelationGetRelationName, RelationGetRelid, RowExclusiveLock, SearchSysCacheCopy1, table_close(), table_open(), TransactionIdIsNormal, TransactionIdPrecedes(), RelationData::trigdesc, and WARNING.

Referenced by do_analyze_rel(), heap_vacuum_rel(), and update_relstats_all_indexes().

◆ vacuum()

void vacuum ( List relations,
VacuumParams params,
BufferAccessStrategy  bstrategy,
MemoryContext  vac_context,
bool  isTopLevel 
)

Definition at line 476 of file vacuum.c.

478 {
479  static bool in_vacuum = false;
480 
481  const char *stmttype;
482  volatile bool in_outer_xact,
483  use_own_xacts;
484 
485  Assert(params != NULL);
486 
487  stmttype = (params->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
488 
489  /*
490  * We cannot run VACUUM inside a user transaction block; if we were inside
491  * a transaction, then our commit- and start-transaction-command calls
492  * would not have the intended effect! There are numerous other subtle
493  * dependencies on this, too.
494  *
495  * ANALYZE (without VACUUM) can run either way.
496  */
497  if (params->options & VACOPT_VACUUM)
498  {
499  PreventInTransactionBlock(isTopLevel, stmttype);
500  in_outer_xact = false;
501  }
502  else
503  in_outer_xact = IsInTransactionBlock(isTopLevel);
504 
505  /*
506  * Check for and disallow recursive calls. This could happen when VACUUM
507  * FULL or ANALYZE calls a hostile index expression that itself calls
508  * ANALYZE.
509  */
510  if (in_vacuum)
511  ereport(ERROR,
512  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
513  errmsg("%s cannot be executed from VACUUM or ANALYZE",
514  stmttype)));
515 
516  /*
517  * Build list of relation(s) to process, putting any new data in
518  * vac_context for safekeeping.
519  */
520  if (params->options & VACOPT_ONLY_DATABASE_STATS)
521  {
522  /* We don't process any tables in this case */
523  Assert(relations == NIL);
524  }
525  else if (relations != NIL)
526  {
527  List *newrels = NIL;
528  ListCell *lc;
529 
530  foreach(lc, relations)
531  {
533  List *sublist;
534  MemoryContext old_context;
535 
536  sublist = expand_vacuum_rel(vrel, vac_context, params->options);
537  old_context = MemoryContextSwitchTo(vac_context);
538  newrels = list_concat(newrels, sublist);
539  MemoryContextSwitchTo(old_context);
540  }
541  relations = newrels;
542  }
543  else
544  relations = get_all_vacuum_rels(vac_context, params->options);
545 
546  /*
547  * Decide whether we need to start/commit our own transactions.
548  *
549  * For VACUUM (with or without ANALYZE): always do so, so that we can
550  * release locks as soon as possible. (We could possibly use the outer
551  * transaction for a one-table VACUUM, but handling TOAST tables would be
552  * problematic.)
553  *
554  * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
555  * start/commit our own transactions. Also, there's no need to do so if
556  * only processing one relation. For multiple relations when not within a
557  * transaction block, and also in an autovacuum worker, use own
558  * transactions so we can release locks sooner.
559  */
560  if (params->options & VACOPT_VACUUM)
561  use_own_xacts = true;
562  else
563  {
564  Assert(params->options & VACOPT_ANALYZE);
566  use_own_xacts = true;
567  else if (in_outer_xact)
568  use_own_xacts = false;
569  else if (list_length(relations) > 1)
570  use_own_xacts = true;
571  else
572  use_own_xacts = false;
573  }
574 
575  /*
576  * vacuum_rel expects to be entered with no transaction active; it will
577  * start and commit its own transaction. But we are called by an SQL
578  * command, and so we are executing inside a transaction already. We
579  * commit the transaction started in PostgresMain() here, and start
580  * another one before exiting to match the commit waiting for us back in
581  * PostgresMain().
582  */
583  if (use_own_xacts)
584  {
585  Assert(!in_outer_xact);
586 
587  /* ActiveSnapshot is not set by autovacuum */
588  if (ActiveSnapshotSet())
590 
591  /* matches the StartTransaction in PostgresMain() */
593  }
594 
595  /* Turn vacuum cost accounting on or off, and set/clear in_vacuum */
596  PG_TRY();
597  {
598  ListCell *cur;
599 
600  in_vacuum = true;
601  VacuumFailsafeActive = false;
603  VacuumCostBalance = 0;
604  VacuumPageHit = 0;
605  VacuumPageMiss = 0;
606  VacuumPageDirty = 0;
609  VacuumActiveNWorkers = NULL;
610 
611  /*
612  * Loop to process each selected relation.
613  */
614  foreach(cur, relations)
615  {
617 
618  if (params->options & VACOPT_VACUUM)
619  {
620  if (!vacuum_rel(vrel->oid, vrel->relation, params, bstrategy))
621  continue;
622  }
623 
624  if (params->options & VACOPT_ANALYZE)
625  {
626  /*
627  * If using separate xacts, start one for analyze. Otherwise,
628  * we can use the outer transaction.
629  */
630  if (use_own_xacts)
631  {
633  /* functions in indexes may want a snapshot set */
635  }
636 
637  analyze_rel(vrel->oid, vrel->relation, params,
638  vrel->va_cols, in_outer_xact, bstrategy);
639 
640  if (use_own_xacts)
641  {
644  }
645  else
646  {
647  /*
648  * If we're not using separate xacts, better separate the
649  * ANALYZE actions with CCIs. This avoids trouble if user
650  * says "ANALYZE t, t".
651  */
653  }
654  }
655 
656  /*
657  * Ensure VacuumFailsafeActive has been reset before vacuuming the
658  * next relation.
659  */
660  VacuumFailsafeActive = false;
661  }
662  }
663  PG_FINALLY();
664  {
665  in_vacuum = false;
666  VacuumCostActive = false;
667  VacuumFailsafeActive = false;
668  VacuumCostBalance = 0;
669  }
670  PG_END_TRY();
671 
672  /*
673  * Finish up processing.
674  */
675  if (use_own_xacts)
676  {
677  /* here, we are not in a transaction */
678 
679  /*
680  * This matches the CommitTransaction waiting for us in
681  * PostgresMain().
682  */
684  }
685 
686  if ((params->options & VACOPT_VACUUM) &&
687  !(params->options & VACOPT_SKIP_DATABASE_STATS))
688  {
689  /*
690  * Update pg_database.datfrozenxid, and truncate pg_xact if possible.
691  */
693  }
694 
695 }
void VacuumUpdateCosts(void)
Definition: autovacuum.c:1747
void analyze_rel(Oid relid, RangeVar *relation, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
Definition: analyze.c:111
struct cursor * cur
Definition: ecpg.c:28
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_FINALLY(...)
Definition: elog.h:387
int64 VacuumPageHit
Definition: globals.c:153
int64 VacuumPageMiss
Definition: globals.c:154
bool VacuumCostActive
Definition: globals.c:158
int64 VacuumPageDirty
Definition: globals.c:155
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:216
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:648
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:782
void PopActiveSnapshot(void)
Definition: snapmgr.c:743
static List * expand_vacuum_rel(VacuumRelation *vrel, MemoryContext vac_context, int options)
Definition: vacuum.c:871
static List * get_all_vacuum_rels(MemoryContext vac_context, int options)
Definition: vacuum.c:1011
static bool vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params, BufferAccessStrategy bstrategy)
Definition: vacuum.c:1949
void vac_update_datfrozenxid(void)
Definition: vacuum.c:1566
bool VacuumFailsafeActive
Definition: vacuum.c:96
bool IsInTransactionBlock(bool isTopLevel)
Definition: xact.c:3627
void CommandCounterIncrement(void)
Definition: xact.c:1076
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3496
void StartTransactionCommand(void)
Definition: xact.c:2952
void CommitTransactionCommand(void)
Definition: xact.c:3049

References ActiveSnapshotSet(), AmAutoVacuumWorkerProcess, analyze_rel(), Assert(), CommandCounterIncrement(), CommitTransactionCommand(), cur, ereport, errcode(), errmsg(), ERROR, expand_vacuum_rel(), get_all_vacuum_rels(), GetTransactionSnapshot(), IsInTransactionBlock(), lfirst_node, list_concat(), list_length(), MemoryContextSwitchTo(), NIL, VacuumRelation::oid, VacuumParams::options, PG_END_TRY, PG_FINALLY, PG_TRY, PopActiveSnapshot(), PreventInTransactionBlock(), PushActiveSnapshot(), VacuumRelation::relation, StartTransactionCommand(), VacuumRelation::va_cols, vac_update_datfrozenxid(), VACOPT_ANALYZE, VACOPT_ONLY_DATABASE_STATS, VACOPT_SKIP_DATABASE_STATS, VACOPT_VACUUM, vacuum_rel(), VacuumActiveNWorkers, VacuumCostActive, VacuumCostBalance, VacuumCostBalanceLocal, VacuumFailsafeActive, VacuumPageDirty, VacuumPageHit, VacuumPageMiss, VacuumSharedCostBalance, and VacuumUpdateCosts().

Referenced by autovacuum_do_vac_analyze(), ExecVacuum(), parallel_vacuum_index_is_parallel_safe(), and parallel_vacuum_process_all_indexes().

◆ vacuum_delay_point()

void vacuum_delay_point ( void  )

Definition at line 2320 of file vacuum.c.

2321 {
2322  double msec = 0;
2323 
2324  /* Always check for interrupts */
2326 
2327  if (InterruptPending ||
2329  return;
2330 
2331  /*
2332  * Autovacuum workers should reload the configuration file if requested.
2333  * This allows changes to [autovacuum_]vacuum_cost_limit and
2334  * [autovacuum_]vacuum_cost_delay to take effect while a table is being
2335  * vacuumed or analyzed.
2336  */
2338  {
2339  ConfigReloadPending = false;
2342  }
2343 
2344  /*
2345  * If we disabled cost-based delays after reloading the config file,
2346  * return.
2347  */
2348  if (!VacuumCostActive)
2349  return;
2350 
2351  /*
2352  * For parallel vacuum, the delay is computed based on the shared cost
2353  * balance. See compute_parallel_delay.
2354  */
2355  if (VacuumSharedCostBalance != NULL)
2356  msec = compute_parallel_delay();
2359 
2360  /* Nap if appropriate */
2361  if (msec > 0)
2362  {
2363  if (msec > vacuum_cost_delay * 4)
2364  msec = vacuum_cost_delay * 4;
2365 
2366  pgstat_report_wait_start(WAIT_EVENT_VACUUM_DELAY);
2367  pg_usleep(msec * 1000);
2369 
2370  /*
2371  * We don't want to ignore postmaster death during very long vacuums
2372  * with vacuum_cost_delay configured. We can't use the usual
2373  * WaitLatch() approach here because we want microsecond-based sleep
2374  * durations above.
2375  */
2377  exit(1);
2378 
2379  VacuumCostBalance = 0;
2380 
2381  /*
2382  * Balance and update limit values for autovacuum workers. We must do
2383  * this periodically, as the number of workers across which we are
2384  * balancing the limit may have changed.
2385  *
2386  * TODO: There may be better criteria for determining when to do this
2387  * besides "check after napping".
2388  */
2390 
2391  /* Might have gotten an interrupt while sleeping */
2393  }
2394 }
void AutoVacuumUpdateCostLimit(void)
Definition: autovacuum.c:1816
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
bool IsUnderPostmaster
Definition: globals.c:116
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
exit(1)
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define PostmasterIsAlive()
Definition: pmsignal.h:102
void pg_usleep(long microsec)
Definition: signal.c:53
static double compute_parallel_delay(void)
Definition: vacuum.c:2419
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104

References AmAutoVacuumWorkerProcess, AutoVacuumUpdateCostLimit(), CHECK_FOR_INTERRUPTS, compute_parallel_delay(), ConfigReloadPending, exit(), InterruptPending, IsUnderPostmaster, pg_usleep(), PGC_SIGHUP, pgstat_report_wait_end(), pgstat_report_wait_start(), PostmasterIsAlive, ProcessConfigFile(), vacuum_cost_delay, vacuum_cost_limit, VacuumCostActive, VacuumCostBalance, VacuumSharedCostBalance, and VacuumUpdateCosts().

Referenced by acquire_sample_rows(), blbulkdelete(), blvacuumcleanup(), btvacuumpage(), compute_array_stats(), compute_distinct_stats(), compute_index_stats(), compute_range_stats(), compute_scalar_stats(), compute_trivial_stats(), compute_tsvector_stats(), file_acquire_sample_rows(), ginbulkdelete(), ginInsertCleanup(), ginvacuumcleanup(), gistvacuumpage(), hashbucketcleanup(), lazy_scan_heap(), lazy_scan_skip(), lazy_vacuum_heap_rel(), spgprocesspending(), and spgvacuumpage().

◆ vacuum_get_cutoffs()

bool vacuum_get_cutoffs ( Relation  rel,
const VacuumParams params,
struct VacuumCutoffs cutoffs 
)

Definition at line 1073 of file vacuum.c.

1075 {
1076  int freeze_min_age,
1077  multixact_freeze_min_age,
1078  freeze_table_age,
1079  multixact_freeze_table_age,
1080  effective_multixact_freeze_max_age;
1081  TransactionId nextXID,
1082  safeOldestXmin,
1083  aggressiveXIDCutoff;
1084  MultiXactId nextMXID,
1085  safeOldestMxact,
1086  aggressiveMXIDCutoff;
1087 
1088  /* Use mutable copies of freeze age parameters */
1089  freeze_min_age = params->freeze_min_age;
1090  multixact_freeze_min_age = params->multixact_freeze_min_age;
1091  freeze_table_age = params->freeze_table_age;
1092  multixact_freeze_table_age = params->multixact_freeze_table_age;
1093 
1094  /* Set pg_class fields in cutoffs */
1095  cutoffs->relfrozenxid = rel->rd_rel->relfrozenxid;
1096  cutoffs->relminmxid = rel->rd_rel->relminmxid;
1097 
1098  /*
1099  * Acquire OldestXmin.
1100  *
1101  * We can always ignore processes running lazy vacuum. This is because we
1102  * use these values only for deciding which tuples we must keep in the
1103  * tables. Since lazy vacuum doesn't write its XID anywhere (usually no
1104  * XID assigned), it's safe to ignore it. In theory it could be
1105  * problematic to ignore lazy vacuums in a full vacuum, but keep in mind
1106  * that only one vacuum process can be working on a particular table at
1107  * any time, and that each vacuum is always an independent transaction.
1108  */
1110 
1112 
1113  /* Acquire OldestMxact */
1114  cutoffs->OldestMxact = GetOldestMultiXactId();
1116 
1117  /* Acquire next XID/next MXID values used to apply age-based settings */
1118  nextXID = ReadNextTransactionId();
1119  nextMXID = ReadNextMultiXactId();
1120 
1121  /*
1122  * Also compute the multixact age for which freezing is urgent. This is
1123  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
1124  * short of multixact member space.
1125  */
1126  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
1127 
1128  /*
1129  * Almost ready to set freeze output parameters; check if OldestXmin or
1130  * OldestMxact are held back to an unsafe degree before we start on that
1131  */
1132  safeOldestXmin = nextXID - autovacuum_freeze_max_age;
1133  if (!TransactionIdIsNormal(safeOldestXmin))
1134  safeOldestXmin = FirstNormalTransactionId;
1135  safeOldestMxact = nextMXID - effective_multixact_freeze_max_age;
1136  if (safeOldestMxact < FirstMultiXactId)
1137  safeOldestMxact = FirstMultiXactId;
1138  if (TransactionIdPrecedes(cutoffs->OldestXmin, safeOldestXmin))
1139  ereport(WARNING,
1140  (errmsg("cutoff for removing and freezing tuples is far in the past"),
1141  errhint("Close open transactions soon to avoid wraparound problems.\n"
1142  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1143  if (MultiXactIdPrecedes(cutoffs->OldestMxact, safeOldestMxact))
1144  ereport(WARNING,
1145  (errmsg("cutoff for freezing multixacts is far in the past"),
1146  errhint("Close open transactions soon to avoid wraparound problems.\n"
1147  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1148 
1149  /*
1150  * Determine the minimum freeze age to use: as specified by the caller, or
1151  * vacuum_freeze_min_age, but in any case not more than half
1152  * autovacuum_freeze_max_age, so that autovacuums to prevent XID
1153  * wraparound won't occur too frequently.
1154  */
1155  if (freeze_min_age < 0)
1156  freeze_min_age = vacuum_freeze_min_age;
1157  freeze_min_age = Min(freeze_min_age, autovacuum_freeze_max_age / 2);
1158  Assert(freeze_min_age >= 0);
1159 
1160  /* Compute FreezeLimit, being careful to generate a normal XID */
1161  cutoffs->FreezeLimit = nextXID - freeze_min_age;
1162  if (!TransactionIdIsNormal(cutoffs->FreezeLimit))
1164  /* FreezeLimit must always be <= OldestXmin */
1165  if (TransactionIdPrecedes(cutoffs->OldestXmin, cutoffs->FreezeLimit))
1166  cutoffs->FreezeLimit = cutoffs->OldestXmin;
1167 
1168  /*
1169  * Determine the minimum multixact freeze age to use: as specified by
1170  * caller, or vacuum_multixact_freeze_min_age, but in any case not more
1171  * than half effective_multixact_freeze_max_age, so that autovacuums to
1172  * prevent MultiXact wraparound won't occur too frequently.
1173  */
1174  if (multixact_freeze_min_age < 0)
1175  multixact_freeze_min_age = vacuum_multixact_freeze_min_age;
1176  multixact_freeze_min_age = Min(multixact_freeze_min_age,
1177  effective_multixact_freeze_max_age / 2);
1178  Assert(multixact_freeze_min_age >= 0);
1179 
1180  /* Compute MultiXactCutoff, being careful to generate a valid value */
1181  cutoffs->MultiXactCutoff = nextMXID - multixact_freeze_min_age;
1182  if (cutoffs->MultiXactCutoff < FirstMultiXactId)
1183  cutoffs->MultiXactCutoff = FirstMultiXactId;
1184  /* MultiXactCutoff must always be <= OldestMxact */
1185  if (MultiXactIdPrecedes(cutoffs->OldestMxact, cutoffs->MultiXactCutoff))
1186  cutoffs->MultiXactCutoff = cutoffs->OldestMxact;
1187 
1188  /*
1189  * Finally, figure out if caller needs to do an aggressive VACUUM or not.
1190  *
1191  * Determine the table freeze age to use: as specified by the caller, or
1192  * the value of the vacuum_freeze_table_age GUC, but in any case not more
1193  * than autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
1194  * VACUUM schedule, the nightly VACUUM gets a chance to freeze XIDs before
1195  * anti-wraparound autovacuum is launched.
1196  */
1197  if (freeze_table_age < 0)
1198  freeze_table_age = vacuum_freeze_table_age;
1199  freeze_table_age = Min(freeze_table_age, autovacuum_freeze_max_age * 0.95);
1200  Assert(freeze_table_age >= 0);
1201  aggressiveXIDCutoff = nextXID - freeze_table_age;
1202  if (!TransactionIdIsNormal(aggressiveXIDCutoff))
1203  aggressiveXIDCutoff = FirstNormalTransactionId;
1204  if (TransactionIdPrecedesOrEquals(rel->rd_rel->relfrozenxid,
1205  aggressiveXIDCutoff))
1206  return true;
1207 
1208  /*
1209  * Similar to the above, determine the table freeze age to use for
1210  * multixacts: as specified by the caller, or the value of the
1211  * vacuum_multixact_freeze_table_age GUC, but in any case not more than
1212  * effective_multixact_freeze_max_age * 0.95, so that if you have e.g.
1213  * nightly VACUUM schedule, the nightly VACUUM gets a chance to freeze
1214  * multixacts before anti-wraparound autovacuum is launched.
1215  */
1216  if (multixact_freeze_table_age < 0)
1217  multixact_freeze_table_age = vacuum_multixact_freeze_table_age;
1218  multixact_freeze_table_age =
1219  Min(multixact_freeze_table_age,
1220  effective_multixact_freeze_max_age * 0.95);
1221  Assert(multixact_freeze_table_age >= 0);
1222  aggressiveMXIDCutoff = nextMXID - multixact_freeze_table_age;
1223  if (aggressiveMXIDCutoff < FirstMultiXactId)
1224  aggressiveMXIDCutoff = FirstMultiXactId;
1225  if (MultiXactIdPrecedesOrEquals(rel->rd_rel->relminmxid,
1226  aggressiveMXIDCutoff))
1227  return true;
1228 
1229  /* Non-aggressive VACUUM */
1230  return false;
1231 }
int autovacuum_freeze_max_age
Definition: autovacuum.c:126
#define Min(x, y)
Definition: c.h:991
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3257
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2912
#define FirstMultiXactId
Definition: multixact.h:25
TransactionId FreezeLimit
Definition: vacuum.h:275
TransactionId OldestXmin
Definition: vacuum.h:265
TransactionId relfrozenxid
Definition: vacuum.h:249
MultiXactId relminmxid
Definition: vacuum.h:250
MultiXactId MultiXactCutoff
Definition: vacuum.h:276
MultiXactId OldestMxact
Definition: vacuum.h:266
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:299
#define FirstNormalTransactionId
Definition: transam.h:34
int vacuum_freeze_min_age
Definition: vacuum.c:67
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:70
int vacuum_freeze_table_age
Definition: vacuum.c:68
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:69

References Assert(), autovacuum_freeze_max_age, ereport, errhint(), errmsg(), FirstMultiXactId, FirstNormalTransactionId, VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, VacuumCutoffs::FreezeLimit, GetOldestMultiXactId(), GetOldestNonRemovableTransactionId(), Min, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, VacuumCutoffs::MultiXactCutoff, MultiXactIdIsValid, MultiXactIdPrecedes(), MultiXactIdPrecedesOrEquals(), MultiXactMemberFreezeThreshold(), VacuumCutoffs::OldestMxact, VacuumCutoffs::OldestXmin, RelationData::rd_rel, ReadNextMultiXactId(), ReadNextTransactionId(), VacuumCutoffs::relfrozenxid, VacuumCutoffs::relminmxid, TransactionIdIsNormal, TransactionIdPrecedes(), TransactionIdPrecedesOrEquals(), vacuum_freeze_min_age, vacuum_freeze_table_age, vacuum_multixact_freeze_min_age, vacuum_multixact_freeze_table_age, and WARNING.

Referenced by copy_table_data(), and heap_vacuum_rel().

◆ vacuum_is_relation_owner()

bool vacuum_is_relation_owner ( Oid  relid,
Form_pg_class  reltuple,
bits32  options 
)

Definition at line 705 of file vacuum.c.

706 {
707  char *relname;
708 
710 
711  /*
712  * Check permissions.
713  *
714  * We allow the user to vacuum or analyze a table if he is superuser, the
715  * table owner, or the database owner (but in the latter case, only if
716  * it's not a shared relation). object_ownercheck includes the superuser
717  * case.
718  *
719  * Note we choose to treat permissions failure as a WARNING and keep
720  * trying to vacuum or analyze the rest of the DB --- is this appropriate?
721  */
722  if (object_ownercheck(RelationRelationId, relid, GetUserId()) ||
723  (object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()) && !reltuple->relisshared))
724  return true;
725 
726  relname = NameStr(reltuple->relname);
727 
728  if ((options & VACOPT_VACUUM) != 0)
729  {
731  (errmsg("permission denied to vacuum \"%s\", skipping it",
732  relname)));
733 
734  /*
735  * For VACUUM ANALYZE, both logs could show up, but just generate
736  * information for VACUUM as that would be the first one to be
737  * processed.
738  */
739  return false;
740  }
741 
742  if ((options & VACOPT_ANALYZE) != 0)
744  (errmsg("permission denied to analyze \"%s\", skipping it",
745  relname)));
746 
747  return false;
748 }
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4115
Oid GetUserId(void)
Definition: miscinit.c:514
NameData relname
Definition: pg_class.h:38

References Assert(), ereport, errmsg(), GetUserId(), MyDatabaseId, NameStr, object_ownercheck(), relname, VACOPT_ANALYZE, VACOPT_VACUUM, and WARNING.

Referenced by analyze_rel(), expand_vacuum_rel(), get_all_vacuum_rels(), and vacuum_rel().

◆ vacuum_open_relation()

Relation vacuum_open_relation ( Oid  relid,
RangeVar relation,
bits32  options,
bool  verbose,
LOCKMODE  lmode 
)

Definition at line 759 of file vacuum.c.

761 {
762  Relation rel;
763  bool rel_lock = true;
764  int elevel;
765 
767 
768  /*
769  * Open the relation and get the appropriate lock on it.
770  *
771  * There's a race condition here: the relation may have gone away since
772  * the last time we saw it. If so, we don't need to vacuum or analyze it.
773  *
774  * If we've been asked not to wait for the relation lock, acquire it first
775  * in non-blocking mode, before calling try_relation_open().
776  */
777  if (!(options & VACOPT_SKIP_LOCKED))
778  rel = try_relation_open(relid, lmode);
779  else if (ConditionalLockRelationOid(relid, lmode))
780  rel = try_relation_open(relid, NoLock);
781  else
782  {
783  rel = NULL;
784  rel_lock = false;
785  }
786 
787  /* if relation is opened, leave */
788  if (rel)
789  return rel;
790 
791  /*
792  * Relation could not be opened, hence generate if possible a log
793  * informing on the situation.
794  *
795  * If the RangeVar is not defined, we do not have enough information to
796  * provide a meaningful log statement. Chances are that the caller has
797  * intentionally not provided this information so that this logging is
798  * skipped, anyway.
799  */
800  if (relation == NULL)
801  return NULL;
802 
803  /*
804  * Determine the log level.
805  *
806  * For manual VACUUM or ANALYZE, we emit a WARNING to match the log
807  * statements in the permission checks; otherwise, only log if the caller
808  * so requested.
809  */
811  elevel = WARNING;
812  else if (verbose)
813  elevel = LOG;
814  else
815  return NULL;
816 
817  if ((options & VACOPT_VACUUM) != 0)
818  {
819  if (!rel_lock)
820  ereport(elevel,
821  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
822  errmsg("skipping vacuum of \"%s\" --- lock not available",
823  relation->relname)));
824  else
825  ereport(elevel,
827  errmsg("skipping vacuum of \"%s\" --- relation no longer exists",
828  relation->relname)));
829 
830  /*
831  * For VACUUM ANALYZE, both logs could show up, but just generate
832  * information for VACUUM as that would be the first one to be
833  * processed.
834  */
835  return NULL;
836  }
837 
838  if ((options & VACOPT_ANALYZE) != 0)
839  {
840  if (!rel_lock)
841  ereport(elevel,
842  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
843  errmsg("skipping analyze of \"%s\" --- lock not available",
844  relation->relname)));
845  else
846  ereport(elevel,
848  errmsg("skipping analyze of \"%s\" --- relation no longer exists",
849  relation->relname)));
850  }
851 
852  return NULL;
853 }
#define LOG
Definition: elog.h:31
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:151
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:88

References AmAutoVacuumWorkerProcess, Assert(), ConditionalLockRelationOid(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg(), LOG, NoLock, RangeVar::relname, try_relation_open(), VACOPT_ANALYZE, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, verbose, and WARNING.

Referenced by analyze_rel(), and vacuum_rel().

◆ vacuum_rel()

static bool vacuum_rel ( Oid  relid,
RangeVar relation,
VacuumParams params,
BufferAccessStrategy  bstrategy 
)
static

Definition at line 1949 of file vacuum.c.

1951 {
1952  LOCKMODE lmode;
1953  Relation rel;
1954  LockRelId lockrelid;
1955  Oid toast_relid;
1956  Oid save_userid;
1957  int save_sec_context;
1958  int save_nestlevel;
1959 
1960  Assert(params != NULL);
1961 
1962  /* Begin a transaction for vacuuming this relation */
1964 
1965  if (!(params->options & VACOPT_FULL))
1966  {
1967  /*
1968  * In lazy vacuum, we can set the PROC_IN_VACUUM flag, which lets
1969  * other concurrent VACUUMs know that they can ignore this one while
1970  * determining their OldestXmin. (The reason we don't set it during a
1971  * full VACUUM is exactly that we may have to run user-defined
1972  * functions for functional indexes, and we want to make sure that if
1973  * they use the snapshot set above, any tuples it requires can't get
1974  * removed from other tables. An index function that depends on the
1975  * contents of other tables is arguably broken, but we won't break it
1976  * here by violating transaction semantics.)
1977  *
1978  * We also set the VACUUM_FOR_WRAPAROUND flag, which is passed down by
1979  * autovacuum; it's used to avoid canceling a vacuum that was invoked
1980  * in an emergency.
1981  *
1982  * Note: these flags remain set until CommitTransaction or
1983  * AbortTransaction. We don't want to clear them until we reset
1984  * MyProc->xid/xmin, otherwise GetOldestNonRemovableTransactionId()
1985  * might appear to go backwards, which is probably Not Good. (We also
1986  * set PROC_IN_VACUUM *before* taking our own snapshot, so that our
1987  * xmin doesn't become visible ahead of setting the flag.)
1988  */
1989  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
1991  if (params->is_wraparound)
1994  LWLockRelease(ProcArrayLock);
1995  }
1996 
1997  /*
1998  * Need to acquire a snapshot to prevent pg_subtrans from being truncated,
1999  * cutoff xids in local memory wrapping around, and to have updated xmin
2000  * horizons.
2001  */
2003 
2004  /*
2005  * Check for user-requested abort. Note we want this to be inside a
2006  * transaction, so xact.c doesn't issue useless WARNING.
2007  */
2009 
2010  /*
2011  * Determine the type of lock we want --- hard exclusive lock for a FULL
2012  * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either
2013  * way, we can be sure that no other backend is vacuuming the same table.
2014  */
2015  lmode = (params->options & VACOPT_FULL) ?
2017 
2018  /* open the relation and get the appropriate lock on it */
2019  rel = vacuum_open_relation(relid, relation, params->options,
2020  params->log_min_duration >= 0, lmode);
2021 
2022  /* leave if relation could not be opened or locked */
2023  if (!rel)
2024  {
2027  return false;
2028  }
2029 
2030  /*
2031  * Check if relation needs to be skipped based on ownership. This check
2032  * happens also when building the relation list to vacuum for a manual
2033  * operation, and needs to be done additionally here as VACUUM could
2034  * happen across multiple transactions where relation ownership could have
2035  * changed in-between. Make sure to only generate logs for VACUUM in this
2036  * case.
2037  */
2039  rel->rd_rel,
2040  params->options & VACOPT_VACUUM))
2041  {
2042  relation_close(rel, lmode);
2045  return false;
2046  }
2047 
2048  /*
2049  * Check that it's of a vacuumable relkind.
2050  */
2051  if (rel->rd_rel->relkind != RELKIND_RELATION &&
2052  rel->rd_rel->relkind != RELKIND_MATVIEW &&
2053  rel->rd_rel->relkind != RELKIND_TOASTVALUE &&
2054  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2055  {
2056  ereport(WARNING,
2057  (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
2058  RelationGetRelationName(rel))));
2059  relation_close(rel, lmode);
2062  return false;
2063  }
2064 
2065  /*
2066  * Silently ignore tables that are temp tables of other backends ---
2067  * trying to vacuum these will lead to great unhappiness, since their
2068  * contents are probably not up-to-date on disk. (We don't throw a
2069  * warning here; it would just lead to chatter during a database-wide
2070  * VACUUM.)
2071  */
2072  if (RELATION_IS_OTHER_TEMP(rel))
2073  {
2074  relation_close(rel, lmode);
2077  return false;
2078  }
2079 
2080  /*
2081  * Silently ignore partitioned tables as there is no work to be done. The
2082  * useful work is on their child partitions, which have been queued up for
2083  * us separately.
2084  */
2085  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2086  {
2087  relation_close(rel, lmode);
2090  /* It's OK to proceed with ANALYZE on this table */
2091  return true;
2092  }
2093 
2094  /*
2095  * Get a session-level lock too. This will protect our access to the
2096  * relation across multiple transactions, so that we can vacuum the
2097  * relation's TOAST table (if any) secure in the knowledge that no one is
2098  * deleting the parent relation.
2099  *
2100  * NOTE: this cannot block, even if someone else is waiting for access,
2101  * because the lock manager knows that both lock requests are from the
2102  * same process.
2103  */
2104  lockrelid = rel->rd_lockInfo.lockRelId;
2105  LockRelationIdForSession(&lockrelid, lmode);
2106 
2107  /*
2108  * Set index_cleanup option based on index_cleanup reloption if it wasn't
2109  * specified in VACUUM command, or when running in an autovacuum worker
2110  */
2111  if (params->index_cleanup == VACOPTVALUE_UNSPECIFIED)
2112  {
2113  StdRdOptIndexCleanup vacuum_index_cleanup;
2114 
2115  if (rel->rd_options == NULL)
2116  vacuum_index_cleanup = STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO;
2117  else
2118  vacuum_index_cleanup =
2119  ((StdRdOptions *) rel->rd_options)->vacuum_index_cleanup;
2120 
2121  if (vacuum_index_cleanup == STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO)
2122  params->index_cleanup = VACOPTVALUE_AUTO;
2123  else if (vacuum_index_cleanup == STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON)
2125  else
2126  {
2127  Assert(vacuum_index_cleanup ==
2130  }
2131  }
2132 
2133  /*
2134  * Set truncate option based on truncate reloption if it wasn't specified
2135  * in VACUUM command, or when running in an autovacuum worker
2136  */
2137  if (params->truncate == VACOPTVALUE_UNSPECIFIED)
2138  {
2139  if (rel->rd_options == NULL ||
2140  ((StdRdOptions *) rel->rd_options)->vacuum_truncate)
2141  params->truncate = VACOPTVALUE_ENABLED;
2142  else
2143  params->truncate = VACOPTVALUE_DISABLED;
2144  }
2145 
2146  /*
2147  * Remember the relation's TOAST relation for later, if the caller asked
2148  * us to process it. In VACUUM FULL, though, the toast table is
2149  * automatically rebuilt by cluster_rel so we shouldn't recurse to it,
2150  * unless PROCESS_MAIN is disabled.
2151  */
2152  if ((params->options & VACOPT_PROCESS_TOAST) != 0 &&
2153  ((params->options & VACOPT_FULL) == 0 ||
2154  (params->options & VACOPT_PROCESS_MAIN) == 0))
2155  toast_relid = rel->rd_rel->reltoastrelid;
2156  else
2157  toast_relid = InvalidOid;
2158 
2159  /*
2160  * Switch to the table owner's userid, so that any index functions are run
2161  * as that user. Also lock down security-restricted operations and
2162  * arrange to make GUC variable changes local to this command. (This is
2163  * unnecessary, but harmless, for lazy VACUUM.)
2164  */
2165  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2166  SetUserIdAndSecContext(rel->rd_rel->relowner,
2167  save_sec_context | SECURITY_RESTRICTED_OPERATION);
2168  save_nestlevel = NewGUCNestLevel();
2169 
2170  /*
2171  * If PROCESS_MAIN is set (the default), it's time to vacuum the main
2172  * relation. Otherwise, we can skip this part. If processing the TOAST
2173  * table is required (e.g., PROCESS_TOAST is set), we force PROCESS_MAIN
2174  * to be set when we recurse to the TOAST table.
2175  */
2176  if (params->options & VACOPT_PROCESS_MAIN)
2177  {
2178  /*
2179  * Do the actual work --- either FULL or "lazy" vacuum
2180  */
2181  if (params->options & VACOPT_FULL)
2182  {
2183  ClusterParams cluster_params = {0};
2184 
2185  /* close relation before vacuuming, but hold lock until commit */
2186  relation_close(rel, NoLock);
2187  rel = NULL;
2188 
2189  if ((params->options & VACOPT_VERBOSE) != 0)
2190  cluster_params.options |= CLUOPT_VERBOSE;
2191 
2192  /* VACUUM FULL is now a variant of CLUSTER; see cluster.c */
2193  cluster_rel(relid, InvalidOid, &cluster_params);
2194  }
2195  else
2196  table_relation_vacuum(rel, params, bstrategy);
2197  }
2198 
2199  /* Roll back any GUC changes executed by index functions */
2200  AtEOXact_GUC(false, save_nestlevel);
2201 
2202  /* Restore userid and security context */
2203  SetUserIdAndSecContext(save_userid, save_sec_context);
2204 
2205  /* all done with this class, but hold lock until commit */
2206  if (rel)
2207  relation_close(rel, NoLock);
2208 
2209  /*
2210  * Complete the transaction and free all temporary memory used.
2211  */
2214 
2215  /*
2216  * If the relation has a secondary toast rel, vacuum that too while we
2217  * still hold the session lock on the main table. Note however that
2218  * "analyze" will not get done on the toast table. This is good, because
2219  * the toaster always uses hardcoded index access and statistics are
2220  * totally unimportant for toast relations.
2221  */
2222  if (toast_relid != InvalidOid)
2223  {
2224  VacuumParams toast_vacuum_params;
2225 
2226  /* force VACOPT_PROCESS_MAIN so vacuum_rel() processes it */
2227  memcpy(&toast_vacuum_params, params, sizeof(VacuumParams));
2228  toast_vacuum_params.options |= VACOPT_PROCESS_MAIN;
2229 
2230  vacuum_rel(toast_relid, NULL, &toast_vacuum_params, bstrategy);
2231  }
2232 
2233  /*
2234  * Now release the session-level lock on the main table.
2235  */
2236  UnlockRelationIdForSession(&lockrelid, lmode);
2237 
2238  /* Report that we really did it. */
2239  return true;
2240 }
void cluster_rel(Oid tableOid, Oid indexOid, ClusterParams *params)
Definition: cluster.c:309
#define CLUOPT_VERBOSE
Definition: cluster.h:23
int NewGUCNestLevel(void)
Definition: guc.c:2232
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2246
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:397
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:410
int LOCKMODE
Definition: lockdefs.h:26
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:315
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:635
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:642
#define PROC_IN_VACUUM
Definition: proc.h:58
#define PROC_VACUUM_FOR_WRAPAROUND
Definition: proc.h:60
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:657
StdRdOptIndexCleanup
Definition: rel.h:329
@ STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO
Definition: rel.h:330
@ STDRD_OPTION_VACUUM_INDEX_CLEANUP_OFF
Definition: rel.h:331
@ STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON
Definition: rel.h:332
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
PGPROC * MyProc
Definition: proc.c:66
PROC_HDR * ProcGlobal
Definition: proc.c:78
bits32 options
Definition: cluster.h:30
LockRelId lockRelId
Definition: rel.h:46
Definition: rel.h:39
uint8 statusFlags
Definition: proc.h:238
int pgxactoff
Definition: proc.h:180
uint8 * statusFlags
Definition: proc.h:395
LockInfoData rd_lockInfo
Definition: rel.h:114
bytea * rd_options
Definition: rel.h:174
static void table_relation_vacuum(Relation rel, struct VacuumParams *params, BufferAccessStrategy bstrategy)
Definition: tableam.h:1702
Relation vacuum_open_relation(Oid relid, RangeVar *relation, bits32 options, bool verbose, LOCKMODE lmode)
Definition: vacuum.c:759

References AccessExclusiveLock, Assert(), AtEOXact_GUC(), CHECK_FOR_INTERRUPTS, CLUOPT_VERBOSE, cluster_rel(), CommitTransactionCommand(), ereport, errmsg(), GetTransactionSnapshot(), GetUserIdAndSecContext(), VacuumParams::index_cleanup, InvalidOid, VacuumParams::is_wraparound, LockRelationIdForSession(), LockInfoData::lockRelId, VacuumParams::log_min_duration, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyProc, NewGUCNestLevel(), NoLock, ClusterParams::options, VacuumParams::options, PGPROC::pgxactoff, PopActiveSnapshot(), PROC_IN_VACUUM, PROC_VACUUM_FOR_WRAPAROUND, ProcGlobal, PushActiveSnapshot(), RelationData::rd_lockInfo, RelationData::rd_options, RelationData::rd_rel, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetRelationName, RelationGetRelid, SECURITY_RESTRICTED_OPERATION, SetUserIdAndSecContext(), ShareUpdateExclusiveLock, StartTransactionCommand(), PGPROC::statusFlags, PROC_HDR::statusFlags, STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO, STDRD_OPTION_VACUUM_INDEX_CLEANUP_OFF, STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON, table_relation_vacuum(), VacuumParams::truncate, UnlockRelationIdForSession(), VACOPT_FULL, VACOPT_PROCESS_MAIN, VACOPT_PROCESS_TOAST, VACOPT_VACUUM, VACOPT_VERBOSE, VACOPTVALUE_AUTO, VACOPTVALUE_DISABLED, VACOPTVALUE_ENABLED, VACOPTVALUE_UNSPECIFIED, vacuum_is_relation_owner(), vacuum_open_relation(), and WARNING.

Referenced by vacuum().

◆ vacuum_xid_failsafe_check()

bool vacuum_xid_failsafe_check ( const struct VacuumCutoffs cutoffs)

Definition at line 1241 of file vacuum.c.

1242 {
1243  TransactionId relfrozenxid = cutoffs->relfrozenxid;
1244  MultiXactId relminmxid = cutoffs->relminmxid;
1245  TransactionId xid_skip_limit;
1246  MultiXactId multi_skip_limit;
1247  int skip_index_vacuum;
1248 
1249  Assert(TransactionIdIsNormal(relfrozenxid));
1250  Assert(MultiXactIdIsValid(relminmxid));
1251 
1252  /*
1253  * Determine the index skipping age to use. In any case no less than
1254  * autovacuum_freeze_max_age * 1.05.
1255  */
1256  skip_index_vacuum = Max(vacuum_failsafe_age, autovacuum_freeze_max_age * 1.05);
1257 
1258  xid_skip_limit = ReadNextTransactionId() - skip_index_vacuum;
1259  if (!TransactionIdIsNormal(xid_skip_limit))
1260  xid_skip_limit = FirstNormalTransactionId;
1261 
1262  if (TransactionIdPrecedes(relfrozenxid, xid_skip_limit))
1263  {
1264  /* The table's relfrozenxid is too old */
1265  return true;
1266  }
1267 
1268  /*
1269  * Similar to above, determine the index skipping age to use for
1270  * multixact. In any case no less than autovacuum_multixact_freeze_max_age *
1271  * 1.05.
1272  */
1273  skip_index_vacuum = Max(vacuum_multixact_failsafe_age,
1275 
1276  multi_skip_limit = ReadNextMultiXactId() - skip_index_vacuum;
1277  if (multi_skip_limit < FirstMultiXactId)
1278  multi_skip_limit = FirstMultiXactId;
1279 
1280  if (MultiXactIdPrecedes(relminmxid, multi_skip_limit))
1281  {
1282  /* The table's relminmxid is too old */
1283  return true;
1284  }
1285 
1286  return false;
1287 }
int autovacuum_multixact_freeze_max_age
Definition: autovacuum.c:127
#define Max(x, y)
Definition: c.h:985
int vacuum_multixact_failsafe_age
Definition: vacuum.c:72
int vacuum_failsafe_age
Definition: vacuum.c:71

References Assert(), autovacuum_freeze_max_age, autovacuum_multixact_freeze_max_age, FirstMultiXactId, FirstNormalTransactionId, Max, MultiXactIdIsValid, MultiXactIdPrecedes(), ReadNextMultiXactId(), ReadNextTransactionId(), VacuumCutoffs::relfrozenxid, VacuumCutoffs::relminmxid, TransactionIdIsNormal, TransactionIdPrecedes(), vacuum_failsafe_age, and vacuum_multixact_failsafe_age.

Referenced by lazy_check_wraparound_failsafe().

Variable Documentation

◆ vacuum_cost_delay

double vacuum_cost_delay = 0

◆ vacuum_cost_limit

int vacuum_cost_limit = 200

◆ vacuum_failsafe_age

int vacuum_failsafe_age

Definition at line 71 of file vacuum.c.

Referenced by vacuum_xid_failsafe_check().

◆ vacuum_freeze_min_age

int vacuum_freeze_min_age

Definition at line 67 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_get_cutoffs().

◆ vacuum_freeze_table_age

int vacuum_freeze_table_age

Definition at line 68 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_get_cutoffs().

◆ vacuum_multixact_failsafe_age

int vacuum_multixact_failsafe_age

Definition at line 72 of file vacuum.c.

Referenced by vacuum_xid_failsafe_check().

◆ vacuum_multixact_freeze_min_age

int vacuum_multixact_freeze_min_age

Definition at line 69 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_get_cutoffs().

◆ vacuum_multixact_freeze_table_age

int vacuum_multixact_freeze_table_age

Definition at line 70 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_get_cutoffs().

◆ VacuumActiveNWorkers

◆ VacuumCostBalanceLocal

int VacuumCostBalanceLocal = 0

◆ VacuumFailsafeActive

◆ VacuumSharedCostBalance

pg_atomic_uint32* VacuumSharedCostBalance = NULL