LCOV - differential code coverage report
Current view: top level - src/backend/postmaster - autovacuum.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DCB
Current: 77aeca80249c9e640c811e80633a2e334a9320de vs 38afc3dcb25c45b744d4025029ce0a6c90b7059f Lines: 79.5 % 1070 851 1 218 5 5 841 5
Current Date: 2026-07-25 19:08:27 +0900 Functions: 94.1 % 34 32 2 5 27
Baseline: lcov-20260725-baseline Branches: 62.8 % 672 422 2 1 247 2 2 418
Baseline Date: 2026-07-25 19:09:19 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 5 5 5
(30,360] days: 71.9 % 167 120 47 120
(360..) days: 80.8 % 898 726 1 171 5 721
Function coverage date bins:
(30,360] days: 75.0 % 4 3 1 1 2
(360..) days: 96.7 % 30 29 1 4 25
Branch coverage date bins:
(7,30] days: 50.0 % 4 2 2 2
(30,360] days: 59.0 % 122 72 50 72
(360..) days: 63.7 % 546 348 1 197 2 346

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

Generated by: LCOV version 2.0-1