Coverage Report

Created: 2026-11-12 07:20

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