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