]> granicus.if.org Git - postgresql/blob - src/backend/commands/vacuum.c
Rationalize vacuuming options and parameters
[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-2015, 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/commit_ts.h"
27 #include "access/genam.h"
28 #include "access/heapam.h"
29 #include "access/htup_details.h"
30 #include "access/multixact.h"
31 #include "access/transam.h"
32 #include "access/xact.h"
33 #include "catalog/namespace.h"
34 #include "catalog/pg_database.h"
35 #include "catalog/pg_namespace.h"
36 #include "commands/cluster.h"
37 #include "commands/vacuum.h"
38 #include "miscadmin.h"
39 #include "pgstat.h"
40 #include "postmaster/autovacuum.h"
41 #include "storage/bufmgr.h"
42 #include "storage/lmgr.h"
43 #include "storage/proc.h"
44 #include "storage/procarray.h"
45 #include "utils/acl.h"
46 #include "utils/fmgroids.h"
47 #include "utils/guc.h"
48 #include "utils/memutils.h"
49 #include "utils/snapmgr.h"
50 #include "utils/syscache.h"
51 #include "utils/tqual.h"
52
53
54 /*
55  * GUC parameters
56  */
57 int                     vacuum_freeze_min_age;
58 int                     vacuum_freeze_table_age;
59 int                     vacuum_multixact_freeze_min_age;
60 int                     vacuum_multixact_freeze_table_age;
61
62
63 /* A few variables that don't seem worth passing around as parameters */
64 static MemoryContext vac_context = NULL;
65 static BufferAccessStrategy vac_strategy;
66
67
68 /* non-export function prototypes */
69 static List *get_rel_oids(Oid relid, const RangeVar *vacrel);
70 static void vac_truncate_clog(TransactionId frozenXID,
71                                   MultiXactId minMulti,
72                                   TransactionId lastSaneFrozenXid,
73                                   MultiXactId lastSaneMinMulti);
74 static bool vacuum_rel(Oid relid, RangeVar *relation, int options,
75                    VacuumParams *params);
76
77 /*
78  * Primary entry point for manual VACUUM and ANALYZE commands
79  *
80  * This is mainly a preparation wrapper for the real operations that will
81  * happen in vacuum().
82  */
83 void
84 ExecVacuum(VacuumStmt *vacstmt, bool isTopLevel)
85 {
86         VacuumParams    params;
87
88         /* sanity checks on options */
89         Assert(vacstmt->options & (VACOPT_VACUUM | VACOPT_ANALYZE));
90         Assert((vacstmt->options & VACOPT_VACUUM) ||
91                    !(vacstmt->options & (VACOPT_FULL | VACOPT_FREEZE)));
92         Assert((vacstmt->options & VACOPT_ANALYZE) || vacstmt->va_cols == NIL);
93         Assert(!(vacstmt->options & VACOPT_SKIPTOAST));
94
95         /*
96          * All freeze ages are zero if the FREEZE option is given; otherwise pass
97          * them as -1 which means to use the default values.
98          */
99         if (vacstmt->options & VACOPT_FREEZE)
100         {
101                 params.freeze_min_age = 0;
102                 params.freeze_table_age = 0;
103                 params.multixact_freeze_min_age = 0;
104                 params.multixact_freeze_table_age = 0;
105         }
106         else
107         {
108                 params.freeze_min_age = -1;
109                 params.freeze_table_age = -1;
110                 params.multixact_freeze_min_age = -1;
111                 params.multixact_freeze_table_age = -1;
112         }
113
114         /* user-invoked vacuum is never "for wraparound" */
115         params.is_wraparound = false;
116
117         /* Now go through the common routine */
118         vacuum(vacstmt->options, vacstmt->relation, InvalidOid, &params,
119                    vacstmt->va_cols, NULL, isTopLevel);
120 }
121
122 /*
123  * Primary entry point for VACUUM and ANALYZE commands.
124  *
125  * options is a bitmask of VacuumOption flags, indicating what to do.
126  *
127  * relid, if not InvalidOid, indicate the relation to process; otherwise,
128  * the RangeVar is used.  (The latter must always be passed, because it's
129  * used for error messages.)
130  *
131  * params contains a set of parameters that can be used to customize the
132  * behavior.
133  *
134  * va_cols is a list of columns to analyze, or NIL to process them all.
135  *
136  * bstrategy is normally given as NULL, but in autovacuum it can be passed
137  * in to use the same buffer strategy object across multiple vacuum() calls.
138  *
139  * isTopLevel should be passed down from ProcessUtility.
140  *
141  * It is the caller's responsibility that all parameters are allocated in a
142  * memory context that will not disappear at transaction commit.
143  */
144 void
145 vacuum(int options, RangeVar *relation, Oid relid, VacuumParams *params,
146            List *va_cols, BufferAccessStrategy bstrategy, bool isTopLevel)
147 {
148         const char *stmttype;
149         volatile bool in_outer_xact,
150                                 use_own_xacts;
151         List       *relations;
152         static bool in_vacuum = false;
153
154         Assert(params != NULL);
155
156         stmttype = (options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
157
158         /*
159          * We cannot run VACUUM inside a user transaction block; if we were inside
160          * a transaction, then our commit- and start-transaction-command calls
161          * would not have the intended effect!  There are numerous other subtle
162          * dependencies on this, too.
163          *
164          * ANALYZE (without VACUUM) can run either way.
165          */
166         if (options & VACOPT_VACUUM)
167         {
168                 PreventTransactionChain(isTopLevel, stmttype);
169                 in_outer_xact = false;
170         }
171         else
172                 in_outer_xact = IsInTransactionChain(isTopLevel);
173
174         /*
175          * Due to static variables vac_context, anl_context and vac_strategy,
176          * vacuum() is not reentrant.  This matters when VACUUM FULL or ANALYZE
177          * calls a hostile index expression that itself calls ANALYZE.
178          */
179         if (in_vacuum)
180                 elog(ERROR, "%s cannot be executed from VACUUM or ANALYZE", stmttype);
181
182         /*
183          * Send info about dead objects to the statistics collector, unless we are
184          * in autovacuum --- autovacuum.c does this for itself.
185          */
186         if ((options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
187                 pgstat_vacuum_stat();
188
189         /*
190          * Create special memory context for cross-transaction storage.
191          *
192          * Since it is a child of PortalContext, it will go away eventually even
193          * if we suffer an error; there's no need for special abort cleanup logic.
194          */
195         vac_context = AllocSetContextCreate(PortalContext,
196                                                                                 "Vacuum",
197                                                                                 ALLOCSET_DEFAULT_MINSIZE,
198                                                                                 ALLOCSET_DEFAULT_INITSIZE,
199                                                                                 ALLOCSET_DEFAULT_MAXSIZE);
200
201         /*
202          * If caller didn't give us a buffer strategy object, make one in the
203          * cross-transaction memory context.
204          */
205         if (bstrategy == NULL)
206         {
207                 MemoryContext old_context = MemoryContextSwitchTo(vac_context);
208
209                 bstrategy = GetAccessStrategy(BAS_VACUUM);
210                 MemoryContextSwitchTo(old_context);
211         }
212         vac_strategy = bstrategy;
213
214         /*
215          * Build list of relations to process, unless caller gave us one. (If we
216          * build one, we put it in vac_context for safekeeping.)
217          */
218         relations = get_rel_oids(relid, relation);
219
220         /*
221          * Decide whether we need to start/commit our own transactions.
222          *
223          * For VACUUM (with or without ANALYZE): always do so, so that we can
224          * release locks as soon as possible.  (We could possibly use the outer
225          * transaction for a one-table VACUUM, but handling TOAST tables would be
226          * problematic.)
227          *
228          * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
229          * start/commit our own transactions.  Also, there's no need to do so if
230          * only processing one relation.  For multiple relations when not within a
231          * transaction block, and also in an autovacuum worker, use own
232          * transactions so we can release locks sooner.
233          */
234         if (options & VACOPT_VACUUM)
235                 use_own_xacts = true;
236         else
237         {
238                 Assert(options & VACOPT_ANALYZE);
239                 if (IsAutoVacuumWorkerProcess())
240                         use_own_xacts = true;
241                 else if (in_outer_xact)
242                         use_own_xacts = false;
243                 else if (list_length(relations) > 1)
244                         use_own_xacts = true;
245                 else
246                         use_own_xacts = false;
247         }
248
249         /*
250          * vacuum_rel expects to be entered with no transaction active; it will
251          * start and commit its own transaction.  But we are called by an SQL
252          * command, and so we are executing inside a transaction already. We
253          * commit the transaction started in PostgresMain() here, and start
254          * another one before exiting to match the commit waiting for us back in
255          * PostgresMain().
256          */
257         if (use_own_xacts)
258         {
259                 Assert(!in_outer_xact);
260
261                 /* ActiveSnapshot is not set by autovacuum */
262                 if (ActiveSnapshotSet())
263                         PopActiveSnapshot();
264
265                 /* matches the StartTransaction in PostgresMain() */
266                 CommitTransactionCommand();
267         }
268
269         /* Turn vacuum cost accounting on or off */
270         PG_TRY();
271         {
272                 ListCell   *cur;
273
274                 in_vacuum = true;
275                 VacuumCostActive = (VacuumCostDelay > 0);
276                 VacuumCostBalance = 0;
277                 VacuumPageHit = 0;
278                 VacuumPageMiss = 0;
279                 VacuumPageDirty = 0;
280
281                 /*
282                  * Loop to process each selected relation.
283                  */
284                 foreach(cur, relations)
285                 {
286                         Oid                     relid = lfirst_oid(cur);
287
288                         if (options & VACOPT_VACUUM)
289                         {
290                                 if (!vacuum_rel(relid, relation, options, params))
291                                         continue;
292                         }
293
294                         if (options & VACOPT_ANALYZE)
295                         {
296                                 /*
297                                  * If using separate xacts, start one for analyze. Otherwise,
298                                  * we can use the outer transaction.
299                                  */
300                                 if (use_own_xacts)
301                                 {
302                                         StartTransactionCommand();
303                                         /* functions in indexes may want a snapshot set */
304                                         PushActiveSnapshot(GetTransactionSnapshot());
305                                 }
306
307                                 analyze_rel(relid, relation, options,
308                                                         va_cols, in_outer_xact, vac_strategy);
309
310                                 if (use_own_xacts)
311                                 {
312                                         PopActiveSnapshot();
313                                         CommitTransactionCommand();
314                                 }
315                         }
316                 }
317         }
318         PG_CATCH();
319         {
320                 in_vacuum = false;
321                 VacuumCostActive = false;
322                 PG_RE_THROW();
323         }
324         PG_END_TRY();
325
326         in_vacuum = false;
327         VacuumCostActive = false;
328
329         /*
330          * Finish up processing.
331          */
332         if (use_own_xacts)
333         {
334                 /* here, we are not in a transaction */
335
336                 /*
337                  * This matches the CommitTransaction waiting for us in
338                  * PostgresMain().
339                  */
340                 StartTransactionCommand();
341         }
342
343         if ((options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
344         {
345                 /*
346                  * Update pg_database.datfrozenxid, and truncate pg_clog if possible.
347                  * (autovacuum.c does this for itself.)
348                  */
349                 vac_update_datfrozenxid();
350         }
351
352         /*
353          * Clean up working storage --- note we must do this after
354          * StartTransactionCommand, else we might be trying to delete the active
355          * context!
356          */
357         MemoryContextDelete(vac_context);
358         vac_context = NULL;
359 }
360
361 /*
362  * Build a list of Oids for each relation to be processed
363  *
364  * The list is built in vac_context so that it will survive across our
365  * per-relation transactions.
366  */
367 static List *
368 get_rel_oids(Oid relid, const RangeVar *vacrel)
369 {
370         List       *oid_list = NIL;
371         MemoryContext oldcontext;
372
373         /* OID supplied by VACUUM's caller? */
374         if (OidIsValid(relid))
375         {
376                 oldcontext = MemoryContextSwitchTo(vac_context);
377                 oid_list = lappend_oid(oid_list, relid);
378                 MemoryContextSwitchTo(oldcontext);
379         }
380         else if (vacrel)
381         {
382                 /* Process a specific relation */
383                 Oid                     relid;
384
385                 /*
386                  * Since we don't take a lock here, the relation might be gone, or the
387                  * RangeVar might no longer refer to the OID we look up here.  In the
388                  * former case, VACUUM will do nothing; in the latter case, it will
389                  * process the OID we looked up here, rather than the new one. Neither
390                  * is ideal, but there's little practical alternative, since we're
391                  * going to commit this transaction and begin a new one between now
392                  * and then.
393                  */
394                 relid = RangeVarGetRelid(vacrel, NoLock, false);
395
396                 /* Make a relation list entry for this guy */
397                 oldcontext = MemoryContextSwitchTo(vac_context);
398                 oid_list = lappend_oid(oid_list, relid);
399                 MemoryContextSwitchTo(oldcontext);
400         }
401         else
402         {
403                 /*
404                  * Process all plain relations and materialized views listed in
405                  * pg_class
406                  */
407                 Relation        pgclass;
408                 HeapScanDesc scan;
409                 HeapTuple       tuple;
410
411                 pgclass = heap_open(RelationRelationId, AccessShareLock);
412
413                 scan = heap_beginscan_catalog(pgclass, 0, NULL);
414
415                 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
416                 {
417                         Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
418
419                         if (classForm->relkind != RELKIND_RELATION &&
420                                 classForm->relkind != RELKIND_MATVIEW)
421                                 continue;
422
423                         /* Make a relation list entry for this guy */
424                         oldcontext = MemoryContextSwitchTo(vac_context);
425                         oid_list = lappend_oid(oid_list, HeapTupleGetOid(tuple));
426                         MemoryContextSwitchTo(oldcontext);
427                 }
428
429                 heap_endscan(scan);
430                 heap_close(pgclass, AccessShareLock);
431         }
432
433         return oid_list;
434 }
435
436 /*
437  * vacuum_set_xid_limits() -- compute oldest-Xmin and freeze cutoff points
438  *
439  * The output parameters are:
440  * - oldestXmin is the cutoff value used to distinguish whether tuples are
441  *       DEAD or RECENTLY_DEAD (see HeapTupleSatisfiesVacuum).
442  * - freezeLimit is the Xid below which all Xids are replaced by
443  *       FrozenTransactionId during vacuum.
444  * - xidFullScanLimit (computed from table_freeze_age parameter)
445  *       represents a minimum Xid value; a table whose relfrozenxid is older than
446  *       this will have a full-table vacuum applied to it, to freeze tuples across
447  *       the whole table.  Vacuuming a table younger than this value can use a
448  *       partial scan.
449  * - multiXactCutoff is the value below which all MultiXactIds are removed from
450  *       Xmax.
451  * - mxactFullScanLimit is a value against which a table's relminmxid value is
452  *       compared to produce a full-table vacuum, as with xidFullScanLimit.
453  *
454  * xidFullScanLimit and mxactFullScanLimit can be passed as NULL if caller is
455  * not interested.
456  */
457 void
458 vacuum_set_xid_limits(Relation rel,
459                                           int freeze_min_age,
460                                           int freeze_table_age,
461                                           int multixact_freeze_min_age,
462                                           int multixact_freeze_table_age,
463                                           TransactionId *oldestXmin,
464                                           TransactionId *freezeLimit,
465                                           TransactionId *xidFullScanLimit,
466                                           MultiXactId *multiXactCutoff,
467                                           MultiXactId *mxactFullScanLimit)
468 {
469         int                     freezemin;
470         int                     mxid_freezemin;
471         TransactionId limit;
472         TransactionId safeLimit;
473         MultiXactId mxactLimit;
474         MultiXactId safeMxactLimit;
475
476         /*
477          * We can always ignore processes running lazy vacuum.  This is because we
478          * use these values only for deciding which tuples we must keep in the
479          * tables.  Since lazy vacuum doesn't write its XID anywhere, it's safe to
480          * ignore it.  In theory it could be problematic to ignore lazy vacuums in
481          * a full vacuum, but keep in mind that only one vacuum process can be
482          * working on a particular table at any time, and that each vacuum is
483          * always an independent transaction.
484          */
485         *oldestXmin = GetOldestXmin(rel, true);
486
487         Assert(TransactionIdIsNormal(*oldestXmin));
488
489         /*
490          * Determine the minimum freeze age to use: as specified by the caller, or
491          * vacuum_freeze_min_age, but in any case not more than half
492          * autovacuum_freeze_max_age, so that autovacuums to prevent XID
493          * wraparound won't occur too frequently.
494          */
495         freezemin = freeze_min_age;
496         if (freezemin < 0)
497                 freezemin = vacuum_freeze_min_age;
498         freezemin = Min(freezemin, autovacuum_freeze_max_age / 2);
499         Assert(freezemin >= 0);
500
501         /*
502          * Compute the cutoff XID, being careful not to generate a "permanent" XID
503          */
504         limit = *oldestXmin - freezemin;
505         if (!TransactionIdIsNormal(limit))
506                 limit = FirstNormalTransactionId;
507
508         /*
509          * If oldestXmin is very far back (in practice, more than
510          * autovacuum_freeze_max_age / 2 XIDs old), complain and force a minimum
511          * freeze age of zero.
512          */
513         safeLimit = ReadNewTransactionId() - autovacuum_freeze_max_age;
514         if (!TransactionIdIsNormal(safeLimit))
515                 safeLimit = FirstNormalTransactionId;
516
517         if (TransactionIdPrecedes(limit, safeLimit))
518         {
519                 ereport(WARNING,
520                                 (errmsg("oldest xmin is far in the past"),
521                                  errhint("Close open transactions soon to avoid wraparound problems.")));
522                 limit = *oldestXmin;
523         }
524
525         *freezeLimit = limit;
526
527         /*
528          * Determine the minimum multixact freeze age to use: as specified by
529          * caller, or vacuum_multixact_freeze_min_age, but in any case not more
530          * than half autovacuum_multixact_freeze_max_age, so that autovacuums to
531          * prevent MultiXact wraparound won't occur too frequently.
532          */
533         mxid_freezemin = multixact_freeze_min_age;
534         if (mxid_freezemin < 0)
535                 mxid_freezemin = vacuum_multixact_freeze_min_age;
536         mxid_freezemin = Min(mxid_freezemin,
537                                                  autovacuum_multixact_freeze_max_age / 2);
538         Assert(mxid_freezemin >= 0);
539
540         /* compute the cutoff multi, being careful to generate a valid value */
541         mxactLimit = GetOldestMultiXactId() - mxid_freezemin;
542         if (mxactLimit < FirstMultiXactId)
543                 mxactLimit = FirstMultiXactId;
544
545         safeMxactLimit =
546                 ReadNextMultiXactId() - autovacuum_multixact_freeze_max_age;
547         if (safeMxactLimit < FirstMultiXactId)
548                 safeMxactLimit = FirstMultiXactId;
549
550         if (MultiXactIdPrecedes(mxactLimit, safeMxactLimit))
551         {
552                 ereport(WARNING,
553                                 (errmsg("oldest multixact is far in the past"),
554                                  errhint("Close open transactions with multixacts soon to avoid wraparound problems.")));
555                 mxactLimit = safeMxactLimit;
556         }
557
558         *multiXactCutoff = mxactLimit;
559
560         if (xidFullScanLimit != NULL)
561         {
562                 int                     freezetable;
563
564                 Assert(mxactFullScanLimit != NULL);
565
566                 /*
567                  * Determine the table freeze age to use: as specified by the caller,
568                  * or vacuum_freeze_table_age, but in any case not more than
569                  * autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
570                  * VACUUM schedule, the nightly VACUUM gets a chance to freeze tuples
571                  * before anti-wraparound autovacuum is launched.
572                  */
573                 freezetable = freeze_table_age;
574                 if (freezetable < 0)
575                         freezetable = vacuum_freeze_table_age;
576                 freezetable = Min(freezetable, autovacuum_freeze_max_age * 0.95);
577                 Assert(freezetable >= 0);
578
579                 /*
580                  * Compute XID limit causing a full-table vacuum, being careful not to
581                  * generate a "permanent" XID.
582                  */
583                 limit = ReadNewTransactionId() - freezetable;
584                 if (!TransactionIdIsNormal(limit))
585                         limit = FirstNormalTransactionId;
586
587                 *xidFullScanLimit = limit;
588
589                 /*
590                  * Similar to the above, determine the table freeze age to use for
591                  * multixacts: as specified by the caller, or
592                  * vacuum_multixact_freeze_table_age, but in any case not more than
593                  * autovacuum_multixact_freeze_table_age * 0.95, so that if you have
594                  * e.g. nightly VACUUM schedule, the nightly VACUUM gets a chance to
595                  * freeze multixacts before anti-wraparound autovacuum is launched.
596                  */
597                 freezetable = multixact_freeze_table_age;
598                 if (freezetable < 0)
599                         freezetable = vacuum_multixact_freeze_table_age;
600                 freezetable = Min(freezetable,
601                                                   autovacuum_multixact_freeze_max_age * 0.95);
602                 Assert(freezetable >= 0);
603
604                 /*
605                  * Compute MultiXact limit causing a full-table vacuum, being careful
606                  * to generate a valid MultiXact value.
607                  */
608                 mxactLimit = ReadNextMultiXactId() - freezetable;
609                 if (mxactLimit < FirstMultiXactId)
610                         mxactLimit = FirstMultiXactId;
611
612                 *mxactFullScanLimit = mxactLimit;
613         }
614         else
615         {
616                 Assert(mxactFullScanLimit == NULL);
617         }
618 }
619
620 /*
621  * vac_estimate_reltuples() -- estimate the new value for pg_class.reltuples
622  *
623  *              If we scanned the whole relation then we should just use the count of
624  *              live tuples seen; but if we did not, we should not trust the count
625  *              unreservedly, especially not in VACUUM, which may have scanned a quite
626  *              nonrandom subset of the table.  When we have only partial information,
627  *              we take the old value of pg_class.reltuples as a measurement of the
628  *              tuple density in the unscanned pages.
629  *
630  *              This routine is shared by VACUUM and ANALYZE.
631  */
632 double
633 vac_estimate_reltuples(Relation relation, bool is_analyze,
634                                            BlockNumber total_pages,
635                                            BlockNumber scanned_pages,
636                                            double scanned_tuples)
637 {
638         BlockNumber old_rel_pages = relation->rd_rel->relpages;
639         double          old_rel_tuples = relation->rd_rel->reltuples;
640         double          old_density;
641         double          new_density;
642         double          multiplier;
643         double          updated_density;
644
645         /* If we did scan the whole table, just use the count as-is */
646         if (scanned_pages >= total_pages)
647                 return scanned_tuples;
648
649         /*
650          * If scanned_pages is zero but total_pages isn't, keep the existing value
651          * of reltuples.  (Note: callers should avoid updating the pg_class
652          * statistics in this situation, since no new information has been
653          * provided.)
654          */
655         if (scanned_pages == 0)
656                 return old_rel_tuples;
657
658         /*
659          * If old value of relpages is zero, old density is indeterminate; we
660          * can't do much except scale up scanned_tuples to match total_pages.
661          */
662         if (old_rel_pages == 0)
663                 return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
664
665         /*
666          * Okay, we've covered the corner cases.  The normal calculation is to
667          * convert the old measurement to a density (tuples per page), then update
668          * the density using an exponential-moving-average approach, and finally
669          * compute reltuples as updated_density * total_pages.
670          *
671          * For ANALYZE, the moving average multiplier is just the fraction of the
672          * table's pages we scanned.  This is equivalent to assuming that the
673          * tuple density in the unscanned pages didn't change.  Of course, it
674          * probably did, if the new density measurement is different. But over
675          * repeated cycles, the value of reltuples will converge towards the
676          * correct value, if repeated measurements show the same new density.
677          *
678          * For VACUUM, the situation is a bit different: we have looked at a
679          * nonrandom sample of pages, but we know for certain that the pages we
680          * didn't look at are precisely the ones that haven't changed lately.
681          * Thus, there is a reasonable argument for doing exactly the same thing
682          * as for the ANALYZE case, that is use the old density measurement as the
683          * value for the unscanned pages.
684          *
685          * This logic could probably use further refinement.
686          */
687         old_density = old_rel_tuples / old_rel_pages;
688         new_density = scanned_tuples / scanned_pages;
689         multiplier = (double) scanned_pages / (double) total_pages;
690         updated_density = old_density + (new_density - old_density) * multiplier;
691         return floor(updated_density * total_pages + 0.5);
692 }
693
694
695 /*
696  *      vac_update_relstats() -- update statistics for one relation
697  *
698  *              Update the whole-relation statistics that are kept in its pg_class
699  *              row.  There are additional stats that will be updated if we are
700  *              doing ANALYZE, but we always update these stats.  This routine works
701  *              for both index and heap relation entries in pg_class.
702  *
703  *              We violate transaction semantics here by overwriting the rel's
704  *              existing pg_class tuple with the new values.  This is reasonably
705  *              safe as long as we're sure that the new values are correct whether or
706  *              not this transaction commits.  The reason for doing this is that if
707  *              we updated these tuples in the usual way, vacuuming pg_class itself
708  *              wouldn't work very well --- by the time we got done with a vacuum
709  *              cycle, most of the tuples in pg_class would've been obsoleted.  Of
710  *              course, this only works for fixed-size not-null columns, but these are.
711  *
712  *              Another reason for doing it this way is that when we are in a lazy
713  *              VACUUM and have PROC_IN_VACUUM set, we mustn't do any regular updates.
714  *              Somebody vacuuming pg_class might think they could delete a tuple
715  *              marked with xmin = our xid.
716  *
717  *              In addition to fundamentally nontransactional statistics such as
718  *              relpages and relallvisible, we try to maintain certain lazily-updated
719  *              DDL flags such as relhasindex, by clearing them if no longer correct.
720  *              It's safe to do this in VACUUM, which can't run in parallel with
721  *              CREATE INDEX/RULE/TRIGGER and can't be part of a transaction block.
722  *              However, it's *not* safe to do it in an ANALYZE that's within an
723  *              outer transaction, because for example the current transaction might
724  *              have dropped the last index; then we'd think relhasindex should be
725  *              cleared, but if the transaction later rolls back this would be wrong.
726  *              So we refrain from updating the DDL flags if we're inside an outer
727  *              transaction.  This is OK since postponing the flag maintenance is
728  *              always allowable.
729  *
730  *              This routine is shared by VACUUM and ANALYZE.
731  */
732 void
733 vac_update_relstats(Relation relation,
734                                         BlockNumber num_pages, double num_tuples,
735                                         BlockNumber num_all_visible_pages,
736                                         bool hasindex, TransactionId frozenxid,
737                                         MultiXactId minmulti,
738                                         bool in_outer_xact)
739 {
740         Oid                     relid = RelationGetRelid(relation);
741         Relation        rd;
742         HeapTuple       ctup;
743         Form_pg_class pgcform;
744         bool            dirty;
745
746         rd = heap_open(RelationRelationId, RowExclusiveLock);
747
748         /* Fetch a copy of the tuple to scribble on */
749         ctup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
750         if (!HeapTupleIsValid(ctup))
751                 elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
752                          relid);
753         pgcform = (Form_pg_class) GETSTRUCT(ctup);
754
755         /* Apply statistical updates, if any, to copied tuple */
756
757         dirty = false;
758         if (pgcform->relpages != (int32) num_pages)
759         {
760                 pgcform->relpages = (int32) num_pages;
761                 dirty = true;
762         }
763         if (pgcform->reltuples != (float4) num_tuples)
764         {
765                 pgcform->reltuples = (float4) num_tuples;
766                 dirty = true;
767         }
768         if (pgcform->relallvisible != (int32) num_all_visible_pages)
769         {
770                 pgcform->relallvisible = (int32) num_all_visible_pages;
771                 dirty = true;
772         }
773
774         /* Apply DDL updates, but not inside an outer transaction (see above) */
775
776         if (!in_outer_xact)
777         {
778                 /*
779                  * If we didn't find any indexes, reset relhasindex.
780                  */
781                 if (pgcform->relhasindex && !hasindex)
782                 {
783                         pgcform->relhasindex = false;
784                         dirty = true;
785                 }
786
787                 /*
788                  * If we have discovered that there are no indexes, then there's no
789                  * primary key either.  This could be done more thoroughly...
790                  */
791                 if (pgcform->relhaspkey && !hasindex)
792                 {
793                         pgcform->relhaspkey = false;
794                         dirty = true;
795                 }
796
797                 /* We also clear relhasrules and relhastriggers if needed */
798                 if (pgcform->relhasrules && relation->rd_rules == NULL)
799                 {
800                         pgcform->relhasrules = false;
801                         dirty = true;
802                 }
803                 if (pgcform->relhastriggers && relation->trigdesc == NULL)
804                 {
805                         pgcform->relhastriggers = false;
806                         dirty = true;
807                 }
808         }
809
810         /*
811          * Update relfrozenxid, unless caller passed InvalidTransactionId
812          * indicating it has no new data.
813          *
814          * Ordinarily, we don't let relfrozenxid go backwards: if things are
815          * working correctly, the only way the new frozenxid could be older would
816          * be if a previous VACUUM was done with a tighter freeze_min_age, in
817          * which case we don't want to forget the work it already did.  However,
818          * if the stored relfrozenxid is "in the future", then it must be corrupt
819          * and it seems best to overwrite it with the cutoff we used this time.
820          * This should match vac_update_datfrozenxid() concerning what we consider
821          * to be "in the future".
822          */
823         if (TransactionIdIsNormal(frozenxid) &&
824                 pgcform->relfrozenxid != frozenxid &&
825                 (TransactionIdPrecedes(pgcform->relfrozenxid, frozenxid) ||
826                  TransactionIdPrecedes(ReadNewTransactionId(),
827                                                            pgcform->relfrozenxid)))
828         {
829                 pgcform->relfrozenxid = frozenxid;
830                 dirty = true;
831         }
832
833         /* Similarly for relminmxid */
834         if (MultiXactIdIsValid(minmulti) &&
835                 pgcform->relminmxid != minmulti &&
836                 (MultiXactIdPrecedes(pgcform->relminmxid, minmulti) ||
837                  MultiXactIdPrecedes(ReadNextMultiXactId(), pgcform->relminmxid)))
838         {
839                 pgcform->relminmxid = minmulti;
840                 dirty = true;
841         }
842
843         /* If anything changed, write out the tuple. */
844         if (dirty)
845                 heap_inplace_update(rd, ctup);
846
847         heap_close(rd, RowExclusiveLock);
848 }
849
850
851 /*
852  *      vac_update_datfrozenxid() -- update pg_database.datfrozenxid for our DB
853  *
854  *              Update pg_database's datfrozenxid entry for our database to be the
855  *              minimum of the pg_class.relfrozenxid values.
856  *
857  *              Similarly, update our datminmxid to be the minimum of the
858  *              pg_class.relminmxid values.
859  *
860  *              If we are able to advance either pg_database value, also try to
861  *              truncate pg_clog and pg_multixact.
862  *
863  *              We violate transaction semantics here by overwriting the database's
864  *              existing pg_database tuple with the new values.  This is reasonably
865  *              safe since the new values are correct whether or not this transaction
866  *              commits.  As with vac_update_relstats, this avoids leaving dead tuples
867  *              behind after a VACUUM.
868  */
869 void
870 vac_update_datfrozenxid(void)
871 {
872         HeapTuple       tuple;
873         Form_pg_database dbform;
874         Relation        relation;
875         SysScanDesc scan;
876         HeapTuple       classTup;
877         TransactionId newFrozenXid;
878         MultiXactId newMinMulti;
879         TransactionId lastSaneFrozenXid;
880         MultiXactId lastSaneMinMulti;
881         bool            bogus = false;
882         bool            dirty = false;
883
884         /*
885          * Initialize the "min" calculation with GetOldestXmin, which is a
886          * reasonable approximation to the minimum relfrozenxid for not-yet-
887          * committed pg_class entries for new tables; see AddNewRelationTuple().
888          * So we cannot produce a wrong minimum by starting with this.
889          */
890         newFrozenXid = GetOldestXmin(NULL, true);
891
892         /*
893          * Similarly, initialize the MultiXact "min" with the value that would be
894          * used on pg_class for new tables.  See AddNewRelationTuple().
895          */
896         newMinMulti = GetOldestMultiXactId();
897
898         /*
899          * Identify the latest relfrozenxid and relminmxid values that we could
900          * validly see during the scan.  These are conservative values, but it's
901          * not really worth trying to be more exact.
902          */
903         lastSaneFrozenXid = ReadNewTransactionId();
904         lastSaneMinMulti = ReadNextMultiXactId();
905
906         /*
907          * We must seqscan pg_class to find the minimum Xid, because there is no
908          * index that can help us here.
909          */
910         relation = heap_open(RelationRelationId, AccessShareLock);
911
912         scan = systable_beginscan(relation, InvalidOid, false,
913                                                           NULL, 0, NULL);
914
915         while ((classTup = systable_getnext(scan)) != NULL)
916         {
917                 Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
918
919                 /*
920                  * Only consider relations able to hold unfrozen XIDs (anything else
921                  * should have InvalidTransactionId in relfrozenxid anyway.)
922                  */
923                 if (classForm->relkind != RELKIND_RELATION &&
924                         classForm->relkind != RELKIND_MATVIEW &&
925                         classForm->relkind != RELKIND_TOASTVALUE)
926                         continue;
927
928                 Assert(TransactionIdIsNormal(classForm->relfrozenxid));
929                 Assert(MultiXactIdIsValid(classForm->relminmxid));
930
931                 /*
932                  * If things are working properly, no relation should have a
933                  * relfrozenxid or relminmxid that is "in the future".  However, such
934                  * cases have been known to arise due to bugs in pg_upgrade.  If we
935                  * see any entries that are "in the future", chicken out and don't do
936                  * anything.  This ensures we won't truncate clog before those
937                  * relations have been scanned and cleaned up.
938                  */
939                 if (TransactionIdPrecedes(lastSaneFrozenXid, classForm->relfrozenxid) ||
940                         MultiXactIdPrecedes(lastSaneMinMulti, classForm->relminmxid))
941                 {
942                         bogus = true;
943                         break;
944                 }
945
946                 if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
947                         newFrozenXid = classForm->relfrozenxid;
948
949                 if (MultiXactIdPrecedes(classForm->relminmxid, newMinMulti))
950                         newMinMulti = classForm->relminmxid;
951         }
952
953         /* we're done with pg_class */
954         systable_endscan(scan);
955         heap_close(relation, AccessShareLock);
956
957         /* chicken out if bogus data found */
958         if (bogus)
959                 return;
960
961         Assert(TransactionIdIsNormal(newFrozenXid));
962         Assert(MultiXactIdIsValid(newMinMulti));
963
964         /* Now fetch the pg_database tuple we need to update. */
965         relation = heap_open(DatabaseRelationId, RowExclusiveLock);
966
967         /* Fetch a copy of the tuple to scribble on */
968         tuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
969         if (!HeapTupleIsValid(tuple))
970                 elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
971         dbform = (Form_pg_database) GETSTRUCT(tuple);
972
973         /*
974          * As in vac_update_relstats(), we ordinarily don't want to let
975          * datfrozenxid go backward; but if it's "in the future" then it must be
976          * corrupt and it seems best to overwrite it.
977          */
978         if (dbform->datfrozenxid != newFrozenXid &&
979                 (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) ||
980                  TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid)))
981         {
982                 dbform->datfrozenxid = newFrozenXid;
983                 dirty = true;
984         }
985         else
986                 newFrozenXid = dbform->datfrozenxid;
987
988         /* Ditto for datminmxid */
989         if (dbform->datminmxid != newMinMulti &&
990                 (MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) ||
991                  MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid)))
992         {
993                 dbform->datminmxid = newMinMulti;
994                 dirty = true;
995         }
996         else
997                 newMinMulti = dbform->datminmxid;
998
999         if (dirty)
1000                 heap_inplace_update(relation, tuple);
1001
1002         heap_freetuple(tuple);
1003         heap_close(relation, RowExclusiveLock);
1004
1005         /*
1006          * If we were able to advance datfrozenxid or datminmxid, see if we can
1007          * truncate pg_clog and/or pg_multixact.  Also do it if the shared
1008          * XID-wrap-limit info is stale, since this action will update that too.
1009          */
1010         if (dirty || ForceTransactionIdLimitUpdate())
1011                 vac_truncate_clog(newFrozenXid, newMinMulti,
1012                                                   lastSaneFrozenXid, lastSaneMinMulti);
1013 }
1014
1015
1016 /*
1017  *      vac_truncate_clog() -- attempt to truncate the commit log
1018  *
1019  *              Scan pg_database to determine the system-wide oldest datfrozenxid,
1020  *              and use it to truncate the transaction commit log (pg_clog).
1021  *              Also update the XID wrap limit info maintained by varsup.c.
1022  *              Likewise for datminmxid.
1023  *
1024  *              The passed frozenXID and minMulti are the updated values for my own
1025  *              pg_database entry. They're used to initialize the "min" calculations.
1026  *              The caller also passes the "last sane" XID and MXID, since it has
1027  *              those at hand already.
1028  *
1029  *              This routine is only invoked when we've managed to change our
1030  *              DB's datfrozenxid/datminmxid values, or we found that the shared
1031  *              XID-wrap-limit info is stale.
1032  */
1033 static void
1034 vac_truncate_clog(TransactionId frozenXID,
1035                                   MultiXactId minMulti,
1036                                   TransactionId lastSaneFrozenXid,
1037                                   MultiXactId lastSaneMinMulti)
1038 {
1039         TransactionId myXID = GetCurrentTransactionId();
1040         Relation        relation;
1041         HeapScanDesc scan;
1042         HeapTuple       tuple;
1043         Oid                     oldestxid_datoid;
1044         Oid                     minmulti_datoid;
1045         bool            bogus = false;
1046         bool            frozenAlreadyWrapped = false;
1047
1048         /* init oldest datoids to sync with my frozenXID/minMulti values */
1049         oldestxid_datoid = MyDatabaseId;
1050         minmulti_datoid = MyDatabaseId;
1051
1052         /*
1053          * Scan pg_database to compute the minimum datfrozenxid/datminmxid
1054          *
1055          * Note: we need not worry about a race condition with new entries being
1056          * inserted by CREATE DATABASE.  Any such entry will have a copy of some
1057          * existing DB's datfrozenxid, and that source DB cannot be ours because
1058          * of the interlock against copying a DB containing an active backend.
1059          * Hence the new entry will not reduce the minimum.  Also, if two VACUUMs
1060          * concurrently modify the datfrozenxid's of different databases, the
1061          * worst possible outcome is that pg_clog is not truncated as aggressively
1062          * as it could be.
1063          */
1064         relation = heap_open(DatabaseRelationId, AccessShareLock);
1065
1066         scan = heap_beginscan_catalog(relation, 0, NULL);
1067
1068         while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1069         {
1070                 Form_pg_database dbform = (Form_pg_database) GETSTRUCT(tuple);
1071
1072                 Assert(TransactionIdIsNormal(dbform->datfrozenxid));
1073                 Assert(MultiXactIdIsValid(dbform->datminmxid));
1074
1075                 /*
1076                  * If things are working properly, no database should have a
1077                  * datfrozenxid or datminmxid that is "in the future".  However, such
1078                  * cases have been known to arise due to bugs in pg_upgrade.  If we
1079                  * see any entries that are "in the future", chicken out and don't do
1080                  * anything.  This ensures we won't truncate clog before those
1081                  * databases have been scanned and cleaned up.  (We will issue the
1082                  * "already wrapped" warning if appropriate, though.)
1083                  */
1084                 if (TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid) ||
1085                         MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid))
1086                         bogus = true;
1087
1088                 if (TransactionIdPrecedes(myXID, dbform->datfrozenxid))
1089                         frozenAlreadyWrapped = true;
1090                 else if (TransactionIdPrecedes(dbform->datfrozenxid, frozenXID))
1091                 {
1092                         frozenXID = dbform->datfrozenxid;
1093                         oldestxid_datoid = HeapTupleGetOid(tuple);
1094                 }
1095
1096                 if (MultiXactIdPrecedes(dbform->datminmxid, minMulti))
1097                 {
1098                         minMulti = dbform->datminmxid;
1099                         minmulti_datoid = HeapTupleGetOid(tuple);
1100                 }
1101         }
1102
1103         heap_endscan(scan);
1104
1105         heap_close(relation, AccessShareLock);
1106
1107         /*
1108          * Do not truncate CLOG if we seem to have suffered wraparound already;
1109          * the computed minimum XID might be bogus.  This case should now be
1110          * impossible due to the defenses in GetNewTransactionId, but we keep the
1111          * test anyway.
1112          */
1113         if (frozenAlreadyWrapped)
1114         {
1115                 ereport(WARNING,
1116                                 (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
1117                                  errdetail("You might have already suffered transaction-wraparound data loss.")));
1118                 return;
1119         }
1120
1121         /* chicken out if data is bogus in any other way */
1122         if (bogus)
1123                 return;
1124
1125         /*
1126          * Truncate CLOG and CommitTs to the oldest computed value.
1127          * Note we don't truncate multixacts; that will be done by the next
1128          * checkpoint.
1129          */
1130         TruncateCLOG(frozenXID);
1131         TruncateCommitTs(frozenXID, true);
1132
1133         /*
1134          * Update the wrap limit for GetNewTransactionId and creation of new
1135          * MultiXactIds.  Note: these functions will also signal the postmaster
1136          * for an(other) autovac cycle if needed.   XXX should we avoid possibly
1137          * signalling twice?
1138          */
1139         SetTransactionIdLimit(frozenXID, oldestxid_datoid);
1140         SetMultiXactIdLimit(minMulti, minmulti_datoid);
1141         AdvanceOldestCommitTs(frozenXID);
1142 }
1143
1144
1145 /*
1146  *      vacuum_rel() -- vacuum one heap relation
1147  *
1148  *              Doing one heap at a time incurs extra overhead, since we need to
1149  *              check that the heap exists again just before we vacuum it.  The
1150  *              reason that we do this is so that vacuuming can be spread across
1151  *              many small transactions.  Otherwise, two-phase locking would require
1152  *              us to lock the entire database during one pass of the vacuum cleaner.
1153  *
1154  *              At entry and exit, we are not inside a transaction.
1155  */
1156 static bool
1157 vacuum_rel(Oid relid, RangeVar *relation, int options, VacuumParams *params)
1158 {
1159         LOCKMODE        lmode;
1160         Relation        onerel;
1161         LockRelId       onerelid;
1162         Oid                     toast_relid;
1163         Oid                     save_userid;
1164         int                     save_sec_context;
1165         int                     save_nestlevel;
1166
1167         Assert(params != NULL);
1168
1169         /* Begin a transaction for vacuuming this relation */
1170         StartTransactionCommand();
1171
1172         /*
1173          * Functions in indexes may want a snapshot set.  Also, setting a snapshot
1174          * ensures that RecentGlobalXmin is kept truly recent.
1175          */
1176         PushActiveSnapshot(GetTransactionSnapshot());
1177
1178         if (!(options & VACOPT_FULL))
1179         {
1180                 /*
1181                  * In lazy vacuum, we can set the PROC_IN_VACUUM flag, which lets
1182                  * other concurrent VACUUMs know that they can ignore this one while
1183                  * determining their OldestXmin.  (The reason we don't set it during a
1184                  * full VACUUM is exactly that we may have to run user-defined
1185                  * functions for functional indexes, and we want to make sure that if
1186                  * they use the snapshot set above, any tuples it requires can't get
1187                  * removed from other tables.  An index function that depends on the
1188                  * contents of other tables is arguably broken, but we won't break it
1189                  * here by violating transaction semantics.)
1190                  *
1191                  * We also set the VACUUM_FOR_WRAPAROUND flag, which is passed down by
1192                  * autovacuum; it's used to avoid canceling a vacuum that was invoked
1193                  * in an emergency.
1194                  *
1195                  * Note: these flags remain set until CommitTransaction or
1196                  * AbortTransaction.  We don't want to clear them until we reset
1197                  * MyPgXact->xid/xmin, else OldestXmin might appear to go backwards,
1198                  * which is probably Not Good.
1199                  */
1200                 LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
1201                 MyPgXact->vacuumFlags |= PROC_IN_VACUUM;
1202                 if (params->is_wraparound)
1203                         MyPgXact->vacuumFlags |= PROC_VACUUM_FOR_WRAPAROUND;
1204                 LWLockRelease(ProcArrayLock);
1205         }
1206
1207         /*
1208          * Check for user-requested abort.  Note we want this to be inside a
1209          * transaction, so xact.c doesn't issue useless WARNING.
1210          */
1211         CHECK_FOR_INTERRUPTS();
1212
1213         /*
1214          * Determine the type of lock we want --- hard exclusive lock for a FULL
1215          * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either
1216          * way, we can be sure that no other backend is vacuuming the same table.
1217          */
1218         lmode = (options & VACOPT_FULL) ? AccessExclusiveLock : ShareUpdateExclusiveLock;
1219
1220         /*
1221          * Open the relation and get the appropriate lock on it.
1222          *
1223          * There's a race condition here: the rel may have gone away since the
1224          * last time we saw it.  If so, we don't need to vacuum it.
1225          *
1226          * If we've been asked not to wait for the relation lock, acquire it first
1227          * in non-blocking mode, before calling try_relation_open().
1228          */
1229         if (!(options & VACOPT_NOWAIT))
1230                 onerel = try_relation_open(relid, lmode);
1231         else if (ConditionalLockRelationOid(relid, lmode))
1232                 onerel = try_relation_open(relid, NoLock);
1233         else
1234         {
1235                 onerel = NULL;
1236                 if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
1237                         ereport(LOG,
1238                                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
1239                                    errmsg("skipping vacuum of \"%s\" --- lock not available",
1240                                                   relation->relname)));
1241         }
1242
1243         if (!onerel)
1244         {
1245                 PopActiveSnapshot();
1246                 CommitTransactionCommand();
1247                 return false;
1248         }
1249
1250         /*
1251          * Check permissions.
1252          *
1253          * We allow the user to vacuum a table if he is superuser, the table
1254          * owner, or the database owner (but in the latter case, only if it's not
1255          * a shared relation).  pg_class_ownercheck includes the superuser case.
1256          *
1257          * Note we choose to treat permissions failure as a WARNING and keep
1258          * trying to vacuum the rest of the DB --- is this appropriate?
1259          */
1260         if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
1261                   (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
1262         {
1263                 if (onerel->rd_rel->relisshared)
1264                         ereport(WARNING,
1265                                   (errmsg("skipping \"%s\" --- only superuser can vacuum it",
1266                                                   RelationGetRelationName(onerel))));
1267                 else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
1268                         ereport(WARNING,
1269                                         (errmsg("skipping \"%s\" --- only superuser or database owner can vacuum it",
1270                                                         RelationGetRelationName(onerel))));
1271                 else
1272                         ereport(WARNING,
1273                                         (errmsg("skipping \"%s\" --- only table or database owner can vacuum it",
1274                                                         RelationGetRelationName(onerel))));
1275                 relation_close(onerel, lmode);
1276                 PopActiveSnapshot();
1277                 CommitTransactionCommand();
1278                 return false;
1279         }
1280
1281         /*
1282          * Check that it's a vacuumable relation; we used to do this in
1283          * get_rel_oids() but seems safer to check after we've locked the
1284          * relation.
1285          */
1286         if (onerel->rd_rel->relkind != RELKIND_RELATION &&
1287                 onerel->rd_rel->relkind != RELKIND_MATVIEW &&
1288                 onerel->rd_rel->relkind != RELKIND_TOASTVALUE)
1289         {
1290                 ereport(WARNING,
1291                                 (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
1292                                                 RelationGetRelationName(onerel))));
1293                 relation_close(onerel, lmode);
1294                 PopActiveSnapshot();
1295                 CommitTransactionCommand();
1296                 return false;
1297         }
1298
1299         /*
1300          * Silently ignore tables that are temp tables of other backends ---
1301          * trying to vacuum these will lead to great unhappiness, since their
1302          * contents are probably not up-to-date on disk.  (We don't throw a
1303          * warning here; it would just lead to chatter during a database-wide
1304          * VACUUM.)
1305          */
1306         if (RELATION_IS_OTHER_TEMP(onerel))
1307         {
1308                 relation_close(onerel, lmode);
1309                 PopActiveSnapshot();
1310                 CommitTransactionCommand();
1311                 return false;
1312         }
1313
1314         /*
1315          * Get a session-level lock too. This will protect our access to the
1316          * relation across multiple transactions, so that we can vacuum the
1317          * relation's TOAST table (if any) secure in the knowledge that no one is
1318          * deleting the parent relation.
1319          *
1320          * NOTE: this cannot block, even if someone else is waiting for access,
1321          * because the lock manager knows that both lock requests are from the
1322          * same process.
1323          */
1324         onerelid = onerel->rd_lockInfo.lockRelId;
1325         LockRelationIdForSession(&onerelid, lmode);
1326
1327         /*
1328          * Remember the relation's TOAST relation for later, if the caller asked
1329          * us to process it.  In VACUUM FULL, though, the toast table is
1330          * automatically rebuilt by cluster_rel so we shouldn't recurse to it.
1331          */
1332         if (!(options & VACOPT_SKIPTOAST) && !(options & VACOPT_FULL))
1333                 toast_relid = onerel->rd_rel->reltoastrelid;
1334         else
1335                 toast_relid = InvalidOid;
1336
1337         /*
1338          * Switch to the table owner's userid, so that any index functions are run
1339          * as that user.  Also lock down security-restricted operations and
1340          * arrange to make GUC variable changes local to this command. (This is
1341          * unnecessary, but harmless, for lazy VACUUM.)
1342          */
1343         GetUserIdAndSecContext(&save_userid, &save_sec_context);
1344         SetUserIdAndSecContext(onerel->rd_rel->relowner,
1345                                                    save_sec_context | SECURITY_RESTRICTED_OPERATION);
1346         save_nestlevel = NewGUCNestLevel();
1347
1348         /*
1349          * Do the actual work --- either FULL or "lazy" vacuum
1350          */
1351         if (options & VACOPT_FULL)
1352         {
1353                 /* close relation before vacuuming, but hold lock until commit */
1354                 relation_close(onerel, NoLock);
1355                 onerel = NULL;
1356
1357                 /* VACUUM FULL is now a variant of CLUSTER; see cluster.c */
1358                 cluster_rel(relid, InvalidOid, false,
1359                                         (options & VACOPT_VERBOSE) != 0);
1360         }
1361         else
1362                 lazy_vacuum_rel(onerel, options, params, vac_strategy);
1363
1364         /* Roll back any GUC changes executed by index functions */
1365         AtEOXact_GUC(false, save_nestlevel);
1366
1367         /* Restore userid and security context */
1368         SetUserIdAndSecContext(save_userid, save_sec_context);
1369
1370         /* all done with this class, but hold lock until commit */
1371         if (onerel)
1372                 relation_close(onerel, NoLock);
1373
1374         /*
1375          * Complete the transaction and free all temporary memory used.
1376          */
1377         PopActiveSnapshot();
1378         CommitTransactionCommand();
1379
1380         /*
1381          * If the relation has a secondary toast rel, vacuum that too while we
1382          * still hold the session lock on the master table.  Note however that
1383          * "analyze" will not get done on the toast table.  This is good, because
1384          * the toaster always uses hardcoded index access and statistics are
1385          * totally unimportant for toast relations.
1386          */
1387         if (toast_relid != InvalidOid)
1388                 vacuum_rel(toast_relid, relation, options, params);
1389
1390         /*
1391          * Now release the session-level lock on the master table.
1392          */
1393         UnlockRelationIdForSession(&onerelid, lmode);
1394
1395         /* Report that we really did it. */
1396         return true;
1397 }
1398
1399
1400 /*
1401  * Open all the vacuumable indexes of the given relation, obtaining the
1402  * specified kind of lock on each.  Return an array of Relation pointers for
1403  * the indexes into *Irel, and the number of indexes into *nindexes.
1404  *
1405  * We consider an index vacuumable if it is marked insertable (IndexIsReady).
1406  * If it isn't, probably a CREATE INDEX CONCURRENTLY command failed early in
1407  * execution, and what we have is too corrupt to be processable.  We will
1408  * vacuum even if the index isn't indisvalid; this is important because in a
1409  * unique index, uniqueness checks will be performed anyway and had better not
1410  * hit dangling index pointers.
1411  */
1412 void
1413 vac_open_indexes(Relation relation, LOCKMODE lockmode,
1414                                  int *nindexes, Relation **Irel)
1415 {
1416         List       *indexoidlist;
1417         ListCell   *indexoidscan;
1418         int                     i;
1419
1420         Assert(lockmode != NoLock);
1421
1422         indexoidlist = RelationGetIndexList(relation);
1423
1424         /* allocate enough memory for all indexes */
1425         i = list_length(indexoidlist);
1426
1427         if (i > 0)
1428                 *Irel = (Relation *) palloc(i * sizeof(Relation));
1429         else
1430                 *Irel = NULL;
1431
1432         /* collect just the ready indexes */
1433         i = 0;
1434         foreach(indexoidscan, indexoidlist)
1435         {
1436                 Oid                     indexoid = lfirst_oid(indexoidscan);
1437                 Relation        indrel;
1438
1439                 indrel = index_open(indexoid, lockmode);
1440                 if (IndexIsReady(indrel->rd_index))
1441                         (*Irel)[i++] = indrel;
1442                 else
1443                         index_close(indrel, lockmode);
1444         }
1445
1446         *nindexes = i;
1447
1448         list_free(indexoidlist);
1449 }
1450
1451 /*
1452  * Release the resources acquired by vac_open_indexes.  Optionally release
1453  * the locks (say NoLock to keep 'em).
1454  */
1455 void
1456 vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
1457 {
1458         if (Irel == NULL)
1459                 return;
1460
1461         while (nindexes--)
1462         {
1463                 Relation        ind = Irel[nindexes];
1464
1465                 index_close(ind, lockmode);
1466         }
1467         pfree(Irel);
1468 }
1469
1470 /*
1471  * vacuum_delay_point --- check for interrupts and cost-based delay.
1472  *
1473  * This should be called in each major loop of VACUUM processing,
1474  * typically once per page processed.
1475  */
1476 void
1477 vacuum_delay_point(void)
1478 {
1479         /* Always check for interrupts */
1480         CHECK_FOR_INTERRUPTS();
1481
1482         /* Nap if appropriate */
1483         if (VacuumCostActive && !InterruptPending &&
1484                 VacuumCostBalance >= VacuumCostLimit)
1485         {
1486                 int                     msec;
1487
1488                 msec = VacuumCostDelay * VacuumCostBalance / VacuumCostLimit;
1489                 if (msec > VacuumCostDelay * 4)
1490                         msec = VacuumCostDelay * 4;
1491
1492                 pg_usleep(msec * 1000L);
1493
1494                 VacuumCostBalance = 0;
1495
1496                 /* update balance values for workers */
1497                 AutoVacuumUpdateDelay();
1498
1499                 /* Might have gotten an interrupt while sleeping */
1500                 CHECK_FOR_INTERRUPTS();
1501         }
1502 }