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