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 DUB DCB
Current: 1a1248818fb8b8b0353c292c632d6a6af77e8209 vs 8e82d6610e7280d7870c0c36ff1c797e3cfb3e09 Lines: 83.7 % 1087 910 2 175 50 40 820 19 43
Current Date: 2026-10-12 11:56:10 +0200 Functions: 97.1 % 34 33 1 11 22 1
Baseline: lcov-20261012-baseline Branches: 67.2 % 690 464 3 2 221 25 33 406
Baseline Date: 2026-10-12 10:36:06 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 83.3 % 6 5 1 5
(30,360] days: 94.9 % 215 204 11 48 40 116
(360..) days: 80.9 % 866 701 1 164 2 699
Function coverage date bins:
(30,360] days: 100.0 % 5 5 3 2
(360..) days: 96.6 % 29 28 1 8 20
Branch coverage date bins:
(7,30] days: 62.5 % 8 5 1 2 5
(30,360] days: 76.5 % 166 127 3 36 21 33 73
(360..) days: 64.3 % 516 332 1 183 4 328

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

Generated by: LCOV version 2.0-1