PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
vacuum.h File Reference
#include "access/htup.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_type.h"
#include "nodes/parsenodes.h"
#include "storage/buf.h"
#include "storage/lock.h"
#include "utils/relcache.h"
Include dependency graph for vacuum.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  VacAttrStats
 
struct  VacuumParams
 

Typedefs

typedef struct VacAttrStatsVacAttrStatsP
 
typedef Datum(* AnalyzeAttrFetchFunc )(VacAttrStatsP stats, int rownum, bool *isNull)
 
typedef void(* AnalyzeAttrComputeStatsFunc )(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
 
typedef struct VacAttrStats VacAttrStats
 
typedef struct VacuumParams VacuumParams
 

Functions

void ExecVacuum (VacuumStmt *vacstmt, bool isTopLevel)
 
void vacuum (int options, RangeVar *relation, Oid relid, VacuumParams *params, List *va_cols, BufferAccessStrategy bstrategy, bool isTopLevel)
 
void vac_open_indexes (Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
 
void vac_close_indexes (int nindexes, Relation *Irel, LOCKMODE lockmode)
 
double vac_estimate_reltuples (Relation relation, bool is_analyze, 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 in_outer_xact)
 
void vacuum_set_xid_limits (Relation rel, int freeze_min_age, int freeze_table_age, int multixact_freeze_min_age, int multixact_freeze_table_age, TransactionId *oldestXmin, TransactionId *freezeLimit, TransactionId *xidFullScanLimit, MultiXactId *multiXactCutoff, MultiXactId *mxactFullScanLimit)
 
void vac_update_datfrozenxid (void)
 
void vacuum_delay_point (void)
 
void lazy_vacuum_rel (Relation onerel, int options, VacuumParams *params, BufferAccessStrategy bstrategy)
 
void analyze_rel (Oid relid, RangeVar *relation, int options, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
 
bool std_typanalyze (VacAttrStats *stats)
 
double anl_random_fract (void)
 
double anl_init_selection_state (int n)
 
double anl_get_next_S (double t, int n, double *stateptr)
 

Variables

PGDLLIMPORT int default_statistics_target
 
int vacuum_freeze_min_age
 
int vacuum_freeze_table_age
 
int vacuum_multixact_freeze_min_age
 
int vacuum_multixact_freeze_table_age
 

Typedef Documentation

typedef void(* AnalyzeAttrComputeStatsFunc)(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)

Definition at line 64 of file vacuum.h.

typedef Datum(* AnalyzeAttrFetchFunc)(VacAttrStatsP stats, int rownum, bool *isNull)

Definition at line 61 of file vacuum.h.

Definition at line 59 of file vacuum.h.

Function Documentation

void analyze_rel ( Oid  relid,
RangeVar relation,
int  options,
VacuumParams params,
List va_cols,
bool  in_outer_xact,
BufferAccessStrategy  bstrategy 
)

Definition at line 111 of file analyze.c.

References acquire_sample_rows(), FdwRoutine::AnalyzeForeignTable, CHECK_FOR_INTERRUPTS, ConditionalLockRelationOid(), DEBUG2, do_analyze_rel(), elevel, ereport, errcode(), errmsg(), GetFdwRoutineForRelation(), GetUserId(), INFO, IsAutoVacuumWorkerProcess(), LOG, VacuumParams::log_min_duration, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyDatabaseId, MyPgXact, NoLock, NULL, PG_CATALOG_NAMESPACE, pg_class_ownercheck(), pg_database_ownercheck(), PROC_IN_ANALYZE, RelationData::rd_rel, relation_close(), RELATION_IS_OTHER_TEMP, RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RangeVar::relname, ShareUpdateExclusiveLock, StatisticRelationId, try_relation_open(), VACOPT_NOWAIT, VACOPT_VACUUM, VACOPT_VERBOSE, PGXACT::vacuumFlags, and WARNING.

Referenced by vacuum().

114 {
115  Relation onerel;
116  int elevel;
117  AcquireSampleRowsFunc acquirefunc = NULL;
118  BlockNumber relpages = 0;
119 
120  /* Select logging level */
121  if (options & VACOPT_VERBOSE)
122  elevel = INFO;
123  else
124  elevel = DEBUG2;
125 
126  /* Set up static variables */
127  vac_strategy = bstrategy;
128 
129  /*
130  * Check for user-requested abort.
131  */
133 
134  /*
135  * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
136  * ANALYZEs don't run on it concurrently. (This also locks out a
137  * concurrent VACUUM, which doesn't matter much at the moment but might
138  * matter if we ever try to accumulate stats on dead tuples.) If the rel
139  * has been dropped since we last saw it, we don't need to process it.
140  */
141  if (!(options & VACOPT_NOWAIT))
144  onerel = try_relation_open(relid, NoLock);
145  else
146  {
147  onerel = NULL;
148  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
149  ereport(LOG,
150  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
151  errmsg("skipping analyze of \"%s\" --- lock not available",
152  relation->relname)));
153  }
154  if (!onerel)
155  return;
156 
157  /*
158  * Check permissions --- this should match vacuum's check!
159  */
160  if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
161  (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
162  {
163  /* No need for a WARNING if we already complained during VACUUM */
164  if (!(options & VACOPT_VACUUM))
165  {
166  if (onerel->rd_rel->relisshared)
168  (errmsg("skipping \"%s\" --- only superuser can analyze it",
169  RelationGetRelationName(onerel))));
170  else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
172  (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
173  RelationGetRelationName(onerel))));
174  else
176  (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
177  RelationGetRelationName(onerel))));
178  }
180  return;
181  }
182 
183  /*
184  * Silently ignore tables that are temp tables of other backends ---
185  * trying to analyze these is rather pointless, since their contents are
186  * probably not up-to-date on disk. (We don't throw a warning here; it
187  * would just lead to chatter during a database-wide ANALYZE.)
188  */
189  if (RELATION_IS_OTHER_TEMP(onerel))
190  {
192  return;
193  }
194 
195  /*
196  * We can ANALYZE any table except pg_statistic. See update_attstats
197  */
198  if (RelationGetRelid(onerel) == StatisticRelationId)
199  {
201  return;
202  }
203 
204  /*
205  * Check that it's a plain table, materialized view, or foreign table; we
206  * used to do this in get_rel_oids() but seems safer to check after we've
207  * locked the relation.
208  */
209  if (onerel->rd_rel->relkind == RELKIND_RELATION ||
210  onerel->rd_rel->relkind == RELKIND_MATVIEW)
211  {
212  /* Regular table, so we'll use the regular row acquisition function */
213  acquirefunc = acquire_sample_rows;
214  /* Also get regular table's size */
215  relpages = RelationGetNumberOfBlocks(onerel);
216  }
217  else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
218  {
219  /*
220  * For a foreign table, call the FDW's hook function to see whether it
221  * supports analysis.
222  */
223  FdwRoutine *fdwroutine;
224  bool ok = false;
225 
226  fdwroutine = GetFdwRoutineForRelation(onerel, false);
227 
228  if (fdwroutine->AnalyzeForeignTable != NULL)
229  ok = fdwroutine->AnalyzeForeignTable(onerel,
230  &acquirefunc,
231  &relpages);
232 
233  if (!ok)
234  {
236  (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
237  RelationGetRelationName(onerel))));
239  return;
240  }
241  }
242  else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
243  {
244  /*
245  * For partitioned tables, we want to do the recursive ANALYZE below.
246  */
247  }
248  else
249  {
250  /* No need for a WARNING if we already complained during VACUUM */
251  if (!(options & VACOPT_VACUUM))
253  (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
254  RelationGetRelationName(onerel))));
256  return;
257  }
258 
259  /*
260  * OK, let's do it. First let other backends know I'm in ANALYZE.
261  */
262  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
264  LWLockRelease(ProcArrayLock);
265 
266  /*
267  * Do the normal non-recursive ANALYZE. We can skip this for partitioned
268  * tables, which don't contain any rows.
269  */
270  if (onerel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
271  do_analyze_rel(onerel, options, params, va_cols, acquirefunc,
272  relpages, false, in_outer_xact, elevel);
273 
274  /*
275  * If there are child tables, do recursive ANALYZE.
276  */
277  if (onerel->rd_rel->relhassubclass)
278  do_analyze_rel(onerel, options, params, va_cols, acquirefunc, relpages,
279  true, in_outer_xact, elevel);
280 
281  /*
282  * Close source relation now, but keep lock so that no one deletes it
283  * before we commit. (If someone did, they'd fail to clean up the entries
284  * we made in pg_statistic. Also, releasing the lock before commit would
285  * expose us to concurrent-update failures in update_attstats.)
286  */
287  relation_close(onerel, NoLock);
288 
289  /*
290  * Reset my PGXACT flag. Note: we need this here, and not in vacuum_rel,
291  * because the vacuum flag is cleared by the end-of-xact code.
292  */
293  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
295  LWLockRelease(ProcArrayLock);
296 }
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:138
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1147
Oid GetUserId(void)
Definition: miscinit.c:283
AnalyzeForeignTable_function AnalyzeForeignTable
Definition: fdwapi.h:218
int(* AcquireSampleRowsFunc)(Relation relation, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: fdwapi.h:134
#define RELKIND_MATVIEW
Definition: pg_class.h:165
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1260
#define INFO
Definition: elog.h:33
static BufferAccessStrategy vac_strategy
Definition: analyze.c:81
uint32 BlockNumber
Definition: block.h:31
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:114
PGXACT * MyPgXact
Definition: proc.c:68
uint8 vacuumFlags
Definition: proc.h:218
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
char * relname
Definition: primnodes.h:68
#define DEBUG2
Definition: elog.h:24
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
#define PG_CATALOG_NAMESPACE
Definition: pg_namespace.h:71
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3360
#define ereport(elevel, rest)
Definition: elog.h:122
bool pg_database_ownercheck(Oid db_oid, Oid roleid)
Definition: aclchk.c:4964
#define WARNING
Definition: elog.h:40
static void do_analyze_rel(Relation onerel, int options, VacuumParams *params, List *va_cols, AcquireSampleRowsFunc acquirefunc, BlockNumber relpages, bool inh, bool in_outer_xact, int elevel)
Definition: analyze.c:306
static int elevel
Definition: vacuumlazy.c:137
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define StatisticRelationId
Definition: pg_statistic.h:29
Oid MyDatabaseId
Definition: globals.c:76
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
#define NULL
Definition: c.h:229
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:534
bool pg_class_ownercheck(Oid class_oid, Oid roleid)
Definition: aclchk.c:4546
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
int log_min_duration
Definition: vacuum.h:145
int errmsg(const char *fmt,...)
Definition: elog.c:797
FdwRoutine * GetFdwRoutineForRelation(Relation relation, bool makecopy)
Definition: foreign.c:395
#define PROC_IN_ANALYZE
Definition: proc.h:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RelationGetRelid(relation)
Definition: rel.h:417
static int acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, int targrows, double *totalrows, double *totaldeadrows)
Definition: analyze.c:992
double anl_get_next_S ( double  t,
int  n,
double *  stateptr 
)

Definition at line 284 of file sampling.c.

285 {
286  double result;
287 
288  oldrs.W = *stateptr;
289  result = reservoir_get_next_S(&oldrs, t, n);
290  *stateptr = oldrs.W;
291  return result;
292 }
return result
Definition: formatting.c:1618
static ReservoirStateData oldrs
Definition: sampling.c:259
double reservoir_get_next_S(ReservoirState rs, double t, int n)
Definition: sampling.c:142
double anl_init_selection_state ( int  n)

Definition at line 273 of file sampling.c.

274 {
275  /* initialize if first time through */
276  if (oldrs.randstate[0] == 0)
278 
279  /* Initial value of W (for use when Algorithm Z is first applied) */
280  return exp(-log(sampler_random_fract(oldrs.randstate)) / n);
281 }
void sampler_random_init_state(long seed, SamplerRandomState randstate)
Definition: sampling.c:229
long random(void)
Definition: random.c:22
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:238
static ReservoirStateData oldrs
Definition: sampling.c:259
SamplerRandomState randstate
Definition: sampling.h:50
double anl_random_fract ( void  )

Definition at line 262 of file sampling.c.

263 {
264  /* initialize if first time through */
265  if (oldrs.randstate[0] == 0)
267 
268  /* and compute a random fraction */
270 }
void sampler_random_init_state(long seed, SamplerRandomState randstate)
Definition: sampling.c:229
long random(void)
Definition: random.c:22
double sampler_random_fract(SamplerRandomState randstate)
Definition: sampling.c:238
static ReservoirStateData oldrs
Definition: sampling.c:259
SamplerRandomState randstate
Definition: sampling.h:50
void ExecVacuum ( VacuumStmt vacstmt,
bool  isTopLevel 
)

Definition at line 85 of file vacuum.c.

References Assert, VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, InvalidOid, VacuumParams::is_wraparound, VacuumParams::log_min_duration, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, NIL, NULL, VacuumStmt::options, VacuumStmt::relation, VacuumStmt::va_cols, VACOPT_ANALYZE, VACOPT_FREEZE, VACOPT_FULL, VACOPT_SKIPTOAST, VACOPT_VACUUM, and vacuum().

Referenced by standard_ProcessUtility().

86 {
87  VacuumParams params;
88 
89  /* sanity checks on options */
91  Assert((vacstmt->options & VACOPT_VACUUM) ||
92  !(vacstmt->options & (VACOPT_FULL | VACOPT_FREEZE)));
93  Assert((vacstmt->options & VACOPT_ANALYZE) || vacstmt->va_cols == NIL);
94  Assert(!(vacstmt->options & VACOPT_SKIPTOAST));
95 
96  /*
97  * All freeze ages are zero if the FREEZE option is given; otherwise pass
98  * them as -1 which means to use the default values.
99  */
100  if (vacstmt->options & VACOPT_FREEZE)
101  {
102  params.freeze_min_age = 0;
103  params.freeze_table_age = 0;
104  params.multixact_freeze_min_age = 0;
105  params.multixact_freeze_table_age = 0;
106  }
107  else
108  {
109  params.freeze_min_age = -1;
110  params.freeze_table_age = -1;
111  params.multixact_freeze_min_age = -1;
112  params.multixact_freeze_table_age = -1;
113  }
114 
115  /* user-invoked vacuum is never "for wraparound" */
116  params.is_wraparound = false;
117 
118  /* user-invoked vacuum never uses this parameter */
119  params.log_min_duration = -1;
120 
121  /* Now go through the common routine */
122  vacuum(vacstmt->options, vacstmt->relation, InvalidOid, &params,
123  vacstmt->va_cols, NULL, isTopLevel);
124 }
#define NIL
Definition: pg_list.h:69
int multixact_freeze_table_age
Definition: vacuum.h:142
int freeze_table_age
Definition: vacuum.h:139
int freeze_min_age
Definition: vacuum.h:138
bool is_wraparound
Definition: vacuum.h:144
List * va_cols
Definition: parsenodes.h:3069
#define InvalidOid
Definition: postgres_ext.h:36
void vacuum(int options, RangeVar *relation, Oid relid, VacuumParams *params, List *va_cols, BufferAccessStrategy bstrategy, bool isTopLevel)
Definition: vacuum.c:149
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
RangeVar * relation
Definition: parsenodes.h:3068
int log_min_duration
Definition: vacuum.h:145
int multixact_freeze_min_age
Definition: vacuum.h:140
void lazy_vacuum_rel ( Relation  onerel,
int  options,
VacuumParams params,
BufferAccessStrategy  bstrategy 
)

Definition at line 183 of file vacuumlazy.c.

References _, appendStringInfo(), Assert, buf, StringInfoData::data, DEBUG2, elevel, ereport, errmsg_internal(), FreeSpaceMapVacuum(), VacuumParams::freeze_min_age, VacuumParams::freeze_table_age, FreezeLimit, LVRelStats::frozenskipped_pages, get_database_name(), get_namespace_name(), GetCurrentTimestamp(), LVRelStats::hasindex, INFO, initStringInfo(), InvalidMultiXactId, InvalidTransactionId, IsAutoVacuumWorkerProcess(), lazy_scan_heap(), lazy_truncate_heap(), LVRelStats::lock_waiter_detected, LOG, VacuumParams::log_min_duration, VacuumParams::multixact_freeze_min_age, VacuumParams::multixact_freeze_table_age, MultiXactCutoff, MultiXactIdPrecedesOrEquals(), MyDatabaseId, LVRelStats::new_dead_tuples, LVRelStats::new_rel_tuples, NoLock, NULL, LVRelStats::num_index_scans, LVRelStats::old_rel_pages, LVRelStats::old_rel_tuples, OldestXmin, LVRelStats::pages_removed, palloc0(), pfree(), pg_rusage_init(), pg_rusage_show(), pgstat_progress_end_command(), pgstat_progress_start_command(), pgstat_progress_update_param(), pgstat_report_vacuum(), LVRelStats::pinskipped_pages, PROGRESS_COMMAND_VACUUM, PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_FINAL_CLEANUP, RelationData::rd_rel, LVRelStats::rel_pages, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RowExclusiveLock, LVRelStats::scanned_pages, should_attempt_truncation(), TimestampDifference(), TimestampDifferenceExceeds(), TransactionIdPrecedesOrEquals(), LVRelStats::tupcount_pages, LVRelStats::tuples_deleted, vac_close_indexes(), vac_open_indexes(), vac_update_relstats(), VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_VERBOSE, vacuum_set_xid_limits(), VacuumPageDirty, VacuumPageHit, VacuumPageMiss, and visibilitymap_count().

Referenced by vacuum_rel().

185 {
186  LVRelStats *vacrelstats;
187  Relation *Irel;
188  int nindexes;
189  PGRUsage ru0;
190  TimestampTz starttime = 0;
191  long secs;
192  int usecs;
193  double read_rate,
194  write_rate;
195  bool aggressive; /* should we scan all unfrozen pages? */
196  bool scanned_all_unfrozen; /* actually scanned all such pages? */
197  TransactionId xidFullScanLimit;
198  MultiXactId mxactFullScanLimit;
199  BlockNumber new_rel_pages;
200  double new_rel_tuples;
201  BlockNumber new_rel_allvisible;
202  double new_live_tuples;
203  TransactionId new_frozen_xid;
204  MultiXactId new_min_multi;
205 
206  Assert(params != NULL);
207 
208  /* measure elapsed time iff autovacuum logging requires it */
209  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
210  {
211  pg_rusage_init(&ru0);
212  starttime = GetCurrentTimestamp();
213  }
214 
215  if (options & VACOPT_VERBOSE)
216  elevel = INFO;
217  else
218  elevel = DEBUG2;
219 
221  RelationGetRelid(onerel));
222 
223  vac_strategy = bstrategy;
224 
225  vacuum_set_xid_limits(onerel,
226  params->freeze_min_age,
227  params->freeze_table_age,
228  params->multixact_freeze_min_age,
230  &OldestXmin, &FreezeLimit, &xidFullScanLimit,
231  &MultiXactCutoff, &mxactFullScanLimit);
232 
233  /*
234  * We request an aggressive scan if the table's frozen Xid is now older
235  * than or equal to the requested Xid full-table scan limit; or if the
236  * table's minimum MultiXactId is older than or equal to the requested
237  * mxid full-table scan limit; or if DISABLE_PAGE_SKIPPING was specified.
238  */
239  aggressive = TransactionIdPrecedesOrEquals(onerel->rd_rel->relfrozenxid,
240  xidFullScanLimit);
241  aggressive |= MultiXactIdPrecedesOrEquals(onerel->rd_rel->relminmxid,
242  mxactFullScanLimit);
244  aggressive = true;
245 
246  vacrelstats = (LVRelStats *) palloc0(sizeof(LVRelStats));
247 
248  vacrelstats->old_rel_pages = onerel->rd_rel->relpages;
249  vacrelstats->old_rel_tuples = onerel->rd_rel->reltuples;
250  vacrelstats->num_index_scans = 0;
251  vacrelstats->pages_removed = 0;
252  vacrelstats->lock_waiter_detected = false;
253 
254  /* Open all indexes of the relation */
255  vac_open_indexes(onerel, RowExclusiveLock, &nindexes, &Irel);
256  vacrelstats->hasindex = (nindexes > 0);
257 
258  /* Do the vacuuming */
259  lazy_scan_heap(onerel, options, vacrelstats, Irel, nindexes, aggressive);
260 
261  /* Done with indexes */
262  vac_close_indexes(nindexes, Irel, NoLock);
263 
264  /*
265  * Compute whether we actually scanned the all unfrozen pages. If we did,
266  * we can adjust relfrozenxid and relminmxid.
267  *
268  * NB: We need to check this before truncating the relation, because that
269  * will change ->rel_pages.
270  */
271  if ((vacrelstats->scanned_pages + vacrelstats->frozenskipped_pages)
272  < vacrelstats->rel_pages)
273  {
274  Assert(!aggressive);
275  scanned_all_unfrozen = false;
276  }
277  else
278  scanned_all_unfrozen = true;
279 
280  /*
281  * Optionally truncate the relation.
282  */
283  if (should_attempt_truncation(vacrelstats))
284  lazy_truncate_heap(onerel, vacrelstats);
285 
286  /* Report that we are now doing final cleanup */
289 
290  /* Vacuum the Free Space Map */
291  FreeSpaceMapVacuum(onerel);
292 
293  /*
294  * Update statistics in pg_class.
295  *
296  * A corner case here is that if we scanned no pages at all because every
297  * page is all-visible, we should not update relpages/reltuples, because
298  * we have no new information to contribute. In particular this keeps us
299  * from replacing relpages=reltuples=0 (which means "unknown tuple
300  * density") with nonzero relpages and reltuples=0 (which means "zero
301  * tuple density") unless there's some actual evidence for the latter.
302  *
303  * It's important that we use tupcount_pages and not scanned_pages for the
304  * check described above; scanned_pages counts pages where we could not
305  * get cleanup lock, and which were processed only for frozenxid purposes.
306  *
307  * We do update relallvisible even in the corner case, since if the table
308  * is all-visible we'd definitely like to know that. But clamp the value
309  * to be not more than what we're setting relpages to.
310  *
311  * Also, don't change relfrozenxid/relminmxid if we skipped any pages,
312  * since then we don't know for certain that all tuples have a newer xmin.
313  */
314  new_rel_pages = vacrelstats->rel_pages;
315  new_rel_tuples = vacrelstats->new_rel_tuples;
316  if (vacrelstats->tupcount_pages == 0 && new_rel_pages > 0)
317  {
318  new_rel_pages = vacrelstats->old_rel_pages;
319  new_rel_tuples = vacrelstats->old_rel_tuples;
320  }
321 
322  visibilitymap_count(onerel, &new_rel_allvisible, NULL);
323  if (new_rel_allvisible > new_rel_pages)
324  new_rel_allvisible = new_rel_pages;
325 
326  new_frozen_xid = scanned_all_unfrozen ? FreezeLimit : InvalidTransactionId;
327  new_min_multi = scanned_all_unfrozen ? MultiXactCutoff : InvalidMultiXactId;
328 
329  vac_update_relstats(onerel,
330  new_rel_pages,
331  new_rel_tuples,
332  new_rel_allvisible,
333  vacrelstats->hasindex,
334  new_frozen_xid,
335  new_min_multi,
336  false);
337 
338  /* report results to the stats collector, too */
339  new_live_tuples = new_rel_tuples - vacrelstats->new_dead_tuples;
340  if (new_live_tuples < 0)
341  new_live_tuples = 0; /* just in case */
342 
344  onerel->rd_rel->relisshared,
345  new_live_tuples,
346  vacrelstats->new_dead_tuples);
348 
349  /* and log the action if appropriate */
350  if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0)
351  {
352  TimestampTz endtime = GetCurrentTimestamp();
353 
354  if (params->log_min_duration == 0 ||
355  TimestampDifferenceExceeds(starttime, endtime,
356  params->log_min_duration))
357  {
359 
360  TimestampDifference(starttime, endtime, &secs, &usecs);
361 
362  read_rate = 0;
363  write_rate = 0;
364  if ((secs > 0) || (usecs > 0))
365  {
366  read_rate = (double) BLCKSZ *VacuumPageMiss / (1024 * 1024) /
367  (secs + usecs / 1000000.0);
368  write_rate = (double) BLCKSZ *VacuumPageDirty / (1024 * 1024) /
369  (secs + usecs / 1000000.0);
370  }
371 
372  /*
373  * This is pretty messy, but we split it up so that we can skip
374  * emitting individual parts of the message when not applicable.
375  */
376  initStringInfo(&buf);
377  appendStringInfo(&buf, _("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n"),
380  RelationGetRelationName(onerel),
381  vacrelstats->num_index_scans);
382  appendStringInfo(&buf, _("pages: %u removed, %u remain, %u skipped due to pins, %u skipped frozen\n"),
383  vacrelstats->pages_removed,
384  vacrelstats->rel_pages,
385  vacrelstats->pinskipped_pages,
386  vacrelstats->frozenskipped_pages);
387  appendStringInfo(&buf,
388  _("tuples: %.0f removed, %.0f remain, %.0f are dead but not yet removable, oldest xmin: %u\n"),
389  vacrelstats->tuples_deleted,
390  vacrelstats->new_rel_tuples,
391  vacrelstats->new_dead_tuples,
392  OldestXmin);
393  appendStringInfo(&buf,
394  _("buffer usage: %d hits, %d misses, %d dirtied\n"),
398  appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"),
399  read_rate, write_rate);
400  appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0));
401 
402  ereport(LOG,
403  (errmsg_internal("%s", buf.data)));
404  pfree(buf.data);
405  }
406  }
407 }
double new_rel_tuples
Definition: vacuumlazy.c:120
int multixact_freeze_table_age
Definition: vacuum.h:142
void vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
Definition: vacuum.c:1539
BlockNumber rel_pages
Definition: vacuumlazy.c:113
uint32 TransactionId
Definition: c.h:397
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3032
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
double tuples_deleted
Definition: vacuumlazy.c:123
int64 TimestampTz
Definition: timestamp.h:39
int VacuumPageHit
Definition: globals.c:134
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3053
double old_rel_tuples
Definition: vacuumlazy.c:119
BlockNumber tupcount_pages
Definition: vacuumlazy.c:117
static void lazy_scan_heap(Relation onerel, int options, LVRelStats *vacrelstats, Relation *Irel, int nindexes, bool aggressive)
Definition: vacuumlazy.c:459
BlockNumber scanned_pages
Definition: vacuumlazy.c:114
#define INFO
Definition: elog.h:33
void vacuum_set_xid_limits(Relation rel, int freeze_min_age, int freeze_table_age, int multixact_freeze_min_age, int multixact_freeze_table_age, TransactionId *oldestXmin, TransactionId *freezeLimit, TransactionId *xidFullScanLimit, MultiXactId *multiXactCutoff, MultiXactId *mxactFullScanLimit)
Definition: vacuum.c:501
uint32 BlockNumber
Definition: block.h:31
BlockNumber pinskipped_pages
Definition: vacuumlazy.c:115
void visibilitymap_count(Relation rel, BlockNumber *all_visible, BlockNumber *all_frozen)
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:114
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
int freeze_table_age
Definition: vacuum.h:139
void pg_rusage_init(PGRUsage *ru0)
Definition: pg_rusage.c:27
BlockNumber old_rel_pages
Definition: vacuumlazy.c:112
void pfree(void *pointer)
Definition: mcxt.c:950
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:110
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
int freeze_min_age
Definition: vacuum.h:138
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
#define DEBUG2
Definition: elog.h:24
static TransactionId FreezeLimit
Definition: vacuumlazy.c:140
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3038
#define NoLock
Definition: lockdefs.h:34
static char * buf
Definition: pg_test_fsync.c:66
#define RowExclusiveLock
Definition: lockdefs.h:38
static MultiXactId MultiXactCutoff
Definition: vacuumlazy.c:141
const char * pg_rusage_show(const PGRUsage *ru0)
Definition: pg_rusage.c:40
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:437
static TransactionId OldestXmin
Definition: vacuumlazy.c:139
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3360
#define ereport(elevel, rest)
Definition: elog.h:122
void FreeSpaceMapVacuum(Relation rel)
Definition: freespace.c:379
void initStringInfo(StringInfo str)
Definition: stringinfo.c:65
void vac_open_indexes(Relation relation, LOCKMODE lockmode, int *nindexes, Relation **Irel)
Definition: vacuum.c:1496
static int elevel
Definition: vacuumlazy.c:137
bool hasindex
Definition: vacuumlazy.c:110
int VacuumPageDirty
Definition: globals.c:136
void * palloc0(Size size)
Definition: mcxt.c:878
void pgstat_progress_end_command(void)
Definition: pgstat.c:3104
Oid MyDatabaseId
Definition: globals.c:76
#define InvalidMultiXactId
Definition: multixact.h:23
static bool should_attempt_truncation(LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1698
#define PROGRESS_VACUUM_PHASE_FINAL_CLEANUP
Definition: progress.h:35
int num_index_scans
Definition: vacuumlazy.c:130
TransactionId MultiXactId
Definition: c.h:407
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static BufferAccessStrategy vac_strategy
Definition: vacuumlazy.c:143
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
double new_dead_tuples
Definition: vacuumlazy.c:121
#define PROGRESS_VACUUM_PHASE
Definition: progress.h:21
int log_min_duration
Definition: vacuum.h:145
void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples)
Definition: pgstat.c:1370
BlockNumber pages_removed
Definition: vacuumlazy.c:122
BlockNumber frozenskipped_pages
Definition: vacuumlazy.c:116
bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3154
int VacuumPageMiss
Definition: globals.c:135
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624
void vac_update_relstats(Relation relation, BlockNumber num_pages, double num_tuples, BlockNumber num_all_visible_pages, bool hasindex, TransactionId frozenxid, MultiXactId minmulti, bool in_outer_xact)
Definition: vacuum.c:785
#define _(x)
Definition: elog.c:84
#define RelationGetRelid(relation)
Definition: rel.h:417
int multixact_freeze_min_age
Definition: vacuum.h:140
static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
Definition: vacuumlazy.c:1716
#define RelationGetNamespace(relation)
Definition: rel.h:444
bool lock_waiter_detected
Definition: vacuumlazy.c:132
bool std_typanalyze ( VacAttrStats stats)

Definition at line 1725 of file analyze.c.

References VacAttrStats::attr, VacAttrStats::attrtypid, compute_distinct_stats(), compute_scalar_stats(), VacAttrStats::compute_stats, compute_trivial_stats(), default_statistics_target, StdAnalyzeData::eqfunc, StdAnalyzeData::eqopr, VacAttrStats::extra_data, get_opcode(), get_sort_group_operators(), InvalidOid, StdAnalyzeData::ltopr, VacAttrStats::minrows, NULL, OidIsValid, and palloc().

Referenced by array_typanalyze(), and examine_attribute().

1726 {
1727  Form_pg_attribute attr = stats->attr;
1728  Oid ltopr;
1729  Oid eqopr;
1730  StdAnalyzeData *mystats;
1731 
1732  /* If the attstattarget column is negative, use the default value */
1733  /* NB: it is okay to scribble on stats->attr since it's a copy */
1734  if (attr->attstattarget < 0)
1735  attr->attstattarget = default_statistics_target;
1736 
1737  /* Look for default "<" and "=" operators for column's type */
1739  false, false, false,
1740  &ltopr, &eqopr, NULL,
1741  NULL);
1742 
1743  /* Save the operator info for compute_stats routines */
1744  mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
1745  mystats->eqopr = eqopr;
1746  mystats->eqfunc = OidIsValid(eqopr) ? get_opcode(eqopr) : InvalidOid;
1747  mystats->ltopr = ltopr;
1748  stats->extra_data = mystats;
1749 
1750  /*
1751  * Determine which standard statistics algorithm to use
1752  */
1753  if (OidIsValid(eqopr) && OidIsValid(ltopr))
1754  {
1755  /* Seems to be a scalar datatype */
1757  /*--------------------
1758  * The following choice of minrows is based on the paper
1759  * "Random sampling for histogram construction: how much is enough?"
1760  * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
1761  * Proceedings of ACM SIGMOD International Conference on Management
1762  * of Data, 1998, Pages 436-447. Their Corollary 1 to Theorem 5
1763  * says that for table size n, histogram size k, maximum relative
1764  * error in bin size f, and error probability gamma, the minimum
1765  * random sample size is
1766  * r = 4 * k * ln(2*n/gamma) / f^2
1767  * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
1768  * r = 305.82 * k
1769  * Note that because of the log function, the dependence on n is
1770  * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
1771  * bin size error with probability 0.99. So there's no real need to
1772  * scale for n, which is a good thing because we don't necessarily
1773  * know it at this point.
1774  *--------------------
1775  */
1776  stats->minrows = 300 * attr->attstattarget;
1777  }
1778  else if (OidIsValid(eqopr))
1779  {
1780  /* We can still recognize distinct values */
1782  /* Might as well use the same minrows as above */
1783  stats->minrows = 300 * attr->attstattarget;
1784  }
1785  else
1786  {
1787  /* Can't do much but the trivial stuff */
1789  /* Might as well use the same minrows as above */
1790  stats->minrows = 300 * attr->attstattarget;
1791  }
1792 
1793  return true;
1794 }
int minrows
Definition: vacuum.h:92
static void compute_scalar_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:2247
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
Form_pg_attribute attr
Definition: vacuum.h:81
Oid attrtypid
Definition: vacuum.h:82
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
static void compute_distinct_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1895
#define InvalidOid
Definition: postgres_ext.h:36
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
#define NULL
Definition: c.h:229
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:187
static void compute_trivial_stats(VacAttrStatsP stats, AnalyzeAttrFetchFunc fetchfunc, int samplerows, double totalrows)
Definition: analyze.c:1805
void * palloc(Size size)
Definition: mcxt.c:849
AnalyzeAttrComputeStatsFunc compute_stats
Definition: vacuum.h:91
void * extra_data
Definition: vacuum.h:93
int default_statistics_target
Definition: analyze.c:77
void vac_close_indexes ( int  nindexes,
Relation Irel,
LOCKMODE  lockmode 
)

Definition at line 1539 of file vacuum.c.

References index_close(), NULL, and pfree().

Referenced by do_analyze_rel(), and lazy_vacuum_rel().

1540 {
1541  if (Irel == NULL)
1542  return;
1543 
1544  while (nindexes--)
1545  {
1546  Relation ind = Irel[nindexes];
1547 
1548  index_close(ind, lockmode);
1549  }
1550  pfree(Irel);
1551 }
void pfree(void *pointer)
Definition: mcxt.c:950
#define NULL
Definition: c.h:229
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
double vac_estimate_reltuples ( Relation  relation,
bool  is_analyze,
BlockNumber  total_pages,
BlockNumber  scanned_pages,
double  scanned_tuples 
)

Definition at line 685 of file vacuum.c.

References RelationData::rd_rel.

Referenced by acquire_sample_rows(), lazy_scan_heap(), and statapprox_heap().

689 {
690  BlockNumber old_rel_pages = relation->rd_rel->relpages;
691  double old_rel_tuples = relation->rd_rel->reltuples;
692  double old_density;
693  double new_density;
694  double multiplier;
695  double updated_density;
696 
697  /* If we did scan the whole table, just use the count as-is */
698  if (scanned_pages >= total_pages)
699  return scanned_tuples;
700 
701  /*
702  * If scanned_pages is zero but total_pages isn't, keep the existing value
703  * of reltuples. (Note: callers should avoid updating the pg_class
704  * statistics in this situation, since no new information has been
705  * provided.)
706  */
707  if (scanned_pages == 0)
708  return old_rel_tuples;
709 
710  /*
711  * If old value of relpages is zero, old density is indeterminate; we
712  * can't do much except scale up scanned_tuples to match total_pages.
713  */
714  if (old_rel_pages == 0)
715  return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
716 
717  /*
718  * Okay, we've covered the corner cases. The normal calculation is to
719  * convert the old measurement to a density (tuples per page), then update
720  * the density using an exponential-moving-average approach, and finally
721  * compute reltuples as updated_density * total_pages.
722  *
723  * For ANALYZE, the moving average multiplier is just the fraction of the
724  * table's pages we scanned. This is equivalent to assuming that the
725  * tuple density in the unscanned pages didn't change. Of course, it
726  * probably did, if the new density measurement is different. But over
727  * repeated cycles, the value of reltuples will converge towards the
728  * correct value, if repeated measurements show the same new density.
729  *
730  * For VACUUM, the situation is a bit different: we have looked at a
731  * nonrandom sample of pages, but we know for certain that the pages we
732  * didn't look at are precisely the ones that haven't changed lately.
733  * Thus, there is a reasonable argument for doing exactly the same thing
734  * as for the ANALYZE case, that is use the old density measurement as the
735  * value for the unscanned pages.
736  *
737  * This logic could probably use further refinement.
738  */
739  old_density = old_rel_tuples / old_rel_pages;
740  new_density = scanned_tuples / scanned_pages;
741  multiplier = (double) scanned_pages / (double) total_pages;
742  updated_density = old_density + (new_density - old_density) * multiplier;
743  return floor(updated_density * total_pages + 0.5);
744 }
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:114
void vac_open_indexes ( Relation  relation,
LOCKMODE  lockmode,
int *  nindexes,
Relation **  Irel 
)

Definition at line 1496 of file vacuum.c.

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

Referenced by do_analyze_rel(), and lazy_vacuum_rel().

1498 {
1499  List *indexoidlist;
1500  ListCell *indexoidscan;
1501  int i;
1502 
1503  Assert(lockmode != NoLock);
1504 
1505  indexoidlist = RelationGetIndexList(relation);
1506 
1507  /* allocate enough memory for all indexes */
1508  i = list_length(indexoidlist);
1509 
1510  if (i > 0)
1511  *Irel = (Relation *) palloc(i * sizeof(Relation));
1512  else
1513  *Irel = NULL;
1514 
1515  /* collect just the ready indexes */
1516  i = 0;
1517  foreach(indexoidscan, indexoidlist)
1518  {
1519  Oid indexoid = lfirst_oid(indexoidscan);
1520  Relation indrel;
1521 
1522  indrel = index_open(indexoid, lockmode);
1523  if (IndexIsReady(indrel->rd_index))
1524  (*Irel)[i++] = indrel;
1525  else
1526  index_close(indrel, lockmode);
1527  }
1528 
1529  *nindexes = i;
1530 
1531  list_free(indexoidlist);
1532 }
#define IndexIsReady(indexForm)
Definition: pg_index.h:108
unsigned int Oid
Definition: postgres_ext.h:31
Form_pg_index rd_index
Definition: rel.h:159
#define NoLock
Definition: lockdefs.h:34
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static int list_length(const List *l)
Definition: pg_list.h:89
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4338
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:176
void * palloc(Size size)
Definition: mcxt.c:849
void list_free(List *list)
Definition: list.c:1133
int i
Definition: pg_list.h:45
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:151
#define lfirst_oid(lc)
Definition: pg_list.h:108
void vac_update_datfrozenxid ( void  )

Definition at line 922 of file vacuum.c.

References AccessShareLock, Assert, DATABASEOID, DatabaseRelationId, elog, ERROR, ForceTransactionIdLimitUpdate(), GetOldestMultiXactId(), GetOldestXmin(), GETSTRUCT, heap_close, heap_freetuple(), heap_inplace_update(), heap_open(), HeapTupleIsValid, InvalidOid, MultiXactIdIsValid, MultiXactIdPrecedes(), MyDatabaseId, NULL, ObjectIdGetDatum, PROCARRAY_FLAGS_VACUUM, ReadNewTransactionId(), ReadNextMultiXactId(), RelationRelationId, RELKIND_MATVIEW, RELKIND_RELATION, RELKIND_TOASTVALUE, RowExclusiveLock, SearchSysCacheCopy1, systable_beginscan(), systable_endscan(), systable_getnext(), TransactionIdIsNormal, TransactionIdPrecedes(), and vac_truncate_clog().

Referenced by do_autovacuum(), and vacuum().

923 {
924  HeapTuple tuple;
925  Form_pg_database dbform;
926  Relation relation;
927  SysScanDesc scan;
928  HeapTuple classTup;
929  TransactionId newFrozenXid;
930  MultiXactId newMinMulti;
931  TransactionId lastSaneFrozenXid;
932  MultiXactId lastSaneMinMulti;
933  bool bogus = false;
934  bool dirty = false;
935 
936  /*
937  * Initialize the "min" calculation with GetOldestXmin, which is a
938  * reasonable approximation to the minimum relfrozenxid for not-yet-
939  * committed pg_class entries for new tables; see AddNewRelationTuple().
940  * So we cannot produce a wrong minimum by starting with this.
941  */
942  newFrozenXid = GetOldestXmin(NULL, PROCARRAY_FLAGS_VACUUM);
943 
944  /*
945  * Similarly, initialize the MultiXact "min" with the value that would be
946  * used on pg_class for new tables. See AddNewRelationTuple().
947  */
948  newMinMulti = GetOldestMultiXactId();
949 
950  /*
951  * Identify the latest relfrozenxid and relminmxid values that we could
952  * validly see during the scan. These are conservative values, but it's
953  * not really worth trying to be more exact.
954  */
955  lastSaneFrozenXid = ReadNewTransactionId();
956  lastSaneMinMulti = ReadNextMultiXactId();
957 
958  /*
959  * We must seqscan pg_class to find the minimum Xid, because there is no
960  * index that can help us here.
961  */
963 
964  scan = systable_beginscan(relation, InvalidOid, false,
965  NULL, 0, NULL);
966 
967  while ((classTup = systable_getnext(scan)) != NULL)
968  {
969  Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
970 
971  /*
972  * Only consider relations able to hold unfrozen XIDs (anything else
973  * should have InvalidTransactionId in relfrozenxid anyway.)
974  */
975  if (classForm->relkind != RELKIND_RELATION &&
976  classForm->relkind != RELKIND_MATVIEW &&
977  classForm->relkind != RELKIND_TOASTVALUE)
978  continue;
979 
980  Assert(TransactionIdIsNormal(classForm->relfrozenxid));
981  Assert(MultiXactIdIsValid(classForm->relminmxid));
982 
983  /*
984  * If things are working properly, no relation should have a
985  * relfrozenxid or relminmxid that is "in the future". However, such
986  * cases have been known to arise due to bugs in pg_upgrade. If we
987  * see any entries that are "in the future", chicken out and don't do
988  * anything. This ensures we won't truncate clog before those
989  * relations have been scanned and cleaned up.
990  */
991  if (TransactionIdPrecedes(lastSaneFrozenXid, classForm->relfrozenxid) ||
992  MultiXactIdPrecedes(lastSaneMinMulti, classForm->relminmxid))
993  {
994  bogus = true;
995  break;
996  }
997 
998  if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
999  newFrozenXid = classForm->relfrozenxid;
1000 
1001  if (MultiXactIdPrecedes(classForm->relminmxid, newMinMulti))
1002  newMinMulti = classForm->relminmxid;
1003  }
1004 
1005  /* we're done with pg_class */
1006  systable_endscan(scan);
1007  heap_close(relation, AccessShareLock);
1008 
1009  /* chicken out if bogus data found */
1010  if (bogus)
1011  return;
1012 
1013  Assert(TransactionIdIsNormal(newFrozenXid));
1014  Assert(MultiXactIdIsValid(newMinMulti));
1015 
1016  /* Now fetch the pg_database tuple we need to update. */
1018 
1019  /* Fetch a copy of the tuple to scribble on */
1021  if (!HeapTupleIsValid(tuple))
1022  elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
1023  dbform = (Form_pg_database) GETSTRUCT(tuple);
1024 
1025  /*
1026  * As in vac_update_relstats(), we ordinarily don't want to let
1027  * datfrozenxid go backward; but if it's "in the future" then it must be
1028  * corrupt and it seems best to overwrite it.
1029  */
1030  if (dbform->datfrozenxid != newFrozenXid &&
1031  (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) ||
1032  TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid)))
1033  {
1034  dbform->datfrozenxid = newFrozenXid;
1035  dirty = true;
1036  }
1037  else
1038  newFrozenXid = dbform->datfrozenxid;
1039 
1040  /* Ditto for datminmxid */
1041  if (dbform->datminmxid != newMinMulti &&
1042  (MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) ||
1043  MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid)))
1044  {
1045  dbform->datminmxid = newMinMulti;
1046  dirty = true;
1047  }
1048  else
1049  newMinMulti = dbform->datminmxid;
1050 
1051  if (dirty)
1052  heap_inplace_update(relation, tuple);
1053 
1054  heap_freetuple(tuple);
1055  heap_close(relation, RowExclusiveLock);
1056 
1057  /*
1058  * If we were able to advance datfrozenxid or datminmxid, see if we can
1059  * truncate pg_xact and/or pg_multixact. Also do it if the shared
1060  * XID-wrap-limit info is stale, since this action will update that too.
1061  */
1062  if (dirty || ForceTransactionIdLimitUpdate())
1063  vac_truncate_clog(newFrozenXid, newMinMulti,
1064  lastSaneFrozenXid, lastSaneMinMulti);
1065 }
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:499
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
uint32 TransactionId
Definition: c.h:397
FormData_pg_database * Form_pg_database
Definition: pg_database.h:57
#define DatabaseRelationId
Definition: pg_database.h:29
#define RelationRelationId
Definition: pg_class.h:29
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define AccessShareLock
Definition: lockdefs.h:36
#define PROCARRAY_FLAGS_VACUUM
Definition: procarray.h:50
#define heap_close(r, l)
Definition: heapam.h:97
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:328
bool ForceTransactionIdLimitUpdate(void)
Definition: varsup.c:429
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:416
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
TransactionId ReadNewTransactionId(void)
Definition: varsup.c:250
#define MultiXactIdIsValid(multi)
Definition: multixact.h:27
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2491
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
Oid MyDatabaseId
Definition: globals.c:76
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define InvalidOid
Definition: postgres_ext.h:36
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1314
TransactionId MultiXactId
Definition: c.h:407
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3140
static void vac_truncate_clog(TransactionId frozenXID, MultiXactId minMulti, TransactionId lastSaneFrozenXid, MultiXactId lastSaneMinMulti)
Definition: vacuum.c:1086
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:161
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:6194
#define elog
Definition: elog.h:219
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define RELKIND_RELATION
Definition: pg_class.h:160
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:721
void vac_update_relstats ( Relation  relation,
BlockNumber  num_pages,
double  num_tuples,
BlockNumber  num_all_visible_pages,
bool  hasindex,
TransactionId  frozenxid,
MultiXactId  minmulti,
bool  in_outer_xact 
)

Definition at line 785 of file vacuum.c.

References elog, ERROR, GETSTRUCT, heap_close, heap_inplace_update(), heap_open(), HeapTupleIsValid, MultiXactIdIsValid, MultiXactIdPrecedes(), NULL, ObjectIdGetDatum, RelationData::rd_rules, ReadNewTransactionId(), ReadNextMultiXactId(), RelationGetRelid, RelationRelationId, RELOID, RowExclusiveLock, SearchSysCacheCopy1, TransactionIdIsNormal, TransactionIdPrecedes(), and RelationData::trigdesc.

Referenced by do_analyze_rel(), lazy_cleanup_index(), and lazy_vacuum_rel().

791 {
792  Oid relid = RelationGetRelid(relation);
793  Relation rd;
794  HeapTuple ctup;
795  Form_pg_class pgcform;
796  bool dirty;
797 
799 
800  /* Fetch a copy of the tuple to scribble on */
802  if (!HeapTupleIsValid(ctup))
803  elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
804  relid);
805  pgcform = (Form_pg_class) GETSTRUCT(ctup);
806 
807  /* Apply statistical updates, if any, to copied tuple */
808 
809  dirty = false;
810  if (pgcform->relpages != (int32) num_pages)
811  {
812  pgcform->relpages = (int32) num_pages;
813  dirty = true;
814  }
815  if (pgcform->reltuples != (float4) num_tuples)
816  {
817  pgcform->reltuples = (float4) num_tuples;
818  dirty = true;
819  }
820  if (pgcform->relallvisible != (int32) num_all_visible_pages)
821  {
822  pgcform->relallvisible = (int32) num_all_visible_pages;
823  dirty = true;
824  }
825 
826  /* Apply DDL updates, but not inside an outer transaction (see above) */
827 
828  if (!in_outer_xact)
829  {
830  /*
831  * If we didn't find any indexes, reset relhasindex.
832  */
833  if (pgcform->relhasindex && !hasindex)
834  {
835  pgcform->relhasindex = false;
836  dirty = true;
837  }
838 
839  /*
840  * If we have discovered that there are no indexes, then there's no
841  * primary key either. This could be done more thoroughly...
842  */
843  if (pgcform->relhaspkey && !hasindex)
844  {
845  pgcform->relhaspkey = false;
846  dirty = true;
847  }
848 
849  /* We also clear relhasrules and relhastriggers if needed */
850  if (pgcform->relhasrules && relation->rd_rules == NULL)
851  {
852  pgcform->relhasrules = false;
853  dirty = true;
854  }
855  if (pgcform->relhastriggers && relation->trigdesc == NULL)
856  {
857  pgcform->relhastriggers = false;
858  dirty = true;
859  }
860  }
861 
862  /*
863  * Update relfrozenxid, unless caller passed InvalidTransactionId
864  * indicating it has no new data.
865  *
866  * Ordinarily, we don't let relfrozenxid go backwards: if things are
867  * working correctly, the only way the new frozenxid could be older would
868  * be if a previous VACUUM was done with a tighter freeze_min_age, in
869  * which case we don't want to forget the work it already did. However,
870  * if the stored relfrozenxid is "in the future", then it must be corrupt
871  * and it seems best to overwrite it with the cutoff we used this time.
872  * This should match vac_update_datfrozenxid() concerning what we consider
873  * to be "in the future".
874  */
875  if (TransactionIdIsNormal(frozenxid) &&
876  pgcform->relfrozenxid != frozenxid &&
877  (TransactionIdPrecedes(pgcform->relfrozenxid, frozenxid) ||
879  pgcform->relfrozenxid)))
880  {
881  pgcform->relfrozenxid = frozenxid;
882  dirty = true;
883  }
884 
885  /* Similarly for relminmxid */
886  if (MultiXactIdIsValid(minmulti) &&
887  pgcform->relminmxid != minmulti &&
888  (MultiXactIdPrecedes(pgcform->relminmxid, minmulti) ||
889  MultiXactIdPrecedes(ReadNextMultiXactId(), pgcform->relminmxid)))
890  {
891  pgcform->relminmxid = minmulti;
892  dirty = true;
893  }
894 
895  /* If anything changed, write out the tuple. */
896  if (dirty)
897  heap_inplace_update(rd, ctup);
898 
900 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define RelationRelationId
Definition: pg_class.h:29
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:256
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
TriggerDesc * trigdesc
Definition: rel.h:120
#define RowExclusiveLock
Definition: lockdefs.h:38
TransactionId ReadNewTransactionId(void)
Definition: varsup.c:250
#define MultiXactIdIsValid(multi)
Definition: multixact.h:27
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
float float4
Definition: c.h:380
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
RuleLock * rd_rules
Definition: rel.h:118
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3140
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:161
void heap_inplace_update(Relation relation, HeapTuple tuple)
Definition: heapam.c:6194
#define elog
Definition: elog.h:219
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define RelationGetRelid(relation)
Definition: rel.h:417
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:721
void vacuum ( int  options,
RangeVar relation,
Oid  relid,
VacuumParams params,
List va_cols,
BufferAccessStrategy  bstrategy,
bool  isTopLevel 
)

Definition at line 149 of file vacuum.c.

References ActiveSnapshotSet(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), analyze_rel(), Assert, BAS_VACUUM, CommitTransactionCommand(), cur, ereport, errcode(), errmsg(), ERROR, get_rel_oids(), GetAccessStrategy(), GetTransactionSnapshot(), IsAutoVacuumWorkerProcess(), IsInTransactionChain(), lfirst_oid, list_length(), MemoryContextDelete(), MemoryContextSwitchTo(), NULL, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pgstat_vacuum_stat(), PopActiveSnapshot(), PortalContext, PreventTransactionChain(), PushActiveSnapshot(), StartTransactionCommand(), vac_update_datfrozenxid(), VACOPT_ANALYZE, VACOPT_DISABLE_PAGE_SKIPPING, VACOPT_FULL, VACOPT_VACUUM, vacuum_rel(), VacuumCostActive, VacuumCostBalance, VacuumCostDelay, VacuumPageDirty, VacuumPageHit, and VacuumPageMiss.

Referenced by autovacuum_do_vac_analyze(), and ExecVacuum().

151 {
152  const char *stmttype;
153  volatile bool in_outer_xact,
154  use_own_xacts;
155  List *relations;
156  static bool in_vacuum = false;
157 
158  Assert(params != NULL);
159 
160  stmttype = (options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
161 
162  /*
163  * We cannot run VACUUM inside a user transaction block; if we were inside
164  * a transaction, then our commit- and start-transaction-command calls
165  * would not have the intended effect! There are numerous other subtle
166  * dependencies on this, too.
167  *
168  * ANALYZE (without VACUUM) can run either way.
169  */
170  if (options & VACOPT_VACUUM)
171  {
172  PreventTransactionChain(isTopLevel, stmttype);
173  in_outer_xact = false;
174  }
175  else
176  in_outer_xact = IsInTransactionChain(isTopLevel);
177 
178  /*
179  * Due to static variables vac_context, anl_context and vac_strategy,
180  * vacuum() is not reentrant. This matters when VACUUM FULL or ANALYZE
181  * calls a hostile index expression that itself calls ANALYZE.
182  */
183  if (in_vacuum)
184  ereport(ERROR,
185  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
186  errmsg("%s cannot be executed from VACUUM or ANALYZE",
187  stmttype)));
188 
189  /*
190  * Sanity check DISABLE_PAGE_SKIPPING option.
191  */
192  if ((options & VACOPT_FULL) != 0 &&
194  ereport(ERROR,
195  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
196  errmsg("VACUUM option DISABLE_PAGE_SKIPPING cannot be used with FULL")));
197 
198  /*
199  * Send info about dead objects to the statistics collector, unless we are
200  * in autovacuum --- autovacuum.c does this for itself.
201  */
202  if ((options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
204 
205  /*
206  * Create special memory context for cross-transaction storage.
207  *
208  * Since it is a child of PortalContext, it will go away eventually even
209  * if we suffer an error; there's no need for special abort cleanup logic.
210  */
212  "Vacuum",
214 
215  /*
216  * If caller didn't give us a buffer strategy object, make one in the
217  * cross-transaction memory context.
218  */
219  if (bstrategy == NULL)
220  {
222 
223  bstrategy = GetAccessStrategy(BAS_VACUUM);
224  MemoryContextSwitchTo(old_context);
225  }
226  vac_strategy = bstrategy;
227 
228  /*
229  * Build list of relations to process, unless caller gave us one. (If we
230  * build one, we put it in vac_context for safekeeping.)
231  */
232  relations = get_rel_oids(relid, relation);
233 
234  /*
235  * Decide whether we need to start/commit our own transactions.
236  *
237  * For VACUUM (with or without ANALYZE): always do so, so that we can
238  * release locks as soon as possible. (We could possibly use the outer
239  * transaction for a one-table VACUUM, but handling TOAST tables would be
240  * problematic.)
241  *
242  * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
243  * start/commit our own transactions. Also, there's no need to do so if
244  * only processing one relation. For multiple relations when not within a
245  * transaction block, and also in an autovacuum worker, use own
246  * transactions so we can release locks sooner.
247  */
248  if (options & VACOPT_VACUUM)
249  use_own_xacts = true;
250  else
251  {
254  use_own_xacts = true;
255  else if (in_outer_xact)
256  use_own_xacts = false;
257  else if (list_length(relations) > 1)
258  use_own_xacts = true;
259  else
260  use_own_xacts = false;
261  }
262 
263  /*
264  * vacuum_rel expects to be entered with no transaction active; it will
265  * start and commit its own transaction. But we are called by an SQL
266  * command, and so we are executing inside a transaction already. We
267  * commit the transaction started in PostgresMain() here, and start
268  * another one before exiting to match the commit waiting for us back in
269  * PostgresMain().
270  */
271  if (use_own_xacts)
272  {
273  Assert(!in_outer_xact);
274 
275  /* ActiveSnapshot is not set by autovacuum */
276  if (ActiveSnapshotSet())
278 
279  /* matches the StartTransaction in PostgresMain() */
281  }
282 
283  /* Turn vacuum cost accounting on or off */
284  PG_TRY();
285  {
286  ListCell *cur;
287 
288  in_vacuum = true;
290  VacuumCostBalance = 0;
291  VacuumPageHit = 0;
292  VacuumPageMiss = 0;
293  VacuumPageDirty = 0;
294 
295  /*
296  * Loop to process each selected relation.
297  */
298  foreach(cur, relations)
299  {
300  Oid relid = lfirst_oid(cur);
301 
302  if (options & VACOPT_VACUUM)
303  {
304  if (!vacuum_rel(relid, relation, options, params))
305  continue;
306  }
307 
308  if (options & VACOPT_ANALYZE)
309  {
310  /*
311  * If using separate xacts, start one for analyze. Otherwise,
312  * we can use the outer transaction.
313  */
314  if (use_own_xacts)
315  {
317  /* functions in indexes may want a snapshot set */
319  }
320 
321  analyze_rel(relid, relation, options, params,
322  va_cols, in_outer_xact, vac_strategy);
323 
324  if (use_own_xacts)
325  {
328  }
329  }
330  }
331  }
332  PG_CATCH();
333  {
334  in_vacuum = false;
335  VacuumCostActive = false;
336  PG_RE_THROW();
337  }
338  PG_END_TRY();
339 
340  in_vacuum = false;
341  VacuumCostActive = false;
342 
343  /*
344  * Finish up processing.
345  */
346  if (use_own_xacts)
347  {
348  /* here, we are not in a transaction */
349 
350  /*
351  * This matches the CommitTransaction waiting for us in
352  * PostgresMain().
353  */
355  }
356 
357  if ((options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
358  {
359  /*
360  * Update pg_database.datfrozenxid, and truncate pg_xact if possible.
361  * (autovacuum.c does this for itself.)
362  */
364  }
365 
366  /*
367  * Clean up working storage --- note we must do this after
368  * StartTransactionCommand, else we might be trying to delete the active
369  * context!
370  */
372  vac_context = NULL;
373 }
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:525
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
int VacuumCostBalance
Definition: globals.c:138
void vac_update_datfrozenxid(void)
Definition: vacuum.c:922
int VacuumPageHit
Definition: globals.c:134
void CommitTransactionCommand(void)
Definition: xact.c:2747
void analyze_rel(Oid relid, RangeVar *relation, int options, VacuumParams *params, List *va_cols, bool in_outer_xact, BufferAccessStrategy bstrategy)
Definition: analyze.c:111
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static BufferAccessStrategy vac_strategy
Definition: vacuum.c:66
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:575
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
unsigned int Oid
Definition: postgres_ext.h:31
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
static List * get_rel_oids(Oid relid, const RangeVar *vacrel)
Definition: vacuum.c:382
MemoryContext PortalContext
Definition: mcxt.c:52
#define ERROR
Definition: elog.h:43
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
static MemoryContext vac_context
Definition: vacuum.c:65
bool ActiveSnapshotSet(void)
Definition: snapmgr.c:846
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3360
#define ereport(elevel, rest)
Definition: elog.h:122
void pgstat_vacuum_stat(void)
Definition: pgstat.c:987
int VacuumPageDirty
Definition: globals.c:136
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
int VacuumCostDelay
Definition: globals.c:132
#define PG_CATCH()
Definition: elog.h:293
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static bool vacuum_rel(Oid relid, RangeVar *relation, int options, VacuumParams *params)
Definition: vacuum.c:1224
void StartTransactionCommand(void)
Definition: xact.c:2677
static int list_length(const List *l)
Definition: pg_list.h:89
#define PG_RE_THROW()
Definition: elog.h:314
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool IsInTransactionChain(bool isTopLevel)
Definition: xact.c:3270
int VacuumPageMiss
Definition: globals.c:135
#define PG_TRY()
Definition: elog.h:284
Definition: pg_list.h:45
#define PG_END_TRY()
Definition: elog.h:300
#define lfirst_oid(lc)
Definition: pg_list.h:108
void PreventTransactionChain(bool isTopLevel, const char *stmtType)
Definition: xact.c:3154
bool VacuumCostActive
Definition: globals.c:139
void vacuum_delay_point ( void  )

Definition at line 1560 of file vacuum.c.

References AutoVacuumUpdateDelay(), CHECK_FOR_INTERRUPTS, InterruptPending, pg_usleep(), VacuumCostActive, VacuumCostBalance, VacuumCostDelay, and VacuumCostLimit.

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(), ginVacuumPostingTreeLeaves(), gistbulkdelete(), gistvacuumcleanup(), hashbucketcleanup(), lazy_scan_heap(), lazy_vacuum_heap(), spgprocesspending(), and spgvacuumpage().

1561 {
1562  /* Always check for interrupts */
1564 
1565  /* Nap if appropriate */
1568  {
1569  int msec;
1570 
1572  if (msec > VacuumCostDelay * 4)
1573  msec = VacuumCostDelay * 4;
1574 
1575  pg_usleep(msec * 1000L);
1576 
1577  VacuumCostBalance = 0;
1578 
1579  /* update balance values for workers */
1581 
1582  /* Might have gotten an interrupt while sleeping */
1584  }
1585 }
int VacuumCostBalance
Definition: globals.c:138
void pg_usleep(long microsec)
Definition: signal.c:53
int VacuumCostLimit
Definition: globals.c:131
int VacuumCostDelay
Definition: globals.c:132
volatile bool InterruptPending
Definition: globals.c:29
void AutoVacuumUpdateDelay(void)
Definition: autovacuum.c:1779
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
bool VacuumCostActive
Definition: globals.c:139
void vacuum_set_xid_limits ( Relation  rel,
int  freeze_min_age,
int  freeze_table_age,
int  multixact_freeze_min_age,
int  multixact_freeze_table_age,
TransactionId oldestXmin,
TransactionId freezeLimit,
TransactionId xidFullScanLimit,
MultiXactId multiXactCutoff,
MultiXactId mxactFullScanLimit 
)

Definition at line 501 of file vacuum.c.

References Assert, autovacuum_freeze_max_age, ereport, errhint(), errmsg(), FirstMultiXactId, FirstNormalTransactionId, GetOldestMultiXactId(), GetOldestXmin(), Min, MultiXactIdPrecedes(), MultiXactMemberFreezeThreshold(), NULL, PROCARRAY_FLAGS_VACUUM, ReadNewTransactionId(), ReadNextMultiXactId(), TransactionIdIsNormal, TransactionIdLimitedForOldSnapshots(), TransactionIdPrecedes(), vacuum_freeze_min_age, vacuum_freeze_table_age, vacuum_multixact_freeze_min_age, vacuum_multixact_freeze_table_age, and WARNING.

Referenced by copy_heap_data(), and lazy_vacuum_rel().

511 {
512  int freezemin;
513  int mxid_freezemin;
514  int effective_multixact_freeze_max_age;
515  TransactionId limit;
516  TransactionId safeLimit;
517  MultiXactId mxactLimit;
518  MultiXactId safeMxactLimit;
519 
520  /*
521  * We can always ignore processes running lazy vacuum. This is because we
522  * use these values only for deciding which tuples we must keep in the
523  * tables. Since lazy vacuum doesn't write its XID anywhere, it's safe to
524  * ignore it. In theory it could be problematic to ignore lazy vacuums in
525  * a full vacuum, but keep in mind that only one vacuum process can be
526  * working on a particular table at any time, and that each vacuum is
527  * always an independent transaction.
528  */
529  *oldestXmin =
531 
532  Assert(TransactionIdIsNormal(*oldestXmin));
533 
534  /*
535  * Determine the minimum freeze age to use: as specified by the caller, or
536  * vacuum_freeze_min_age, but in any case not more than half
537  * autovacuum_freeze_max_age, so that autovacuums to prevent XID
538  * wraparound won't occur too frequently.
539  */
540  freezemin = freeze_min_age;
541  if (freezemin < 0)
542  freezemin = vacuum_freeze_min_age;
543  freezemin = Min(freezemin, autovacuum_freeze_max_age / 2);
544  Assert(freezemin >= 0);
545 
546  /*
547  * Compute the cutoff XID, being careful not to generate a "permanent" XID
548  */
549  limit = *oldestXmin - freezemin;
550  if (!TransactionIdIsNormal(limit))
551  limit = FirstNormalTransactionId;
552 
553  /*
554  * If oldestXmin is very far back (in practice, more than
555  * autovacuum_freeze_max_age / 2 XIDs old), complain and force a minimum
556  * freeze age of zero.
557  */
559  if (!TransactionIdIsNormal(safeLimit))
560  safeLimit = FirstNormalTransactionId;
561 
562  if (TransactionIdPrecedes(limit, safeLimit))
563  {
565  (errmsg("oldest xmin is far in the past"),
566  errhint("Close open transactions soon to avoid wraparound problems.")));
567  limit = *oldestXmin;
568  }
569 
570  *freezeLimit = limit;
571 
572  /*
573  * Compute the multixact age for which freezing is urgent. This is
574  * normally autovacuum_multixact_freeze_max_age, but may be less if we are
575  * short of multixact member space.
576  */
577  effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
578 
579  /*
580  * Determine the minimum multixact freeze age to use: as specified by
581  * caller, or vacuum_multixact_freeze_min_age, but in any case not more
582  * than half effective_multixact_freeze_max_age, so that autovacuums to
583  * prevent MultiXact wraparound won't occur too frequently.
584  */
585  mxid_freezemin = multixact_freeze_min_age;
586  if (mxid_freezemin < 0)
587  mxid_freezemin = vacuum_multixact_freeze_min_age;
588  mxid_freezemin = Min(mxid_freezemin,
589  effective_multixact_freeze_max_age / 2);
590  Assert(mxid_freezemin >= 0);
591 
592  /* compute the cutoff multi, being careful to generate a valid value */
593  mxactLimit = GetOldestMultiXactId() - mxid_freezemin;
594  if (mxactLimit < FirstMultiXactId)
595  mxactLimit = FirstMultiXactId;
596 
597  safeMxactLimit =
598  ReadNextMultiXactId() - effective_multixact_freeze_max_age;
599  if (safeMxactLimit < FirstMultiXactId)
600  safeMxactLimit = FirstMultiXactId;
601 
602  if (MultiXactIdPrecedes(mxactLimit, safeMxactLimit))
603  {
605  (errmsg("oldest multixact is far in the past"),
606  errhint("Close open transactions with multixacts soon to avoid wraparound problems.")));
607  mxactLimit = safeMxactLimit;
608  }
609 
610  *multiXactCutoff = mxactLimit;
611 
612  if (xidFullScanLimit != NULL)
613  {
614  int freezetable;
615 
616  Assert(mxactFullScanLimit != NULL);
617 
618  /*
619  * Determine the table freeze age to use: as specified by the caller,
620  * or vacuum_freeze_table_age, but in any case not more than
621  * autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
622  * VACUUM schedule, the nightly VACUUM gets a chance to freeze tuples
623  * before anti-wraparound autovacuum is launched.
624  */
625  freezetable = freeze_table_age;
626  if (freezetable < 0)
627  freezetable = vacuum_freeze_table_age;
628  freezetable = Min(freezetable, autovacuum_freeze_max_age * 0.95);
629  Assert(freezetable >= 0);
630 
631  /*
632  * Compute XID limit causing a full-table vacuum, being careful not to
633  * generate a "permanent" XID.
634  */
635  limit = ReadNewTransactionId() - freezetable;
636  if (!TransactionIdIsNormal(limit))
637  limit = FirstNormalTransactionId;
638 
639  *xidFullScanLimit = limit;
640 
641  /*
642  * Similar to the above, determine the table freeze age to use for
643  * multixacts: as specified by the caller, or
644  * vacuum_multixact_freeze_table_age, but in any case not more than
645  * autovacuum_multixact_freeze_table_age * 0.95, so that if you have
646  * e.g. nightly VACUUM schedule, the nightly VACUUM gets a chance to
647  * freeze multixacts before anti-wraparound autovacuum is launched.
648  */
649  freezetable = multixact_freeze_table_age;
650  if (freezetable < 0)
651  freezetable = vacuum_multixact_freeze_table_age;
652  freezetable = Min(freezetable,
653  effective_multixact_freeze_max_age * 0.95);
654  Assert(freezetable >= 0);
655 
656  /*
657  * Compute MultiXact limit causing a full-table vacuum, being careful
658  * to generate a valid MultiXact value.
659  */
660  mxactLimit = ReadNextMultiXactId() - freezetable;
661  if (mxactLimit < FirstMultiXactId)
662  mxactLimit = FirstMultiXactId;
663 
664  *mxactFullScanLimit = mxactLimit;
665  }
666  else
667  {
668  Assert(mxactFullScanLimit == NULL);
669  }
670 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int vacuum_multixact_freeze_table_age
Definition: vacuum.c:61
uint32 TransactionId
Definition: c.h:397
#define Min(x, y)
Definition: c.h:806
TransactionId TransactionIdLimitedForOldSnapshots(TransactionId recentXmin, Relation relation)
Definition: snapmgr.c:1698
#define PROCARRAY_FLAGS_VACUUM
Definition: procarray.h:50
#define FirstNormalTransactionId
Definition: transam.h:34
int autovacuum_freeze_max_age
Definition: autovacuum.c:120
int vacuum_multixact_freeze_min_age
Definition: vacuum.c:60
TransactionId ReadNewTransactionId(void)
Definition: varsup.c:250
#define FirstMultiXactId
Definition: multixact.h:24
#define ereport(elevel, rest)
Definition: elog.h:122
int MultiXactMemberFreezeThreshold(void)
Definition: multixact.c:2817
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define WARNING
Definition: elog.h:40
MultiXactId GetOldestMultiXactId(void)
Definition: multixact.c:2491
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1314
TransactionId MultiXactId
Definition: c.h:407
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
int vacuum_freeze_min_age
Definition: vacuum.c:58
bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2)
Definition: multixact.c:3140
int vacuum_freeze_table_age
Definition: vacuum.c:59
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
MultiXactId ReadNextMultiXactId(void)
Definition: multixact.c:721

Variable Documentation

PGDLLIMPORT int default_statistics_target

Definition at line 77 of file analyze.c.

Referenced by range_typanalyze(), std_typanalyze(), and ts_typanalyze().

int vacuum_freeze_min_age

Definition at line 58 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

int vacuum_freeze_table_age

Definition at line 59 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

int vacuum_multixact_freeze_min_age

Definition at line 60 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().

int vacuum_multixact_freeze_table_age

Definition at line 61 of file vacuum.c.

Referenced by do_autovacuum(), and vacuum_set_xid_limits().