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-2011, 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/transam.h"
29 #include "access/xact.h"
30 #include "catalog/namespace.h"
31 #include "catalog/pg_database.h"
32 #include "catalog/pg_namespace.h"
33 #include "commands/cluster.h"
34 #include "commands/vacuum.h"
35 #include "miscadmin.h"
37 #include "postmaster/autovacuum.h"
38 #include "storage/bufmgr.h"
39 #include "storage/lmgr.h"
40 #include "storage/proc.h"
41 #include "storage/procarray.h"
42 #include "utils/acl.h"
43 #include "utils/fmgroids.h"
44 #include "utils/guc.h"
45 #include "utils/memutils.h"
46 #include "utils/snapmgr.h"
47 #include "utils/syscache.h"
48 #include "utils/tqual.h"
54 int vacuum_freeze_min_age;
55 int vacuum_freeze_table_age;
58 /* A few variables that don't seem worth passing around as parameters */
59 static MemoryContext vac_context = NULL;
60 static BufferAccessStrategy vac_strategy;
63 /* non-export function prototypes */
64 static List *get_rel_oids(Oid relid, const RangeVar *vacrel);
65 static void vac_truncate_clog(TransactionId frozenXID);
66 static bool vacuum_rel(Oid relid, VacuumStmt *vacstmt, bool do_toast,
71 * Primary entry point for VACUUM and ANALYZE commands.
73 * relid is normally InvalidOid; if it is not, then it provides the relation
74 * OID to be processed, and vacstmt->relation is ignored. (The non-invalid
75 * case is currently only used by autovacuum.)
77 * do_toast is passed as FALSE by autovacuum, because it processes TOAST
80 * for_wraparound is used by autovacuum to let us know when it's forcing
81 * a vacuum for wraparound, which should not be auto-canceled.
83 * bstrategy is normally given as NULL, but in autovacuum it can be passed
84 * in to use the same buffer strategy object across multiple vacuum() calls.
86 * isTopLevel should be passed down from ProcessUtility.
88 * It is the caller's responsibility that vacstmt and bstrategy
89 * (if given) be allocated in a memory context that won't disappear
90 * at transaction commit.
93 vacuum(VacuumStmt *vacstmt, Oid relid, bool do_toast,
94 BufferAccessStrategy bstrategy, bool for_wraparound, bool isTopLevel)
97 volatile bool in_outer_xact,
101 /* sanity checks on options */
102 Assert(vacstmt->options & (VACOPT_VACUUM | VACOPT_ANALYZE));
103 Assert((vacstmt->options & VACOPT_VACUUM) ||
104 !(vacstmt->options & (VACOPT_FULL | VACOPT_FREEZE)));
105 Assert((vacstmt->options & VACOPT_ANALYZE) || vacstmt->va_cols == NIL);
107 stmttype = (vacstmt->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
110 * We cannot run VACUUM inside a user transaction block; if we were inside
111 * a transaction, then our commit- and start-transaction-command calls
112 * would not have the intended effect! There are numerous other subtle
113 * dependencies on this, too.
115 * ANALYZE (without VACUUM) can run either way.
117 if (vacstmt->options & VACOPT_VACUUM)
119 PreventTransactionChain(isTopLevel, stmttype);
120 in_outer_xact = false;
123 in_outer_xact = IsInTransactionChain(isTopLevel);
126 * Send info about dead objects to the statistics collector, unless we are
127 * in autovacuum --- autovacuum.c does this for itself.
129 if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
130 pgstat_vacuum_stat();
133 * Create special memory context for cross-transaction storage.
135 * Since it is a child of PortalContext, it will go away eventually even
136 * if we suffer an error; there's no need for special abort cleanup logic.
138 vac_context = AllocSetContextCreate(PortalContext,
140 ALLOCSET_DEFAULT_MINSIZE,
141 ALLOCSET_DEFAULT_INITSIZE,
142 ALLOCSET_DEFAULT_MAXSIZE);
145 * If caller didn't give us a buffer strategy object, make one in the
146 * cross-transaction memory context.
148 if (bstrategy == NULL)
150 MemoryContext old_context = MemoryContextSwitchTo(vac_context);
152 bstrategy = GetAccessStrategy(BAS_VACUUM);
153 MemoryContextSwitchTo(old_context);
155 vac_strategy = bstrategy;
158 * Build list of relations to process, unless caller gave us one. (If we
159 * build one, we put it in vac_context for safekeeping.)
161 relations = get_rel_oids(relid, vacstmt->relation);
164 * Decide whether we need to start/commit our own transactions.
166 * For VACUUM (with or without ANALYZE): always do so, so that we can
167 * release locks as soon as possible. (We could possibly use the outer
168 * transaction for a one-table VACUUM, but handling TOAST tables would be
171 * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
172 * start/commit our own transactions. Also, there's no need to do so if
173 * only processing one relation. For multiple relations when not within a
174 * transaction block, and also in an autovacuum worker, use own
175 * transactions so we can release locks sooner.
177 if (vacstmt->options & VACOPT_VACUUM)
178 use_own_xacts = true;
181 Assert(vacstmt->options & VACOPT_ANALYZE);
182 if (IsAutoVacuumWorkerProcess())
183 use_own_xacts = true;
184 else if (in_outer_xact)
185 use_own_xacts = false;
186 else if (list_length(relations) > 1)
187 use_own_xacts = true;
189 use_own_xacts = false;
193 * vacuum_rel expects to be entered with no transaction active; it will
194 * start and commit its own transaction. But we are called by an SQL
195 * command, and so we are executing inside a transaction already. We
196 * commit the transaction started in PostgresMain() here, and start
197 * another one before exiting to match the commit waiting for us back in
202 /* ActiveSnapshot is not set by autovacuum */
203 if (ActiveSnapshotSet())
206 /* matches the StartTransaction in PostgresMain() */
207 CommitTransactionCommand();
210 /* Turn vacuum cost accounting on or off */
215 VacuumCostActive = (VacuumCostDelay > 0);
216 VacuumCostBalance = 0;
219 * Loop to process each selected relation.
221 foreach(cur, relations)
223 Oid relid = lfirst_oid(cur);
225 if (vacstmt->options & VACOPT_VACUUM)
227 if (!vacuum_rel(relid, vacstmt, do_toast, for_wraparound))
231 if (vacstmt->options & VACOPT_ANALYZE)
234 * If using separate xacts, start one for analyze. Otherwise,
235 * we can use the outer transaction.
239 StartTransactionCommand();
240 /* functions in indexes may want a snapshot set */
241 PushActiveSnapshot(GetTransactionSnapshot());
244 analyze_rel(relid, vacstmt, vac_strategy);
249 CommitTransactionCommand();
256 /* Make sure cost accounting is turned off after error */
257 VacuumCostActive = false;
262 /* Turn off vacuum cost accounting */
263 VacuumCostActive = false;
266 * Finish up processing.
270 /* here, we are not in a transaction */
273 * This matches the CommitTransaction waiting for us in
276 StartTransactionCommand();
279 if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
282 * Update pg_database.datfrozenxid, and truncate pg_clog if possible.
283 * (autovacuum.c does this for itself.)
285 vac_update_datfrozenxid();
289 * Clean up working storage --- note we must do this after
290 * StartTransactionCommand, else we might be trying to delete the active
293 MemoryContextDelete(vac_context);
298 * Build a list of Oids for each relation to be processed
300 * The list is built in vac_context so that it will survive across our
301 * per-relation transactions.
304 get_rel_oids(Oid relid, const RangeVar *vacrel)
306 List *oid_list = NIL;
307 MemoryContext oldcontext;
309 /* OID supplied by VACUUM's caller? */
310 if (OidIsValid(relid))
312 oldcontext = MemoryContextSwitchTo(vac_context);
313 oid_list = lappend_oid(oid_list, relid);
314 MemoryContextSwitchTo(oldcontext);
318 /* Process a specific relation */
321 relid = RangeVarGetRelid(vacrel, false);
323 /* Make a relation list entry for this guy */
324 oldcontext = MemoryContextSwitchTo(vac_context);
325 oid_list = lappend_oid(oid_list, relid);
326 MemoryContextSwitchTo(oldcontext);
330 /* Process all plain relations listed in pg_class */
337 Anum_pg_class_relkind,
338 BTEqualStrategyNumber, F_CHAREQ,
339 CharGetDatum(RELKIND_RELATION));
341 pgclass = heap_open(RelationRelationId, AccessShareLock);
343 scan = heap_beginscan(pgclass, SnapshotNow, 1, &key);
345 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
347 /* Make a relation list entry for this guy */
348 oldcontext = MemoryContextSwitchTo(vac_context);
349 oid_list = lappend_oid(oid_list, HeapTupleGetOid(tuple));
350 MemoryContextSwitchTo(oldcontext);
354 heap_close(pgclass, AccessShareLock);
361 * vacuum_set_xid_limits() -- compute oldest-Xmin and freeze cutoff points
364 vacuum_set_xid_limits(int freeze_min_age,
365 int freeze_table_age,
367 TransactionId *oldestXmin,
368 TransactionId *freezeLimit,
369 TransactionId *freezeTableLimit)
373 TransactionId safeLimit;
376 * We can always ignore processes running lazy vacuum. This is because we
377 * use these values only for deciding which tuples we must keep in the
378 * tables. Since lazy vacuum doesn't write its XID anywhere, it's safe to
379 * ignore it. In theory it could be problematic to ignore lazy vacuums in
380 * a full vacuum, but keep in mind that only one vacuum process can be
381 * working on a particular table at any time, and that each vacuum is
382 * always an independent transaction.
384 *oldestXmin = GetOldestXmin(sharedRel, true);
386 Assert(TransactionIdIsNormal(*oldestXmin));
389 * Determine the minimum freeze age to use: as specified by the caller, or
390 * vacuum_freeze_min_age, but in any case not more than half
391 * autovacuum_freeze_max_age, so that autovacuums to prevent XID
392 * wraparound won't occur too frequently.
394 freezemin = freeze_min_age;
396 freezemin = vacuum_freeze_min_age;
397 freezemin = Min(freezemin, autovacuum_freeze_max_age / 2);
398 Assert(freezemin >= 0);
401 * Compute the cutoff XID, being careful not to generate a "permanent" XID
403 limit = *oldestXmin - freezemin;
404 if (!TransactionIdIsNormal(limit))
405 limit = FirstNormalTransactionId;
408 * If oldestXmin is very far back (in practice, more than
409 * autovacuum_freeze_max_age / 2 XIDs old), complain and force a minimum
410 * freeze age of zero.
412 safeLimit = ReadNewTransactionId() - autovacuum_freeze_max_age;
413 if (!TransactionIdIsNormal(safeLimit))
414 safeLimit = FirstNormalTransactionId;
416 if (TransactionIdPrecedes(limit, safeLimit))
419 (errmsg("oldest xmin is far in the past"),
420 errhint("Close open transactions soon to avoid wraparound problems.")));
424 *freezeLimit = limit;
426 if (freezeTableLimit != NULL)
431 * Determine the table freeze age to use: as specified by the caller,
432 * or vacuum_freeze_table_age, but in any case not more than
433 * autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
434 * VACUUM schedule, the nightly VACUUM gets a chance to freeze tuples
435 * before anti-wraparound autovacuum is launched.
437 freezetable = freeze_min_age;
439 freezetable = vacuum_freeze_table_age;
440 freezetable = Min(freezetable, autovacuum_freeze_max_age * 0.95);
441 Assert(freezetable >= 0);
444 * Compute the cutoff XID, being careful not to generate a "permanent"
447 limit = ReadNewTransactionId() - freezetable;
448 if (!TransactionIdIsNormal(limit))
449 limit = FirstNormalTransactionId;
451 *freezeTableLimit = limit;
457 * vac_estimate_reltuples() -- estimate the new value for pg_class.reltuples
459 * If we scanned the whole relation then we should just use the count of
460 * live tuples seen; but if we did not, we should not trust the count
461 * unreservedly, especially not in VACUUM, which may have scanned a quite
462 * nonrandom subset of the table. When we have only partial information,
463 * we take the old value of pg_class.reltuples as a measurement of the
464 * tuple density in the unscanned pages.
466 * This routine is shared by VACUUM and ANALYZE.
469 vac_estimate_reltuples(Relation relation, bool is_analyze,
470 BlockNumber total_pages,
471 BlockNumber scanned_pages,
472 double scanned_tuples)
474 BlockNumber old_rel_pages = relation->rd_rel->relpages;
475 double old_rel_tuples = relation->rd_rel->reltuples;
479 double updated_density;
481 /* If we did scan the whole table, just use the count as-is */
482 if (scanned_pages >= total_pages)
483 return scanned_tuples;
486 * If scanned_pages is zero but total_pages isn't, keep the existing value
489 if (scanned_pages == 0)
490 return old_rel_tuples;
493 * If old value of relpages is zero, old density is indeterminate; we
494 * can't do much except scale up scanned_tuples to match total_pages.
496 if (old_rel_pages == 0)
497 return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
500 * Okay, we've covered the corner cases. The normal calculation is to
501 * convert the old measurement to a density (tuples per page), then update
502 * the density using an exponential-moving-average approach, and finally
503 * compute reltuples as updated_density * total_pages.
505 * For ANALYZE, the moving average multiplier is just the fraction of the
506 * table's pages we scanned. This is equivalent to assuming that the
507 * tuple density in the unscanned pages didn't change. Of course, it
508 * probably did, if the new density measurement is different. But over
509 * repeated cycles, the value of reltuples will converge towards the
510 * correct value, if repeated measurements show the same new density.
512 * For VACUUM, the situation is a bit different: we have looked at a
513 * nonrandom sample of pages, but we know for certain that the pages we
514 * didn't look at are precisely the ones that haven't changed lately.
515 * Thus, there is a reasonable argument for doing exactly the same thing
516 * as for the ANALYZE case, that is use the old density measurement as the
517 * value for the unscanned pages.
519 * This logic could probably use further refinement.
521 old_density = old_rel_tuples / old_rel_pages;
522 new_density = scanned_tuples / scanned_pages;
523 multiplier = (double) scanned_pages / (double) total_pages;
524 updated_density = old_density + (new_density - old_density) * multiplier;
525 return floor(updated_density * total_pages + 0.5);
530 * vac_update_relstats() -- update statistics for one relation
532 * Update the whole-relation statistics that are kept in its pg_class
533 * row. There are additional stats that will be updated if we are
534 * doing ANALYZE, but we always update these stats. This routine works
535 * for both index and heap relation entries in pg_class.
537 * We violate transaction semantics here by overwriting the rel's
538 * existing pg_class tuple with the new values. This is reasonably
539 * safe since the new values are correct whether or not this transaction
540 * commits. The reason for this is that if we updated these tuples in
541 * the usual way, vacuuming pg_class itself wouldn't work very well ---
542 * by the time we got done with a vacuum cycle, most of the tuples in
543 * pg_class would've been obsoleted. Of course, this only works for
544 * fixed-size never-null columns, but these are.
546 * Note another assumption: that two VACUUMs/ANALYZEs on a table can't
547 * run in parallel, nor can VACUUM/ANALYZE run in parallel with a
548 * schema alteration such as adding an index, rule, or trigger. Otherwise
549 * our updates of relhasindex etc might overwrite uncommitted updates.
551 * Another reason for doing it this way is that when we are in a lazy
552 * VACUUM and have PROC_IN_VACUUM set, we mustn't do any updates ---
553 * somebody vacuuming pg_class might think they could delete a tuple
554 * marked with xmin = our xid.
556 * This routine is shared by VACUUM and ANALYZE.
559 vac_update_relstats(Relation relation,
560 BlockNumber num_pages, double num_tuples,
561 bool hasindex, TransactionId frozenxid)
563 Oid relid = RelationGetRelid(relation);
566 Form_pg_class pgcform;
569 rd = heap_open(RelationRelationId, RowExclusiveLock);
571 /* Fetch a copy of the tuple to scribble on */
572 ctup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
573 if (!HeapTupleIsValid(ctup))
574 elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
576 pgcform = (Form_pg_class) GETSTRUCT(ctup);
578 /* Apply required updates, if any, to copied tuple */
581 if (pgcform->relpages != (int32) num_pages)
583 pgcform->relpages = (int32) num_pages;
586 if (pgcform->reltuples != (float4) num_tuples)
588 pgcform->reltuples = (float4) num_tuples;
591 if (pgcform->relhasindex != hasindex)
593 pgcform->relhasindex = hasindex;
598 * If we have discovered that there are no indexes, then there's no
599 * primary key either. This could be done more thoroughly...
601 if (pgcform->relhaspkey && !hasindex)
603 pgcform->relhaspkey = false;
607 /* We also clear relhasrules and relhastriggers if needed */
608 if (pgcform->relhasrules && relation->rd_rules == NULL)
610 pgcform->relhasrules = false;
613 if (pgcform->relhastriggers && relation->trigdesc == NULL)
615 pgcform->relhastriggers = false;
620 * relfrozenxid should never go backward. Caller can pass
621 * InvalidTransactionId if it has no new data.
623 if (TransactionIdIsNormal(frozenxid) &&
624 TransactionIdPrecedes(pgcform->relfrozenxid, frozenxid))
626 pgcform->relfrozenxid = frozenxid;
630 /* If anything changed, write out the tuple. */
632 heap_inplace_update(rd, ctup);
634 heap_close(rd, RowExclusiveLock);
639 * vac_update_datfrozenxid() -- update pg_database.datfrozenxid for our DB
641 * Update pg_database's datfrozenxid entry for our database to be the
642 * minimum of the pg_class.relfrozenxid values. If we are able to
643 * advance pg_database.datfrozenxid, also try to truncate pg_clog.
645 * We violate transaction semantics here by overwriting the database's
646 * existing pg_database tuple with the new value. This is reasonably
647 * safe since the new value is correct whether or not this transaction
648 * commits. As with vac_update_relstats, this avoids leaving dead tuples
649 * behind after a VACUUM.
652 vac_update_datfrozenxid(void)
655 Form_pg_database dbform;
659 TransactionId newFrozenXid;
663 * Initialize the "min" calculation with GetOldestXmin, which is a
664 * reasonable approximation to the minimum relfrozenxid for not-yet-
665 * committed pg_class entries for new tables; see AddNewRelationTuple().
666 * Se we cannot produce a wrong minimum by starting with this.
668 newFrozenXid = GetOldestXmin(true, true);
671 * We must seqscan pg_class to find the minimum Xid, because there is no
672 * index that can help us here.
674 relation = heap_open(RelationRelationId, AccessShareLock);
676 scan = systable_beginscan(relation, InvalidOid, false,
677 SnapshotNow, 0, NULL);
679 while ((classTup = systable_getnext(scan)) != NULL)
681 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
684 * Only consider heap and TOAST tables (anything else should have
685 * InvalidTransactionId in relfrozenxid anyway.)
687 if (classForm->relkind != RELKIND_RELATION &&
688 classForm->relkind != RELKIND_TOASTVALUE)
691 Assert(TransactionIdIsNormal(classForm->relfrozenxid));
693 if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
694 newFrozenXid = classForm->relfrozenxid;
697 /* we're done with pg_class */
698 systable_endscan(scan);
699 heap_close(relation, AccessShareLock);
701 Assert(TransactionIdIsNormal(newFrozenXid));
703 /* Now fetch the pg_database tuple we need to update. */
704 relation = heap_open(DatabaseRelationId, RowExclusiveLock);
706 /* Fetch a copy of the tuple to scribble on */
707 tuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
708 if (!HeapTupleIsValid(tuple))
709 elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
710 dbform = (Form_pg_database) GETSTRUCT(tuple);
713 * Don't allow datfrozenxid to go backward (probably can't happen anyway);
714 * and detect the common case where it doesn't go forward either.
716 if (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid))
718 dbform->datfrozenxid = newFrozenXid;
723 heap_inplace_update(relation, tuple);
725 heap_freetuple(tuple);
726 heap_close(relation, RowExclusiveLock);
729 * If we were able to advance datfrozenxid, see if we can truncate
730 * pg_clog. Also do it if the shared XID-wrap-limit info is stale, since
731 * this action will update that too.
733 if (dirty || ForceTransactionIdLimitUpdate())
734 vac_truncate_clog(newFrozenXid);
739 * vac_truncate_clog() -- attempt to truncate the commit log
741 * Scan pg_database to determine the system-wide oldest datfrozenxid,
742 * and use it to truncate the transaction commit log (pg_clog).
743 * Also update the XID wrap limit info maintained by varsup.c.
745 * The passed XID is simply the one I just wrote into my pg_database
746 * entry. It's used to initialize the "min" calculation.
748 * This routine is only invoked when we've managed to change our
749 * DB's datfrozenxid entry, or we found that the shared XID-wrap-limit
753 vac_truncate_clog(TransactionId frozenXID)
755 TransactionId myXID = GetCurrentTransactionId();
760 bool frozenAlreadyWrapped = false;
762 /* init oldest_datoid to sync with my frozenXID */
763 oldest_datoid = MyDatabaseId;
766 * Scan pg_database to compute the minimum datfrozenxid
768 * Note: we need not worry about a race condition with new entries being
769 * inserted by CREATE DATABASE. Any such entry will have a copy of some
770 * existing DB's datfrozenxid, and that source DB cannot be ours because
771 * of the interlock against copying a DB containing an active backend.
772 * Hence the new entry will not reduce the minimum. Also, if two VACUUMs
773 * concurrently modify the datfrozenxid's of different databases, the
774 * worst possible outcome is that pg_clog is not truncated as aggressively
777 relation = heap_open(DatabaseRelationId, AccessShareLock);
779 scan = heap_beginscan(relation, SnapshotNow, 0, NULL);
781 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
783 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
785 Assert(TransactionIdIsNormal(dbform->datfrozenxid));
787 if (TransactionIdPrecedes(myXID, dbform->datfrozenxid))
788 frozenAlreadyWrapped = true;
789 else if (TransactionIdPrecedes(dbform->datfrozenxid, frozenXID))
791 frozenXID = dbform->datfrozenxid;
792 oldest_datoid = HeapTupleGetOid(tuple);
798 heap_close(relation, AccessShareLock);
801 * Do not truncate CLOG if we seem to have suffered wraparound already;
802 * the computed minimum XID might be bogus. This case should now be
803 * impossible due to the defenses in GetNewTransactionId, but we keep the
806 if (frozenAlreadyWrapped)
809 (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
810 errdetail("You might have already suffered transaction-wraparound data loss.")));
814 /* Truncate CLOG to the oldest frozenxid */
815 TruncateCLOG(frozenXID);
818 * Update the wrap limit for GetNewTransactionId. Note: this function
819 * will also signal the postmaster for an(other) autovac cycle if needed.
821 SetTransactionIdLimit(frozenXID, oldest_datoid);
826 * vacuum_rel() -- vacuum one heap relation
828 * Doing one heap at a time incurs extra overhead, since we need to
829 * check that the heap exists again just before we vacuum it. The
830 * reason that we do this is so that vacuuming can be spread across
831 * many small transactions. Otherwise, two-phase locking would require
832 * us to lock the entire database during one pass of the vacuum cleaner.
834 * At entry and exit, we are not inside a transaction.
837 vacuum_rel(Oid relid, VacuumStmt *vacstmt, bool do_toast, bool for_wraparound)
844 int save_sec_context;
847 /* Begin a transaction for vacuuming this relation */
848 StartTransactionCommand();
851 * Functions in indexes may want a snapshot set. Also, setting a snapshot
852 * ensures that RecentGlobalXmin is kept truly recent.
854 PushActiveSnapshot(GetTransactionSnapshot());
856 if (!(vacstmt->options & VACOPT_FULL))
859 * In lazy vacuum, we can set the PROC_IN_VACUUM flag, which lets
860 * other concurrent VACUUMs know that they can ignore this one while
861 * determining their OldestXmin. (The reason we don't set it during a
862 * full VACUUM is exactly that we may have to run user-defined
863 * functions for functional indexes, and we want to make sure that if
864 * they use the snapshot set above, any tuples it requires can't get
865 * removed from other tables. An index function that depends on the
866 * contents of other tables is arguably broken, but we won't break it
867 * here by violating transaction semantics.)
869 * We also set the VACUUM_FOR_WRAPAROUND flag, which is passed down by
870 * autovacuum; it's used to avoid canceling a vacuum that was invoked
873 * Note: these flags remain set until CommitTransaction or
874 * AbortTransaction. We don't want to clear them until we reset
875 * MyProc->xid/xmin, else OldestXmin might appear to go backwards,
876 * which is probably Not Good.
878 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
879 MyProc->vacuumFlags |= PROC_IN_VACUUM;
881 MyProc->vacuumFlags |= PROC_VACUUM_FOR_WRAPAROUND;
882 LWLockRelease(ProcArrayLock);
886 * Check for user-requested abort. Note we want this to be inside a
887 * transaction, so xact.c doesn't issue useless WARNING.
889 CHECK_FOR_INTERRUPTS();
892 * Determine the type of lock we want --- hard exclusive lock for a FULL
893 * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either
894 * way, we can be sure that no other backend is vacuuming the same table.
896 lmode = (vacstmt->options & VACOPT_FULL) ? AccessExclusiveLock : ShareUpdateExclusiveLock;
899 * Open the relation and get the appropriate lock on it.
901 * There's a race condition here: the rel may have gone away since the
902 * last time we saw it. If so, we don't need to vacuum it.
904 * If we've been asked not to wait for the relation lock, acquire it first
905 * in non-blocking mode, before calling try_relation_open().
907 if (!(vacstmt->options & VACOPT_NOWAIT))
908 onerel = try_relation_open(relid, lmode);
909 else if (ConditionalLockRelationOid(relid, lmode))
910 onerel = try_relation_open(relid, NoLock);
914 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
916 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
917 errmsg("skipping vacuum of \"%s\" --- lock not available",
918 vacstmt->relation->relname)));
924 CommitTransactionCommand();
931 * We allow the user to vacuum a table if he is superuser, the table
932 * owner, or the database owner (but in the latter case, only if it's not
933 * a shared relation). pg_class_ownercheck includes the superuser case.
935 * Note we choose to treat permissions failure as a WARNING and keep
936 * trying to vacuum the rest of the DB --- is this appropriate?
938 if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
939 (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
941 if (onerel->rd_rel->relisshared)
943 (errmsg("skipping \"%s\" --- only superuser can vacuum it",
944 RelationGetRelationName(onerel))));
945 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
947 (errmsg("skipping \"%s\" --- only superuser or database owner can vacuum it",
948 RelationGetRelationName(onerel))));
951 (errmsg("skipping \"%s\" --- only table or database owner can vacuum it",
952 RelationGetRelationName(onerel))));
953 relation_close(onerel, lmode);
955 CommitTransactionCommand();
960 * Check that it's a vacuumable table; we used to do this in
961 * get_rel_oids() but seems safer to check after we've locked the
964 if (onerel->rd_rel->relkind != RELKIND_RELATION &&
965 onerel->rd_rel->relkind != RELKIND_TOASTVALUE)
968 (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
969 RelationGetRelationName(onerel))));
970 relation_close(onerel, lmode);
972 CommitTransactionCommand();
977 * Silently ignore tables that are temp tables of other backends ---
978 * trying to vacuum these will lead to great unhappiness, since their
979 * contents are probably not up-to-date on disk. (We don't throw a
980 * warning here; it would just lead to chatter during a database-wide
983 if (RELATION_IS_OTHER_TEMP(onerel))
985 relation_close(onerel, lmode);
987 CommitTransactionCommand();
992 * Get a session-level lock too. This will protect our access to the
993 * relation across multiple transactions, so that we can vacuum the
994 * relation's TOAST table (if any) secure in the knowledge that no one is
995 * deleting the parent relation.
997 * NOTE: this cannot block, even if someone else is waiting for access,
998 * because the lock manager knows that both lock requests are from the
1001 onerelid = onerel->rd_lockInfo.lockRelId;
1002 LockRelationIdForSession(&onerelid, lmode);
1005 * Remember the relation's TOAST relation for later, if the caller asked
1006 * us to process it. In VACUUM FULL, though, the toast table is
1007 * automatically rebuilt by cluster_rel so we shouldn't recurse to it.
1009 if (do_toast && !(vacstmt->options & VACOPT_FULL))
1010 toast_relid = onerel->rd_rel->reltoastrelid;
1012 toast_relid = InvalidOid;
1015 * Switch to the table owner's userid, so that any index functions are run
1016 * as that user. Also lock down security-restricted operations and
1017 * arrange to make GUC variable changes local to this command. (This is
1018 * unnecessary, but harmless, for lazy VACUUM.)
1020 GetUserIdAndSecContext(&save_userid, &save_sec_context);
1021 SetUserIdAndSecContext(onerel->rd_rel->relowner,
1022 save_sec_context | SECURITY_RESTRICTED_OPERATION);
1023 save_nestlevel = NewGUCNestLevel();
1026 * Do the actual work --- either FULL or "lazy" vacuum
1028 if (vacstmt->options & VACOPT_FULL)
1030 /* close relation before vacuuming, but hold lock until commit */
1031 relation_close(onerel, NoLock);
1034 /* VACUUM FULL is now a variant of CLUSTER; see cluster.c */
1035 cluster_rel(relid, InvalidOid, false,
1036 (vacstmt->options & VACOPT_VERBOSE) != 0,
1037 vacstmt->freeze_min_age, vacstmt->freeze_table_age);
1040 lazy_vacuum_rel(onerel, vacstmt, vac_strategy);
1042 /* Roll back any GUC changes executed by index functions */
1043 AtEOXact_GUC(false, save_nestlevel);
1045 /* Restore userid and security context */
1046 SetUserIdAndSecContext(save_userid, save_sec_context);
1048 /* all done with this class, but hold lock until commit */
1050 relation_close(onerel, NoLock);
1053 * Complete the transaction and free all temporary memory used.
1055 PopActiveSnapshot();
1056 CommitTransactionCommand();
1059 * If the relation has a secondary toast rel, vacuum that too while we
1060 * still hold the session lock on the master table. Note however that
1061 * "analyze" will not get done on the toast table. This is good, because
1062 * the toaster always uses hardcoded index access and statistics are
1063 * totally unimportant for toast relations.
1065 if (toast_relid != InvalidOid)
1066 vacuum_rel(toast_relid, vacstmt, false, for_wraparound);
1069 * Now release the session-level lock on the master table.
1071 UnlockRelationIdForSession(&onerelid, lmode);
1073 /* Report that we really did it. */
1079 * Open all the indexes of the given relation, obtaining the specified kind
1080 * of lock on each. Return an array of Relation pointers for the indexes
1081 * into *Irel, and the number of indexes into *nindexes.
1084 vac_open_indexes(Relation relation, LOCKMODE lockmode,
1085 int *nindexes, Relation **Irel)
1088 ListCell *indexoidscan;
1091 Assert(lockmode != NoLock);
1093 indexoidlist = RelationGetIndexList(relation);
1095 *nindexes = list_length(indexoidlist);
1098 *Irel = (Relation *) palloc(*nindexes * sizeof(Relation));
1103 foreach(indexoidscan, indexoidlist)
1105 Oid indexoid = lfirst_oid(indexoidscan);
1107 (*Irel)[i++] = index_open(indexoid, lockmode);
1110 list_free(indexoidlist);
1114 * Release the resources acquired by vac_open_indexes. Optionally release
1115 * the locks (say NoLock to keep 'em).
1118 vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
1125 Relation ind = Irel[nindexes];
1127 index_close(ind, lockmode);
1133 * vacuum_delay_point --- check for interrupts and cost-based delay.
1135 * This should be called in each major loop of VACUUM processing,
1136 * typically once per page processed.
1139 vacuum_delay_point(void)
1141 /* Always check for interrupts */
1142 CHECK_FOR_INTERRUPTS();
1144 /* Nap if appropriate */
1145 if (VacuumCostActive && !InterruptPending &&
1146 VacuumCostBalance >= VacuumCostLimit)
1150 msec = VacuumCostDelay * VacuumCostBalance / VacuumCostLimit;
1151 if (msec > VacuumCostDelay * 4)
1152 msec = VacuumCostDelay * 4;
1154 pg_usleep(msec * 1000L);
1156 VacuumCostBalance = 0;
1158 /* update balance values for workers */
1159 AutoVacuumUpdateDelay();
1161 /* Might have gotten an interrupt while sleeping */
1162 CHECK_FOR_INTERRUPTS();