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