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