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