1 /*-------------------------------------------------------------------------
4 * The postgres vacuum cleaner.
6 * This file now includes only control and dispatch code for VACUUM and
7 * ANALYZE commands. Regular VACUUM is implemented in vacuumlazy.c,
8 * ANALYZE in analyze.c, and VACUUM FULL is a variant of CLUSTER, handled
12 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
17 * src/backend/commands/vacuum.c
19 *-------------------------------------------------------------------------
25 #include "access/clog.h"
26 #include "access/genam.h"
27 #include "access/heapam.h"
28 #include "access/htup_details.h"
29 #include "access/multixact.h"
30 #include "access/transam.h"
31 #include "access/xact.h"
32 #include "catalog/namespace.h"
33 #include "catalog/pg_database.h"
34 #include "catalog/pg_namespace.h"
35 #include "commands/cluster.h"
36 #include "commands/vacuum.h"
37 #include "miscadmin.h"
39 #include "postmaster/autovacuum.h"
40 #include "storage/bufmgr.h"
41 #include "storage/lmgr.h"
42 #include "storage/proc.h"
43 #include "storage/procarray.h"
44 #include "utils/acl.h"
45 #include "utils/fmgroids.h"
46 #include "utils/guc.h"
47 #include "utils/memutils.h"
48 #include "utils/snapmgr.h"
49 #include "utils/syscache.h"
50 #include "utils/tqual.h"
56 int vacuum_freeze_min_age;
57 int vacuum_freeze_table_age;
60 /* A few variables that don't seem worth passing around as parameters */
61 static MemoryContext vac_context = NULL;
62 static BufferAccessStrategy vac_strategy;
65 /* non-export function prototypes */
66 static List *get_rel_oids(Oid relid, const RangeVar *vacrel);
67 static void vac_truncate_clog(TransactionId frozenXID, MultiXactId frozenMulti);
68 static bool vacuum_rel(Oid relid, VacuumStmt *vacstmt, bool do_toast,
73 * Primary entry point for VACUUM and ANALYZE commands.
75 * relid is normally InvalidOid; if it is not, then it provides the relation
76 * OID to be processed, and vacstmt->relation is ignored. (The non-invalid
77 * case is currently only used by autovacuum.)
79 * do_toast is passed as FALSE by autovacuum, because it processes TOAST
82 * for_wraparound is used by autovacuum to let us know when it's forcing
83 * a vacuum for wraparound, which should not be auto-canceled.
85 * bstrategy is normally given as NULL, but in autovacuum it can be passed
86 * in to use the same buffer strategy object across multiple vacuum() calls.
88 * isTopLevel should be passed down from ProcessUtility.
90 * It is the caller's responsibility that vacstmt and bstrategy
91 * (if given) be allocated in a memory context that won't disappear
92 * at transaction commit.
95 vacuum(VacuumStmt *vacstmt, Oid relid, bool do_toast,
96 BufferAccessStrategy bstrategy, bool for_wraparound, bool isTopLevel)
99 volatile bool in_outer_xact,
103 /* sanity checks on options */
104 Assert(vacstmt->options & (VACOPT_VACUUM | VACOPT_ANALYZE));
105 Assert((vacstmt->options & VACOPT_VACUUM) ||
106 !(vacstmt->options & (VACOPT_FULL | VACOPT_FREEZE)));
107 Assert((vacstmt->options & VACOPT_ANALYZE) || vacstmt->va_cols == NIL);
109 stmttype = (vacstmt->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
112 * We cannot run VACUUM inside a user transaction block; if we were inside
113 * a transaction, then our commit- and start-transaction-command calls
114 * would not have the intended effect! There are numerous other subtle
115 * dependencies on this, too.
117 * ANALYZE (without VACUUM) can run either way.
119 if (vacstmt->options & VACOPT_VACUUM)
121 PreventTransactionChain(isTopLevel, stmttype);
122 in_outer_xact = false;
125 in_outer_xact = IsInTransactionChain(isTopLevel);
128 * Send info about dead objects to the statistics collector, unless we are
129 * in autovacuum --- autovacuum.c does this for itself.
131 if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
132 pgstat_vacuum_stat();
135 * Create special memory context for cross-transaction storage.
137 * Since it is a child of PortalContext, it will go away eventually even
138 * if we suffer an error; there's no need for special abort cleanup logic.
140 vac_context = AllocSetContextCreate(PortalContext,
142 ALLOCSET_DEFAULT_MINSIZE,
143 ALLOCSET_DEFAULT_INITSIZE,
144 ALLOCSET_DEFAULT_MAXSIZE);
147 * If caller didn't give us a buffer strategy object, make one in the
148 * cross-transaction memory context.
150 if (bstrategy == NULL)
152 MemoryContext old_context = MemoryContextSwitchTo(vac_context);
154 bstrategy = GetAccessStrategy(BAS_VACUUM);
155 MemoryContextSwitchTo(old_context);
157 vac_strategy = bstrategy;
160 * Build list of relations to process, unless caller gave us one. (If we
161 * build one, we put it in vac_context for safekeeping.)
163 relations = get_rel_oids(relid, vacstmt->relation);
166 * Decide whether we need to start/commit our own transactions.
168 * For VACUUM (with or without ANALYZE): always do so, so that we can
169 * release locks as soon as possible. (We could possibly use the outer
170 * transaction for a one-table VACUUM, but handling TOAST tables would be
173 * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
174 * start/commit our own transactions. Also, there's no need to do so if
175 * only processing one relation. For multiple relations when not within a
176 * transaction block, and also in an autovacuum worker, use own
177 * transactions so we can release locks sooner.
179 if (vacstmt->options & VACOPT_VACUUM)
180 use_own_xacts = true;
183 Assert(vacstmt->options & VACOPT_ANALYZE);
184 if (IsAutoVacuumWorkerProcess())
185 use_own_xacts = true;
186 else if (in_outer_xact)
187 use_own_xacts = false;
188 else if (list_length(relations) > 1)
189 use_own_xacts = true;
191 use_own_xacts = false;
195 * vacuum_rel expects to be entered with no transaction active; it will
196 * start and commit its own transaction. But we are called by an SQL
197 * command, and so we are executing inside a transaction already. We
198 * commit the transaction started in PostgresMain() here, and start
199 * another one before exiting to match the commit waiting for us back in
204 /* ActiveSnapshot is not set by autovacuum */
205 if (ActiveSnapshotSet())
208 /* matches the StartTransaction in PostgresMain() */
209 CommitTransactionCommand();
212 /* Turn vacuum cost accounting on or off */
217 VacuumCostActive = (VacuumCostDelay > 0);
218 VacuumCostBalance = 0;
224 * Loop to process each selected relation.
226 foreach(cur, relations)
228 Oid relid = lfirst_oid(cur);
230 if (vacstmt->options & VACOPT_VACUUM)
232 if (!vacuum_rel(relid, vacstmt, do_toast, for_wraparound))
236 if (vacstmt->options & VACOPT_ANALYZE)
239 * If using separate xacts, start one for analyze. Otherwise,
240 * we can use the outer transaction.
244 StartTransactionCommand();
245 /* functions in indexes may want a snapshot set */
246 PushActiveSnapshot(GetTransactionSnapshot());
249 analyze_rel(relid, vacstmt, vac_strategy);
254 CommitTransactionCommand();
261 /* Make sure cost accounting is turned off after error */
262 VacuumCostActive = false;
267 /* Turn off vacuum cost accounting */
268 VacuumCostActive = false;
271 * Finish up processing.
275 /* here, we are not in a transaction */
278 * This matches the CommitTransaction waiting for us in
281 StartTransactionCommand();
284 if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
287 * Update pg_database.datfrozenxid, and truncate pg_clog if possible.
288 * (autovacuum.c does this for itself.)
290 vac_update_datfrozenxid();
294 * Clean up working storage --- note we must do this after
295 * StartTransactionCommand, else we might be trying to delete the active
298 MemoryContextDelete(vac_context);
303 * Build a list of Oids for each relation to be processed
305 * The list is built in vac_context so that it will survive across our
306 * per-relation transactions.
309 get_rel_oids(Oid relid, const RangeVar *vacrel)
311 List *oid_list = NIL;
312 MemoryContext oldcontext;
314 /* OID supplied by VACUUM's caller? */
315 if (OidIsValid(relid))
317 oldcontext = MemoryContextSwitchTo(vac_context);
318 oid_list = lappend_oid(oid_list, relid);
319 MemoryContextSwitchTo(oldcontext);
323 /* Process a specific relation */
327 * Since we don't take a lock here, the relation might be gone, or the
328 * RangeVar might no longer refer to the OID we look up here. In the
329 * former case, VACUUM will do nothing; in the latter case, it will
330 * process the OID we looked up here, rather than the new one. Neither
331 * is ideal, but there's little practical alternative, since we're
332 * going to commit this transaction and begin a new one between now
335 relid = RangeVarGetRelid(vacrel, NoLock, false);
337 /* Make a relation list entry for this guy */
338 oldcontext = MemoryContextSwitchTo(vac_context);
339 oid_list = lappend_oid(oid_list, relid);
340 MemoryContextSwitchTo(oldcontext);
345 * Process all plain relations and materialized views listed in
352 pgclass = heap_open(RelationRelationId, AccessShareLock);
354 scan = heap_beginscan(pgclass, SnapshotNow, 0, NULL);
356 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
358 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
360 if (classForm->relkind != RELKIND_RELATION &&
361 classForm->relkind != RELKIND_MATVIEW)
364 /* Make a relation list entry for this guy */
365 oldcontext = MemoryContextSwitchTo(vac_context);
366 oid_list = lappend_oid(oid_list, HeapTupleGetOid(tuple));
367 MemoryContextSwitchTo(oldcontext);
371 heap_close(pgclass, AccessShareLock);
378 * vacuum_set_xid_limits() -- compute oldest-Xmin and freeze cutoff points
381 vacuum_set_xid_limits(int freeze_min_age,
382 int freeze_table_age,
384 TransactionId *oldestXmin,
385 TransactionId *freezeLimit,
386 TransactionId *freezeTableLimit,
387 MultiXactId *multiXactFrzLimit)
391 TransactionId safeLimit;
394 * We can always ignore processes running lazy vacuum. This is because we
395 * use these values only for deciding which tuples we must keep in the
396 * tables. Since lazy vacuum doesn't write its XID anywhere, it's safe to
397 * ignore it. In theory it could be problematic to ignore lazy vacuums in
398 * a full vacuum, but keep in mind that only one vacuum process can be
399 * working on a particular table at any time, and that each vacuum is
400 * always an independent transaction.
402 *oldestXmin = GetOldestXmin(sharedRel, true);
404 Assert(TransactionIdIsNormal(*oldestXmin));
407 * Determine the minimum freeze age to use: as specified by the caller, or
408 * vacuum_freeze_min_age, but in any case not more than half
409 * autovacuum_freeze_max_age, so that autovacuums to prevent XID
410 * wraparound won't occur too frequently.
412 freezemin = freeze_min_age;
414 freezemin = vacuum_freeze_min_age;
415 freezemin = Min(freezemin, autovacuum_freeze_max_age / 2);
416 Assert(freezemin >= 0);
419 * Compute the cutoff XID, being careful not to generate a "permanent" XID
421 limit = *oldestXmin - freezemin;
422 if (!TransactionIdIsNormal(limit))
423 limit = FirstNormalTransactionId;
426 * If oldestXmin is very far back (in practice, more than
427 * autovacuum_freeze_max_age / 2 XIDs old), complain and force a minimum
428 * freeze age of zero.
430 safeLimit = ReadNewTransactionId() - autovacuum_freeze_max_age;
431 if (!TransactionIdIsNormal(safeLimit))
432 safeLimit = FirstNormalTransactionId;
434 if (TransactionIdPrecedes(limit, safeLimit))
437 (errmsg("oldest xmin is far in the past"),
438 errhint("Close open transactions soon to avoid wraparound problems.")));
442 *freezeLimit = limit;
444 if (freezeTableLimit != NULL)
449 * Determine the table freeze age to use: as specified by the caller,
450 * or vacuum_freeze_table_age, but in any case not more than
451 * autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
452 * VACUUM schedule, the nightly VACUUM gets a chance to freeze tuples
453 * before anti-wraparound autovacuum is launched.
455 freezetable = freeze_table_age;
457 freezetable = vacuum_freeze_table_age;
458 freezetable = Min(freezetable, autovacuum_freeze_max_age * 0.95);
459 Assert(freezetable >= 0);
462 * Compute the cutoff XID, being careful not to generate a "permanent"
465 limit = ReadNewTransactionId() - freezetable;
466 if (!TransactionIdIsNormal(limit))
467 limit = FirstNormalTransactionId;
469 *freezeTableLimit = limit;
472 if (multiXactFrzLimit != NULL)
477 * simplistic multixactid freezing: use the same freezing policy as
480 mxLimit = GetOldestMultiXactId() - freezemin;
481 if (mxLimit < FirstMultiXactId)
482 mxLimit = FirstMultiXactId;
484 *multiXactFrzLimit = mxLimit;
489 * vac_estimate_reltuples() -- estimate the new value for pg_class.reltuples
491 * If we scanned the whole relation then we should just use the count of
492 * live tuples seen; but if we did not, we should not trust the count
493 * unreservedly, especially not in VACUUM, which may have scanned a quite
494 * nonrandom subset of the table. When we have only partial information,
495 * we take the old value of pg_class.reltuples as a measurement of the
496 * tuple density in the unscanned pages.
498 * This routine is shared by VACUUM and ANALYZE.
501 vac_estimate_reltuples(Relation relation, bool is_analyze,
502 BlockNumber total_pages,
503 BlockNumber scanned_pages,
504 double scanned_tuples)
506 BlockNumber old_rel_pages = relation->rd_rel->relpages;
507 double old_rel_tuples = relation->rd_rel->reltuples;
511 double updated_density;
513 /* If we did scan the whole table, just use the count as-is */
514 if (scanned_pages >= total_pages)
515 return scanned_tuples;
518 * If scanned_pages is zero but total_pages isn't, keep the existing value
519 * of reltuples. (Note: callers should avoid updating the pg_class
520 * statistics in this situation, since no new information has been
523 if (scanned_pages == 0)
524 return old_rel_tuples;
527 * If old value of relpages is zero, old density is indeterminate; we
528 * can't do much except scale up scanned_tuples to match total_pages.
530 if (old_rel_pages == 0)
531 return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
534 * Okay, we've covered the corner cases. The normal calculation is to
535 * convert the old measurement to a density (tuples per page), then update
536 * the density using an exponential-moving-average approach, and finally
537 * compute reltuples as updated_density * total_pages.
539 * For ANALYZE, the moving average multiplier is just the fraction of the
540 * table's pages we scanned. This is equivalent to assuming that the
541 * tuple density in the unscanned pages didn't change. Of course, it
542 * probably did, if the new density measurement is different. But over
543 * repeated cycles, the value of reltuples will converge towards the
544 * correct value, if repeated measurements show the same new density.
546 * For VACUUM, the situation is a bit different: we have looked at a
547 * nonrandom sample of pages, but we know for certain that the pages we
548 * didn't look at are precisely the ones that haven't changed lately.
549 * Thus, there is a reasonable argument for doing exactly the same thing
550 * as for the ANALYZE case, that is use the old density measurement as the
551 * value for the unscanned pages.
553 * This logic could probably use further refinement.
555 old_density = old_rel_tuples / old_rel_pages;
556 new_density = scanned_tuples / scanned_pages;
557 multiplier = (double) scanned_pages / (double) total_pages;
558 updated_density = old_density + (new_density - old_density) * multiplier;
559 return floor(updated_density * total_pages + 0.5);
564 * vac_update_relstats() -- update statistics for one relation
566 * Update the whole-relation statistics that are kept in its pg_class
567 * row. There are additional stats that will be updated if we are
568 * doing ANALYZE, but we always update these stats. This routine works
569 * for both index and heap relation entries in pg_class.
571 * We violate transaction semantics here by overwriting the rel's
572 * existing pg_class tuple with the new values. This is reasonably
573 * safe since the new values are correct whether or not this transaction
574 * commits. The reason for this is that if we updated these tuples in
575 * the usual way, vacuuming pg_class itself wouldn't work very well ---
576 * by the time we got done with a vacuum cycle, most of the tuples in
577 * pg_class would've been obsoleted. Of course, this only works for
578 * fixed-size never-null columns, but these are.
580 * Note another assumption: that two VACUUMs/ANALYZEs on a table can't
581 * run in parallel, nor can VACUUM/ANALYZE run in parallel with a
582 * schema alteration such as adding an index, rule, or trigger. Otherwise
583 * our updates of relhasindex etc might overwrite uncommitted updates.
585 * Another reason for doing it this way is that when we are in a lazy
586 * VACUUM and have PROC_IN_VACUUM set, we mustn't do any updates ---
587 * somebody vacuuming pg_class might think they could delete a tuple
588 * marked with xmin = our xid.
590 * This routine is shared by VACUUM and ANALYZE.
593 vac_update_relstats(Relation relation,
594 BlockNumber num_pages, double num_tuples,
595 BlockNumber num_all_visible_pages,
596 bool hasindex, TransactionId frozenxid,
597 MultiXactId minmulti)
599 Oid relid = RelationGetRelid(relation);
602 Form_pg_class pgcform;
605 rd = heap_open(RelationRelationId, RowExclusiveLock);
607 /* Fetch a copy of the tuple to scribble on */
608 ctup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
609 if (!HeapTupleIsValid(ctup))
610 elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
612 pgcform = (Form_pg_class) GETSTRUCT(ctup);
614 /* Apply required updates, if any, to copied tuple */
617 if (pgcform->relpages != (int32) num_pages)
619 pgcform->relpages = (int32) num_pages;
622 if (pgcform->reltuples != (float4) num_tuples)
624 pgcform->reltuples = (float4) num_tuples;
627 if (pgcform->relallvisible != (int32) num_all_visible_pages)
629 pgcform->relallvisible = (int32) num_all_visible_pages;
632 if (pgcform->relhasindex != hasindex)
634 pgcform->relhasindex = hasindex;
639 * If we have discovered that there are no indexes, then there's no
640 * primary key either. This could be done more thoroughly...
642 if (pgcform->relhaspkey && !hasindex)
644 pgcform->relhaspkey = false;
648 /* We also clear relhasrules and relhastriggers if needed */
649 if (pgcform->relhasrules && relation->rd_rules == NULL)
651 pgcform->relhasrules = false;
654 if (pgcform->relhastriggers && relation->trigdesc == NULL)
656 pgcform->relhastriggers = false;
661 * relfrozenxid should never go backward. Caller can pass
662 * InvalidTransactionId if it has no new data.
664 if (TransactionIdIsNormal(frozenxid) &&
665 TransactionIdPrecedes(pgcform->relfrozenxid, frozenxid))
667 pgcform->relfrozenxid = frozenxid;
671 /* relminmxid must never go backward, either */
672 if (MultiXactIdIsValid(minmulti) &&
673 MultiXactIdPrecedes(pgcform->relminmxid, minmulti))
675 pgcform->relminmxid = minmulti;
679 /* If anything changed, write out the tuple. */
681 heap_inplace_update(rd, ctup);
683 heap_close(rd, RowExclusiveLock);
688 * vac_update_datfrozenxid() -- update pg_database.datfrozenxid for our DB
690 * Update pg_database's datfrozenxid entry for our database to be the
691 * minimum of the pg_class.relfrozenxid values.
693 * Similarly, update our datfrozenmulti to be the minimum of the
694 * pg_class.relfrozenmulti values.
696 * If we are able to advance either pg_database value, also try to
697 * truncate pg_clog and pg_multixact.
699 * We violate transaction semantics here by overwriting the database's
700 * existing pg_database tuple with the new value. This is reasonably
701 * safe since the new value is correct whether or not this transaction
702 * commits. As with vac_update_relstats, this avoids leaving dead tuples
703 * behind after a VACUUM.
706 vac_update_datfrozenxid(void)
709 Form_pg_database dbform;
713 TransactionId newFrozenXid;
714 MultiXactId newFrozenMulti;
718 * Initialize the "min" calculation with GetOldestXmin, which is a
719 * reasonable approximation to the minimum relfrozenxid for not-yet-
720 * committed pg_class entries for new tables; see AddNewRelationTuple().
721 * So we cannot produce a wrong minimum by starting with this.
723 newFrozenXid = GetOldestXmin(true, true);
726 * Similarly, initialize the MultiXact "min" with the value that would be
727 * used on pg_class for new tables. See AddNewRelationTuple().
729 newFrozenMulti = GetOldestMultiXactId();
732 * We must seqscan pg_class to find the minimum Xid, because there is no
733 * index that can help us here.
735 relation = heap_open(RelationRelationId, AccessShareLock);
737 scan = systable_beginscan(relation, InvalidOid, false,
738 SnapshotNow, 0, NULL);
740 while ((classTup = systable_getnext(scan)) != NULL)
742 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
745 * Only consider heap and TOAST tables (anything else should have
746 * InvalidTransactionId in relfrozenxid anyway.)
748 if (classForm->relkind != RELKIND_RELATION &&
749 classForm->relkind != RELKIND_MATVIEW &&
750 classForm->relkind != RELKIND_TOASTVALUE)
753 Assert(TransactionIdIsNormal(classForm->relfrozenxid));
754 Assert(MultiXactIdIsValid(classForm->relminmxid));
756 if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
757 newFrozenXid = classForm->relfrozenxid;
759 if (MultiXactIdPrecedes(classForm->relminmxid, newFrozenMulti))
760 newFrozenMulti = classForm->relminmxid;
763 /* we're done with pg_class */
764 systable_endscan(scan);
765 heap_close(relation, AccessShareLock);
767 Assert(TransactionIdIsNormal(newFrozenXid));
768 Assert(MultiXactIdIsValid(newFrozenMulti));
770 /* Now fetch the pg_database tuple we need to update. */
771 relation = heap_open(DatabaseRelationId, RowExclusiveLock);
773 /* Fetch a copy of the tuple to scribble on */
774 tuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
775 if (!HeapTupleIsValid(tuple))
776 elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
777 dbform = (Form_pg_database) GETSTRUCT(tuple);
780 * Don't allow datfrozenxid to go backward (probably can't happen anyway);
781 * and detect the common case where it doesn't go forward either.
783 if (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid))
785 dbform->datfrozenxid = newFrozenXid;
790 if (MultiXactIdPrecedes(dbform->datminmxid, newFrozenMulti))
792 dbform->datminmxid = newFrozenMulti;
797 heap_inplace_update(relation, tuple);
799 heap_freetuple(tuple);
800 heap_close(relation, RowExclusiveLock);
803 * If we were able to advance datfrozenxid, see if we can truncate
804 * pg_clog. Also do it if the shared XID-wrap-limit info is stale, since
805 * this action will update that too.
807 if (dirty || ForceTransactionIdLimitUpdate())
808 vac_truncate_clog(newFrozenXid, newFrozenMulti);
813 * vac_truncate_clog() -- attempt to truncate the commit log
815 * Scan pg_database to determine the system-wide oldest datfrozenxid,
816 * and use it to truncate the transaction commit log (pg_clog).
817 * Also update the XID wrap limit info maintained by varsup.c.
819 * The passed XID is simply the one I just wrote into my pg_database
820 * entry. It's used to initialize the "min" calculation.
822 * This routine is only invoked when we've managed to change our
823 * DB's datfrozenxid entry, or we found that the shared XID-wrap-limit
827 vac_truncate_clog(TransactionId frozenXID, MultiXactId frozenMulti)
829 TransactionId myXID = GetCurrentTransactionId();
833 Oid oldestxid_datoid;
834 Oid oldestmulti_datoid;
835 bool frozenAlreadyWrapped = false;
837 /* init oldest datoids to sync with my frozen values */
838 oldestxid_datoid = MyDatabaseId;
839 oldestmulti_datoid = MyDatabaseId;
842 * Scan pg_database to compute the minimum datfrozenxid
844 * Note: we need not worry about a race condition with new entries being
845 * inserted by CREATE DATABASE. Any such entry will have a copy of some
846 * existing DB's datfrozenxid, and that source DB cannot be ours because
847 * of the interlock against copying a DB containing an active backend.
848 * Hence the new entry will not reduce the minimum. Also, if two VACUUMs
849 * concurrently modify the datfrozenxid's of different databases, the
850 * worst possible outcome is that pg_clog is not truncated as aggressively
853 relation = heap_open(DatabaseRelationId, AccessShareLock);
855 scan = heap_beginscan(relation, SnapshotNow, 0, NULL);
857 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
859 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
861 Assert(TransactionIdIsNormal(dbform->datfrozenxid));
862 Assert(MultiXactIdIsValid(dbform->datminmxid));
864 if (TransactionIdPrecedes(myXID, dbform->datfrozenxid))
865 frozenAlreadyWrapped = true;
866 else if (TransactionIdPrecedes(dbform->datfrozenxid, frozenXID))
868 frozenXID = dbform->datfrozenxid;
869 oldestxid_datoid = HeapTupleGetOid(tuple);
872 if (MultiXactIdPrecedes(dbform->datminmxid, frozenMulti))
874 frozenMulti = dbform->datminmxid;
875 oldestmulti_datoid = HeapTupleGetOid(tuple);
881 heap_close(relation, AccessShareLock);
884 * Do not truncate CLOG if we seem to have suffered wraparound already;
885 * the computed minimum XID might be bogus. This case should now be
886 * impossible due to the defenses in GetNewTransactionId, but we keep the
889 if (frozenAlreadyWrapped)
892 (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
893 errdetail("You might have already suffered transaction-wraparound data loss.")));
897 /* Truncate CLOG and Multi to the oldest computed value */
898 TruncateCLOG(frozenXID);
899 TruncateMultiXact(frozenMulti);
902 * Update the wrap limit for GetNewTransactionId and creation of new
903 * MultiXactIds. Note: these functions will also signal the postmaster
904 * for an(other) autovac cycle if needed. XXX should we avoid possibly
907 SetTransactionIdLimit(frozenXID, oldestxid_datoid);
908 MultiXactAdvanceOldest(frozenMulti, oldestmulti_datoid);
913 * vacuum_rel() -- vacuum one heap relation
915 * Doing one heap at a time incurs extra overhead, since we need to
916 * check that the heap exists again just before we vacuum it. The
917 * reason that we do this is so that vacuuming can be spread across
918 * many small transactions. Otherwise, two-phase locking would require
919 * us to lock the entire database during one pass of the vacuum cleaner.
921 * At entry and exit, we are not inside a transaction.
924 vacuum_rel(Oid relid, VacuumStmt *vacstmt, bool do_toast, bool for_wraparound)
931 int save_sec_context;
934 /* Begin a transaction for vacuuming this relation */
935 StartTransactionCommand();
938 * Functions in indexes may want a snapshot set. Also, setting a snapshot
939 * ensures that RecentGlobalXmin is kept truly recent.
941 PushActiveSnapshot(GetTransactionSnapshot());
943 if (!(vacstmt->options & VACOPT_FULL))
946 * In lazy vacuum, we can set the PROC_IN_VACUUM flag, which lets
947 * other concurrent VACUUMs know that they can ignore this one while
948 * determining their OldestXmin. (The reason we don't set it during a
949 * full VACUUM is exactly that we may have to run user-defined
950 * functions for functional indexes, and we want to make sure that if
951 * they use the snapshot set above, any tuples it requires can't get
952 * removed from other tables. An index function that depends on the
953 * contents of other tables is arguably broken, but we won't break it
954 * here by violating transaction semantics.)
956 * We also set the VACUUM_FOR_WRAPAROUND flag, which is passed down by
957 * autovacuum; it's used to avoid canceling a vacuum that was invoked
960 * Note: these flags remain set until CommitTransaction or
961 * AbortTransaction. We don't want to clear them until we reset
962 * MyPgXact->xid/xmin, else OldestXmin might appear to go backwards,
963 * which is probably Not Good.
965 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
966 MyPgXact->vacuumFlags |= PROC_IN_VACUUM;
968 MyPgXact->vacuumFlags |= PROC_VACUUM_FOR_WRAPAROUND;
969 LWLockRelease(ProcArrayLock);
973 * Check for user-requested abort. Note we want this to be inside a
974 * transaction, so xact.c doesn't issue useless WARNING.
976 CHECK_FOR_INTERRUPTS();
979 * Determine the type of lock we want --- hard exclusive lock for a FULL
980 * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either
981 * way, we can be sure that no other backend is vacuuming the same table.
983 lmode = (vacstmt->options & VACOPT_FULL) ? AccessExclusiveLock : ShareUpdateExclusiveLock;
986 * Open the relation and get the appropriate lock on it.
988 * There's a race condition here: the rel may have gone away since the
989 * last time we saw it. If so, we don't need to vacuum it.
991 * If we've been asked not to wait for the relation lock, acquire it first
992 * in non-blocking mode, before calling try_relation_open().
994 if (!(vacstmt->options & VACOPT_NOWAIT))
995 onerel = try_relation_open(relid, lmode);
996 else if (ConditionalLockRelationOid(relid, lmode))
997 onerel = try_relation_open(relid, NoLock);
1001 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
1003 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
1004 errmsg("skipping vacuum of \"%s\" --- lock not available",
1005 vacstmt->relation->relname)));
1010 PopActiveSnapshot();
1011 CommitTransactionCommand();
1016 * Check permissions.
1018 * We allow the user to vacuum a table if he is superuser, the table
1019 * owner, or the database owner (but in the latter case, only if it's not
1020 * a shared relation). pg_class_ownercheck includes the superuser case.
1022 * Note we choose to treat permissions failure as a WARNING and keep
1023 * trying to vacuum the rest of the DB --- is this appropriate?
1025 if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
1026 (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
1028 if (onerel->rd_rel->relisshared)
1030 (errmsg("skipping \"%s\" --- only superuser can vacuum it",
1031 RelationGetRelationName(onerel))));
1032 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
1034 (errmsg("skipping \"%s\" --- only superuser or database owner can vacuum it",
1035 RelationGetRelationName(onerel))));
1038 (errmsg("skipping \"%s\" --- only table or database owner can vacuum it",
1039 RelationGetRelationName(onerel))));
1040 relation_close(onerel, lmode);
1041 PopActiveSnapshot();
1042 CommitTransactionCommand();
1047 * Check that it's a vacuumable table; we used to do this in
1048 * get_rel_oids() but seems safer to check after we've locked the
1051 if (onerel->rd_rel->relkind != RELKIND_RELATION &&
1052 onerel->rd_rel->relkind != RELKIND_MATVIEW &&
1053 onerel->rd_rel->relkind != RELKIND_TOASTVALUE)
1056 (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
1057 RelationGetRelationName(onerel))));
1058 relation_close(onerel, lmode);
1059 PopActiveSnapshot();
1060 CommitTransactionCommand();
1065 * Silently ignore tables that are temp tables of other backends ---
1066 * trying to vacuum these will lead to great unhappiness, since their
1067 * contents are probably not up-to-date on disk. (We don't throw a
1068 * warning here; it would just lead to chatter during a database-wide
1071 if (RELATION_IS_OTHER_TEMP(onerel))
1073 relation_close(onerel, lmode);
1074 PopActiveSnapshot();
1075 CommitTransactionCommand();
1080 * Get a session-level lock too. This will protect our access to the
1081 * relation across multiple transactions, so that we can vacuum the
1082 * relation's TOAST table (if any) secure in the knowledge that no one is
1083 * deleting the parent relation.
1085 * NOTE: this cannot block, even if someone else is waiting for access,
1086 * because the lock manager knows that both lock requests are from the
1089 onerelid = onerel->rd_lockInfo.lockRelId;
1090 LockRelationIdForSession(&onerelid, lmode);
1093 * Remember the relation's TOAST relation for later, if the caller asked
1094 * us to process it. In VACUUM FULL, though, the toast table is
1095 * automatically rebuilt by cluster_rel so we shouldn't recurse to it.
1097 if (do_toast && !(vacstmt->options & VACOPT_FULL))
1098 toast_relid = onerel->rd_rel->reltoastrelid;
1100 toast_relid = InvalidOid;
1103 * Switch to the table owner's userid, so that any index functions are run
1104 * as that user. Also lock down security-restricted operations and
1105 * arrange to make GUC variable changes local to this command. (This is
1106 * unnecessary, but harmless, for lazy VACUUM.)
1108 GetUserIdAndSecContext(&save_userid, &save_sec_context);
1109 SetUserIdAndSecContext(onerel->rd_rel->relowner,
1110 save_sec_context | SECURITY_RESTRICTED_OPERATION);
1111 save_nestlevel = NewGUCNestLevel();
1114 * Do the actual work --- either FULL or "lazy" vacuum
1116 if (vacstmt->options & VACOPT_FULL)
1118 /* close relation before vacuuming, but hold lock until commit */
1119 relation_close(onerel, NoLock);
1122 /* VACUUM FULL is now a variant of CLUSTER; see cluster.c */
1123 cluster_rel(relid, InvalidOid, false,
1124 (vacstmt->options & VACOPT_VERBOSE) != 0,
1125 vacstmt->freeze_min_age, vacstmt->freeze_table_age);
1128 lazy_vacuum_rel(onerel, vacstmt, vac_strategy);
1130 /* Roll back any GUC changes executed by index functions */
1131 AtEOXact_GUC(false, save_nestlevel);
1133 /* Restore userid and security context */
1134 SetUserIdAndSecContext(save_userid, save_sec_context);
1136 /* all done with this class, but hold lock until commit */
1138 relation_close(onerel, NoLock);
1141 * Complete the transaction and free all temporary memory used.
1143 PopActiveSnapshot();
1144 CommitTransactionCommand();
1147 * If the relation has a secondary toast rel, vacuum that too while we
1148 * still hold the session lock on the master table. Note however that
1149 * "analyze" will not get done on the toast table. This is good, because
1150 * the toaster always uses hardcoded index access and statistics are
1151 * totally unimportant for toast relations.
1153 if (toast_relid != InvalidOid)
1154 vacuum_rel(toast_relid, vacstmt, false, for_wraparound);
1157 * Now release the session-level lock on the master table.
1159 UnlockRelationIdForSession(&onerelid, lmode);
1161 /* Report that we really did it. */
1167 * Open all the vacuumable indexes of the given relation, obtaining the
1168 * specified kind of lock on each. Return an array of Relation pointers for
1169 * the indexes into *Irel, and the number of indexes into *nindexes.
1171 * We consider an index vacuumable if it is marked insertable (IndexIsReady).
1172 * If it isn't, probably a CREATE INDEX CONCURRENTLY command failed early in
1173 * execution, and what we have is too corrupt to be processable. We will
1174 * vacuum even if the index isn't indisvalid; this is important because in a
1175 * unique index, uniqueness checks will be performed anyway and had better not
1176 * hit dangling index pointers.
1179 vac_open_indexes(Relation relation, LOCKMODE lockmode,
1180 int *nindexes, Relation **Irel)
1183 ListCell *indexoidscan;
1186 Assert(lockmode != NoLock);
1188 indexoidlist = RelationGetIndexList(relation);
1190 /* allocate enough memory for all indexes */
1191 i = list_length(indexoidlist);
1194 *Irel = (Relation *) palloc(i * sizeof(Relation));
1198 /* collect just the ready indexes */
1200 foreach(indexoidscan, indexoidlist)
1202 Oid indexoid = lfirst_oid(indexoidscan);
1205 indrel = index_open(indexoid, lockmode);
1206 if (IndexIsReady(indrel->rd_index))
1207 (*Irel)[i++] = indrel;
1209 index_close(indrel, lockmode);
1214 list_free(indexoidlist);
1218 * Release the resources acquired by vac_open_indexes. Optionally release
1219 * the locks (say NoLock to keep 'em).
1222 vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
1229 Relation ind = Irel[nindexes];
1231 index_close(ind, lockmode);
1237 * vacuum_delay_point --- check for interrupts and cost-based delay.
1239 * This should be called in each major loop of VACUUM processing,
1240 * typically once per page processed.
1243 vacuum_delay_point(void)
1245 /* Always check for interrupts */
1246 CHECK_FOR_INTERRUPTS();
1248 /* Nap if appropriate */
1249 if (VacuumCostActive && !InterruptPending &&
1250 VacuumCostBalance >= VacuumCostLimit)
1254 msec = VacuumCostDelay * VacuumCostBalance / VacuumCostLimit;
1255 if (msec > VacuumCostDelay * 4)
1256 msec = VacuumCostDelay * 4;
1258 pg_usleep(msec * 1000L);
1260 VacuumCostBalance = 0;
1262 /* update balance values for workers */
1263 AutoVacuumUpdateDelay();
1265 /* Might have gotten an interrupt while sleeping */
1266 CHECK_FOR_INTERRUPTS();