LCOV - code coverage report
Current view: top level - src/backend/postmaster - autovacuum.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 794 962 82.5 %
Date: 2025-04-24 12:15:10 Functions: 32 33 97.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14