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

Generated by: LCOV version 2.0-1