LCOV - code coverage report
Current view: top level - src/backend/commands - vacuum.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 654 718 91.1 %
Date: 2025-01-18 04:15:08 Functions: 21 22 95.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * vacuum.c
       4             :  *    The postgres vacuum cleaner.
       5             :  *
       6             :  * This file includes (a) control and dispatch code for VACUUM and ANALYZE
       7             :  * commands, (b) code to compute various vacuum thresholds, and (c) index
       8             :  * vacuum code.
       9             :  *
      10             :  * VACUUM for heap AM is implemented in vacuumlazy.c, parallel vacuum in
      11             :  * vacuumparallel.c, ANALYZE in analyze.c, and VACUUM FULL is a variant of
      12             :  * CLUSTER, handled in cluster.c.
      13             :  *
      14             :  *
      15             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
      16             :  * Portions Copyright (c) 1994, Regents of the University of California
      17             :  *
      18             :  *
      19             :  * IDENTIFICATION
      20             :  *    src/backend/commands/vacuum.c
      21             :  *
      22             :  *-------------------------------------------------------------------------
      23             :  */
      24             : #include "postgres.h"
      25             : 
      26             : #include <math.h>
      27             : 
      28             : #include "access/clog.h"
      29             : #include "access/commit_ts.h"
      30             : #include "access/genam.h"
      31             : #include "access/heapam.h"
      32             : #include "access/htup_details.h"
      33             : #include "access/multixact.h"
      34             : #include "access/tableam.h"
      35             : #include "access/transam.h"
      36             : #include "access/xact.h"
      37             : #include "catalog/namespace.h"
      38             : #include "catalog/pg_database.h"
      39             : #include "catalog/pg_inherits.h"
      40             : #include "commands/cluster.h"
      41             : #include "commands/defrem.h"
      42             : #include "commands/vacuum.h"
      43             : #include "miscadmin.h"
      44             : #include "nodes/makefuncs.h"
      45             : #include "pgstat.h"
      46             : #include "postmaster/autovacuum.h"
      47             : #include "postmaster/bgworker_internals.h"
      48             : #include "postmaster/interrupt.h"
      49             : #include "storage/bufmgr.h"
      50             : #include "storage/lmgr.h"
      51             : #include "storage/pmsignal.h"
      52             : #include "storage/proc.h"
      53             : #include "storage/procarray.h"
      54             : #include "utils/acl.h"
      55             : #include "utils/fmgroids.h"
      56             : #include "utils/guc.h"
      57             : #include "utils/guc_hooks.h"
      58             : #include "utils/memutils.h"
      59             : #include "utils/snapmgr.h"
      60             : #include "utils/syscache.h"
      61             : 
      62             : 
      63             : /*
      64             :  * GUC parameters
      65             :  */
      66             : int         vacuum_freeze_min_age;
      67             : int         vacuum_freeze_table_age;
      68             : int         vacuum_multixact_freeze_min_age;
      69             : int         vacuum_multixact_freeze_table_age;
      70             : int         vacuum_failsafe_age;
      71             : int         vacuum_multixact_failsafe_age;
      72             : 
      73             : /*
      74             :  * Variables for cost-based vacuum delay. The defaults differ between
      75             :  * autovacuum and vacuum. They should be set with the appropriate GUC value in
      76             :  * vacuum code. They are initialized here to the defaults for client backends
      77             :  * executing VACUUM or ANALYZE.
      78             :  */
      79             : double      vacuum_cost_delay = 0;
      80             : int         vacuum_cost_limit = 200;
      81             : 
      82             : /*
      83             :  * VacuumFailsafeActive is a defined as a global so that we can determine
      84             :  * whether or not to re-enable cost-based vacuum delay when vacuuming a table.
      85             :  * If failsafe mode has been engaged, we will not re-enable cost-based delay
      86             :  * for the table until after vacuuming has completed, regardless of other
      87             :  * settings.
      88             :  *
      89             :  * Only VACUUM code should inspect this variable and only table access methods
      90             :  * should set it to true. In Table AM-agnostic VACUUM code, this variable is
      91             :  * inspected to determine whether or not to allow cost-based delays. Table AMs
      92             :  * are free to set it if they desire this behavior, but it is false by default
      93             :  * and reset to false in between vacuuming each relation.
      94             :  */
      95             : bool        VacuumFailsafeActive = false;
      96             : 
      97             : /*
      98             :  * Variables for cost-based parallel vacuum.  See comments atop
      99             :  * compute_parallel_delay to understand how it works.
     100             :  */
     101             : pg_atomic_uint32 *VacuumSharedCostBalance = NULL;
     102             : pg_atomic_uint32 *VacuumActiveNWorkers = NULL;
     103             : int         VacuumCostBalanceLocal = 0;
     104             : 
     105             : /* non-export function prototypes */
     106             : static List *expand_vacuum_rel(VacuumRelation *vrel,
     107             :                                MemoryContext vac_context, int options);
     108             : static List *get_all_vacuum_rels(MemoryContext vac_context, int options);
     109             : static void vac_truncate_clog(TransactionId frozenXID,
     110             :                               MultiXactId minMulti,
     111             :                               TransactionId lastSaneFrozenXid,
     112             :                               MultiXactId lastSaneMinMulti);
     113             : static bool vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,
     114             :                        BufferAccessStrategy bstrategy);
     115             : static double compute_parallel_delay(void);
     116             : static VacOptValue get_vacoptval_from_boolean(DefElem *def);
     117             : static bool vac_tid_reaped(ItemPointer itemptr, void *state);
     118             : 
     119             : /*
     120             :  * GUC check function to ensure GUC value specified is within the allowable
     121             :  * range.
     122             :  */
     123             : bool
     124        1982 : check_vacuum_buffer_usage_limit(int *newval, void **extra,
     125             :                                 GucSource source)
     126             : {
     127             :     /* Value upper and lower hard limits are inclusive */
     128        1982 :     if (*newval == 0 || (*newval >= MIN_BAS_VAC_RING_SIZE_KB &&
     129        1982 :                          *newval <= MAX_BAS_VAC_RING_SIZE_KB))
     130        1982 :         return true;
     131             : 
     132             :     /* Value does not fall within any allowable range */
     133           0 :     GUC_check_errdetail("\"%s\" must be 0 or between %d kB and %d kB.",
     134             :                         "vacuum_buffer_usage_limit",
     135             :                         MIN_BAS_VAC_RING_SIZE_KB, MAX_BAS_VAC_RING_SIZE_KB);
     136             : 
     137           0 :     return false;
     138             : }
     139             : 
     140             : /*
     141             :  * Primary entry point for manual VACUUM and ANALYZE commands
     142             :  *
     143             :  * This is mainly a preparation wrapper for the real operations that will
     144             :  * happen in vacuum().
     145             :  */
     146             : void
     147       10734 : ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel)
     148             : {
     149             :     VacuumParams params;
     150       10734 :     BufferAccessStrategy bstrategy = NULL;
     151       10734 :     bool        verbose = false;
     152       10734 :     bool        skip_locked = false;
     153       10734 :     bool        analyze = false;
     154       10734 :     bool        freeze = false;
     155       10734 :     bool        full = false;
     156       10734 :     bool        disable_page_skipping = false;
     157       10734 :     bool        process_main = true;
     158       10734 :     bool        process_toast = true;
     159             :     int         ring_size;
     160       10734 :     bool        skip_database_stats = false;
     161       10734 :     bool        only_database_stats = false;
     162             :     MemoryContext vac_context;
     163             :     ListCell   *lc;
     164             : 
     165             :     /* index_cleanup and truncate values unspecified for now */
     166       10734 :     params.index_cleanup = VACOPTVALUE_UNSPECIFIED;
     167       10734 :     params.truncate = VACOPTVALUE_UNSPECIFIED;
     168             : 
     169             :     /* By default parallel vacuum is enabled */
     170       10734 :     params.nworkers = 0;
     171             : 
     172             :     /* Will be set later if we recurse to a TOAST table. */
     173       10734 :     params.toast_parent = InvalidOid;
     174             : 
     175             :     /*
     176             :      * Set this to an invalid value so it is clear whether or not a
     177             :      * BUFFER_USAGE_LIMIT was specified when making the access strategy.
     178             :      */
     179       10734 :     ring_size = -1;
     180             : 
     181             :     /* Parse options list */
     182       19712 :     foreach(lc, vacstmt->options)
     183             :     {
     184        9014 :         DefElem    *opt = (DefElem *) lfirst(lc);
     185             : 
     186             :         /* Parse common options for VACUUM and ANALYZE */
     187        9014 :         if (strcmp(opt->defname, "verbose") == 0)
     188          38 :             verbose = defGetBoolean(opt);
     189        8976 :         else if (strcmp(opt->defname, "skip_locked") == 0)
     190         334 :             skip_locked = defGetBoolean(opt);
     191        8642 :         else if (strcmp(opt->defname, "buffer_usage_limit") == 0)
     192             :         {
     193             :             const char *hintmsg;
     194             :             int         result;
     195             :             char       *vac_buffer_size;
     196             : 
     197          54 :             vac_buffer_size = defGetString(opt);
     198             : 
     199             :             /*
     200             :              * Check that the specified value is valid and the size falls
     201             :              * within the hard upper and lower limits if it is not 0.
     202             :              */
     203          54 :             if (!parse_int(vac_buffer_size, &result, GUC_UNIT_KB, &hintmsg) ||
     204          48 :                 (result != 0 &&
     205          36 :                  (result < MIN_BAS_VAC_RING_SIZE_KB || result > MAX_BAS_VAC_RING_SIZE_KB)))
     206             :             {
     207          18 :                 ereport(ERROR,
     208             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     209             :                          errmsg("BUFFER_USAGE_LIMIT option must be 0 or between %d kB and %d kB",
     210             :                                 MIN_BAS_VAC_RING_SIZE_KB, MAX_BAS_VAC_RING_SIZE_KB),
     211             :                          hintmsg ? errhint("%s", _(hintmsg)) : 0));
     212             :             }
     213             : 
     214          36 :             ring_size = result;
     215             :         }
     216        8588 :         else if (!vacstmt->is_vacuumcmd)
     217           6 :             ereport(ERROR,
     218             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     219             :                      errmsg("unrecognized ANALYZE option \"%s\"", opt->defname),
     220             :                      parser_errposition(pstate, opt->location)));
     221             : 
     222             :         /* Parse options available on VACUUM */
     223        8582 :         else if (strcmp(opt->defname, "analyze") == 0)
     224        1376 :             analyze = defGetBoolean(opt);
     225        7206 :         else if (strcmp(opt->defname, "freeze") == 0)
     226        1162 :             freeze = defGetBoolean(opt);
     227        6044 :         else if (strcmp(opt->defname, "full") == 0)
     228         370 :             full = defGetBoolean(opt);
     229        5674 :         else if (strcmp(opt->defname, "disable_page_skipping") == 0)
     230         184 :             disable_page_skipping = defGetBoolean(opt);
     231        5490 :         else if (strcmp(opt->defname, "index_cleanup") == 0)
     232             :         {
     233             :             /* Interpret no string as the default, which is 'auto' */
     234         174 :             if (!opt->arg)
     235           0 :                 params.index_cleanup = VACOPTVALUE_AUTO;
     236             :             else
     237             :             {
     238         174 :                 char       *sval = defGetString(opt);
     239             : 
     240             :                 /* Try matching on 'auto' string, or fall back on boolean */
     241         174 :                 if (pg_strcasecmp(sval, "auto") == 0)
     242           6 :                     params.index_cleanup = VACOPTVALUE_AUTO;
     243             :                 else
     244         168 :                     params.index_cleanup = get_vacoptval_from_boolean(opt);
     245             :             }
     246             :         }
     247        5316 :         else if (strcmp(opt->defname, "process_main") == 0)
     248         154 :             process_main = defGetBoolean(opt);
     249        5162 :         else if (strcmp(opt->defname, "process_toast") == 0)
     250         160 :             process_toast = defGetBoolean(opt);
     251        5002 :         else if (strcmp(opt->defname, "truncate") == 0)
     252         148 :             params.truncate = get_vacoptval_from_boolean(opt);
     253        4854 :         else if (strcmp(opt->defname, "parallel") == 0)
     254             :         {
     255         338 :             if (opt->arg == NULL)
     256             :             {
     257           6 :                 ereport(ERROR,
     258             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     259             :                          errmsg("parallel option requires a value between 0 and %d",
     260             :                                 MAX_PARALLEL_WORKER_LIMIT),
     261             :                          parser_errposition(pstate, opt->location)));
     262             :             }
     263             :             else
     264             :             {
     265             :                 int         nworkers;
     266             : 
     267         332 :                 nworkers = defGetInt32(opt);
     268         332 :                 if (nworkers < 0 || nworkers > MAX_PARALLEL_WORKER_LIMIT)
     269           6 :                     ereport(ERROR,
     270             :                             (errcode(ERRCODE_SYNTAX_ERROR),
     271             :                              errmsg("parallel workers for vacuum must be between 0 and %d",
     272             :                                     MAX_PARALLEL_WORKER_LIMIT),
     273             :                              parser_errposition(pstate, opt->location)));
     274             : 
     275             :                 /*
     276             :                  * Disable parallel vacuum, if user has specified parallel
     277             :                  * degree as zero.
     278             :                  */
     279         326 :                 if (nworkers == 0)
     280         154 :                     params.nworkers = -1;
     281             :                 else
     282         172 :                     params.nworkers = nworkers;
     283             :             }
     284             :         }
     285        4516 :         else if (strcmp(opt->defname, "skip_database_stats") == 0)
     286        4398 :             skip_database_stats = defGetBoolean(opt);
     287         118 :         else if (strcmp(opt->defname, "only_database_stats") == 0)
     288         118 :             only_database_stats = defGetBoolean(opt);
     289             :         else
     290           0 :             ereport(ERROR,
     291             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     292             :                      errmsg("unrecognized VACUUM option \"%s\"", opt->defname),
     293             :                      parser_errposition(pstate, opt->location)));
     294             :     }
     295             : 
     296             :     /* Set vacuum options */
     297       10698 :     params.options =
     298       10698 :         (vacstmt->is_vacuumcmd ? VACOPT_VACUUM : VACOPT_ANALYZE) |
     299       10698 :         (verbose ? VACOPT_VERBOSE : 0) |
     300       10698 :         (skip_locked ? VACOPT_SKIP_LOCKED : 0) |
     301       10698 :         (analyze ? VACOPT_ANALYZE : 0) |
     302       10698 :         (freeze ? VACOPT_FREEZE : 0) |
     303       10698 :         (full ? VACOPT_FULL : 0) |
     304       10698 :         (disable_page_skipping ? VACOPT_DISABLE_PAGE_SKIPPING : 0) |
     305       10698 :         (process_main ? VACOPT_PROCESS_MAIN : 0) |
     306       10698 :         (process_toast ? VACOPT_PROCESS_TOAST : 0) |
     307       10698 :         (skip_database_stats ? VACOPT_SKIP_DATABASE_STATS : 0) |
     308       10698 :         (only_database_stats ? VACOPT_ONLY_DATABASE_STATS : 0);
     309             : 
     310             :     /* sanity checks on options */
     311             :     Assert(params.options & (VACOPT_VACUUM | VACOPT_ANALYZE));
     312             :     Assert((params.options & VACOPT_VACUUM) ||
     313             :            !(params.options & (VACOPT_FULL | VACOPT_FREEZE)));
     314             : 
     315       10698 :     if ((params.options & VACOPT_FULL) && params.nworkers > 0)
     316           6 :         ereport(ERROR,
     317             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     318             :                  errmsg("VACUUM FULL cannot be performed in parallel")));
     319             : 
     320             :     /*
     321             :      * BUFFER_USAGE_LIMIT does nothing for VACUUM (FULL) so just raise an
     322             :      * ERROR for that case.  VACUUM (FULL, ANALYZE) does make use of it, so
     323             :      * we'll permit that.
     324             :      */
     325       10692 :     if (ring_size != -1 && (params.options & VACOPT_FULL) &&
     326           6 :         !(params.options & VACOPT_ANALYZE))
     327           6 :         ereport(ERROR,
     328             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     329             :                  errmsg("BUFFER_USAGE_LIMIT cannot be specified for VACUUM FULL")));
     330             : 
     331             :     /*
     332             :      * Make sure VACOPT_ANALYZE is specified if any column lists are present.
     333             :      */
     334       10686 :     if (!(params.options & VACOPT_ANALYZE))
     335             :     {
     336        9324 :         foreach(lc, vacstmt->rels)
     337             :         {
     338        4576 :             VacuumRelation *vrel = lfirst_node(VacuumRelation, lc);
     339             : 
     340        4576 :             if (vrel->va_cols != NIL)
     341           6 :                 ereport(ERROR,
     342             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     343             :                          errmsg("ANALYZE option must be specified when a column list is provided")));
     344             :         }
     345             :     }
     346             : 
     347             : 
     348             :     /*
     349             :      * Sanity check DISABLE_PAGE_SKIPPING option.
     350             :      */
     351       10680 :     if ((params.options & VACOPT_FULL) != 0 &&
     352         346 :         (params.options & VACOPT_DISABLE_PAGE_SKIPPING) != 0)
     353           0 :         ereport(ERROR,
     354             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     355             :                  errmsg("VACUUM option DISABLE_PAGE_SKIPPING cannot be used with FULL")));
     356             : 
     357             :     /* sanity check for PROCESS_TOAST */
     358       10680 :     if ((params.options & VACOPT_FULL) != 0 &&
     359         346 :         (params.options & VACOPT_PROCESS_TOAST) == 0)
     360           6 :         ereport(ERROR,
     361             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     362             :                  errmsg("PROCESS_TOAST required with VACUUM FULL")));
     363             : 
     364             :     /* sanity check for ONLY_DATABASE_STATS */
     365       10674 :     if (params.options & VACOPT_ONLY_DATABASE_STATS)
     366             :     {
     367             :         Assert(params.options & VACOPT_VACUUM);
     368         118 :         if (vacstmt->rels != NIL)
     369           6 :             ereport(ERROR,
     370             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     371             :                      errmsg("ONLY_DATABASE_STATS cannot be specified with a list of tables")));
     372             :         /* don't require people to turn off PROCESS_TOAST/MAIN explicitly */
     373         112 :         if (params.options & ~(VACOPT_VACUUM |
     374             :                                VACOPT_VERBOSE |
     375             :                                VACOPT_PROCESS_MAIN |
     376             :                                VACOPT_PROCESS_TOAST |
     377             :                                VACOPT_ONLY_DATABASE_STATS))
     378           0 :             ereport(ERROR,
     379             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     380             :                      errmsg("ONLY_DATABASE_STATS cannot be specified with other VACUUM options")));
     381             :     }
     382             : 
     383             :     /*
     384             :      * All freeze ages are zero if the FREEZE option is given; otherwise pass
     385             :      * them as -1 which means to use the default values.
     386             :      */
     387       10668 :     if (params.options & VACOPT_FREEZE)
     388             :     {
     389        1162 :         params.freeze_min_age = 0;
     390        1162 :         params.freeze_table_age = 0;
     391        1162 :         params.multixact_freeze_min_age = 0;
     392        1162 :         params.multixact_freeze_table_age = 0;
     393             :     }
     394             :     else
     395             :     {
     396        9506 :         params.freeze_min_age = -1;
     397        9506 :         params.freeze_table_age = -1;
     398        9506 :         params.multixact_freeze_min_age = -1;
     399        9506 :         params.multixact_freeze_table_age = -1;
     400             :     }
     401             : 
     402             :     /* user-invoked vacuum is never "for wraparound" */
     403       10668 :     params.is_wraparound = false;
     404             : 
     405             :     /* user-invoked vacuum uses VACOPT_VERBOSE instead of log_min_duration */
     406       10668 :     params.log_min_duration = -1;
     407             : 
     408             :     /*
     409             :      * Create special memory context for cross-transaction storage.
     410             :      *
     411             :      * Since it is a child of PortalContext, it will go away eventually even
     412             :      * if we suffer an error; there's no need for special abort cleanup logic.
     413             :      */
     414       10668 :     vac_context = AllocSetContextCreate(PortalContext,
     415             :                                         "Vacuum",
     416             :                                         ALLOCSET_DEFAULT_SIZES);
     417             : 
     418             :     /*
     419             :      * Make a buffer strategy object in the cross-transaction memory context.
     420             :      * We needn't bother making this for VACUUM (FULL) or VACUUM
     421             :      * (ONLY_DATABASE_STATS) as they'll not make use of it.  VACUUM (FULL,
     422             :      * ANALYZE) is possible, so we'd better ensure that we make a strategy
     423             :      * when we see ANALYZE.
     424             :      */
     425       10668 :     if ((params.options & (VACOPT_ONLY_DATABASE_STATS |
     426         452 :                            VACOPT_FULL)) == 0 ||
     427         452 :         (params.options & VACOPT_ANALYZE) != 0)
     428             :     {
     429             : 
     430       10222 :         MemoryContext old_context = MemoryContextSwitchTo(vac_context);
     431             : 
     432             :         Assert(ring_size >= -1);
     433             : 
     434             :         /*
     435             :          * If BUFFER_USAGE_LIMIT was specified by the VACUUM or ANALYZE
     436             :          * command, it overrides the value of VacuumBufferUsageLimit.  Either
     437             :          * value may be 0, in which case GetAccessStrategyWithSize() will
     438             :          * return NULL, effectively allowing full use of shared buffers.
     439             :          */
     440       10222 :         if (ring_size == -1)
     441       10192 :             ring_size = VacuumBufferUsageLimit;
     442             : 
     443       10222 :         bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, ring_size);
     444             : 
     445       10222 :         MemoryContextSwitchTo(old_context);
     446             :     }
     447             : 
     448             :     /* Now go through the common routine */
     449       10668 :     vacuum(vacstmt->rels, &params, bstrategy, vac_context, isTopLevel);
     450             : 
     451             :     /* Finally, clean up the vacuum memory context */
     452       10542 :     MemoryContextDelete(vac_context);
     453       10542 : }
     454             : 
     455             : /*
     456             :  * Internal entry point for autovacuum and the VACUUM / ANALYZE commands.
     457             :  *
     458             :  * relations, if not NIL, is a list of VacuumRelation to process; otherwise,
     459             :  * we process all relevant tables in the database.  For each VacuumRelation,
     460             :  * if a valid OID is supplied, the table with that OID is what to process;
     461             :  * otherwise, the VacuumRelation's RangeVar indicates what to process.
     462             :  *
     463             :  * params contains a set of parameters that can be used to customize the
     464             :  * behavior.
     465             :  *
     466             :  * bstrategy may be passed in as NULL when the caller does not want to
     467             :  * restrict the number of shared_buffers that VACUUM / ANALYZE can use,
     468             :  * otherwise, the caller must build a BufferAccessStrategy with the number of
     469             :  * shared_buffers that VACUUM / ANALYZE should try to limit themselves to
     470             :  * using.
     471             :  *
     472             :  * isTopLevel should be passed down from ProcessUtility.
     473             :  *
     474             :  * It is the caller's responsibility that all parameters are allocated in a
     475             :  * memory context that will not disappear at transaction commit.
     476             :  */
     477             : void
     478      104490 : vacuum(List *relations, VacuumParams *params, BufferAccessStrategy bstrategy,
     479             :        MemoryContext vac_context, bool isTopLevel)
     480             : {
     481             :     static bool in_vacuum = false;
     482             : 
     483             :     const char *stmttype;
     484             :     volatile bool in_outer_xact,
     485             :                 use_own_xacts;
     486             : 
     487             :     Assert(params != NULL);
     488             : 
     489      104490 :     stmttype = (params->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
     490             : 
     491             :     /*
     492             :      * We cannot run VACUUM inside a user transaction block; if we were inside
     493             :      * a transaction, then our commit- and start-transaction-command calls
     494             :      * would not have the intended effect!  There are numerous other subtle
     495             :      * dependencies on this, too.
     496             :      *
     497             :      * ANALYZE (without VACUUM) can run either way.
     498             :      */
     499      104490 :     if (params->options & VACOPT_VACUUM)
     500             :     {
     501       99754 :         PreventInTransactionBlock(isTopLevel, stmttype);
     502       99740 :         in_outer_xact = false;
     503             :     }
     504             :     else
     505        4736 :         in_outer_xact = IsInTransactionBlock(isTopLevel);
     506             : 
     507             :     /*
     508             :      * Check for and disallow recursive calls.  This could happen when VACUUM
     509             :      * FULL or ANALYZE calls a hostile index expression that itself calls
     510             :      * ANALYZE.
     511             :      */
     512      104476 :     if (in_vacuum)
     513          12 :         ereport(ERROR,
     514             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     515             :                  errmsg("%s cannot be executed from VACUUM or ANALYZE",
     516             :                         stmttype)));
     517             : 
     518             :     /*
     519             :      * Build list of relation(s) to process, putting any new data in
     520             :      * vac_context for safekeeping.
     521             :      */
     522      104464 :     if (params->options & VACOPT_ONLY_DATABASE_STATS)
     523             :     {
     524             :         /* We don't process any tables in this case */
     525             :         Assert(relations == NIL);
     526             :     }
     527      104352 :     else if (relations != NIL)
     528             :     {
     529      104160 :         List       *newrels = NIL;
     530             :         ListCell   *lc;
     531             : 
     532      208408 :         foreach(lc, relations)
     533             :         {
     534      104284 :             VacuumRelation *vrel = lfirst_node(VacuumRelation, lc);
     535             :             List       *sublist;
     536             :             MemoryContext old_context;
     537             : 
     538      104284 :             sublist = expand_vacuum_rel(vrel, vac_context, params->options);
     539      104248 :             old_context = MemoryContextSwitchTo(vac_context);
     540      104248 :             newrels = list_concat(newrels, sublist);
     541      104248 :             MemoryContextSwitchTo(old_context);
     542             :         }
     543      104124 :         relations = newrels;
     544             :     }
     545             :     else
     546         192 :         relations = get_all_vacuum_rels(vac_context, params->options);
     547             : 
     548             :     /*
     549             :      * Decide whether we need to start/commit our own transactions.
     550             :      *
     551             :      * For VACUUM (with or without ANALYZE): always do so, so that we can
     552             :      * release locks as soon as possible.  (We could possibly use the outer
     553             :      * transaction for a one-table VACUUM, but handling TOAST tables would be
     554             :      * problematic.)
     555             :      *
     556             :      * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
     557             :      * start/commit our own transactions.  Also, there's no need to do so if
     558             :      * only processing one relation.  For multiple relations when not within a
     559             :      * transaction block, and also in an autovacuum worker, use own
     560             :      * transactions so we can release locks sooner.
     561             :      */
     562      104428 :     if (params->options & VACOPT_VACUUM)
     563       99728 :         use_own_xacts = true;
     564             :     else
     565             :     {
     566             :         Assert(params->options & VACOPT_ANALYZE);
     567        4700 :         if (AmAutoVacuumWorkerProcess())
     568         180 :             use_own_xacts = true;
     569        4520 :         else if (in_outer_xact)
     570         238 :             use_own_xacts = false;
     571        4282 :         else if (list_length(relations) > 1)
     572         722 :             use_own_xacts = true;
     573             :         else
     574        3560 :             use_own_xacts = false;
     575             :     }
     576             : 
     577             :     /*
     578             :      * vacuum_rel expects to be entered with no transaction active; it will
     579             :      * start and commit its own transaction.  But we are called by an SQL
     580             :      * command, and so we are executing inside a transaction already. We
     581             :      * commit the transaction started in PostgresMain() here, and start
     582             :      * another one before exiting to match the commit waiting for us back in
     583             :      * PostgresMain().
     584             :      */
     585      104428 :     if (use_own_xacts)
     586             :     {
     587             :         Assert(!in_outer_xact);
     588             : 
     589             :         /* ActiveSnapshot is not set by autovacuum */
     590      100630 :         if (ActiveSnapshotSet())
     591        6808 :             PopActiveSnapshot();
     592             : 
     593             :         /* matches the StartTransaction in PostgresMain() */
     594      100630 :         CommitTransactionCommand();
     595             :     }
     596             : 
     597             :     /* Turn vacuum cost accounting on or off, and set/clear in_vacuum */
     598      104428 :     PG_TRY();
     599             :     {
     600             :         ListCell   *cur;
     601             : 
     602      104428 :         in_vacuum = true;
     603      104428 :         VacuumFailsafeActive = false;
     604      104428 :         VacuumUpdateCosts();
     605      104428 :         VacuumCostBalance = 0;
     606      104428 :         VacuumCostBalanceLocal = 0;
     607      104428 :         VacuumSharedCostBalance = NULL;
     608      104428 :         VacuumActiveNWorkers = NULL;
     609             : 
     610             :         /*
     611             :          * Loop to process each selected relation.
     612             :          */
     613      224336 :         foreach(cur, relations)
     614             :         {
     615      119974 :             VacuumRelation *vrel = lfirst_node(VacuumRelation, cur);
     616             : 
     617      119974 :             if (params->options & VACOPT_VACUUM)
     618             :             {
     619      107804 :                 if (!vacuum_rel(vrel->oid, vrel->relation, params, bstrategy))
     620         100 :                     continue;
     621             :             }
     622             : 
     623      119868 :             if (params->options & VACOPT_ANALYZE)
     624             :             {
     625             :                 /*
     626             :                  * If using separate xacts, start one for analyze. Otherwise,
     627             :                  * we can use the outer transaction.
     628             :                  */
     629       13784 :                 if (use_own_xacts)
     630             :                 {
     631       10036 :                     StartTransactionCommand();
     632             :                     /* functions in indexes may want a snapshot set */
     633       10036 :                     PushActiveSnapshot(GetTransactionSnapshot());
     634             :                 }
     635             : 
     636       13784 :                 analyze_rel(vrel->oid, vrel->relation, params,
     637             :                             vrel->va_cols, in_outer_xact, bstrategy);
     638             : 
     639       13724 :                 if (use_own_xacts)
     640             :                 {
     641        9996 :                     PopActiveSnapshot();
     642        9996 :                     CommitTransactionCommand();
     643             :                 }
     644             :                 else
     645             :                 {
     646             :                     /*
     647             :                      * If we're not using separate xacts, better separate the
     648             :                      * ANALYZE actions with CCIs.  This avoids trouble if user
     649             :                      * says "ANALYZE t, t".
     650             :                      */
     651        3728 :                     CommandCounterIncrement();
     652             :                 }
     653             :             }
     654             : 
     655             :             /*
     656             :              * Ensure VacuumFailsafeActive has been reset before vacuuming the
     657             :              * next relation.
     658             :              */
     659      119808 :             VacuumFailsafeActive = false;
     660             :         }
     661             :     }
     662          64 :     PG_FINALLY();
     663             :     {
     664      104426 :         in_vacuum = false;
     665      104426 :         VacuumCostActive = false;
     666      104426 :         VacuumFailsafeActive = false;
     667      104426 :         VacuumCostBalance = 0;
     668             :     }
     669      104426 :     PG_END_TRY();
     670             : 
     671             :     /*
     672             :      * Finish up processing.
     673             :      */
     674      104362 :     if (use_own_xacts)
     675             :     {
     676             :         /* here, we are not in a transaction */
     677             : 
     678             :         /*
     679             :          * This matches the CommitTransaction waiting for us in
     680             :          * PostgresMain().
     681             :          */
     682      100584 :         StartTransactionCommand();
     683             :     }
     684             : 
     685      104362 :     if ((params->options & VACOPT_VACUUM) &&
     686       99694 :         !(params->options & VACOPT_SKIP_DATABASE_STATS))
     687             :     {
     688             :         /*
     689             :          * Update pg_database.datfrozenxid, and truncate pg_xact if possible.
     690             :          */
     691        1658 :         vac_update_datfrozenxid();
     692             :     }
     693             : 
     694      104362 : }
     695             : 
     696             : /*
     697             :  * Check if the current user has privileges to vacuum or analyze the relation.
     698             :  * If not, issue a WARNING log message and return false to let the caller
     699             :  * decide what to do with this relation.  This routine is used to decide if a
     700             :  * relation can be processed for VACUUM or ANALYZE.
     701             :  */
     702             : bool
     703      153360 : vacuum_is_permitted_for_relation(Oid relid, Form_pg_class reltuple,
     704             :                                  bits32 options)
     705             : {
     706             :     char       *relname;
     707             : 
     708             :     Assert((options & (VACOPT_VACUUM | VACOPT_ANALYZE)) != 0);
     709             : 
     710             :     /*----------
     711             :      * A role has privileges to vacuum or analyze the relation if any of the
     712             :      * following are true:
     713             :      *   - the role owns the current database and the relation is not shared
     714             :      *   - the role has the MAINTAIN privilege on the relation
     715             :      *----------
     716             :      */
     717      153360 :     if ((object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()) &&
     718      177642 :          !reltuple->relisshared) ||
     719       25056 :         pg_class_aclcheck(relid, GetUserId(), ACL_MAINTAIN) == ACLCHECK_OK)
     720      153020 :         return true;
     721             : 
     722         340 :     relname = NameStr(reltuple->relname);
     723             : 
     724         340 :     if ((options & VACOPT_VACUUM) != 0)
     725             :     {
     726         224 :         ereport(WARNING,
     727             :                 (errmsg("permission denied to vacuum \"%s\", skipping it",
     728             :                         relname)));
     729             : 
     730             :         /*
     731             :          * For VACUUM ANALYZE, both logs could show up, but just generate
     732             :          * information for VACUUM as that would be the first one to be
     733             :          * processed.
     734             :          */
     735         224 :         return false;
     736             :     }
     737             : 
     738         116 :     if ((options & VACOPT_ANALYZE) != 0)
     739         116 :         ereport(WARNING,
     740             :                 (errmsg("permission denied to analyze \"%s\", skipping it",
     741             :                         relname)));
     742             : 
     743         116 :     return false;
     744             : }
     745             : 
     746             : 
     747             : /*
     748             :  * vacuum_open_relation
     749             :  *
     750             :  * This routine is used for attempting to open and lock a relation which
     751             :  * is going to be vacuumed or analyzed.  If the relation cannot be opened
     752             :  * or locked, a log is emitted if possible.
     753             :  */
     754             : Relation
     755      128996 : vacuum_open_relation(Oid relid, RangeVar *relation, bits32 options,
     756             :                      bool verbose, LOCKMODE lmode)
     757             : {
     758             :     Relation    rel;
     759      128996 :     bool        rel_lock = true;
     760             :     int         elevel;
     761             : 
     762             :     Assert((options & (VACOPT_VACUUM | VACOPT_ANALYZE)) != 0);
     763             : 
     764             :     /*
     765             :      * Open the relation and get the appropriate lock on it.
     766             :      *
     767             :      * There's a race condition here: the relation may have gone away since
     768             :      * the last time we saw it.  If so, we don't need to vacuum or analyze it.
     769             :      *
     770             :      * If we've been asked not to wait for the relation lock, acquire it first
     771             :      * in non-blocking mode, before calling try_relation_open().
     772             :      */
     773      128996 :     if (!(options & VACOPT_SKIP_LOCKED))
     774      128066 :         rel = try_relation_open(relid, lmode);
     775         930 :     else if (ConditionalLockRelationOid(relid, lmode))
     776         910 :         rel = try_relation_open(relid, NoLock);
     777             :     else
     778             :     {
     779          20 :         rel = NULL;
     780          20 :         rel_lock = false;
     781             :     }
     782             : 
     783             :     /* if relation is opened, leave */
     784      128996 :     if (rel)
     785      128964 :         return rel;
     786             : 
     787             :     /*
     788             :      * Relation could not be opened, hence generate if possible a log
     789             :      * informing on the situation.
     790             :      *
     791             :      * If the RangeVar is not defined, we do not have enough information to
     792             :      * provide a meaningful log statement.  Chances are that the caller has
     793             :      * intentionally not provided this information so that this logging is
     794             :      * skipped, anyway.
     795             :      */
     796          32 :     if (relation == NULL)
     797          18 :         return NULL;
     798             : 
     799             :     /*
     800             :      * Determine the log level.
     801             :      *
     802             :      * For manual VACUUM or ANALYZE, we emit a WARNING to match the log
     803             :      * statements in the permission checks; otherwise, only log if the caller
     804             :      * so requested.
     805             :      */
     806          14 :     if (!AmAutoVacuumWorkerProcess())
     807          14 :         elevel = WARNING;
     808           0 :     else if (verbose)
     809           0 :         elevel = LOG;
     810             :     else
     811           0 :         return NULL;
     812             : 
     813          14 :     if ((options & VACOPT_VACUUM) != 0)
     814             :     {
     815          10 :         if (!rel_lock)
     816           6 :             ereport(elevel,
     817             :                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
     818             :                      errmsg("skipping vacuum of \"%s\" --- lock not available",
     819             :                             relation->relname)));
     820             :         else
     821           4 :             ereport(elevel,
     822             :                     (errcode(ERRCODE_UNDEFINED_TABLE),
     823             :                      errmsg("skipping vacuum of \"%s\" --- relation no longer exists",
     824             :                             relation->relname)));
     825             : 
     826             :         /*
     827             :          * For VACUUM ANALYZE, both logs could show up, but just generate
     828             :          * information for VACUUM as that would be the first one to be
     829             :          * processed.
     830             :          */
     831          10 :         return NULL;
     832             :     }
     833             : 
     834           4 :     if ((options & VACOPT_ANALYZE) != 0)
     835             :     {
     836           4 :         if (!rel_lock)
     837           2 :             ereport(elevel,
     838             :                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
     839             :                      errmsg("skipping analyze of \"%s\" --- lock not available",
     840             :                             relation->relname)));
     841             :         else
     842           2 :             ereport(elevel,
     843             :                     (errcode(ERRCODE_UNDEFINED_TABLE),
     844             :                      errmsg("skipping analyze of \"%s\" --- relation no longer exists",
     845             :                             relation->relname)));
     846             :     }
     847             : 
     848           4 :     return NULL;
     849             : }
     850             : 
     851             : 
     852             : /*
     853             :  * Given a VacuumRelation, fill in the table OID if it wasn't specified,
     854             :  * and optionally add VacuumRelations for partitions or inheritance children.
     855             :  *
     856             :  * If a VacuumRelation does not have an OID supplied and is a partitioned
     857             :  * table, an extra entry will be added to the output for each partition.
     858             :  * Presently, only autovacuum supplies OIDs when calling vacuum(), and
     859             :  * it does not want us to expand partitioned tables.
     860             :  *
     861             :  * We take care not to modify the input data structure, but instead build
     862             :  * new VacuumRelation(s) to return.  (But note that they will reference
     863             :  * unmodified parts of the input, eg column lists.)  New data structures
     864             :  * are made in vac_context.
     865             :  */
     866             : static List *
     867      104284 : expand_vacuum_rel(VacuumRelation *vrel, MemoryContext vac_context,
     868             :                   int options)
     869             : {
     870      104284 :     List       *vacrels = NIL;
     871             :     MemoryContext oldcontext;
     872             : 
     873             :     /* If caller supplied OID, there's nothing we need do here. */
     874      104284 :     if (OidIsValid(vrel->oid))
     875             :     {
     876       93822 :         oldcontext = MemoryContextSwitchTo(vac_context);
     877       93822 :         vacrels = lappend(vacrels, vrel);
     878       93822 :         MemoryContextSwitchTo(oldcontext);
     879             :     }
     880             :     else
     881             :     {
     882             :         /*
     883             :          * Process a specific relation, and possibly partitions or child
     884             :          * tables thereof.
     885             :          */
     886             :         Oid         relid;
     887             :         HeapTuple   tuple;
     888             :         Form_pg_class classForm;
     889             :         bool        include_children;
     890             :         bool        is_partitioned_table;
     891             :         int         rvr_opts;
     892             : 
     893             :         /*
     894             :          * Since autovacuum workers supply OIDs when calling vacuum(), no
     895             :          * autovacuum worker should reach this code.
     896             :          */
     897             :         Assert(!AmAutoVacuumWorkerProcess());
     898             : 
     899             :         /*
     900             :          * We transiently take AccessShareLock to protect the syscache lookup
     901             :          * below, as well as find_all_inheritors's expectation that the caller
     902             :          * holds some lock on the starting relation.
     903             :          */
     904       10462 :         rvr_opts = (options & VACOPT_SKIP_LOCKED) ? RVR_SKIP_LOCKED : 0;
     905       10462 :         relid = RangeVarGetRelidExtended(vrel->relation,
     906             :                                          AccessShareLock,
     907             :                                          rvr_opts,
     908             :                                          NULL, NULL);
     909             : 
     910             :         /*
     911             :          * If the lock is unavailable, emit the same log statement that
     912             :          * vacuum_rel() and analyze_rel() would.
     913             :          */
     914       10426 :         if (!OidIsValid(relid))
     915             :         {
     916           8 :             if (options & VACOPT_VACUUM)
     917           6 :                 ereport(WARNING,
     918             :                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
     919             :                          errmsg("skipping vacuum of \"%s\" --- lock not available",
     920             :                                 vrel->relation->relname)));
     921             :             else
     922           2 :                 ereport(WARNING,
     923             :                         (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
     924             :                          errmsg("skipping analyze of \"%s\" --- lock not available",
     925             :                                 vrel->relation->relname)));
     926           8 :             return vacrels;
     927             :         }
     928             : 
     929             :         /*
     930             :          * To check whether the relation is a partitioned table and its
     931             :          * ownership, fetch its syscache entry.
     932             :          */
     933       10418 :         tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
     934       10418 :         if (!HeapTupleIsValid(tuple))
     935           0 :             elog(ERROR, "cache lookup failed for relation %u", relid);
     936       10418 :         classForm = (Form_pg_class) GETSTRUCT(tuple);
     937             : 
     938             :         /*
     939             :          * Make a returnable VacuumRelation for this rel if the user has the
     940             :          * required privileges.
     941             :          */
     942       10418 :         if (vacuum_is_permitted_for_relation(relid, classForm, options))
     943             :         {
     944       10186 :             oldcontext = MemoryContextSwitchTo(vac_context);
     945       10186 :             vacrels = lappend(vacrels, makeVacuumRelation(vrel->relation,
     946             :                                                           relid,
     947             :                                                           vrel->va_cols));
     948       10186 :             MemoryContextSwitchTo(oldcontext);
     949             :         }
     950             : 
     951             :         /*
     952             :          * Vacuuming a partitioned table with ONLY will not do anything since
     953             :          * the partitioned table itself is empty.  Issue a warning if the user
     954             :          * requests this.
     955             :          */
     956       10418 :         include_children = vrel->relation->inh;
     957       10418 :         is_partitioned_table = (classForm->relkind == RELKIND_PARTITIONED_TABLE);
     958       10418 :         if ((options & VACOPT_VACUUM) && is_partitioned_table && !include_children)
     959           6 :             ereport(WARNING,
     960             :                     (errmsg("VACUUM ONLY of partitioned table \"%s\" has no effect",
     961             :                             vrel->relation->relname)));
     962             : 
     963       10418 :         ReleaseSysCache(tuple);
     964             : 
     965             :         /*
     966             :          * Unless the user has specified ONLY, make relation list entries for
     967             :          * its partitions or inheritance child tables.  Note that the list
     968             :          * returned by find_all_inheritors() includes the passed-in OID, so we
     969             :          * have to skip that.  There's no point in taking locks on the
     970             :          * individual partitions or child tables yet, and doing so would just
     971             :          * add unnecessary deadlock risk.  For this last reason, we do not yet
     972             :          * check the ownership of the partitions/tables, which get added to
     973             :          * the list to process.  Ownership will be checked later on anyway.
     974             :          */
     975       10418 :         if (include_children)
     976             :         {
     977       10388 :             List       *part_oids = find_all_inheritors(relid, NoLock, NULL);
     978             :             ListCell   *part_lc;
     979             : 
     980       22812 :             foreach(part_lc, part_oids)
     981             :             {
     982       12424 :                 Oid         part_oid = lfirst_oid(part_lc);
     983             : 
     984       12424 :                 if (part_oid == relid)
     985       10388 :                     continue;   /* ignore original table */
     986             : 
     987             :                 /*
     988             :                  * We omit a RangeVar since it wouldn't be appropriate to
     989             :                  * complain about failure to open one of these relations
     990             :                  * later.
     991             :                  */
     992        2036 :                 oldcontext = MemoryContextSwitchTo(vac_context);
     993        2036 :                 vacrels = lappend(vacrels, makeVacuumRelation(NULL,
     994             :                                                               part_oid,
     995             :                                                               vrel->va_cols));
     996        2036 :                 MemoryContextSwitchTo(oldcontext);
     997             :             }
     998             :         }
     999             : 
    1000             :         /*
    1001             :          * Release lock again.  This means that by the time we actually try to
    1002             :          * process the table, it might be gone or renamed.  In the former case
    1003             :          * we'll silently ignore it; in the latter case we'll process it
    1004             :          * anyway, but we must beware that the RangeVar doesn't necessarily
    1005             :          * identify it anymore.  This isn't ideal, perhaps, but there's little
    1006             :          * practical alternative, since we're typically going to commit this
    1007             :          * transaction and begin a new one between now and then.  Moreover,
    1008             :          * holding locks on multiple relations would create significant risk
    1009             :          * of deadlock.
    1010             :          */
    1011       10418 :         UnlockRelationOid(relid, AccessShareLock);
    1012             :     }
    1013             : 
    1014      104240 :     return vacrels;
    1015             : }
    1016             : 
    1017             : /*
    1018             :  * Construct a list of VacuumRelations for all vacuumable rels in
    1019             :  * the current database.  The list is built in vac_context.
    1020             :  */
    1021             : static List *
    1022         192 : get_all_vacuum_rels(MemoryContext vac_context, int options)
    1023             : {
    1024         192 :     List       *vacrels = NIL;
    1025             :     Relation    pgclass;
    1026             :     TableScanDesc scan;
    1027             :     HeapTuple   tuple;
    1028             : 
    1029         192 :     pgclass = table_open(RelationRelationId, AccessShareLock);
    1030             : 
    1031         192 :     scan = table_beginscan_catalog(pgclass, 0, NULL);
    1032             : 
    1033       82014 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
    1034             :     {
    1035       81822 :         Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
    1036             :         MemoryContext oldcontext;
    1037       81822 :         Oid         relid = classForm->oid;
    1038             : 
    1039             :         /*
    1040             :          * We include partitioned tables here; depending on which operation is
    1041             :          * to be performed, caller will decide whether to process or ignore
    1042             :          * them.
    1043             :          */
    1044       81822 :         if (classForm->relkind != RELKIND_RELATION &&
    1045       67912 :             classForm->relkind != RELKIND_MATVIEW &&
    1046       67906 :             classForm->relkind != RELKIND_PARTITIONED_TABLE)
    1047       67844 :             continue;
    1048             : 
    1049             :         /* check permissions of relation */
    1050       13978 :         if (!vacuum_is_permitted_for_relation(relid, classForm, options))
    1051           0 :             continue;
    1052             : 
    1053             :         /*
    1054             :          * Build VacuumRelation(s) specifying the table OIDs to be processed.
    1055             :          * We omit a RangeVar since it wouldn't be appropriate to complain
    1056             :          * about failure to open one of these relations later.
    1057             :          */
    1058       13978 :         oldcontext = MemoryContextSwitchTo(vac_context);
    1059       13978 :         vacrels = lappend(vacrels, makeVacuumRelation(NULL,
    1060             :                                                       relid,
    1061             :                                                       NIL));
    1062       13978 :         MemoryContextSwitchTo(oldcontext);
    1063             :     }
    1064             : 
    1065         192 :     table_endscan(scan);
    1066         192 :     table_close(pgclass, AccessShareLock);
    1067             : 
    1068         192 :     return vacrels;
    1069             : }
    1070             : 
    1071             : /*
    1072             :  * vacuum_get_cutoffs() -- compute OldestXmin and freeze cutoff points
    1073             :  *
    1074             :  * The target relation and VACUUM parameters are our inputs.
    1075             :  *
    1076             :  * Output parameters are the cutoffs that VACUUM caller should use.
    1077             :  *
    1078             :  * Return value indicates if vacuumlazy.c caller should make its VACUUM
    1079             :  * operation aggressive.  An aggressive VACUUM must advance relfrozenxid up to
    1080             :  * FreezeLimit (at a minimum), and relminmxid up to MultiXactCutoff (at a
    1081             :  * minimum).
    1082             :  */
    1083             : bool
    1084      114968 : vacuum_get_cutoffs(Relation rel, const VacuumParams *params,
    1085             :                    struct VacuumCutoffs *cutoffs)
    1086             : {
    1087             :     int         freeze_min_age,
    1088             :                 multixact_freeze_min_age,
    1089             :                 freeze_table_age,
    1090             :                 multixact_freeze_table_age,
    1091             :                 effective_multixact_freeze_max_age;
    1092             :     TransactionId nextXID,
    1093             :                 safeOldestXmin,
    1094             :                 aggressiveXIDCutoff;
    1095             :     MultiXactId nextMXID,
    1096             :                 safeOldestMxact,
    1097             :                 aggressiveMXIDCutoff;
    1098             : 
    1099             :     /* Use mutable copies of freeze age parameters */
    1100      114968 :     freeze_min_age = params->freeze_min_age;
    1101      114968 :     multixact_freeze_min_age = params->multixact_freeze_min_age;
    1102      114968 :     freeze_table_age = params->freeze_table_age;
    1103      114968 :     multixact_freeze_table_age = params->multixact_freeze_table_age;
    1104             : 
    1105             :     /* Set pg_class fields in cutoffs */
    1106      114968 :     cutoffs->relfrozenxid = rel->rd_rel->relfrozenxid;
    1107      114968 :     cutoffs->relminmxid = rel->rd_rel->relminmxid;
    1108             : 
    1109             :     /*
    1110             :      * Acquire OldestXmin.
    1111             :      *
    1112             :      * We can always ignore processes running lazy vacuum.  This is because we
    1113             :      * use these values only for deciding which tuples we must keep in the
    1114             :      * tables.  Since lazy vacuum doesn't write its XID anywhere (usually no
    1115             :      * XID assigned), it's safe to ignore it.  In theory it could be
    1116             :      * problematic to ignore lazy vacuums in a full vacuum, but keep in mind
    1117             :      * that only one vacuum process can be working on a particular table at
    1118             :      * any time, and that each vacuum is always an independent transaction.
    1119             :      */
    1120      114968 :     cutoffs->OldestXmin = GetOldestNonRemovableTransactionId(rel);
    1121             : 
    1122             :     Assert(TransactionIdIsNormal(cutoffs->OldestXmin));
    1123             : 
    1124             :     /* Acquire OldestMxact */
    1125      114968 :     cutoffs->OldestMxact = GetOldestMultiXactId();
    1126             :     Assert(MultiXactIdIsValid(cutoffs->OldestMxact));
    1127             : 
    1128             :     /* Acquire next XID/next MXID values used to apply age-based settings */
    1129      114968 :     nextXID = ReadNextTransactionId();
    1130      114968 :     nextMXID = ReadNextMultiXactId();
    1131             : 
    1132             :     /*
    1133             :      * Also compute the multixact age for which freezing is urgent.  This is
    1134             :      * normally autovacuum_multixact_freeze_max_age, but may be less if we are
    1135             :      * short of multixact member space.
    1136             :      */
    1137      114968 :     effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
    1138             : 
    1139             :     /*
    1140             :      * Almost ready to set freeze output parameters; check if OldestXmin or
    1141             :      * OldestMxact are held back to an unsafe degree before we start on that
    1142             :      */
    1143      114968 :     safeOldestXmin = nextXID - autovacuum_freeze_max_age;
    1144      114968 :     if (!TransactionIdIsNormal(safeOldestXmin))
    1145           0 :         safeOldestXmin = FirstNormalTransactionId;
    1146      114968 :     safeOldestMxact = nextMXID - effective_multixact_freeze_max_age;
    1147      114968 :     if (safeOldestMxact < FirstMultiXactId)
    1148           0 :         safeOldestMxact = FirstMultiXactId;
    1149      114968 :     if (TransactionIdPrecedes(cutoffs->OldestXmin, safeOldestXmin))
    1150       57162 :         ereport(WARNING,
    1151             :                 (errmsg("cutoff for removing and freezing tuples is far in the past"),
    1152             :                  errhint("Close open transactions soon to avoid wraparound problems.\n"
    1153             :                          "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
    1154      114968 :     if (MultiXactIdPrecedes(cutoffs->OldestMxact, safeOldestMxact))
    1155           0 :         ereport(WARNING,
    1156             :                 (errmsg("cutoff for freezing multixacts is far in the past"),
    1157             :                  errhint("Close open transactions soon to avoid wraparound problems.\n"
    1158             :                          "You might also need to commit or roll back old prepared transactions, or drop stale replication slots.")));
    1159             : 
    1160             :     /*
    1161             :      * Determine the minimum freeze age to use: as specified by the caller, or
    1162             :      * vacuum_freeze_min_age, but in any case not more than half
    1163             :      * autovacuum_freeze_max_age, so that autovacuums to prevent XID
    1164             :      * wraparound won't occur too frequently.
    1165             :      */
    1166      114968 :     if (freeze_min_age < 0)
    1167        8942 :         freeze_min_age = vacuum_freeze_min_age;
    1168      114968 :     freeze_min_age = Min(freeze_min_age, autovacuum_freeze_max_age / 2);
    1169             :     Assert(freeze_min_age >= 0);
    1170             : 
    1171             :     /* Compute FreezeLimit, being careful to generate a normal XID */
    1172      114968 :     cutoffs->FreezeLimit = nextXID - freeze_min_age;
    1173      114968 :     if (!TransactionIdIsNormal(cutoffs->FreezeLimit))
    1174           0 :         cutoffs->FreezeLimit = FirstNormalTransactionId;
    1175             :     /* FreezeLimit must always be <= OldestXmin */
    1176      114968 :     if (TransactionIdPrecedes(cutoffs->OldestXmin, cutoffs->FreezeLimit))
    1177       81838 :         cutoffs->FreezeLimit = cutoffs->OldestXmin;
    1178             : 
    1179             :     /*
    1180             :      * Determine the minimum multixact freeze age to use: as specified by
    1181             :      * caller, or vacuum_multixact_freeze_min_age, but in any case not more
    1182             :      * than half effective_multixact_freeze_max_age, so that autovacuums to
    1183             :      * prevent MultiXact wraparound won't occur too frequently.
    1184             :      */
    1185      114968 :     if (multixact_freeze_min_age < 0)
    1186        8942 :         multixact_freeze_min_age = vacuum_multixact_freeze_min_age;
    1187      114968 :     multixact_freeze_min_age = Min(multixact_freeze_min_age,
    1188             :                                    effective_multixact_freeze_max_age / 2);
    1189             :     Assert(multixact_freeze_min_age >= 0);
    1190             : 
    1191             :     /* Compute MultiXactCutoff, being careful to generate a valid value */
    1192      114968 :     cutoffs->MultiXactCutoff = nextMXID - multixact_freeze_min_age;
    1193      114968 :     if (cutoffs->MultiXactCutoff < FirstMultiXactId)
    1194           0 :         cutoffs->MultiXactCutoff = FirstMultiXactId;
    1195             :     /* MultiXactCutoff must always be <= OldestMxact */
    1196      114968 :     if (MultiXactIdPrecedes(cutoffs->OldestMxact, cutoffs->MultiXactCutoff))
    1197           4 :         cutoffs->MultiXactCutoff = cutoffs->OldestMxact;
    1198             : 
    1199             :     /*
    1200             :      * Finally, figure out if caller needs to do an aggressive VACUUM or not.
    1201             :      *
    1202             :      * Determine the table freeze age to use: as specified by the caller, or
    1203             :      * the value of the vacuum_freeze_table_age GUC, but in any case not more
    1204             :      * than autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
    1205             :      * VACUUM schedule, the nightly VACUUM gets a chance to freeze XIDs before
    1206             :      * anti-wraparound autovacuum is launched.
    1207             :      */
    1208      114968 :     if (freeze_table_age < 0)
    1209        8942 :         freeze_table_age = vacuum_freeze_table_age;
    1210      114968 :     freeze_table_age = Min(freeze_table_age, autovacuum_freeze_max_age * 0.95);
    1211             :     Assert(freeze_table_age >= 0);
    1212      114968 :     aggressiveXIDCutoff = nextXID - freeze_table_age;
    1213      114968 :     if (!TransactionIdIsNormal(aggressiveXIDCutoff))
    1214           0 :         aggressiveXIDCutoff = FirstNormalTransactionId;
    1215      114968 :     if (TransactionIdPrecedesOrEquals(cutoffs->relfrozenxid,
    1216             :                                       aggressiveXIDCutoff))
    1217      106118 :         return true;
    1218             : 
    1219             :     /*
    1220             :      * Similar to the above, determine the table freeze age to use for
    1221             :      * multixacts: as specified by the caller, or the value of the
    1222             :      * vacuum_multixact_freeze_table_age GUC, but in any case not more than
    1223             :      * effective_multixact_freeze_max_age * 0.95, so that if you have e.g.
    1224             :      * nightly VACUUM schedule, the nightly VACUUM gets a chance to freeze
    1225             :      * multixacts before anti-wraparound autovacuum is launched.
    1226             :      */
    1227        8850 :     if (multixact_freeze_table_age < 0)
    1228        8722 :         multixact_freeze_table_age = vacuum_multixact_freeze_table_age;
    1229        8850 :     multixact_freeze_table_age =
    1230        8850 :         Min(multixact_freeze_table_age,
    1231             :             effective_multixact_freeze_max_age * 0.95);
    1232             :     Assert(multixact_freeze_table_age >= 0);
    1233        8850 :     aggressiveMXIDCutoff = nextMXID - multixact_freeze_table_age;
    1234        8850 :     if (aggressiveMXIDCutoff < FirstMultiXactId)
    1235           0 :         aggressiveMXIDCutoff = FirstMultiXactId;
    1236        8850 :     if (MultiXactIdPrecedesOrEquals(cutoffs->relminmxid,
    1237             :                                     aggressiveMXIDCutoff))
    1238           0 :         return true;
    1239             : 
    1240             :     /* Non-aggressive VACUUM */
    1241        8850 :     return false;
    1242             : }
    1243             : 
    1244             : /*
    1245             :  * vacuum_xid_failsafe_check() -- Used by VACUUM's wraparound failsafe
    1246             :  * mechanism to determine if its table's relfrozenxid and relminmxid are now
    1247             :  * dangerously far in the past.
    1248             :  *
    1249             :  * When we return true, VACUUM caller triggers the failsafe.
    1250             :  */
    1251             : bool
    1252      117504 : vacuum_xid_failsafe_check(const struct VacuumCutoffs *cutoffs)
    1253             : {
    1254      117504 :     TransactionId relfrozenxid = cutoffs->relfrozenxid;
    1255      117504 :     MultiXactId relminmxid = cutoffs->relminmxid;
    1256             :     TransactionId xid_skip_limit;
    1257             :     MultiXactId multi_skip_limit;
    1258             :     int         skip_index_vacuum;
    1259             : 
    1260             :     Assert(TransactionIdIsNormal(relfrozenxid));
    1261             :     Assert(MultiXactIdIsValid(relminmxid));
    1262             : 
    1263             :     /*
    1264             :      * Determine the index skipping age to use. In any case no less than
    1265             :      * autovacuum_freeze_max_age * 1.05.
    1266             :      */
    1267      117504 :     skip_index_vacuum = Max(vacuum_failsafe_age, autovacuum_freeze_max_age * 1.05);
    1268             : 
    1269      117504 :     xid_skip_limit = ReadNextTransactionId() - skip_index_vacuum;
    1270      117504 :     if (!TransactionIdIsNormal(xid_skip_limit))
    1271           0 :         xid_skip_limit = FirstNormalTransactionId;
    1272             : 
    1273      117504 :     if (TransactionIdPrecedes(relfrozenxid, xid_skip_limit))
    1274             :     {
    1275             :         /* The table's relfrozenxid is too old */
    1276       19278 :         return true;
    1277             :     }
    1278             : 
    1279             :     /*
    1280             :      * Similar to above, determine the index skipping age to use for
    1281             :      * multixact. In any case no less than autovacuum_multixact_freeze_max_age *
    1282             :      * 1.05.
    1283             :      */
    1284       98226 :     skip_index_vacuum = Max(vacuum_multixact_failsafe_age,
    1285             :                             autovacuum_multixact_freeze_max_age * 1.05);
    1286             : 
    1287       98226 :     multi_skip_limit = ReadNextMultiXactId() - skip_index_vacuum;
    1288       98226 :     if (multi_skip_limit < FirstMultiXactId)
    1289           0 :         multi_skip_limit = FirstMultiXactId;
    1290             : 
    1291       98226 :     if (MultiXactIdPrecedes(relminmxid, multi_skip_limit))
    1292             :     {
    1293             :         /* The table's relminmxid is too old */
    1294           0 :         return true;
    1295             :     }
    1296             : 
    1297       98226 :     return false;
    1298             : }
    1299             : 
    1300             : /*
    1301             :  * vac_estimate_reltuples() -- estimate the new value for pg_class.reltuples
    1302             :  *
    1303             :  *      If we scanned the whole relation then we should just use the count of
    1304             :  *      live tuples seen; but if we did not, we should not blindly extrapolate
    1305             :  *      from that number, since VACUUM may have scanned a quite nonrandom
    1306             :  *      subset of the table.  When we have only partial information, we take
    1307             :  *      the old value of pg_class.reltuples/pg_class.relpages as a measurement
    1308             :  *      of the tuple density in the unscanned pages.
    1309             :  *
    1310             :  *      Note: scanned_tuples should count only *live* tuples, since
    1311             :  *      pg_class.reltuples is defined that way.
    1312             :  */
    1313             : double
    1314      114426 : vac_estimate_reltuples(Relation relation,
    1315             :                        BlockNumber total_pages,
    1316             :                        BlockNumber scanned_pages,
    1317             :                        double scanned_tuples)
    1318             : {
    1319      114426 :     BlockNumber old_rel_pages = relation->rd_rel->relpages;
    1320      114426 :     double      old_rel_tuples = relation->rd_rel->reltuples;
    1321             :     double      old_density;
    1322             :     double      unscanned_pages;
    1323             :     double      total_tuples;
    1324             : 
    1325             :     /* If we did scan the whole table, just use the count as-is */
    1326      114426 :     if (scanned_pages >= total_pages)
    1327      110488 :         return scanned_tuples;
    1328             : 
    1329             :     /*
    1330             :      * When successive VACUUM commands scan the same few pages again and
    1331             :      * again, without anything from the table really changing, there is a risk
    1332             :      * that our beliefs about tuple density will gradually become distorted.
    1333             :      * This might be caused by vacuumlazy.c implementation details, such as
    1334             :      * its tendency to always scan the last heap page.  Handle that here.
    1335             :      *
    1336             :      * If the relation is _exactly_ the same size according to the existing
    1337             :      * pg_class entry, and only a few of its pages (less than 2%) were
    1338             :      * scanned, keep the existing value of reltuples.  Also keep the existing
    1339             :      * value when only a subset of rel's pages <= a single page were scanned.
    1340             :      *
    1341             :      * (Note: we might be returning -1 here.)
    1342             :      */
    1343        3938 :     if (old_rel_pages == total_pages &&
    1344        3908 :         scanned_pages < (double) total_pages * 0.02)
    1345        2732 :         return old_rel_tuples;
    1346        1206 :     if (scanned_pages <= 1)
    1347         948 :         return old_rel_tuples;
    1348             : 
    1349             :     /*
    1350             :      * If old density is unknown, we can't do much except scale up
    1351             :      * scanned_tuples to match total_pages.
    1352             :      */
    1353         258 :     if (old_rel_tuples < 0 || old_rel_pages == 0)
    1354           2 :         return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);
    1355             : 
    1356             :     /*
    1357             :      * Okay, we've covered the corner cases.  The normal calculation is to
    1358             :      * convert the old measurement to a density (tuples per page), then
    1359             :      * estimate the number of tuples in the unscanned pages using that figure,
    1360             :      * and finally add on the number of tuples in the scanned pages.
    1361             :      */
    1362         256 :     old_density = old_rel_tuples / old_rel_pages;
    1363         256 :     unscanned_pages = (double) total_pages - (double) scanned_pages;
    1364         256 :     total_tuples = old_density * unscanned_pages + scanned_tuples;
    1365         256 :     return floor(total_tuples + 0.5);
    1366             : }
    1367             : 
    1368             : 
    1369             : /*
    1370             :  *  vac_update_relstats() -- update statistics for one relation
    1371             :  *
    1372             :  *      Update the whole-relation statistics that are kept in its pg_class
    1373             :  *      row.  There are additional stats that will be updated if we are
    1374             :  *      doing ANALYZE, but we always update these stats.  This routine works
    1375             :  *      for both index and heap relation entries in pg_class.
    1376             :  *
    1377             :  *      We violate transaction semantics here by overwriting the rel's
    1378             :  *      existing pg_class tuple with the new values.  This is reasonably
    1379             :  *      safe as long as we're sure that the new values are correct whether or
    1380             :  *      not this transaction commits.  The reason for doing this is that if
    1381             :  *      we updated these tuples in the usual way, vacuuming pg_class itself
    1382             :  *      wouldn't work very well --- by the time we got done with a vacuum
    1383             :  *      cycle, most of the tuples in pg_class would've been obsoleted.  Of
    1384             :  *      course, this only works for fixed-size not-null columns, but these are.
    1385             :  *
    1386             :  *      Another reason for doing it this way is that when we are in a lazy
    1387             :  *      VACUUM and have PROC_IN_VACUUM set, we mustn't do any regular updates.
    1388             :  *      Somebody vacuuming pg_class might think they could delete a tuple
    1389             :  *      marked with xmin = our xid.
    1390             :  *
    1391             :  *      In addition to fundamentally nontransactional statistics such as
    1392             :  *      relpages and relallvisible, we try to maintain certain lazily-updated
    1393             :  *      DDL flags such as relhasindex, by clearing them if no longer correct.
    1394             :  *      It's safe to do this in VACUUM, which can't run in parallel with
    1395             :  *      CREATE INDEX/RULE/TRIGGER and can't be part of a transaction block.
    1396             :  *      However, it's *not* safe to do it in an ANALYZE that's within an
    1397             :  *      outer transaction, because for example the current transaction might
    1398             :  *      have dropped the last index; then we'd think relhasindex should be
    1399             :  *      cleared, but if the transaction later rolls back this would be wrong.
    1400             :  *      So we refrain from updating the DDL flags if we're inside an outer
    1401             :  *      transaction.  This is OK since postponing the flag maintenance is
    1402             :  *      always allowable.
    1403             :  *
    1404             :  *      Note: num_tuples should count only *live* tuples, since
    1405             :  *      pg_class.reltuples is defined that way.
    1406             :  *
    1407             :  *      This routine is shared by VACUUM and ANALYZE.
    1408             :  */
    1409             : void
    1410      148820 : vac_update_relstats(Relation relation,
    1411             :                     BlockNumber num_pages, double num_tuples,
    1412             :                     BlockNumber num_all_visible_pages,
    1413             :                     bool hasindex, TransactionId frozenxid,
    1414             :                     MultiXactId minmulti,
    1415             :                     bool *frozenxid_updated, bool *minmulti_updated,
    1416             :                     bool in_outer_xact)
    1417             : {
    1418      148820 :     Oid         relid = RelationGetRelid(relation);
    1419             :     Relation    rd;
    1420             :     ScanKeyData key[1];
    1421             :     HeapTuple   ctup;
    1422             :     void       *inplace_state;
    1423             :     Form_pg_class pgcform;
    1424             :     bool        dirty,
    1425             :                 futurexid,
    1426             :                 futuremxid;
    1427             :     TransactionId oldfrozenxid;
    1428             :     MultiXactId oldminmulti;
    1429             : 
    1430      148820 :     rd = table_open(RelationRelationId, RowExclusiveLock);
    1431             : 
    1432             :     /* Fetch a copy of the tuple to scribble on */
    1433      148820 :     ScanKeyInit(&key[0],
    1434             :                 Anum_pg_class_oid,
    1435             :                 BTEqualStrategyNumber, F_OIDEQ,
    1436             :                 ObjectIdGetDatum(relid));
    1437      148820 :     systable_inplace_update_begin(rd, ClassOidIndexId, true,
    1438             :                                   NULL, 1, key, &ctup, &inplace_state);
    1439      148820 :     if (!HeapTupleIsValid(ctup))
    1440           0 :         elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
    1441             :              relid);
    1442      148820 :     pgcform = (Form_pg_class) GETSTRUCT(ctup);
    1443             : 
    1444             :     /* Apply statistical updates, if any, to copied tuple */
    1445             : 
    1446      148820 :     dirty = false;
    1447      148820 :     if (pgcform->relpages != (int32) num_pages)
    1448             :     {
    1449        8486 :         pgcform->relpages = (int32) num_pages;
    1450        8486 :         dirty = true;
    1451             :     }
    1452      148820 :     if (pgcform->reltuples != (float4) num_tuples)
    1453             :     {
    1454       18040 :         pgcform->reltuples = (float4) num_tuples;
    1455       18040 :         dirty = true;
    1456             :     }
    1457      148820 :     if (pgcform->relallvisible != (int32) num_all_visible_pages)
    1458             :     {
    1459        5138 :         pgcform->relallvisible = (int32) num_all_visible_pages;
    1460        5138 :         dirty = true;
    1461             :     }
    1462             : 
    1463             :     /* Apply DDL updates, but not inside an outer transaction (see above) */
    1464             : 
    1465      148820 :     if (!in_outer_xact)
    1466             :     {
    1467             :         /*
    1468             :          * If we didn't find any indexes, reset relhasindex.
    1469             :          */
    1470      148506 :         if (pgcform->relhasindex && !hasindex)
    1471             :         {
    1472          20 :             pgcform->relhasindex = false;
    1473          20 :             dirty = true;
    1474             :         }
    1475             : 
    1476             :         /* We also clear relhasrules and relhastriggers if needed */
    1477      148506 :         if (pgcform->relhasrules && relation->rd_rules == NULL)
    1478             :         {
    1479           0 :             pgcform->relhasrules = false;
    1480           0 :             dirty = true;
    1481             :         }
    1482      148506 :         if (pgcform->relhastriggers && relation->trigdesc == NULL)
    1483             :         {
    1484           6 :             pgcform->relhastriggers = false;
    1485           6 :             dirty = true;
    1486             :         }
    1487             :     }
    1488             : 
    1489             :     /*
    1490             :      * Update relfrozenxid, unless caller passed InvalidTransactionId
    1491             :      * indicating it has no new data.
    1492             :      *
    1493             :      * Ordinarily, we don't let relfrozenxid go backwards.  However, if the
    1494             :      * stored relfrozenxid is "in the future" then it seems best to assume
    1495             :      * it's corrupt, and overwrite with the oldest remaining XID in the table.
    1496             :      * This should match vac_update_datfrozenxid() concerning what we consider
    1497             :      * to be "in the future".
    1498             :      */
    1499      148820 :     oldfrozenxid = pgcform->relfrozenxid;
    1500      148820 :     futurexid = false;
    1501      148820 :     if (frozenxid_updated)
    1502      114422 :         *frozenxid_updated = false;
    1503      148820 :     if (TransactionIdIsNormal(frozenxid) && oldfrozenxid != frozenxid)
    1504             :     {
    1505       55410 :         bool        update = false;
    1506             : 
    1507       55410 :         if (TransactionIdPrecedes(oldfrozenxid, frozenxid))
    1508       55342 :             update = true;
    1509          68 :         else if (TransactionIdPrecedes(ReadNextTransactionId(), oldfrozenxid))
    1510           0 :             futurexid = update = true;
    1511             : 
    1512       55410 :         if (update)
    1513             :         {
    1514       55342 :             pgcform->relfrozenxid = frozenxid;
    1515       55342 :             dirty = true;
    1516       55342 :             if (frozenxid_updated)
    1517       55342 :                 *frozenxid_updated = true;
    1518             :         }
    1519             :     }
    1520             : 
    1521             :     /* Similarly for relminmxid */
    1522      148820 :     oldminmulti = pgcform->relminmxid;
    1523      148820 :     futuremxid = false;
    1524      148820 :     if (minmulti_updated)
    1525      114422 :         *minmulti_updated = false;
    1526      148820 :     if (MultiXactIdIsValid(minmulti) && oldminmulti != minmulti)
    1527             :     {
    1528         358 :         bool        update = false;
    1529             : 
    1530         358 :         if (MultiXactIdPrecedes(oldminmulti, minmulti))
    1531         358 :             update = true;
    1532           0 :         else if (MultiXactIdPrecedes(ReadNextMultiXactId(), oldminmulti))
    1533           0 :             futuremxid = update = true;
    1534             : 
    1535         358 :         if (update)
    1536             :         {
    1537         358 :             pgcform->relminmxid = minmulti;
    1538         358 :             dirty = true;
    1539         358 :             if (minmulti_updated)
    1540         358 :                 *minmulti_updated = true;
    1541             :         }
    1542             :     }
    1543             : 
    1544             :     /* If anything changed, write out the tuple. */
    1545      148820 :     if (dirty)
    1546       67974 :         systable_inplace_update_finish(inplace_state, ctup);
    1547             :     else
    1548       80846 :         systable_inplace_update_cancel(inplace_state);
    1549             : 
    1550      148820 :     table_close(rd, RowExclusiveLock);
    1551             : 
    1552      148820 :     if (futurexid)
    1553           0 :         ereport(WARNING,
    1554             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1555             :                  errmsg_internal("overwrote invalid relfrozenxid value %u with new value %u for table \"%s\"",
    1556             :                                  oldfrozenxid, frozenxid,
    1557             :                                  RelationGetRelationName(relation))));
    1558      148820 :     if (futuremxid)
    1559           0 :         ereport(WARNING,
    1560             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1561             :                  errmsg_internal("overwrote invalid relminmxid value %u with new value %u for table \"%s\"",
    1562             :                                  oldminmulti, minmulti,
    1563             :                                  RelationGetRelationName(relation))));
    1564      148820 : }
    1565             : 
    1566             : 
    1567             : /*
    1568             :  *  vac_update_datfrozenxid() -- update pg_database.datfrozenxid for our DB
    1569             :  *
    1570             :  *      Update pg_database's datfrozenxid entry for our database to be the
    1571             :  *      minimum of the pg_class.relfrozenxid values.
    1572             :  *
    1573             :  *      Similarly, update our datminmxid to be the minimum of the
    1574             :  *      pg_class.relminmxid values.
    1575             :  *
    1576             :  *      If we are able to advance either pg_database value, also try to
    1577             :  *      truncate pg_xact and pg_multixact.
    1578             :  *
    1579             :  *      We violate transaction semantics here by overwriting the database's
    1580             :  *      existing pg_database tuple with the new values.  This is reasonably
    1581             :  *      safe since the new values are correct whether or not this transaction
    1582             :  *      commits.  As with vac_update_relstats, this avoids leaving dead tuples
    1583             :  *      behind after a VACUUM.
    1584             :  */
    1585             : void
    1586        3922 : vac_update_datfrozenxid(void)
    1587             : {
    1588             :     HeapTuple   tuple;
    1589             :     Form_pg_database dbform;
    1590             :     Relation    relation;
    1591             :     SysScanDesc scan;
    1592             :     HeapTuple   classTup;
    1593             :     TransactionId newFrozenXid;
    1594             :     MultiXactId newMinMulti;
    1595             :     TransactionId lastSaneFrozenXid;
    1596             :     MultiXactId lastSaneMinMulti;
    1597        3922 :     bool        bogus = false;
    1598        3922 :     bool        dirty = false;
    1599             :     ScanKeyData key[1];
    1600             :     void       *inplace_state;
    1601             : 
    1602             :     /*
    1603             :      * Restrict this task to one backend per database.  This avoids race
    1604             :      * conditions that would move datfrozenxid or datminmxid backward.  It
    1605             :      * avoids calling vac_truncate_clog() with a datfrozenxid preceding a
    1606             :      * datfrozenxid passed to an earlier vac_truncate_clog() call.
    1607             :      */
    1608        3922 :     LockDatabaseFrozenIds(ExclusiveLock);
    1609             : 
    1610             :     /*
    1611             :      * Initialize the "min" calculation with
    1612             :      * GetOldestNonRemovableTransactionId(), which is a reasonable
    1613             :      * approximation to the minimum relfrozenxid for not-yet-committed
    1614             :      * pg_class entries for new tables; see AddNewRelationTuple().  So we
    1615             :      * cannot produce a wrong minimum by starting with this.
    1616             :      */
    1617        3922 :     newFrozenXid = GetOldestNonRemovableTransactionId(NULL);
    1618             : 
    1619             :     /*
    1620             :      * Similarly, initialize the MultiXact "min" with the value that would be
    1621             :      * used on pg_class for new tables.  See AddNewRelationTuple().
    1622             :      */
    1623        3922 :     newMinMulti = GetOldestMultiXactId();
    1624             : 
    1625             :     /*
    1626             :      * Identify the latest relfrozenxid and relminmxid values that we could
    1627             :      * validly see during the scan.  These are conservative values, but it's
    1628             :      * not really worth trying to be more exact.
    1629             :      */
    1630        3922 :     lastSaneFrozenXid = ReadNextTransactionId();
    1631        3922 :     lastSaneMinMulti = ReadNextMultiXactId();
    1632             : 
    1633             :     /*
    1634             :      * We must seqscan pg_class to find the minimum Xid, because there is no
    1635             :      * index that can help us here.
    1636             :      *
    1637             :      * See vac_truncate_clog() for the race condition to prevent.
    1638             :      */
    1639        3922 :     relation = table_open(RelationRelationId, AccessShareLock);
    1640             : 
    1641        3922 :     scan = systable_beginscan(relation, InvalidOid, false,
    1642             :                               NULL, 0, NULL);
    1643             : 
    1644     2014034 :     while ((classTup = systable_getnext(scan)) != NULL)
    1645             :     {
    1646     2010112 :         volatile FormData_pg_class *classForm = (Form_pg_class) GETSTRUCT(classTup);
    1647     2010112 :         TransactionId relfrozenxid = classForm->relfrozenxid;
    1648     2010112 :         TransactionId relminmxid = classForm->relminmxid;
    1649             : 
    1650             :         /*
    1651             :          * Only consider relations able to hold unfrozen XIDs (anything else
    1652             :          * should have InvalidTransactionId in relfrozenxid anyway).
    1653             :          */
    1654     2010112 :         if (classForm->relkind != RELKIND_RELATION &&
    1655     1595152 :             classForm->relkind != RELKIND_MATVIEW &&
    1656     1593054 :             classForm->relkind != RELKIND_TOASTVALUE)
    1657             :         {
    1658             :             Assert(!TransactionIdIsValid(relfrozenxid));
    1659             :             Assert(!MultiXactIdIsValid(relminmxid));
    1660     1372120 :             continue;
    1661             :         }
    1662             : 
    1663             :         /*
    1664             :          * Some table AMs might not need per-relation xid / multixid horizons.
    1665             :          * It therefore seems reasonable to allow relfrozenxid and relminmxid
    1666             :          * to not be set (i.e. set to their respective Invalid*Id)
    1667             :          * independently. Thus validate and compute horizon for each only if
    1668             :          * set.
    1669             :          *
    1670             :          * If things are working properly, no relation should have a
    1671             :          * relfrozenxid or relminmxid that is "in the future".  However, such
    1672             :          * cases have been known to arise due to bugs in pg_upgrade.  If we
    1673             :          * see any entries that are "in the future", chicken out and don't do
    1674             :          * anything.  This ensures we won't truncate clog & multixact SLRUs
    1675             :          * before those relations have been scanned and cleaned up.
    1676             :          */
    1677             : 
    1678      637992 :         if (TransactionIdIsValid(relfrozenxid))
    1679             :         {
    1680             :             Assert(TransactionIdIsNormal(relfrozenxid));
    1681             : 
    1682             :             /* check for values in the future */
    1683      637992 :             if (TransactionIdPrecedes(lastSaneFrozenXid, relfrozenxid))
    1684             :             {
    1685           0 :                 bogus = true;
    1686           0 :                 break;
    1687             :             }
    1688             : 
    1689             :             /* determine new horizon */
    1690      637992 :             if (TransactionIdPrecedes(relfrozenxid, newFrozenXid))
    1691        3958 :                 newFrozenXid = relfrozenxid;
    1692             :         }
    1693             : 
    1694      637992 :         if (MultiXactIdIsValid(relminmxid))
    1695             :         {
    1696             :             /* check for values in the future */
    1697      637992 :             if (MultiXactIdPrecedes(lastSaneMinMulti, relminmxid))
    1698             :             {
    1699           0 :                 bogus = true;
    1700           0 :                 break;
    1701             :             }
    1702             : 
    1703             :             /* determine new horizon */
    1704      637992 :             if (MultiXactIdPrecedes(relminmxid, newMinMulti))
    1705         200 :                 newMinMulti = relminmxid;
    1706             :         }
    1707             :     }
    1708             : 
    1709             :     /* we're done with pg_class */
    1710        3922 :     systable_endscan(scan);
    1711        3922 :     table_close(relation, AccessShareLock);
    1712             : 
    1713             :     /* chicken out if bogus data found */
    1714        3922 :     if (bogus)
    1715           0 :         return;
    1716             : 
    1717             :     Assert(TransactionIdIsNormal(newFrozenXid));
    1718             :     Assert(MultiXactIdIsValid(newMinMulti));
    1719             : 
    1720             :     /* Now fetch the pg_database tuple we need to update. */
    1721        3922 :     relation = table_open(DatabaseRelationId, RowExclusiveLock);
    1722             : 
    1723             :     /*
    1724             :      * Fetch a copy of the tuple to scribble on.  We could check the syscache
    1725             :      * tuple first.  If that concluded !dirty, we'd avoid waiting on
    1726             :      * concurrent heap_update() and would avoid exclusive-locking the buffer.
    1727             :      * For now, don't optimize that.
    1728             :      */
    1729        3922 :     ScanKeyInit(&key[0],
    1730             :                 Anum_pg_database_oid,
    1731             :                 BTEqualStrategyNumber, F_OIDEQ,
    1732             :                 ObjectIdGetDatum(MyDatabaseId));
    1733             : 
    1734        3922 :     systable_inplace_update_begin(relation, DatabaseOidIndexId, true,
    1735             :                                   NULL, 1, key, &tuple, &inplace_state);
    1736             : 
    1737        3922 :     if (!HeapTupleIsValid(tuple))
    1738           0 :         elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
    1739             : 
    1740        3922 :     dbform = (Form_pg_database) GETSTRUCT(tuple);
    1741             : 
    1742             :     /*
    1743             :      * As in vac_update_relstats(), we ordinarily don't want to let
    1744             :      * datfrozenxid go backward; but if it's "in the future" then it must be
    1745             :      * corrupt and it seems best to overwrite it.
    1746             :      */
    1747        4440 :     if (dbform->datfrozenxid != newFrozenXid &&
    1748         518 :         (TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) ||
    1749           0 :          TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid)))
    1750             :     {
    1751         518 :         dbform->datfrozenxid = newFrozenXid;
    1752         518 :         dirty = true;
    1753             :     }
    1754             :     else
    1755        3404 :         newFrozenXid = dbform->datfrozenxid;
    1756             : 
    1757             :     /* Ditto for datminmxid */
    1758        3924 :     if (dbform->datminmxid != newMinMulti &&
    1759           2 :         (MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) ||
    1760           0 :          MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid)))
    1761             :     {
    1762           2 :         dbform->datminmxid = newMinMulti;
    1763           2 :         dirty = true;
    1764             :     }
    1765             :     else
    1766        3920 :         newMinMulti = dbform->datminmxid;
    1767             : 
    1768        3922 :     if (dirty)
    1769         518 :         systable_inplace_update_finish(inplace_state, tuple);
    1770             :     else
    1771        3404 :         systable_inplace_update_cancel(inplace_state);
    1772             : 
    1773        3922 :     heap_freetuple(tuple);
    1774        3922 :     table_close(relation, RowExclusiveLock);
    1775             : 
    1776             :     /*
    1777             :      * If we were able to advance datfrozenxid or datminmxid, see if we can
    1778             :      * truncate pg_xact and/or pg_multixact.  Also do it if the shared
    1779             :      * XID-wrap-limit info is stale, since this action will update that too.
    1780             :      */
    1781        3922 :     if (dirty || ForceTransactionIdLimitUpdate())
    1782        1062 :         vac_truncate_clog(newFrozenXid, newMinMulti,
    1783             :                           lastSaneFrozenXid, lastSaneMinMulti);
    1784             : }
    1785             : 
    1786             : 
    1787             : /*
    1788             :  *  vac_truncate_clog() -- attempt to truncate the commit log
    1789             :  *
    1790             :  *      Scan pg_database to determine the system-wide oldest datfrozenxid,
    1791             :  *      and use it to truncate the transaction commit log (pg_xact).
    1792             :  *      Also update the XID wrap limit info maintained by varsup.c.
    1793             :  *      Likewise for datminmxid.
    1794             :  *
    1795             :  *      The passed frozenXID and minMulti are the updated values for my own
    1796             :  *      pg_database entry. They're used to initialize the "min" calculations.
    1797             :  *      The caller also passes the "last sane" XID and MXID, since it has
    1798             :  *      those at hand already.
    1799             :  *
    1800             :  *      This routine is only invoked when we've managed to change our
    1801             :  *      DB's datfrozenxid/datminmxid values, or we found that the shared
    1802             :  *      XID-wrap-limit info is stale.
    1803             :  */
    1804             : static void
    1805        1062 : vac_truncate_clog(TransactionId frozenXID,
    1806             :                   MultiXactId minMulti,
    1807             :                   TransactionId lastSaneFrozenXid,
    1808             :                   MultiXactId lastSaneMinMulti)
    1809             : {
    1810        1062 :     TransactionId nextXID = ReadNextTransactionId();
    1811             :     Relation    relation;
    1812             :     TableScanDesc scan;
    1813             :     HeapTuple   tuple;
    1814             :     Oid         oldestxid_datoid;
    1815             :     Oid         minmulti_datoid;
    1816        1062 :     bool        bogus = false;
    1817        1062 :     bool        frozenAlreadyWrapped = false;
    1818             : 
    1819             :     /* Restrict task to one backend per cluster; see SimpleLruTruncate(). */
    1820        1062 :     LWLockAcquire(WrapLimitsVacuumLock, LW_EXCLUSIVE);
    1821             : 
    1822             :     /* init oldest datoids to sync with my frozenXID/minMulti values */
    1823        1062 :     oldestxid_datoid = MyDatabaseId;
    1824        1062 :     minmulti_datoid = MyDatabaseId;
    1825             : 
    1826             :     /*
    1827             :      * Scan pg_database to compute the minimum datfrozenxid/datminmxid
    1828             :      *
    1829             :      * Since vac_update_datfrozenxid updates datfrozenxid/datminmxid in-place,
    1830             :      * the values could change while we look at them.  Fetch each one just
    1831             :      * once to ensure sane behavior of the comparison logic.  (Here, as in
    1832             :      * many other places, we assume that fetching or updating an XID in shared
    1833             :      * storage is atomic.)
    1834             :      *
    1835             :      * Note: we need not worry about a race condition with new entries being
    1836             :      * inserted by CREATE DATABASE.  Any such entry will have a copy of some
    1837             :      * existing DB's datfrozenxid, and that source DB cannot be ours because
    1838             :      * of the interlock against copying a DB containing an active backend.
    1839             :      * Hence the new entry will not reduce the minimum.  Also, if two VACUUMs
    1840             :      * concurrently modify the datfrozenxid's of different databases, the
    1841             :      * worst possible outcome is that pg_xact is not truncated as aggressively
    1842             :      * as it could be.
    1843             :      */
    1844        1062 :     relation = table_open(DatabaseRelationId, AccessShareLock);
    1845             : 
    1846        1062 :     scan = table_beginscan_catalog(relation, 0, NULL);
    1847             : 
    1848        4094 :     while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
    1849             :     {
    1850        3032 :         volatile FormData_pg_database *dbform = (Form_pg_database) GETSTRUCT(tuple);
    1851        3032 :         TransactionId datfrozenxid = dbform->datfrozenxid;
    1852        3032 :         TransactionId datminmxid = dbform->datminmxid;
    1853             : 
    1854             :         Assert(TransactionIdIsNormal(datfrozenxid));
    1855             :         Assert(MultiXactIdIsValid(datminmxid));
    1856             : 
    1857             :         /*
    1858             :          * If database is in the process of getting dropped, or has been
    1859             :          * interrupted while doing so, no connections to it are possible
    1860             :          * anymore. Therefore we don't need to take it into account here.
    1861             :          * Which is good, because it can't be processed by autovacuum either.
    1862             :          */
    1863        3032 :         if (database_is_invalid_form((Form_pg_database) dbform))
    1864             :         {
    1865           2 :             elog(DEBUG2,
    1866             :                  "skipping invalid database \"%s\" while computing relfrozenxid",
    1867             :                  NameStr(dbform->datname));
    1868           2 :             continue;
    1869             :         }
    1870             : 
    1871             :         /*
    1872             :          * If things are working properly, no database should have a
    1873             :          * datfrozenxid or datminmxid that is "in the future".  However, such
    1874             :          * cases have been known to arise due to bugs in pg_upgrade.  If we
    1875             :          * see any entries that are "in the future", chicken out and don't do
    1876             :          * anything.  This ensures we won't truncate clog before those
    1877             :          * databases have been scanned and cleaned up.  (We will issue the
    1878             :          * "already wrapped" warning if appropriate, though.)
    1879             :          */
    1880        6060 :         if (TransactionIdPrecedes(lastSaneFrozenXid, datfrozenxid) ||
    1881        3030 :             MultiXactIdPrecedes(lastSaneMinMulti, datminmxid))
    1882           0 :             bogus = true;
    1883             : 
    1884        3030 :         if (TransactionIdPrecedes(nextXID, datfrozenxid))
    1885           0 :             frozenAlreadyWrapped = true;
    1886        3030 :         else if (TransactionIdPrecedes(datfrozenxid, frozenXID))
    1887             :         {
    1888         510 :             frozenXID = datfrozenxid;
    1889         510 :             oldestxid_datoid = dbform->oid;
    1890             :         }
    1891             : 
    1892        3030 :         if (MultiXactIdPrecedes(datminmxid, minMulti))
    1893             :         {
    1894           4 :             minMulti = datminmxid;
    1895           4 :             minmulti_datoid = dbform->oid;
    1896             :         }
    1897             :     }
    1898             : 
    1899        1062 :     table_endscan(scan);
    1900             : 
    1901        1062 :     table_close(relation, AccessShareLock);
    1902             : 
    1903             :     /*
    1904             :      * Do not truncate CLOG if we seem to have suffered wraparound already;
    1905             :      * the computed minimum XID might be bogus.  This case should now be
    1906             :      * impossible due to the defenses in GetNewTransactionId, but we keep the
    1907             :      * test anyway.
    1908             :      */
    1909        1062 :     if (frozenAlreadyWrapped)
    1910             :     {
    1911           0 :         ereport(WARNING,
    1912             :                 (errmsg("some databases have not been vacuumed in over 2 billion transactions"),
    1913             :                  errdetail("You might have already suffered transaction-wraparound data loss.")));
    1914           0 :         LWLockRelease(WrapLimitsVacuumLock);
    1915           0 :         return;
    1916             :     }
    1917             : 
    1918             :     /* chicken out if data is bogus in any other way */
    1919        1062 :     if (bogus)
    1920             :     {
    1921           0 :         LWLockRelease(WrapLimitsVacuumLock);
    1922           0 :         return;
    1923             :     }
    1924             : 
    1925             :     /*
    1926             :      * Advance the oldest value for commit timestamps before truncating, so
    1927             :      * that if a user requests a timestamp for a transaction we're truncating
    1928             :      * away right after this point, they get NULL instead of an ugly "file not
    1929             :      * found" error from slru.c.  This doesn't matter for xact/multixact
    1930             :      * because they are not subject to arbitrary lookups from users.
    1931             :      */
    1932        1062 :     AdvanceOldestCommitTsXid(frozenXID);
    1933             : 
    1934             :     /*
    1935             :      * Truncate CLOG, multixact and CommitTs to the oldest computed value.
    1936             :      */
    1937        1062 :     TruncateCLOG(frozenXID, oldestxid_datoid);
    1938        1062 :     TruncateCommitTs(frozenXID);
    1939        1062 :     TruncateMultiXact(minMulti, minmulti_datoid);
    1940             : 
    1941             :     /*
    1942             :      * Update the wrap limit for GetNewTransactionId and creation of new
    1943             :      * MultiXactIds.  Note: these functions will also signal the postmaster
    1944             :      * for an(other) autovac cycle if needed.   XXX should we avoid possibly
    1945             :      * signaling twice?
    1946             :      */
    1947        1062 :     SetTransactionIdLimit(frozenXID, oldestxid_datoid);
    1948        1062 :     SetMultiXactIdLimit(minMulti, minmulti_datoid, false);
    1949             : 
    1950        1062 :     LWLockRelease(WrapLimitsVacuumLock);
    1951             : }
    1952             : 
    1953             : 
    1954             : /*
    1955             :  *  vacuum_rel() -- vacuum one heap relation
    1956             :  *
    1957             :  *      relid identifies the relation to vacuum.  If relation is supplied,
    1958             :  *      use the name therein for reporting any failure to open/lock the rel;
    1959             :  *      do not use it once we've successfully opened the rel, since it might
    1960             :  *      be stale.
    1961             :  *
    1962             :  *      Returns true if it's okay to proceed with a requested ANALYZE
    1963             :  *      operation on this table.
    1964             :  *
    1965             :  *      Doing one heap at a time incurs extra overhead, since we need to
    1966             :  *      check that the heap exists again just before we vacuum it.  The
    1967             :  *      reason that we do this is so that vacuuming can be spread across
    1968             :  *      many small transactions.  Otherwise, two-phase locking would require
    1969             :  *      us to lock the entire database during one pass of the vacuum cleaner.
    1970             :  *
    1971             :  *      At entry and exit, we are not inside a transaction.
    1972             :  */
    1973             : static bool
    1974      115212 : vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params,
    1975             :            BufferAccessStrategy bstrategy)
    1976             : {
    1977             :     LOCKMODE    lmode;
    1978             :     Relation    rel;
    1979             :     LockRelId   lockrelid;
    1980             :     Oid         priv_relid;
    1981             :     Oid         toast_relid;
    1982             :     Oid         save_userid;
    1983             :     int         save_sec_context;
    1984             :     int         save_nestlevel;
    1985             : 
    1986             :     Assert(params != NULL);
    1987             : 
    1988             :     /* Begin a transaction for vacuuming this relation */
    1989      115212 :     StartTransactionCommand();
    1990             : 
    1991      115212 :     if (!(params->options & VACOPT_FULL))
    1992             :     {
    1993             :         /*
    1994             :          * In lazy vacuum, we can set the PROC_IN_VACUUM flag, which lets
    1995             :          * other concurrent VACUUMs know that they can ignore this one while
    1996             :          * determining their OldestXmin.  (The reason we don't set it during a
    1997             :          * full VACUUM is exactly that we may have to run user-defined
    1998             :          * functions for functional indexes, and we want to make sure that if
    1999             :          * they use the snapshot set above, any tuples it requires can't get
    2000             :          * removed from other tables.  An index function that depends on the
    2001             :          * contents of other tables is arguably broken, but we won't break it
    2002             :          * here by violating transaction semantics.)
    2003             :          *
    2004             :          * We also set the VACUUM_FOR_WRAPAROUND flag, which is passed down by
    2005             :          * autovacuum; it's used to avoid canceling a vacuum that was invoked
    2006             :          * in an emergency.
    2007             :          *
    2008             :          * Note: these flags remain set until CommitTransaction or
    2009             :          * AbortTransaction.  We don't want to clear them until we reset
    2010             :          * MyProc->xid/xmin, otherwise GetOldestNonRemovableTransactionId()
    2011             :          * might appear to go backwards, which is probably Not Good.  (We also
    2012             :          * set PROC_IN_VACUUM *before* taking our own snapshot, so that our
    2013             :          * xmin doesn't become visible ahead of setting the flag.)
    2014             :          */
    2015      114820 :         LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
    2016      114820 :         MyProc->statusFlags |= PROC_IN_VACUUM;
    2017      114820 :         if (params->is_wraparound)
    2018       93490 :             MyProc->statusFlags |= PROC_VACUUM_FOR_WRAPAROUND;
    2019      114820 :         ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
    2020      114820 :         LWLockRelease(ProcArrayLock);
    2021             :     }
    2022             : 
    2023             :     /*
    2024             :      * Need to acquire a snapshot to prevent pg_subtrans from being truncated,
    2025             :      * cutoff xids in local memory wrapping around, and to have updated xmin
    2026             :      * horizons.
    2027             :      */
    2028      115212 :     PushActiveSnapshot(GetTransactionSnapshot());
    2029             : 
    2030             :     /*
    2031             :      * Check for user-requested abort.  Note we want this to be inside a
    2032             :      * transaction, so xact.c doesn't issue useless WARNING.
    2033             :      */
    2034      115212 :     CHECK_FOR_INTERRUPTS();
    2035             : 
    2036             :     /*
    2037             :      * Determine the type of lock we want --- hard exclusive lock for a FULL
    2038             :      * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either
    2039             :      * way, we can be sure that no other backend is vacuuming the same table.
    2040             :      */
    2041      230424 :     lmode = (params->options & VACOPT_FULL) ?
    2042      115212 :         AccessExclusiveLock : ShareUpdateExclusiveLock;
    2043             : 
    2044             :     /* open the relation and get the appropriate lock on it */
    2045      115212 :     rel = vacuum_open_relation(relid, relation, params->options,
    2046      115212 :                                params->log_min_duration >= 0, lmode);
    2047             : 
    2048             :     /* leave if relation could not be opened or locked */
    2049      115212 :     if (!rel)
    2050             :     {
    2051          24 :         PopActiveSnapshot();
    2052          24 :         CommitTransactionCommand();
    2053          24 :         return false;
    2054             :     }
    2055             : 
    2056             :     /*
    2057             :      * When recursing to a TOAST table, check privileges on the parent.  NB:
    2058             :      * This is only safe to do because we hold a session lock on the main
    2059             :      * relation that prevents concurrent deletion.
    2060             :      */
    2061      115188 :     if (OidIsValid(params->toast_parent))
    2062        7408 :         priv_relid = params->toast_parent;
    2063             :     else
    2064      107780 :         priv_relid = RelationGetRelid(rel);
    2065             : 
    2066             :     /*
    2067             :      * Check if relation needs to be skipped based on privileges.  This check
    2068             :      * happens also when building the relation list to vacuum for a manual
    2069             :      * operation, and needs to be done additionally here as VACUUM could
    2070             :      * happen across multiple transactions where privileges could have changed
    2071             :      * in-between.  Make sure to only generate logs for VACUUM in this case.
    2072             :      */
    2073      115188 :     if (!vacuum_is_permitted_for_relation(priv_relid,
    2074             :                                           rel->rd_rel,
    2075      115188 :                                           params->options & ~VACOPT_ANALYZE))
    2076             :     {
    2077          72 :         relation_close(rel, lmode);
    2078          72 :         PopActiveSnapshot();
    2079          72 :         CommitTransactionCommand();
    2080          72 :         return false;
    2081             :     }
    2082             : 
    2083             :     /*
    2084             :      * Check that it's of a vacuumable relkind.
    2085             :      */
    2086      115116 :     if (rel->rd_rel->relkind != RELKIND_RELATION &&
    2087       42410 :         rel->rd_rel->relkind != RELKIND_MATVIEW &&
    2088       42402 :         rel->rd_rel->relkind != RELKIND_TOASTVALUE &&
    2089         180 :         rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
    2090             :     {
    2091           2 :         ereport(WARNING,
    2092             :                 (errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
    2093             :                         RelationGetRelationName(rel))));
    2094           2 :         relation_close(rel, lmode);
    2095           2 :         PopActiveSnapshot();
    2096           2 :         CommitTransactionCommand();
    2097           2 :         return false;
    2098             :     }
    2099             : 
    2100             :     /*
    2101             :      * Silently ignore tables that are temp tables of other backends ---
    2102             :      * trying to vacuum these will lead to great unhappiness, since their
    2103             :      * contents are probably not up-to-date on disk.  (We don't throw a
    2104             :      * warning here; it would just lead to chatter during a database-wide
    2105             :      * VACUUM.)
    2106             :      */
    2107      115114 :     if (RELATION_IS_OTHER_TEMP(rel))
    2108             :     {
    2109           2 :         relation_close(rel, lmode);
    2110           2 :         PopActiveSnapshot();
    2111           2 :         CommitTransactionCommand();
    2112           2 :         return false;
    2113             :     }
    2114             : 
    2115             :     /*
    2116             :      * Silently ignore partitioned tables as there is no work to be done.  The
    2117             :      * useful work is on their child partitions, which have been queued up for
    2118             :      * us separately.
    2119             :      */
    2120      115112 :     if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
    2121             :     {
    2122         178 :         relation_close(rel, lmode);
    2123         178 :         PopActiveSnapshot();
    2124         178 :         CommitTransactionCommand();
    2125             :         /* It's OK to proceed with ANALYZE on this table */
    2126         178 :         return true;
    2127             :     }
    2128             : 
    2129             :     /*
    2130             :      * Get a session-level lock too. This will protect our access to the
    2131             :      * relation across multiple transactions, so that we can vacuum the
    2132             :      * relation's TOAST table (if any) secure in the knowledge that no one is
    2133             :      * deleting the parent relation.
    2134             :      *
    2135             :      * NOTE: this cannot block, even if someone else is waiting for access,
    2136             :      * because the lock manager knows that both lock requests are from the
    2137             :      * same process.
    2138             :      */
    2139      114934 :     lockrelid = rel->rd_lockInfo.lockRelId;
    2140      114934 :     LockRelationIdForSession(&lockrelid, lmode);
    2141             : 
    2142             :     /*
    2143             :      * Set index_cleanup option based on index_cleanup reloption if it wasn't
    2144             :      * specified in VACUUM command, or when running in an autovacuum worker
    2145             :      */
    2146      114934 :     if (params->index_cleanup == VACOPTVALUE_UNSPECIFIED)
    2147             :     {
    2148             :         StdRdOptIndexCleanup vacuum_index_cleanup;
    2149             : 
    2150       99276 :         if (rel->rd_options == NULL)
    2151       97746 :             vacuum_index_cleanup = STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO;
    2152             :         else
    2153        1530 :             vacuum_index_cleanup =
    2154        1530 :                 ((StdRdOptions *) rel->rd_options)->vacuum_index_cleanup;
    2155             : 
    2156       99276 :         if (vacuum_index_cleanup == STDRD_OPTION_VACUUM_INDEX_CLEANUP_AUTO)
    2157       99252 :             params->index_cleanup = VACOPTVALUE_AUTO;
    2158          24 :         else if (vacuum_index_cleanup == STDRD_OPTION_VACUUM_INDEX_CLEANUP_ON)
    2159          12 :             params->index_cleanup = VACOPTVALUE_ENABLED;
    2160             :         else
    2161             :         {
    2162             :             Assert(vacuum_index_cleanup ==
    2163             :                    STDRD_OPTION_VACUUM_INDEX_CLEANUP_OFF);
    2164          12 :             params->index_cleanup = VACOPTVALUE_DISABLED;
    2165             :         }
    2166             :     }
    2167             : 
    2168             :     /*
    2169             :      * Set truncate option based on truncate reloption if it wasn't specified
    2170             :      * in VACUUM command, or when running in an autovacuum worker
    2171             :      */
    2172      114934 :     if (params->truncate == VACOPTVALUE_UNSPECIFIED)
    2173             :     {
    2174       99302 :         if (rel->rd_options == NULL ||
    2175        1530 :             ((StdRdOptions *) rel->rd_options)->vacuum_truncate)
    2176       99296 :             params->truncate = VACOPTVALUE_ENABLED;
    2177             :         else
    2178           6 :             params->truncate = VACOPTVALUE_DISABLED;
    2179             :     }
    2180             : 
    2181             :     /*
    2182             :      * Remember the relation's TOAST relation for later, if the caller asked
    2183             :      * us to process it.  In VACUUM FULL, though, the toast table is
    2184             :      * automatically rebuilt by cluster_rel so we shouldn't recurse to it,
    2185             :      * unless PROCESS_MAIN is disabled.
    2186             :      */
    2187      114934 :     if ((params->options & VACOPT_PROCESS_TOAST) != 0 &&
    2188       21144 :         ((params->options & VACOPT_FULL) == 0 ||
    2189         364 :          (params->options & VACOPT_PROCESS_MAIN) == 0))
    2190       20786 :         toast_relid = rel->rd_rel->reltoastrelid;
    2191             :     else
    2192       94148 :         toast_relid = InvalidOid;
    2193             : 
    2194             :     /*
    2195             :      * Switch to the table owner's userid, so that any index functions are run
    2196             :      * as that user.  Also lock down security-restricted operations and
    2197             :      * arrange to make GUC variable changes local to this command. (This is
    2198             :      * unnecessary, but harmless, for lazy VACUUM.)
    2199             :      */
    2200      114934 :     GetUserIdAndSecContext(&save_userid, &save_sec_context);
    2201      114934 :     SetUserIdAndSecContext(rel->rd_rel->relowner,
    2202             :                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
    2203      114934 :     save_nestlevel = NewGUCNestLevel();
    2204      114934 :     RestrictSearchPath();
    2205             : 
    2206             :     /*
    2207             :      * If PROCESS_MAIN is set (the default), it's time to vacuum the main
    2208             :      * relation.  Otherwise, we can skip this part.  If processing the TOAST
    2209             :      * table is required (e.g., PROCESS_TOAST is set), we force PROCESS_MAIN
    2210             :      * to be set when we recurse to the TOAST table.
    2211             :      */
    2212      114934 :     if (params->options & VACOPT_PROCESS_MAIN)
    2213             :     {
    2214             :         /*
    2215             :          * Do the actual work --- either FULL or "lazy" vacuum
    2216             :          */
    2217      114780 :         if (params->options & VACOPT_FULL)
    2218             :         {
    2219         358 :             ClusterParams cluster_params = {0};
    2220             : 
    2221         358 :             if ((params->options & VACOPT_VERBOSE) != 0)
    2222           2 :                 cluster_params.options |= CLUOPT_VERBOSE;
    2223             : 
    2224             :             /* VACUUM FULL is now a variant of CLUSTER; see cluster.c */
    2225         358 :             cluster_rel(rel, InvalidOid, &cluster_params);
    2226             :             /* cluster_rel closes the relation, but keeps lock */
    2227             : 
    2228         352 :             rel = NULL;
    2229             :         }
    2230             :         else
    2231      114422 :             table_relation_vacuum(rel, params, bstrategy);
    2232             :     }
    2233             : 
    2234             :     /* Roll back any GUC changes executed by index functions */
    2235      114928 :     AtEOXact_GUC(false, save_nestlevel);
    2236             : 
    2237             :     /* Restore userid and security context */
    2238      114928 :     SetUserIdAndSecContext(save_userid, save_sec_context);
    2239             : 
    2240             :     /* all done with this class, but hold lock until commit */
    2241      114928 :     if (rel)
    2242      114576 :         relation_close(rel, NoLock);
    2243             : 
    2244             :     /*
    2245             :      * Complete the transaction and free all temporary memory used.
    2246             :      */
    2247      114928 :     PopActiveSnapshot();
    2248      114928 :     CommitTransactionCommand();
    2249             : 
    2250             :     /*
    2251             :      * If the relation has a secondary toast rel, vacuum that too while we
    2252             :      * still hold the session lock on the main table.  Note however that
    2253             :      * "analyze" will not get done on the toast table.  This is good, because
    2254             :      * the toaster always uses hardcoded index access and statistics are
    2255             :      * totally unimportant for toast relations.
    2256             :      */
    2257      114928 :     if (toast_relid != InvalidOid)
    2258             :     {
    2259             :         VacuumParams toast_vacuum_params;
    2260             : 
    2261             :         /*
    2262             :          * Force VACOPT_PROCESS_MAIN so vacuum_rel() processes it.  Likewise,
    2263             :          * set toast_parent so that the privilege checks are done on the main
    2264             :          * relation.  NB: This is only safe to do because we hold a session
    2265             :          * lock on the main relation that prevents concurrent deletion.
    2266             :          */
    2267        7408 :         memcpy(&toast_vacuum_params, params, sizeof(VacuumParams));
    2268        7408 :         toast_vacuum_params.options |= VACOPT_PROCESS_MAIN;
    2269        7408 :         toast_vacuum_params.toast_parent = relid;
    2270             : 
    2271        7408 :         vacuum_rel(toast_relid, NULL, &toast_vacuum_params, bstrategy);
    2272             :     }
    2273             : 
    2274             :     /*
    2275             :      * Now release the session-level lock on the main table.
    2276             :      */
    2277      114928 :     UnlockRelationIdForSession(&lockrelid, lmode);
    2278             : 
    2279             :     /* Report that we really did it. */
    2280      114928 :     return true;
    2281             : }
    2282             : 
    2283             : 
    2284             : /*
    2285             :  * Open all the vacuumable indexes of the given relation, obtaining the
    2286             :  * specified kind of lock on each.  Return an array of Relation pointers for
    2287             :  * the indexes into *Irel, and the number of indexes into *nindexes.
    2288             :  *
    2289             :  * We consider an index vacuumable if it is marked insertable (indisready).
    2290             :  * If it isn't, probably a CREATE INDEX CONCURRENTLY command failed early in
    2291             :  * execution, and what we have is too corrupt to be processable.  We will
    2292             :  * vacuum even if the index isn't indisvalid; this is important because in a
    2293             :  * unique index, uniqueness checks will be performed anyway and had better not
    2294             :  * hit dangling index pointers.
    2295             :  */
    2296             : void
    2297      127324 : vac_open_indexes(Relation relation, LOCKMODE lockmode,
    2298             :                  int *nindexes, Relation **Irel)
    2299             : {
    2300             :     List       *indexoidlist;
    2301             :     ListCell   *indexoidscan;
    2302             :     int         i;
    2303             : 
    2304             :     Assert(lockmode != NoLock);
    2305             : 
    2306      127324 :     indexoidlist = RelationGetIndexList(relation);
    2307             : 
    2308             :     /* allocate enough memory for all indexes */
    2309      127324 :     i = list_length(indexoidlist);
    2310             : 
    2311      127324 :     if (i > 0)
    2312      118752 :         *Irel = (Relation *) palloc(i * sizeof(Relation));
    2313             :     else
    2314        8572 :         *Irel = NULL;
    2315             : 
    2316             :     /* collect just the ready indexes */
    2317      127324 :     i = 0;
    2318      316116 :     foreach(indexoidscan, indexoidlist)
    2319             :     {
    2320      188792 :         Oid         indexoid = lfirst_oid(indexoidscan);
    2321             :         Relation    indrel;
    2322             : 
    2323      188792 :         indrel = index_open(indexoid, lockmode);
    2324      188792 :         if (indrel->rd_index->indisready)
    2325      188792 :             (*Irel)[i++] = indrel;
    2326             :         else
    2327           0 :             index_close(indrel, lockmode);
    2328             :     }
    2329             : 
    2330      127324 :     *nindexes = i;
    2331             : 
    2332      127324 :     list_free(indexoidlist);
    2333      127324 : }
    2334             : 
    2335             : /*
    2336             :  * Release the resources acquired by vac_open_indexes.  Optionally release
    2337             :  * the locks (say NoLock to keep 'em).
    2338             :  */
    2339             : void
    2340      128108 : vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
    2341             : {
    2342      128108 :     if (Irel == NULL)
    2343        9364 :         return;
    2344             : 
    2345      307520 :     while (nindexes--)
    2346             :     {
    2347      188776 :         Relation    ind = Irel[nindexes];
    2348             : 
    2349      188776 :         index_close(ind, lockmode);
    2350             :     }
    2351      118744 :     pfree(Irel);
    2352             : }
    2353             : 
    2354             : /*
    2355             :  * vacuum_delay_point --- check for interrupts and cost-based delay.
    2356             :  *
    2357             :  * This should be called in each major loop of VACUUM processing,
    2358             :  * typically once per page processed.
    2359             :  */
    2360             : void
    2361    70316542 : vacuum_delay_point(void)
    2362             : {
    2363    70316542 :     double      msec = 0;
    2364             : 
    2365             :     /* Always check for interrupts */
    2366    70316542 :     CHECK_FOR_INTERRUPTS();
    2367             : 
    2368    70316542 :     if (InterruptPending ||
    2369    70316542 :         (!VacuumCostActive && !ConfigReloadPending))
    2370    63397674 :         return;
    2371             : 
    2372             :     /*
    2373             :      * Autovacuum workers should reload the configuration file if requested.
    2374             :      * This allows changes to [autovacuum_]vacuum_cost_limit and
    2375             :      * [autovacuum_]vacuum_cost_delay to take effect while a table is being
    2376             :      * vacuumed or analyzed.
    2377             :      */
    2378     6918868 :     if (ConfigReloadPending && AmAutoVacuumWorkerProcess())
    2379             :     {
    2380           0 :         ConfigReloadPending = false;
    2381           0 :         ProcessConfigFile(PGC_SIGHUP);
    2382           0 :         VacuumUpdateCosts();
    2383             :     }
    2384             : 
    2385             :     /*
    2386             :      * If we disabled cost-based delays after reloading the config file,
    2387             :      * return.
    2388             :      */
    2389     6918868 :     if (!VacuumCostActive)
    2390           0 :         return;
    2391             : 
    2392             :     /*
    2393             :      * For parallel vacuum, the delay is computed based on the shared cost
    2394             :      * balance.  See compute_parallel_delay.
    2395             :      */
    2396     6918868 :     if (VacuumSharedCostBalance != NULL)
    2397           0 :         msec = compute_parallel_delay();
    2398     6918868 :     else if (VacuumCostBalance >= vacuum_cost_limit)
    2399        4062 :         msec = vacuum_cost_delay * VacuumCostBalance / vacuum_cost_limit;
    2400             : 
    2401             :     /* Nap if appropriate */
    2402     6918868 :     if (msec > 0)
    2403             :     {
    2404        4062 :         if (msec > vacuum_cost_delay * 4)
    2405          10 :             msec = vacuum_cost_delay * 4;
    2406             : 
    2407        4062 :         pgstat_report_wait_start(WAIT_EVENT_VACUUM_DELAY);
    2408        4062 :         pg_usleep(msec * 1000);
    2409        4062 :         pgstat_report_wait_end();
    2410             : 
    2411             :         /*
    2412             :          * We don't want to ignore postmaster death during very long vacuums
    2413             :          * with vacuum_cost_delay configured.  We can't use the usual
    2414             :          * WaitLatch() approach here because we want microsecond-based sleep
    2415             :          * durations above.
    2416             :          */
    2417        4062 :         if (IsUnderPostmaster && !PostmasterIsAlive())
    2418           0 :             exit(1);
    2419             : 
    2420        4062 :         VacuumCostBalance = 0;
    2421             : 
    2422             :         /*
    2423             :          * Balance and update limit values for autovacuum workers. We must do
    2424             :          * this periodically, as the number of workers across which we are
    2425             :          * balancing the limit may have changed.
    2426             :          *
    2427             :          * TODO: There may be better criteria for determining when to do this
    2428             :          * besides "check after napping".
    2429             :          */
    2430        4062 :         AutoVacuumUpdateCostLimit();
    2431             : 
    2432             :         /* Might have gotten an interrupt while sleeping */
    2433        4062 :         CHECK_FOR_INTERRUPTS();
    2434             :     }
    2435             : }
    2436             : 
    2437             : /*
    2438             :  * Computes the vacuum delay for parallel workers.
    2439             :  *
    2440             :  * The basic idea of a cost-based delay for parallel vacuum is to allow each
    2441             :  * worker to sleep in proportion to the share of work it's done.  We achieve this
    2442             :  * by allowing all parallel vacuum workers including the leader process to
    2443             :  * have a shared view of cost related parameters (mainly VacuumCostBalance).
    2444             :  * We allow each worker to update it as and when it has incurred any cost and
    2445             :  * then based on that decide whether it needs to sleep.  We compute the time
    2446             :  * to sleep for a worker based on the cost it has incurred
    2447             :  * (VacuumCostBalanceLocal) and then reduce the VacuumSharedCostBalance by
    2448             :  * that amount.  This avoids putting to sleep those workers which have done less
    2449             :  * I/O than other workers and therefore ensure that workers
    2450             :  * which are doing more I/O got throttled more.
    2451             :  *
    2452             :  * We allow a worker to sleep only if it has performed I/O above a certain
    2453             :  * threshold, which is calculated based on the number of active workers
    2454             :  * (VacuumActiveNWorkers), and the overall cost balance is more than
    2455             :  * VacuumCostLimit set by the system.  Testing reveals that we achieve
    2456             :  * the required throttling if we force a worker that has done more than 50%
    2457             :  * of its share of work to sleep.
    2458             :  */
    2459             : static double
    2460           0 : compute_parallel_delay(void)
    2461             : {
    2462           0 :     double      msec = 0;
    2463             :     uint32      shared_balance;
    2464             :     int         nworkers;
    2465             : 
    2466             :     /* Parallel vacuum must be active */
    2467             :     Assert(VacuumSharedCostBalance);
    2468             : 
    2469           0 :     nworkers = pg_atomic_read_u32(VacuumActiveNWorkers);
    2470             : 
    2471             :     /* At least count itself */
    2472             :     Assert(nworkers >= 1);
    2473             : 
    2474             :     /* Update the shared cost balance value atomically */
    2475           0 :     shared_balance = pg_atomic_add_fetch_u32(VacuumSharedCostBalance, VacuumCostBalance);
    2476             : 
    2477             :     /* Compute the total local balance for the current worker */
    2478           0 :     VacuumCostBalanceLocal += VacuumCostBalance;
    2479             : 
    2480           0 :     if ((shared_balance >= vacuum_cost_limit) &&
    2481           0 :         (VacuumCostBalanceLocal > 0.5 * ((double) vacuum_cost_limit / nworkers)))
    2482             :     {
    2483             :         /* Compute sleep time based on the local cost balance */
    2484           0 :         msec = vacuum_cost_delay * VacuumCostBalanceLocal / vacuum_cost_limit;
    2485           0 :         pg_atomic_sub_fetch_u32(VacuumSharedCostBalance, VacuumCostBalanceLocal);
    2486           0 :         VacuumCostBalanceLocal = 0;
    2487             :     }
    2488             : 
    2489             :     /*
    2490             :      * Reset the local balance as we accumulated it into the shared value.
    2491             :      */
    2492           0 :     VacuumCostBalance = 0;
    2493             : 
    2494           0 :     return msec;
    2495             : }
    2496             : 
    2497             : /*
    2498             :  * A wrapper function of defGetBoolean().
    2499             :  *
    2500             :  * This function returns VACOPTVALUE_ENABLED and VACOPTVALUE_DISABLED instead
    2501             :  * of true and false.
    2502             :  */
    2503             : static VacOptValue
    2504         316 : get_vacoptval_from_boolean(DefElem *def)
    2505             : {
    2506         316 :     return defGetBoolean(def) ? VACOPTVALUE_ENABLED : VACOPTVALUE_DISABLED;
    2507             : }
    2508             : 
    2509             : /*
    2510             :  *  vac_bulkdel_one_index() -- bulk-deletion for index relation.
    2511             :  *
    2512             :  * Returns bulk delete stats derived from input stats
    2513             :  */
    2514             : IndexBulkDeleteResult *
    2515        2058 : vac_bulkdel_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat,
    2516             :                       TidStore *dead_items, VacDeadItemsInfo *dead_items_info)
    2517             : {
    2518             :     /* Do bulk deletion */
    2519        2058 :     istat = index_bulk_delete(ivinfo, istat, vac_tid_reaped,
    2520             :                               dead_items);
    2521             : 
    2522        2058 :     ereport(ivinfo->message_level,
    2523             :             (errmsg("scanned index \"%s\" to remove %lld row versions",
    2524             :                     RelationGetRelationName(ivinfo->index),
    2525             :                     (long long) dead_items_info->num_items)));
    2526             : 
    2527        2058 :     return istat;
    2528             : }
    2529             : 
    2530             : /*
    2531             :  *  vac_cleanup_one_index() -- do post-vacuum cleanup for index relation.
    2532             :  *
    2533             :  * Returns bulk delete stats derived from input stats
    2534             :  */
    2535             : IndexBulkDeleteResult *
    2536      140800 : vac_cleanup_one_index(IndexVacuumInfo *ivinfo, IndexBulkDeleteResult *istat)
    2537             : {
    2538      140800 :     istat = index_vacuum_cleanup(ivinfo, istat);
    2539             : 
    2540      140800 :     if (istat)
    2541        2316 :         ereport(ivinfo->message_level,
    2542             :                 (errmsg("index \"%s\" now contains %.0f row versions in %u pages",
    2543             :                         RelationGetRelationName(ivinfo->index),
    2544             :                         istat->num_index_tuples,
    2545             :                         istat->num_pages),
    2546             :                  errdetail("%.0f index row versions were removed.\n"
    2547             :                            "%u index pages were newly deleted.\n"
    2548             :                            "%u index pages are currently deleted, of which %u are currently reusable.",
    2549             :                            istat->tuples_removed,
    2550             :                            istat->pages_newly_deleted,
    2551             :                            istat->pages_deleted, istat->pages_free)));
    2552             : 
    2553      140800 :     return istat;
    2554             : }
    2555             : 
    2556             : /*
    2557             :  *  vac_tid_reaped() -- is a particular tid deletable?
    2558             :  *
    2559             :  *      This has the right signature to be an IndexBulkDeleteCallback.
    2560             :  */
    2561             : static bool
    2562     6032946 : vac_tid_reaped(ItemPointer itemptr, void *state)
    2563             : {
    2564     6032946 :     TidStore   *dead_items = (TidStore *) state;
    2565             : 
    2566     6032946 :     return TidStoreIsMember(dead_items, itemptr);
    2567             : }

Generated by: LCOV version 1.14