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