LCOV - code coverage report
Current view: top level - src/backend/postmaster - autovacuum.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 739 933 79.2 %
Date: 2024-07-19 16:11:31 Functions: 30 31 96.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * autovacuum.c
       4             :  *
       5             :  * PostgreSQL Integrated Autovacuum Daemon
       6             :  *
       7             :  * The autovacuum system is structured in two different kinds of processes: the
       8             :  * autovacuum launcher and the autovacuum worker.  The launcher is an
       9             :  * always-running process, started by the postmaster when the autovacuum GUC
      10             :  * parameter is set.  The launcher schedules autovacuum workers to be started
      11             :  * when appropriate.  The workers are the processes which execute the actual
      12             :  * vacuuming; they connect to a database as determined in the launcher, and
      13             :  * once connected they examine the catalogs to select the tables to vacuum.
      14             :  *
      15             :  * The autovacuum launcher cannot start the worker processes by itself,
      16             :  * because doing so would cause robustness issues (namely, failure to shut
      17             :  * them down on exceptional conditions, and also, since the launcher is
      18             :  * connected to shared memory and is thus subject to corruption there, it is
      19             :  * not as robust as the postmaster).  So it leaves that task to the postmaster.
      20             :  *
      21             :  * There is an autovacuum shared memory area, where the launcher stores
      22             :  * information about the database it wants vacuumed.  When it wants a new
      23             :  * worker to start, it sets a flag in shared memory and sends a signal to the
      24             :  * postmaster.  Then postmaster knows nothing more than it must start a worker;
      25             :  * so it forks a new child, which turns into a worker.  This new process
      26             :  * connects to shared memory, and there it can inspect the information that the
      27             :  * launcher has set up.
      28             :  *
      29             :  * If the fork() call fails in the postmaster, it sets a flag in the shared
      30             :  * memory area, and sends a signal to the launcher.  The launcher, upon
      31             :  * noticing the flag, can try starting the worker again by resending the
      32             :  * signal.  Note that the failure can only be transient (fork failure due to
      33             :  * high load, memory pressure, too many processes, etc); more permanent
      34             :  * problems, like failure to connect to a database, are detected later in the
      35             :  * worker and dealt with just by having the worker exit normally.  The launcher
      36             :  * will launch a new worker again later, per schedule.
      37             :  *
      38             :  * When the worker is done vacuuming it sends SIGUSR2 to the launcher.  The
      39             :  * launcher then wakes up and is able to launch another worker, if the schedule
      40             :  * is so tight that a new worker is needed immediately.  At this time the
      41             :  * launcher can also balance the settings for the various remaining workers'
      42             :  * cost-based vacuum delay feature.
      43             :  *
      44             :  * Note that there can be more than one worker in a database concurrently.
      45             :  * They will store the table they are currently vacuuming in shared memory, so
      46             :  * that other workers avoid being blocked waiting for the vacuum lock for that
      47             :  * table.  They will also fetch the last time the table was vacuumed from
      48             :  * pgstats just before vacuuming each table, to avoid vacuuming a table that
      49             :  * was just finished being vacuumed by another worker and thus is no longer
      50             :  * noted in shared memory.  However, there is a small window (due to not yet
      51             :  * holding the relation lock) during which a worker may choose a table that was
      52             :  * already vacuumed; this is a bug in the current design.
      53             :  *
      54             :  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
      55             :  * Portions Copyright (c) 1994, Regents of the University of California
      56             :  *
      57             :  *
      58             :  * IDENTIFICATION
      59             :  *    src/backend/postmaster/autovacuum.c
      60             :  *
      61             :  *-------------------------------------------------------------------------
      62             :  */
      63             : #include "postgres.h"
      64             : 
      65             : #include <signal.h>
      66             : #include <sys/time.h>
      67             : #include <unistd.h>
      68             : 
      69             : #include "access/heapam.h"
      70             : #include "access/htup_details.h"
      71             : #include "access/multixact.h"
      72             : #include "access/reloptions.h"
      73             : #include "access/tableam.h"
      74             : #include "access/transam.h"
      75             : #include "access/xact.h"
      76             : #include "catalog/dependency.h"
      77             : #include "catalog/namespace.h"
      78             : #include "catalog/pg_database.h"
      79             : #include "catalog/pg_namespace.h"
      80             : #include "commands/dbcommands.h"
      81             : #include "commands/vacuum.h"
      82             : #include "common/int.h"
      83             : #include "lib/ilist.h"
      84             : #include "libpq/pqsignal.h"
      85             : #include "miscadmin.h"
      86             : #include "nodes/makefuncs.h"
      87             : #include "pgstat.h"
      88             : #include "postmaster/autovacuum.h"
      89             : #include "postmaster/interrupt.h"
      90             : #include "postmaster/postmaster.h"
      91             : #include "storage/bufmgr.h"
      92             : #include "storage/ipc.h"
      93             : #include "storage/latch.h"
      94             : #include "storage/lmgr.h"
      95             : #include "storage/pmsignal.h"
      96             : #include "storage/proc.h"
      97             : #include "storage/procsignal.h"
      98             : #include "storage/smgr.h"
      99             : #include "tcop/tcopprot.h"
     100             : #include "utils/fmgroids.h"
     101             : #include "utils/fmgrprotos.h"
     102             : #include "utils/guc_hooks.h"
     103             : #include "utils/injection_point.h"
     104             : #include "utils/lsyscache.h"
     105             : #include "utils/memutils.h"
     106             : #include "utils/ps_status.h"
     107             : #include "utils/rel.h"
     108             : #include "utils/snapmgr.h"
     109             : #include "utils/syscache.h"
     110             : #include "utils/timeout.h"
     111             : #include "utils/timestamp.h"
     112             : 
     113             : 
     114             : /*
     115             :  * GUC parameters
     116             :  */
     117             : bool        autovacuum_start_daemon = false;
     118             : int         autovacuum_max_workers;
     119             : int         autovacuum_work_mem = -1;
     120             : int         autovacuum_naptime;
     121             : int         autovacuum_vac_thresh;
     122             : double      autovacuum_vac_scale;
     123             : int         autovacuum_vac_ins_thresh;
     124             : double      autovacuum_vac_ins_scale;
     125             : int         autovacuum_anl_thresh;
     126             : double      autovacuum_anl_scale;
     127             : int         autovacuum_freeze_max_age;
     128             : int         autovacuum_multixact_freeze_max_age;
     129             : 
     130             : double      autovacuum_vac_cost_delay;
     131             : int         autovacuum_vac_cost_limit;
     132             : 
     133             : int         Log_autovacuum_min_duration = 600000;
     134             : 
     135             : /* the minimum allowed time between two awakenings of the launcher */
     136             : #define MIN_AUTOVAC_SLEEPTIME 100.0 /* milliseconds */
     137             : #define MAX_AUTOVAC_SLEEPTIME 300   /* seconds */
     138             : 
     139             : /*
     140             :  * Variables to save the cost-related storage parameters for the current
     141             :  * relation being vacuumed by this autovacuum worker. Using these, we can
     142             :  * ensure we don't overwrite the values of vacuum_cost_delay and
     143             :  * vacuum_cost_limit after reloading the configuration file. They are
     144             :  * initialized to "invalid" values to indicate that no cost-related storage
     145             :  * parameters were specified and will be set in do_autovacuum() after checking
     146             :  * the storage parameters in table_recheck_autovac().
     147             :  */
     148             : static double av_storage_param_cost_delay = -1;
     149             : static int  av_storage_param_cost_limit = -1;
     150             : 
     151             : /* Flags set by signal handlers */
     152             : static volatile sig_atomic_t got_SIGUSR2 = false;
     153             : 
     154             : /* Comparison points for determining whether freeze_max_age is exceeded */
     155             : static TransactionId recentXid;
     156             : static MultiXactId recentMulti;
     157             : 
     158             : /* Default freeze ages to use for autovacuum (varies by database) */
     159             : static int  default_freeze_min_age;
     160             : static int  default_freeze_table_age;
     161             : static int  default_multixact_freeze_min_age;
     162             : static int  default_multixact_freeze_table_age;
     163             : 
     164             : /* Memory context for long-lived data */
     165             : static MemoryContext AutovacMemCxt;
     166             : 
     167             : /* struct to keep track of databases in launcher */
     168             : typedef struct avl_dbase
     169             : {
     170             :     Oid         adl_datid;      /* hash key -- must be first */
     171             :     TimestampTz adl_next_worker;
     172             :     int         adl_score;
     173             :     dlist_node  adl_node;
     174             : } avl_dbase;
     175             : 
     176             : /* struct to keep track of databases in worker */
     177             : typedef struct avw_dbase
     178             : {
     179             :     Oid         adw_datid;
     180             :     char       *adw_name;
     181             :     TransactionId adw_frozenxid;
     182             :     MultiXactId adw_minmulti;
     183             :     PgStat_StatDBEntry *adw_entry;
     184             : } avw_dbase;
     185             : 
     186             : /* struct to keep track of tables to vacuum and/or analyze, in 1st pass */
     187             : typedef struct av_relation
     188             : {
     189             :     Oid         ar_toastrelid;  /* hash key - must be first */
     190             :     Oid         ar_relid;
     191             :     bool        ar_hasrelopts;
     192             :     AutoVacOpts ar_reloptions;  /* copy of AutoVacOpts from the main table's
     193             :                                  * reloptions, or NULL if none */
     194             : } av_relation;
     195             : 
     196             : /* struct to keep track of tables to vacuum and/or analyze, after rechecking */
     197             : typedef struct autovac_table
     198             : {
     199             :     Oid         at_relid;
     200             :     VacuumParams at_params;
     201             :     double      at_storage_param_vac_cost_delay;
     202             :     int         at_storage_param_vac_cost_limit;
     203             :     bool        at_dobalance;
     204             :     bool        at_sharedrel;
     205             :     char       *at_relname;
     206             :     char       *at_nspname;
     207             :     char       *at_datname;
     208             : } autovac_table;
     209             : 
     210             : /*-------------
     211             :  * This struct holds information about a single worker's whereabouts.  We keep
     212             :  * an array of these in shared memory, sized according to
     213             :  * autovacuum_max_workers.
     214             :  *
     215             :  * wi_links     entry into free list or running list
     216             :  * wi_dboid     OID of the database this worker is supposed to work on
     217             :  * wi_tableoid  OID of the table currently being vacuumed, if any
     218             :  * wi_sharedrel flag indicating whether table is marked relisshared
     219             :  * wi_proc      pointer to PGPROC of the running worker, NULL if not started
     220             :  * wi_launchtime Time at which this worker was launched
     221             :  * wi_dobalance Whether this worker should be included in balance calculations
     222             :  *
     223             :  * All fields are protected by AutovacuumLock, except for wi_tableoid and
     224             :  * wi_sharedrel which are protected by AutovacuumScheduleLock (note these
     225             :  * two fields are read-only for everyone except that worker itself).
     226             :  *-------------
     227             :  */
     228             : typedef struct WorkerInfoData
     229             : {
     230             :     dlist_node  wi_links;
     231             :     Oid         wi_dboid;
     232             :     Oid         wi_tableoid;
     233             :     PGPROC     *wi_proc;
     234             :     TimestampTz wi_launchtime;
     235             :     pg_atomic_flag wi_dobalance;
     236             :     bool        wi_sharedrel;
     237             : } WorkerInfoData;
     238             : 
     239             : typedef struct WorkerInfoData *WorkerInfo;
     240             : 
     241             : /*
     242             :  * Possible signals received by the launcher from remote processes.  These are
     243             :  * stored atomically in shared memory so that other processes can set them
     244             :  * without locking.
     245             :  */
     246             : typedef enum
     247             : {
     248             :     AutoVacForkFailed,          /* failed trying to start a worker */
     249             :     AutoVacRebalance,           /* rebalance the cost limits */
     250             :     AutoVacNumSignals,          /* must be last */
     251             : }           AutoVacuumSignal;
     252             : 
     253             : /*
     254             :  * Autovacuum workitem array, stored in AutoVacuumShmem->av_workItems.  This
     255             :  * list is mostly protected by AutovacuumLock, except that if an item is
     256             :  * marked 'active' other processes must not modify the work-identifying
     257             :  * members.
     258             :  */
     259             : typedef struct AutoVacuumWorkItem
     260             : {
     261             :     AutoVacuumWorkItemType avw_type;
     262             :     bool        avw_used;       /* below data is valid */
     263             :     bool        avw_active;     /* being processed */
     264             :     Oid         avw_database;
     265             :     Oid         avw_relation;
     266             :     BlockNumber avw_blockNumber;
     267             : } AutoVacuumWorkItem;
     268             : 
     269             : #define NUM_WORKITEMS   256
     270             : 
     271             : /*-------------
     272             :  * The main autovacuum shmem struct.  On shared memory we store this main
     273             :  * struct and the array of WorkerInfo structs.  This struct keeps:
     274             :  *
     275             :  * av_signal        set by other processes to indicate various conditions
     276             :  * av_launcherpid   the PID of the autovacuum launcher
     277             :  * av_freeWorkers   the WorkerInfo freelist
     278             :  * av_runningWorkers the WorkerInfo non-free queue
     279             :  * av_startingWorker pointer to WorkerInfo currently being started (cleared by
     280             :  *                  the worker itself as soon as it's up and running)
     281             :  * av_workItems     work item array
     282             :  * av_nworkersForBalance the number of autovacuum workers to use when
     283             :  *                  calculating the per worker cost limit
     284             :  *
     285             :  * This struct is protected by AutovacuumLock, except for av_signal and parts
     286             :  * of the worker list (see above).
     287             :  *-------------
     288             :  */
     289             : typedef struct
     290             : {
     291             :     sig_atomic_t av_signal[AutoVacNumSignals];
     292             :     pid_t       av_launcherpid;
     293             :     dlist_head  av_freeWorkers;
     294             :     dlist_head  av_runningWorkers;
     295             :     WorkerInfo  av_startingWorker;
     296             :     AutoVacuumWorkItem av_workItems[NUM_WORKITEMS];
     297             :     pg_atomic_uint32 av_nworkersForBalance;
     298             : } AutoVacuumShmemStruct;
     299             : 
     300             : static AutoVacuumShmemStruct *AutoVacuumShmem;
     301             : 
     302             : /*
     303             :  * the database list (of avl_dbase elements) in the launcher, and the context
     304             :  * that contains it
     305             :  */
     306             : static dlist_head DatabaseList = DLIST_STATIC_INIT(DatabaseList);
     307             : static MemoryContext DatabaseListCxt = NULL;
     308             : 
     309             : /* Pointer to my own WorkerInfo, valid on each worker */
     310             : static WorkerInfo MyWorkerInfo = NULL;
     311             : 
     312             : /* PID of launcher, valid only in worker while shutting down */
     313             : int         AutovacuumLauncherPid = 0;
     314             : 
     315             : static Oid  do_start_worker(void);
     316             : static void HandleAutoVacLauncherInterrupts(void);
     317             : static void AutoVacLauncherShutdown(void) pg_attribute_noreturn();
     318             : static void launcher_determine_sleep(bool canlaunch, bool recursing,
     319             :                                      struct timeval *nap);
     320             : static void launch_worker(TimestampTz now);
     321             : static List *get_database_list(void);
     322             : static void rebuild_database_list(Oid newdb);
     323             : static int  db_comparator(const void *a, const void *b);
     324             : static void autovac_recalculate_workers_for_balance(void);
     325             : 
     326             : static void do_autovacuum(void);
     327             : static void FreeWorkerInfo(int code, Datum arg);
     328             : 
     329             : static autovac_table *table_recheck_autovac(Oid relid, HTAB *table_toast_map,
     330             :                                             TupleDesc pg_class_desc,
     331             :                                             int effective_multixact_freeze_max_age);
     332             : static void recheck_relation_needs_vacanalyze(Oid relid, AutoVacOpts *avopts,
     333             :                                               Form_pg_class classForm,
     334             :                                               int effective_multixact_freeze_max_age,
     335             :                                               bool *dovacuum, bool *doanalyze, bool *wraparound);
     336             : static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts,
     337             :                                       Form_pg_class classForm,
     338             :                                       PgStat_StatTabEntry *tabentry,
     339             :                                       int effective_multixact_freeze_max_age,
     340             :                                       bool *dovacuum, bool *doanalyze, bool *wraparound);
     341             : 
     342             : static void autovacuum_do_vac_analyze(autovac_table *tab,
     343             :                                       BufferAccessStrategy bstrategy);
     344             : static AutoVacOpts *extract_autovac_opts(HeapTuple tup,
     345             :                                          TupleDesc pg_class_desc);
     346             : static void perform_work_item(AutoVacuumWorkItem *workitem);
     347             : static void autovac_report_activity(autovac_table *tab);
     348             : static void autovac_report_workitem(AutoVacuumWorkItem *workitem,
     349             :                                     const char *nspname, const char *relname);
     350             : static void avl_sigusr2_handler(SIGNAL_ARGS);
     351             : 
     352             : 
     353             : 
     354             : /********************************************************************
     355             :  *                    AUTOVACUUM LAUNCHER CODE
     356             :  ********************************************************************/
     357             : 
     358             : /*
     359             :  * Main entry point for the autovacuum launcher process.
     360             :  */
     361             : void
     362         648 : AutoVacLauncherMain(char *startup_data, size_t startup_data_len)
     363             : {
     364             :     sigjmp_buf  local_sigjmp_buf;
     365             : 
     366             :     Assert(startup_data_len == 0);
     367             : 
     368             :     /* Release postmaster's working memory context */
     369         648 :     if (PostmasterContext)
     370             :     {
     371         648 :         MemoryContextDelete(PostmasterContext);
     372         648 :         PostmasterContext = NULL;
     373             :     }
     374             : 
     375         648 :     MyBackendType = B_AUTOVAC_LAUNCHER;
     376         648 :     init_ps_display(NULL);
     377             : 
     378         648 :     ereport(DEBUG1,
     379             :             (errmsg_internal("autovacuum launcher started")));
     380             : 
     381         648 :     if (PostAuthDelay)
     382           0 :         pg_usleep(PostAuthDelay * 1000000L);
     383             : 
     384             :     Assert(GetProcessingMode() == InitProcessing);
     385             : 
     386             :     /*
     387             :      * Set up signal handlers.  We operate on databases much like a regular
     388             :      * backend, so we use the same signal handling.  See equivalent code in
     389             :      * tcop/postgres.c.
     390             :      */
     391         648 :     pqsignal(SIGHUP, SignalHandlerForConfigReload);
     392         648 :     pqsignal(SIGINT, StatementCancelHandler);
     393         648 :     pqsignal(SIGTERM, SignalHandlerForShutdownRequest);
     394             :     /* SIGQUIT handler was already set up by InitPostmasterChild */
     395             : 
     396         648 :     InitializeTimeouts();       /* establishes SIGALRM handler */
     397             : 
     398         648 :     pqsignal(SIGPIPE, SIG_IGN);
     399         648 :     pqsignal(SIGUSR1, procsignal_sigusr1_handler);
     400         648 :     pqsignal(SIGUSR2, avl_sigusr2_handler);
     401         648 :     pqsignal(SIGFPE, FloatExceptionHandler);
     402         648 :     pqsignal(SIGCHLD, SIG_DFL);
     403             : 
     404             :     /*
     405             :      * Create a per-backend PGPROC struct in shared memory.  We must do this
     406             :      * before we can use LWLocks or access any shared memory.
     407             :      */
     408         648 :     InitProcess();
     409             : 
     410             :     /* Early initialization */
     411         648 :     BaseInit();
     412             : 
     413         648 :     InitPostgres(NULL, InvalidOid, NULL, InvalidOid, 0, NULL);
     414             : 
     415         648 :     SetProcessingMode(NormalProcessing);
     416             : 
     417             :     /*
     418             :      * Create a memory context that we will do all our work in.  We do this so
     419             :      * that we can reset the context during error recovery and thereby avoid
     420             :      * possible memory leaks.
     421             :      */
     422         648 :     AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
     423             :                                           "Autovacuum Launcher",
     424             :                                           ALLOCSET_DEFAULT_SIZES);
     425         648 :     MemoryContextSwitchTo(AutovacMemCxt);
     426             : 
     427             :     /*
     428             :      * If an exception is encountered, processing resumes here.
     429             :      *
     430             :      * This code is a stripped down version of PostgresMain error recovery.
     431             :      *
     432             :      * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
     433             :      * (to wit, BlockSig) will be restored when longjmp'ing to here.  Thus,
     434             :      * signals other than SIGQUIT will be blocked until we complete error
     435             :      * recovery.  It might seem that this policy makes the HOLD_INTERRUPTS()
     436             :      * call redundant, but it is not since InterruptPending might be set
     437             :      * already.
     438             :      */
     439         648 :     if (sigsetjmp(local_sigjmp_buf, 1) != 0)
     440             :     {
     441             :         /* since not using PG_TRY, must reset error stack by hand */
     442           0 :         error_context_stack = NULL;
     443             : 
     444             :         /* Prevents interrupts while cleaning up */
     445           0 :         HOLD_INTERRUPTS();
     446             : 
     447             :         /* Forget any pending QueryCancel or timeout request */
     448           0 :         disable_all_timeouts(false);
     449           0 :         QueryCancelPending = false; /* second to avoid race condition */
     450             : 
     451             :         /* Report the error to the server log */
     452           0 :         EmitErrorReport();
     453             : 
     454             :         /* Abort the current transaction in order to recover */
     455           0 :         AbortCurrentTransaction();
     456             : 
     457             :         /*
     458             :          * Release any other resources, for the case where we were not in a
     459             :          * transaction.
     460             :          */
     461           0 :         LWLockReleaseAll();
     462           0 :         pgstat_report_wait_end();
     463           0 :         UnlockBuffers();
     464             :         /* this is probably dead code, but let's be safe: */
     465           0 :         if (AuxProcessResourceOwner)
     466           0 :             ReleaseAuxProcessResources(false);
     467           0 :         AtEOXact_Buffers(false);
     468           0 :         AtEOXact_SMgr();
     469           0 :         AtEOXact_Files(false);
     470           0 :         AtEOXact_HashTables(false);
     471             : 
     472             :         /*
     473             :          * Now return to normal top-level context and clear ErrorContext for
     474             :          * next time.
     475             :          */
     476           0 :         MemoryContextSwitchTo(AutovacMemCxt);
     477           0 :         FlushErrorState();
     478             : 
     479             :         /* Flush any leaked data in the top-level context */
     480           0 :         MemoryContextReset(AutovacMemCxt);
     481             : 
     482             :         /* don't leave dangling pointers to freed memory */
     483           0 :         DatabaseListCxt = NULL;
     484           0 :         dlist_init(&DatabaseList);
     485             : 
     486             :         /* Now we can allow interrupts again */
     487           0 :         RESUME_INTERRUPTS();
     488             : 
     489             :         /* if in shutdown mode, no need for anything further; just go away */
     490           0 :         if (ShutdownRequestPending)
     491           0 :             AutoVacLauncherShutdown();
     492             : 
     493             :         /*
     494             :          * Sleep at least 1 second after any error.  We don't want to be
     495             :          * filling the error logs as fast as we can.
     496             :          */
     497           0 :         pg_usleep(1000000L);
     498             :     }
     499             : 
     500             :     /* We can now handle ereport(ERROR) */
     501         648 :     PG_exception_stack = &local_sigjmp_buf;
     502             : 
     503             :     /* must unblock signals before calling rebuild_database_list */
     504         648 :     sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
     505             : 
     506             :     /*
     507             :      * Set always-secure search path.  Launcher doesn't connect to a database,
     508             :      * so this has no effect.
     509             :      */
     510         648 :     SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
     511             : 
     512             :     /*
     513             :      * Force zero_damaged_pages OFF in the autovac process, even if it is set
     514             :      * in postgresql.conf.  We don't really want such a dangerous option being
     515             :      * applied non-interactively.
     516             :      */
     517         648 :     SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
     518             : 
     519             :     /*
     520             :      * Force settable timeouts off to avoid letting these settings prevent
     521             :      * regular maintenance from being executed.
     522             :      */
     523         648 :     SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
     524         648 :     SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
     525         648 :     SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
     526         648 :     SetConfigOption("idle_in_transaction_session_timeout", "0",
     527             :                     PGC_SUSET, PGC_S_OVERRIDE);
     528             : 
     529             :     /*
     530             :      * Force default_transaction_isolation to READ COMMITTED.  We don't want
     531             :      * to pay the overhead of serializable mode, nor add any risk of causing
     532             :      * deadlocks or delaying other transactions.
     533             :      */
     534         648 :     SetConfigOption("default_transaction_isolation", "read committed",
     535             :                     PGC_SUSET, PGC_S_OVERRIDE);
     536             : 
     537             :     /*
     538             :      * Even when system is configured to use a different fetch consistency,
     539             :      * for autovac we always want fresh stats.
     540             :      */
     541         648 :     SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
     542             : 
     543             :     /*
     544             :      * In emergency mode, just start a worker (unless shutdown was requested)
     545             :      * and go away.
     546             :      */
     547         648 :     if (!AutoVacuumingActive())
     548             :     {
     549           0 :         if (!ShutdownRequestPending)
     550           0 :             do_start_worker();
     551           0 :         proc_exit(0);           /* done */
     552             :     }
     553             : 
     554         648 :     AutoVacuumShmem->av_launcherpid = MyProcPid;
     555             : 
     556             :     /*
     557             :      * Create the initial database list.  The invariant we want this list to
     558             :      * keep is that it's ordered by decreasing next_time.  As soon as an entry
     559             :      * is updated to a higher time, it will be moved to the front (which is
     560             :      * correct because the only operation is to add autovacuum_naptime to the
     561             :      * entry, and time always increases).
     562             :      */
     563         648 :     rebuild_database_list(InvalidOid);
     564             : 
     565             :     /* loop until shutdown request */
     566        3394 :     while (!ShutdownRequestPending)
     567             :     {
     568             :         struct timeval nap;
     569        3394 :         TimestampTz current_time = 0;
     570             :         bool        can_launch;
     571             : 
     572             :         /*
     573             :          * This loop is a bit different from the normal use of WaitLatch,
     574             :          * because we'd like to sleep before the first launch of a child
     575             :          * process.  So it's WaitLatch, then ResetLatch, then check for
     576             :          * wakening conditions.
     577             :          */
     578             : 
     579        3394 :         launcher_determine_sleep(!dlist_is_empty(&AutoVacuumShmem->av_freeWorkers),
     580        3394 :                                  false, &nap);
     581             : 
     582             :         /*
     583             :          * Wait until naptime expires or we get some type of signal (all the
     584             :          * signal handlers will wake us by calling SetLatch).
     585             :          */
     586        3394 :         (void) WaitLatch(MyLatch,
     587             :                          WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     588        3394 :                          (nap.tv_sec * 1000L) + (nap.tv_usec / 1000L),
     589             :                          WAIT_EVENT_AUTOVACUUM_MAIN);
     590             : 
     591        3388 :         ResetLatch(MyLatch);
     592             : 
     593        3388 :         HandleAutoVacLauncherInterrupts();
     594             : 
     595             :         /*
     596             :          * a worker finished, or postmaster signaled failure to start a worker
     597             :          */
     598        2746 :         if (got_SIGUSR2)
     599             :         {
     600          40 :             got_SIGUSR2 = false;
     601             : 
     602             :             /* rebalance cost limits, if needed */
     603          40 :             if (AutoVacuumShmem->av_signal[AutoVacRebalance])
     604             :             {
     605          20 :                 LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
     606          20 :                 AutoVacuumShmem->av_signal[AutoVacRebalance] = false;
     607          20 :                 autovac_recalculate_workers_for_balance();
     608          20 :                 LWLockRelease(AutovacuumLock);
     609             :             }
     610             : 
     611          40 :             if (AutoVacuumShmem->av_signal[AutoVacForkFailed])
     612             :             {
     613             :                 /*
     614             :                  * If the postmaster failed to start a new worker, we sleep
     615             :                  * for a little while and resend the signal.  The new worker's
     616             :                  * state is still in memory, so this is sufficient.  After
     617             :                  * that, we restart the main loop.
     618             :                  *
     619             :                  * XXX should we put a limit to the number of times we retry?
     620             :                  * I don't think it makes much sense, because a future start
     621             :                  * of a worker will continue to fail in the same way.
     622             :                  */
     623           0 :                 AutoVacuumShmem->av_signal[AutoVacForkFailed] = false;
     624           0 :                 pg_usleep(1000000L);    /* 1s */
     625           0 :                 SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
     626           0 :                 continue;
     627             :             }
     628             :         }
     629             : 
     630             :         /*
     631             :          * There are some conditions that we need to check before trying to
     632             :          * start a worker.  First, we need to make sure that there is a worker
     633             :          * slot available.  Second, we need to make sure that no other worker
     634             :          * failed while starting up.
     635             :          */
     636             : 
     637        2746 :         current_time = GetCurrentTimestamp();
     638        2746 :         LWLockAcquire(AutovacuumLock, LW_SHARED);
     639             : 
     640        2746 :         can_launch = !dlist_is_empty(&AutoVacuumShmem->av_freeWorkers);
     641             : 
     642        2746 :         if (AutoVacuumShmem->av_startingWorker != NULL)
     643             :         {
     644             :             int         waittime;
     645           0 :             WorkerInfo  worker = AutoVacuumShmem->av_startingWorker;
     646             : 
     647             :             /*
     648             :              * We can't launch another worker when another one is still
     649             :              * starting up (or failed while doing so), so just sleep for a bit
     650             :              * more; that worker will wake us up again as soon as it's ready.
     651             :              * We will only wait autovacuum_naptime seconds (up to a maximum
     652             :              * of 60 seconds) for this to happen however.  Note that failure
     653             :              * to connect to a particular database is not a problem here,
     654             :              * because the worker removes itself from the startingWorker
     655             :              * pointer before trying to connect.  Problems detected by the
     656             :              * postmaster (like fork() failure) are also reported and handled
     657             :              * differently.  The only problems that may cause this code to
     658             :              * fire are errors in the earlier sections of AutoVacWorkerMain,
     659             :              * before the worker removes the WorkerInfo from the
     660             :              * startingWorker pointer.
     661             :              */
     662           0 :             waittime = Min(autovacuum_naptime, 60) * 1000;
     663           0 :             if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
     664             :                                            waittime))
     665             :             {
     666           0 :                 LWLockRelease(AutovacuumLock);
     667           0 :                 LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
     668             : 
     669             :                 /*
     670             :                  * No other process can put a worker in starting mode, so if
     671             :                  * startingWorker is still INVALID after exchanging our lock,
     672             :                  * we assume it's the same one we saw above (so we don't
     673             :                  * recheck the launch time).
     674             :                  */
     675           0 :                 if (AutoVacuumShmem->av_startingWorker != NULL)
     676             :                 {
     677           0 :                     worker = AutoVacuumShmem->av_startingWorker;
     678           0 :                     worker->wi_dboid = InvalidOid;
     679           0 :                     worker->wi_tableoid = InvalidOid;
     680           0 :                     worker->wi_sharedrel = false;
     681           0 :                     worker->wi_proc = NULL;
     682           0 :                     worker->wi_launchtime = 0;
     683           0 :                     dlist_push_head(&AutoVacuumShmem->av_freeWorkers,
     684             :                                     &worker->wi_links);
     685           0 :                     AutoVacuumShmem->av_startingWorker = NULL;
     686           0 :                     ereport(WARNING,
     687             :                             errmsg("autovacuum worker took too long to start; canceled"));
     688             :                 }
     689             :             }
     690             :             else
     691           0 :                 can_launch = false;
     692             :         }
     693        2746 :         LWLockRelease(AutovacuumLock);  /* either shared or exclusive */
     694             : 
     695             :         /* if we can't do anything, just go back to sleep */
     696        2746 :         if (!can_launch)
     697           0 :             continue;
     698             : 
     699             :         /* We're OK to start a new worker */
     700             : 
     701        2746 :         if (dlist_is_empty(&DatabaseList))
     702             :         {
     703             :             /*
     704             :              * Special case when the list is empty: start a worker right away.
     705             :              * This covers the initial case, when no database is in pgstats
     706             :              * (thus the list is empty).  Note that the constraints in
     707             :              * launcher_determine_sleep keep us from starting workers too
     708             :              * quickly (at most once every autovacuum_naptime when the list is
     709             :              * empty).
     710             :              */
     711          62 :             launch_worker(current_time);
     712             :         }
     713             :         else
     714             :         {
     715             :             /*
     716             :              * because rebuild_database_list constructs a list with most
     717             :              * distant adl_next_worker first, we obtain our database from the
     718             :              * tail of the list.
     719             :              */
     720             :             avl_dbase  *avdb;
     721             : 
     722        2684 :             avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
     723             : 
     724             :             /*
     725             :              * launch a worker if next_worker is right now or it is in the
     726             :              * past
     727             :              */
     728        2684 :             if (TimestampDifferenceExceeds(avdb->adl_next_worker,
     729             :                                            current_time, 0))
     730          20 :                 launch_worker(current_time);
     731             :         }
     732             :     }
     733             : 
     734           0 :     AutoVacLauncherShutdown();
     735             : }
     736             : 
     737             : /*
     738             :  * Process any new interrupts.
     739             :  */
     740             : static void
     741        3388 : HandleAutoVacLauncherInterrupts(void)
     742             : {
     743             :     /* the normal shutdown case */
     744        3388 :     if (ShutdownRequestPending)
     745         642 :         AutoVacLauncherShutdown();
     746             : 
     747        2746 :     if (ConfigReloadPending)
     748             :     {
     749          56 :         ConfigReloadPending = false;
     750          56 :         ProcessConfigFile(PGC_SIGHUP);
     751             : 
     752             :         /* shutdown requested in config file? */
     753          56 :         if (!AutoVacuumingActive())
     754           0 :             AutoVacLauncherShutdown();
     755             : 
     756             :         /* rebuild the list in case the naptime changed */
     757          56 :         rebuild_database_list(InvalidOid);
     758             :     }
     759             : 
     760             :     /* Process barrier events */
     761        2746 :     if (ProcSignalBarrierPending)
     762          54 :         ProcessProcSignalBarrier();
     763             : 
     764             :     /* Perform logging of memory contexts of this process */
     765        2746 :     if (LogMemoryContextPending)
     766           0 :         ProcessLogMemoryContextInterrupt();
     767             : 
     768             :     /* Process sinval catchup interrupts that happened while sleeping */
     769        2746 :     ProcessCatchupInterrupt();
     770        2746 : }
     771             : 
     772             : /*
     773             :  * Perform a normal exit from the autovac launcher.
     774             :  */
     775             : static void
     776         642 : AutoVacLauncherShutdown(void)
     777             : {
     778         642 :     ereport(DEBUG1,
     779             :             (errmsg_internal("autovacuum launcher shutting down")));
     780         642 :     AutoVacuumShmem->av_launcherpid = 0;
     781             : 
     782         642 :     proc_exit(0);               /* done */
     783             : }
     784             : 
     785             : /*
     786             :  * Determine the time to sleep, based on the database list.
     787             :  *
     788             :  * The "canlaunch" parameter indicates whether we can start a worker right now,
     789             :  * for example due to the workers being all busy.  If this is false, we will
     790             :  * cause a long sleep, which will be interrupted when a worker exits.
     791             :  */
     792             : static void
     793        3394 : launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval *nap)
     794             : {
     795             :     /*
     796             :      * We sleep until the next scheduled vacuum.  We trust that when the
     797             :      * database list was built, care was taken so that no entries have times
     798             :      * in the past; if the first entry has too close a next_worker value, or a
     799             :      * time in the past, we will sleep a small nominal time.
     800             :      */
     801        3394 :     if (!canlaunch)
     802             :     {
     803           0 :         nap->tv_sec = autovacuum_naptime;
     804           0 :         nap->tv_usec = 0;
     805             :     }
     806        3394 :     else if (!dlist_is_empty(&DatabaseList))
     807             :     {
     808        3270 :         TimestampTz current_time = GetCurrentTimestamp();
     809             :         TimestampTz next_wakeup;
     810             :         avl_dbase  *avdb;
     811             :         long        secs;
     812             :         int         usecs;
     813             : 
     814        3270 :         avdb = dlist_tail_element(avl_dbase, adl_node, &DatabaseList);
     815             : 
     816        3270 :         next_wakeup = avdb->adl_next_worker;
     817        3270 :         TimestampDifference(current_time, next_wakeup, &secs, &usecs);
     818             : 
     819        3270 :         nap->tv_sec = secs;
     820        3270 :         nap->tv_usec = usecs;
     821             :     }
     822             :     else
     823             :     {
     824             :         /* list is empty, sleep for whole autovacuum_naptime seconds  */
     825         124 :         nap->tv_sec = autovacuum_naptime;
     826         124 :         nap->tv_usec = 0;
     827             :     }
     828             : 
     829             :     /*
     830             :      * If the result is exactly zero, it means a database had an entry with
     831             :      * time in the past.  Rebuild the list so that the databases are evenly
     832             :      * distributed again, and recalculate the time to sleep.  This can happen
     833             :      * if there are more tables needing vacuum than workers, and they all take
     834             :      * longer to vacuum than autovacuum_naptime.
     835             :      *
     836             :      * We only recurse once.  rebuild_database_list should always return times
     837             :      * in the future, but it seems best not to trust too much on that.
     838             :      */
     839        3394 :     if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
     840             :     {
     841           0 :         rebuild_database_list(InvalidOid);
     842           0 :         launcher_determine_sleep(canlaunch, true, nap);
     843           0 :         return;
     844             :     }
     845             : 
     846             :     /* The smallest time we'll allow the launcher to sleep. */
     847        3394 :     if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
     848             :     {
     849          12 :         nap->tv_sec = 0;
     850          12 :         nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000;
     851             :     }
     852             : 
     853             :     /*
     854             :      * If the sleep time is too large, clamp it to an arbitrary maximum (plus
     855             :      * any fractional seconds, for simplicity).  This avoids an essentially
     856             :      * infinite sleep in strange cases like the system clock going backwards a
     857             :      * few years.
     858             :      */
     859        3394 :     if (nap->tv_sec > MAX_AUTOVAC_SLEEPTIME)
     860          22 :         nap->tv_sec = MAX_AUTOVAC_SLEEPTIME;
     861             : }
     862             : 
     863             : /*
     864             :  * Build an updated DatabaseList.  It must only contain databases that appear
     865             :  * in pgstats, and must be sorted by next_worker from highest to lowest,
     866             :  * distributed regularly across the next autovacuum_naptime interval.
     867             :  *
     868             :  * Receives the Oid of the database that made this list be generated (we call
     869             :  * this the "new" database, because when the database was already present on
     870             :  * the list, we expect that this function is not called at all).  The
     871             :  * preexisting list, if any, will be used to preserve the order of the
     872             :  * databases in the autovacuum_naptime period.  The new database is put at the
     873             :  * end of the interval.  The actual values are not saved, which should not be
     874             :  * much of a problem.
     875             :  */
     876             : static void
     877         712 : rebuild_database_list(Oid newdb)
     878             : {
     879             :     List       *dblist;
     880             :     ListCell   *cell;
     881             :     MemoryContext newcxt;
     882             :     MemoryContext oldcxt;
     883             :     MemoryContext tmpcxt;
     884             :     HASHCTL     hctl;
     885             :     int         score;
     886             :     int         nelems;
     887             :     HTAB       *dbhash;
     888             :     dlist_iter  iter;
     889             : 
     890         712 :     newcxt = AllocSetContextCreate(AutovacMemCxt,
     891             :                                    "Autovacuum database list",
     892             :                                    ALLOCSET_DEFAULT_SIZES);
     893         712 :     tmpcxt = AllocSetContextCreate(newcxt,
     894             :                                    "Autovacuum database list (tmp)",
     895             :                                    ALLOCSET_DEFAULT_SIZES);
     896         712 :     oldcxt = MemoryContextSwitchTo(tmpcxt);
     897             : 
     898             :     /*
     899             :      * Implementing this is not as simple as it sounds, because we need to put
     900             :      * the new database at the end of the list; next the databases that were
     901             :      * already on the list, and finally (at the tail of the list) all the
     902             :      * other databases that are not on the existing list.
     903             :      *
     904             :      * To do this, we build an empty hash table of scored databases.  We will
     905             :      * start with the lowest score (zero) for the new database, then
     906             :      * increasing scores for the databases in the existing list, in order, and
     907             :      * lastly increasing scores for all databases gotten via
     908             :      * get_database_list() that are not already on the hash.
     909             :      *
     910             :      * Then we will put all the hash elements into an array, sort the array by
     911             :      * score, and finally put the array elements into the new doubly linked
     912             :      * list.
     913             :      */
     914         712 :     hctl.keysize = sizeof(Oid);
     915         712 :     hctl.entrysize = sizeof(avl_dbase);
     916         712 :     hctl.hcxt = tmpcxt;
     917         712 :     dbhash = hash_create("autovacuum db hash", 20, &hctl, /* magic number here
     918             :                                                              * FIXME */
     919             :                          HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     920             : 
     921             :     /* start by inserting the new database */
     922         712 :     score = 0;
     923         712 :     if (OidIsValid(newdb))
     924             :     {
     925             :         avl_dbase  *db;
     926             :         PgStat_StatDBEntry *entry;
     927             : 
     928             :         /* only consider this database if it has a pgstat entry */
     929           8 :         entry = pgstat_fetch_stat_dbentry(newdb);
     930           8 :         if (entry != NULL)
     931             :         {
     932             :             /* we assume it isn't found because the hash was just created */
     933           8 :             db = hash_search(dbhash, &newdb, HASH_ENTER, NULL);
     934             : 
     935             :             /* hash_search already filled in the key */
     936           8 :             db->adl_score = score++;
     937             :             /* next_worker is filled in later */
     938             :         }
     939             :     }
     940             : 
     941             :     /* Now insert the databases from the existing list */
     942         804 :     dlist_foreach(iter, &DatabaseList)
     943             :     {
     944          92 :         avl_dbase  *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
     945             :         avl_dbase  *db;
     946             :         bool        found;
     947             :         PgStat_StatDBEntry *entry;
     948             : 
     949             :         /*
     950             :          * skip databases with no stat entries -- in particular, this gets rid
     951             :          * of dropped databases
     952             :          */
     953          92 :         entry = pgstat_fetch_stat_dbentry(avdb->adl_datid);
     954          92 :         if (entry == NULL)
     955           0 :             continue;
     956             : 
     957          92 :         db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found);
     958             : 
     959          92 :         if (!found)
     960             :         {
     961             :             /* hash_search already filled in the key */
     962          92 :             db->adl_score = score++;
     963             :             /* next_worker is filled in later */
     964             :         }
     965             :     }
     966             : 
     967             :     /* finally, insert all qualifying databases not previously inserted */
     968         712 :     dblist = get_database_list();
     969        3138 :     foreach(cell, dblist)
     970             :     {
     971        2426 :         avw_dbase  *avdb = lfirst(cell);
     972             :         avl_dbase  *db;
     973             :         bool        found;
     974             :         PgStat_StatDBEntry *entry;
     975             : 
     976             :         /* only consider databases with a pgstat entry */
     977        2426 :         entry = pgstat_fetch_stat_dbentry(avdb->adw_datid);
     978        2426 :         if (entry == NULL)
     979        1492 :             continue;
     980             : 
     981         934 :         db = hash_search(dbhash, &(avdb->adw_datid), HASH_ENTER, &found);
     982             :         /* only update the score if the database was not already on the hash */
     983         934 :         if (!found)
     984             :         {
     985             :             /* hash_search already filled in the key */
     986         834 :             db->adl_score = score++;
     987             :             /* next_worker is filled in later */
     988             :         }
     989             :     }
     990         712 :     nelems = score;
     991             : 
     992             :     /* from here on, the allocated memory belongs to the new list */
     993         712 :     MemoryContextSwitchTo(newcxt);
     994         712 :     dlist_init(&DatabaseList);
     995             : 
     996         712 :     if (nelems > 0)
     997             :     {
     998             :         TimestampTz current_time;
     999             :         int         millis_increment;
    1000             :         avl_dbase  *dbary;
    1001             :         avl_dbase  *db;
    1002             :         HASH_SEQ_STATUS seq;
    1003             :         int         i;
    1004             : 
    1005             :         /* put all the hash elements into an array */
    1006         650 :         dbary = palloc(nelems * sizeof(avl_dbase));
    1007             : 
    1008         650 :         i = 0;
    1009         650 :         hash_seq_init(&seq, dbhash);
    1010        1584 :         while ((db = hash_seq_search(&seq)) != NULL)
    1011         934 :             memcpy(&(dbary[i++]), db, sizeof(avl_dbase));
    1012             : 
    1013             :         /* sort the array */
    1014         650 :         qsort(dbary, nelems, sizeof(avl_dbase), db_comparator);
    1015             : 
    1016             :         /*
    1017             :          * Determine the time interval between databases in the schedule. If
    1018             :          * we see that the configured naptime would take us to sleep times
    1019             :          * lower than our min sleep time (which launcher_determine_sleep is
    1020             :          * coded not to allow), silently use a larger naptime (but don't touch
    1021             :          * the GUC variable).
    1022             :          */
    1023         650 :         millis_increment = 1000.0 * autovacuum_naptime / nelems;
    1024         650 :         if (millis_increment <= MIN_AUTOVAC_SLEEPTIME)
    1025           0 :             millis_increment = MIN_AUTOVAC_SLEEPTIME * 1.1;
    1026             : 
    1027         650 :         current_time = GetCurrentTimestamp();
    1028             : 
    1029             :         /*
    1030             :          * move the elements from the array into the dlist, setting the
    1031             :          * next_worker while walking the array
    1032             :          */
    1033        1584 :         for (i = 0; i < nelems; i++)
    1034             :         {
    1035         934 :             db = &(dbary[i]);
    1036             : 
    1037         934 :             current_time = TimestampTzPlusMilliseconds(current_time,
    1038             :                                                        millis_increment);
    1039         934 :             db->adl_next_worker = current_time;
    1040             : 
    1041             :             /* later elements should go closer to the head of the list */
    1042         934 :             dlist_push_head(&DatabaseList, &db->adl_node);
    1043             :         }
    1044             :     }
    1045             : 
    1046             :     /* all done, clean up memory */
    1047         712 :     if (DatabaseListCxt != NULL)
    1048          64 :         MemoryContextDelete(DatabaseListCxt);
    1049         712 :     MemoryContextDelete(tmpcxt);
    1050         712 :     DatabaseListCxt = newcxt;
    1051         712 :     MemoryContextSwitchTo(oldcxt);
    1052         712 : }
    1053             : 
    1054             : /* qsort comparator for avl_dbase, using adl_score */
    1055             : static int
    1056         408 : db_comparator(const void *a, const void *b)
    1057             : {
    1058         408 :     return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
    1059             :                       ((const avl_dbase *) b)->adl_score);
    1060             : }
    1061             : 
    1062             : /*
    1063             :  * do_start_worker
    1064             :  *
    1065             :  * Bare-bones procedure for starting an autovacuum worker from the launcher.
    1066             :  * It determines what database to work on, sets up shared memory stuff and
    1067             :  * signals postmaster to start the worker.  It fails gracefully if invoked when
    1068             :  * autovacuum_workers are already active.
    1069             :  *
    1070             :  * Return value is the OID of the database that the worker is going to process,
    1071             :  * or InvalidOid if no worker was actually started.
    1072             :  */
    1073             : static Oid
    1074          82 : do_start_worker(void)
    1075             : {
    1076             :     List       *dblist;
    1077             :     ListCell   *cell;
    1078             :     TransactionId xidForceLimit;
    1079             :     MultiXactId multiForceLimit;
    1080             :     bool        for_xid_wrap;
    1081             :     bool        for_multi_wrap;
    1082             :     avw_dbase  *avdb;
    1083             :     TimestampTz current_time;
    1084          82 :     bool        skipit = false;
    1085          82 :     Oid         retval = InvalidOid;
    1086             :     MemoryContext tmpcxt,
    1087             :                 oldcxt;
    1088             : 
    1089             :     /* return quickly when there are no free workers */
    1090          82 :     LWLockAcquire(AutovacuumLock, LW_SHARED);
    1091          82 :     if (dlist_is_empty(&AutoVacuumShmem->av_freeWorkers))
    1092             :     {
    1093           0 :         LWLockRelease(AutovacuumLock);
    1094           0 :         return InvalidOid;
    1095             :     }
    1096          82 :     LWLockRelease(AutovacuumLock);
    1097             : 
    1098             :     /*
    1099             :      * Create and switch to a temporary context to avoid leaking the memory
    1100             :      * allocated for the database list.
    1101             :      */
    1102          82 :     tmpcxt = AllocSetContextCreate(CurrentMemoryContext,
    1103             :                                    "Autovacuum start worker (tmp)",
    1104             :                                    ALLOCSET_DEFAULT_SIZES);
    1105          82 :     oldcxt = MemoryContextSwitchTo(tmpcxt);
    1106             : 
    1107             :     /* Get a list of databases */
    1108          82 :     dblist = get_database_list();
    1109             : 
    1110             :     /*
    1111             :      * Determine the oldest datfrozenxid/relfrozenxid that we will allow to
    1112             :      * pass without forcing a vacuum.  (This limit can be tightened for
    1113             :      * particular tables, but not loosened.)
    1114             :      */
    1115          82 :     recentXid = ReadNextTransactionId();
    1116          82 :     xidForceLimit = recentXid - autovacuum_freeze_max_age;
    1117             :     /* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
    1118             :     /* this can cause the limit to go backwards by 3, but that's OK */
    1119          82 :     if (xidForceLimit < FirstNormalTransactionId)
    1120           0 :         xidForceLimit -= FirstNormalTransactionId;
    1121             : 
    1122             :     /* Also determine the oldest datminmxid we will consider. */
    1123          82 :     recentMulti = ReadNextMultiXactId();
    1124          82 :     multiForceLimit = recentMulti - MultiXactMemberFreezeThreshold();
    1125          82 :     if (multiForceLimit < FirstMultiXactId)
    1126           0 :         multiForceLimit -= FirstMultiXactId;
    1127             : 
    1128             :     /*
    1129             :      * Choose a database to connect to.  We pick the database that was least
    1130             :      * recently auto-vacuumed, or one that needs vacuuming to prevent Xid
    1131             :      * wraparound-related data loss.  If any db at risk of Xid wraparound is
    1132             :      * found, we pick the one with oldest datfrozenxid, independently of
    1133             :      * autovacuum times; similarly we pick the one with the oldest datminmxid
    1134             :      * if any is in MultiXactId wraparound.  Note that those in Xid wraparound
    1135             :      * danger are given more priority than those in multi wraparound danger.
    1136             :      *
    1137             :      * Note that a database with no stats entry is not considered, except for
    1138             :      * Xid wraparound purposes.  The theory is that if no one has ever
    1139             :      * connected to it since the stats were last initialized, it doesn't need
    1140             :      * vacuuming.
    1141             :      *
    1142             :      * XXX This could be improved if we had more info about whether it needs
    1143             :      * vacuuming before connecting to it.  Perhaps look through the pgstats
    1144             :      * data for the database's tables?  One idea is to keep track of the
    1145             :      * number of new and dead tuples per database in pgstats.  However it
    1146             :      * isn't clear how to construct a metric that measures that and not cause
    1147             :      * starvation for less busy databases.
    1148             :      */
    1149          82 :     avdb = NULL;
    1150          82 :     for_xid_wrap = false;
    1151          82 :     for_multi_wrap = false;
    1152          82 :     current_time = GetCurrentTimestamp();
    1153         370 :     foreach(cell, dblist)
    1154             :     {
    1155         288 :         avw_dbase  *tmp = lfirst(cell);
    1156             :         dlist_iter  iter;
    1157             : 
    1158             :         /* Check to see if this one is at risk of wraparound */
    1159         288 :         if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit))
    1160             :         {
    1161           0 :             if (avdb == NULL ||
    1162           0 :                 TransactionIdPrecedes(tmp->adw_frozenxid,
    1163             :                                       avdb->adw_frozenxid))
    1164           0 :                 avdb = tmp;
    1165           0 :             for_xid_wrap = true;
    1166         254 :             continue;
    1167             :         }
    1168         288 :         else if (for_xid_wrap)
    1169           0 :             continue;           /* ignore not-at-risk DBs */
    1170         288 :         else if (MultiXactIdPrecedes(tmp->adw_minmulti, multiForceLimit))
    1171             :         {
    1172           0 :             if (avdb == NULL ||
    1173           0 :                 MultiXactIdPrecedes(tmp->adw_minmulti, avdb->adw_minmulti))
    1174           0 :                 avdb = tmp;
    1175           0 :             for_multi_wrap = true;
    1176           0 :             continue;
    1177             :         }
    1178         288 :         else if (for_multi_wrap)
    1179           0 :             continue;           /* ignore not-at-risk DBs */
    1180             : 
    1181             :         /* Find pgstat entry if any */
    1182         288 :         tmp->adw_entry = pgstat_fetch_stat_dbentry(tmp->adw_datid);
    1183             : 
    1184             :         /*
    1185             :          * Skip a database with no pgstat entry; it means it hasn't seen any
    1186             :          * activity.
    1187             :          */
    1188         288 :         if (!tmp->adw_entry)
    1189         230 :             continue;
    1190             : 
    1191             :         /*
    1192             :          * Also, skip a database that appears on the database list as having
    1193             :          * been processed recently (less than autovacuum_naptime seconds ago).
    1194             :          * We do this so that we don't select a database which we just
    1195             :          * selected, but that pgstat hasn't gotten around to updating the last
    1196             :          * autovacuum time yet.
    1197             :          */
    1198          58 :         skipit = false;
    1199             : 
    1200         108 :         dlist_reverse_foreach(iter, &DatabaseList)
    1201             :         {
    1202          94 :             avl_dbase  *dbp = dlist_container(avl_dbase, adl_node, iter.cur);
    1203             : 
    1204          94 :             if (dbp->adl_datid == tmp->adw_datid)
    1205             :             {
    1206             :                 /*
    1207             :                  * Skip this database if its next_worker value falls between
    1208             :                  * the current time and the current time plus naptime.
    1209             :                  */
    1210          44 :                 if (!TimestampDifferenceExceeds(dbp->adl_next_worker,
    1211          24 :                                                 current_time, 0) &&
    1212          24 :                     !TimestampDifferenceExceeds(current_time,
    1213             :                                                 dbp->adl_next_worker,
    1214             :                                                 autovacuum_naptime * 1000))
    1215          24 :                     skipit = true;
    1216             : 
    1217          44 :                 break;
    1218             :             }
    1219             :         }
    1220          58 :         if (skipit)
    1221          24 :             continue;
    1222             : 
    1223             :         /*
    1224             :          * Remember the db with oldest autovac time.  (If we are here, both
    1225             :          * tmp->entry and db->entry must be non-null.)
    1226             :          */
    1227          34 :         if (avdb == NULL ||
    1228          14 :             tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time)
    1229          20 :             avdb = tmp;
    1230             :     }
    1231             : 
    1232             :     /* Found a database -- process it */
    1233          82 :     if (avdb != NULL)
    1234             :     {
    1235             :         WorkerInfo  worker;
    1236             :         dlist_node *wptr;
    1237             : 
    1238          20 :         LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
    1239             : 
    1240             :         /*
    1241             :          * Get a worker entry from the freelist.  We checked above, so there
    1242             :          * really should be a free slot.
    1243             :          */
    1244          20 :         wptr = dlist_pop_head_node(&AutoVacuumShmem->av_freeWorkers);
    1245             : 
    1246          20 :         worker = dlist_container(WorkerInfoData, wi_links, wptr);
    1247          20 :         worker->wi_dboid = avdb->adw_datid;
    1248          20 :         worker->wi_proc = NULL;
    1249          20 :         worker->wi_launchtime = GetCurrentTimestamp();
    1250             : 
    1251          20 :         AutoVacuumShmem->av_startingWorker = worker;
    1252             : 
    1253          20 :         LWLockRelease(AutovacuumLock);
    1254             : 
    1255          20 :         SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
    1256             : 
    1257          20 :         retval = avdb->adw_datid;
    1258             :     }
    1259          62 :     else if (skipit)
    1260             :     {
    1261             :         /*
    1262             :          * If we skipped all databases on the list, rebuild it, because it
    1263             :          * probably contains a dropped database.
    1264             :          */
    1265           0 :         rebuild_database_list(InvalidOid);
    1266             :     }
    1267             : 
    1268          82 :     MemoryContextSwitchTo(oldcxt);
    1269          82 :     MemoryContextDelete(tmpcxt);
    1270             : 
    1271          82 :     return retval;
    1272             : }
    1273             : 
    1274             : /*
    1275             :  * launch_worker
    1276             :  *
    1277             :  * Wrapper for starting a worker from the launcher.  Besides actually starting
    1278             :  * it, update the database list to reflect the next time that another one will
    1279             :  * need to be started on the selected database.  The actual database choice is
    1280             :  * left to do_start_worker.
    1281             :  *
    1282             :  * This routine is also expected to insert an entry into the database list if
    1283             :  * the selected database was previously absent from the list.
    1284             :  */
    1285             : static void
    1286          82 : launch_worker(TimestampTz now)
    1287             : {
    1288             :     Oid         dbid;
    1289             :     dlist_iter  iter;
    1290             : 
    1291          82 :     dbid = do_start_worker();
    1292          82 :     if (OidIsValid(dbid))
    1293             :     {
    1294          20 :         bool        found = false;
    1295             : 
    1296             :         /*
    1297             :          * Walk the database list and update the corresponding entry.  If the
    1298             :          * database is not on the list, we'll recreate the list.
    1299             :          */
    1300          52 :         dlist_foreach(iter, &DatabaseList)
    1301             :         {
    1302          44 :             avl_dbase  *avdb = dlist_container(avl_dbase, adl_node, iter.cur);
    1303             : 
    1304          44 :             if (avdb->adl_datid == dbid)
    1305             :             {
    1306          12 :                 found = true;
    1307             : 
    1308             :                 /*
    1309             :                  * add autovacuum_naptime seconds to the current time, and use
    1310             :                  * that as the new "next_worker" field for this database.
    1311             :                  */
    1312          12 :                 avdb->adl_next_worker =
    1313          12 :                     TimestampTzPlusMilliseconds(now, autovacuum_naptime * 1000);
    1314             : 
    1315          12 :                 dlist_move_head(&DatabaseList, iter.cur);
    1316          12 :                 break;
    1317             :             }
    1318             :         }
    1319             : 
    1320             :         /*
    1321             :          * If the database was not present in the database list, we rebuild
    1322             :          * the list.  It's possible that the database does not get into the
    1323             :          * list anyway, for example if it's a database that doesn't have a
    1324             :          * pgstat entry, but this is not a problem because we don't want to
    1325             :          * schedule workers regularly into those in any case.
    1326             :          */
    1327          20 :         if (!found)
    1328           8 :             rebuild_database_list(dbid);
    1329             :     }
    1330          82 : }
    1331             : 
    1332             : /*
    1333             :  * Called from postmaster to signal a failure to fork a process to become
    1334             :  * worker.  The postmaster should kill(SIGUSR2) the launcher shortly
    1335             :  * after calling this function.
    1336             :  */
    1337             : void
    1338           0 : AutoVacWorkerFailed(void)
    1339             : {
    1340           0 :     AutoVacuumShmem->av_signal[AutoVacForkFailed] = true;
    1341           0 : }
    1342             : 
    1343             : /* SIGUSR2: a worker is up and running, or just finished, or failed to fork */
    1344             : static void
    1345          40 : avl_sigusr2_handler(SIGNAL_ARGS)
    1346             : {
    1347          40 :     got_SIGUSR2 = true;
    1348          40 :     SetLatch(MyLatch);
    1349          40 : }
    1350             : 
    1351             : 
    1352             : /********************************************************************
    1353             :  *                    AUTOVACUUM WORKER CODE
    1354             :  ********************************************************************/
    1355             : 
    1356             : /*
    1357             :  * Main entry point for autovacuum worker processes.
    1358             :  */
    1359             : void
    1360          20 : AutoVacWorkerMain(char *startup_data, size_t startup_data_len)
    1361             : {
    1362             :     sigjmp_buf  local_sigjmp_buf;
    1363             :     Oid         dbid;
    1364             : 
    1365             :     Assert(startup_data_len == 0);
    1366             : 
    1367             :     /* Release postmaster's working memory context */
    1368          20 :     if (PostmasterContext)
    1369             :     {
    1370          20 :         MemoryContextDelete(PostmasterContext);
    1371          20 :         PostmasterContext = NULL;
    1372             :     }
    1373             : 
    1374          20 :     MyBackendType = B_AUTOVAC_WORKER;
    1375          20 :     init_ps_display(NULL);
    1376             : 
    1377             :     Assert(GetProcessingMode() == InitProcessing);
    1378             : 
    1379             :     /*
    1380             :      * Set up signal handlers.  We operate on databases much like a regular
    1381             :      * backend, so we use the same signal handling.  See equivalent code in
    1382             :      * tcop/postgres.c.
    1383             :      */
    1384          20 :     pqsignal(SIGHUP, SignalHandlerForConfigReload);
    1385             : 
    1386             :     /*
    1387             :      * SIGINT is used to signal canceling the current table's vacuum; SIGTERM
    1388             :      * means abort and exit cleanly, and SIGQUIT means abandon ship.
    1389             :      */
    1390          20 :     pqsignal(SIGINT, StatementCancelHandler);
    1391          20 :     pqsignal(SIGTERM, die);
    1392             :     /* SIGQUIT handler was already set up by InitPostmasterChild */
    1393             : 
    1394          20 :     InitializeTimeouts();       /* establishes SIGALRM handler */
    1395             : 
    1396          20 :     pqsignal(SIGPIPE, SIG_IGN);
    1397          20 :     pqsignal(SIGUSR1, procsignal_sigusr1_handler);
    1398          20 :     pqsignal(SIGUSR2, SIG_IGN);
    1399          20 :     pqsignal(SIGFPE, FloatExceptionHandler);
    1400          20 :     pqsignal(SIGCHLD, SIG_DFL);
    1401             : 
    1402             :     /*
    1403             :      * Create a per-backend PGPROC struct in shared memory.  We must do this
    1404             :      * before we can use LWLocks or access any shared memory.
    1405             :      */
    1406          20 :     InitProcess();
    1407             : 
    1408             :     /* Early initialization */
    1409          20 :     BaseInit();
    1410             : 
    1411             :     /*
    1412             :      * If an exception is encountered, processing resumes here.
    1413             :      *
    1414             :      * Unlike most auxiliary processes, we don't attempt to continue
    1415             :      * processing after an error; we just clean up and exit.  The autovac
    1416             :      * launcher is responsible for spawning another worker later.
    1417             :      *
    1418             :      * Note that we use sigsetjmp(..., 1), so that the prevailing signal mask
    1419             :      * (to wit, BlockSig) will be restored when longjmp'ing to here.  Thus,
    1420             :      * signals other than SIGQUIT will be blocked until we exit.  It might
    1421             :      * seem that this policy makes the HOLD_INTERRUPTS() call redundant, but
    1422             :      * it is not since InterruptPending might be set already.
    1423             :      */
    1424          20 :     if (sigsetjmp(local_sigjmp_buf, 1) != 0)
    1425             :     {
    1426             :         /* since not using PG_TRY, must reset error stack by hand */
    1427           0 :         error_context_stack = NULL;
    1428             : 
    1429             :         /* Prevents interrupts while cleaning up */
    1430           0 :         HOLD_INTERRUPTS();
    1431             : 
    1432             :         /* Report the error to the server log */
    1433           0 :         EmitErrorReport();
    1434             : 
    1435             :         /*
    1436             :          * We can now go away.  Note that because we called InitProcess, a
    1437             :          * callback was registered to do ProcKill, which will clean up
    1438             :          * necessary state.
    1439             :          */
    1440           0 :         proc_exit(0);
    1441             :     }
    1442             : 
    1443             :     /* We can now handle ereport(ERROR) */
    1444          20 :     PG_exception_stack = &local_sigjmp_buf;
    1445             : 
    1446          20 :     sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
    1447             : 
    1448             :     /*
    1449             :      * Set always-secure search path, so malicious users can't redirect user
    1450             :      * code (e.g. pg_index.indexprs).  (That code runs in a
    1451             :      * SECURITY_RESTRICTED_OPERATION sandbox, so malicious users could not
    1452             :      * take control of the entire autovacuum worker in any case.)
    1453             :      */
    1454          20 :     SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
    1455             : 
    1456             :     /*
    1457             :      * Force zero_damaged_pages OFF in the autovac process, even if it is set
    1458             :      * in postgresql.conf.  We don't really want such a dangerous option being
    1459             :      * applied non-interactively.
    1460             :      */
    1461          20 :     SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);
    1462             : 
    1463             :     /*
    1464             :      * Force settable timeouts off to avoid letting these settings prevent
    1465             :      * regular maintenance from being executed.
    1466             :      */
    1467          20 :     SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
    1468          20 :     SetConfigOption("transaction_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
    1469          20 :     SetConfigOption("lock_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
    1470          20 :     SetConfigOption("idle_in_transaction_session_timeout", "0",
    1471             :                     PGC_SUSET, PGC_S_OVERRIDE);
    1472             : 
    1473             :     /*
    1474             :      * Force default_transaction_isolation to READ COMMITTED.  We don't want
    1475             :      * to pay the overhead of serializable mode, nor add any risk of causing
    1476             :      * deadlocks or delaying other transactions.
    1477             :      */
    1478          20 :     SetConfigOption("default_transaction_isolation", "read committed",
    1479             :                     PGC_SUSET, PGC_S_OVERRIDE);
    1480             : 
    1481             :     /*
    1482             :      * Force synchronous replication off to allow regular maintenance even if
    1483             :      * we are waiting for standbys to connect. This is important to ensure we
    1484             :      * aren't blocked from performing anti-wraparound tasks.
    1485             :      */
    1486          20 :     if (synchronous_commit > SYNCHRONOUS_COMMIT_LOCAL_FLUSH)
    1487          20 :         SetConfigOption("synchronous_commit", "local",
    1488             :                         PGC_SUSET, PGC_S_OVERRIDE);
    1489             : 
    1490             :     /*
    1491             :      * Even when system is configured to use a different fetch consistency,
    1492             :      * for autovac we always want fresh stats.
    1493             :      */
    1494          20 :     SetConfigOption("stats_fetch_consistency", "none", PGC_SUSET, PGC_S_OVERRIDE);
    1495             : 
    1496             :     /*
    1497             :      * Get the info about the database we're going to work on.
    1498             :      */
    1499          20 :     LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
    1500             : 
    1501             :     /*
    1502             :      * beware of startingWorker being INVALID; this should normally not
    1503             :      * happen, but if a worker fails after forking and before this, the
    1504             :      * launcher might have decided to remove it from the queue and start
    1505             :      * again.
    1506             :      */
    1507          20 :     if (AutoVacuumShmem->av_startingWorker != NULL)
    1508             :     {
    1509          20 :         MyWorkerInfo = AutoVacuumShmem->av_startingWorker;
    1510          20 :         dbid = MyWorkerInfo->wi_dboid;
    1511          20 :         MyWorkerInfo->wi_proc = MyProc;
    1512             : 
    1513             :         /* insert into the running list */
    1514          20 :         dlist_push_head(&AutoVacuumShmem->av_runningWorkers,
    1515          20 :                         &MyWorkerInfo->wi_links);
    1516             : 
    1517             :         /*
    1518             :          * remove from the "starting" pointer, so that the launcher can start
    1519             :          * a new worker if required
    1520             :          */
    1521          20 :         AutoVacuumShmem->av_startingWorker = NULL;
    1522          20 :         LWLockRelease(AutovacuumLock);
    1523             : 
    1524          20 :         on_shmem_exit(FreeWorkerInfo, 0);
    1525             : 
    1526             :         /* wake up the launcher */
    1527          20 :         if (AutoVacuumShmem->av_launcherpid != 0)
    1528          20 :             kill(AutoVacuumShmem->av_launcherpid, SIGUSR2);
    1529             :     }
    1530             :     else
    1531             :     {
    1532             :         /* no worker entry for me, go away */
    1533           0 :         elog(WARNING, "autovacuum worker started without a worker entry");
    1534           0 :         dbid = InvalidOid;
    1535           0 :         LWLockRelease(AutovacuumLock);
    1536             :     }
    1537             : 
    1538          20 :     if (OidIsValid(dbid))
    1539             :     {
    1540             :         char        dbname[NAMEDATALEN];
    1541             : 
    1542             :         /*
    1543             :          * Report autovac startup to the cumulative stats system.  We
    1544             :          * deliberately do this before InitPostgres, so that the
    1545             :          * last_autovac_time will get updated even if the connection attempt
    1546             :          * fails.  This is to prevent autovac from getting "stuck" repeatedly
    1547             :          * selecting an unopenable database, rather than making any progress
    1548             :          * on stuff it can connect to.
    1549             :          */
    1550          20 :         pgstat_report_autovac(dbid);
    1551             : 
    1552             :         /*
    1553             :          * Connect to the selected database, specifying no particular user
    1554             :          *
    1555             :          * Note: if we have selected a just-deleted database (due to using
    1556             :          * stale stats info), we'll fail and exit here.
    1557             :          */
    1558          20 :         InitPostgres(NULL, dbid, NULL, InvalidOid, 0, dbname);
    1559          20 :         SetProcessingMode(NormalProcessing);
    1560          20 :         set_ps_display(dbname);
    1561          20 :         ereport(DEBUG1,
    1562             :                 (errmsg_internal("autovacuum: processing database \"%s\"", dbname)));
    1563             : 
    1564          20 :         if (PostAuthDelay)
    1565           0 :             pg_usleep(PostAuthDelay * 1000000L);
    1566             : 
    1567             :         /* And do an appropriate amount of work */
    1568          20 :         recentXid = ReadNextTransactionId();
    1569          20 :         recentMulti = ReadNextMultiXactId();
    1570          20 :         do_autovacuum();
    1571             :     }
    1572             : 
    1573             :     /*
    1574             :      * The launcher will be notified of my death in ProcKill, *if* we managed
    1575             :      * to get a worker slot at all
    1576             :      */
    1577             : 
    1578             :     /* All done, go away */
    1579          20 :     proc_exit(0);
    1580             : }
    1581             : 
    1582             : /*
    1583             :  * Return a WorkerInfo to the free list
    1584             :  */
    1585             : static void
    1586          20 : FreeWorkerInfo(int code, Datum arg)
    1587             : {
    1588          20 :     if (MyWorkerInfo != NULL)
    1589             :     {
    1590          20 :         LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
    1591             : 
    1592             :         /*
    1593             :          * Wake the launcher up so that he can launch a new worker immediately
    1594             :          * if required.  We only save the launcher's PID in local memory here;
    1595             :          * the actual signal will be sent when the PGPROC is recycled.  Note
    1596             :          * that we always do this, so that the launcher can rebalance the cost
    1597             :          * limit setting of the remaining workers.
    1598             :          *
    1599             :          * We somewhat ignore the risk that the launcher changes its PID
    1600             :          * between us reading it and the actual kill; we expect ProcKill to be
    1601             :          * called shortly after us, and we assume that PIDs are not reused too
    1602             :          * quickly after a process exits.
    1603             :          */
    1604          20 :         AutovacuumLauncherPid = AutoVacuumShmem->av_launcherpid;
    1605             : 
    1606          20 :         dlist_delete(&MyWorkerInfo->wi_links);
    1607          20 :         MyWorkerInfo->wi_dboid = InvalidOid;
    1608          20 :         MyWorkerInfo->wi_tableoid = InvalidOid;
    1609          20 :         MyWorkerInfo->wi_sharedrel = false;
    1610          20 :         MyWorkerInfo->wi_proc = NULL;
    1611          20 :         MyWorkerInfo->wi_launchtime = 0;
    1612          20 :         pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance);
    1613          20 :         dlist_push_head(&AutoVacuumShmem->av_freeWorkers,
    1614          20 :                         &MyWorkerInfo->wi_links);
    1615             :         /* not mine anymore */
    1616          20 :         MyWorkerInfo = NULL;
    1617             : 
    1618             :         /*
    1619             :          * now that we're inactive, cause a rebalancing of the surviving
    1620             :          * workers
    1621             :          */
    1622          20 :         AutoVacuumShmem->av_signal[AutoVacRebalance] = true;
    1623          20 :         LWLockRelease(AutovacuumLock);
    1624             :     }
    1625          20 : }
    1626             : 
    1627             : /*
    1628             :  * Update vacuum cost-based delay-related parameters for autovacuum workers and
    1629             :  * backends executing VACUUM or ANALYZE using the value of relevant GUCs and
    1630             :  * global state. This must be called during setup for vacuum and after every
    1631             :  * config reload to ensure up-to-date values.
    1632             :  */
    1633             : void
    1634       10684 : VacuumUpdateCosts(void)
    1635             : {
    1636       10684 :     if (MyWorkerInfo)
    1637             :     {
    1638         260 :         if (av_storage_param_cost_delay >= 0)
    1639           0 :             vacuum_cost_delay = av_storage_param_cost_delay;
    1640         260 :         else if (autovacuum_vac_cost_delay >= 0)
    1641         260 :             vacuum_cost_delay = autovacuum_vac_cost_delay;
    1642             :         else
    1643             :             /* fall back to VacuumCostDelay */
    1644           0 :             vacuum_cost_delay = VacuumCostDelay;
    1645             : 
    1646         260 :         AutoVacuumUpdateCostLimit();
    1647             :     }
    1648             :     else
    1649             :     {
    1650             :         /* Must be explicit VACUUM or ANALYZE */
    1651       10424 :         vacuum_cost_delay = VacuumCostDelay;
    1652       10424 :         vacuum_cost_limit = VacuumCostLimit;
    1653             :     }
    1654             : 
    1655             :     /*
    1656             :      * If configuration changes are allowed to impact VacuumCostActive, make
    1657             :      * sure it is updated.
    1658             :      */
    1659       10684 :     if (VacuumFailsafeActive)
    1660             :         Assert(!VacuumCostActive);
    1661       10684 :     else if (vacuum_cost_delay > 0)
    1662         260 :         VacuumCostActive = true;
    1663             :     else
    1664             :     {
    1665       10424 :         VacuumCostActive = false;
    1666       10424 :         VacuumCostBalance = 0;
    1667             :     }
    1668             : 
    1669             :     /*
    1670             :      * Since the cost logging requires a lock, avoid rendering the log message
    1671             :      * in case we are using a message level where the log wouldn't be emitted.
    1672             :      */
    1673       10684 :     if (MyWorkerInfo && message_level_is_interesting(DEBUG2))
    1674             :     {
    1675             :         Oid         dboid,
    1676             :                     tableoid;
    1677             : 
    1678             :         Assert(!LWLockHeldByMe(AutovacuumLock));
    1679             : 
    1680           0 :         LWLockAcquire(AutovacuumLock, LW_SHARED);
    1681           0 :         dboid = MyWorkerInfo->wi_dboid;
    1682           0 :         tableoid = MyWorkerInfo->wi_tableoid;
    1683           0 :         LWLockRelease(AutovacuumLock);
    1684             : 
    1685           0 :         elog(DEBUG2,
    1686             :              "Autovacuum VacuumUpdateCosts(db=%u, rel=%u, dobalance=%s, cost_limit=%d, cost_delay=%g active=%s failsafe=%s)",
    1687             :              dboid, tableoid, pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance) ? "no" : "yes",
    1688             :              vacuum_cost_limit, vacuum_cost_delay,
    1689             :              vacuum_cost_delay > 0 ? "yes" : "no",
    1690             :              VacuumFailsafeActive ? "yes" : "no");
    1691             :     }
    1692       10684 : }
    1693             : 
    1694             : /*
    1695             :  * Update vacuum_cost_limit with the correct value for an autovacuum worker,
    1696             :  * given the value of other relevant cost limit parameters and the number of
    1697             :  * workers across which the limit must be balanced. Autovacuum workers must
    1698             :  * call this regularly in case av_nworkersForBalance has been updated by
    1699             :  * another worker or by the autovacuum launcher. They must also call it after a
    1700             :  * config reload.
    1701             :  */
    1702             : void
    1703         650 : AutoVacuumUpdateCostLimit(void)
    1704             : {
    1705         650 :     if (!MyWorkerInfo)
    1706           0 :         return;
    1707             : 
    1708             :     /*
    1709             :      * note: in cost_limit, zero also means use value from elsewhere, because
    1710             :      * zero is not a valid value.
    1711             :      */
    1712             : 
    1713         650 :     if (av_storage_param_cost_limit > 0)
    1714           0 :         vacuum_cost_limit = av_storage_param_cost_limit;
    1715             :     else
    1716             :     {
    1717             :         int         nworkers_for_balance;
    1718             : 
    1719         650 :         if (autovacuum_vac_cost_limit > 0)
    1720           0 :             vacuum_cost_limit = autovacuum_vac_cost_limit;
    1721             :         else
    1722         650 :             vacuum_cost_limit = VacuumCostLimit;
    1723             : 
    1724             :         /* Only balance limit if no cost-related storage parameters specified */
    1725         650 :         if (pg_atomic_unlocked_test_flag(&MyWorkerInfo->wi_dobalance))
    1726           0 :             return;
    1727             : 
    1728             :         Assert(vacuum_cost_limit > 0);
    1729             : 
    1730         650 :         nworkers_for_balance = pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
    1731             : 
    1732             :         /* There is at least 1 autovac worker (this worker) */
    1733         650 :         if (nworkers_for_balance <= 0)
    1734           0 :             elog(ERROR, "nworkers_for_balance must be > 0");
    1735             : 
    1736         650 :         vacuum_cost_limit = Max(vacuum_cost_limit / nworkers_for_balance, 1);
    1737             :     }
    1738             : }
    1739             : 
    1740             : /*
    1741             :  * autovac_recalculate_workers_for_balance
    1742             :  *      Recalculate the number of workers to consider, given cost-related
    1743             :  *      storage parameters and the current number of active workers.
    1744             :  *
    1745             :  * Caller must hold the AutovacuumLock in at least shared mode to access
    1746             :  * worker->wi_proc.
    1747             :  */
    1748             : static void
    1749         150 : autovac_recalculate_workers_for_balance(void)
    1750             : {
    1751             :     dlist_iter  iter;
    1752             :     int         orig_nworkers_for_balance;
    1753         150 :     int         nworkers_for_balance = 0;
    1754             : 
    1755             :     Assert(LWLockHeldByMe(AutovacuumLock));
    1756             : 
    1757         150 :     orig_nworkers_for_balance =
    1758         150 :         pg_atomic_read_u32(&AutoVacuumShmem->av_nworkersForBalance);
    1759             : 
    1760         280 :     dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers)
    1761             :     {
    1762         130 :         WorkerInfo  worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
    1763             : 
    1764         260 :         if (worker->wi_proc == NULL ||
    1765         130 :             pg_atomic_unlocked_test_flag(&worker->wi_dobalance))
    1766           0 :             continue;
    1767             : 
    1768         130 :         nworkers_for_balance++;
    1769             :     }
    1770             : 
    1771         150 :     if (nworkers_for_balance != orig_nworkers_for_balance)
    1772          28 :         pg_atomic_write_u32(&AutoVacuumShmem->av_nworkersForBalance,
    1773             :                             nworkers_for_balance);
    1774         150 : }
    1775             : 
    1776             : /*
    1777             :  * get_database_list
    1778             :  *      Return a list of all databases found in pg_database.
    1779             :  *
    1780             :  * The list and associated data is allocated in the caller's memory context,
    1781             :  * which is in charge of ensuring that it's properly cleaned up afterwards.
    1782             :  *
    1783             :  * Note: this is the only function in which the autovacuum launcher uses a
    1784             :  * transaction.  Although we aren't attached to any particular database and
    1785             :  * therefore can't access most catalogs, we do have enough infrastructure
    1786             :  * to do a seqscan on pg_database.
    1787             :  */
    1788             : static List *
    1789         794 : get_database_list(void)
    1790             : {
    1791         794 :     List       *dblist = NIL;
    1792             :     Relation    rel;
    1793             :     TableScanDesc scan;
    1794             :     HeapTuple   tup;
    1795             :     MemoryContext resultcxt;
    1796             : 
    1797             :     /* This is the context that we will allocate our output data in */
    1798         794 :     resultcxt = CurrentMemoryContext;
    1799             : 
    1800             :     /*
    1801             :      * Start a transaction so we can access pg_database, and get a snapshot.
    1802             :      * We don't have a use for the snapshot itself, but we're interested in
    1803             :      * the secondary effect that it sets RecentGlobalXmin.  (This is critical
    1804             :      * for anything that reads heap pages, because HOT may decide to prune
    1805             :      * them even if the process doesn't attempt to modify any tuples.)
    1806             :      *
    1807             :      * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
    1808             :      * not pushed/active does not reliably prevent HOT pruning (->xmin could
    1809             :      * e.g. be cleared when cache invalidations are processed).
    1810             :      */
    1811         794 :     StartTransactionCommand();
    1812         794 :     (void) GetTransactionSnapshot();
    1813             : 
    1814         794 :     rel = table_open(DatabaseRelationId, AccessShareLock);
    1815         794 :     scan = table_beginscan_catalog(rel, 0, NULL);
    1816             : 
    1817        3510 :     while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
    1818             :     {
    1819        2716 :         Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
    1820             :         avw_dbase  *avdb;
    1821             :         MemoryContext oldcxt;
    1822             : 
    1823             :         /*
    1824             :          * If database has partially been dropped, we can't, nor need to,
    1825             :          * vacuum it.
    1826             :          */
    1827        2716 :         if (database_is_invalid_form(pgdatabase))
    1828             :         {
    1829           2 :             elog(DEBUG2,
    1830             :                  "autovacuum: skipping invalid database \"%s\"",
    1831             :                  NameStr(pgdatabase->datname));
    1832           2 :             continue;
    1833             :         }
    1834             : 
    1835             :         /*
    1836             :          * Allocate our results in the caller's context, not the
    1837             :          * transaction's. We do this inside the loop, and restore the original
    1838             :          * context at the end, so that leaky things like heap_getnext() are
    1839             :          * not called in a potentially long-lived context.
    1840             :          */
    1841        2714 :         oldcxt = MemoryContextSwitchTo(resultcxt);
    1842             : 
    1843        2714 :         avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
    1844             : 
    1845        2714 :         avdb->adw_datid = pgdatabase->oid;
    1846        2714 :         avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
    1847        2714 :         avdb->adw_frozenxid = pgdatabase->datfrozenxid;
    1848        2714 :         avdb->adw_minmulti = pgdatabase->datminmxid;
    1849             :         /* this gets set later: */
    1850        2714 :         avdb->adw_entry = NULL;
    1851             : 
    1852        2714 :         dblist = lappend(dblist, avdb);
    1853        2714 :         MemoryContextSwitchTo(oldcxt);
    1854             :     }
    1855             : 
    1856         794 :     table_endscan(scan);
    1857         794 :     table_close(rel, AccessShareLock);
    1858             : 
    1859         794 :     CommitTransactionCommand();
    1860             : 
    1861             :     /* Be sure to restore caller's memory context */
    1862         794 :     MemoryContextSwitchTo(resultcxt);
    1863             : 
    1864         794 :     return dblist;
    1865             : }
    1866             : 
    1867             : /*
    1868             :  * Process a database table-by-table
    1869             :  *
    1870             :  * Note that CHECK_FOR_INTERRUPTS is supposed to be used in certain spots in
    1871             :  * order not to ignore shutdown commands for too long.
    1872             :  */
    1873             : static void
    1874          20 : do_autovacuum(void)
    1875             : {
    1876             :     Relation    classRel;
    1877             :     HeapTuple   tuple;
    1878             :     TableScanDesc relScan;
    1879             :     Form_pg_database dbForm;
    1880          20 :     List       *table_oids = NIL;
    1881          20 :     List       *orphan_oids = NIL;
    1882             :     HASHCTL     ctl;
    1883             :     HTAB       *table_toast_map;
    1884             :     ListCell   *volatile cell;
    1885             :     BufferAccessStrategy bstrategy;
    1886             :     ScanKeyData key;
    1887             :     TupleDesc   pg_class_desc;
    1888             :     int         effective_multixact_freeze_max_age;
    1889          20 :     bool        did_vacuum = false;
    1890          20 :     bool        found_concurrent_worker = false;
    1891             :     int         i;
    1892             : 
    1893             :     /*
    1894             :      * StartTransactionCommand and CommitTransactionCommand will automatically
    1895             :      * switch to other contexts.  We need this one to keep the list of
    1896             :      * relations to vacuum/analyze across transactions.
    1897             :      */
    1898          20 :     AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
    1899             :                                           "Autovacuum worker",
    1900             :                                           ALLOCSET_DEFAULT_SIZES);
    1901          20 :     MemoryContextSwitchTo(AutovacMemCxt);
    1902             : 
    1903             :     /* Start a transaction so our commands have one to play into. */
    1904          20 :     StartTransactionCommand();
    1905             : 
    1906             :     /*
    1907             :      * This injection point is put in a transaction block to work with a wait
    1908             :      * that uses a condition variable.
    1909             :      */
    1910             :     INJECTION_POINT("autovacuum-worker-start");
    1911             : 
    1912             :     /*
    1913             :      * Compute the multixact age for which freezing is urgent.  This is
    1914             :      * normally autovacuum_multixact_freeze_max_age, but may be less if we are
    1915             :      * short of multixact member space.
    1916             :      */
    1917          20 :     effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();
    1918             : 
    1919             :     /*
    1920             :      * Find the pg_database entry and select the default freeze ages. We use
    1921             :      * zero in template and nonconnectable databases, else the system-wide
    1922             :      * default.
    1923             :      */
    1924          20 :     tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
    1925          20 :     if (!HeapTupleIsValid(tuple))
    1926           0 :         elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
    1927          20 :     dbForm = (Form_pg_database) GETSTRUCT(tuple);
    1928             : 
    1929          20 :     if (dbForm->datistemplate || !dbForm->datallowconn)
    1930             :     {
    1931           4 :         default_freeze_min_age = 0;
    1932           4 :         default_freeze_table_age = 0;
    1933           4 :         default_multixact_freeze_min_age = 0;
    1934           4 :         default_multixact_freeze_table_age = 0;
    1935             :     }
    1936             :     else
    1937             :     {
    1938          16 :         default_freeze_min_age = vacuum_freeze_min_age;
    1939          16 :         default_freeze_table_age = vacuum_freeze_table_age;
    1940          16 :         default_multixact_freeze_min_age = vacuum_multixact_freeze_min_age;
    1941          16 :         default_multixact_freeze_table_age = vacuum_multixact_freeze_table_age;
    1942             :     }
    1943             : 
    1944          20 :     ReleaseSysCache(tuple);
    1945             : 
    1946             :     /* StartTransactionCommand changed elsewhere */
    1947          20 :     MemoryContextSwitchTo(AutovacMemCxt);
    1948             : 
    1949          20 :     classRel = table_open(RelationRelationId, AccessShareLock);
    1950             : 
    1951             :     /* create a copy so we can use it after closing pg_class */
    1952          20 :     pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
    1953             : 
    1954             :     /* create hash table for toast <-> main relid mapping */
    1955          20 :     ctl.keysize = sizeof(Oid);
    1956          20 :     ctl.entrysize = sizeof(av_relation);
    1957             : 
    1958          20 :     table_toast_map = hash_create("TOAST to main relid map",
    1959             :                                   100,
    1960             :                                   &ctl,
    1961             :                                   HASH_ELEM | HASH_BLOBS);
    1962             : 
    1963             :     /*
    1964             :      * Scan pg_class to determine which tables to vacuum.
    1965             :      *
    1966             :      * We do this in two passes: on the first one we collect the list of plain
    1967             :      * relations and materialized views, and on the second one we collect
    1968             :      * TOAST tables. The reason for doing the second pass is that during it we
    1969             :      * want to use the main relation's pg_class.reloptions entry if the TOAST
    1970             :      * table does not have any, and we cannot obtain it unless we know
    1971             :      * beforehand what's the main table OID.
    1972             :      *
    1973             :      * We need to check TOAST tables separately because in cases with short,
    1974             :      * wide tables there might be proportionally much more activity in the
    1975             :      * TOAST table than in its parent.
    1976             :      */
    1977          20 :     relScan = table_beginscan_catalog(classRel, 0, NULL);
    1978             : 
    1979             :     /*
    1980             :      * On the first pass, we collect main tables to vacuum, and also the main
    1981             :      * table relid to TOAST relid mapping.
    1982             :      */
    1983       11180 :     while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
    1984             :     {
    1985       11160 :         Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
    1986             :         PgStat_StatTabEntry *tabentry;
    1987             :         AutoVacOpts *relopts;
    1988             :         Oid         relid;
    1989             :         bool        dovacuum;
    1990             :         bool        doanalyze;
    1991             :         bool        wraparound;
    1992             : 
    1993       11160 :         if (classForm->relkind != RELKIND_RELATION &&
    1994        8752 :             classForm->relkind != RELKIND_MATVIEW)
    1995        8750 :             continue;
    1996             : 
    1997        2424 :         relid = classForm->oid;
    1998             : 
    1999             :         /*
    2000             :          * Check if it is a temp table (presumably, of some other backend's).
    2001             :          * We cannot safely process other backends' temp tables.
    2002             :          */
    2003        2424 :         if (classForm->relpersistence == RELPERSISTENCE_TEMP)
    2004             :         {
    2005             :             /*
    2006             :              * We just ignore it if the owning backend is still active and
    2007             :              * using the temporary schema.  Also, for safety, ignore it if the
    2008             :              * namespace doesn't exist or isn't a temp namespace after all.
    2009             :              */
    2010          14 :             if (checkTempNamespaceStatus(classForm->relnamespace) == TEMP_NAMESPACE_IDLE)
    2011             :             {
    2012             :                 /*
    2013             :                  * The table seems to be orphaned -- although it might be that
    2014             :                  * the owning backend has already deleted it and exited; our
    2015             :                  * pg_class scan snapshot is not necessarily up-to-date
    2016             :                  * anymore, so we could be looking at a committed-dead entry.
    2017             :                  * Remember it so we can try to delete it later.
    2018             :                  */
    2019           0 :                 orphan_oids = lappend_oid(orphan_oids, relid);
    2020             :             }
    2021          14 :             continue;
    2022             :         }
    2023             : 
    2024             :         /* Fetch reloptions and the pgstat entry for this table */
    2025        2410 :         relopts = extract_autovac_opts(tuple, pg_class_desc);
    2026        2410 :         tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
    2027             :                                                   relid);
    2028             : 
    2029             :         /* Check if it needs vacuum or analyze */
    2030        2410 :         relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
    2031             :                                   effective_multixact_freeze_max_age,
    2032             :                                   &dovacuum, &doanalyze, &wraparound);
    2033             : 
    2034             :         /* Relations that need work are added to table_oids */
    2035        2410 :         if (dovacuum || doanalyze)
    2036         130 :             table_oids = lappend_oid(table_oids, relid);
    2037             : 
    2038             :         /*
    2039             :          * Remember TOAST associations for the second pass.  Note: we must do
    2040             :          * this whether or not the table is going to be vacuumed, because we
    2041             :          * don't automatically vacuum toast tables along the parent table.
    2042             :          */
    2043        2410 :         if (OidIsValid(classForm->reltoastrelid))
    2044             :         {
    2045             :             av_relation *hentry;
    2046             :             bool        found;
    2047             : 
    2048        2556 :             hentry = hash_search(table_toast_map,
    2049        1278 :                                  &classForm->reltoastrelid,
    2050             :                                  HASH_ENTER, &found);
    2051             : 
    2052        1278 :             if (!found)
    2053             :             {
    2054             :                 /* hash_search already filled in the key */
    2055        1278 :                 hentry->ar_relid = relid;
    2056        1278 :                 hentry->ar_hasrelopts = false;
    2057        1278 :                 if (relopts != NULL)
    2058             :                 {
    2059          20 :                     hentry->ar_hasrelopts = true;
    2060          20 :                     memcpy(&hentry->ar_reloptions, relopts,
    2061             :                            sizeof(AutoVacOpts));
    2062             :                 }
    2063             :             }
    2064             :         }
    2065             :     }
    2066             : 
    2067          20 :     table_endscan(relScan);
    2068             : 
    2069             :     /* second pass: check TOAST tables */
    2070          20 :     ScanKeyInit(&key,
    2071             :                 Anum_pg_class_relkind,
    2072             :                 BTEqualStrategyNumber, F_CHAREQ,
    2073             :                 CharGetDatum(RELKIND_TOASTVALUE));
    2074             : 
    2075          20 :     relScan = table_beginscan_catalog(classRel, 1, &key);
    2076        1304 :     while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
    2077             :     {
    2078        1284 :         Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
    2079             :         PgStat_StatTabEntry *tabentry;
    2080             :         Oid         relid;
    2081        1284 :         AutoVacOpts *relopts = NULL;
    2082             :         bool        dovacuum;
    2083             :         bool        doanalyze;
    2084             :         bool        wraparound;
    2085             : 
    2086             :         /*
    2087             :          * We cannot safely process other backends' temp tables, so skip 'em.
    2088             :          */
    2089        1284 :         if (classForm->relpersistence == RELPERSISTENCE_TEMP)
    2090           0 :             continue;
    2091             : 
    2092        1284 :         relid = classForm->oid;
    2093             : 
    2094             :         /*
    2095             :          * fetch reloptions -- if this toast table does not have them, try the
    2096             :          * main rel
    2097             :          */
    2098        1284 :         relopts = extract_autovac_opts(tuple, pg_class_desc);
    2099        1284 :         if (relopts == NULL)
    2100             :         {
    2101             :             av_relation *hentry;
    2102             :             bool        found;
    2103             : 
    2104        1282 :             hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
    2105        1282 :             if (found && hentry->ar_hasrelopts)
    2106          18 :                 relopts = &hentry->ar_reloptions;
    2107             :         }
    2108             : 
    2109             :         /* Fetch the pgstat entry for this table */
    2110        1284 :         tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
    2111             :                                                   relid);
    2112             : 
    2113        1284 :         relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
    2114             :                                   effective_multixact_freeze_max_age,
    2115             :                                   &dovacuum, &doanalyze, &wraparound);
    2116             : 
    2117             :         /* ignore analyze for toast tables */
    2118        1284 :         if (dovacuum)
    2119           0 :             table_oids = lappend_oid(table_oids, relid);
    2120             :     }
    2121             : 
    2122          20 :     table_endscan(relScan);
    2123          20 :     table_close(classRel, AccessShareLock);
    2124             : 
    2125             :     /*
    2126             :      * Recheck orphan temporary tables, and if they still seem orphaned, drop
    2127             :      * them.  We'll eat a transaction per dropped table, which might seem
    2128             :      * excessive, but we should only need to do anything as a result of a
    2129             :      * previous backend crash, so this should not happen often enough to
    2130             :      * justify "optimizing".  Using separate transactions ensures that we
    2131             :      * don't bloat the lock table if there are many temp tables to be dropped,
    2132             :      * and it ensures that we don't lose work if a deletion attempt fails.
    2133             :      */
    2134          20 :     foreach(cell, orphan_oids)
    2135             :     {
    2136           0 :         Oid         relid = lfirst_oid(cell);
    2137             :         Form_pg_class classForm;
    2138             :         ObjectAddress object;
    2139             : 
    2140             :         /*
    2141             :          * Check for user-requested abort.
    2142             :          */
    2143           0 :         CHECK_FOR_INTERRUPTS();
    2144             : 
    2145             :         /*
    2146             :          * Try to lock the table.  If we can't get the lock immediately,
    2147             :          * somebody else is using (or dropping) the table, so it's not our
    2148             :          * concern anymore.  Having the lock prevents race conditions below.
    2149             :          */
    2150           0 :         if (!ConditionalLockRelationOid(relid, AccessExclusiveLock))
    2151           0 :             continue;
    2152             : 
    2153             :         /*
    2154             :          * Re-fetch the pg_class tuple and re-check whether it still seems to
    2155             :          * be an orphaned temp table.  If it's not there or no longer the same
    2156             :          * relation, ignore it.
    2157             :          */
    2158           0 :         tuple = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
    2159           0 :         if (!HeapTupleIsValid(tuple))
    2160             :         {
    2161             :             /* be sure to drop useless lock so we don't bloat lock table */
    2162           0 :             UnlockRelationOid(relid, AccessExclusiveLock);
    2163           0 :             continue;
    2164             :         }
    2165           0 :         classForm = (Form_pg_class) GETSTRUCT(tuple);
    2166             : 
    2167             :         /*
    2168             :          * Make all the same tests made in the loop above.  In event of OID
    2169             :          * counter wraparound, the pg_class entry we have now might be
    2170             :          * completely unrelated to the one we saw before.
    2171             :          */
    2172           0 :         if (!((classForm->relkind == RELKIND_RELATION ||
    2173           0 :                classForm->relkind == RELKIND_MATVIEW) &&
    2174           0 :               classForm->relpersistence == RELPERSISTENCE_TEMP))
    2175             :         {
    2176           0 :             UnlockRelationOid(relid, AccessExclusiveLock);
    2177           0 :             continue;
    2178             :         }
    2179             : 
    2180           0 :         if (checkTempNamespaceStatus(classForm->relnamespace) != TEMP_NAMESPACE_IDLE)
    2181             :         {
    2182           0 :             UnlockRelationOid(relid, AccessExclusiveLock);
    2183           0 :             continue;
    2184             :         }
    2185             : 
    2186             :         /*
    2187             :          * Try to lock the temp namespace, too.  Even though we have lock on
    2188             :          * the table itself, there's a risk of deadlock against an incoming
    2189             :          * backend trying to clean out the temp namespace, in case this table
    2190             :          * has dependencies (such as sequences) that the backend's
    2191             :          * performDeletion call might visit in a different order.  If we can
    2192             :          * get AccessShareLock on the namespace, that's sufficient to ensure
    2193             :          * we're not running concurrently with RemoveTempRelations.  If we
    2194             :          * can't, back off and let RemoveTempRelations do its thing.
    2195             :          */
    2196           0 :         if (!ConditionalLockDatabaseObject(NamespaceRelationId,
    2197             :                                            classForm->relnamespace, 0,
    2198             :                                            AccessShareLock))
    2199             :         {
    2200           0 :             UnlockRelationOid(relid, AccessExclusiveLock);
    2201           0 :             continue;
    2202             :         }
    2203             : 
    2204             :         /* OK, let's delete it */
    2205           0 :         ereport(LOG,
    2206             :                 (errmsg("autovacuum: dropping orphan temp table \"%s.%s.%s\"",
    2207             :                         get_database_name(MyDatabaseId),
    2208             :                         get_namespace_name(classForm->relnamespace),
    2209             :                         NameStr(classForm->relname))));
    2210             : 
    2211           0 :         object.classId = RelationRelationId;
    2212           0 :         object.objectId = relid;
    2213           0 :         object.objectSubId = 0;
    2214           0 :         performDeletion(&object, DROP_CASCADE,
    2215             :                         PERFORM_DELETION_INTERNAL |
    2216             :                         PERFORM_DELETION_QUIETLY |
    2217             :                         PERFORM_DELETION_SKIP_EXTENSIONS);
    2218             : 
    2219             :         /*
    2220             :          * To commit the deletion, end current transaction and start a new
    2221             :          * one.  Note this also releases the locks we took.
    2222             :          */
    2223           0 :         CommitTransactionCommand();
    2224           0 :         StartTransactionCommand();
    2225             : 
    2226             :         /* StartTransactionCommand changed current memory context */
    2227           0 :         MemoryContextSwitchTo(AutovacMemCxt);
    2228             :     }
    2229             : 
    2230             :     /*
    2231             :      * Optionally, create a buffer access strategy object for VACUUM to use.
    2232             :      * We use the same BufferAccessStrategy object for all tables VACUUMed by
    2233             :      * this worker to prevent autovacuum from blowing out shared buffers.
    2234             :      *
    2235             :      * VacuumBufferUsageLimit being set to 0 results in
    2236             :      * GetAccessStrategyWithSize returning NULL, effectively meaning we can
    2237             :      * use up to all of shared buffers.
    2238             :      *
    2239             :      * If we later enter failsafe mode on any of the tables being vacuumed, we
    2240             :      * will cease use of the BufferAccessStrategy only for that table.
    2241             :      *
    2242             :      * XXX should we consider adding code to adjust the size of this if
    2243             :      * VacuumBufferUsageLimit changes?
    2244             :      */
    2245          20 :     bstrategy = GetAccessStrategyWithSize(BAS_VACUUM, VacuumBufferUsageLimit);
    2246             : 
    2247             :     /*
    2248             :      * create a memory context to act as fake PortalContext, so that the
    2249             :      * contexts created in the vacuum code are cleaned up for each table.
    2250             :      */
    2251          20 :     PortalContext = AllocSetContextCreate(AutovacMemCxt,
    2252             :                                           "Autovacuum Portal",
    2253             :                                           ALLOCSET_DEFAULT_SIZES);
    2254             : 
    2255             :     /*
    2256             :      * Perform operations on collected tables.
    2257             :      */
    2258         150 :     foreach(cell, table_oids)
    2259             :     {
    2260         130 :         Oid         relid = lfirst_oid(cell);
    2261             :         HeapTuple   classTup;
    2262             :         autovac_table *tab;
    2263             :         bool        isshared;
    2264             :         bool        skipit;
    2265             :         dlist_iter  iter;
    2266             : 
    2267         130 :         CHECK_FOR_INTERRUPTS();
    2268             : 
    2269             :         /*
    2270             :          * Check for config changes before processing each collected table.
    2271             :          */
    2272         130 :         if (ConfigReloadPending)
    2273             :         {
    2274           0 :             ConfigReloadPending = false;
    2275           0 :             ProcessConfigFile(PGC_SIGHUP);
    2276             : 
    2277             :             /*
    2278             :              * You might be tempted to bail out if we see autovacuum is now
    2279             :              * disabled.  Must resist that temptation -- this might be a
    2280             :              * for-wraparound emergency worker, in which case that would be
    2281             :              * entirely inappropriate.
    2282             :              */
    2283             :         }
    2284             : 
    2285             :         /*
    2286             :          * Find out whether the table is shared or not.  (It's slightly
    2287             :          * annoying to fetch the syscache entry just for this, but in typical
    2288             :          * cases it adds little cost because table_recheck_autovac would
    2289             :          * refetch the entry anyway.  We could buy that back by copying the
    2290             :          * tuple here and passing it to table_recheck_autovac, but that
    2291             :          * increases the odds of that function working with stale data.)
    2292             :          */
    2293         130 :         classTup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
    2294         130 :         if (!HeapTupleIsValid(classTup))
    2295           0 :             continue;           /* somebody deleted the rel, forget it */
    2296         130 :         isshared = ((Form_pg_class) GETSTRUCT(classTup))->relisshared;
    2297         130 :         ReleaseSysCache(classTup);
    2298             : 
    2299             :         /*
    2300             :          * Hold schedule lock from here until we've claimed the table.  We
    2301             :          * also need the AutovacuumLock to walk the worker array, but that one
    2302             :          * can just be a shared lock.
    2303             :          */
    2304         130 :         LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
    2305         130 :         LWLockAcquire(AutovacuumLock, LW_SHARED);
    2306             : 
    2307             :         /*
    2308             :          * Check whether the table is being vacuumed concurrently by another
    2309             :          * worker.
    2310             :          */
    2311         130 :         skipit = false;
    2312         260 :         dlist_foreach(iter, &AutoVacuumShmem->av_runningWorkers)
    2313             :         {
    2314         130 :             WorkerInfo  worker = dlist_container(WorkerInfoData, wi_links, iter.cur);
    2315             : 
    2316             :             /* ignore myself */
    2317         130 :             if (worker == MyWorkerInfo)
    2318         130 :                 continue;
    2319             : 
    2320             :             /* ignore workers in other databases (unless table is shared) */
    2321           0 :             if (!worker->wi_sharedrel && worker->wi_dboid != MyDatabaseId)
    2322           0 :                 continue;
    2323             : 
    2324           0 :             if (worker->wi_tableoid == relid)
    2325             :             {
    2326           0 :                 skipit = true;
    2327           0 :                 found_concurrent_worker = true;
    2328           0 :                 break;
    2329             :             }
    2330             :         }
    2331         130 :         LWLockRelease(AutovacuumLock);
    2332         130 :         if (skipit)
    2333             :         {
    2334           0 :             LWLockRelease(AutovacuumScheduleLock);
    2335           0 :             continue;
    2336             :         }
    2337             : 
    2338             :         /*
    2339             :          * Store the table's OID in shared memory before releasing the
    2340             :          * schedule lock, so that other workers don't try to vacuum it
    2341             :          * concurrently.  (We claim it here so as not to hold
    2342             :          * AutovacuumScheduleLock while rechecking the stats.)
    2343             :          */
    2344         130 :         MyWorkerInfo->wi_tableoid = relid;
    2345         130 :         MyWorkerInfo->wi_sharedrel = isshared;
    2346         130 :         LWLockRelease(AutovacuumScheduleLock);
    2347             : 
    2348             :         /*
    2349             :          * Check whether pgstat data still says we need to vacuum this table.
    2350             :          * It could have changed if something else processed the table while
    2351             :          * we weren't looking. This doesn't entirely close the race condition,
    2352             :          * but it is very small.
    2353             :          */
    2354         130 :         MemoryContextSwitchTo(AutovacMemCxt);
    2355         130 :         tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc,
    2356             :                                     effective_multixact_freeze_max_age);
    2357         130 :         if (tab == NULL)
    2358             :         {
    2359             :             /* someone else vacuumed the table, or it went away */
    2360           0 :             LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
    2361           0 :             MyWorkerInfo->wi_tableoid = InvalidOid;
    2362           0 :             MyWorkerInfo->wi_sharedrel = false;
    2363           0 :             LWLockRelease(AutovacuumScheduleLock);
    2364           0 :             continue;
    2365             :         }
    2366             : 
    2367             :         /*
    2368             :          * Save the cost-related storage parameter values in global variables
    2369             :          * for reference when updating vacuum_cost_delay and vacuum_cost_limit
    2370             :          * during vacuuming this table.
    2371             :          */
    2372         130 :         av_storage_param_cost_delay = tab->at_storage_param_vac_cost_delay;
    2373         130 :         av_storage_param_cost_limit = tab->at_storage_param_vac_cost_limit;
    2374             : 
    2375             :         /*
    2376             :          * We only expect this worker to ever set the flag, so don't bother
    2377             :          * checking the return value. We shouldn't have to retry.
    2378             :          */
    2379         130 :         if (tab->at_dobalance)
    2380         130 :             pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance);
    2381             :         else
    2382           0 :             pg_atomic_clear_flag(&MyWorkerInfo->wi_dobalance);
    2383             : 
    2384         130 :         LWLockAcquire(AutovacuumLock, LW_SHARED);
    2385         130 :         autovac_recalculate_workers_for_balance();
    2386         130 :         LWLockRelease(AutovacuumLock);
    2387             : 
    2388             :         /*
    2389             :          * We wait until this point to update cost delay and cost limit
    2390             :          * values, even though we reloaded the configuration file above, so
    2391             :          * that we can take into account the cost-related storage parameters.
    2392             :          */
    2393         130 :         VacuumUpdateCosts();
    2394             : 
    2395             : 
    2396             :         /* clean up memory before each iteration */
    2397         130 :         MemoryContextReset(PortalContext);
    2398             : 
    2399             :         /*
    2400             :          * Save the relation name for a possible error message, to avoid a
    2401             :          * catalog lookup in case of an error.  If any of these return NULL,
    2402             :          * then the relation has been dropped since last we checked; skip it.
    2403             :          * Note: they must live in a long-lived memory context because we call
    2404             :          * vacuum and analyze in different transactions.
    2405             :          */
    2406             : 
    2407         130 :         tab->at_relname = get_rel_name(tab->at_relid);
    2408         130 :         tab->at_nspname = get_namespace_name(get_rel_namespace(tab->at_relid));
    2409         130 :         tab->at_datname = get_database_name(MyDatabaseId);
    2410         130 :         if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
    2411           0 :             goto deleted;
    2412             : 
    2413             :         /*
    2414             :          * We will abort vacuuming the current table if something errors out,
    2415             :          * and continue with the next one in schedule; in particular, this
    2416             :          * happens if we are interrupted with SIGINT.
    2417             :          */
    2418         130 :         PG_TRY();
    2419             :         {
    2420             :             /* Use PortalContext for any per-table allocations */
    2421         130 :             MemoryContextSwitchTo(PortalContext);
    2422             : 
    2423             :             /* have at it */
    2424         130 :             autovacuum_do_vac_analyze(tab, bstrategy);
    2425             : 
    2426             :             /*
    2427             :              * Clear a possible query-cancel signal, to avoid a late reaction
    2428             :              * to an automatically-sent signal because of vacuuming the
    2429             :              * current table (we're done with it, so it would make no sense to
    2430             :              * cancel at this point.)
    2431             :              */
    2432         130 :             QueryCancelPending = false;
    2433             :         }
    2434           0 :         PG_CATCH();
    2435             :         {
    2436             :             /*
    2437             :              * Abort the transaction, start a new one, and proceed with the
    2438             :              * next table in our list.
    2439             :              */
    2440           0 :             HOLD_INTERRUPTS();
    2441           0 :             if (tab->at_params.options & VACOPT_VACUUM)
    2442           0 :                 errcontext("automatic vacuum of table \"%s.%s.%s\"",
    2443             :                            tab->at_datname, tab->at_nspname, tab->at_relname);
    2444             :             else
    2445           0 :                 errcontext("automatic analyze of table \"%s.%s.%s\"",
    2446             :                            tab->at_datname, tab->at_nspname, tab->at_relname);
    2447           0 :             EmitErrorReport();
    2448             : 
    2449             :             /* this resets ProcGlobal->statusFlags[i] too */
    2450           0 :             AbortOutOfAnyTransaction();
    2451           0 :             FlushErrorState();
    2452           0 :             MemoryContextReset(PortalContext);
    2453             : 
    2454             :             /* restart our transaction for the following operations */
    2455           0 :             StartTransactionCommand();
    2456           0 :             RESUME_INTERRUPTS();
    2457             :         }
    2458         130 :         PG_END_TRY();
    2459             : 
    2460             :         /* Make sure we're back in AutovacMemCxt */
    2461         130 :         MemoryContextSwitchTo(AutovacMemCxt);
    2462             : 
    2463         130 :         did_vacuum = true;
    2464             : 
    2465             :         /* ProcGlobal->statusFlags[i] are reset at the next end of xact */
    2466             : 
    2467             :         /* be tidy */
    2468         130 : deleted:
    2469         130 :         if (tab->at_datname != NULL)
    2470         130 :             pfree(tab->at_datname);
    2471         130 :         if (tab->at_nspname != NULL)
    2472         130 :             pfree(tab->at_nspname);
    2473         130 :         if (tab->at_relname != NULL)
    2474         130 :             pfree(tab->at_relname);
    2475         130 :         pfree(tab);
    2476             : 
    2477             :         /*
    2478             :          * Remove my info from shared memory.  We set wi_dobalance on the
    2479             :          * assumption that we are more likely than not to vacuum a table with
    2480             :          * no cost-related storage parameters next, so we want to claim our
    2481             :          * share of I/O as soon as possible to avoid thrashing the global
    2482             :          * balance.
    2483             :          */
    2484         130 :         LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
    2485         130 :         MyWorkerInfo->wi_tableoid = InvalidOid;
    2486         130 :         MyWorkerInfo->wi_sharedrel = false;
    2487         130 :         LWLockRelease(AutovacuumScheduleLock);
    2488         130 :         pg_atomic_test_set_flag(&MyWorkerInfo->wi_dobalance);
    2489             :     }
    2490             : 
    2491             :     /*
    2492             :      * Perform additional work items, as requested by backends.
    2493             :      */
    2494          20 :     LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
    2495        5140 :     for (i = 0; i < NUM_WORKITEMS; i++)
    2496             :     {
    2497        5120 :         AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i];
    2498             : 
    2499        5120 :         if (!workitem->avw_used)
    2500        5114 :             continue;
    2501           6 :         if (workitem->avw_active)
    2502           0 :             continue;
    2503           6 :         if (workitem->avw_database != MyDatabaseId)
    2504           0 :             continue;
    2505             : 
    2506             :         /* claim this one, and release lock while performing it */
    2507           6 :         workitem->avw_active = true;
    2508           6 :         LWLockRelease(AutovacuumLock);
    2509             : 
    2510           6 :         perform_work_item(workitem);
    2511             : 
    2512             :         /*
    2513             :          * Check for config changes before acquiring lock for further jobs.
    2514             :          */
    2515           6 :         CHECK_FOR_INTERRUPTS();
    2516           6 :         if (ConfigReloadPending)
    2517             :         {
    2518           0 :             ConfigReloadPending = false;
    2519           0 :             ProcessConfigFile(PGC_SIGHUP);
    2520           0 :             VacuumUpdateCosts();
    2521             :         }
    2522             : 
    2523           6 :         LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
    2524             : 
    2525             :         /* and mark it done */
    2526           6 :         workitem->avw_active = false;
    2527           6 :         workitem->avw_used = false;
    2528             :     }
    2529          20 :     LWLockRelease(AutovacuumLock);
    2530             : 
    2531             :     /*
    2532             :      * We leak table_toast_map here (among other things), but since we're
    2533             :      * going away soon, it's not a problem.
    2534             :      */
    2535             : 
    2536             :     /*
    2537             :      * Update pg_database.datfrozenxid, and truncate pg_xact if possible. We
    2538             :      * only need to do this once, not after each table.
    2539             :      *
    2540             :      * Even if we didn't vacuum anything, it may still be important to do
    2541             :      * this, because one indirect effect of vac_update_datfrozenxid() is to
    2542             :      * update TransamVariables->xidVacLimit.  That might need to be done even
    2543             :      * if we haven't vacuumed anything, because relations with older
    2544             :      * relfrozenxid values or other databases with older datfrozenxid values
    2545             :      * might have been dropped, allowing xidVacLimit to advance.
    2546             :      *
    2547             :      * However, it's also important not to do this blindly in all cases,
    2548             :      * because when autovacuum=off this will restart the autovacuum launcher.
    2549             :      * If we're not careful, an infinite loop can result, where workers find
    2550             :      * no work to do and restart the launcher, which starts another worker in
    2551             :      * the same database that finds no work to do.  To prevent that, we skip
    2552             :      * this if (1) we found no work to do and (2) we skipped at least one
    2553             :      * table due to concurrent autovacuum activity.  In that case, the other
    2554             :      * worker has already done it, or will do so when it finishes.
    2555             :      */
    2556          20 :     if (did_vacuum || !found_concurrent_worker)
    2557          20 :         vac_update_datfrozenxid();
    2558             : 
    2559             :     /* Finally close out the last transaction. */
    2560          20 :     CommitTransactionCommand();
    2561          20 : }
    2562             : 
    2563             : /*
    2564             :  * Execute a previously registered work item.
    2565             :  */
    2566             : static void
    2567           6 : perform_work_item(AutoVacuumWorkItem *workitem)
    2568             : {
    2569           6 :     char       *cur_datname = NULL;
    2570           6 :     char       *cur_nspname = NULL;
    2571           6 :     char       *cur_relname = NULL;
    2572             : 
    2573             :     /*
    2574             :      * Note we do not store table info in MyWorkerInfo, since this is not
    2575             :      * vacuuming proper.
    2576             :      */
    2577             : 
    2578             :     /*
    2579             :      * Save the relation name for a possible error message, to avoid a catalog
    2580             :      * lookup in case of an error.  If any of these return NULL, then the
    2581             :      * relation has been dropped since last we checked; skip it.
    2582             :      */
    2583             :     Assert(CurrentMemoryContext == AutovacMemCxt);
    2584             : 
    2585           6 :     cur_relname = get_rel_name(workitem->avw_relation);
    2586           6 :     cur_nspname = get_namespace_name(get_rel_namespace(workitem->avw_relation));
    2587           6 :     cur_datname = get_database_name(MyDatabaseId);
    2588           6 :     if (!cur_relname || !cur_nspname || !cur_datname)
    2589           0 :         goto deleted2;
    2590             : 
    2591           6 :     autovac_report_workitem(workitem, cur_nspname, cur_relname);
    2592             : 
    2593             :     /* clean up memory before each work item */
    2594           6 :     MemoryContextReset(PortalContext);
    2595             : 
    2596             :     /*
    2597             :      * We will abort the current work item if something errors out, and
    2598             :      * continue with the next one; in particular, this happens if we are
    2599             :      * interrupted with SIGINT.  Note that this means that the work item list
    2600             :      * can be lossy.
    2601             :      */
    2602           6 :     PG_TRY();
    2603             :     {
    2604             :         /* Use PortalContext for any per-work-item allocations */
    2605           6 :         MemoryContextSwitchTo(PortalContext);
    2606             : 
    2607             :         /*
    2608             :          * Have at it.  Functions called here are responsible for any required
    2609             :          * user switch and sandbox.
    2610             :          */
    2611           6 :         switch (workitem->avw_type)
    2612             :         {
    2613           6 :             case AVW_BRINSummarizeRange:
    2614           6 :                 DirectFunctionCall2(brin_summarize_range,
    2615             :                                     ObjectIdGetDatum(workitem->avw_relation),
    2616             :                                     Int64GetDatum((int64) workitem->avw_blockNumber));
    2617           6 :                 break;
    2618           0 :             default:
    2619           0 :                 elog(WARNING, "unrecognized work item found: type %d",
    2620             :                      workitem->avw_type);
    2621           0 :                 break;
    2622             :         }
    2623             : 
    2624             :         /*
    2625             :          * Clear a possible query-cancel signal, to avoid a late reaction to
    2626             :          * an automatically-sent signal because of vacuuming the current table
    2627             :          * (we're done with it, so it would make no sense to cancel at this
    2628             :          * point.)
    2629             :          */
    2630           6 :         QueryCancelPending = false;
    2631             :     }
    2632           0 :     PG_CATCH();
    2633             :     {
    2634             :         /*
    2635             :          * Abort the transaction, start a new one, and proceed with the next
    2636             :          * table in our list.
    2637             :          */
    2638           0 :         HOLD_INTERRUPTS();
    2639           0 :         errcontext("processing work entry for relation \"%s.%s.%s\"",
    2640             :                    cur_datname, cur_nspname, cur_relname);
    2641           0 :         EmitErrorReport();
    2642             : 
    2643             :         /* this resets ProcGlobal->statusFlags[i] too */
    2644           0 :         AbortOutOfAnyTransaction();
    2645           0 :         FlushErrorState();
    2646           0 :         MemoryContextReset(PortalContext);
    2647             : 
    2648             :         /* restart our transaction for the following operations */
    2649           0 :         StartTransactionCommand();
    2650           0 :         RESUME_INTERRUPTS();
    2651             :     }
    2652           6 :     PG_END_TRY();
    2653             : 
    2654             :     /* Make sure we're back in AutovacMemCxt */
    2655           6 :     MemoryContextSwitchTo(AutovacMemCxt);
    2656             : 
    2657             :     /* We intentionally do not set did_vacuum here */
    2658             : 
    2659             :     /* be tidy */
    2660           6 : deleted2:
    2661           6 :     if (cur_datname)
    2662           6 :         pfree(cur_datname);
    2663           6 :     if (cur_nspname)
    2664           6 :         pfree(cur_nspname);
    2665           6 :     if (cur_relname)
    2666           6 :         pfree(cur_relname);
    2667           6 : }
    2668             : 
    2669             : /*
    2670             :  * extract_autovac_opts
    2671             :  *
    2672             :  * Given a relation's pg_class tuple, return the AutoVacOpts portion of
    2673             :  * reloptions, if set; otherwise, return NULL.
    2674             :  *
    2675             :  * Note: callers do not have a relation lock on the table at this point,
    2676             :  * so the table could have been dropped, and its catalog rows gone, after
    2677             :  * we acquired the pg_class row.  If pg_class had a TOAST table, this would
    2678             :  * be a risk; fortunately, it doesn't.
    2679             :  */
    2680             : static AutoVacOpts *
    2681        3824 : extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
    2682             : {
    2683             :     bytea      *relopts;
    2684             :     AutoVacOpts *av;
    2685             : 
    2686             :     Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
    2687             :            ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_MATVIEW ||
    2688             :            ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
    2689             : 
    2690        3824 :     relopts = extractRelOptions(tup, pg_class_desc, NULL);
    2691        3824 :     if (relopts == NULL)
    2692        3780 :         return NULL;
    2693             : 
    2694          44 :     av = palloc(sizeof(AutoVacOpts));
    2695          44 :     memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
    2696          44 :     pfree(relopts);
    2697             : 
    2698          44 :     return av;
    2699             : }
    2700             : 
    2701             : 
    2702             : /*
    2703             :  * table_recheck_autovac
    2704             :  *
    2705             :  * Recheck whether a table still needs vacuum or analyze.  Return value is a
    2706             :  * valid autovac_table pointer if it does, NULL otherwise.
    2707             :  *
    2708             :  * Note that the returned autovac_table does not have the name fields set.
    2709             :  */
    2710             : static autovac_table *
    2711         130 : table_recheck_autovac(Oid relid, HTAB *table_toast_map,
    2712             :                       TupleDesc pg_class_desc,
    2713             :                       int effective_multixact_freeze_max_age)
    2714             : {
    2715             :     Form_pg_class classForm;
    2716             :     HeapTuple   classTup;
    2717             :     bool        dovacuum;
    2718             :     bool        doanalyze;
    2719         130 :     autovac_table *tab = NULL;
    2720             :     bool        wraparound;
    2721             :     AutoVacOpts *avopts;
    2722             : 
    2723             :     /* fetch the relation's relcache entry */
    2724         130 :     classTup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
    2725         130 :     if (!HeapTupleIsValid(classTup))
    2726           0 :         return NULL;
    2727         130 :     classForm = (Form_pg_class) GETSTRUCT(classTup);
    2728             : 
    2729             :     /*
    2730             :      * Get the applicable reloptions.  If it is a TOAST table, try to get the
    2731             :      * main table reloptions if the toast table itself doesn't have.
    2732             :      */
    2733         130 :     avopts = extract_autovac_opts(classTup, pg_class_desc);
    2734         130 :     if (classForm->relkind == RELKIND_TOASTVALUE &&
    2735           0 :         avopts == NULL && table_toast_map != NULL)
    2736             :     {
    2737             :         av_relation *hentry;
    2738             :         bool        found;
    2739             : 
    2740           0 :         hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
    2741           0 :         if (found && hentry->ar_hasrelopts)
    2742           0 :             avopts = &hentry->ar_reloptions;
    2743             :     }
    2744             : 
    2745         130 :     recheck_relation_needs_vacanalyze(relid, avopts, classForm,
    2746             :                                       effective_multixact_freeze_max_age,
    2747             :                                       &dovacuum, &doanalyze, &wraparound);
    2748             : 
    2749             :     /* OK, it needs something done */
    2750         130 :     if (doanalyze || dovacuum)
    2751             :     {
    2752             :         int         freeze_min_age;
    2753             :         int         freeze_table_age;
    2754             :         int         multixact_freeze_min_age;
    2755             :         int         multixact_freeze_table_age;
    2756             :         int         log_min_duration;
    2757             : 
    2758             :         /*
    2759             :          * Calculate the vacuum cost parameters and the freeze ages.  If there
    2760             :          * are options set in pg_class.reloptions, use them; in the case of a
    2761             :          * toast table, try the main table too.  Otherwise use the GUC
    2762             :          * defaults, autovacuum's own first and plain vacuum second.
    2763             :          */
    2764             : 
    2765             :         /* -1 in autovac setting means use log_autovacuum_min_duration */
    2766           2 :         log_min_duration = (avopts && avopts->log_min_duration >= 0)
    2767             :             ? avopts->log_min_duration
    2768         132 :             : Log_autovacuum_min_duration;
    2769             : 
    2770             :         /* these do not have autovacuum-specific settings */
    2771           2 :         freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
    2772             :             ? avopts->freeze_min_age
    2773         132 :             : default_freeze_min_age;
    2774             : 
    2775           2 :         freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
    2776             :             ? avopts->freeze_table_age
    2777         132 :             : default_freeze_table_age;
    2778             : 
    2779         132 :         multixact_freeze_min_age = (avopts &&
    2780           2 :                                     avopts->multixact_freeze_min_age >= 0)
    2781             :             ? avopts->multixact_freeze_min_age
    2782         132 :             : default_multixact_freeze_min_age;
    2783             : 
    2784         132 :         multixact_freeze_table_age = (avopts &&
    2785           2 :                                       avopts->multixact_freeze_table_age >= 0)
    2786             :             ? avopts->multixact_freeze_table_age
    2787         132 :             : default_multixact_freeze_table_age;
    2788             : 
    2789         130 :         tab = palloc(sizeof(autovac_table));
    2790         130 :         tab->at_relid = relid;
    2791         130 :         tab->at_sharedrel = classForm->relisshared;
    2792             : 
    2793             :         /*
    2794             :          * Select VACUUM options.  Note we don't say VACOPT_PROCESS_TOAST, so
    2795             :          * that vacuum() skips toast relations.  Also note we tell vacuum() to
    2796             :          * skip vac_update_datfrozenxid(); we'll do that separately.
    2797             :          */
    2798         130 :         tab->at_params.options =
    2799         130 :             (dovacuum ? (VACOPT_VACUUM |
    2800             :                          VACOPT_PROCESS_MAIN |
    2801         130 :                          VACOPT_SKIP_DATABASE_STATS) : 0) |
    2802         130 :             (doanalyze ? VACOPT_ANALYZE : 0) |
    2803         130 :             (!wraparound ? VACOPT_SKIP_LOCKED : 0);
    2804             : 
    2805             :         /*
    2806             :          * index_cleanup and truncate are unspecified at first in autovacuum.
    2807             :          * They will be filled in with usable values using their reloptions
    2808             :          * (or reloption defaults) later.
    2809             :          */
    2810         130 :         tab->at_params.index_cleanup = VACOPTVALUE_UNSPECIFIED;
    2811         130 :         tab->at_params.truncate = VACOPTVALUE_UNSPECIFIED;
    2812             :         /* As of now, we don't support parallel vacuum for autovacuum */
    2813         130 :         tab->at_params.nworkers = -1;
    2814         130 :         tab->at_params.freeze_min_age = freeze_min_age;
    2815         130 :         tab->at_params.freeze_table_age = freeze_table_age;
    2816         130 :         tab->at_params.multixact_freeze_min_age = multixact_freeze_min_age;
    2817         130 :         tab->at_params.multixact_freeze_table_age = multixact_freeze_table_age;
    2818         130 :         tab->at_params.is_wraparound = wraparound;
    2819         130 :         tab->at_params.log_min_duration = log_min_duration;
    2820         130 :         tab->at_params.toast_parent = InvalidOid;
    2821         130 :         tab->at_storage_param_vac_cost_limit = avopts ?
    2822         130 :             avopts->vacuum_cost_limit : 0;
    2823         130 :         tab->at_storage_param_vac_cost_delay = avopts ?
    2824         130 :             avopts->vacuum_cost_delay : -1;
    2825         130 :         tab->at_relname = NULL;
    2826         130 :         tab->at_nspname = NULL;
    2827         130 :         tab->at_datname = NULL;
    2828             : 
    2829             :         /*
    2830             :          * If any of the cost delay parameters has been set individually for
    2831             :          * this table, disable the balancing algorithm.
    2832             :          */
    2833         130 :         tab->at_dobalance =
    2834         132 :             !(avopts && (avopts->vacuum_cost_limit > 0 ||
    2835           2 :                          avopts->vacuum_cost_delay >= 0));
    2836             :     }
    2837             : 
    2838         130 :     heap_freetuple(classTup);
    2839         130 :     return tab;
    2840             : }
    2841             : 
    2842             : /*
    2843             :  * recheck_relation_needs_vacanalyze
    2844             :  *
    2845             :  * Subroutine for table_recheck_autovac.
    2846             :  *
    2847             :  * Fetch the pgstat of a relation and recheck whether a relation
    2848             :  * needs to be vacuumed or analyzed.
    2849             :  */
    2850             : static void
    2851         130 : recheck_relation_needs_vacanalyze(Oid relid,
    2852             :                                   AutoVacOpts *avopts,
    2853             :                                   Form_pg_class classForm,
    2854             :                                   int effective_multixact_freeze_max_age,
    2855             :                                   bool *dovacuum,
    2856             :                                   bool *doanalyze,
    2857             :                                   bool *wraparound)
    2858             : {
    2859             :     PgStat_StatTabEntry *tabentry;
    2860             : 
    2861             :     /* fetch the pgstat table entry */
    2862         130 :     tabentry = pgstat_fetch_stat_tabentry_ext(classForm->relisshared,
    2863             :                                               relid);
    2864             : 
    2865         130 :     relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
    2866             :                               effective_multixact_freeze_max_age,
    2867             :                               dovacuum, doanalyze, wraparound);
    2868             : 
    2869             :     /* ignore ANALYZE for toast tables */
    2870         130 :     if (classForm->relkind == RELKIND_TOASTVALUE)
    2871           0 :         *doanalyze = false;
    2872         130 : }
    2873             : 
    2874             : /*
    2875             :  * relation_needs_vacanalyze
    2876             :  *
    2877             :  * Check whether a relation needs to be vacuumed or analyzed; return each into
    2878             :  * "dovacuum" and "doanalyze", respectively.  Also return whether the vacuum is
    2879             :  * being forced because of Xid or multixact wraparound.
    2880             :  *
    2881             :  * relopts is a pointer to the AutoVacOpts options (either for itself in the
    2882             :  * case of a plain table, or for either itself or its parent table in the case
    2883             :  * of a TOAST table), NULL if none; tabentry is the pgstats entry, which can be
    2884             :  * NULL.
    2885             :  *
    2886             :  * A table needs to be vacuumed if the number of dead tuples exceeds a
    2887             :  * threshold.  This threshold is calculated as
    2888             :  *
    2889             :  * threshold = vac_base_thresh + vac_scale_factor * reltuples
    2890             :  *
    2891             :  * For analyze, the analysis done is that the number of tuples inserted,
    2892             :  * deleted and updated since the last analyze exceeds a threshold calculated
    2893             :  * in the same fashion as above.  Note that the cumulative stats system stores
    2894             :  * the number of tuples (both live and dead) that there were as of the last
    2895             :  * analyze.  This is asymmetric to the VACUUM case.
    2896             :  *
    2897             :  * We also force vacuum if the table's relfrozenxid is more than freeze_max_age
    2898             :  * transactions back, and if its relminmxid is more than
    2899             :  * multixact_freeze_max_age multixacts back.
    2900             :  *
    2901             :  * A table whose autovacuum_enabled option is false is
    2902             :  * automatically skipped (unless we have to vacuum it due to freeze_max_age).
    2903             :  * Thus autovacuum can be disabled for specific tables. Also, when the cumulative
    2904             :  * stats system does not have data about a table, it will be skipped.
    2905             :  *
    2906             :  * A table whose vac_base_thresh value is < 0 takes the base value from the
    2907             :  * autovacuum_vacuum_threshold GUC variable.  Similarly, a vac_scale_factor
    2908             :  * value < 0 is substituted with the value of
    2909             :  * autovacuum_vacuum_scale_factor GUC variable.  Ditto for analyze.
    2910             :  */
    2911             : static void
    2912        3824 : relation_needs_vacanalyze(Oid relid,
    2913             :                           AutoVacOpts *relopts,
    2914             :                           Form_pg_class classForm,
    2915             :                           PgStat_StatTabEntry *tabentry,
    2916             :                           int effective_multixact_freeze_max_age,
    2917             :  /* output params below */
    2918             :                           bool *dovacuum,
    2919             :                           bool *doanalyze,
    2920             :                           bool *wraparound)
    2921             : {
    2922             :     bool        force_vacuum;
    2923             :     bool        av_enabled;
    2924             :     float4      reltuples;      /* pg_class.reltuples */
    2925             : 
    2926             :     /* constants from reloptions or GUC variables */
    2927             :     int         vac_base_thresh,
    2928             :                 vac_ins_base_thresh,
    2929             :                 anl_base_thresh;
    2930             :     float4      vac_scale_factor,
    2931             :                 vac_ins_scale_factor,
    2932             :                 anl_scale_factor;
    2933             : 
    2934             :     /* thresholds calculated from above constants */
    2935             :     float4      vacthresh,
    2936             :                 vacinsthresh,
    2937             :                 anlthresh;
    2938             : 
    2939             :     /* number of vacuum (resp. analyze) tuples at this time */
    2940             :     float4      vactuples,
    2941             :                 instuples,
    2942             :                 anltuples;
    2943             : 
    2944             :     /* freeze parameters */
    2945             :     int         freeze_max_age;
    2946             :     int         multixact_freeze_max_age;
    2947             :     TransactionId xidForceLimit;
    2948             :     TransactionId relfrozenxid;
    2949             :     MultiXactId multiForceLimit;
    2950             : 
    2951             :     Assert(classForm != NULL);
    2952             :     Assert(OidIsValid(relid));
    2953             : 
    2954             :     /*
    2955             :      * Determine vacuum/analyze equation parameters.  We have two possible
    2956             :      * sources: the passed reloptions (which could be a main table or a toast
    2957             :      * table), or the autovacuum GUC variables.
    2958             :      */
    2959             : 
    2960             :     /* -1 in autovac setting means use plain vacuum_scale_factor */
    2961          62 :     vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
    2962           0 :         ? relopts->vacuum_scale_factor
    2963        3886 :         : autovacuum_vac_scale;
    2964             : 
    2965          62 :     vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
    2966             :         ? relopts->vacuum_threshold
    2967        3886 :         : autovacuum_vac_thresh;
    2968             : 
    2969          62 :     vac_ins_scale_factor = (relopts && relopts->vacuum_ins_scale_factor >= 0)
    2970           0 :         ? relopts->vacuum_ins_scale_factor
    2971        3886 :         : autovacuum_vac_ins_scale;
    2972             : 
    2973             :     /* -1 is used to disable insert vacuums */
    2974          62 :     vac_ins_base_thresh = (relopts && relopts->vacuum_ins_threshold >= -1)
    2975             :         ? relopts->vacuum_ins_threshold
    2976        3886 :         : autovacuum_vac_ins_thresh;
    2977             : 
    2978          62 :     anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
    2979           0 :         ? relopts->analyze_scale_factor
    2980        3886 :         : autovacuum_anl_scale;
    2981             : 
    2982          62 :     anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
    2983             :         ? relopts->analyze_threshold
    2984        3886 :         : autovacuum_anl_thresh;
    2985             : 
    2986          62 :     freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
    2987           0 :         ? Min(relopts->freeze_max_age, autovacuum_freeze_max_age)
    2988        3886 :         : autovacuum_freeze_max_age;
    2989             : 
    2990          62 :     multixact_freeze_max_age = (relopts && relopts->multixact_freeze_max_age >= 0)
    2991           0 :         ? Min(relopts->multixact_freeze_max_age, effective_multixact_freeze_max_age)
    2992        3886 :         : effective_multixact_freeze_max_age;
    2993             : 
    2994        3824 :     av_enabled = (relopts ? relopts->enabled : true);
    2995             : 
    2996             :     /* Force vacuum if table is at risk of wraparound */
    2997        3824 :     xidForceLimit = recentXid - freeze_max_age;
    2998        3824 :     if (xidForceLimit < FirstNormalTransactionId)
    2999           0 :         xidForceLimit -= FirstNormalTransactionId;
    3000        3824 :     relfrozenxid = classForm->relfrozenxid;
    3001        7648 :     force_vacuum = (TransactionIdIsNormal(relfrozenxid) &&
    3002        3824 :                     TransactionIdPrecedes(relfrozenxid, xidForceLimit));
    3003        3824 :     if (!force_vacuum)
    3004             :     {
    3005        3824 :         MultiXactId relminmxid = classForm->relminmxid;
    3006             : 
    3007        3824 :         multiForceLimit = recentMulti - multixact_freeze_max_age;
    3008        3824 :         if (multiForceLimit < FirstMultiXactId)
    3009           0 :             multiForceLimit -= FirstMultiXactId;
    3010        7648 :         force_vacuum = MultiXactIdIsValid(relminmxid) &&
    3011        3824 :             MultiXactIdPrecedes(relminmxid, multiForceLimit);
    3012             :     }
    3013        3824 :     *wraparound = force_vacuum;
    3014             : 
    3015             :     /* User disabled it in pg_class.reloptions?  (But ignore if at risk) */
    3016        3824 :     if (!av_enabled && !force_vacuum)
    3017             :     {
    3018          42 :         *doanalyze = false;
    3019          42 :         *dovacuum = false;
    3020          42 :         return;
    3021             :     }
    3022             : 
    3023             :     /*
    3024             :      * If we found stats for the table, and autovacuum is currently enabled,
    3025             :      * make a threshold-based decision whether to vacuum and/or analyze.  If
    3026             :      * autovacuum is currently disabled, we must be here for anti-wraparound
    3027             :      * vacuuming only, so don't vacuum (or analyze) anything that's not being
    3028             :      * forced.
    3029             :      */
    3030        3782 :     if (PointerIsValid(tabentry) && AutoVacuumingActive())
    3031             :     {
    3032        2606 :         reltuples = classForm->reltuples;
    3033        2606 :         vactuples = tabentry->dead_tuples;
    3034        2606 :         instuples = tabentry->ins_since_vacuum;
    3035        2606 :         anltuples = tabentry->mod_since_analyze;
    3036             : 
    3037             :         /* If the table hasn't yet been vacuumed, take reltuples as zero */
    3038        2606 :         if (reltuples < 0)
    3039         818 :             reltuples = 0;
    3040             : 
    3041        2606 :         vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
    3042        2606 :         vacinsthresh = (float4) vac_ins_base_thresh + vac_ins_scale_factor * reltuples;
    3043        2606 :         anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;
    3044             : 
    3045             :         /*
    3046             :          * Note that we don't need to take special consideration for stat
    3047             :          * reset, because if that happens, the last vacuum and analyze counts
    3048             :          * will be reset too.
    3049             :          */
    3050        2606 :         if (vac_ins_base_thresh >= 0)
    3051        2606 :             elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
    3052             :                  NameStr(classForm->relname),
    3053             :                  vactuples, vacthresh, instuples, vacinsthresh, anltuples, anlthresh);
    3054             :         else
    3055           0 :             elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), ins: (disabled), anl: %.0f (threshold %.0f)",
    3056             :                  NameStr(classForm->relname),
    3057             :                  vactuples, vacthresh, anltuples, anlthresh);
    3058             : 
    3059             :         /* Determine if this table needs vacuum or analyze. */
    3060        5132 :         *dovacuum = force_vacuum || (vactuples > vacthresh) ||
    3061        2526 :             (vac_ins_base_thresh >= 0 && instuples > vacinsthresh);
    3062        2606 :         *doanalyze = (anltuples > anlthresh);
    3063             :     }
    3064             :     else
    3065             :     {
    3066             :         /*
    3067             :          * Skip a table not found in stat hash, unless we have to force vacuum
    3068             :          * for anti-wrap purposes.  If it's not acted upon, there's no need to
    3069             :          * vacuum it.
    3070             :          */
    3071        1176 :         *dovacuum = force_vacuum;
    3072        1176 :         *doanalyze = false;
    3073             :     }
    3074             : 
    3075             :     /* ANALYZE refuses to work with pg_statistic */
    3076        3782 :     if (relid == StatisticRelationId)
    3077          22 :         *doanalyze = false;
    3078             : }
    3079             : 
    3080             : /*
    3081             :  * autovacuum_do_vac_analyze
    3082             :  *      Vacuum and/or analyze the specified table
    3083             :  *
    3084             :  * We expect the caller to have switched into a memory context that won't
    3085             :  * disappear at transaction commit.
    3086             :  */
    3087             : static void
    3088         130 : autovacuum_do_vac_analyze(autovac_table *tab, BufferAccessStrategy bstrategy)
    3089             : {
    3090             :     RangeVar   *rangevar;
    3091             :     VacuumRelation *rel;
    3092             :     List       *rel_list;
    3093             :     MemoryContext vac_context;
    3094             : 
    3095             :     /* Let pgstat know what we're doing */
    3096         130 :     autovac_report_activity(tab);
    3097             : 
    3098             :     /* Set up one VacuumRelation target, identified by OID, for vacuum() */
    3099         130 :     rangevar = makeRangeVar(tab->at_nspname, tab->at_relname, -1);
    3100         130 :     rel = makeVacuumRelation(rangevar, tab->at_relid, NIL);
    3101         130 :     rel_list = list_make1(rel);
    3102             : 
    3103         130 :     vac_context = AllocSetContextCreate(CurrentMemoryContext,
    3104             :                                         "Vacuum",
    3105             :                                         ALLOCSET_DEFAULT_SIZES);
    3106             : 
    3107         130 :     vacuum(rel_list, &tab->at_params, bstrategy, vac_context, true);
    3108             : 
    3109         130 :     MemoryContextDelete(vac_context);
    3110         130 : }
    3111             : 
    3112             : /*
    3113             :  * autovac_report_activity
    3114             :  *      Report to pgstat what autovacuum is doing
    3115             :  *
    3116             :  * We send a SQL string corresponding to what the user would see if the
    3117             :  * equivalent command was to be issued manually.
    3118             :  *
    3119             :  * Note we assume that we are going to report the next command as soon as we're
    3120             :  * done with the current one, and exit right after the last one, so we don't
    3121             :  * bother to report "<IDLE>" or some such.
    3122             :  */
    3123             : static void
    3124         130 : autovac_report_activity(autovac_table *tab)
    3125             : {
    3126             : #define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
    3127             :     char        activity[MAX_AUTOVAC_ACTIV_LEN];
    3128             :     int         len;
    3129             : 
    3130             :     /* Report the command and possible options */
    3131         130 :     if (tab->at_params.options & VACOPT_VACUUM)
    3132          54 :         snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
    3133             :                  "autovacuum: VACUUM%s",
    3134          54 :                  tab->at_params.options & VACOPT_ANALYZE ? " ANALYZE" : "");
    3135             :     else
    3136          76 :         snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
    3137             :                  "autovacuum: ANALYZE");
    3138             : 
    3139             :     /*
    3140             :      * Report the qualified name of the relation.
    3141             :      */
    3142         130 :     len = strlen(activity);
    3143             : 
    3144         130 :     snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
    3145             :              " %s.%s%s", tab->at_nspname, tab->at_relname,
    3146         130 :              tab->at_params.is_wraparound ? " (to prevent wraparound)" : "");
    3147             : 
    3148             :     /* Set statement_timestamp() to current time for pg_stat_activity */
    3149         130 :     SetCurrentStatementStartTimestamp();
    3150             : 
    3151         130 :     pgstat_report_activity(STATE_RUNNING, activity);
    3152         130 : }
    3153             : 
    3154             : /*
    3155             :  * autovac_report_workitem
    3156             :  *      Report to pgstat that autovacuum is processing a work item
    3157             :  */
    3158             : static void
    3159           6 : autovac_report_workitem(AutoVacuumWorkItem *workitem,
    3160             :                         const char *nspname, const char *relname)
    3161             : {
    3162             :     char        activity[MAX_AUTOVAC_ACTIV_LEN + 12 + 2];
    3163             :     char        blk[12 + 2];
    3164             :     int         len;
    3165             : 
    3166           6 :     switch (workitem->avw_type)
    3167             :     {
    3168           6 :         case AVW_BRINSummarizeRange:
    3169           6 :             snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
    3170             :                      "autovacuum: BRIN summarize");
    3171           6 :             break;
    3172             :     }
    3173             : 
    3174             :     /*
    3175             :      * Report the qualified name of the relation, and the block number if any
    3176             :      */
    3177           6 :     len = strlen(activity);
    3178             : 
    3179           6 :     if (BlockNumberIsValid(workitem->avw_blockNumber))
    3180           6 :         snprintf(blk, sizeof(blk), " %u", workitem->avw_blockNumber);
    3181             :     else
    3182           0 :         blk[0] = '\0';
    3183             : 
    3184           6 :     snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
    3185             :              " %s.%s%s", nspname, relname, blk);
    3186             : 
    3187             :     /* Set statement_timestamp() to current time for pg_stat_activity */
    3188           6 :     SetCurrentStatementStartTimestamp();
    3189             : 
    3190           6 :     pgstat_report_activity(STATE_RUNNING, activity);
    3191           6 : }
    3192             : 
    3193             : /*
    3194             :  * AutoVacuumingActive
    3195             :  *      Check GUC vars and report whether the autovacuum process should be
    3196             :  *      running.
    3197             :  */
    3198             : bool
    3199       15904 : AutoVacuumingActive(void)
    3200             : {
    3201       15904 :     if (!autovacuum_start_daemon || !pgstat_track_counts)
    3202        6228 :         return false;
    3203        9676 :     return true;
    3204             : }
    3205             : 
    3206             : /*
    3207             :  * Request one work item to the next autovacuum run processing our database.
    3208             :  * Return false if the request can't be recorded.
    3209             :  */
    3210             : bool
    3211           6 : AutoVacuumRequestWork(AutoVacuumWorkItemType type, Oid relationId,
    3212             :                       BlockNumber blkno)
    3213             : {
    3214             :     int         i;
    3215           6 :     bool        result = false;
    3216             : 
    3217           6 :     LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
    3218             : 
    3219             :     /*
    3220             :      * Locate an unused work item and fill it with the given data.
    3221             :      */
    3222          12 :     for (i = 0; i < NUM_WORKITEMS; i++)
    3223             :     {
    3224          12 :         AutoVacuumWorkItem *workitem = &AutoVacuumShmem->av_workItems[i];
    3225             : 
    3226          12 :         if (workitem->avw_used)
    3227           6 :             continue;
    3228             : 
    3229           6 :         workitem->avw_used = true;
    3230           6 :         workitem->avw_active = false;
    3231           6 :         workitem->avw_type = type;
    3232           6 :         workitem->avw_database = MyDatabaseId;
    3233           6 :         workitem->avw_relation = relationId;
    3234           6 :         workitem->avw_blockNumber = blkno;
    3235           6 :         result = true;
    3236             : 
    3237             :         /* done */
    3238           6 :         break;
    3239             :     }
    3240             : 
    3241           6 :     LWLockRelease(AutovacuumLock);
    3242             : 
    3243           6 :     return result;
    3244             : }
    3245             : 
    3246             : /*
    3247             :  * autovac_init
    3248             :  *      This is called at postmaster initialization.
    3249             :  *
    3250             :  * All we do here is annoy the user if he got it wrong.
    3251             :  */
    3252             : void
    3253        1436 : autovac_init(void)
    3254             : {
    3255        1436 :     if (autovacuum_start_daemon && !pgstat_track_counts)
    3256           0 :         ereport(WARNING,
    3257             :                 (errmsg("autovacuum not started because of misconfiguration"),
    3258             :                  errhint("Enable the \"track_counts\" option.")));
    3259        1436 : }
    3260             : 
    3261             : /*
    3262             :  * AutoVacuumShmemSize
    3263             :  *      Compute space needed for autovacuum-related shared memory
    3264             :  */
    3265             : Size
    3266        5108 : AutoVacuumShmemSize(void)
    3267             : {
    3268             :     Size        size;
    3269             : 
    3270             :     /*
    3271             :      * Need the fixed struct and the array of WorkerInfoData.
    3272             :      */
    3273        5108 :     size = sizeof(AutoVacuumShmemStruct);
    3274        5108 :     size = MAXALIGN(size);
    3275        5108 :     size = add_size(size, mul_size(autovacuum_max_workers,
    3276             :                                    sizeof(WorkerInfoData)));
    3277        5108 :     return size;
    3278             : }
    3279             : 
    3280             : /*
    3281             :  * AutoVacuumShmemInit
    3282             :  *      Allocate and initialize autovacuum-related shared memory
    3283             :  */
    3284             : void
    3285        1782 : AutoVacuumShmemInit(void)
    3286             : {
    3287             :     bool        found;
    3288             : 
    3289        1782 :     AutoVacuumShmem = (AutoVacuumShmemStruct *)
    3290        1782 :         ShmemInitStruct("AutoVacuum Data",
    3291             :                         AutoVacuumShmemSize(),
    3292             :                         &found);
    3293             : 
    3294        1782 :     if (!IsUnderPostmaster)
    3295             :     {
    3296             :         WorkerInfo  worker;
    3297             :         int         i;
    3298             : 
    3299             :         Assert(!found);
    3300             : 
    3301        1782 :         AutoVacuumShmem->av_launcherpid = 0;
    3302        1782 :         dlist_init(&AutoVacuumShmem->av_freeWorkers);
    3303        1782 :         dlist_init(&AutoVacuumShmem->av_runningWorkers);
    3304        1782 :         AutoVacuumShmem->av_startingWorker = NULL;
    3305        1782 :         memset(AutoVacuumShmem->av_workItems, 0,
    3306             :                sizeof(AutoVacuumWorkItem) * NUM_WORKITEMS);
    3307             : 
    3308        1782 :         worker = (WorkerInfo) ((char *) AutoVacuumShmem +
    3309             :                                MAXALIGN(sizeof(AutoVacuumShmemStruct)));
    3310             : 
    3311             :         /* initialize the WorkerInfo free list */
    3312        7128 :         for (i = 0; i < autovacuum_max_workers; i++)
    3313             :         {
    3314        5346 :             dlist_push_head(&AutoVacuumShmem->av_freeWorkers,
    3315        5346 :                             &worker[i].wi_links);
    3316        5346 :             pg_atomic_init_flag(&worker[i].wi_dobalance);
    3317             :         }
    3318             : 
    3319        1782 :         pg_atomic_init_u32(&AutoVacuumShmem->av_nworkersForBalance, 0);
    3320             : 
    3321             :     }
    3322             :     else
    3323             :         Assert(found);
    3324        1782 : }
    3325             : 
    3326             : /*
    3327             :  * GUC check_hook for autovacuum_work_mem
    3328             :  */
    3329             : bool
    3330        1848 : check_autovacuum_work_mem(int *newval, void **extra, GucSource source)
    3331             : {
    3332             :     /*
    3333             :      * -1 indicates fallback.
    3334             :      *
    3335             :      * If we haven't yet changed the boot_val default of -1, just let it be.
    3336             :      * Autovacuum will look to maintenance_work_mem instead.
    3337             :      */
    3338        1848 :     if (*newval == -1)
    3339        1844 :         return true;
    3340             : 
    3341             :     /*
    3342             :      * We clamp manually-set values to at least 1MB.  Since
    3343             :      * maintenance_work_mem is always set to at least this value, do the same
    3344             :      * here.
    3345             :      */
    3346           4 :     if (*newval < 1024)
    3347           4 :         *newval = 1024;
    3348             : 
    3349           4 :     return true;
    3350             : }

Generated by: LCOV version 1.14