Coverage Report

Created: 2025-06-13 06:06

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