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