]> granicus.if.org Git - postgresql/blob - src/backend/commands/vacuum.c
pgindent run for release 9.3
[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-2013, 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/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"
38 #include "pgstat.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"
51
52
53 /*
54  * GUC parameters
55  */
56 int                     vacuum_freeze_min_age;
57 int                     vacuum_freeze_table_age;
58
59
60 /* A few variables that don't seem worth passing around as parameters */
61 static MemoryContext vac_context = NULL;
62 static BufferAccessStrategy vac_strategy;
63
64
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,
69                    bool for_wraparound);
70
71
72 /*
73  * Primary entry point for VACUUM and ANALYZE commands.
74  *
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.)
78  *
79  * do_toast is passed as FALSE by autovacuum, because it processes TOAST
80  * tables separately.
81  *
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.
84  *
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.
87  *
88  * isTopLevel should be passed down from ProcessUtility.
89  *
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.
93  */
94 void
95 vacuum(VacuumStmt *vacstmt, Oid relid, bool do_toast,
96            BufferAccessStrategy bstrategy, bool for_wraparound, bool isTopLevel)
97 {
98         const char *stmttype;
99         volatile bool in_outer_xact,
100                                 use_own_xacts;
101         List       *relations;
102
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);
108
109         stmttype = (vacstmt->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
110
111         /*
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.
116          *
117          * ANALYZE (without VACUUM) can run either way.
118          */
119         if (vacstmt->options & VACOPT_VACUUM)
120         {
121                 PreventTransactionChain(isTopLevel, stmttype);
122                 in_outer_xact = false;
123         }
124         else
125                 in_outer_xact = IsInTransactionChain(isTopLevel);
126
127         /*
128          * Send info about dead objects to the statistics collector, unless we are
129          * in autovacuum --- autovacuum.c does this for itself.
130          */
131         if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
132                 pgstat_vacuum_stat();
133
134         /*
135          * Create special memory context for cross-transaction storage.
136          *
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.
139          */
140         vac_context = AllocSetContextCreate(PortalContext,
141                                                                                 "Vacuum",
142                                                                                 ALLOCSET_DEFAULT_MINSIZE,
143                                                                                 ALLOCSET_DEFAULT_INITSIZE,
144                                                                                 ALLOCSET_DEFAULT_MAXSIZE);
145
146         /*
147          * If caller didn't give us a buffer strategy object, make one in the
148          * cross-transaction memory context.
149          */
150         if (bstrategy == NULL)
151         {
152                 MemoryContext old_context = MemoryContextSwitchTo(vac_context);
153
154                 bstrategy = GetAccessStrategy(BAS_VACUUM);
155                 MemoryContextSwitchTo(old_context);
156         }
157         vac_strategy = bstrategy;
158
159         /*
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.)
162          */
163         relations = get_rel_oids(relid, vacstmt->relation);
164
165         /*
166          * Decide whether we need to start/commit our own transactions.
167          *
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
171          * problematic.)
172          *
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.
178          */
179         if (vacstmt->options & VACOPT_VACUUM)
180                 use_own_xacts = true;
181         else
182         {
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;
190                 else
191                         use_own_xacts = false;
192         }
193
194         /*
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
200          * PostgresMain().
201          */
202         if (use_own_xacts)
203         {
204                 /* ActiveSnapshot is not set by autovacuum */
205                 if (ActiveSnapshotSet())
206                         PopActiveSnapshot();
207
208                 /* matches the StartTransaction in PostgresMain() */
209                 CommitTransactionCommand();
210         }
211
212         /* Turn vacuum cost accounting on or off */
213         PG_TRY();
214         {
215                 ListCell   *cur;
216
217                 VacuumCostActive = (VacuumCostDelay > 0);
218                 VacuumCostBalance = 0;
219                 VacuumPageHit = 0;
220                 VacuumPageMiss = 0;
221                 VacuumPageDirty = 0;
222
223                 /*
224                  * Loop to process each selected relation.
225                  */
226                 foreach(cur, relations)
227                 {
228                         Oid                     relid = lfirst_oid(cur);
229
230                         if (vacstmt->options & VACOPT_VACUUM)
231                         {
232                                 if (!vacuum_rel(relid, vacstmt, do_toast, for_wraparound))
233                                         continue;
234                         }
235
236                         if (vacstmt->options & VACOPT_ANALYZE)
237                         {
238                                 /*
239                                  * If using separate xacts, start one for analyze. Otherwise,
240                                  * we can use the outer transaction.
241                                  */
242                                 if (use_own_xacts)
243                                 {
244                                         StartTransactionCommand();
245                                         /* functions in indexes may want a snapshot set */
246                                         PushActiveSnapshot(GetTransactionSnapshot());
247                                 }
248
249                                 analyze_rel(relid, vacstmt, vac_strategy);
250
251                                 if (use_own_xacts)
252                                 {
253                                         PopActiveSnapshot();
254                                         CommitTransactionCommand();
255                                 }
256                         }
257                 }
258         }
259         PG_CATCH();
260         {
261                 /* Make sure cost accounting is turned off after error */
262                 VacuumCostActive = false;
263                 PG_RE_THROW();
264         }
265         PG_END_TRY();
266
267         /* Turn off vacuum cost accounting */
268         VacuumCostActive = false;
269
270         /*
271          * Finish up processing.
272          */
273         if (use_own_xacts)
274         {
275                 /* here, we are not in a transaction */
276
277                 /*
278                  * This matches the CommitTransaction waiting for us in
279                  * PostgresMain().
280                  */
281                 StartTransactionCommand();
282         }
283
284         if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
285         {
286                 /*
287                  * Update pg_database.datfrozenxid, and truncate pg_clog if possible.
288                  * (autovacuum.c does this for itself.)
289                  */
290                 vac_update_datfrozenxid();
291         }
292
293         /*
294          * Clean up working storage --- note we must do this after
295          * StartTransactionCommand, else we might be trying to delete the active
296          * context!
297          */
298         MemoryContextDelete(vac_context);
299         vac_context = NULL;
300 }
301
302 /*
303  * Build a list of Oids for each relation to be processed
304  *
305  * The list is built in vac_context so that it will survive across our
306  * per-relation transactions.
307  */
308 static List *
309 get_rel_oids(Oid relid, const RangeVar *vacrel)
310 {
311         List       *oid_list = NIL;
312         MemoryContext oldcontext;
313
314         /* OID supplied by VACUUM's caller? */
315         if (OidIsValid(relid))
316         {
317                 oldcontext = MemoryContextSwitchTo(vac_context);
318                 oid_list = lappend_oid(oid_list, relid);
319                 MemoryContextSwitchTo(oldcontext);
320         }
321         else if (vacrel)
322         {
323                 /* Process a specific relation */
324                 Oid                     relid;
325
326                 /*
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
333                  * and then.
334                  */
335                 relid = RangeVarGetRelid(vacrel, NoLock, false);
336
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);
341         }
342         else
343         {
344                 /*
345                  * Process all plain relations and materialized views listed in
346                  * pg_class
347                  */
348                 Relation        pgclass;
349                 HeapScanDesc scan;
350                 HeapTuple       tuple;
351
352                 pgclass = heap_open(RelationRelationId, AccessShareLock);
353
354                 scan = heap_beginscan(pgclass, SnapshotNow, 0, NULL);
355
356                 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
357                 {
358                         Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
359
360                         if (classForm->relkind != RELKIND_RELATION &&
361                                 classForm->relkind != RELKIND_MATVIEW)
362                                 continue;
363
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);
368                 }
369
370                 heap_endscan(scan);
371                 heap_close(pgclass, AccessShareLock);
372         }
373
374         return oid_list;
375 }
376
377 /*
378  * vacuum_set_xid_limits() -- compute oldest-Xmin and freeze cutoff points
379  */
380 void
381 vacuum_set_xid_limits(int freeze_min_age,
382                                           int freeze_table_age,
383                                           bool sharedRel,
384                                           TransactionId *oldestXmin,
385                                           TransactionId *freezeLimit,
386                                           TransactionId *freezeTableLimit,
387                                           MultiXactId *multiXactFrzLimit)
388 {
389         int                     freezemin;
390         TransactionId limit;
391         TransactionId safeLimit;
392
393         /*
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.
401          */
402         *oldestXmin = GetOldestXmin(sharedRel, true);
403
404         Assert(TransactionIdIsNormal(*oldestXmin));
405
406         /*
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.
411          */
412         freezemin = freeze_min_age;
413         if (freezemin < 0)
414                 freezemin = vacuum_freeze_min_age;
415         freezemin = Min(freezemin, autovacuum_freeze_max_age / 2);
416         Assert(freezemin >= 0);
417
418         /*
419          * Compute the cutoff XID, being careful not to generate a "permanent" XID
420          */
421         limit = *oldestXmin - freezemin;
422         if (!TransactionIdIsNormal(limit))
423                 limit = FirstNormalTransactionId;
424
425         /*
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.
429          */
430         safeLimit = ReadNewTransactionId() - autovacuum_freeze_max_age;
431         if (!TransactionIdIsNormal(safeLimit))
432                 safeLimit = FirstNormalTransactionId;
433
434         if (TransactionIdPrecedes(limit, safeLimit))
435         {
436                 ereport(WARNING,
437                                 (errmsg("oldest xmin is far in the past"),
438                                  errhint("Close open transactions soon to avoid wraparound problems.")));
439                 limit = *oldestXmin;
440         }
441
442         *freezeLimit = limit;
443
444         if (freezeTableLimit != NULL)
445         {
446                 int                     freezetable;
447
448                 /*
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.
454                  */
455                 freezetable = freeze_table_age;
456                 if (freezetable < 0)
457                         freezetable = vacuum_freeze_table_age;
458                 freezetable = Min(freezetable, autovacuum_freeze_max_age * 0.95);
459                 Assert(freezetable >= 0);
460
461                 /*
462                  * Compute the cutoff XID, being careful not to generate a "permanent"
463                  * XID.
464                  */
465                 limit = ReadNewTransactionId() - freezetable;
466                 if (!TransactionIdIsNormal(limit))
467                         limit = FirstNormalTransactionId;
468
469                 *freezeTableLimit = limit;
470         }
471
472         if (multiXactFrzLimit != NULL)
473         {
474                 MultiXactId mxLimit;
475
476                 /*
477                  * simplistic multixactid freezing: use the same freezing policy as
478                  * for Xids
479                  */
480                 mxLimit = GetOldestMultiXactId() - freezemin;
481                 if (mxLimit < FirstMultiXactId)
482                         mxLimit = FirstMultiXactId;
483
484                 *multiXactFrzLimit = mxLimit;
485         }
486 }
487
488 /*
489  * vac_estimate_reltuples() -- estimate the new value for pg_class.reltuples
490  *
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.
497  *
498  *              This routine is shared by VACUUM and ANALYZE.
499  */
500 double
501 vac_estimate_reltuples(Relation relation, bool is_analyze,
502                                            BlockNumber total_pages,
503                                            BlockNumber scanned_pages,
504                                            double scanned_tuples)
505 {
506         BlockNumber old_rel_pages = relation->rd_rel->relpages;
507         double          old_rel_tuples = relation->rd_rel->reltuples;
508         double          old_density;
509         double          new_density;
510         double          multiplier;
511         double          updated_density;
512
513         /* If we did scan the whole table, just use the count as-is */
514         if (scanned_pages >= total_pages)
515                 return scanned_tuples;
516
517         /*
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
521          * provided.)
522          */
523         if (scanned_pages == 0)
524                 return old_rel_tuples;
525
526         /*
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.
529          */
530         if (old_rel_pages == 0)
531                 return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
532
533         /*
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.
538          *
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.
545          *
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.
552          *
553          * This logic could probably use further refinement.
554          */
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);
560 }
561
562
563 /*
564  *      vac_update_relstats() -- update statistics for one relation
565  *
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.
570  *
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.
579  *
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.
584  *
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.
589  *
590  *              This routine is shared by VACUUM and ANALYZE.
591  */
592 void
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)
598 {
599         Oid                     relid = RelationGetRelid(relation);
600         Relation        rd;
601         HeapTuple       ctup;
602         Form_pg_class pgcform;
603         bool            dirty;
604
605         rd = heap_open(RelationRelationId, RowExclusiveLock);
606
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",
611                          relid);
612         pgcform = (Form_pg_class) GETSTRUCT(ctup);
613
614         /* Apply required updates, if any, to copied tuple */
615
616         dirty = false;
617         if (pgcform->relpages != (int32) num_pages)
618         {
619                 pgcform->relpages = (int32) num_pages;
620                 dirty = true;
621         }
622         if (pgcform->reltuples != (float4) num_tuples)
623         {
624                 pgcform->reltuples = (float4) num_tuples;
625                 dirty = true;
626         }
627         if (pgcform->relallvisible != (int32) num_all_visible_pages)
628         {
629                 pgcform->relallvisible = (int32) num_all_visible_pages;
630                 dirty = true;
631         }
632         if (pgcform->relhasindex != hasindex)
633         {
634                 pgcform->relhasindex = hasindex;
635                 dirty = true;
636         }
637
638         /*
639          * If we have discovered that there are no indexes, then there's no
640          * primary key either.  This could be done more thoroughly...
641          */
642         if (pgcform->relhaspkey && !hasindex)
643         {
644                 pgcform->relhaspkey = false;
645                 dirty = true;
646         }
647
648         /* We also clear relhasrules and relhastriggers if needed */
649         if (pgcform->relhasrules && relation->rd_rules == NULL)
650         {
651                 pgcform->relhasrules = false;
652                 dirty = true;
653         }
654         if (pgcform->relhastriggers && relation->trigdesc == NULL)
655         {
656                 pgcform->relhastriggers = false;
657                 dirty = true;
658         }
659
660         /*
661          * relfrozenxid should never go backward.  Caller can pass
662          * InvalidTransactionId if it has no new data.
663          */
664         if (TransactionIdIsNormal(frozenxid) &&
665                 TransactionIdPrecedes(pgcform->relfrozenxid, frozenxid))
666         {
667                 pgcform->relfrozenxid = frozenxid;
668                 dirty = true;
669         }
670
671         /* relminmxid must never go backward, either */
672         if (MultiXactIdIsValid(minmulti) &&
673                 MultiXactIdPrecedes(pgcform->relminmxid, minmulti))
674         {
675                 pgcform->relminmxid = minmulti;
676                 dirty = true;
677         }
678
679         /* If anything changed, write out the tuple. */
680         if (dirty)
681                 heap_inplace_update(rd, ctup);
682
683         heap_close(rd, RowExclusiveLock);
684 }
685
686
687 /*
688  *      vac_update_datfrozenxid() -- update pg_database.datfrozenxid for our DB
689  *
690  *              Update pg_database's datfrozenxid entry for our database to be the
691  *              minimum of the pg_class.relfrozenxid values.
692  *
693  *              Similarly, update our datfrozenmulti to be the minimum of the
694  *              pg_class.relfrozenmulti values.
695  *
696  *              If we are able to advance either pg_database value, also try to
697  *              truncate pg_clog and pg_multixact.
698  *
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.
704  */
705 void
706 vac_update_datfrozenxid(void)
707 {
708         HeapTuple       tuple;
709         Form_pg_database dbform;
710         Relation        relation;
711         SysScanDesc scan;
712         HeapTuple       classTup;
713         TransactionId newFrozenXid;
714         MultiXactId newFrozenMulti;
715         bool            dirty = false;
716
717         /*
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.
722          */
723         newFrozenXid = GetOldestXmin(true, true);
724
725         /*
726          * Similarly, initialize the MultiXact "min" with the value that would be
727          * used on pg_class for new tables.  See AddNewRelationTuple().
728          */
729         newFrozenMulti = GetOldestMultiXactId();
730
731         /*
732          * We must seqscan pg_class to find the minimum Xid, because there is no
733          * index that can help us here.
734          */
735         relation = heap_open(RelationRelationId, AccessShareLock);
736
737         scan = systable_beginscan(relation, InvalidOid, false,
738                                                           SnapshotNow, 0, NULL);
739
740         while ((classTup = systable_getnext(scan)) != NULL)
741         {
742                 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
743
744                 /*
745                  * Only consider heap and TOAST tables (anything else should have
746                  * InvalidTransactionId in relfrozenxid anyway.)
747                  */
748                 if (classForm->relkind != RELKIND_RELATION &&
749                         classForm->relkind != RELKIND_MATVIEW &&
750                         classForm->relkind != RELKIND_TOASTVALUE)
751                         continue;
752
753                 Assert(TransactionIdIsNormal(classForm->relfrozenxid));
754                 Assert(MultiXactIdIsValid(classForm->relminmxid));
755
756                 if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
757                         newFrozenXid = classForm->relfrozenxid;
758
759                 if (MultiXactIdPrecedes(classForm->relminmxid, newFrozenMulti))
760                         newFrozenMulti = classForm->relminmxid;
761         }
762
763         /* we're done with pg_class */
764         systable_endscan(scan);
765         heap_close(relation, AccessShareLock);
766
767         Assert(TransactionIdIsNormal(newFrozenXid));
768         Assert(MultiXactIdIsValid(newFrozenMulti));
769
770         /* Now fetch the pg_database tuple we need to update. */
771         relation = heap_open(DatabaseRelationId, RowExclusiveLock);
772
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);
778
779         /*
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.
782          */
783         if (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid))
784         {
785                 dbform->datfrozenxid = newFrozenXid;
786                 dirty = true;
787         }
788
789         /* ditto */
790         if (MultiXactIdPrecedes(dbform->datminmxid, newFrozenMulti))
791         {
792                 dbform->datminmxid = newFrozenMulti;
793                 dirty = true;
794         }
795
796         if (dirty)
797                 heap_inplace_update(relation, tuple);
798
799         heap_freetuple(tuple);
800         heap_close(relation, RowExclusiveLock);
801
802         /*
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.
806          */
807         if (dirty || ForceTransactionIdLimitUpdate())
808                 vac_truncate_clog(newFrozenXid, newFrozenMulti);
809 }
810
811
812 /*
813  *      vac_truncate_clog() -- attempt to truncate the commit log
814  *
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.
818  *
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.
821  *
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
824  *              info is stale.
825  */
826 static void
827 vac_truncate_clog(TransactionId frozenXID, MultiXactId frozenMulti)
828 {
829         TransactionId myXID = GetCurrentTransactionId();
830         Relation        relation;
831         HeapScanDesc scan;
832         HeapTuple       tuple;
833         Oid                     oldestxid_datoid;
834         Oid                     oldestmulti_datoid;
835         bool            frozenAlreadyWrapped = false;
836
837         /* init oldest datoids to sync with my frozen values */
838         oldestxid_datoid = MyDatabaseId;
839         oldestmulti_datoid = MyDatabaseId;
840
841         /*
842          * Scan pg_database to compute the minimum datfrozenxid
843          *
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
851          * as it could be.
852          */
853         relation = heap_open(DatabaseRelationId, AccessShareLock);
854
855         scan = heap_beginscan(relation, SnapshotNow, 0, NULL);
856
857         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
858         {
859                 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
860
861                 Assert(TransactionIdIsNormal(dbform->datfrozenxid));
862                 Assert(MultiXactIdIsValid(dbform->datminmxid));
863
864                 if (TransactionIdPrecedes(myXID, dbform->datfrozenxid))
865                         frozenAlreadyWrapped = true;
866                 else if (TransactionIdPrecedes(dbform->datfrozenxid, frozenXID))
867                 {
868                         frozenXID = dbform->datfrozenxid;
869                         oldestxid_datoid = HeapTupleGetOid(tuple);
870                 }
871
872                 if (MultiXactIdPrecedes(dbform->datminmxid, frozenMulti))
873                 {
874                         frozenMulti = dbform->datminmxid;
875                         oldestmulti_datoid = HeapTupleGetOid(tuple);
876                 }
877         }
878
879         heap_endscan(scan);
880
881         heap_close(relation, AccessShareLock);
882
883         /*
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
887          * test anyway.
888          */
889         if (frozenAlreadyWrapped)
890         {
891                 ereport(WARNING,
892                                 (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
893                                  errdetail("You might have already suffered transaction-wraparound data loss.")));
894                 return;
895         }
896
897         /* Truncate CLOG and Multi to the oldest computed value */
898         TruncateCLOG(frozenXID);
899         TruncateMultiXact(frozenMulti);
900
901         /*
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
905          * signalling twice?
906          */
907         SetTransactionIdLimit(frozenXID, oldestxid_datoid);
908         MultiXactAdvanceOldest(frozenMulti, oldestmulti_datoid);
909 }
910
911
912 /*
913  *      vacuum_rel() -- vacuum one heap relation
914  *
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.
920  *
921  *              At entry and exit, we are not inside a transaction.
922  */
923 static bool
924 vacuum_rel(Oid relid, VacuumStmt *vacstmt, bool do_toast, bool for_wraparound)
925 {
926         LOCKMODE        lmode;
927         Relation        onerel;
928         LockRelId       onerelid;
929         Oid                     toast_relid;
930         Oid                     save_userid;
931         int                     save_sec_context;
932         int                     save_nestlevel;
933
934         /* Begin a transaction for vacuuming this relation */
935         StartTransactionCommand();
936
937         /*
938          * Functions in indexes may want a snapshot set.  Also, setting a snapshot
939          * ensures that RecentGlobalXmin is kept truly recent.
940          */
941         PushActiveSnapshot(GetTransactionSnapshot());
942
943         if (!(vacstmt->options & VACOPT_FULL))
944         {
945                 /*
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.)
955                  *
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
958                  * in an emergency.
959                  *
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.
964                  */
965                 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
966                 MyPgXact->vacuumFlags |= PROC_IN_VACUUM;
967                 if (for_wraparound)
968                         MyPgXact->vacuumFlags |= PROC_VACUUM_FOR_WRAPAROUND;
969                 LWLockRelease(ProcArrayLock);
970         }
971
972         /*
973          * Check for user-requested abort.      Note we want this to be inside a
974          * transaction, so xact.c doesn't issue useless WARNING.
975          */
976         CHECK_FOR_INTERRUPTS();
977
978         /*
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.
982          */
983         lmode = (vacstmt->options & VACOPT_FULL) ? AccessExclusiveLock : ShareUpdateExclusiveLock;
984
985         /*
986          * Open the relation and get the appropriate lock on it.
987          *
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.
990          *
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().
993          */
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);
998         else
999         {
1000                 onerel = NULL;
1001                 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
1002                         ereport(LOG,
1003                                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
1004                                    errmsg("skipping vacuum of \"%s\" --- lock not available",
1005                                                   vacstmt->relation->relname)));
1006         }
1007
1008         if (!onerel)
1009         {
1010                 PopActiveSnapshot();
1011                 CommitTransactionCommand();
1012                 return false;
1013         }
1014
1015         /*
1016          * Check permissions.
1017          *
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.
1021          *
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?
1024          */
1025         if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
1026                   (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
1027         {
1028                 if (onerel->rd_rel->relisshared)
1029                         ereport(WARNING,
1030                                   (errmsg("skipping \"%s\" --- only superuser can vacuum it",
1031                                                   RelationGetRelationName(onerel))));
1032                 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
1033                         ereport(WARNING,
1034                                         (errmsg("skipping \"%s\" --- only superuser or database owner can vacuum it",
1035                                                         RelationGetRelationName(onerel))));
1036                 else
1037                         ereport(WARNING,
1038                                         (errmsg("skipping \"%s\" --- only table or database owner can vacuum it",
1039                                                         RelationGetRelationName(onerel))));
1040                 relation_close(onerel, lmode);
1041                 PopActiveSnapshot();
1042                 CommitTransactionCommand();
1043                 return false;
1044         }
1045
1046         /*
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
1049          * relation.
1050          */
1051         if (onerel->rd_rel->relkind != RELKIND_RELATION &&
1052                 onerel->rd_rel->relkind != RELKIND_MATVIEW &&
1053                 onerel->rd_rel->relkind != RELKIND_TOASTVALUE)
1054         {
1055                 ereport(WARNING,
1056                                 (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
1057                                                 RelationGetRelationName(onerel))));
1058                 relation_close(onerel, lmode);
1059                 PopActiveSnapshot();
1060                 CommitTransactionCommand();
1061                 return false;
1062         }
1063
1064         /*
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
1069          * VACUUM.)
1070          */
1071         if (RELATION_IS_OTHER_TEMP(onerel))
1072         {
1073                 relation_close(onerel, lmode);
1074                 PopActiveSnapshot();
1075                 CommitTransactionCommand();
1076                 return false;
1077         }
1078
1079         /*
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.
1084          *
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
1087          * same process.
1088          */
1089         onerelid = onerel->rd_lockInfo.lockRelId;
1090         LockRelationIdForSession(&onerelid, lmode);
1091
1092         /*
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.
1096          */
1097         if (do_toast && !(vacstmt->options & VACOPT_FULL))
1098                 toast_relid = onerel->rd_rel->reltoastrelid;
1099         else
1100                 toast_relid = InvalidOid;
1101
1102         /*
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.)
1107          */
1108         GetUserIdAndSecContext(&save_userid, &save_sec_context);
1109         SetUserIdAndSecContext(onerel->rd_rel->relowner,
1110                                                    save_sec_context | SECURITY_RESTRICTED_OPERATION);
1111         save_nestlevel = NewGUCNestLevel();
1112
1113         /*
1114          * Do the actual work --- either FULL or "lazy" vacuum
1115          */
1116         if (vacstmt->options & VACOPT_FULL)
1117         {
1118                 /* close relation before vacuuming, but hold lock until commit */
1119                 relation_close(onerel, NoLock);
1120                 onerel = NULL;
1121
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);
1126         }
1127         else
1128                 lazy_vacuum_rel(onerel, vacstmt, vac_strategy);
1129
1130         /* Roll back any GUC changes executed by index functions */
1131         AtEOXact_GUC(false, save_nestlevel);
1132
1133         /* Restore userid and security context */
1134         SetUserIdAndSecContext(save_userid, save_sec_context);
1135
1136         /* all done with this class, but hold lock until commit */
1137         if (onerel)
1138                 relation_close(onerel, NoLock);
1139
1140         /*
1141          * Complete the transaction and free all temporary memory used.
1142          */
1143         PopActiveSnapshot();
1144         CommitTransactionCommand();
1145
1146         /*
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.
1152          */
1153         if (toast_relid != InvalidOid)
1154                 vacuum_rel(toast_relid, vacstmt, false, for_wraparound);
1155
1156         /*
1157          * Now release the session-level lock on the master table.
1158          */
1159         UnlockRelationIdForSession(&onerelid, lmode);
1160
1161         /* Report that we really did it. */
1162         return true;
1163 }
1164
1165
1166 /*
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.
1170  *
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.
1177  */
1178 void
1179 vac_open_indexes(Relation relation, LOCKMODE lockmode,
1180                                  int *nindexes, Relation **Irel)
1181 {
1182         List       *indexoidlist;
1183         ListCell   *indexoidscan;
1184         int                     i;
1185
1186         Assert(lockmode != NoLock);
1187
1188         indexoidlist = RelationGetIndexList(relation);
1189
1190         /* allocate enough memory for all indexes */
1191         i = list_length(indexoidlist);
1192
1193         if (i > 0)
1194                 *Irel = (Relation *) palloc(i * sizeof(Relation));
1195         else
1196                 *Irel = NULL;
1197
1198         /* collect just the ready indexes */
1199         i = 0;
1200         foreach(indexoidscan, indexoidlist)
1201         {
1202                 Oid                     indexoid = lfirst_oid(indexoidscan);
1203                 Relation        indrel;
1204
1205                 indrel = index_open(indexoid, lockmode);
1206                 if (IndexIsReady(indrel->rd_index))
1207                         (*Irel)[i++] = indrel;
1208                 else
1209                         index_close(indrel, lockmode);
1210         }
1211
1212         *nindexes = i;
1213
1214         list_free(indexoidlist);
1215 }
1216
1217 /*
1218  * Release the resources acquired by vac_open_indexes.  Optionally release
1219  * the locks (say NoLock to keep 'em).
1220  */
1221 void
1222 vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
1223 {
1224         if (Irel == NULL)
1225                 return;
1226
1227         while (nindexes--)
1228         {
1229                 Relation        ind = Irel[nindexes];
1230
1231                 index_close(ind, lockmode);
1232         }
1233         pfree(Irel);
1234 }
1235
1236 /*
1237  * vacuum_delay_point --- check for interrupts and cost-based delay.
1238  *
1239  * This should be called in each major loop of VACUUM processing,
1240  * typically once per page processed.
1241  */
1242 void
1243 vacuum_delay_point(void)
1244 {
1245         /* Always check for interrupts */
1246         CHECK_FOR_INTERRUPTS();
1247
1248         /* Nap if appropriate */
1249         if (VacuumCostActive && !InterruptPending &&
1250                 VacuumCostBalance >= VacuumCostLimit)
1251         {
1252                 int                     msec;
1253
1254                 msec = VacuumCostDelay * VacuumCostBalance / VacuumCostLimit;
1255                 if (msec > VacuumCostDelay * 4)
1256                         msec = VacuumCostDelay * 4;
1257
1258                 pg_usleep(msec * 1000L);
1259
1260                 VacuumCostBalance = 0;
1261
1262                 /* update balance values for workers */
1263                 AutoVacuumUpdateDelay();
1264
1265                 /* Might have gotten an interrupt while sleeping */
1266                 CHECK_FOR_INTERRUPTS();
1267         }
1268 }