]> granicus.if.org Git - postgresql/blob - src/backend/commands/vacuum.c
Unify spelling of "canceled", "canceling", "cancellation"
[postgresql] / src / backend / commands / vacuum.c
1 /*-------------------------------------------------------------------------
2  *
3  * vacuum.c
4  *        The postgres vacuum cleaner.
5  *
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
9  * in cluster.c.
10  *
11  *
12  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
13  * Portions Copyright (c) 1994, Regents of the University of California
14  *
15  *
16  * IDENTIFICATION
17  *        src/backend/commands/vacuum.c
18  *
19  *-------------------------------------------------------------------------
20  */
21 #include "postgres.h"
22
23 #include <math.h>
24
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"
36 #include "pgstat.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"
49
50
51 /*
52  * GUC parameters
53  */
54 int                     vacuum_freeze_min_age;
55 int                     vacuum_freeze_table_age;
56
57
58 /* A few variables that don't seem worth passing around as parameters */
59 static MemoryContext vac_context = NULL;
60 static BufferAccessStrategy vac_strategy;
61
62
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,
67                    bool for_wraparound);
68
69
70 /*
71  * Primary entry point for VACUUM and ANALYZE commands.
72  *
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.)
76  *
77  * do_toast is passed as FALSE by autovacuum, because it processes TOAST
78  * tables separately.
79  *
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.
82  *
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.
85  *
86  * isTopLevel should be passed down from ProcessUtility.
87  *
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.
91  */
92 void
93 vacuum(VacuumStmt *vacstmt, Oid relid, bool do_toast,
94            BufferAccessStrategy bstrategy, bool for_wraparound, bool isTopLevel)
95 {
96         const char *stmttype;
97         volatile bool in_outer_xact,
98                                 use_own_xacts;
99         List       *relations;
100
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);
106
107         stmttype = (vacstmt->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
108
109         /*
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.
114          *
115          * ANALYZE (without VACUUM) can run either way.
116          */
117         if (vacstmt->options & VACOPT_VACUUM)
118         {
119                 PreventTransactionChain(isTopLevel, stmttype);
120                 in_outer_xact = false;
121         }
122         else
123                 in_outer_xact = IsInTransactionChain(isTopLevel);
124
125         /*
126          * Send info about dead objects to the statistics collector, unless we are
127          * in autovacuum --- autovacuum.c does this for itself.
128          */
129         if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
130                 pgstat_vacuum_stat();
131
132         /*
133          * Create special memory context for cross-transaction storage.
134          *
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.
137          */
138         vac_context = AllocSetContextCreate(PortalContext,
139                                                                                 "Vacuum",
140                                                                                 ALLOCSET_DEFAULT_MINSIZE,
141                                                                                 ALLOCSET_DEFAULT_INITSIZE,
142                                                                                 ALLOCSET_DEFAULT_MAXSIZE);
143
144         /*
145          * If caller didn't give us a buffer strategy object, make one in the
146          * cross-transaction memory context.
147          */
148         if (bstrategy == NULL)
149         {
150                 MemoryContext old_context = MemoryContextSwitchTo(vac_context);
151
152                 bstrategy = GetAccessStrategy(BAS_VACUUM);
153                 MemoryContextSwitchTo(old_context);
154         }
155         vac_strategy = bstrategy;
156
157         /*
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.)
160          */
161         relations = get_rel_oids(relid, vacstmt->relation);
162
163         /*
164          * Decide whether we need to start/commit our own transactions.
165          *
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
169          * problematic.)
170          *
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.
176          */
177         if (vacstmt->options & VACOPT_VACUUM)
178                 use_own_xacts = true;
179         else
180         {
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;
188                 else
189                         use_own_xacts = false;
190         }
191
192         /*
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
198          * PostgresMain().
199          */
200         if (use_own_xacts)
201         {
202                 /* ActiveSnapshot is not set by autovacuum */
203                 if (ActiveSnapshotSet())
204                         PopActiveSnapshot();
205
206                 /* matches the StartTransaction in PostgresMain() */
207                 CommitTransactionCommand();
208         }
209
210         /* Turn vacuum cost accounting on or off */
211         PG_TRY();
212         {
213                 ListCell   *cur;
214
215                 VacuumCostActive = (VacuumCostDelay > 0);
216                 VacuumCostBalance = 0;
217
218                 /*
219                  * Loop to process each selected relation.
220                  */
221                 foreach(cur, relations)
222                 {
223                         Oid                     relid = lfirst_oid(cur);
224
225                         if (vacstmt->options & VACOPT_VACUUM)
226                         {
227                                 if (!vacuum_rel(relid, vacstmt, do_toast, for_wraparound))
228                                         continue;
229                         }
230
231                         if (vacstmt->options & VACOPT_ANALYZE)
232                         {
233                                 /*
234                                  * If using separate xacts, start one for analyze. Otherwise,
235                                  * we can use the outer transaction.
236                                  */
237                                 if (use_own_xacts)
238                                 {
239                                         StartTransactionCommand();
240                                         /* functions in indexes may want a snapshot set */
241                                         PushActiveSnapshot(GetTransactionSnapshot());
242                                 }
243
244                                 analyze_rel(relid, vacstmt, vac_strategy);
245
246                                 if (use_own_xacts)
247                                 {
248                                         PopActiveSnapshot();
249                                         CommitTransactionCommand();
250                                 }
251                         }
252                 }
253         }
254         PG_CATCH();
255         {
256                 /* Make sure cost accounting is turned off after error */
257                 VacuumCostActive = false;
258                 PG_RE_THROW();
259         }
260         PG_END_TRY();
261
262         /* Turn off vacuum cost accounting */
263         VacuumCostActive = false;
264
265         /*
266          * Finish up processing.
267          */
268         if (use_own_xacts)
269         {
270                 /* here, we are not in a transaction */
271
272                 /*
273                  * This matches the CommitTransaction waiting for us in
274                  * PostgresMain().
275                  */
276                 StartTransactionCommand();
277         }
278
279         if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
280         {
281                 /*
282                  * Update pg_database.datfrozenxid, and truncate pg_clog if possible.
283                  * (autovacuum.c does this for itself.)
284                  */
285                 vac_update_datfrozenxid();
286         }
287
288         /*
289          * Clean up working storage --- note we must do this after
290          * StartTransactionCommand, else we might be trying to delete the active
291          * context!
292          */
293         MemoryContextDelete(vac_context);
294         vac_context = NULL;
295 }
296
297 /*
298  * Build a list of Oids for each relation to be processed
299  *
300  * The list is built in vac_context so that it will survive across our
301  * per-relation transactions.
302  */
303 static List *
304 get_rel_oids(Oid relid, const RangeVar *vacrel)
305 {
306         List       *oid_list = NIL;
307         MemoryContext oldcontext;
308
309         /* OID supplied by VACUUM's caller? */
310         if (OidIsValid(relid))
311         {
312                 oldcontext = MemoryContextSwitchTo(vac_context);
313                 oid_list = lappend_oid(oid_list, relid);
314                 MemoryContextSwitchTo(oldcontext);
315         }
316         else if (vacrel)
317         {
318                 /* Process a specific relation */
319                 Oid                     relid;
320
321                 relid = RangeVarGetRelid(vacrel, false);
322
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);
327         }
328         else
329         {
330                 /* Process all plain relations listed in pg_class */
331                 Relation        pgclass;
332                 HeapScanDesc scan;
333                 HeapTuple       tuple;
334                 ScanKeyData key;
335
336                 ScanKeyInit(&key,
337                                         Anum_pg_class_relkind,
338                                         BTEqualStrategyNumber, F_CHAREQ,
339                                         CharGetDatum(RELKIND_RELATION));
340
341                 pgclass = heap_open(RelationRelationId, AccessShareLock);
342
343                 scan = heap_beginscan(pgclass, SnapshotNow, 1, &key);
344
345                 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
346                 {
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);
351                 }
352
353                 heap_endscan(scan);
354                 heap_close(pgclass, AccessShareLock);
355         }
356
357         return oid_list;
358 }
359
360 /*
361  * vacuum_set_xid_limits() -- compute oldest-Xmin and freeze cutoff points
362  */
363 void
364 vacuum_set_xid_limits(int freeze_min_age,
365                                           int freeze_table_age,
366                                           bool sharedRel,
367                                           TransactionId *oldestXmin,
368                                           TransactionId *freezeLimit,
369                                           TransactionId *freezeTableLimit)
370 {
371         int                     freezemin;
372         TransactionId limit;
373         TransactionId safeLimit;
374
375         /*
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.
383          */
384         *oldestXmin = GetOldestXmin(sharedRel, true);
385
386         Assert(TransactionIdIsNormal(*oldestXmin));
387
388         /*
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.
393          */
394         freezemin = freeze_min_age;
395         if (freezemin < 0)
396                 freezemin = vacuum_freeze_min_age;
397         freezemin = Min(freezemin, autovacuum_freeze_max_age / 2);
398         Assert(freezemin >= 0);
399
400         /*
401          * Compute the cutoff XID, being careful not to generate a "permanent" XID
402          */
403         limit = *oldestXmin - freezemin;
404         if (!TransactionIdIsNormal(limit))
405                 limit = FirstNormalTransactionId;
406
407         /*
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.
411          */
412         safeLimit = ReadNewTransactionId() - autovacuum_freeze_max_age;
413         if (!TransactionIdIsNormal(safeLimit))
414                 safeLimit = FirstNormalTransactionId;
415
416         if (TransactionIdPrecedes(limit, safeLimit))
417         {
418                 ereport(WARNING,
419                                 (errmsg("oldest xmin is far in the past"),
420                                  errhint("Close open transactions soon to avoid wraparound problems.")));
421                 limit = *oldestXmin;
422         }
423
424         *freezeLimit = limit;
425
426         if (freezeTableLimit != NULL)
427         {
428                 int                     freezetable;
429
430                 /*
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.
436                  */
437                 freezetable = freeze_min_age;
438                 if (freezetable < 0)
439                         freezetable = vacuum_freeze_table_age;
440                 freezetable = Min(freezetable, autovacuum_freeze_max_age * 0.95);
441                 Assert(freezetable >= 0);
442
443                 /*
444                  * Compute the cutoff XID, being careful not to generate a "permanent"
445                  * XID.
446                  */
447                 limit = ReadNewTransactionId() - freezetable;
448                 if (!TransactionIdIsNormal(limit))
449                         limit = FirstNormalTransactionId;
450
451                 *freezeTableLimit = limit;
452         }
453 }
454
455
456 /*
457  * vac_estimate_reltuples() -- estimate the new value for pg_class.reltuples
458  *
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.
465  *
466  *              This routine is shared by VACUUM and ANALYZE.
467  */
468 double
469 vac_estimate_reltuples(Relation relation, bool is_analyze,
470                                            BlockNumber total_pages,
471                                            BlockNumber scanned_pages,
472                                            double scanned_tuples)
473 {
474         BlockNumber old_rel_pages = relation->rd_rel->relpages;
475         double          old_rel_tuples = relation->rd_rel->reltuples;
476         double          old_density;
477         double          new_density;
478         double          multiplier;
479         double          updated_density;
480
481         /* If we did scan the whole table, just use the count as-is */
482         if (scanned_pages >= total_pages)
483                 return scanned_tuples;
484
485         /*
486          * If scanned_pages is zero but total_pages isn't, keep the existing value
487          * of reltuples.
488          */
489         if (scanned_pages == 0)
490                 return old_rel_tuples;
491
492         /*
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.
495          */
496         if (old_rel_pages == 0)
497                 return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
498
499         /*
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.
504          *
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.
511          *
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.
518          *
519          * This logic could probably use further refinement.
520          */
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);
526 }
527
528
529 /*
530  *      vac_update_relstats() -- update statistics for one relation
531  *
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.
536  *
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.
545  *
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.
550  *
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.
555  *
556  *              This routine is shared by VACUUM and ANALYZE.
557  */
558 void
559 vac_update_relstats(Relation relation,
560                                         BlockNumber num_pages, double num_tuples,
561                                         bool hasindex, TransactionId frozenxid)
562 {
563         Oid                     relid = RelationGetRelid(relation);
564         Relation        rd;
565         HeapTuple       ctup;
566         Form_pg_class pgcform;
567         bool            dirty;
568
569         rd = heap_open(RelationRelationId, RowExclusiveLock);
570
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",
575                          relid);
576         pgcform = (Form_pg_class) GETSTRUCT(ctup);
577
578         /* Apply required updates, if any, to copied tuple */
579
580         dirty = false;
581         if (pgcform->relpages != (int32) num_pages)
582         {
583                 pgcform->relpages = (int32) num_pages;
584                 dirty = true;
585         }
586         if (pgcform->reltuples != (float4) num_tuples)
587         {
588                 pgcform->reltuples = (float4) num_tuples;
589                 dirty = true;
590         }
591         if (pgcform->relhasindex != hasindex)
592         {
593                 pgcform->relhasindex = hasindex;
594                 dirty = true;
595         }
596
597         /*
598          * If we have discovered that there are no indexes, then there's no
599          * primary key either.  This could be done more thoroughly...
600          */
601         if (pgcform->relhaspkey && !hasindex)
602         {
603                 pgcform->relhaspkey = false;
604                 dirty = true;
605         }
606
607         /* We also clear relhasrules and relhastriggers if needed */
608         if (pgcform->relhasrules && relation->rd_rules == NULL)
609         {
610                 pgcform->relhasrules = false;
611                 dirty = true;
612         }
613         if (pgcform->relhastriggers && relation->trigdesc == NULL)
614         {
615                 pgcform->relhastriggers = false;
616                 dirty = true;
617         }
618
619         /*
620          * relfrozenxid should never go backward.  Caller can pass
621          * InvalidTransactionId if it has no new data.
622          */
623         if (TransactionIdIsNormal(frozenxid) &&
624                 TransactionIdPrecedes(pgcform->relfrozenxid, frozenxid))
625         {
626                 pgcform->relfrozenxid = frozenxid;
627                 dirty = true;
628         }
629
630         /* If anything changed, write out the tuple. */
631         if (dirty)
632                 heap_inplace_update(rd, ctup);
633
634         heap_close(rd, RowExclusiveLock);
635 }
636
637
638 /*
639  *      vac_update_datfrozenxid() -- update pg_database.datfrozenxid for our DB
640  *
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.
644  *
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.
650  */
651 void
652 vac_update_datfrozenxid(void)
653 {
654         HeapTuple       tuple;
655         Form_pg_database dbform;
656         Relation        relation;
657         SysScanDesc scan;
658         HeapTuple       classTup;
659         TransactionId newFrozenXid;
660         bool            dirty = false;
661
662         /*
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.
667          */
668         newFrozenXid = GetOldestXmin(true, true);
669
670         /*
671          * We must seqscan pg_class to find the minimum Xid, because there is no
672          * index that can help us here.
673          */
674         relation = heap_open(RelationRelationId, AccessShareLock);
675
676         scan = systable_beginscan(relation, InvalidOid, false,
677                                                           SnapshotNow, 0, NULL);
678
679         while ((classTup = systable_getnext(scan)) != NULL)
680         {
681                 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
682
683                 /*
684                  * Only consider heap and TOAST tables (anything else should have
685                  * InvalidTransactionId in relfrozenxid anyway.)
686                  */
687                 if (classForm->relkind != RELKIND_RELATION &&
688                         classForm->relkind != RELKIND_TOASTVALUE)
689                         continue;
690
691                 Assert(TransactionIdIsNormal(classForm->relfrozenxid));
692
693                 if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
694                         newFrozenXid = classForm->relfrozenxid;
695         }
696
697         /* we're done with pg_class */
698         systable_endscan(scan);
699         heap_close(relation, AccessShareLock);
700
701         Assert(TransactionIdIsNormal(newFrozenXid));
702
703         /* Now fetch the pg_database tuple we need to update. */
704         relation = heap_open(DatabaseRelationId, RowExclusiveLock);
705
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);
711
712         /*
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.
715          */
716         if (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid))
717         {
718                 dbform->datfrozenxid = newFrozenXid;
719                 dirty = true;
720         }
721
722         if (dirty)
723                 heap_inplace_update(relation, tuple);
724
725         heap_freetuple(tuple);
726         heap_close(relation, RowExclusiveLock);
727
728         /*
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.
732          */
733         if (dirty || ForceTransactionIdLimitUpdate())
734                 vac_truncate_clog(newFrozenXid);
735 }
736
737
738 /*
739  *      vac_truncate_clog() -- attempt to truncate the commit log
740  *
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.
744  *
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.
747  *
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
750  *              info is stale.
751  */
752 static void
753 vac_truncate_clog(TransactionId frozenXID)
754 {
755         TransactionId myXID = GetCurrentTransactionId();
756         Relation        relation;
757         HeapScanDesc scan;
758         HeapTuple       tuple;
759         Oid                     oldest_datoid;
760         bool            frozenAlreadyWrapped = false;
761
762         /* init oldest_datoid to sync with my frozenXID */
763         oldest_datoid = MyDatabaseId;
764
765         /*
766          * Scan pg_database to compute the minimum datfrozenxid
767          *
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
775          * as it could be.
776          */
777         relation = heap_open(DatabaseRelationId, AccessShareLock);
778
779         scan = heap_beginscan(relation, SnapshotNow, 0, NULL);
780
781         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
782         {
783                 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
784
785                 Assert(TransactionIdIsNormal(dbform->datfrozenxid));
786
787                 if (TransactionIdPrecedes(myXID, dbform->datfrozenxid))
788                         frozenAlreadyWrapped = true;
789                 else if (TransactionIdPrecedes(dbform->datfrozenxid, frozenXID))
790                 {
791                         frozenXID = dbform->datfrozenxid;
792                         oldest_datoid = HeapTupleGetOid(tuple);
793                 }
794         }
795
796         heap_endscan(scan);
797
798         heap_close(relation, AccessShareLock);
799
800         /*
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
804          * test anyway.
805          */
806         if (frozenAlreadyWrapped)
807         {
808                 ereport(WARNING,
809                                 (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
810                                  errdetail("You might have already suffered transaction-wraparound data loss.")));
811                 return;
812         }
813
814         /* Truncate CLOG to the oldest frozenxid */
815         TruncateCLOG(frozenXID);
816
817         /*
818          * Update the wrap limit for GetNewTransactionId.  Note: this function
819          * will also signal the postmaster for an(other) autovac cycle if needed.
820          */
821         SetTransactionIdLimit(frozenXID, oldest_datoid);
822 }
823
824
825 /*
826  *      vacuum_rel() -- vacuum one heap relation
827  *
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.
833  *
834  *              At entry and exit, we are not inside a transaction.
835  */
836 static bool
837 vacuum_rel(Oid relid, VacuumStmt *vacstmt, bool do_toast, bool for_wraparound)
838 {
839         LOCKMODE        lmode;
840         Relation        onerel;
841         LockRelId       onerelid;
842         Oid                     toast_relid;
843         Oid                     save_userid;
844         int                     save_sec_context;
845         int                     save_nestlevel;
846
847         /* Begin a transaction for vacuuming this relation */
848         StartTransactionCommand();
849
850         /*
851          * Functions in indexes may want a snapshot set.  Also, setting a snapshot
852          * ensures that RecentGlobalXmin is kept truly recent.
853          */
854         PushActiveSnapshot(GetTransactionSnapshot());
855
856         if (!(vacstmt->options & VACOPT_FULL))
857         {
858                 /*
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.)
868                  *
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
871                  * in an emergency.
872                  *
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.
877                  */
878                 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
879                 MyProc->vacuumFlags |= PROC_IN_VACUUM;
880                 if (for_wraparound)
881                         MyProc->vacuumFlags |= PROC_VACUUM_FOR_WRAPAROUND;
882                 LWLockRelease(ProcArrayLock);
883         }
884
885         /*
886          * Check for user-requested abort.      Note we want this to be inside a
887          * transaction, so xact.c doesn't issue useless WARNING.
888          */
889         CHECK_FOR_INTERRUPTS();
890
891         /*
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.
895          */
896         lmode = (vacstmt->options & VACOPT_FULL) ? AccessExclusiveLock : ShareUpdateExclusiveLock;
897
898         /*
899          * Open the relation and get the appropriate lock on it.
900          *
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.
903          *
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().
906          */
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);
911         else
912         {
913                 onerel = NULL;
914                 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
915                         ereport(LOG,
916                                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
917                                    errmsg("skipping vacuum of \"%s\" --- lock not available",
918                                                   vacstmt->relation->relname)));
919         }
920
921         if (!onerel)
922         {
923                 PopActiveSnapshot();
924                 CommitTransactionCommand();
925                 return false;
926         }
927
928         /*
929          * Check permissions.
930          *
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.
934          *
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?
937          */
938         if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
939                   (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
940         {
941                 if (onerel->rd_rel->relisshared)
942                         ereport(WARNING,
943                                   (errmsg("skipping \"%s\" --- only superuser can vacuum it",
944                                                   RelationGetRelationName(onerel))));
945                 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
946                         ereport(WARNING,
947                                         (errmsg("skipping \"%s\" --- only superuser or database owner can vacuum it",
948                                                         RelationGetRelationName(onerel))));
949                 else
950                         ereport(WARNING,
951                                         (errmsg("skipping \"%s\" --- only table or database owner can vacuum it",
952                                                         RelationGetRelationName(onerel))));
953                 relation_close(onerel, lmode);
954                 PopActiveSnapshot();
955                 CommitTransactionCommand();
956                 return false;
957         }
958
959         /*
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
962          * relation.
963          */
964         if (onerel->rd_rel->relkind != RELKIND_RELATION &&
965                 onerel->rd_rel->relkind != RELKIND_TOASTVALUE)
966         {
967                 ereport(WARNING,
968                                 (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
969                                                 RelationGetRelationName(onerel))));
970                 relation_close(onerel, lmode);
971                 PopActiveSnapshot();
972                 CommitTransactionCommand();
973                 return false;
974         }
975
976         /*
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
981          * VACUUM.)
982          */
983         if (RELATION_IS_OTHER_TEMP(onerel))
984         {
985                 relation_close(onerel, lmode);
986                 PopActiveSnapshot();
987                 CommitTransactionCommand();
988                 return false;
989         }
990
991         /*
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.
996          *
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
999          * same process.
1000          */
1001         onerelid = onerel->rd_lockInfo.lockRelId;
1002         LockRelationIdForSession(&onerelid, lmode);
1003
1004         /*
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.
1008          */
1009         if (do_toast && !(vacstmt->options & VACOPT_FULL))
1010                 toast_relid = onerel->rd_rel->reltoastrelid;
1011         else
1012                 toast_relid = InvalidOid;
1013
1014         /*
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.)
1019          */
1020         GetUserIdAndSecContext(&save_userid, &save_sec_context);
1021         SetUserIdAndSecContext(onerel->rd_rel->relowner,
1022                                                    save_sec_context | SECURITY_RESTRICTED_OPERATION);
1023         save_nestlevel = NewGUCNestLevel();
1024
1025         /*
1026          * Do the actual work --- either FULL or "lazy" vacuum
1027          */
1028         if (vacstmt->options & VACOPT_FULL)
1029         {
1030                 /* close relation before vacuuming, but hold lock until commit */
1031                 relation_close(onerel, NoLock);
1032                 onerel = NULL;
1033
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);
1038         }
1039         else
1040                 lazy_vacuum_rel(onerel, vacstmt, vac_strategy);
1041
1042         /* Roll back any GUC changes executed by index functions */
1043         AtEOXact_GUC(false, save_nestlevel);
1044
1045         /* Restore userid and security context */
1046         SetUserIdAndSecContext(save_userid, save_sec_context);
1047
1048         /* all done with this class, but hold lock until commit */
1049         if (onerel)
1050                 relation_close(onerel, NoLock);
1051
1052         /*
1053          * Complete the transaction and free all temporary memory used.
1054          */
1055         PopActiveSnapshot();
1056         CommitTransactionCommand();
1057
1058         /*
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.
1064          */
1065         if (toast_relid != InvalidOid)
1066                 vacuum_rel(toast_relid, vacstmt, false, for_wraparound);
1067
1068         /*
1069          * Now release the session-level lock on the master table.
1070          */
1071         UnlockRelationIdForSession(&onerelid, lmode);
1072
1073         /* Report that we really did it. */
1074         return true;
1075 }
1076
1077
1078 /*
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.
1082  */
1083 void
1084 vac_open_indexes(Relation relation, LOCKMODE lockmode,
1085                                  int *nindexes, Relation **Irel)
1086 {
1087         List       *indexoidlist;
1088         ListCell   *indexoidscan;
1089         int                     i;
1090
1091         Assert(lockmode != NoLock);
1092
1093         indexoidlist = RelationGetIndexList(relation);
1094
1095         *nindexes = list_length(indexoidlist);
1096
1097         if (*nindexes > 0)
1098                 *Irel = (Relation *) palloc(*nindexes * sizeof(Relation));
1099         else
1100                 *Irel = NULL;
1101
1102         i = 0;
1103         foreach(indexoidscan, indexoidlist)
1104         {
1105                 Oid                     indexoid = lfirst_oid(indexoidscan);
1106
1107                 (*Irel)[i++] = index_open(indexoid, lockmode);
1108         }
1109
1110         list_free(indexoidlist);
1111 }
1112
1113 /*
1114  * Release the resources acquired by vac_open_indexes.  Optionally release
1115  * the locks (say NoLock to keep 'em).
1116  */
1117 void
1118 vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
1119 {
1120         if (Irel == NULL)
1121                 return;
1122
1123         while (nindexes--)
1124         {
1125                 Relation        ind = Irel[nindexes];
1126
1127                 index_close(ind, lockmode);
1128         }
1129         pfree(Irel);
1130 }
1131
1132 /*
1133  * vacuum_delay_point --- check for interrupts and cost-based delay.
1134  *
1135  * This should be called in each major loop of VACUUM processing,
1136  * typically once per page processed.
1137  */
1138 void
1139 vacuum_delay_point(void)
1140 {
1141         /* Always check for interrupts */
1142         CHECK_FOR_INTERRUPTS();
1143
1144         /* Nap if appropriate */
1145         if (VacuumCostActive && !InterruptPending &&
1146                 VacuumCostBalance >= VacuumCostLimit)
1147         {
1148                 int                     msec;
1149
1150                 msec = VacuumCostDelay * VacuumCostBalance / VacuumCostLimit;
1151                 if (msec > VacuumCostDelay * 4)
1152                         msec = VacuumCostDelay * 4;
1153
1154                 pg_usleep(msec * 1000L);
1155
1156                 VacuumCostBalance = 0;
1157
1158                 /* update balance values for workers */
1159                 AutoVacuumUpdateDelay();
1160
1161                 /* Might have gotten an interrupt while sleeping */
1162                 CHECK_FOR_INTERRUPTS();
1163         }
1164 }