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

Generated by: LCOV version 1.14