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

Generated by: LCOV version 1.14