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