LCOV - code coverage report
Current view: top level - src/backend/postmaster - autovacuum.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 41.9 % 1242 520
Test Date: 2026-01-26 10:56:24 Functions: 57.6 % 33 19
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 27.9 % 675 188

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

Generated by: LCOV version 2.3.2-1