LCOV - differential code coverage report
Current view: top level - src/backend/postmaster - autovacuum.c (source / functions) Coverage Total Hit UNC LBC UBC GBC GNC CBC DCB
Current: a2387c32f2f8a1643c7d71b951587e6bcb2d4744 vs 371a302eecdc82274b0ae2967d18fd726a0aa6a1 Lines: 80.2 % 998 800 5 193 3 8 789 4
Current Date: 2025-10-26 12:31:50 -0700 Functions: 97.0 % 33 32 1 6 26
Baseline: lcov-20251027-010456-baseline Branches: 61.6 % 612 377 3 4 228 3 7 367
Baseline Date: 2025-10-26 11:01:32 +1300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 5 5 5
(30,360] days: 90.8 % 76 69 7 2 3 64
(360..) days: 79.2 % 917 726 5 186 1 725
Function coverage date bins:
(30,360] days: 100.0 % 5 5 1 4
(360..) days: 96.4 % 28 27 1 5 22
Branch coverage date bins:
(7,30] days: 66.7 % 6 4 2 4
(30,360] days: 76.0 % 50 38 1 11 2 3 33
(360..) days: 60.3 % 556 335 4 217 1 334

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

Generated by: LCOV version 2.4-beta