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