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