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

Generated by: LCOV version 1.14