LCOV - code coverage report
Current view: top level - src/backend/postmaster - autovacuum.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 83.5 % 1027 858
Test Date: 2026-04-03 00:16:05 Functions: 97.1 % 34 33
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.0-1