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 "catalog/pg_namespace.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 "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/acl.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/pg_rusage.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, int options)
 
static Listget_all_vacuum_rels (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)
 
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)
 
void ExecVacuum (ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)
 
void vacuum (List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
 
bool vacuum_is_permitted_for_relation (Oid relid, Form_pg_class reltuple, bits32 options)
 
Relation vacuum_open_relation (Oid relid, RangeVar *relation, bits32 options, bool verbose, LOCKMODE lmode)
 
bool vacuum_set_xid_limits (Relation rel, const VacuumParams *params, TransactionId *OldestXmin, MultiXactId *OldestMxact, TransactionId *FreezeLimit, MultiXactId *MultiXactCutoff)
 
bool vacuum_xid_failsafe_check (TransactionId relfrozenxid, MultiXactId relminmxid)
 
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
 
static MemoryContext vac_context = NULL
 
static BufferAccessStrategy vac_strategy
 
pg_atomic_uint32VacuumSharedCostBalance = NULL
 
pg_atomic_uint32VacuumActiveNWorkers = NULL
 
int VacuumCostBalanceLocal = 0
 

Function Documentation

◆ compute_parallel_delay()

static double compute_parallel_delay ( void  )
static

Definition at line 2230 of file vacuum.c.

2231 {
2232  double msec = 0;
2233  uint32 shared_balance;
2234  int nworkers;
2235 
2236  /* Parallel vacuum must be active */
2238 
2240 
2241  /* At least count itself */
2242  Assert(nworkers >= 1);
2243 
2244  /* Update the shared cost balance value atomically */
2246 
2247  /* Compute the total local balance for the current worker */
2249 
2250  if ((shared_balance >= VacuumCostLimit) &&
2251  (VacuumCostBalanceLocal > 0.5 * ((double) VacuumCostLimit / nworkers)))
2252  {
2253  /* Compute sleep time based on the local cost balance */
2257  }
2258 
2259  /*
2260  * Reset the local balance as we accumulated it into the shared value.
2261  */
2262  VacuumCostBalance = 0;
2263 
2264  return msec;
2265 }
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition: atomics.h:396
static uint32 pg_atomic_add_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 add_)
Definition: atomics.h:381
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:236
unsigned int uint32
Definition: c.h:442
int VacuumCostLimit
Definition: globals.c:145
int VacuumCostBalance
Definition: globals.c:152
double VacuumCostDelay
Definition: globals.c:146
Assert(fmt[strlen(fmt) - 1] !='\n')
pg_atomic_uint32 * VacuumActiveNWorkers
Definition: vacuum.c:84
int VacuumCostBalanceLocal
Definition: vacuum.c:85
pg_atomic_uint32 * VacuumSharedCostBalance
Definition: vacuum.c:83

References Assert(), pg_atomic_add_fetch_u32(), pg_atomic_read_u32(), pg_atomic_sub_fetch_u32(), VacuumActiveNWorkers, VacuumCostBalance, VacuumCostBalanceLocal, VacuumCostDelay, VacuumCostLimit, and VacuumSharedCostBalance.

Referenced by vacuum_delay_point().

◆ ExecVacuum()

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

Definition at line 107 of file vacuum.c.

108 {
109  VacuumParams params;
110  bool verbose = false;
111  bool skip_locked = false;
112  bool analyze = false;
113  bool freeze = false;
114  bool full = false;
115  bool disable_page_skipping = false;
116  bool process_toast = true;
117  ListCell *lc;
118 
119  /* index_cleanup and truncate values unspecified for now */
122 
123  /* By default parallel vacuum is enabled */
124  params.nworkers = 0;
125 
126  /* Parse options list */
127  foreach(lc, vacstmt->options)
128  {
129  DefElem *opt = (DefElem *) lfirst(lc);
130 
131  /* Parse common options for VACUUM and ANALYZE */
132  if (strcmp(opt->defname, "verbose") == 0)
133  verbose = defGetBoolean(opt);
134  else if (strcmp(opt->defname, "skip_locked") == 0)
135  skip_locked = defGetBoolean(opt);
136  else if (!vacstmt->is_vacuumcmd)
137  ereport(ERROR,
138  (errcode(ERRCODE_SYNTAX_ERROR),
139  errmsg("unrecognized ANALYZE option \"%s\"", opt->defname),
140  parser_errposition(pstate, opt->location)));
141 
142  /* Parse options available on VACUUM */
143  else if (strcmp(opt->defname, "analyze") == 0)
144  analyze = defGetBoolean(opt);
145  else if (strcmp(opt->defname, "freeze") == 0)
146  freeze = defGetBoolean(opt);
147  else if (strcmp(opt->defname, "full") == 0)
148  full = defGetBoolean(opt);
149  else if (strcmp(opt->defname, "disable_page_skipping") == 0)
150  disable_page_skipping = defGetBoolean(opt);
151  else if (strcmp(opt->defname, "index_cleanup") == 0)
152  {
153  /* Interpret no string as the default, which is 'auto' */
154  if (!opt->arg)
156  else
157  {
158  char *sval = defGetString(opt);
159 
160  /* Try matching on 'auto' string, or fall back on boolean */
161  if (pg_strcasecmp(sval, "auto") == 0)
163  else
165  }
166  }
167  else if (strcmp(opt->defname, "process_toast") == 0)
168  process_toast = defGetBoolean(opt);
169  else if (strcmp(opt->defname, "truncate") == 0)
170  params.truncate = get_vacoptval_from_boolean(opt);
171  else if (strcmp(opt->defname, "parallel") == 0)
172  {
173  if (opt->arg == NULL)
174  {
175  ereport(ERROR,
176  (errcode(ERRCODE_SYNTAX_ERROR),
177  errmsg("parallel option requires a value between 0 and %d",
179  parser_errposition(pstate, opt->location)));
180  }
181  else
182  {
183  int nworkers;
184 
185  nworkers = defGetInt32(opt);
186  if (nworkers < 0 || nworkers > MAX_PARALLEL_WORKER_LIMIT)
187  ereport(ERROR,
188  (errcode(ERRCODE_SYNTAX_ERROR),
189  errmsg("parallel workers for vacuum must be between 0 and %d",
191  parser_errposition(pstate, opt->location)));
192 
193  /*
194  * Disable parallel vacuum, if user has specified parallel
195  * degree as zero.
196  */
197  if (nworkers == 0)
198  params.nworkers = -1;
199  else
200  params.nworkers = nworkers;
201  }
202  }
203  else
204  ereport(ERROR,
205  (errcode(ERRCODE_SYNTAX_ERROR),
206  errmsg("unrecognized VACUUM option \"%s\"", opt->defname),
207  parser_errposition(pstate, opt->location)));
208  }
209 
210  /* Set vacuum options */
211  params.options =
212  (vacstmt->is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE) |
213  (verbose ? VACOPT_VERBOSE : 0) |
214  (skip_locked ? VACOPT_SKIP_LOCKED : 0) |
215  (analyze ? VACOPT_ANALYZE : 0) |
216  (freeze ? VACOPT_FREEZE : 0) |
217  (full ? VACOPT_FULL : 0) |
218  (disable_page_skipping ? VACOPT_DISABLE_PAGE_SKIPPING : 0) |
219  (process_toast ? VACOPT_PROCESS_TOAST : 0);
220 
221  /* sanity checks on options */
223  Assert((params.options & VACOPT_VACUUM) ||
224  !(params.options & (VACOPT_FULL | VACOPT_FREEZE)));
225 
226  if ((params.options & VACOPT_FULL) && params.nworkers > 0)
227  ereport(ERROR,
228  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
229  errmsg("VACUUM FULL cannot be performed in parallel")));
230 
231  /*
232  * Make sure VACOPT_ANALYZE is specified if any column lists are present.
233  */
234  if (!(params.options & VACOPT_ANALYZE))
235  {
236  foreach(lc, vacstmt->rels)
237  {
239 
240  if (vrel->va_cols != NIL)
241  ereport(ERROR,
242  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
243  errmsg("ANALYZE option must be specified when a column list is provided")));
244  }
245  }
246 
247  /*
248  * All freeze ages are zero if the FREEZE option is given; otherwise pass
249  * them as -1 which means to use the default values.
250  */
251  if (params.options & VACOPT_FREEZE)
252  {
253  params.freeze_min_age = 0;
254  params.freeze_table_age = 0;
255  params.multixact_freeze_min_age = 0;
256  params.multixact_freeze_table_age = 0;
257  }
258  else
259  {
260  params.freeze_min_age = -1;
261  params.freeze_table_age = -1;
262  params.multixact_freeze_min_age = -1;
263  params.multixact_freeze_table_age = -1;
264  }
265 
266  /* user-invoked vacuum is never "for wraparound" */
267  params.is_wraparound = false;
268 
269  /* user-invoked vacuum uses VACOPT_VERBOSE instead of log_min_duration */
270  params.log_min_duration = -1;
271 
272  /* Now go through the common routine */
273  vacuum(vacstmt->rels, &params, NULL, isTopLevel);
274 }
#define MAX_PARALLEL_WORKER_LIMIT
int32 defGetInt32(DefElem *def)
Definition: define.c:163
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
int errcode(int sqlerrcode)
Definition: elog.c:735
int errmsg(const char *fmt,...)
Definition: elog.c:946
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
static int verbose
#define lfirst(lc)
Definition: pg_list.h:170
#define lfirst_node(type, lc)
Definition: pg_list.h:174
#define NIL
Definition: pg_list.h:66
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
static long analyze(struct nfa *nfa)
Definition: regc_nfa.c:3044
char * defname
Definition: parsenodes.h:779
int location
Definition: parsenodes.h:783
Node * arg
Definition: parsenodes.h:780
int nworkers
Definition: vacuum.h:235
int freeze_table_age
Definition: vacuum.h:218
VacOptValue truncate
Definition: vacuum.h:228
bits32 options
Definition: vacuum.h:216
int freeze_min_age
Definition: vacuum.h:217
bool is_wraparound
Definition: vacuum.h:223
int multixact_freeze_min_age
Definition: vacuum.h:219
int multixact_freeze_table_age
Definition: vacuum.h:221
int log_min_duration
Definition: vacuum.h:224
VacOptValue index_cleanup
Definition: vacuum.h:227
List * options
Definition: parsenodes.h:3474
bool is_vacuumcmd
Definition: parsenodes.h:3476
List * rels
Definition: parsenodes.h:3475
static VacOptValue get_vacoptval_from_boolean(DefElem *def)
Definition: vacuum.c:2274
void vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:296
#define VACOPT_FREEZE
Definition: vacuum.h:186
#define VACOPT_SKIP_LOCKED
Definition: vacuum.h:188
#define VACOPT_VACUUM
Definition: vacuum.h:183
#define VACOPT_VERBOSE
Definition: vacuum.h:185
#define VACOPT_FULL
Definition: vacuum.h:187
@ VACOPTVALUE_AUTO
Definition: vacuum.h:203
@ VACOPTVALUE_UNSPECIFIED
Definition: vacuum.h:202
#define VACOPT_PROCESS_TOAST
Definition: vacuum.h:189
#define VACOPT_DISABLE_PAGE_SKIPPING
Definition: vacuum.h:190
#define VACOPT_ANALYZE
Definition: vacuum.h:184

References analyze(), DefElem::arg, Assert(), defGetBoolean(), defGetInt32(), defGetString(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, get_vacoptval_from_boolean(), VacuumParams::index_cleanup, VacuumStmt::is_vacuumcmd, VacuumParams::is_wraparound, lfirst, lfirst_node, DefElem::location, VacuumParams::log_min_duration, MAX_PARALLEL_WORKER_LIMIT, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, NIL, VacuumParams::nworkers, VacuumParams::options, VacuumStmt::options, parser_errposition(), pg_strcasecmp(), VacuumStmt::rels, VacuumParams::truncate, VacuumRelation::va_cols, VACOPT_ANALYZE, VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_FREEZE, VACOPT_FULL, VACOPT_PROCESS_TOAST, VACOPT_SKIP_LOCKED, VACOPT_VACUUM, VACOPT_VERBOSE, VACOPTVALUE_AUTO, VACOPTVALUE_UNSPECIFIED, vacuum(), and verbose.

Referenced by standard_ProcessUtility().

◆ expand_vacuum_rel()

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

Definition at line 726 of file vacuum.c.

727 {
728  List *vacrels = NIL;
729  MemoryContext oldcontext;
730 
731  /* If caller supplied OID, there's nothing we need do here. */
732  if (OidIsValid(vrel->oid))
733  {
734  oldcontext = MemoryContextSwitchTo(vac_context);
735  vacrels = lappend(vacrels, vrel);
736  MemoryContextSwitchTo(oldcontext);
737  }
738  else
739  {
740  /* Process a specific relation, and possibly partitions thereof */
741  Oid relid;
742  HeapTuple tuple;
743  Form_pg_class classForm;
744  bool include_parts;
745  int rvr_opts;
746 
747  /*
748  * Since autovacuum workers supply OIDs when calling vacuum(), no
749  * autovacuum worker should reach this code.
750  */
752 
753  /*
754  * We transiently take AccessShareLock to protect the syscache lookup
755  * below, as well as find_all_inheritors's expectation that the caller
756  * holds some lock on the starting relation.
757  */
758  rvr_opts = (options & VACOPT_SKIP_LOCKED) ? RVR_SKIP_LOCKED : 0;
759  relid = RangeVarGetRelidExtended(vrel->relation,
761  rvr_opts,
762  NULL, NULL);
763 
764  /*
765  * If the lock is unavailable, emit the same log statement that
766  * vacuum_rel() and analyze_rel() would.
767  */
768  if (!OidIsValid(relid))
769  {
770  if (options & VACOPT_VACUUM)
772  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
773  errmsg("skipping vacuum of \"%s\" --- lock not available",
774  vrel->relation->relname)));
775  else
777  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
778  errmsg("skipping analyze of \"%s\" --- lock not available",
779  vrel->relation->relname)));
780  return vacrels;
781  }
782 
783  /*
784  * To check whether the relation is a partitioned table and its
785  * ownership, fetch its syscache entry.
786  */
787  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
788  if (!HeapTupleIsValid(tuple))
789  elog(ERROR, "cache lookup failed for relation %u", relid);
790  classForm = (Form_pg_class) GETSTRUCT(tuple);
791 
792  /*
793  * Make a returnable VacuumRelation for this rel if the user has the
794  * required privileges.
795  */
796  if (vacuum_is_permitted_for_relation(relid, classForm, options))
797  {
798  oldcontext = MemoryContextSwitchTo(vac_context);
799  vacrels = lappend(vacrels, makeVacuumRelation(vrel->relation,
800  relid,
801  vrel->va_cols));
802  MemoryContextSwitchTo(oldcontext);
803  }
804 
805 
806  include_parts = (classForm->relkind == RELKIND_PARTITIONED_TABLE);
807  ReleaseSysCache(tuple);
808 
809  /*
810  * If it is, make relation list entries for its partitions. Note that
811  * the list returned by find_all_inheritors() includes the passed-in
812  * OID, so we have to skip that. There's no point in taking locks on
813  * the individual partitions yet, and doing so would just add
814  * unnecessary deadlock risk. For this last reason we do not check
815  * yet the ownership of the partitions, which get added to the list to
816  * process. Ownership will be checked later on anyway.
817  */
818  if (include_parts)
819  {
820  List *part_oids = find_all_inheritors(relid, NoLock, NULL);
821  ListCell *part_lc;
822 
823  foreach(part_lc, part_oids)
824  {
825  Oid part_oid = lfirst_oid(part_lc);
826 
827  if (part_oid == relid)
828  continue; /* ignore original table */
829 
830  /*
831  * We omit a RangeVar since it wouldn't be appropriate to
832  * complain about failure to open one of these relations
833  * later.
834  */
835  oldcontext = MemoryContextSwitchTo(vac_context);
836  vacrels = lappend(vacrels, makeVacuumRelation(NULL,
837  part_oid,
838  vrel->va_cols));
839  MemoryContextSwitchTo(oldcontext);
840  }
841  }
842 
843  /*
844  * Release lock again. This means that by the time we actually try to
845  * process the table, it might be gone or renamed. In the former case
846  * we'll silently ignore it; in the latter case we'll process it
847  * anyway, but we must beware that the RangeVar doesn't necessarily
848  * identify it anymore. This isn't ideal, perhaps, but there's little
849  * practical alternative, since we're typically going to commit this
850  * transaction and begin a new one between now and then. Moreover,
851  * holding locks on multiple relations would create significant risk
852  * of deadlock.
853  */
855  }
856 
857  return vacrels;
858 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3314
#define OidIsValid(objectId)
Definition: c.h:711
#define WARNING
Definition: elog.h:32
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
List * lappend(List *list, void *datum)
Definition: list.c:338
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:228
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
VacuumRelation * makeVacuumRelation(RangeVar *relation, Oid oid, List *va_cols)
Definition: makefuncs.c:812
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition: namespace.c:239
@ RVR_SKIP_LOCKED
Definition: namespace.h:73
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:135
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:256
#define lfirst_oid(lc)
Definition: pg_list.h:172
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
unsigned int Oid
Definition: postgres_ext.h:31
Definition: pg_list.h:52
char * relname
Definition: primnodes.h:77
RangeVar * relation
Definition: parsenodes.h:3489
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ RELOID
Definition: syscache.h:89
static MemoryContext vac_context
Definition: vacuum.c:75
bool vacuum_is_permitted_for_relation(Oid relid, Form_pg_class reltuple, bits32 options)
Definition: vacuum.c:556

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

Referenced by vacuum().

◆ get_all_vacuum_rels()

static List * get_all_vacuum_rels ( int  options)
static

Definition at line 865 of file vacuum.c.

866 {
867  List *vacrels = NIL;
868  Relation pgclass;
869  TableScanDesc scan;
870  HeapTuple tuple;
871 
872  pgclass = table_open(RelationRelationId, AccessShareLock);
873 
874  scan = table_beginscan_catalog(pgclass, 0, NULL);
875 
876  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
877  {
878  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
879  MemoryContext oldcontext;
880  Oid relid = classForm->oid;
881 
882  /* check permissions of relation */
883  if (!vacuum_is_permitted_for_relation(relid, classForm, options))
884  continue;
885 
886  /*
887  * We include partitioned tables here; depending on which operation is
888  * to be performed, caller will decide whether to process or ignore
889  * them.
890  */
891  if (classForm->relkind != RELKIND_RELATION &&
892  classForm->relkind != RELKIND_MATVIEW &&
893  classForm->relkind != RELKIND_PARTITIONED_TABLE)
894  continue;
895 
896  /*
897  * Build VacuumRelation(s) specifying the table OIDs to be processed.
898  * We omit a RangeVar since it wouldn't be appropriate to complain
899  * about failure to open one of these relations later.
900  */
901  oldcontext = MemoryContextSwitchTo(vac_context);
902  vacrels = lappend(vacrels, makeVacuumRelation(NULL,
903  relid,
904  NIL));
905  MemoryContextSwitchTo(oldcontext);
906  }
907 
908  table_endscan(scan);
909  table_close(pgclass, AccessShareLock);
910 
911  return vacrels;
912 }
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1299
@ ForwardScanDirection
Definition: sdir.h:26
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:993

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

Referenced by vacuum().

◆ get_vacoptval_from_boolean()

static VacOptValue get_vacoptval_from_boolean ( DefElem def)
static

Definition at line 2274 of file vacuum.c.

2275 {
2277 }
@ VACOPTVALUE_ENABLED
Definition: vacuum.h:205
@ VACOPTVALUE_DISABLED
Definition: vacuum.h:204

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 2285 of file vacuum.c.

2287 {
2288  /* Do bulk deletion */
2289  istat = index_bulk_delete(ivinfo, istat, vac_tid_reaped,
2290  (void *) dead_items);
2291 
2292  ereport(ivinfo->message_level,
2293  (errmsg("scanned index \"%s\" to remove %d row versions",
2294  RelationGetRelationName(ivinfo->index),
2295  dead_items->num_items)));
2296 
2297  return istat;
2298 }
IndexBulkDeleteResult * index_bulk_delete(IndexVacuumInfo *info, IndexBulkDeleteResult *istat, IndexBulkDeleteCallback callback, void *callback_state)
Definition: indexam.c:699
#define RelationGetRelationName(relation)
Definition: rel.h:535
Relation index
Definition: genam.h:46
int message_level
Definition: genam.h:50
int num_items
Definition: vacuum.h:244
static bool vac_tid_reaped(ItemPointer itemptr, void *state)
Definition: vacuum.c:2346

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 2306 of file vacuum.c.

2307 {
2308  istat = index_vacuum_cleanup(ivinfo, istat);
2309 
2310  if (istat)
2311  ereport(ivinfo->message_level,
2312  (errmsg("index \"%s\" now contains %.0f row versions in %u pages",
2313  RelationGetRelationName(ivinfo->index),
2314  istat->num_index_tuples,
2315  istat->num_pages),
2316  errdetail("%.0f index row versions were removed.\n"
2317  "%u index pages were newly deleted.\n"
2318  "%u index pages are currently deleted, of which %u are currently reusable.",
2319  istat->tuples_removed,
2320  istat->pages_newly_deleted,
2321  istat->pages_deleted, istat->pages_free)));
2322 
2323  return istat;
2324 }
int errdetail(const char *fmt,...)
Definition: elog.c:1079
IndexBulkDeleteResult * index_vacuum_cleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *istat)
Definition: indexam.c:720
BlockNumber pages_deleted
Definition: genam.h:81
BlockNumber pages_newly_deleted
Definition: genam.h:80
BlockNumber pages_free
Definition: genam.h:82
BlockNumber num_pages
Definition: genam.h:76
double tuples_removed
Definition: genam.h:79
double num_index_tuples
Definition: genam.h:78

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 2145 of file vacuum.c.

2146 {
2147  if (Irel == NULL)
2148  return;
2149 
2150  while (nindexes--)
2151  {
2152  Relation ind = Irel[nindexes];
2153 
2154  index_close(ind, lockmode);
2155  }
2156  pfree(Irel);
2157 }
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
void pfree(void *pointer)
Definition: mcxt.c:1306

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 2380 of file vacuum.c.

2381 {
2382  BlockNumber lblk,
2383  rblk;
2384  OffsetNumber loff,
2385  roff;
2386 
2387  lblk = ItemPointerGetBlockNumber((ItemPointer) left);
2388  rblk = ItemPointerGetBlockNumber((ItemPointer) right);
2389 
2390  if (lblk < rblk)
2391  return -1;
2392  if (lblk > rblk)
2393  return 1;
2394 
2395  loff = ItemPointerGetOffsetNumber((ItemPointer) left);
2396  roff = ItemPointerGetOffsetNumber((ItemPointer) right);
2397 
2398  if (loff < roff)
2399  return -1;
2400  if (loff > roff)
2401  return 1;
2402 
2403  return 0;
2404 }
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 1186 of file vacuum.c.

1190 {
1191  BlockNumber old_rel_pages = relation->rd_rel->relpages;
1192  double old_rel_tuples = relation->rd_rel->reltuples;
1193  double old_density;
1194  double unscanned_pages;
1195  double total_tuples;
1196 
1197  /* If we did scan the whole table, just use the count as-is */
1198  if (scanned_pages >= total_pages)
1199  return scanned_tuples;
1200 
1201  /*
1202  * When successive VACUUM commands scan the same few pages again and
1203  * again, without anything from the table really changing, there is a risk
1204  * that our beliefs about tuple density will gradually become distorted.
1205  * This might be caused by vacuumlazy.c implementation details, such as
1206  * its tendency to always scan the last heap page. Handle that here.
1207  *
1208  * If the relation is _exactly_ the same size according to the existing
1209  * pg_class entry, and only a few of its pages (less than 2%) were
1210  * scanned, keep the existing value of reltuples. Also keep the existing
1211  * value when only a subset of rel's pages <= a single page were scanned.
1212  *
1213  * (Note: we might be returning -1 here.)
1214  */
1215  if (old_rel_pages == total_pages &&
1216  scanned_pages < (double) total_pages * 0.02)
1217  return old_rel_tuples;
1218  if (scanned_pages <= 1)
1219  return old_rel_tuples;
1220 
1221  /*
1222  * If old density is unknown, we can't do much except scale up
1223  * scanned_tuples to match total_pages.
1224  */
1225  if (old_rel_tuples < 0 || old_rel_pages == 0)
1226  return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
1227 
1228  /*
1229  * Okay, we've covered the corner cases. The normal calculation is to
1230  * convert the old measurement to a density (tuples per page), then
1231  * estimate the number of tuples in the unscanned pages using that figure,
1232  * and finally add on the number of tuples in the scanned pages.
1233  */
1234  old_density = old_rel_tuples / old_rel_pages;
1235  unscanned_pages = (double) total_pages - (double) scanned_pages;
1236  total_tuples = old_density * unscanned_pages + scanned_tuples;
1237  return floor(total_tuples + 0.5);
1238 }
Form_pg_class rd_rel
Definition: rel.h:110

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 2331 of file vacuum.c.

2332 {
2333  Assert(max_items <= MAXDEADITEMS(MaxAllocSize));
2334 
2335  return offsetof(VacDeadItems, items) + sizeof(ItemPointerData) * max_items;
2336 }
struct ItemPointerData ItemPointerData
#define MaxAllocSize
Definition: memutils.h:40
#define MAXDEADITEMS(avail_mem)
Definition: vacuum.h:250

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 2102 of file vacuum.c.

2104 {
2105  List *indexoidlist;
2106  ListCell *indexoidscan;
2107  int i;
2108 
2109  Assert(lockmode != NoLock);
2110 
2111  indexoidlist = RelationGetIndexList(relation);
2112 
2113  /* allocate enough memory for all indexes */
2114  i = list_length(indexoidlist);
2115 
2116  if (i > 0)
2117  *Irel = (Relation *) palloc(i * sizeof(Relation));
2118  else
2119  *Irel = NULL;
2120 
2121  /* collect just the ready indexes */
2122  i = 0;
2123  foreach(indexoidscan, indexoidlist)
2124  {
2125  Oid indexoid = lfirst_oid(indexoidscan);
2126  Relation indrel;
2127 
2128  indrel = index_open(indexoid, lockmode);
2129  if (indrel->rd_index->indisready)
2130  (*Irel)[i++] = indrel;
2131  else
2132  index_close(indrel, lockmode);
2133  }
2134 
2135  *nindexes = i;
2136 
2137  list_free(indexoidlist);
2138 }
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
int i
Definition: isn.c:73
void list_free(List *list)
Definition: list.c:1545
void * palloc(Size size)
Definition: mcxt.c:1199
static int list_length(const List *l)
Definition: pg_list.h:150
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4738
Form_pg_index rd_index
Definition: rel.h:188

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 2346 of file vacuum.c.

2347 {
2348  VacDeadItems *dead_items = (VacDeadItems *) state;
2349  int64 litem,
2350  ritem,
2351  item;
2352  ItemPointer res;
2353 
2354  litem = itemptr_encode(&dead_items->items[0]);
2355  ritem = itemptr_encode(&dead_items->items[dead_items->num_items - 1]);
2356  item = itemptr_encode(itemptr);
2357 
2358  /*
2359  * Doing a simple bound check before bsearch() is useful to avoid the
2360  * extra cost of bsearch(), especially if dead items on the heap are
2361  * concentrated in a certain range. Since this function is called for
2362  * every index tuple, it pays to be really fast.
2363  */
2364  if (item < litem || item > ritem)
2365  return false;
2366 
2367  res = (ItemPointer) bsearch((void *) itemptr,
2368  (void *) dead_items->items,
2369  dead_items->num_items,
2370  sizeof(ItemPointerData),
2371  vac_cmp_itemptr);
2372 
2373  return (res != NULL);
2374 }
static int64 itemptr_encode(ItemPointer itemptr)
Definition: index.h:185
ItemPointerData * ItemPointer
Definition: itemptr.h:49
ItemPointerData items[FLEXIBLE_ARRAY_MEMBER]
Definition: vacuum.h:247
Definition: regguts.h:318
static int vac_cmp_itemptr(const void *left, const void *right)
Definition: vacuum.c:2380

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 1663 of file vacuum.c.

1667 {
1669  Relation relation;
1670  TableScanDesc scan;
1671  HeapTuple tuple;
1672  Oid oldestxid_datoid;
1673  Oid minmulti_datoid;
1674  bool bogus = false;
1675  bool frozenAlreadyWrapped = false;
1676 
1677  /* Restrict task to one backend per cluster; see SimpleLruTruncate(). */
1678  LWLockAcquire(WrapLimitsVacuumLock, LW_EXCLUSIVE);
1679 
1680  /* init oldest datoids to sync with my frozenXID/minMulti values */
1681  oldestxid_datoid = MyDatabaseId;
1682  minmulti_datoid = MyDatabaseId;
1683 
1684  /*
1685  * Scan pg_database to compute the minimum datfrozenxid/datminmxid
1686  *
1687  * Since vac_update_datfrozenxid updates datfrozenxid/datminmxid in-place,
1688  * the values could change while we look at them. Fetch each one just
1689  * once to ensure sane behavior of the comparison logic. (Here, as in
1690  * many other places, we assume that fetching or updating an XID in shared
1691  * storage is atomic.)
1692  *
1693  * Note: we need not worry about a race condition with new entries being
1694  * inserted by CREATE DATABASE. Any such entry will have a copy of some
1695  * existing DB's datfrozenxid, and that source DB cannot be ours because
1696  * of the interlock against copying a DB containing an active backend.
1697  * Hence the new entry will not reduce the minimum. Also, if two VACUUMs
1698  * concurrently modify the datfrozenxid's of different databases, the
1699  * worst possible outcome is that pg_xact is not truncated as aggressively
1700  * as it could be.
1701  */
1702  relation = table_open(DatabaseRelationId, AccessShareLock);
1703 
1704  scan = table_beginscan_catalog(relation, 0, NULL);
1705 
1706  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1707  {
1708  volatile FormData_pg_database *dbform = (Form_pg_database) GETSTRUCT(tuple);
1709  TransactionId datfrozenxid = dbform->datfrozenxid;
1710  TransactionId datminmxid = dbform->datminmxid;
1711 
1714 
1715  /*
1716  * If things are working properly, no database should have a
1717  * datfrozenxid or datminmxid that is "in the future". However, such
1718  * cases have been known to arise due to bugs in pg_upgrade. If we
1719  * see any entries that are "in the future", chicken out and don't do
1720  * anything. This ensures we won't truncate clog before those
1721  * databases have been scanned and cleaned up. (We will issue the
1722  * "already wrapped" warning if appropriate, though.)
1723  */
1724  if (TransactionIdPrecedes(lastSaneFrozenXid, datfrozenxid) ||
1725  MultiXactIdPrecedes(lastSaneMinMulti, datminmxid))
1726  bogus = true;
1727 
1728  if (TransactionIdPrecedes(nextXID, datfrozenxid))
1729  frozenAlreadyWrapped = true;
1730  else if (TransactionIdPrecedes(datfrozenxid, frozenXID))
1731  {
1732  frozenXID = datfrozenxid;
1733  oldestxid_datoid = dbform->oid;
1734  }
1735 
1736  if (MultiXactIdPrecedes(datminmxid, minMulti))
1737  {
1738  minMulti = datminmxid;
1739  minmulti_datoid = dbform->oid;
1740  }
1741  }
1742 
1743  table_endscan(scan);
1744 
1745  table_close(relation, AccessShareLock);
1746 
1747  /*
1748  * Do not truncate CLOG if we seem to have suffered wraparound already;
1749  * the computed minimum XID might be bogus. This case should now be
1750  * impossible due to the defenses in GetNewTransactionId, but we keep the
1751  * test anyway.
1752  */
1753  if (frozenAlreadyWrapped)
1754  {
1755  ereport(WARNING,
1756  (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
1757  errdetail("You might have already suffered transaction-wraparound data loss.")));
1758  return;
1759  }
1760 
1761  /* chicken out if data is bogus in any other way */
1762  if (bogus)
1763  return;
1764 
1765  /*
1766  * Advance the oldest value for commit timestamps before truncating, so
1767  * that if a user requests a timestamp for a transaction we're truncating
1768  * away right after this point, they get NULL instead of an ugly "file not
1769  * found" error from slru.c. This doesn't matter for xact/multixact
1770  * because they are not subject to arbitrary lookups from users.
1771  */
1772  AdvanceOldestCommitTsXid(frozenXID);
1773 
1774  /*
1775  * Truncate CLOG, multixact and CommitTs to the oldest computed value.
1776  */
1777  TruncateCLOG(frozenXID, oldestxid_datoid);
1778  TruncateCommitTs(frozenXID);
1779  TruncateMultiXact(minMulti, minmulti_datoid);
1780 
1781  /*
1782  * Update the wrap limit for GetNewTransactionId and creation of new
1783  * MultiXactIds. Note: these functions will also signal the postmaster
1784  * for an(other) autovac cycle if needed. XXX should we avoid possibly
1785  * signaling twice?
1786  */
1787  SetTransactionIdLimit(frozenXID, oldestxid_datoid);
1788  SetMultiXactIdLimit(minMulti, minmulti_datoid, false);
1789 
1790  LWLockRelease(WrapLimitsVacuumLock);
1791 }
uint32 TransactionId
Definition: c.h:588
void TruncateCLOG(TransactionId oldestXact, Oid oldestxid_datoid)
Definition: clog.c:878
void AdvanceOldestCommitTsXid(TransactionId oldestXact)
Definition: commit_ts.c:905
void TruncateCommitTs(TransactionId oldestXact)
Definition: commit_ts.c:852
Oid MyDatabaseId
Definition: globals.c:89
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1194
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1802
@ LW_EXCLUSIVE
Definition: lwlock.h:112
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3157
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2211
void TruncateMultiXact(MultiXactId newOldestMulti, Oid newOldestMultiDB)
Definition: multixact.c:2942
#define MultiXactIdIsValid(multi)
Definition: multixact.h:28
TransactionId datfrozenxid
Definition: pg_database.h:56
TransactionId datminmxid
Definition: pg_database.h:59
FormData_pg_database * Form_pg_database
Definition: pg_database.h:87
FormData_pg_database
Definition: pg_database.h:80
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:273
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:345

References AccessShareLock, AdvanceOldestCommitTsXid(), Assert(), datfrozenxid, datminmxid, ereport, errdetail(), errmsg(), FormData_pg_database, ForwardScanDirection, GETSTRUCT, heap_getnext(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MultiXactIdIsValid, MultiXactIdPrecedes(), MyDatabaseId, 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 1449 of file vacuum.c.

1450 {
1451  HeapTuple tuple;
1452  Form_pg_database dbform;
1453  Relation relation;
1454  SysScanDesc scan;
1455  HeapTuple classTup;
1456  TransactionId newFrozenXid;
1457  MultiXactId newMinMulti;
1458  TransactionId lastSaneFrozenXid;
1459  MultiXactId lastSaneMinMulti;
1460  bool bogus = false;
1461  bool dirty = false;
1462  ScanKeyData key[1];
1463 
1464  /*
1465  * Restrict this task to one backend per database. This avoids race
1466  * conditions that would move datfrozenxid or datminmxid backward. It
1467  * avoids calling vac_truncate_clog() with a datfrozenxid preceding a
1468  * datfrozenxid passed to an earlier vac_truncate_clog() call.
1469  */
1471 
1472  /*
1473  * Initialize the "min" calculation with
1474  * GetOldestNonRemovableTransactionId(), which is a reasonable
1475  * approximation to the minimum relfrozenxid for not-yet-committed
1476  * pg_class entries for new tables; see AddNewRelationTuple(). So we
1477  * cannot produce a wrong minimum by starting with this.
1478  */
1479  newFrozenXid = GetOldestNonRemovableTransactionId(NULL);
1480 
1481  /*
1482  * Similarly, initialize the MultiXact "min" with the value that would be
1483  * used on pg_class for new tables. See AddNewRelationTuple().
1484  */
1485  newMinMulti = GetOldestMultiXactId();
1486 
1487  /*
1488  * Identify the latest relfrozenxid and relminmxid values that we could
1489  * validly see during the scan. These are conservative values, but it's
1490  * not really worth trying to be more exact.
1491  */
1492  lastSaneFrozenXid = ReadNextTransactionId();
1493  lastSaneMinMulti = ReadNextMultiXactId();
1494 
1495  /*
1496  * We must seqscan pg_class to find the minimum Xid, because there is no
1497  * index that can help us here.
1498  */
1499  relation = table_open(RelationRelationId, AccessShareLock);
1500 
1501  scan = systable_beginscan(relation, InvalidOid, false,
1502  NULL, 0, NULL);
1503 
1504  while ((classTup = systable_getnext(scan)) != NULL)
1505  {
1506  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
1507 
1508  /*
1509  * Only consider relations able to hold unfrozen XIDs (anything else
1510  * should have InvalidTransactionId in relfrozenxid anyway).
1511  */
1512  if (classForm->relkind != RELKIND_RELATION &&
1513  classForm->relkind != RELKIND_MATVIEW &&
1514  classForm->relkind != RELKIND_TOASTVALUE)
1515  {
1516  Assert(!TransactionIdIsValid(classForm->relfrozenxid));
1517  Assert(!MultiXactIdIsValid(classForm->relminmxid));
1518  continue;
1519  }
1520 
1521  /*
1522  * Some table AMs might not need per-relation xid / multixid horizons.
1523  * It therefore seems reasonable to allow relfrozenxid and relminmxid
1524  * to not be set (i.e. set to their respective Invalid*Id)
1525  * independently. Thus validate and compute horizon for each only if
1526  * set.
1527  *
1528  * If things are working properly, no relation should have a
1529  * relfrozenxid or relminmxid that is "in the future". However, such
1530  * cases have been known to arise due to bugs in pg_upgrade. If we
1531  * see any entries that are "in the future", chicken out and don't do
1532  * anything. This ensures we won't truncate clog & multixact SLRUs
1533  * before those relations have been scanned and cleaned up.
1534  */
1535 
1536  if (TransactionIdIsValid(classForm->relfrozenxid))
1537  {
1538  Assert(TransactionIdIsNormal(classForm->relfrozenxid));
1539 
1540  /* check for values in the future */
1541  if (TransactionIdPrecedes(lastSaneFrozenXid, classForm->relfrozenxid))
1542  {
1543  bogus = true;
1544  break;
1545  }
1546 
1547  /* determine new horizon */
1548  if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
1549  newFrozenXid = classForm->relfrozenxid;
1550  }
1551 
1552  if (MultiXactIdIsValid(classForm->relminmxid))
1553  {
1554  /* check for values in the future */
1555  if (MultiXactIdPrecedes(lastSaneMinMulti, classForm->relminmxid))
1556  {
1557  bogus = true;
1558  break;
1559  }
1560 
1561  /* determine new horizon */
1562  if (MultiXactIdPrecedes(classForm->relminmxid, newMinMulti))
1563  newMinMulti = classForm->relminmxid;
1564  }
1565  }
1566 
1567  /* we're done with pg_class */
1568  systable_endscan(scan);
1569  table_close(relation, AccessShareLock);
1570 
1571  /* chicken out if bogus data found */
1572  if (bogus)
1573  return;
1574 
1575  Assert(TransactionIdIsNormal(newFrozenXid));
1576  Assert(MultiXactIdIsValid(newMinMulti));
1577 
1578  /* Now fetch the pg_database tuple we need to update. */
1579  relation = table_open(DatabaseRelationId, RowExclusiveLock);
1580 
1581  /*
1582  * Get the pg_database tuple to scribble on. Note that this does not
1583  * directly rely on the syscache to avoid issues with flattened toast
1584  * values for the in-place update.
1585  */
1586  ScanKeyInit(&key[0],
1587  Anum_pg_database_oid,
1588  BTEqualStrategyNumber, F_OIDEQ,
1590 
1591  scan = systable_beginscan(relation, DatabaseOidIndexId, true,
1592  NULL, 1, key);
1593  tuple = systable_getnext(scan);
1594  tuple = heap_copytuple(tuple);
1595  systable_endscan(scan);
1596 
1597  if (!HeapTupleIsValid(tuple))
1598  elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
1599 
1600  dbform = (Form_pg_database) GETSTRUCT(tuple);
1601 
1602  /*
1603  * As in vac_update_relstats(), we ordinarily don't want to let
1604  * datfrozenxid go backward; but if it's "in the future" then it must be
1605  * corrupt and it seems best to overwrite it.
1606  */
1607  if (dbform->datfrozenxid != newFrozenXid &&
1608  (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) ||
1609  TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid)))
1610  {
1611  dbform->datfrozenxid = newFrozenXid;
1612  dirty = true;
1613  }
1614  else
1615  newFrozenXid = dbform->datfrozenxid;
1616 
1617  /* Ditto for datminmxid */
1618  if (dbform->datminmxid != newMinMulti &&
1619  (MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) ||
1620  MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid)))
1621  {
1622  dbform->datminmxid = newMinMulti;
1623  dirty = true;
1624  }
1625  else
1626  newMinMulti = dbform->datminmxid;
1627 
1628  if (dirty)
1629  heap_inplace_update(relation, tuple);
1630 
1631  heap_freetuple(tuple);
1632  table_close(relation, RowExclusiveLock);
1633 
1634  /*
1635  * If we were able to advance datfrozenxid or datminmxid, see if we can
1636  * truncate pg_xact and/or pg_multixact. Also do it if the shared
1637  * XID-wrap-limit info is stale, since this action will update that too.
1638  */
1639  if (dirty || ForceTransactionIdLimitUpdate())
1640  vac_truncate_clog(newFrozenXid, newMinMulti,
1641  lastSaneFrozenXid, lastSaneMinMulti);
1642 }
TransactionId MultiXactId
Definition: c.h:598
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:6009
HeapTuple heap_copytuple(HeapTuple tuple)
Definition: heaptuple.c:680
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void LockDatabaseFrozenIds(LOCKMODE lockmode)
Definition: lmgr.c:498
#define ExclusiveLock
Definition: lockdefs.h:42
#define RowExclusiveLock
Definition: lockdefs.h:38
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2504
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:722
#define InvalidOid
Definition: postgres_ext.h:36
TransactionId GetOldestNonRemovableTransactionId(Relation rel)
Definition: procarray.c:2013
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:1663
bool ForceTransactionIdLimitUpdate(void)
Definition: varsup.c:490

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 1282 of file vacuum.c.

1289 {
1290  Oid relid = RelationGetRelid(relation);
1291  Relation rd;
1292  HeapTuple ctup;
1293  Form_pg_class pgcform;
1294  bool dirty,
1295  futurexid,
1296  futuremxid;
1297  TransactionId oldfrozenxid;
1298  MultiXactId oldminmulti;
1299 
1300  rd = table_open(RelationRelationId, RowExclusiveLock);
1301 
1302  /* Fetch a copy of the tuple to scribble on */
1304  if (!HeapTupleIsValid(ctup))
1305  elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
1306  relid);
1307  pgcform = (Form_pg_class) GETSTRUCT(ctup);
1308 
1309  /* Apply statistical updates, if any, to copied tuple */
1310 
1311  dirty = false;
1312  if (pgcform->relpages != (int32) num_pages)
1313  {
1314  pgcform->relpages = (int32) num_pages;
1315  dirty = true;
1316  }
1317  if (pgcform->reltuples != (float4) num_tuples)
1318  {
1319  pgcform->reltuples = (float4) num_tuples;
1320  dirty = true;
1321  }
1322  if (pgcform->relallvisible != (int32) num_all_visible_pages)
1323  {
1324  pgcform->relallvisible = (int32) num_all_visible_pages;
1325  dirty = true;
1326  }
1327 
1328  /* Apply DDL updates, but not inside an outer transaction (see above) */
1329 
1330  if (!in_outer_xact)
1331  {
1332  /*
1333  * If we didn't find any indexes, reset relhasindex.
1334  */
1335  if (pgcform->relhasindex && !hasindex)
1336  {
1337  pgcform->relhasindex = false;
1338  dirty = true;
1339  }
1340 
1341  /* We also clear relhasrules and relhastriggers if needed */
1342  if (pgcform->relhasrules && relation->rd_rules == NULL)
1343  {
1344  pgcform->relhasrules = false;
1345  dirty = true;
1346  }
1347  if (pgcform->relhastriggers && relation->trigdesc == NULL)
1348  {
1349  pgcform->relhastriggers = false;
1350  dirty = true;
1351  }
1352  }
1353 
1354  /*
1355  * Update relfrozenxid, unless caller passed InvalidTransactionId
1356  * indicating it has no new data.
1357  *
1358  * Ordinarily, we don't let relfrozenxid go backwards. However, if the
1359  * stored relfrozenxid is "in the future" then it seems best to assume
1360  * it's corrupt, and overwrite with the oldest remaining XID in the table.
1361  * This should match vac_update_datfrozenxid() concerning what we consider
1362  * to be "in the future".
1363  */
1364  oldfrozenxid = pgcform->relfrozenxid;
1365  futurexid = false;
1366  if (frozenxid_updated)
1367  *frozenxid_updated = false;
1368  if (TransactionIdIsNormal(frozenxid) && oldfrozenxid != frozenxid)
1369  {
1370  bool update = false;
1371 
1372  if (TransactionIdPrecedes(oldfrozenxid, frozenxid))
1373  update = true;
1374  else if (TransactionIdPrecedes(ReadNextTransactionId(), oldfrozenxid))
1375  futurexid = update = true;
1376 
1377  if (update)
1378  {
1379  pgcform->relfrozenxid = frozenxid;
1380  dirty = true;
1381  if (frozenxid_updated)
1382  *frozenxid_updated = true;
1383  }
1384  }
1385 
1386  /* Similarly for relminmxid */
1387  oldminmulti = pgcform->relminmxid;
1388  futuremxid = false;
1389  if (minmulti_updated)
1390  *minmulti_updated = false;
1391  if (MultiXactIdIsValid(minmulti) && oldminmulti != minmulti)
1392  {
1393  bool update = false;
1394 
1395  if (MultiXactIdPrecedes(oldminmulti, minmulti))
1396  update = true;
1397  else if (MultiXactIdPrecedes(ReadNextMultiXactId(), oldminmulti))
1398  futuremxid = update = true;
1399 
1400  if (update)
1401  {
1402  pgcform->relminmxid = minmulti;
1403  dirty = true;
1404  if (minmulti_updated)
1405  *minmulti_updated = true;
1406  }
1407  }
1408 
1409  /* If anything changed, write out the tuple. */
1410  if (dirty)
1411  heap_inplace_update(rd, ctup);
1412 
1414 
1415  if (futurexid)
1416  ereport(WARNING,
1418  errmsg_internal("overwrote invalid relfrozenxid value %u with new value %u for table \"%s\"",
1419  oldfrozenxid, frozenxid,
1420  RelationGetRelationName(relation))));
1421  if (futuremxid)
1422  ereport(WARNING,
1424  errmsg_internal("overwrote invalid relminmxid value %u with new value %u for table \"%s\"",
1425  oldminmulti, minmulti,
1426  RelationGetRelationName(relation))));
1427 }
signed int int32
Definition: c.h:430
float float4
Definition: c.h:565
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1033
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
#define RelationGetRelid(relation)
Definition: rel.h:501
TriggerDesc * trigdesc
Definition: rel.h:116
RuleLock * rd_rules
Definition: rel.h:114
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179

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, RELOID, 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,
bool  isTopLevel 
)

Definition at line 296 of file vacuum.c.

298 {
299  static bool in_vacuum = false;
300 
301  const char *stmttype;
302  volatile bool in_outer_xact,
303  use_own_xacts;
304 
305  Assert(params != NULL);
306 
307  stmttype = (params->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
308 
309  /*
310  * We cannot run VACUUM inside a user transaction block; if we were inside
311  * a transaction, then our commit- and start-transaction-command calls
312  * would not have the intended effect! There are numerous other subtle
313  * dependencies on this, too.
314  *
315  * ANALYZE (without VACUUM) can run either way.
316  */
317  if (params->options & VACOPT_VACUUM)
318  {
319  PreventInTransactionBlock(isTopLevel, stmttype);
320  in_outer_xact = false;
321  }
322  else
323  in_outer_xact = IsInTransactionBlock(isTopLevel);
324 
325  /*
326  * Due to static variables vac_context, anl_context and vac_strategy,
327  * vacuum() is not reentrant. This matters when VACUUM FULL or ANALYZE
328  * calls a hostile index expression that itself calls ANALYZE.
329  */
330  if (in_vacuum)
331  ereport(ERROR,
332  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
333  errmsg("%s cannot be executed from VACUUM or ANALYZE",
334  stmttype)));
335 
336  /*
337  * Sanity check DISABLE_PAGE_SKIPPING option.
338  */
339  if ((params->options & VACOPT_FULL) != 0 &&
340  (params->options & VACOPT_DISABLE_PAGE_SKIPPING) != 0)
341  ereport(ERROR,
342  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
343  errmsg("VACUUM option DISABLE_PAGE_SKIPPING cannot be used with FULL")));
344 
345  /* sanity check for PROCESS_TOAST */
346  if ((params->options & VACOPT_FULL) != 0 &&
347  (params->options & VACOPT_PROCESS_TOAST) == 0)
348  ereport(ERROR,
349  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
350  errmsg("PROCESS_TOAST required with VACUUM FULL")));
351 
352  /*
353  * Create special memory context for cross-transaction storage.
354  *
355  * Since it is a child of PortalContext, it will go away eventually even
356  * if we suffer an error; there's no need for special abort cleanup logic.
357  */
359  "Vacuum",
361 
362  /*
363  * If caller didn't give us a buffer strategy object, make one in the
364  * cross-transaction memory context.
365  */
366  if (bstrategy == NULL)
367  {
369 
370  bstrategy = GetAccessStrategy(BAS_VACUUM);
371  MemoryContextSwitchTo(old_context);
372  }
373  vac_strategy = bstrategy;
374 
375  /*
376  * Build list of relation(s) to process, putting any new data in
377  * vac_context for safekeeping.
378  */
379  if (relations != NIL)
380  {
381  List *newrels = NIL;
382  ListCell *lc;
383 
384  foreach(lc, relations)
385  {
387  List *sublist;
388  MemoryContext old_context;
389 
390  sublist = expand_vacuum_rel(vrel, params->options);
391  old_context = MemoryContextSwitchTo(vac_context);
392  newrels = list_concat(newrels, sublist);
393  MemoryContextSwitchTo(old_context);
394  }
395  relations = newrels;
396  }
397  else
398  relations = get_all_vacuum_rels(params->options);
399 
400  /*
401  * Decide whether we need to start/commit our own transactions.
402  *
403  * For VACUUM (with or without ANALYZE): always do so, so that we can
404  * release locks as soon as possible. (We could possibly use the outer
405  * transaction for a one-table VACUUM, but handling TOAST tables would be
406  * problematic.)
407  *
408  * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
409  * start/commit our own transactions. Also, there's no need to do so if
410  * only processing one relation. For multiple relations when not within a
411  * transaction block, and also in an autovacuum worker, use own
412  * transactions so we can release locks sooner.
413  */
414  if (params->options & VACOPT_VACUUM)
415  use_own_xacts = true;
416  else
417  {
418  Assert(params->options & VACOPT_ANALYZE);
420  use_own_xacts = true;
421  else if (in_outer_xact)
422  use_own_xacts = false;
423  else if (list_length(relations) > 1)
424  use_own_xacts = true;
425  else
426  use_own_xacts = false;
427  }
428 
429  /*
430  * vacuum_rel expects to be entered with no transaction active; it will
431  * start and commit its own transaction. But we are called by an SQL
432  * command, and so we are executing inside a transaction already. We
433  * commit the transaction started in PostgresMain() here, and start
434  * another one before exiting to match the commit waiting for us back in
435  * PostgresMain().
436  */
437  if (use_own_xacts)
438  {
439  Assert(!in_outer_xact);
440 
441  /* ActiveSnapshot is not set by autovacuum */
442  if (ActiveSnapshotSet())
444 
445  /* matches the StartTransaction in PostgresMain() */
447  }
448 
449  /* Turn vacuum cost accounting on or off, and set/clear in_vacuum */
450  PG_TRY();
451  {
452  ListCell *cur;
453 
454  in_vacuum = true;
456  VacuumCostBalance = 0;
457  VacuumPageHit = 0;
458  VacuumPageMiss = 0;
459  VacuumPageDirty = 0;
462  VacuumActiveNWorkers = NULL;
463 
464  /*
465  * Loop to process each selected relation.
466  */
467  foreach(cur, relations)
468  {
470 
471  if (params->options & VACOPT_VACUUM)
472  {
473  if (!vacuum_rel(vrel->oid, vrel->relation, params))
474  continue;
475  }
476 
477  if (params->options & VACOPT_ANALYZE)
478  {
479  /*
480  * If using separate xacts, start one for analyze. Otherwise,
481  * we can use the outer transaction.
482  */
483  if (use_own_xacts)
484  {
486  /* functions in indexes may want a snapshot set */
488  }
489 
490  analyze_rel(vrel->oid, vrel->relation, params,
491  vrel->va_cols, in_outer_xact, vac_strategy);
492 
493  if (use_own_xacts)
494  {
497  }
498  else
499  {
500  /*
501  * If we're not using separate xacts, better separate the
502  * ANALYZE actions with CCIs. This avoids trouble if user
503  * says "ANALYZE t, t".
504  */
506  }
507  }
508  }
509  }
510  PG_FINALLY();
511  {
512  in_vacuum = false;
513  VacuumCostActive = false;
514  }
515  PG_END_TRY();
516 
517  /*
518  * Finish up processing.
519  */
520  if (use_own_xacts)
521  {
522  /* here, we are not in a transaction */
523 
524  /*
525  * This matches the CommitTransaction waiting for us in
526  * PostgresMain().
527  */
529  }
530 
531  if ((params->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
532  {
533  /*
534  * Update pg_database.datfrozenxid, and truncate pg_xact if possible.
535  * (autovacuum.c does this for itself.)
536  */
538  }
539 
540  /*
541  * Clean up working storage --- note we must do this after
542  * StartTransactionCommand, else we might be trying to delete the active
543  * context!
544  */
546  vac_context = NULL;
547 }
@ BAS_VACUUM
Definition: bufmgr.h:33
void analyze_rel(Oid relid, RangeVar *relation, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
Definition: analyze.c:121
struct cursor * cur
Definition: ecpg.c:28
#define PG_TRY(...)
Definition: elog.h:309
#define PG_END_TRY(...)
Definition: elog.h:334
#define PG_FINALLY(...)
Definition: elog.h:326
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:541
int64 VacuumPageHit
Definition: globals.c:148
int64 VacuumPageMiss
Definition: globals.c:149
bool VacuumCostActive
Definition: globals.c:153
int64 VacuumPageDirty
Definition: globals.c:150
List * list_concat(List *list1, const List *list2)
Definition: list.c:560
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:376
MemoryContext PortalContext
Definition: mcxt.c:139
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:251
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:683
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:817
void PopActiveSnapshot(void)
Definition: snapmgr.c:778
static List * get_all_vacuum_rels(int options)
Definition: vacuum.c:865
static List * expand_vacuum_rel(VacuumRelation *vrel, int options)
Definition: vacuum.c:726
static BufferAccessStrategy vac_strategy
Definition: vacuum.c:76
static bool vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params)
Definition: vacuum.c:1816
void vac_update_datfrozenxid(void)
Definition: vacuum.c:1449
bool IsInTransactionBlock(bool isTopLevel)
Definition: xact.c:3588
void CommandCounterIncrement(void)
Definition: xact.c:1077
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3469
void StartTransactionCommand(void)
Definition: xact.c:2925
void CommitTransactionCommand(void)
Definition: xact.c:3022

References ActiveSnapshotSet(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, analyze_rel(), Assert(), BAS_VACUUM, CommandCounterIncrement(), CommitTransactionCommand(), cur, ereport, errcode(), errmsg(), ERROR, expand_vacuum_rel(), get_all_vacuum_rels(), GetAccessStrategy(), GetTransactionSnapshot(), IsAutoVacuumWorkerProcess(), IsInTransactionBlock(), lfirst_node, list_concat(), list_length(), MemoryContextDelete(), MemoryContextSwitchTo(), NIL, VacuumRelation::oid, VacuumParams::options, PG_END_TRY, PG_FINALLY, PG_TRY, PopActiveSnapshot(), PortalContext, PreventInTransactionBlock(), PushActiveSnapshot(), VacuumRelation::relation, StartTransactionCommand(), VacuumRelation::va_cols, vac_context, vac_strategy, vac_update_datfrozenxid(), VACOPT_ANALYZE, VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_FULL, VACOPT_PROCESS_TOAST, VACOPT_VACUUM, vacuum_rel(), VacuumActiveNWorkers, VacuumCostActive, VacuumCostBalance, VacuumCostBalanceLocal, VacuumCostDelay, VacuumPageDirty, VacuumPageHit, VacuumPageMiss, and VacuumSharedCostBalance.

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 2166 of file vacuum.c.

2167 {
2168  double msec = 0;
2169 
2170  /* Always check for interrupts */
2172 
2174  return;
2175 
2176  /*
2177  * For parallel vacuum, the delay is computed based on the shared cost
2178  * balance. See compute_parallel_delay.
2179  */
2180  if (VacuumSharedCostBalance != NULL)
2181  msec = compute_parallel_delay();
2182  else if (VacuumCostBalance >= VacuumCostLimit)
2184 
2185  /* Nap if appropriate */
2186  if (msec > 0)
2187  {
2188  if (msec > VacuumCostDelay * 4)
2189  msec = VacuumCostDelay * 4;
2190 
2191  (void) WaitLatch(MyLatch,
2193  msec,
2196 
2197  VacuumCostBalance = 0;
2198 
2199  /* update balance values for workers */
2201 
2202  /* Might have gotten an interrupt while sleeping */
2204  }
2205 }
void AutoVacuumUpdateDelay(void)
Definition: autovacuum.c:1781
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
struct Latch * MyLatch
Definition: globals.c:58
void ResetLatch(Latch *latch)
Definition: latch.c:683
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:476
#define WL_TIMEOUT
Definition: latch.h:128
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
static double compute_parallel_delay(void)
Definition: vacuum.c:2230
@ WAIT_EVENT_VACUUM_DELAY
Definition: wait_event.h:149

References AutoVacuumUpdateDelay(), CHECK_FOR_INTERRUPTS, compute_parallel_delay(), InterruptPending, MyLatch, ResetLatch(), VacuumCostActive, VacuumCostBalance, VacuumCostDelay, VacuumCostLimit, VacuumSharedCostBalance, WAIT_EVENT_VACUUM_DELAY, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

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_is_permitted_for_relation()

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

Definition at line 556 of file vacuum.c.

558 {
559  char *relname;
560  AclMode mode = 0;
561 
563 
564  /*
565  * A role has privileges to vacuum or analyze the relation if any of the
566  * following are true:
567  * - the role is a superuser
568  * - the role owns the relation
569  * - the role owns the current database and the relation is not shared
570  * - the role has been granted privileges to vacuum/analyze the relation
571  */
572  if (options & VACOPT_VACUUM)
573  mode |= ACL_VACUUM;
574  if (options & VACOPT_ANALYZE)
575  mode |= ACL_ANALYZE;
576  if (object_ownercheck(RelationRelationId, relid, GetUserId()) ||
577  (object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()) && !reltuple->relisshared) ||
579  return true;
580 
581  relname = NameStr(reltuple->relname);
582 
583  if ((options & VACOPT_VACUUM) != 0)
584  {
586  (errmsg("permission denied to vacuum \"%s\", skipping it",
587  relname)));
588 
589  /*
590  * For VACUUM ANALYZE, both logs could show up, but just generate
591  * information for VACUUM as that would be the first one to be
592  * processed.
593  */
594  return false;
595  }
596 
597  if ((options & VACOPT_ANALYZE) != 0)
599  (errmsg("permission denied to analyze \"%s\", skipping it",
600  relname)));
601 
602  return false;
603 }
@ ACLCHECK_OK
Definition: acl.h:184
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4799
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4746
#define NameStr(name)
Definition: c.h:682
Oid GetUserId(void)
Definition: miscinit.c:497
uint64 AclMode
Definition: parsenodes.h:81
#define ACL_ANALYZE
Definition: parsenodes.h:98
#define ACL_VACUUM
Definition: parsenodes.h:97
static PgChecksumMode mode
Definition: pg_checksums.c:65
NameData relname
Definition: pg_class.h:38

References ACL_ANALYZE, ACL_VACUUM, ACLCHECK_OK, Assert(), ereport, errmsg(), GetUserId(), mode, MyDatabaseId, NameStr, object_ownercheck(), pg_class_aclcheck(), 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 614 of file vacuum.c.

616 {
617  Relation rel;
618  bool rel_lock = true;
619  int elevel;
620 
622 
623  /*
624  * Open the relation and get the appropriate lock on it.
625  *
626  * There's a race condition here: the relation may have gone away since
627  * the last time we saw it. If so, we don't need to vacuum or analyze it.
628  *
629  * If we've been asked not to wait for the relation lock, acquire it first
630  * in non-blocking mode, before calling try_relation_open().
631  */
632  if (!(options & VACOPT_SKIP_LOCKED))
633  rel = try_relation_open(relid, lmode);
634  else if (ConditionalLockRelationOid(relid, lmode))
635  rel = try_relation_open(relid, NoLock);
636  else
637  {
638  rel = NULL;
639  rel_lock = false;
640  }
641 
642  /* if relation is opened, leave */
643  if (rel)
644  return rel;
645 
646  /*
647  * Relation could not be opened, hence generate if possible a log
648  * informing on the situation.
649  *
650  * If the RangeVar is not defined, we do not have enough information to
651  * provide a meaningful log statement. Chances are that the caller has
652  * intentionally not provided this information so that this logging is
653  * skipped, anyway.
654  */
655  if (relation == NULL)
656  return NULL;
657 
658  /*
659  * Determine the log level.
660  *
661  * For manual VACUUM or ANALYZE, we emit a WARNING to match the log
662  * statements in the permission checks; otherwise, only log if the caller
663  * so requested.
664  */
666  elevel = WARNING;
667  else if (verbose)
668  elevel = LOG;
669  else
670  return NULL;
671 
672  if ((options & VACOPT_VACUUM) != 0)
673  {
674  if (!rel_lock)
675  ereport(elevel,
676  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
677  errmsg("skipping vacuum of \"%s\" --- lock not available",
678  relation->relname)));
679  else
680  ereport(elevel,
682  errmsg("skipping vacuum of \"%s\" --- relation no longer exists",
683  relation->relname)));
684 
685  /*
686  * For VACUUM ANALYZE, both logs could show up, but just generate
687  * information for VACUUM as that would be the first one to be
688  * processed.
689  */
690  return NULL;
691  }
692 
693  if ((options & VACOPT_ANALYZE) != 0)
694  {
695  if (!rel_lock)
696  ereport(elevel,
697  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
698  errmsg("skipping analyze of \"%s\" --- lock not available",
699  relation->relname)));
700  else
701  ereport(elevel,
703  errmsg("skipping analyze of \"%s\" --- relation no longer exists",
704  relation->relname)));
705  }
706 
707  return NULL;
708 }
#define LOG
Definition: elog.h:27
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:152
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:77
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:89

References Assert(), ConditionalLockRelationOid(), ereport, errcode(), ERRCODE_UNDEFINED_TABLE, errmsg(), IsAutoVacuumWorkerProcess(), 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 
)
static

Definition at line 1816 of file vacuum.c.

1817 {
1818  LOCKMODE lmode;
1819  Relation rel;
1820  LockRelId lockrelid;
1821  Oid toast_relid;
1822  Oid save_userid;
1823  int save_sec_context;
1824  int save_nestlevel;
1825 
1826  Assert(params != NULL);
1827 
1828  /* Begin a transaction for vacuuming this relation */
1830 
1831  if (!(params->options & VACOPT_FULL))
1832  {
1833  /*
1834  * In lazy vacuum, we can set the PROC_IN_VACUUM flag, which lets
1835  * other concurrent VACUUMs know that they can ignore this one while
1836  * determining their OldestXmin. (The reason we don't set it during a
1837  * full VACUUM is exactly that we may have to run user-defined
1838  * functions for functional indexes, and we want to make sure that if
1839  * they use the snapshot set above, any tuples it requires can't get
1840  * removed from other tables. An index function that depends on the
1841  * contents of other tables is arguably broken, but we won't break it
1842  * here by violating transaction semantics.)
1843  *
1844  * We also set the VACUUM_FOR_WRAPAROUND flag, which is passed down by
1845  * autovacuum; it's used to avoid canceling a vacuum that was invoked
1846  * in an emergency.
1847  *
1848  * Note: these flags remain set until CommitTransaction or
1849  * AbortTransaction. We don't want to clear them until we reset
1850  * MyProc->xid/xmin, otherwise GetOldestNonRemovableTransactionId()
1851  * might appear to go backwards, which is probably Not Good. (We also
1852  * set PROC_IN_VACUUM *before* taking our own snapshot, so that our
1853  * xmin doesn't become visible ahead of setting the flag.)
1854  */
1855  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
1857  if (params->is_wraparound)
1860  LWLockRelease(ProcArrayLock);
1861  }
1862 
1863  /*
1864  * Need to acquire a snapshot to prevent pg_subtrans from being truncated,
1865  * cutoff xids in local memory wrapping around, and to have updated xmin
1866  * horizons.
1867  */
1869 
1870  /*
1871  * Check for user-requested abort. Note we want this to be inside a
1872  * transaction, so xact.c doesn't issue useless WARNING.
1873  */
1875 
1876  /*
1877  * Determine the type of lock we want --- hard exclusive lock for a FULL
1878  * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either
1879  * way, we can be sure that no other backend is vacuuming the same table.
1880  */
1881  lmode = (params->options & VACOPT_FULL) ?
1883 
1884  /* open the relation and get the appropriate lock on it */
1885  rel = vacuum_open_relation(relid, relation, params->options,
1886  params->log_min_duration >= 0, lmode);
1887 
1888  /* leave if relation could not be opened or locked */
1889  if (!rel)
1890  {
1893  return false;
1894  }
1895 
1896  /*
1897  * Check if relation needs to be skipped based on privileges. This check
1898  * happens also when building the relation list to vacuum for a manual
1899  * operation, and needs to be done additionally here as VACUUM could
1900  * happen across multiple transactions where privileges could have changed
1901  * in-between. Make sure to only generate logs for VACUUM in this case.
1902  */
1904  rel->rd_rel,
1905  VACOPT_VACUUM))
1906  {
1907  relation_close(rel, lmode);
1910  return true; /* user might have the ANALYZE privilege */
1911  }
1912 
1913  /*
1914  * Check that it's of a vacuumable relkind.
1915  */
1916  if (rel->rd_rel->relkind != RELKIND_RELATION &&
1917  rel->rd_rel->relkind != RELKIND_MATVIEW &&
1918  rel->rd_rel->relkind != RELKIND_TOASTVALUE &&
1919  rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1920  {
1921  ereport(WARNING,
1922  (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
1923  RelationGetRelationName(rel))));
1924  relation_close(rel, lmode);
1927  return false;
1928  }
1929 
1930  /*
1931  * Silently ignore tables that are temp tables of other backends ---
1932  * trying to vacuum these will lead to great unhappiness, since their
1933  * contents are probably not up-to-date on disk. (We don't throw a
1934  * warning here; it would just lead to chatter during a database-wide
1935  * VACUUM.)
1936  */
1937  if (RELATION_IS_OTHER_TEMP(rel))
1938  {
1939  relation_close(rel, lmode);
1942  return false;
1943  }
1944 
1945  /*
1946  * Silently ignore partitioned tables as there is no work to be done. The
1947  * useful work is on their child partitions, which have been queued up for
1948  * us separately.
1949  */
1950  if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1951  {
1952  relation_close(rel, lmode);
1955  /* It's OK to proceed with ANALYZE on this table */
1956  return true;
1957  }
1958 
1959  /*
1960  * Get a session-level lock too. This will protect our access to the
1961  * relation across multiple transactions, so that we can vacuum the
1962  * relation's TOAST table (if any) secure in the knowledge that no one is
1963  * deleting the parent relation.
1964  *
1965  * NOTE: this cannot block, even if someone else is waiting for access,
1966  * because the lock manager knows that both lock requests are from the
1967  * same process.
1968  */
1969  lockrelid = rel->rd_lockInfo.lockRelId;
1970  LockRelationIdForSession(&lockrelid, lmode);
1971 
1972  /*
1973  * Set index_cleanup option based on index_cleanup reloption if it wasn't
1974  * specified in VACUUM command, or when running in an autovacuum worker
1975  */
1976  if (params->index_cleanup == VACOPTVALUE_UNSPECIFIED)
1977  {
1978  StdRdOptIndexCleanup vacuum_index_cleanup;
1979 
1980  if (rel->rd_options == NULL)
1981  vacuum_index_cleanup = STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO;
1982  else
1983  vacuum_index_cleanup =
1984  ((StdRdOptions *) rel->rd_options)->vacuum_index_cleanup;
1985 
1986  if (vacuum_index_cleanup == STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO)
1987  params->index_cleanup = VACOPTVALUE_AUTO;
1988  else if (vacuum_index_cleanup == STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON)
1990  else
1991  {
1992  Assert(vacuum_index_cleanup ==
1995  }
1996  }
1997 
1998  /*
1999  * Set truncate option based on truncate reloption if it wasn't specified
2000  * in VACUUM command, or when running in an autovacuum worker
2001  */
2002  if (params->truncate == VACOPTVALUE_UNSPECIFIED)
2003  {
2004  if (rel->rd_options == NULL ||
2005  ((StdRdOptions *) rel->rd_options)->vacuum_truncate)
2006  params->truncate = VACOPTVALUE_ENABLED;
2007  else
2008  params->truncate = VACOPTVALUE_DISABLED;
2009  }
2010 
2011  /*
2012  * Remember the relation's TOAST relation for later, if the caller asked
2013  * us to process it. In VACUUM FULL, though, the toast table is
2014  * automatically rebuilt by cluster_rel so we shouldn't recurse to it.
2015  */
2016  if ((params->options & VACOPT_PROCESS_TOAST) != 0 &&
2017  (params->options & VACOPT_FULL) == 0)
2018  toast_relid = rel->rd_rel->reltoastrelid;
2019  else
2020  toast_relid = InvalidOid;
2021 
2022  /*
2023  * Switch to the table owner's userid, so that any index functions are run
2024  * as that user. Also lock down security-restricted operations and
2025  * arrange to make GUC variable changes local to this command. (This is
2026  * unnecessary, but harmless, for lazy VACUUM.)
2027  */
2028  GetUserIdAndSecContext(&save_userid, &save_sec_context);
2029  SetUserIdAndSecContext(rel->rd_rel->relowner,
2030  save_sec_context | SECURITY_RESTRICTED_OPERATION);
2031  save_nestlevel = NewGUCNestLevel();
2032 
2033  /*
2034  * Do the actual work --- either FULL or "lazy" vacuum
2035  */
2036  if (params->options & VACOPT_FULL)
2037  {
2038  ClusterParams cluster_params = {0};
2039 
2040  /* close relation before vacuuming, but hold lock until commit */
2041  relation_close(rel, NoLock);
2042  rel = NULL;
2043 
2044  if ((params->options & VACOPT_VERBOSE) != 0)
2045  cluster_params.options |= CLUOPT_VERBOSE;
2046 
2047  /* VACUUM FULL is now a variant of CLUSTER; see cluster.c */
2048  cluster_rel(relid, InvalidOid, &cluster_params);
2049  }
2050  else
2051  table_relation_vacuum(rel, params, vac_strategy);
2052 
2053  /* Roll back any GUC changes executed by index functions */
2054  AtEOXact_GUC(false, save_nestlevel);
2055 
2056  /* Restore userid and security context */
2057  SetUserIdAndSecContext(save_userid, save_sec_context);
2058 
2059  /* all done with this class, but hold lock until commit */
2060  if (rel)
2061  relation_close(rel, NoLock);
2062 
2063  /*
2064  * Complete the transaction and free all temporary memory used.
2065  */
2068 
2069  /*
2070  * If the relation has a secondary toast rel, vacuum that too while we
2071  * still hold the session lock on the main table. Note however that
2072  * "analyze" will not get done on the toast table. This is good, because
2073  * the toaster always uses hardcoded index access and statistics are
2074  * totally unimportant for toast relations.
2075  */
2076  if (toast_relid != InvalidOid)
2077  vacuum_rel(toast_relid, NULL, params);
2078 
2079  /*
2080  * Now release the session-level lock on the main table.
2081  */
2082  UnlockRelationIdForSession(&lockrelid, lmode);
2083 
2084  /* Report that we really did it. */
2085  return true;
2086 }
void cluster_rel(Oid tableOid, Oid indexOid, ClusterParams *params)
Definition: cluster.c:312
#define CLUOPT_VERBOSE
Definition: cluster.h:23
int NewGUCNestLevel(void)
Definition: guc.c:2183
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2197
void LockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:398
void UnlockRelationIdForSession(LockRelId *relid, LOCKMODE lockmode)
Definition: lmgr.c:411
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:305
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:618
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:625
#define PROC_IN_VACUUM
Definition: proc.h:57
#define PROC_VACUUM_FOR_WRAPAROUND
Definition: proc.h:59
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:656
StdRdOptIndexCleanup
Definition: rel.h:326
@ STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO
Definition: rel.h:327
@ STDRD_OPTION_VACUUM_INDEX_CLEANUP_OFF
Definition: rel.h:328
@ STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON
Definition: rel.h:329
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
PGPROC * MyProc
Definition: proc.c:68
PROC_HDR * ProcGlobal
Definition: proc.c:80
bits32 options
Definition: cluster.h:30
LockRelId lockRelId
Definition: rel.h:45
Definition: rel.h:38
uint8 statusFlags
Definition: proc.h:233
int pgxactoff
Definition: proc.h:188
uint8 * statusFlags
Definition: proc.h:377
LockInfoData rd_lockInfo
Definition: rel.h:113
bytea * rd_options
Definition: rel.h:171
static void table_relation_vacuum(Relation rel, struct VacuumParams *params, BufferAccessStrategy bstrategy)
Definition: tableam.h:1678
Relation vacuum_open_relation(Oid relid, RangeVar *relation, bits32 options, bool verbose, LOCKMODE lmode)
Definition: vacuum.c:614

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(), vac_strategy, VACOPT_FULL, VACOPT_PROCESS_TOAST, VACOPT_VACUUM, VACOPT_VERBOSE, VACOPTVALUE_AUTO, VACOPTVALUE_DISABLED, VACOPTVALUE_ENABLED, VACOPTVALUE_UNSPECIFIED, vacuum_is_permitted_for_relation(), vacuum_open_relation(), and WARNING.

Referenced by vacuum().

◆ vacuum_set_xid_limits()

bool vacuum_set_xid_limits ( Relation  rel,
const VacuumParams params,
TransactionId OldestXmin,
MultiXactId OldestMxact,
TransactionId FreezeLimit,
MultiXactId MultiXactCutoff 
)

Definition at line 940 of file vacuum.c.

943 {
944  int freeze_min_age,
945  multixact_freeze_min_age,
946  freeze_table_age,
947  multixact_freeze_table_age,
948  effective_multixact_freeze_max_age;
949  TransactionId nextXID,
950  safeOldestXmin,
951  aggressiveXIDCutoff;
952  MultiXactId nextMXID,
953  safeOldestMxact,
954  aggressiveMXIDCutoff;
955 
956  /* Use mutable copies of freeze age parameters */
957  freeze_min_age = params->freeze_min_age;
958  multixact_freeze_min_age = params->multixact_freeze_min_age;
959  freeze_table_age = params->freeze_table_age;
960  multixact_freeze_table_age = params->multixact_freeze_table_age;
961 
962  /*
963  * Acquire OldestXmin.
964  *
965  * We can always ignore processes running lazy vacuum. This is because we
966  * use these values only for deciding which tuples we must keep in the
967  * tables. Since lazy vacuum doesn't write its XID anywhere (usually no
968  * XID assigned), it's safe to ignore it. In theory it could be
969  * problematic to ignore lazy vacuums in a full vacuum, but keep in mind
970  * that only one vacuum process can be working on a particular table at
971  * any time, and that each vacuum is always an independent transaction.
972  */
973  *OldestXmin = GetOldestNonRemovableTransactionId(rel);
974 
976  {
977  TransactionId limit_xmin;
978  TimestampTz limit_ts;
979 
980  if (TransactionIdLimitedForOldSnapshots(*OldestXmin, rel,
981  &limit_xmin, &limit_ts))
982  {
983  /*
984  * TODO: We should only set the threshold if we are pruning on the
985  * basis of the increased limits. Not as crucial here as it is
986  * for opportunistic pruning (which often happens at a much higher
987  * frequency), but would still be a significant improvement.
988  */
989  SetOldSnapshotThresholdTimestamp(limit_ts, limit_xmin);
990  *OldestXmin = limit_xmin;
991  }
992  }
993 
994  Assert(TransactionIdIsNormal(*OldestXmin));
995 
996  /* Acquire OldestMxact */
997  *OldestMxact = GetOldestMultiXactId();
998  Assert(MultiXactIdIsValid(*OldestMxact));
999 
1000  /* Acquire next XID/next MXID values used to apply age-based settings */
1001  nextXID = ReadNextTransactionId();
1002  nextMXID = ReadNextMultiXactId();
1003 
1004  /*
1005  * Determine the minimum freeze age to use: as specified by the caller, or
1006  * vacuum_freeze_min_age, but in any case not more than half
1007  * autovacuum_freeze_max_age, so that autovacuums to prevent XID
1008  * wraparound won't occur too frequently.
1009  */
1010  if (freeze_min_age < 0)
1011  freeze_min_age = vacuum_freeze_min_age;
1012  freeze_min_age = Min(freeze_min_age, autovacuum_freeze_max_age / 2);
1013  Assert(freeze_min_age >= 0);
1014 
1015  /* Compute FreezeLimit, being careful to generate a normal XID */
1016  *FreezeLimit = nextXID - freeze_min_age;
1017  if (!TransactionIdIsNormal(*FreezeLimit))
1018  *FreezeLimit = FirstNormalTransactionId;
1019  /* FreezeLimit must always be <= OldestXmin */
1020  if (TransactionIdPrecedes(*OldestXmin, *FreezeLimit))
1021  *FreezeLimit = *OldestXmin;
1022 
1023  /*
1024  * Compute the multixact age for which freezing is urgent. This is
1025  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
1026  * short of multixact member space.
1027  */
1028  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
1029 
1030  /*
1031  * Determine the minimum multixact freeze age to use: as specified by
1032  * caller, or vacuum_multixact_freeze_min_age, but in any case not more
1033  * than half effective_multixact_freeze_max_age, so that autovacuums to
1034  * prevent MultiXact wraparound won't occur too frequently.
1035  */
1036  if (multixact_freeze_min_age < 0)
1037  multixact_freeze_min_age = vacuum_multixact_freeze_min_age;
1038  multixact_freeze_min_age = Min(multixact_freeze_min_age,
1039  effective_multixact_freeze_max_age / 2);
1040  Assert(multixact_freeze_min_age >= 0);
1041 
1042  /* Compute MultiXactCutoff, being careful to generate a valid value */
1043  *MultiXactCutoff = nextMXID - multixact_freeze_min_age;
1044  if (*MultiXactCutoff < FirstMultiXactId)
1045  *MultiXactCutoff = FirstMultiXactId;
1046  /* MultiXactCutoff must always be <= OldestMxact */
1047  if (MultiXactIdPrecedes(*OldestMxact, *MultiXactCutoff))
1048  *MultiXactCutoff = *OldestMxact;
1049 
1050  /*
1051  * Done setting output parameters; check if OldestXmin or OldestMxact are
1052  * held back to an unsafe degree in passing
1053  */
1054  safeOldestXmin = nextXID - autovacuum_freeze_max_age;
1055  if (!TransactionIdIsNormal(safeOldestXmin))
1056  safeOldestXmin = FirstNormalTransactionId;
1057  safeOldestMxact = nextMXID - effective_multixact_freeze_max_age;
1058  if (safeOldestMxact < FirstMultiXactId)
1059  safeOldestMxact = FirstMultiXactId;
1060  if (TransactionIdPrecedes(*OldestXmin, safeOldestXmin))
1061  ereport(WARNING,
1062  (errmsg("cutoff for removing and freezing tuples is far in the past"),
1063  errhint("Close open transactions soon to avoid wraparound problems.\n"
1064  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1065  if (MultiXactIdPrecedes(*OldestMxact, safeOldestMxact))
1066  ereport(WARNING,
1067  (errmsg("cutoff for freezing multixacts is far in the past"),
1068  errhint("Close open transactions soon to avoid wraparound problems.\n"
1069  "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
1070 
1071  /*
1072  * Finally, figure out if caller needs to do an aggressive VACUUM or not.
1073  *
1074  * Determine the table freeze age to use: as specified by the caller, or
1075  * the value of the vacuum_freeze_table_age GUC, but in any case not more
1076  * than autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
1077  * VACUUM schedule, the nightly VACUUM gets a chance to freeze XIDs before
1078  * anti-wraparound autovacuum is launched.
1079  */
1080  if (freeze_table_age < 0)
1081  freeze_table_age = vacuum_freeze_table_age;
1082  freeze_table_age = Min(freeze_table_age, autovacuum_freeze_max_age * 0.95);
1083  Assert(freeze_table_age >= 0);
1084  aggressiveXIDCutoff = nextXID - freeze_table_age;
1085  if (!TransactionIdIsNormal(aggressiveXIDCutoff))
1086  aggressiveXIDCutoff = FirstNormalTransactionId;
1087  if (TransactionIdPrecedesOrEquals(rel->rd_rel->relfrozenxid,
1088  aggressiveXIDCutoff))
1089  return true;
1090 
1091  /*
1092  * Similar to the above, determine the table freeze age to use for
1093  * multixacts: as specified by the caller, or the value of the
1094  * vacuum_multixact_freeze_table_age GUC, but in any case not more than
1095  * effective_multixact_freeze_max_age * 0.95, so that if you have e.g.
1096  * nightly VACUUM schedule, the nightly VACUUM gets a chance to freeze
1097  * multixacts before anti-wraparound autovacuum is launched.
1098  */
1099  if (multixact_freeze_table_age < 0)
1100  multixact_freeze_table_age = vacuum_multixact_freeze_table_age;
1101  multixact_freeze_table_age =
1102  Min(multixact_freeze_table_age,
1103  effective_multixact_freeze_max_age * 0.95);
1104  Assert(multixact_freeze_table_age >= 0);
1105  aggressiveMXIDCutoff = nextMXID - multixact_freeze_table_age;
1106  if (aggressiveMXIDCutoff < FirstMultiXactId)
1107  aggressiveMXIDCutoff = FirstMultiXactId;
1108  if (MultiXactIdPrecedesOrEquals(rel->rd_rel->relminmxid,
1109  aggressiveMXIDCutoff))
1110  return true;
1111 
1112  /* Non-aggressive VACUUM */
1113  return false;
1114 }
int autovacuum_freeze_max_age
Definition: autovacuum.c:126
#define Min(x, y)
Definition: c.h:937
int64 TimestampTz
Definition: timestamp.h:39
int errhint(const char *fmt,...)
Definition: elog.c:1193
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3171
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2826
#define FirstMultiXactId
Definition: multixact.h:25
bool TransactionIdLimitedForOldSnapshots(TransactionId recentXmin, Relation relation, TransactionId *limit_xid, TimestampTz *limit_ts)
Definition: snapmgr.c:1796
void SetOldSnapshotThresholdTimestamp(TimestampTz ts, TransactionId xlimit)
Definition: snapmgr.c:1717
static bool OldSnapshotThresholdActive(void)
Definition: snapmgr.h:102
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:292
#define FirstNormalTransactionId
Definition: transam.h:34
int vacuum_freeze_min_age
Definition: vacuum.c:66
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:69
int vacuum_freeze_table_age
Definition: vacuum.c:67
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:68

References Assert(), autovacuum_freeze_max_age, ereport, errhint(), errmsg(), FirstMultiXactId, FirstNormalTransactionId, VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, GetOldestMultiXactId(), GetOldestNonRemovableTransactionId(), Min, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, MultiXactIdIsValid, MultiXactIdPrecedes(), MultiXactIdPrecedesOrEquals(), MultiXactMemberFreezeThreshold(), OldSnapshotThresholdActive(), RelationData::rd_rel, ReadNextMultiXactId(), ReadNextTransactionId(), SetOldSnapshotThresholdTimestamp(), TransactionIdIsNormal, TransactionIdLimitedForOldSnapshots(), 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_xid_failsafe_check()

bool vacuum_xid_failsafe_check ( TransactionId  relfrozenxid,
MultiXactId  relminmxid 
)

Definition at line 1126 of file vacuum.c.

1127 {
1128  TransactionId xid_skip_limit;
1129  MultiXactId multi_skip_limit;
1130  int skip_index_vacuum;
1131 
1132  Assert(TransactionIdIsNormal(relfrozenxid));
1133  Assert(MultiXactIdIsValid(relminmxid));
1134 
1135  /*
1136  * Determine the index skipping age to use. In any case no less than
1137  * autovacuum_freeze_max_age * 1.05.
1138  */
1139  skip_index_vacuum = Max(vacuum_failsafe_age, autovacuum_freeze_max_age * 1.05);
1140 
1141  xid_skip_limit = ReadNextTransactionId() - skip_index_vacuum;
1142  if (!TransactionIdIsNormal(xid_skip_limit))
1143  xid_skip_limit = FirstNormalTransactionId;
1144 
1145  if (TransactionIdPrecedes(relfrozenxid, xid_skip_limit))
1146  {
1147  /* The table's relfrozenxid is too old */
1148  return true;
1149  }
1150 
1151  /*
1152  * Similar to above, determine the index skipping age to use for
1153  * multixact. In any case no less than autovacuum_multixact_freeze_max_age *
1154  * 1.05.
1155  */
1156  skip_index_vacuum = Max(vacuum_multixact_failsafe_age,
1158 
1159  multi_skip_limit = ReadNextMultiXactId() - skip_index_vacuum;
1160  if (multi_skip_limit < FirstMultiXactId)
1161  multi_skip_limit = FirstMultiXactId;
1162 
1163  if (MultiXactIdPrecedes(relminmxid, multi_skip_limit))
1164  {
1165  /* The table's relminmxid is too old */
1166  return true;
1167  }
1168 
1169  return false;
1170 }
int autovacuum_multixact_freeze_max_age
Definition: autovacuum.c:127
#define Max(x, y)
Definition: c.h:931
int vacuum_multixact_failsafe_age
Definition: vacuum.c:71
int vacuum_failsafe_age
Definition: vacuum.c:70

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

Referenced by lazy_check_wraparound_failsafe().

Variable Documentation

◆ vac_context

MemoryContext vac_context = NULL
static

Definition at line 75 of file vacuum.c.

Referenced by expand_vacuum_rel(), get_all_vacuum_rels(), and vacuum().

◆ vac_strategy

BufferAccessStrategy vac_strategy
static

Definition at line 76 of file vacuum.c.

Referenced by vacuum(), and vacuum_rel().

◆ vacuum_failsafe_age

int vacuum_failsafe_age

Definition at line 70 of file vacuum.c.

Referenced by vacuum_xid_failsafe_check().

◆ vacuum_freeze_min_age

int vacuum_freeze_min_age

Definition at line 66 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

◆ vacuum_freeze_table_age

int vacuum_freeze_table_age

Definition at line 67 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

◆ vacuum_multixact_failsafe_age

int vacuum_multixact_failsafe_age

Definition at line 71 of file vacuum.c.

Referenced by vacuum_xid_failsafe_check().

◆ vacuum_multixact_freeze_min_age

int vacuum_multixact_freeze_min_age

Definition at line 68 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

◆ vacuum_multixact_freeze_table_age

int vacuum_multixact_freeze_table_age

Definition at line 69 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

◆ VacuumActiveNWorkers

◆ VacuumCostBalanceLocal

int VacuumCostBalanceLocal = 0

◆ VacuumSharedCostBalance

pg_atomic_uint32* VacuumSharedCostBalance = NULL