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