autovacuum.c 80.4 KB
Newer Older
1 2 3 4 5 6
/*-------------------------------------------------------------------------
 *
 * autovacuum.c
 *
 * PostgreSQL Integrated Autovacuum Daemon
 *
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * The autovacuum system is structured in two different kinds of processes: the
 * autovacuum launcher and the autovacuum worker.  The launcher is an
 * always-running process, started by the postmaster when the autovacuum GUC
 * parameter is set.  The launcher schedules autovacuum workers to be started
 * when appropriate.  The workers are the processes which execute the actual
 * vacuuming; they connect to a database as determined in the launcher, and
 * once connected they examine the catalogs to select the tables to vacuum.
 *
 * The autovacuum launcher cannot start the worker processes by itself,
 * because doing so would cause robustness issues (namely, failure to shut
 * them down on exceptional conditions, and also, since the launcher is
 * connected to shared memory and is thus subject to corruption there, it is
 * not as robust as the postmaster).  So it leaves that task to the postmaster.
 *
 * There is an autovacuum shared memory area, where the launcher stores
 * information about the database it wants vacuumed.  When it wants a new
 * worker to start, it sets a flag in shared memory and sends a signal to the
B
Bruce Momjian 已提交
24 25
 * postmaster.	Then postmaster knows nothing more than it must start a worker;
 * so it forks a new child, which turns into a worker.	This new process
26 27 28 29 30 31
 * connects to shared memory, and there it can inspect the information that the
 * launcher has set up.
 *
 * If the fork() call fails in the postmaster, it sets a flag in the shared
 * memory area, and sends a signal to the launcher.  The launcher, upon
 * noticing the flag, can try starting the worker again by resending the
B
Bruce Momjian 已提交
32
 * signal.	Note that the failure can only be transient (fork failure due to
33 34 35 36 37
 * high load, memory pressure, too many processes, etc); more permanent
 * problems, like failure to connect to a database, are detected later in the
 * worker and dealt with just by having the worker exit normally.  The launcher
 * will launch a new worker again later, per schedule.
 *
38
 * When the worker is done vacuuming it sends SIGUSR2 to the launcher.	The
39 40 41 42 43 44 45 46 47 48 49 50 51
 * launcher then wakes up and is able to launch another worker, if the schedule
 * is so tight that a new worker is needed immediately.  At this time the
 * launcher can also balance the settings for the various remaining workers'
 * cost-based vacuum delay feature.
 *
 * Note that there can be more than one worker in a database concurrently.
 * They will store the table they are currently vacuuming in shared memory, so
 * that other workers avoid being blocked waiting for the vacuum lock for that
 * table.  They will also reload the pgstats data just before vacuuming each
 * table, to avoid vacuuming a table that was just finished being vacuumed by
 * another worker and thus is no longer noted in shared memory.  However,
 * there is a window (caused by pgstat delay) on which a worker may choose a
 * table that was already vacuumed; this is a bug in the current design.
52
 *
B
Bruce Momjian 已提交
53
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
54 55 56 57
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
58
 *	  $PostgreSQL: pgsql/src/backend/postmaster/autovacuum.c,v 1.106 2009/12/30 20:32:14 tgl Exp $
59 60 61 62 63 64 65
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <signal.h>
#include <sys/types.h>
66
#include <sys/time.h>
67
#include <time.h>
68 69 70
#include <unistd.h>

#include "access/heapam.h"
71
#include "access/reloptions.h"
72 73
#include "access/transam.h"
#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 79 80 81 82 83 84
#include "commands/vacuum.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/fork_process.h"
#include "postmaster/postmaster.h"
85
#include "storage/bufmgr.h"
86
#include "storage/ipc.h"
87
#include "storage/pmsignal.h"
88
#include "storage/proc.h"
89
#include "storage/procsignal.h"
90
#include "storage/sinvaladt.h"
91 92
#include "tcop/tcopprot.h"
#include "utils/fmgroids.h"
93
#include "utils/lsyscache.h"
94 95
#include "utils/memutils.h"
#include "utils/ps_status.h"
96
#include "utils/snapmgr.h"
97
#include "utils/syscache.h"
98
#include "utils/tqual.h"
99 100 101 102 103 104


/*
 * GUC parameters
 */
bool		autovacuum_start_daemon = false;
105
int			autovacuum_max_workers;
106 107 108 109 110
int			autovacuum_naptime;
int			autovacuum_vac_thresh;
double		autovacuum_vac_scale;
int			autovacuum_anl_thresh;
double		autovacuum_anl_scale;
111
int			autovacuum_freeze_max_age;
112

113 114 115
int			autovacuum_vac_cost_delay;
int			autovacuum_vac_cost_limit;

116
int			Log_autovacuum_min_duration = -1;
117

118 119 120
/* how long to keep pgstat data in the launcher, in milliseconds */
#define STATS_READ_DELAY 1000

A
Alvaro Herrera 已提交
121
/* the minimum allowed time between two awakenings of the launcher */
122
#define MIN_AUTOVAC_SLEEPTIME 100.0		/* milliseconds */
123

124
/* Flags to tell if we are in an autovacuum process */
125 126
static bool am_autovacuum_launcher = false;
static bool am_autovacuum_worker = false;
127

128 129
/* Flags set by signal handlers */
static volatile sig_atomic_t got_SIGHUP = false;
130
static volatile sig_atomic_t got_SIGUSR2 = false;
131 132
static volatile sig_atomic_t got_SIGTERM = false;

133 134 135
/* Comparison point for determining whether freeze_max_age is exceeded */
static TransactionId recentXid;

136
/* Default freeze ages to use for autovacuum (varies by database) */
137
static int	default_freeze_min_age;
138
static int	default_freeze_table_age;
139

140
/* Memory context for long-lived data */
B
Bruce Momjian 已提交
141
static MemoryContext AutovacMemCxt;
142

143 144
/* struct to keep track of databases in launcher */
typedef struct avl_dbase
145
{
B
Bruce Momjian 已提交
146 147
	Oid			adl_datid;		/* hash key -- must be first */
	TimestampTz adl_next_worker;
148
	int			adl_score;
149
} avl_dbase;
150 151 152 153 154 155 156 157

/* struct to keep track of databases in worker */
typedef struct avw_dbase
{
	Oid			adw_datid;
	char	   *adw_name;
	TransactionId adw_frozenxid;
	PgStat_StatDBEntry *adw_entry;
158
} avw_dbase;
159

160 161 162
/* struct to keep track of tables to vacuum and/or analyze, in 1st pass */
typedef struct av_relation
{
163
	Oid			ar_toastrelid;	/* hash key - must be first */
B
Bruce Momjian 已提交
164
	Oid			ar_relid;
165
	bool		ar_hasrelopts;
166 167
	AutoVacOpts ar_reloptions;	/* copy of AutoVacOpts from the main table's
								 * reloptions, or NULL if none */
168
} av_relation;
169

170
/* struct to keep track of tables to vacuum and/or analyze, after rechecking */
171 172
typedef struct autovac_table
{
173 174 175 176
	Oid			at_relid;
	bool		at_dovacuum;
	bool		at_doanalyze;
	int			at_freeze_min_age;
177
	int			at_freeze_table_age;
178 179
	int			at_vacuum_cost_delay;
	int			at_vacuum_cost_limit;
180
	bool		at_wraparound;
181 182 183
	char	   *at_relname;
	char	   *at_nspname;
	char	   *at_datname;
184 185
} autovac_table;

186 187 188 189 190 191 192 193
/*-------------
 * This struct holds information about a single worker's whereabouts.  We keep
 * an array of these in shared memory, sized according to
 * autovacuum_max_workers.
 *
 * wi_links		entry into free list or running list
 * wi_dboid		OID of the database this worker is supposed to work on
 * wi_tableoid	OID of the table currently being vacuumed
194
 * wi_proc		pointer to PGPROC of the running worker, NULL if not started
195 196 197 198 199 200 201 202 203 204 205 206 207
 * wi_launchtime Time at which this worker was launched
 * wi_cost_*	Vacuum cost-based delay parameters current in this worker
 *
 * All fields are protected by AutovacuumLock, except for wi_tableoid which is
 * protected by AutovacuumScheduleLock (which is read-only for everyone except
 * that worker itself).
 *-------------
 */
typedef struct WorkerInfoData
{
	SHM_QUEUE	wi_links;
	Oid			wi_dboid;
	Oid			wi_tableoid;
208
	PGPROC	   *wi_proc;
B
Bruce Momjian 已提交
209
	TimestampTz wi_launchtime;
210 211 212
	int			wi_cost_delay;
	int			wi_cost_limit;
	int			wi_cost_limit_base;
213
} WorkerInfoData;
214 215 216

typedef struct WorkerInfoData *WorkerInfo;

217 218 219 220 221
/*
 * Possible signals received by the launcher from remote processes.  These are
 * stored atomically in shared memory so that other processes can set them
 * without locking.
 */
B
Bruce Momjian 已提交
222
typedef enum
223
{
B
Bruce Momjian 已提交
224 225
	AutoVacForkFailed,			/* failed trying to start a worker */
	AutoVacRebalance,			/* rebalance the cost limits */
226
	AutoVacNumSignals			/* must be last */
227 228
} AutoVacuumSignal;

229 230
/*-------------
 * The main autovacuum shmem struct.  On shared memory we store this main
B
Bruce Momjian 已提交
231
 * struct and the array of WorkerInfo structs.	This struct keeps:
232
 *
233
 * av_signal		set by other processes to indicate various conditions
234 235 236 237 238 239
 * av_launcherpid	the PID of the autovacuum launcher
 * av_freeWorkers	the WorkerInfo freelist
 * av_runningWorkers the WorkerInfo non-free queue
 * av_startingWorker pointer to WorkerInfo currently being started (cleared by
 *					the worker itself as soon as it's up and running)
 *
240 241
 * This struct is protected by AutovacuumLock, except for av_signal and parts
 * of the worker list (see above).
242 243
 *-------------
 */
244 245
typedef struct
{
B
Bruce Momjian 已提交
246 247
	sig_atomic_t av_signal[AutoVacNumSignals];
	pid_t		av_launcherpid;
248
	WorkerInfo	av_freeWorkers;
B
Bruce Momjian 已提交
249
	SHM_QUEUE	av_runningWorkers;
250
	WorkerInfo	av_startingWorker;
251
} AutoVacuumShmemStruct;
252 253

static AutoVacuumShmemStruct *AutoVacuumShmem;
254

255 256 257 258 259
/* the database list in the launcher, and the context that contains it */
static Dllist *DatabaseList = NULL;
static MemoryContext DatabaseListCxt = NULL;

/* Pointer to my own WorkerInfo, valid on each worker */
B
Bruce Momjian 已提交
260
static WorkerInfo MyWorkerInfo = NULL;
261 262

/* PID of launcher, valid only in worker while shutting down */
B
Bruce Momjian 已提交
263
int			AutovacuumLauncherPid = 0;
264

265
#ifdef EXEC_BACKEND
266 267
static pid_t avlauncher_forkexec(void);
static pid_t avworker_forkexec(void);
268
#endif
269 270 271
NON_EXEC_STATIC void AutoVacWorkerMain(int argc, char *argv[]);
NON_EXEC_STATIC void AutoVacLauncherMain(int argc, char *argv[]);

B
Bruce Momjian 已提交
272
static Oid	do_start_worker(void);
273
static void launcher_determine_sleep(bool canlaunch, bool recursing,
B
Bruce Momjian 已提交
274
						 struct timeval * nap);
275 276 277
static void launch_worker(TimestampTz now);
static List *get_database_list(void);
static void rebuild_database_list(Oid newdb);
B
Bruce Momjian 已提交
278
static int	db_comparator(const void *a, const void *b);
279 280
static void autovac_balance_cost(void);

281
static void do_autovacuum(void);
282
static void FreeWorkerInfo(int code, Datum arg);
283

284 285 286
static autovac_table *table_recheck_autovac(Oid relid, HTAB *table_toast_map,
					  TupleDesc pg_class_desc);
static void relation_needs_vacanalyze(Oid relid, AutoVacOpts *relopts,
287
						  Form_pg_class classForm,
288 289
						  PgStat_StatTabEntry *tabentry,
						  bool *dovacuum, bool *doanalyze, bool *wraparound);
290

291
static void autovacuum_do_vac_analyze(autovac_table *tab,
292
						  BufferAccessStrategy bstrategy);
293 294
static AutoVacOpts *extract_autovac_opts(HeapTuple tup,
					 TupleDesc pg_class_desc);
295 296 297
static PgStat_StatTabEntry *get_pgstat_tabentry_relid(Oid relid, bool isshared,
						  PgStat_StatDBEntry *shared,
						  PgStat_StatDBEntry *dbentry);
298
static void autovac_report_activity(autovac_table *tab);
299
static void avl_sighup_handler(SIGNAL_ARGS);
300
static void avl_sigusr2_handler(SIGNAL_ARGS);
301
static void avl_sigterm_handler(SIGNAL_ARGS);
302
static void autovac_refresh_stats(void);
303 304


305 306

/********************************************************************
B
Bruce Momjian 已提交
307
 *					  AUTOVACUUM LAUNCHER CODE
308 309 310
 ********************************************************************/

#ifdef EXEC_BACKEND
311
/*
312
 * forkexec routine for the autovacuum launcher process.
313
 *
314
 * Format up the arglist, then fork and exec.
315
 */
316 317
static pid_t
avlauncher_forkexec(void)
318
{
319 320
	char	   *av[10];
	int			ac = 0;
321

322 323 324 325
	av[ac++] = "postgres";
	av[ac++] = "--forkavlauncher";
	av[ac++] = NULL;			/* filled in by postmaster_forkexec */
	av[ac] = NULL;
326

327
	Assert(ac < lengthof(av));
328

329 330
	return postmaster_forkexec(ac, av);
}
331

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
/*
 * We need this set from the outside, before InitProcess is called
 */
void
AutovacuumLauncherIAm(void)
{
	am_autovacuum_launcher = true;
}
#endif

/*
 * Main entry point for autovacuum launcher process, to be called from the
 * postmaster.
 */
int
StartAutoVacLauncher(void)
{
	pid_t		AutoVacPID;
350 351

#ifdef EXEC_BACKEND
352
	switch ((AutoVacPID = avlauncher_forkexec()))
353
#else
B
Bruce Momjian 已提交
354
	switch ((AutoVacPID = fork_process()))
355 356 357 358
#endif
	{
		case -1:
			ereport(LOG,
359
				 (errmsg("could not fork autovacuum launcher process: %m")));
360 361 362 363 364 365 366 367
			return 0;

#ifndef EXEC_BACKEND
		case 0:
			/* in postmaster child ... */
			/* Close the postmaster's sockets */
			ClosePostmasterPorts(false);

368 369 370
			/* Lose the postmaster's on-exit routines */
			on_exit_reset();

371
			AutoVacLauncherMain(0, NULL);
372 373 374 375 376 377 378 379 380 381 382
			break;
#endif
		default:
			return (int) AutoVacPID;
	}

	/* shouldn't get here */
	return 0;
}

/*
383
 * Main loop for the autovacuum launcher process.
384
 */
385 386
NON_EXEC_STATIC void
AutoVacLauncherMain(int argc, char *argv[])
387
{
388 389 390 391 392 393 394 395 396
	sigjmp_buf	local_sigjmp_buf;

	/* we are a postmaster subprocess now */
	IsUnderPostmaster = true;
	am_autovacuum_launcher = true;

	/* reset MyProcPid */
	MyProcPid = getpid();

397 398 399
	/* record Start Time for logging */
	MyStartTime = time(NULL);

400 401 402
	/* Identify myself via ps */
	init_ps_display("autovacuum launcher process", "", "", "");

403 404 405
	ereport(LOG,
			(errmsg("autovacuum launcher started")));

406 407 408
	if (PostAuthDelay)
		pg_usleep(PostAuthDelay * 1000000L);

409 410 411 412
	SetProcessingMode(InitProcessing);

	/*
	 * If possible, make this process a group leader, so that the postmaster
B
Bruce Momjian 已提交
413 414 415
	 * can signal any child processes too.	(autovacuum probably never has any
	 * child processes, but for consistency we make all postmaster child
	 * processes do this.)
416 417 418 419 420 421 422
	 */
#ifdef HAVE_SETSID
	if (setsid() < 0)
		elog(FATAL, "setsid() failed: %m");
#endif

	/*
423 424 425
	 * Set up signal handlers.	We operate on databases much like a regular
	 * backend, so we use the same signal handling.  See equivalent code in
	 * tcop/postgres.c.
426 427
	 */
	pqsignal(SIGHUP, avl_sighup_handler);
428
	pqsignal(SIGINT, StatementCancelHandler);
429
	pqsignal(SIGTERM, avl_sigterm_handler);
430 431 432

	pqsignal(SIGQUIT, quickdie);
	pqsignal(SIGALRM, handle_sig_alarm);
433 434

	pqsignal(SIGPIPE, SIG_IGN);
435 436
	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
	pqsignal(SIGUSR2, avl_sigusr2_handler);
437 438 439 440 441 442 443 444 445 446 447 448 449
	pqsignal(SIGFPE, FloatExceptionHandler);
	pqsignal(SIGCHLD, SIG_DFL);

	/* Early initialization */
	BaseInit();

	/*
	 * Create a per-backend PGPROC struct in shared memory, except in the
	 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
	 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
	 * had to do some stuff with LWLocks).
	 */
#ifndef EXEC_BACKEND
450
	InitProcess();
451 452
#endif

453 454 455 456
	InitPostgres(NULL, InvalidOid, NULL, NULL);

	SetProcessingMode(NormalProcessing);

457 458 459 460 461
	/*
	 * Create a memory context that we will do all our work in.  We do this so
	 * that we can reset the context during error recovery and thereby avoid
	 * possible memory leaks.
	 */
462 463 464 465 466 467
	AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
										  "Autovacuum Launcher",
										  ALLOCSET_DEFAULT_MINSIZE,
										  ALLOCSET_DEFAULT_INITSIZE,
										  ALLOCSET_DEFAULT_MAXSIZE);
	MemoryContextSwitchTo(AutovacMemCxt);
468 469 470 471

	/*
	 * If an exception is encountered, processing resumes here.
	 *
472
	 * This code is a stripped down version of PostgresMain error recovery.
473 474 475 476 477 478 479 480 481
	 */
	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
	{
		/* since not using PG_TRY, must reset error stack by hand */
		error_context_stack = NULL;

		/* Prevents interrupts while cleaning up */
		HOLD_INTERRUPTS();

482 483 484 485 486
		/* Forget any pending QueryCancel request */
		QueryCancelPending = false;
		disable_sig_alarm(true);
		QueryCancelPending = false;		/* again in case timeout occurred */

487 488 489
		/* Report the error to the server log */
		EmitErrorReport();

490 491
		/* Abort the current transaction in order to recover */
		AbortCurrentTransaction();
492 493 494 495 496

		/*
		 * Now return to normal top-level context and clear ErrorContext for
		 * next time.
		 */
497
		MemoryContextSwitchTo(AutovacMemCxt);
498 499 500
		FlushErrorState();

		/* Flush any leaked data in the top-level context */
501 502 503 504 505
		MemoryContextResetAndDeleteChildren(AutovacMemCxt);

		/* don't leave dangling pointers to freed memory */
		DatabaseListCxt = NULL;
		DatabaseList = NULL;
506

507 508 509 510
		/*
		 * Make sure pgstat also considers our stat data as gone.  Note: we
		 * mustn't use autovac_refresh_stats here.
		 */
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
		pgstat_clear_snapshot();

		/* Now we can allow interrupts again */
		RESUME_INTERRUPTS();

		/*
		 * Sleep at least 1 second after any error.  We don't want to be
		 * filling the error logs as fast as we can.
		 */
		pg_usleep(1000000L);
	}

	/* We can now handle ereport(ERROR) */
	PG_exception_stack = &local_sigjmp_buf;

526
	/* must unblock signals before calling rebuild_database_list */
527 528
	PG_SETMASK(&UnBlockSig);

529
	/* in emergency mode, just start a worker and go away */
530
	if (!AutoVacuumingActive())
531 532
	{
		do_start_worker();
B
Bruce Momjian 已提交
533
		proc_exit(0);			/* done */
534 535 536 537
	}

	AutoVacuumShmem->av_launcherpid = MyProcPid;

538
	/*
539 540 541 542 543
	 * Create the initial database list.  The invariant we want this list to
	 * keep is that it's ordered by decreasing next_time.  As soon as an entry
	 * is updated to a higher time, it will be moved to the front (which is
	 * correct because the only operation is to add autovacuum_naptime to the
	 * entry, and time always increases).
544
	 */
545
	rebuild_database_list(InvalidOid);
546 547 548

	for (;;)
	{
549
		struct timeval nap;
550
		TimestampTz current_time = 0;
B
Bruce Momjian 已提交
551 552
		bool		can_launch;
		Dlelem	   *elem;
553 554 555 556 557 558

		/*
		 * Emergency bailout if postmaster has died.  This is to avoid the
		 * necessity for manual cleanup of all postmaster children.
		 */
		if (!PostmasterIsAlive(true))
559
			proc_exit(1);
560

561 562
		launcher_determine_sleep((AutoVacuumShmem->av_freeWorkers != NULL),
								 false, &nap);
563

564 565 566
		/* Allow sinval catchup interrupts while sleeping */
		EnableCatchupInterrupt();

567
		/*
568 569 570 571 572 573
		 * Sleep for a while according to schedule.
		 *
		 * On some platforms, signals won't interrupt the sleep.  To ensure we
		 * respond reasonably promptly when someone signals us, break down the
		 * sleep into 1-second increments, and check for interrupts after each
		 * nap.
574 575 576
		 */
		while (nap.tv_sec > 0 || nap.tv_usec > 0)
		{
B
Bruce Momjian 已提交
577
			uint32		sleeptime;
578 579 580

			if (nap.tv_sec > 0)
			{
581 582 583 584 585 586 587
				sleeptime = 1000000;
				nap.tv_sec--;
			}
			else
			{
				sleeptime = nap.tv_usec;
				nap.tv_usec = 0;
588 589 590 591 592 593 594 595
			}
			pg_usleep(sleeptime);

			/*
			 * Emergency bailout if postmaster has died.  This is to avoid the
			 * necessity for manual cleanup of all postmaster children.
			 */
			if (!PostmasterIsAlive(true))
596
				proc_exit(1);
597

598
			if (got_SIGTERM || got_SIGHUP || got_SIGUSR2)
599 600
				break;
		}
601

602 603
		DisableCatchupInterrupt();

604
		/* the normal shutdown case */
605
		if (got_SIGTERM)
606 607 608 609 610 611
			break;

		if (got_SIGHUP)
		{
			got_SIGHUP = false;
			ProcessConfigFile(PGC_SIGHUP);
612

613
			/* shutdown requested in config file? */
614
			if (!AutoVacuumingActive())
615 616
				break;

617 618 619 620 621 622 623 624 625
			/* rebalance in case the default cost parameters changed */
			LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
			autovac_balance_cost();
			LWLockRelease(AutovacuumLock);

			/* rebuild the list in case the naptime changed */
			rebuild_database_list(InvalidOid);
		}

626 627 628 629
		/*
		 * a worker finished, or postmaster signalled failure to start a
		 * worker
		 */
630
		if (got_SIGUSR2)
631
		{
632
			got_SIGUSR2 = false;
633 634

			/* rebalance cost limits, if needed */
635
			if (AutoVacuumShmem->av_signal[AutoVacRebalance])
636 637
			{
				LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
638
				AutoVacuumShmem->av_signal[AutoVacRebalance] = false;
639 640 641
				autovac_balance_cost();
				LWLockRelease(AutovacuumLock);
			}
642 643 644 645 646 647 648 649 650 651 652 653 654 655

			if (AutoVacuumShmem->av_signal[AutoVacForkFailed])
			{
				/*
				 * If the postmaster failed to start a new worker, we sleep
				 * for a little while and resend the signal.  The new worker's
				 * state is still in memory, so this is sufficient.  After
				 * that, we restart the main loop.
				 *
				 * XXX should we put a limit to the number of times we retry?
				 * I don't think it makes much sense, because a future start
				 * of a worker will continue to fail in the same way.
				 */
				AutoVacuumShmem->av_signal[AutoVacForkFailed] = false;
656
				pg_usleep(1000000L);		/* 1s */
657 658 659
				SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
				continue;
			}
660 661 662
		}

		/*
663 664
		 * There are some conditions that we need to check before trying to
		 * start a launcher.  First, we need to make sure that there is a
B
Bruce Momjian 已提交
665 666
		 * launcher slot available.  Second, we need to make sure that no
		 * other worker failed while starting up.
667
		 */
668

669
		current_time = GetCurrentTimestamp();
670 671
		LWLockAcquire(AutovacuumLock, LW_SHARED);

672
		can_launch = (AutoVacuumShmem->av_freeWorkers != NULL);
673

674
		if (AutoVacuumShmem->av_startingWorker != NULL)
675
		{
B
Bruce Momjian 已提交
676
			int			waittime;
677
			WorkerInfo	worker = AutoVacuumShmem->av_startingWorker;
678 679 680

			/*
			 * We can't launch another worker when another one is still
681 682
			 * starting up (or failed while doing so), so just sleep for a bit
			 * more; that worker will wake us up again as soon as it's ready.
B
Bruce Momjian 已提交
683 684 685 686 687 688 689 690 691 692
			 * We will only wait autovacuum_naptime seconds (up to a maximum
			 * of 60 seconds) for this to happen however.  Note that failure
			 * to connect to a particular database is not a problem here,
			 * because the worker removes itself from the startingWorker
			 * pointer before trying to connect.  Problems detected by the
			 * postmaster (like fork() failure) are also reported and handled
			 * differently.  The only problems that may cause this code to
			 * fire are errors in the earlier sections of AutoVacWorkerMain,
			 * before the worker removes the WorkerInfo from the
			 * startingWorker pointer.
693
			 */
694
			waittime = Min(autovacuum_naptime, 60) * 1000;
695
			if (TimestampDifferenceExceeds(worker->wi_launchtime, current_time,
696
										   waittime))
697 698 699
			{
				LWLockRelease(AutovacuumLock);
				LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
B
Bruce Momjian 已提交
700

701 702 703 704 705 706
				/*
				 * No other process can put a worker in starting mode, so if
				 * startingWorker is still INVALID after exchanging our lock,
				 * we assume it's the same one we saw above (so we don't
				 * recheck the launch time).
				 */
707
				if (AutoVacuumShmem->av_startingWorker != NULL)
708
				{
709
					worker = AutoVacuumShmem->av_startingWorker;
710 711
					worker->wi_dboid = InvalidOid;
					worker->wi_tableoid = InvalidOid;
712
					worker->wi_proc = NULL;
713
					worker->wi_launchtime = 0;
714 715 716
					worker->wi_links.next = (SHM_QUEUE *) AutoVacuumShmem->av_freeWorkers;
					AutoVacuumShmem->av_freeWorkers = worker;
					AutoVacuumShmem->av_startingWorker = NULL;
717
					elog(WARNING, "worker took too long to start; cancelled");
718 719
				}
			}
720
			else
721
				can_launch = false;
722
		}
B
Bruce Momjian 已提交
723
		LWLockRelease(AutovacuumLock);	/* either shared or exclusive */
724

725 726 727
		/* if we can't do anything, just go back to sleep */
		if (!can_launch)
			continue;
728

729
		/* We're OK to start a new worker */
730

731 732 733
		elem = DLGetTail(DatabaseList);
		if (elem != NULL)
		{
B
Bruce Momjian 已提交
734
			avl_dbase  *avdb = DLE_VAL(elem);
735

736
			/*
B
Bruce Momjian 已提交
737 738
			 * launch a worker if next_worker is right now or it is in the
			 * past
739 740 741
			 */
			if (TimestampDifferenceExceeds(avdb->adl_next_worker,
										   current_time, 0))
742
				launch_worker(current_time);
743 744 745 746 747 748 749 750 751 752 753 754
		}
		else
		{
			/*
			 * Special case when the list is empty: start a worker right away.
			 * This covers the initial case, when no database is in pgstats
			 * (thus the list is empty).  Note that the constraints in
			 * launcher_determine_sleep keep us from starting workers too
			 * quickly (at most once every autovacuum_naptime when the list is
			 * empty).
			 */
			launch_worker(current_time);
755
		}
756 757 758 759 760
	}

	/* Normal exit from the autovac launcher is here */
	ereport(LOG,
			(errmsg("autovacuum launcher shutting down")));
761
	AutoVacuumShmem->av_launcherpid = 0;
762

B
Bruce Momjian 已提交
763
	proc_exit(0);				/* done */
764 765
}

766
/*
767
 * Determine the time to sleep, based on the database list.
768 769
 *
 * The "canlaunch" parameter indicates whether we can start a worker right now,
770 771
 * for example due to the workers being all busy.  If this is false, we will
 * cause a long sleep, which will be interrupted when a worker exits.
772
 */
773
static void
B
Bruce Momjian 已提交
774
launcher_determine_sleep(bool canlaunch, bool recursing, struct timeval * nap)
775
{
B
Bruce Momjian 已提交
776
	Dlelem	   *elem;
777 778 779

	/*
	 * We sleep until the next scheduled vacuum.  We trust that when the
B
Bruce Momjian 已提交
780 781
	 * database list was built, care was taken so that no entries have times
	 * in the past; if the first entry has too close a next_worker value, or a
782 783 784 785
	 * time in the past, we will sleep a small nominal time.
	 */
	if (!canlaunch)
	{
786 787
		nap->tv_sec = autovacuum_naptime;
		nap->tv_usec = 0;
788 789 790 791
	}
	else if ((elem = DLGetTail(DatabaseList)) != NULL)
	{
		avl_dbase  *avdb = DLE_VAL(elem);
B
Bruce Momjian 已提交
792 793 794 795
		TimestampTz current_time = GetCurrentTimestamp();
		TimestampTz next_wakeup;
		long		secs;
		int			usecs;
796 797 798

		next_wakeup = avdb->adl_next_worker;
		TimestampDifference(current_time, next_wakeup, &secs, &usecs);
799 800 801

		nap->tv_sec = secs;
		nap->tv_usec = usecs;
802 803 804 805
	}
	else
	{
		/* list is empty, sleep for whole autovacuum_naptime seconds  */
806 807
		nap->tv_sec = autovacuum_naptime;
		nap->tv_usec = 0;
808 809 810 811 812 813 814 815 816 817 818 819
	}

	/*
	 * If the result is exactly zero, it means a database had an entry with
	 * time in the past.  Rebuild the list so that the databases are evenly
	 * distributed again, and recalculate the time to sleep.  This can happen
	 * if there are more tables needing vacuum than workers, and they all take
	 * longer to vacuum than autovacuum_naptime.
	 *
	 * We only recurse once.  rebuild_database_list should always return times
	 * in the future, but it seems best not to trust too much on that.
	 */
820
	if (nap->tv_sec == 0 && nap->tv_usec == 0 && !recursing)
821 822
	{
		rebuild_database_list(InvalidOid);
823 824
		launcher_determine_sleep(canlaunch, true, nap);
		return;
825 826
	}

827 828
	/* The smallest time we'll allow the launcher to sleep. */
	if (nap->tv_sec <= 0 && nap->tv_usec <= MIN_AUTOVAC_SLEEPTIME * 1000)
829
	{
830
		nap->tv_sec = 0;
831
		nap->tv_usec = MIN_AUTOVAC_SLEEPTIME * 1000;
832 833 834 835 836 837 838 839 840 841 842 843
	}
}

/*
 * Build an updated DatabaseList.  It must only contain databases that appear
 * in pgstats, and must be sorted by next_worker from highest to lowest,
 * distributed regularly across the next autovacuum_naptime interval.
 *
 * Receives the Oid of the database that made this list be generated (we call
 * this the "new" database, because when the database was already present on
 * the list, we expect that this function is not called at all).  The
 * preexisting list, if any, will be used to preserve the order of the
B
Bruce Momjian 已提交
844
 * databases in the autovacuum_naptime period.	The new database is put at the
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
 * end of the interval.  The actual values are not saved, which should not be
 * much of a problem.
 */
static void
rebuild_database_list(Oid newdb)
{
	List	   *dblist;
	ListCell   *cell;
	MemoryContext newcxt;
	MemoryContext oldcxt;
	MemoryContext tmpcxt;
	HASHCTL		hctl;
	int			score;
	int			nelems;
	HTAB	   *dbhash;

	/* use fresh stats */
862
	autovac_refresh_stats();
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

	newcxt = AllocSetContextCreate(AutovacMemCxt,
								   "AV dblist",
								   ALLOCSET_DEFAULT_MINSIZE,
								   ALLOCSET_DEFAULT_INITSIZE,
								   ALLOCSET_DEFAULT_MAXSIZE);
	tmpcxt = AllocSetContextCreate(newcxt,
								   "tmp AV dblist",
								   ALLOCSET_DEFAULT_MINSIZE,
								   ALLOCSET_DEFAULT_INITSIZE,
								   ALLOCSET_DEFAULT_MAXSIZE);
	oldcxt = MemoryContextSwitchTo(tmpcxt);

	/*
	 * Implementing this is not as simple as it sounds, because we need to put
	 * the new database at the end of the list; next the databases that were
B
Bruce Momjian 已提交
879 880
	 * already on the list, and finally (at the tail of the list) all the
	 * other databases that are not on the existing list.
881 882
	 *
	 * To do this, we build an empty hash table of scored databases.  We will
B
Bruce Momjian 已提交
883 884 885 886
	 * start with the lowest score (zero) for the new database, then
	 * increasing scores for the databases in the existing list, in order, and
	 * lastly increasing scores for all databases gotten via
	 * get_database_list() that are not already on the hash.
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
	 *
	 * Then we will put all the hash elements into an array, sort the array by
	 * score, and finally put the array elements into the new doubly linked
	 * list.
	 */
	hctl.keysize = sizeof(Oid);
	hctl.entrysize = sizeof(avl_dbase);
	hctl.hash = oid_hash;
	hctl.hcxt = tmpcxt;
	dbhash = hash_create("db hash", 20, &hctl,	/* magic number here FIXME */
						 HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);

	/* start by inserting the new database */
	score = 0;
	if (OidIsValid(newdb))
	{
B
Bruce Momjian 已提交
903
		avl_dbase  *db;
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
		PgStat_StatDBEntry *entry;

		/* only consider this database if it has a pgstat entry */
		entry = pgstat_fetch_stat_dbentry(newdb);
		if (entry != NULL)
		{
			/* we assume it isn't found because the hash was just created */
			db = hash_search(dbhash, &newdb, HASH_ENTER, NULL);

			/* hash_search already filled in the key */
			db->adl_score = score++;
			/* next_worker is filled in later */
		}
	}

	/* Now insert the databases from the existing list */
	if (DatabaseList != NULL)
	{
B
Bruce Momjian 已提交
922
		Dlelem	   *elem;
923 924 925 926 927 928 929 930 931 932 933 934

		elem = DLGetHead(DatabaseList);
		while (elem != NULL)
		{
			avl_dbase  *avdb = DLE_VAL(elem);
			avl_dbase  *db;
			bool		found;
			PgStat_StatDBEntry *entry;

			elem = DLGetSucc(elem);

			/*
B
Bruce Momjian 已提交
935 936
			 * skip databases with no stat entries -- in particular, this gets
			 * rid of dropped databases
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
			 */
			entry = pgstat_fetch_stat_dbentry(avdb->adl_datid);
			if (entry == NULL)
				continue;

			db = hash_search(dbhash, &(avdb->adl_datid), HASH_ENTER, &found);

			if (!found)
			{
				/* hash_search already filled in the key */
				db->adl_score = score++;
				/* next_worker is filled in later */
			}
		}
	}

	/* finally, insert all qualifying databases not previously inserted */
	dblist = get_database_list();
	foreach(cell, dblist)
	{
		avw_dbase  *avdb = lfirst(cell);
		avl_dbase  *db;
		bool		found;
		PgStat_StatDBEntry *entry;

		/* only consider databases with a pgstat entry */
		entry = pgstat_fetch_stat_dbentry(avdb->adw_datid);
		if (entry == NULL)
			continue;

		db = hash_search(dbhash, &(avdb->adw_datid), HASH_ENTER, &found);
		/* only update the score if the database was not already on the hash */
		if (!found)
		{
			/* hash_search already filled in the key */
			db->adl_score = score++;
			/* next_worker is filled in later */
		}
	}
	nelems = score;

	/* from here on, the allocated memory belongs to the new list */
	MemoryContextSwitchTo(newcxt);
	DatabaseList = DLNewList();

	if (nelems > 0)
	{
B
Bruce Momjian 已提交
984 985 986 987 988 989
		TimestampTz current_time;
		int			millis_increment;
		avl_dbase  *dbary;
		avl_dbase  *db;
		HASH_SEQ_STATUS seq;
		int			i;
990 991 992 993 994 995 996 997 998 999 1000 1001

		/* put all the hash elements into an array */
		dbary = palloc(nelems * sizeof(avl_dbase));

		i = 0;
		hash_seq_init(&seq, dbhash);
		while ((db = hash_seq_search(&seq)) != NULL)
			memcpy(&(dbary[i++]), db, sizeof(avl_dbase));

		/* sort the array */
		qsort(dbary, nelems, sizeof(avl_dbase), db_comparator);

1002
		/*
1003 1004
		 * Determine the time interval between databases in the schedule. If
		 * we see that the configured naptime would take us to sleep times
1005 1006 1007 1008
		 * lower than our min sleep time (which launcher_determine_sleep is
		 * coded not to allow), silently use a larger naptime (but don't touch
		 * the GUC variable).
		 */
1009
		millis_increment = 1000.0 * autovacuum_naptime / nelems;
1010 1011 1012
		if (millis_increment <= MIN_AUTOVAC_SLEEPTIME)
			millis_increment = MIN_AUTOVAC_SLEEPTIME * 1.1;

1013 1014 1015
		current_time = GetCurrentTimestamp();

		/*
B
Bruce Momjian 已提交
1016
		 * move the elements from the array into the dllist, setting the
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
		 * next_worker while walking the array
		 */
		for (i = 0; i < nelems; i++)
		{
			avl_dbase  *db = &(dbary[i]);
			Dlelem	   *elem;

			current_time = TimestampTzPlusMilliseconds(current_time,
													   millis_increment);
			db->adl_next_worker = current_time;

			elem = DLNewElem(db);
			/* later elements should go closer to the head of the list */
			DLAddHead(DatabaseList, elem);
		}
	}

	/* all done, clean up memory */
	if (DatabaseListCxt != NULL)
		MemoryContextDelete(DatabaseListCxt);
	MemoryContextDelete(tmpcxt);
	DatabaseListCxt = newcxt;
	MemoryContextSwitchTo(oldcxt);
}

/* qsort comparator for avl_dbase, using adl_score */
static int
db_comparator(const void *a, const void *b)
{
	if (((avl_dbase *) a)->adl_score == ((avl_dbase *) b)->adl_score)
		return 0;
	else
		return (((avl_dbase *) a)->adl_score < ((avl_dbase *) b)->adl_score) ? 1 : -1;
}

1052 1053 1054 1055 1056
/*
 * do_start_worker
 *
 * Bare-bones procedure for starting an autovacuum worker from the launcher.
 * It determines what database to work on, sets up shared memory stuff and
B
Bruce Momjian 已提交
1057
 * signals postmaster to start the worker.	It fails gracefully if invoked when
1058 1059 1060 1061
 * autovacuum_workers are already active.
 *
 * Return value is the OID of the database that the worker is going to process,
 * or InvalidOid if no worker was actually started.
1062
 */
1063
static Oid
1064 1065 1066
do_start_worker(void)
{
	List	   *dblist;
1067
	ListCell   *cell;
1068
	TransactionId xidForceLimit;
1069 1070
	bool		for_xid_wrap;
	avw_dbase  *avdb;
B
Bruce Momjian 已提交
1071
	TimestampTz current_time;
1072
	bool		skipit = false;
1073 1074
	Oid			retval = InvalidOid;
	MemoryContext tmpcxt,
B
Bruce Momjian 已提交
1075
				oldcxt;
1076 1077 1078

	/* return quickly when there are no free workers */
	LWLockAcquire(AutovacuumLock, LW_SHARED);
1079
	if (AutoVacuumShmem->av_freeWorkers == NULL)
1080 1081 1082 1083 1084 1085
	{
		LWLockRelease(AutovacuumLock);
		return InvalidOid;
	}
	LWLockRelease(AutovacuumLock);

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
	/*
	 * Create and switch to a temporary context to avoid leaking the memory
	 * allocated for the database list.
	 */
	tmpcxt = AllocSetContextCreate(CurrentMemoryContext,
								   "Start worker tmp cxt",
								   ALLOCSET_DEFAULT_MINSIZE,
								   ALLOCSET_DEFAULT_INITSIZE,
								   ALLOCSET_DEFAULT_MAXSIZE);
	oldcxt = MemoryContextSwitchTo(tmpcxt);

1097
	/* use fresh stats */
1098
	autovac_refresh_stats();
1099 1100

	/* Get a list of databases */
1101
	dblist = get_database_list();
1102 1103

	/*
B
Bruce Momjian 已提交
1104 1105
	 * Determine the oldest datfrozenxid/relfrozenxid that we will allow to
	 * pass without forcing a vacuum.  (This limit can be tightened for
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
	 * particular tables, but not loosened.)
	 */
	recentXid = ReadNewTransactionId();
	xidForceLimit = recentXid - autovacuum_freeze_max_age;
	/* ensure it's a "normal" XID, else TransactionIdPrecedes misbehaves */
	if (xidForceLimit < FirstNormalTransactionId)
		xidForceLimit -= FirstNormalTransactionId;

	/*
	 * Choose a database to connect to.  We pick the database that was least
	 * recently auto-vacuumed, or one that needs vacuuming to prevent Xid
	 * wraparound-related data loss.  If any db at risk of wraparound is
	 * found, we pick the one with oldest datfrozenxid, independently of
	 * autovacuum times.
	 *
	 * Note that a database with no stats entry is not considered, except for
	 * Xid wraparound purposes.  The theory is that if no one has ever
	 * connected to it since the stats were last initialized, it doesn't need
	 * vacuuming.
	 *
	 * XXX This could be improved if we had more info about whether it needs
	 * vacuuming before connecting to it.  Perhaps look through the pgstats
	 * data for the database's tables?  One idea is to keep track of the
	 * number of new and dead tuples per database in pgstats.  However it
	 * isn't clear how to construct a metric that measures that and not cause
	 * starvation for less busy databases.
	 */
1133
	avdb = NULL;
1134
	for_xid_wrap = false;
1135
	current_time = GetCurrentTimestamp();
1136 1137
	foreach(cell, dblist)
	{
1138 1139
		avw_dbase  *tmp = lfirst(cell);
		Dlelem	   *elem;
1140 1141

		/* Check to see if this one is at risk of wraparound */
1142
		if (TransactionIdPrecedes(tmp->adw_frozenxid, xidForceLimit))
1143
		{
1144
			if (avdb == NULL ||
B
Bruce Momjian 已提交
1145
			  TransactionIdPrecedes(tmp->adw_frozenxid, avdb->adw_frozenxid))
1146
				avdb = tmp;
1147 1148 1149 1150 1151 1152
			for_xid_wrap = true;
			continue;
		}
		else if (for_xid_wrap)
			continue;			/* ignore not-at-risk DBs */

1153 1154 1155
		/* Find pgstat entry if any */
		tmp->adw_entry = pgstat_fetch_stat_dbentry(tmp->adw_datid);

1156
		/*
1157 1158
		 * Skip a database with no pgstat entry; it means it hasn't seen any
		 * activity.
1159
		 */
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
		if (!tmp->adw_entry)
			continue;

		/*
		 * Also, skip a database that appears on the database list as having
		 * been processed recently (less than autovacuum_naptime seconds ago).
		 * We do this so that we don't select a database which we just
		 * selected, but that pgstat hasn't gotten around to updating the last
		 * autovacuum time yet.
		 */
		skipit = false;
		elem = DatabaseList ? DLGetTail(DatabaseList) : NULL;

		while (elem != NULL)
		{
B
Bruce Momjian 已提交
1175
			avl_dbase  *dbp = DLE_VAL(elem);
1176 1177 1178 1179

			if (dbp->adl_datid == tmp->adw_datid)
			{
				/*
1180
				 * Skip this database if its next_worker value falls between
1181 1182
				 * the current time and the current time plus naptime.
				 */
1183
				if (!TimestampDifferenceExceeds(dbp->adl_next_worker,
B
Bruce Momjian 已提交
1184
												current_time, 0) &&
1185 1186 1187
					!TimestampDifferenceExceeds(current_time,
												dbp->adl_next_worker,
												autovacuum_naptime * 1000))
1188 1189 1190 1191 1192 1193 1194
					skipit = true;

				break;
			}
			elem = DLGetPred(elem);
		}
		if (skipit)
1195 1196 1197
			continue;

		/*
B
Bruce Momjian 已提交
1198 1199
		 * Remember the db with oldest autovac time.  (If we are here, both
		 * tmp->entry and db->entry must be non-null.)
1200
		 */
1201 1202 1203
		if (avdb == NULL ||
			tmp->adw_entry->last_autovac_time < avdb->adw_entry->last_autovac_time)
			avdb = tmp;
1204 1205 1206
	}

	/* Found a database -- process it */
1207
	if (avdb != NULL)
1208
	{
1209 1210
		WorkerInfo	worker;

1211
		LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1212 1213 1214

		/*
		 * Get a worker entry from the freelist.  We checked above, so there
B
Bruce Momjian 已提交
1215 1216
		 * really should be a free slot -- complain very loudly if there
		 * isn't.
1217
		 */
1218 1219
		worker = AutoVacuumShmem->av_freeWorkers;
		if (worker == NULL)
1220 1221
			elog(FATAL, "no free worker found");

1222
		AutoVacuumShmem->av_freeWorkers = (WorkerInfo) worker->wi_links.next;
1223 1224

		worker->wi_dboid = avdb->adw_datid;
1225
		worker->wi_proc = NULL;
1226 1227
		worker->wi_launchtime = GetCurrentTimestamp();

1228
		AutoVacuumShmem->av_startingWorker = worker;
1229

1230 1231 1232
		LWLockRelease(AutovacuumLock);

		SendPostmasterSignal(PMSIGNAL_START_AUTOVAC_WORKER);
1233

1234
		retval = avdb->adw_datid;
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
	}
	else if (skipit)
	{
		/*
		 * If we skipped all databases on the list, rebuild it, because it
		 * probably contains a dropped database.
		 */
		rebuild_database_list(InvalidOid);
	}

1245 1246 1247 1248
	MemoryContextSwitchTo(oldcxt);
	MemoryContextDelete(tmpcxt);

	return retval;
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
}

/*
 * launch_worker
 *
 * Wrapper for starting a worker from the launcher.  Besides actually starting
 * it, update the database list to reflect the next time that another one will
 * need to be started on the selected database.  The actual database choice is
 * left to do_start_worker.
 *
 * This routine is also expected to insert an entry into the database list if
1260
 * the selected database was previously absent from the list.
1261 1262 1263 1264
 */
static void
launch_worker(TimestampTz now)
{
B
Bruce Momjian 已提交
1265 1266
	Oid			dbid;
	Dlelem	   *elem;
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277

	dbid = do_start_worker();
	if (OidIsValid(dbid))
	{
		/*
		 * Walk the database list and update the corresponding entry.  If the
		 * database is not on the list, we'll recreate the list.
		 */
		elem = (DatabaseList == NULL) ? NULL : DLGetHead(DatabaseList);
		while (elem != NULL)
		{
B
Bruce Momjian 已提交
1278
			avl_dbase  *avdb = DLE_VAL(elem);
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295

			if (avdb->adl_datid == dbid)
			{
				/*
				 * add autovacuum_naptime seconds to the current time, and use
				 * that as the new "next_worker" field for this database.
				 */
				avdb->adl_next_worker =
					TimestampTzPlusMilliseconds(now, autovacuum_naptime * 1000);

				DLMoveToFront(elem);
				break;
			}
			elem = DLGetSucc(elem);
		}

		/*
B
Bruce Momjian 已提交
1296 1297 1298 1299 1300
		 * If the database was not present in the database list, we rebuild
		 * the list.  It's possible that the database does not get into the
		 * list anyway, for example if it's a database that doesn't have a
		 * pgstat entry, but this is not a problem because we don't want to
		 * schedule workers regularly into those in any case.
1301 1302 1303
		 */
		if (elem == NULL)
			rebuild_database_list(dbid);
1304 1305 1306
	}
}

1307 1308
/*
 * Called from postmaster to signal a failure to fork a process to become
1309
 * worker.	The postmaster should kill(SIGUSR2) the launcher shortly
1310 1311 1312 1313 1314 1315 1316 1317
 * after calling this function.
 */
void
AutoVacWorkerFailed(void)
{
	AutoVacuumShmem->av_signal[AutoVacForkFailed] = true;
}

1318 1319 1320 1321 1322
/* SIGHUP: set flag to re-read config file at next convenient time */
static void
avl_sighup_handler(SIGNAL_ARGS)
{
	got_SIGHUP = true;
1323 1324
}

1325
/* SIGUSR2: a worker is up and running, or just finished, or failed to fork */
1326
static void
1327
avl_sigusr2_handler(SIGNAL_ARGS)
1328
{
1329
	got_SIGUSR2 = true;
1330 1331
}

1332
/* SIGTERM: time to die */
1333
static void
1334
avl_sigterm_handler(SIGNAL_ARGS)
1335
{
1336
	got_SIGTERM = true;
1337 1338 1339 1340
}


/********************************************************************
B
Bruce Momjian 已提交
1341
 *					  AUTOVACUUM WORKER CODE
1342 1343
 ********************************************************************/

1344 1345
#ifdef EXEC_BACKEND
/*
1346
 * forkexec routines for the autovacuum worker.
1347
 *
1348
 * Format up the arglist, then fork and exec.
1349 1350
 */
static pid_t
1351
avworker_forkexec(void)
1352 1353 1354 1355 1356
{
	char	   *av[10];
	int			ac = 0;

	av[ac++] = "postgres";
1357
	av[ac++] = "--forkavworker";
B
Bruce Momjian 已提交
1358
	av[ac++] = NULL;			/* filled in by postmaster_forkexec */
1359 1360 1361 1362 1363 1364
	av[ac] = NULL;

	Assert(ac < lengthof(av));

	return postmaster_forkexec(ac, av);
}
1365 1366 1367 1368 1369

/*
 * We need this set from the outside, before InitProcess is called
 */
void
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
AutovacuumWorkerIAm(void)
{
	am_autovacuum_worker = true;
}
#endif

/*
 * Main entry point for autovacuum worker process.
 *
 * This code is heavily based on pgarch.c, q.v.
 */
int
StartAutoVacWorker(void)
1383
{
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
	pid_t		worker_pid;

#ifdef EXEC_BACKEND
	switch ((worker_pid = avworker_forkexec()))
#else
	switch ((worker_pid = fork_process()))
#endif
	{
		case -1:
			ereport(LOG,
1394
					(errmsg("could not fork autovacuum worker process: %m")));
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
			return 0;

#ifndef EXEC_BACKEND
		case 0:
			/* in postmaster child ... */
			/* Close the postmaster's sockets */
			ClosePostmasterPorts(false);

			/* Lose the postmaster's on-exit routines */
			on_exit_reset();

			AutoVacWorkerMain(0, NULL);
			break;
#endif
		default:
			return (int) worker_pid;
	}

	/* shouldn't get here */
	return 0;
1415
}
1416 1417

/*
1418
 * AutoVacWorkerMain
1419 1420
 */
NON_EXEC_STATIC void
1421
AutoVacWorkerMain(int argc, char *argv[])
1422
{
B
Bruce Momjian 已提交
1423
	sigjmp_buf	local_sigjmp_buf;
1424
	Oid			dbid;
1425 1426 1427

	/* we are a postmaster subprocess now */
	IsUnderPostmaster = true;
1428
	am_autovacuum_worker = true;
1429 1430 1431 1432

	/* reset MyProcPid */
	MyProcPid = getpid();

1433 1434 1435
	/* record Start Time for logging */
	MyStartTime = time(NULL);

1436
	/* Identify myself via ps */
1437
	init_ps_display("autovacuum worker process", "", "", "");
1438 1439 1440

	SetProcessingMode(InitProcessing);

1441 1442
	/*
	 * If possible, make this process a group leader, so that the postmaster
B
Bruce Momjian 已提交
1443 1444 1445
	 * can signal any child processes too.	(autovacuum probably never has any
	 * child processes, but for consistency we make all postmaster child
	 * processes do this.)
1446 1447 1448 1449 1450 1451
	 */
#ifdef HAVE_SETSID
	if (setsid() < 0)
		elog(FATAL, "setsid() failed: %m");
#endif

1452
	/*
B
Bruce Momjian 已提交
1453 1454 1455
	 * Set up signal handlers.	We operate on databases much like a regular
	 * backend, so we use the same signal handling.  See equivalent code in
	 * tcop/postgres.c.
1456
	 *
1457 1458
	 * Currently, we don't pay attention to postgresql.conf changes that
	 * happen during a single daemon iteration, so we can ignore SIGHUP.
1459 1460
	 */
	pqsignal(SIGHUP, SIG_IGN);
B
Bruce Momjian 已提交
1461

1462
	/*
B
Bruce Momjian 已提交
1463 1464
	 * SIGINT is used to signal cancelling the current table's vacuum; SIGTERM
	 * means abort and exit cleanly, and SIGQUIT means abandon ship.
1465 1466 1467 1468 1469 1470 1471
	 */
	pqsignal(SIGINT, StatementCancelHandler);
	pqsignal(SIGTERM, die);
	pqsignal(SIGQUIT, quickdie);
	pqsignal(SIGALRM, handle_sig_alarm);

	pqsignal(SIGPIPE, SIG_IGN);
1472
	pqsignal(SIGUSR1, procsignal_sigusr1_handler);
1473
	pqsignal(SIGUSR2, SIG_IGN);
1474
	pqsignal(SIGFPE, FloatExceptionHandler);
1475 1476 1477 1478 1479
	pqsignal(SIGCHLD, SIG_DFL);

	/* Early initialization */
	BaseInit();

1480
	/*
B
Bruce Momjian 已提交
1481 1482 1483 1484
	 * Create a per-backend PGPROC struct in shared memory, except in the
	 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
	 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
	 * had to do some stuff with LWLocks).
1485 1486 1487 1488 1489
	 */
#ifndef EXEC_BACKEND
	InitProcess();
#endif

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
	/*
	 * If an exception is encountered, processing resumes here.
	 *
	 * See notes in postgres.c about the design of this coding.
	 */
	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
	{
		/* Prevents interrupts while cleaning up */
		HOLD_INTERRUPTS();

		/* Report the error to the server log */
		EmitErrorReport();

		/*
1504 1505
		 * We can now go away.	Note that because we called InitProcess, a
		 * callback was registered to do ProcKill, which will clean up
B
Bruce Momjian 已提交
1506
		 * necessary state.
1507 1508 1509 1510 1511 1512 1513 1514 1515
		 */
		proc_exit(0);
	}

	/* We can now handle ereport(ERROR) */
	PG_exception_stack = &local_sigjmp_buf;

	PG_SETMASK(&UnBlockSig);

1516
	/*
B
Bruce Momjian 已提交
1517 1518 1519
	 * Force zero_damaged_pages OFF in the autovac process, even if it is set
	 * in postgresql.conf.	We don't really want such a dangerous option being
	 * applied non-interactively.
1520 1521 1522
	 */
	SetConfigOption("zero_damaged_pages", "false", PGC_SUSET, PGC_S_OVERRIDE);

1523
	/*
1524 1525
	 * Force statement_timeout to zero to avoid a timeout setting from
	 * preventing regular maintenance from being executed.
1526
	 */
1527
	SetConfigOption("statement_timeout", "0", PGC_SUSET, PGC_S_OVERRIDE);
1528

1529 1530 1531 1532
	/*
	 * Get the info about the database we're going to work on.
	 */
	LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
1533

1534
	/*
B
Bruce Momjian 已提交
1535 1536 1537 1538
	 * beware of startingWorker being INVALID; this should normally not
	 * happen, but if a worker fails after forking and before this, the
	 * launcher might have decided to remove it from the queue and start
	 * again.
1539
	 */
1540
	if (AutoVacuumShmem->av_startingWorker != NULL)
1541
	{
1542
		MyWorkerInfo = AutoVacuumShmem->av_startingWorker;
1543
		dbid = MyWorkerInfo->wi_dboid;
1544
		MyWorkerInfo->wi_proc = MyProc;
1545

1546
		/* insert into the running list */
B
Bruce Momjian 已提交
1547
		SHMQueueInsertBefore(&AutoVacuumShmem->av_runningWorkers,
1548
							 &MyWorkerInfo->wi_links);
1549

1550
		/*
1551 1552
		 * remove from the "starting" pointer, so that the launcher can start
		 * a new worker if required
1553
		 */
1554
		AutoVacuumShmem->av_startingWorker = NULL;
1555
		LWLockRelease(AutovacuumLock);
1556

1557 1558 1559 1560
		on_shmem_exit(FreeWorkerInfo, 0);

		/* wake up the launcher */
		if (AutoVacuumShmem->av_launcherpid != 0)
1561
			kill(AutoVacuumShmem->av_launcherpid, SIGUSR2);
1562 1563
	}
	else
1564
	{
1565
		/* no worker entry for me, go away */
1566
		elog(WARNING, "autovacuum worker started without a worker entry");
1567
		dbid = InvalidOid;
1568
		LWLockRelease(AutovacuumLock);
1569
	}
1570

1571
	if (OidIsValid(dbid))
1572
	{
1573
		char		dbname[NAMEDATALEN];
1574

1575
		/*
B
Bruce Momjian 已提交
1576 1577 1578 1579 1580 1581
		 * Report autovac startup to the stats collector.  We deliberately do
		 * this before InitPostgres, so that the last_autovac_time will get
		 * updated even if the connection attempt fails.  This is to prevent
		 * autovac from getting "stuck" repeatedly selecting an unopenable
		 * database, rather than making any progress on stuff it can connect
		 * to.
1582
		 */
1583
		pgstat_report_autovac(dbid);
1584

1585 1586
		/*
		 * Connect to the selected database
1587 1588 1589
		 *
		 * Note: if we have selected a just-deleted database (due to using
		 * stale stats info), we'll fail and exit here.
1590
		 */
1591
		InitPostgres(NULL, dbid, NULL, dbname);
1592
		SetProcessingMode(NormalProcessing);
1593
		set_ps_display(dbname, false);
1594
		ereport(DEBUG1,
1595
				(errmsg("autovacuum: processing database \"%s\"", dbname)));
1596

1597 1598 1599
		if (PostAuthDelay)
			pg_usleep(PostAuthDelay * 1000000L);

1600 1601
		/* And do an appropriate amount of work */
		recentXid = ReadNewTransactionId();
1602
		do_autovacuum();
1603 1604
	}

1605
	/*
1606 1607
	 * The launcher will be notified of my death in ProcKill, *if* we managed
	 * to get a worker slot at all
1608 1609 1610
	 */

	/* All done, go away */
1611 1612 1613 1614
	proc_exit(0);
}

/*
1615 1616
 * Return a WorkerInfo to the free list
 */
1617 1618 1619 1620 1621 1622 1623 1624
static void
FreeWorkerInfo(int code, Datum arg)
{
	if (MyWorkerInfo != NULL)
	{
		LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);

		/*
1625 1626
		 * Wake the launcher up so that he can launch a new worker immediately
		 * if required.  We only save the launcher's PID in local memory here;
B
Bruce Momjian 已提交
1627
		 * the actual signal will be sent when the PGPROC is recycled.	Note
1628 1629
		 * that we always do this, so that the launcher can rebalance the cost
		 * limit setting of the remaining workers.
1630 1631 1632 1633 1634 1635
		 *
		 * We somewhat ignore the risk that the launcher changes its PID
		 * between we reading it and the actual kill; we expect ProcKill to be
		 * called shortly after us, and we assume that PIDs are not reused too
		 * quickly after a process exits.
		 */
1636
		AutovacuumLauncherPid = AutoVacuumShmem->av_launcherpid;
1637 1638

		SHMQueueDelete(&MyWorkerInfo->wi_links);
1639
		MyWorkerInfo->wi_links.next = (SHM_QUEUE *) AutoVacuumShmem->av_freeWorkers;
1640 1641
		MyWorkerInfo->wi_dboid = InvalidOid;
		MyWorkerInfo->wi_tableoid = InvalidOid;
1642
		MyWorkerInfo->wi_proc = NULL;
1643 1644 1645 1646
		MyWorkerInfo->wi_launchtime = 0;
		MyWorkerInfo->wi_cost_delay = 0;
		MyWorkerInfo->wi_cost_limit = 0;
		MyWorkerInfo->wi_cost_limit_base = 0;
1647
		AutoVacuumShmem->av_freeWorkers = MyWorkerInfo;
1648 1649 1650 1651 1652 1653 1654
		/* not mine anymore */
		MyWorkerInfo = NULL;

		/*
		 * now that we're inactive, cause a rebalancing of the surviving
		 * workers
		 */
1655
		AutoVacuumShmem->av_signal[AutoVacRebalance] = true;
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
		LWLockRelease(AutovacuumLock);
	}
}

/*
 * Update the cost-based delay parameters, so that multiple workers consume
 * each a fraction of the total available I/O.
 */
void
AutoVacuumUpdateDelay(void)
{
	if (MyWorkerInfo)
	{
		VacuumCostDelay = MyWorkerInfo->wi_cost_delay;
		VacuumCostLimit = MyWorkerInfo->wi_cost_limit;
	}
}

/*
 * autovac_balance_cost
 *		Recalculate the cost limit setting for each active workers.
 *
 * Caller must hold the AutovacuumLock in exclusive mode.
 */
static void
autovac_balance_cost(void)
{
	WorkerInfo	worker;
B
Bruce Momjian 已提交
1684

1685 1686 1687 1688
	/*
	 * note: in cost_limit, zero also means use value from elsewhere, because
	 * zero is not a valid value.
	 */
B
Bruce Momjian 已提交
1689 1690 1691 1692 1693 1694
	int			vac_cost_limit = (autovacuum_vac_cost_limit > 0 ?
								autovacuum_vac_cost_limit : VacuumCostLimit);
	int			vac_cost_delay = (autovacuum_vac_cost_delay >= 0 ?
								autovacuum_vac_cost_delay : VacuumCostDelay);
	double		cost_total;
	double		cost_avail;
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706

	/* not set? nothing to do */
	if (vac_cost_limit <= 0 || vac_cost_delay <= 0)
		return;

	/* caculate the total base cost limit of active workers */
	cost_total = 0.0;
	worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers,
									   &AutoVacuumShmem->av_runningWorkers,
									   offsetof(WorkerInfoData, wi_links));
	while (worker)
	{
1707
		if (worker->wi_proc != NULL &&
1708 1709 1710 1711 1712 1713
			worker->wi_cost_limit_base > 0 && worker->wi_cost_delay > 0)
			cost_total +=
				(double) worker->wi_cost_limit_base / worker->wi_cost_delay;

		worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers,
										   &worker->wi_links,
B
Bruce Momjian 已提交
1714
										 offsetof(WorkerInfoData, wi_links));
1715 1716 1717 1718 1719 1720
	}
	/* there are no cost limits -- nothing to do */
	if (cost_total <= 0)
		return;

	/*
B
Bruce Momjian 已提交
1721 1722
	 * Adjust each cost limit of active workers to balance the total of cost
	 * limit to autovacuum_vacuum_cost_limit.
1723 1724 1725 1726 1727 1728 1729
	 */
	cost_avail = (double) vac_cost_limit / vac_cost_delay;
	worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers,
									   &AutoVacuumShmem->av_runningWorkers,
									   offsetof(WorkerInfoData, wi_links));
	while (worker)
	{
1730
		if (worker->wi_proc != NULL &&
1731 1732
			worker->wi_cost_limit_base > 0 && worker->wi_cost_delay > 0)
		{
B
Bruce Momjian 已提交
1733 1734
			int			limit = (int)
			(cost_avail * worker->wi_cost_limit_base / cost_total);
1735

1736 1737 1738 1739 1740
			/*
			 * We put a lower bound of 1 to the cost_limit, to avoid division-
			 * by-zero in the vacuum code.
			 */
			worker->wi_cost_limit = Max(Min(limit, worker->wi_cost_limit_base), 1);
1741 1742

			elog(DEBUG2, "autovac_balance_cost(pid=%u db=%u, rel=%u, cost_limit=%d, cost_delay=%d)",
1743
				 worker->wi_proc->pid, worker->wi_dboid,
1744 1745 1746 1747 1748
				 worker->wi_tableoid, worker->wi_cost_limit, worker->wi_cost_delay);
		}

		worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers,
										   &worker->wi_links,
B
Bruce Momjian 已提交
1749
										 offsetof(WorkerInfoData, wi_links));
1750 1751 1752 1753 1754
	}
}

/*
 * get_database_list
1755
 *		Return a list of all databases found in pg_database.
1756
 *
1757 1758 1759 1760
 * Note: this is the only function in which the autovacuum launcher uses a
 * transaction.  Although we aren't attached to any particular database and
 * therefore can't access most catalogs, we do have enough infrastructure
 * to do a seqscan on pg_database.
1761 1762
 */
static List *
1763
get_database_list(void)
1764
{
B
Bruce Momjian 已提交
1765
	List	   *dblist = NIL;
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
	Relation	rel;
	HeapScanDesc scan;
	HeapTuple	tup;

	/*
	 * Start a transaction so we can access pg_database, and get a snapshot.
	 * We don't have a use for the snapshot itself, but we're interested in
	 * the secondary effect that it sets RecentGlobalXmin.  (This is critical
	 * for anything that reads heap pages, because HOT may decide to prune
	 * them even if the process doesn't attempt to modify any tuples.)
	 */
	StartTransactionCommand();
	(void) GetTransactionSnapshot();

	/* Allocate our results in AutovacMemCxt, not transaction context */
	MemoryContextSwitchTo(AutovacMemCxt);

	rel = heap_open(DatabaseRelationId, AccessShareLock);
	scan = heap_beginscan(rel, SnapshotNow, 0, NULL);

	while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
1787
	{
1788 1789
		Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
		avw_dbase   *avdb;
1790

1791
		avdb = (avw_dbase *) palloc(sizeof(avw_dbase));
1792

1793 1794 1795
		avdb->adw_datid = HeapTupleGetOid(tup);
		avdb->adw_name = pstrdup(NameStr(pgdatabase->datname));
		avdb->adw_frozenxid = pgdatabase->datfrozenxid;
1796
		/* this gets set later: */
1797
		avdb->adw_entry = NULL;
1798

1799
		dblist = lappend(dblist, avdb);
1800 1801
	}

1802 1803 1804 1805
	heap_endscan(scan);
	heap_close(rel, AccessShareLock);

	CommitTransactionCommand();
1806 1807 1808 1809

	return dblist;
}

1810 1811
/*
 * Process a database table-by-table
1812
 *
1813 1814 1815 1816
 * Note that CHECK_FOR_INTERRUPTS is supposed to be used in certain spots in
 * order not to ignore shutdown commands for too long.
 */
static void
1817
do_autovacuum(void)
1818
{
1819
	Relation	classRel;
B
Bruce Momjian 已提交
1820 1821
	HeapTuple	tuple;
	HeapScanDesc relScan;
1822
	Form_pg_database dbForm;
1823
	List	   *table_oids = NIL;
1824 1825
	HASHCTL		ctl;
	HTAB	   *table_toast_map;
B
Bruce Momjian 已提交
1826
	ListCell   *volatile cell;
1827
	PgStat_StatDBEntry *shared;
1828
	PgStat_StatDBEntry *dbentry;
1829
	BufferAccessStrategy bstrategy;
1830
	ScanKeyData key;
1831
	TupleDesc	pg_class_desc;
1832

1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844
	/*
	 * StartTransactionCommand and CommitTransactionCommand will automatically
	 * switch to other contexts.  We need this one to keep the list of
	 * relations to vacuum/analyze across transactions.
	 */
	AutovacMemCxt = AllocSetContextCreate(TopMemoryContext,
										  "AV worker",
										  ALLOCSET_DEFAULT_MINSIZE,
										  ALLOCSET_DEFAULT_INITSIZE,
										  ALLOCSET_DEFAULT_MAXSIZE);
	MemoryContextSwitchTo(AutovacMemCxt);

1845
	/*
B
Bruce Momjian 已提交
1846 1847
	 * may be NULL if we couldn't find an entry (only happens if we are
	 * forcing a vacuum for anti-wrap purposes).
1848
	 */
1849
	dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);
1850 1851 1852 1853

	/* Start a transaction so our commands have one to play into. */
	StartTransactionCommand();

1854
	/*
B
Bruce Momjian 已提交
1855 1856 1857
	 * Clean up any dead statistics collector entries for this DB. We always
	 * want to do this exactly once per DB-processing cycle, even if we find
	 * nothing worth vacuuming in the database.
1858
	 */
1859
	pgstat_vacuum_stat();
1860

1861
	/*
1862 1863
	 * Find the pg_database entry and select the default freeze ages. We use
	 * zero in template and nonconnectable databases, else the system-wide
B
Bruce Momjian 已提交
1864
	 * default.
1865 1866 1867 1868 1869 1870 1871 1872 1873
	 */
	tuple = SearchSysCache(DATABASEOID,
						   ObjectIdGetDatum(MyDatabaseId),
						   0, 0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
	dbForm = (Form_pg_database) GETSTRUCT(tuple);

	if (dbForm->datistemplate || !dbForm->datallowconn)
1874
	{
1875
		default_freeze_min_age = 0;
1876 1877
		default_freeze_table_age = 0;
	}
1878
	else
1879
	{
1880
		default_freeze_min_age = vacuum_freeze_min_age;
1881 1882
		default_freeze_table_age = vacuum_freeze_table_age;
	}
1883 1884 1885

	ReleaseSysCache(tuple);

1886
	/* StartTransactionCommand changed elsewhere */
1887 1888
	MemoryContextSwitchTo(AutovacMemCxt);

1889 1890
	/* The database hash where pgstat keeps shared relations */
	shared = pgstat_fetch_stat_dbentry(InvalidOid);
1891

1892
	classRel = heap_open(RelationRelationId, AccessShareLock);
1893 1894 1895

	/* create a copy so we can use it after closing pg_class */
	pg_class_desc = CreateTupleDescCopy(RelationGetDescr(classRel));
1896

1897 1898 1899
	/* create hash table for toast <-> main relid mapping */
	MemSet(&ctl, 0, sizeof(ctl));
	ctl.keysize = sizeof(Oid);
1900
	ctl.entrysize = sizeof(av_relation);
1901 1902 1903 1904 1905 1906 1907
	ctl.hash = oid_hash;

	table_toast_map = hash_create("TOAST to main relid map",
								  100,
								  &ctl,
								  HASH_ELEM | HASH_FUNCTION);

1908
	/*
1909
	 * Scan pg_class to determine which tables to vacuum.
1910
	 *
1911 1912 1913 1914 1915 1916
	 * We do this in two passes: on the first one we collect the list of plain
	 * relations, and on the second one we collect TOAST tables. The reason
	 * for doing the second pass is that during it we want to use the main
	 * relation's pg_class.reloptions entry if the TOAST table does not have
	 * any, and we cannot obtain it unless we know beforehand what's the main
	 * table OID.
1917
	 *
1918 1919 1920
	 * We need to check TOAST tables separately because in cases with short,
	 * wide tables there might be proportionally much more activity in the
	 * TOAST table than in its parent.
1921
	 */
1922 1923 1924 1925 1926 1927
	ScanKeyInit(&key,
				Anum_pg_class_relkind,
				BTEqualStrategyNumber, F_CHAREQ,
				CharGetDatum(RELKIND_RELATION));

	relScan = heap_beginscan(classRel, SnapshotNow, 1, &key);
1928

1929
	/*
1930 1931
	 * On the first pass, we collect main tables to vacuum, and also the main
	 * table relid to TOAST relid mapping.
1932
	 */
1933 1934 1935 1936
	while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
	{
		Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
		PgStat_StatTabEntry *tabentry;
1937
		AutoVacOpts *relopts;
1938
		Oid			relid;
1939 1940 1941
		bool		dovacuum;
		bool		doanalyze;
		bool		wraparound;
1942 1943

		relid = HeapTupleGetOid(tuple);
1944

1945 1946
		/* Fetch reloptions and the pgstat entry for this table */
		relopts = extract_autovac_opts(tuple, pg_class_desc);
1947 1948
		tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
											 shared, dbentry);
1949

1950
		/* Check if it needs vacuum or analyze */
1951
		relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
1952 1953 1954 1955 1956 1957
								  &dovacuum, &doanalyze, &wraparound);

		/*
		 * Check if it is a temp table (presumably, of some other backend's).
		 * We cannot safely process other backends' temp tables.
		 */
1958
		if (classForm->relistemp)
1959
		{
1960 1961 1962 1963
			int			backendID;

			backendID = GetTempNamespaceBackendId(classForm->relnamespace);

1964 1965 1966 1967 1968 1969 1970 1971 1972
			/* We just ignore it if the owning backend is still active */
			if (backendID == MyBackendId || !BackendIdIsActive(backendID))
			{
				/*
				 * We found an orphan temp table (which was probably left
				 * behind by a crashed backend).  If it's so old as to need
				 * vacuum for wraparound, forcibly drop it.  Otherwise just
				 * log a complaint.
				 */
1973
				if (wraparound)
1974 1975 1976 1977 1978
				{
					ObjectAddress object;

					ereport(LOG,
							(errmsg("autovacuum: dropping orphan temp table \"%s\".\"%s\" in database \"%s\"",
1979
								 get_namespace_name(classForm->relnamespace),
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990
									NameStr(classForm->relname),
									get_database_name(MyDatabaseId))));
					object.classId = RelationRelationId;
					object.objectId = relid;
					object.objectSubId = 0;
					performDeletion(&object, DROP_CASCADE);
				}
				else
				{
					ereport(LOG,
							(errmsg("autovacuum: found orphan temp table \"%s\".\"%s\" in database \"%s\"",
1991
								 get_namespace_name(classForm->relnamespace),
1992 1993 1994 1995 1996
									NameStr(classForm->relname),
									get_database_name(MyDatabaseId))));
				}
			}
		}
1997
		else
1998
		{
1999
			/* relations that need work are added to table_oids */
2000 2001
			if (dovacuum || doanalyze)
				table_oids = lappend_oid(table_oids, relid);
2002 2003 2004 2005 2006 2007 2008

			/*
			 * Remember the association for the second pass.  Note: we must do
			 * this even if the table is going to be vacuumed, because we
			 * don't automatically vacuum toast tables along the parent table.
			 */
			if (OidIsValid(classForm->reltoastrelid))
2009
			{
2010 2011
				av_relation *hentry;
				bool		found;
2012

2013 2014 2015
				hentry = hash_search(table_toast_map,
									 &classForm->reltoastrelid,
									 HASH_ENTER, &found);
2016

2017 2018 2019 2020
				if (!found)
				{
					/* hash_search already filled in the key */
					hentry->ar_relid = relid;
2021 2022 2023 2024 2025 2026 2027
					hentry->ar_hasrelopts = false;
					if (relopts != NULL)
					{
						hentry->ar_hasrelopts = true;
						memcpy(&hentry->ar_reloptions, relopts,
							   sizeof(AutoVacOpts));
					}
2028
				}
2029 2030
			}
		}
2031
	}
2032

2033
	heap_endscan(relScan);
2034

2035 2036 2037 2038 2039 2040 2041 2042
	/* second pass: check TOAST tables */
	ScanKeyInit(&key,
				Anum_pg_class_relkind,
				BTEqualStrategyNumber, F_CHAREQ,
				CharGetDatum(RELKIND_TOASTVALUE));

	relScan = heap_beginscan(classRel, SnapshotNow, 1, &key);
	while ((tuple = heap_getnext(relScan, ForwardScanDirection)) != NULL)
2043
	{
2044 2045
		Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
		PgStat_StatTabEntry *tabentry;
2046
		Oid			relid;
2047
		AutoVacOpts *relopts = NULL;
2048 2049 2050
		bool		dovacuum;
		bool		doanalyze;
		bool		wraparound;
2051

2052
		/*
2053
		 * We cannot safely process other backends' temp tables, so skip 'em.
2054
		 */
2055
		if (classForm->relistemp)
2056
			continue;
2057

2058 2059
		relid = HeapTupleGetOid(tuple);

2060
		/*
2061 2062
		 * fetch reloptions -- if this toast table does not have them, try the
		 * main rel
2063 2064 2065 2066
		 */
		relopts = extract_autovac_opts(tuple, pg_class_desc);
		if (relopts == NULL)
		{
2067 2068
			av_relation *hentry;
			bool		found;
2069

2070 2071 2072 2073
			hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
			if (found && hentry->ar_hasrelopts)
				relopts = &hentry->ar_reloptions;
		}
2074 2075 2076 2077 2078

		/* Fetch the pgstat entry for this table */
		tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
											 shared, dbentry);

2079
		relation_needs_vacanalyze(relid, relopts, classForm, tabentry,
2080 2081 2082 2083 2084
								  &dovacuum, &doanalyze, &wraparound);

		/* ignore analyze for toast tables */
		if (dovacuum)
			table_oids = lappend_oid(table_oids, relid);
2085 2086
	}

2087 2088
	heap_endscan(relScan);
	heap_close(classRel, AccessShareLock);
2089

2090
	/*
B
Bruce Momjian 已提交
2091 2092 2093
	 * Create a buffer access strategy object for VACUUM to use.  We want to
	 * use the same one across all the vacuum operations we perform, since the
	 * point is for VACUUM not to blow out the shared cache.
2094 2095 2096
	 */
	bstrategy = GetAccessStrategy(BAS_VACUUM);

2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
	/*
	 * create a memory context to act as fake PortalContext, so that the
	 * contexts created in the vacuum code are cleaned up for each table.
	 */
	PortalContext = AllocSetContextCreate(AutovacMemCxt,
										  "Autovacuum Portal",
										  ALLOCSET_DEFAULT_INITSIZE,
										  ALLOCSET_DEFAULT_MINSIZE,
										  ALLOCSET_DEFAULT_MAXSIZE);

2107 2108 2109
	/*
	 * Perform operations on collected tables.
	 */
2110
	foreach(cell, table_oids)
2111
	{
B
Bruce Momjian 已提交
2112
		Oid			relid = lfirst_oid(cell);
2113
		autovac_table *tab;
2114
		WorkerInfo	worker;
B
Bruce Momjian 已提交
2115
		bool		skipit;
2116

2117
		CHECK_FOR_INTERRUPTS();
2118

2119
		/*
B
Bruce Momjian 已提交
2120 2121 2122
		 * hold schedule lock from here until we're sure that this table still
		 * needs vacuuming.  We also need the AutovacuumLock to walk the
		 * worker array, but we'll let go of that one quickly.
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
		 */
		LWLockAcquire(AutovacuumScheduleLock, LW_EXCLUSIVE);
		LWLockAcquire(AutovacuumLock, LW_SHARED);

		/*
		 * Check whether the table is being vacuumed concurrently by another
		 * worker.
		 */
		skipit = false;
		worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers,
B
Bruce Momjian 已提交
2133 2134
										 &AutoVacuumShmem->av_runningWorkers,
										 offsetof(WorkerInfoData, wi_links));
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
		while (worker)
		{
			/* ignore myself */
			if (worker == MyWorkerInfo)
				goto next_worker;

			/* ignore workers in other databases */
			if (worker->wi_dboid != MyDatabaseId)
				goto next_worker;

			if (worker->wi_tableoid == relid)
			{
				skipit = true;
				break;
			}

B
Bruce Momjian 已提交
2151
	next_worker:
2152 2153
			worker = (WorkerInfo) SHMQueueNext(&AutoVacuumShmem->av_runningWorkers,
											   &worker->wi_links,
B
Bruce Momjian 已提交
2154
										 offsetof(WorkerInfoData, wi_links));
2155 2156 2157 2158 2159 2160 2161 2162
		}
		LWLockRelease(AutovacuumLock);
		if (skipit)
		{
			LWLockRelease(AutovacuumScheduleLock);
			continue;
		}

2163
		/*
2164
		 * Check whether pgstat data still says we need to vacuum this table.
B
Bruce Momjian 已提交
2165 2166
		 * It could have changed if something else processed the table while
		 * we weren't looking.
2167
		 *
2168 2169 2170 2171
		 * Note: we have a special case in pgstat code to ensure that the
		 * stats we read are as up-to-date as possible, to avoid the problem
		 * that somebody just finished vacuuming this table.  The window to
		 * the race condition is not closed but it is very small.
2172
		 */
2173
		MemoryContextSwitchTo(AutovacMemCxt);
2174
		tab = table_recheck_autovac(relid, table_toast_map, pg_class_desc);
2175
		if (tab == NULL)
2176
		{
2177
			/* someone else vacuumed the table, or it went away */
2178
			LWLockRelease(AutovacuumScheduleLock);
2179
			continue;
2180
		}
2181

2182
		/*
B
Bruce Momjian 已提交
2183
		 * Ok, good to go.	Store the table in shared memory before releasing
2184 2185 2186 2187 2188 2189
		 * the lock so that other workers don't vacuum it concurrently.
		 */
		MyWorkerInfo->wi_tableoid = relid;
		LWLockRelease(AutovacuumScheduleLock);

		/* Set the initial vacuum cost parameters for this table */
2190 2191
		VacuumCostDelay = tab->at_vacuum_cost_delay;
		VacuumCostLimit = tab->at_vacuum_cost_limit;
2192

2193
		/* Last fixups before actually starting to work */
2194
		LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
2195 2196

		/* advertise my cost delay parameters for the balancing algorithm */
2197 2198 2199
		MyWorkerInfo->wi_cost_delay = tab->at_vacuum_cost_delay;
		MyWorkerInfo->wi_cost_limit = tab->at_vacuum_cost_limit;
		MyWorkerInfo->wi_cost_limit_base = tab->at_vacuum_cost_limit;
2200 2201

		/* do a balance */
2202
		autovac_balance_cost();
2203 2204

		/* done */
2205 2206
		LWLockRelease(AutovacuumLock);

2207 2208 2209
		/* clean up memory before each iteration */
		MemoryContextResetAndDeleteChildren(PortalContext);

2210 2211
		/*
		 * Save the relation name for a possible error message, to avoid a
2212
		 * catalog lookup in case of an error.	If any of these return NULL,
2213 2214 2215
		 * then the relation has been dropped since last we checked; skip it.
		 * Note: they must live in a long-lived memory context because we call
		 * vacuum and analyze in different transactions.
2216
		 */
2217 2218 2219 2220 2221 2222

		tab->at_relname = get_rel_name(tab->at_relid);
		tab->at_nspname = get_namespace_name(get_rel_namespace(tab->at_relid));
		tab->at_datname = get_database_name(MyDatabaseId);
		if (!tab->at_relname || !tab->at_nspname || !tab->at_datname)
			goto deleted;
2223

2224
		/*
2225 2226 2227
		 * We will abort vacuuming the current table if something errors out,
		 * and continue with the next one in schedule; in particular, this
		 * happens if we are interrupted with SIGINT.
2228 2229 2230 2231
		 */
		PG_TRY();
		{
			/* have at it */
2232
			MemoryContextSwitchTo(TopTransactionContext);
2233
			autovacuum_do_vac_analyze(tab, bstrategy);
2234 2235 2236

			/*
			 * Clear a possible query-cancel signal, to avoid a late reaction
B
Bruce Momjian 已提交
2237 2238 2239
			 * to an automatically-sent signal because of vacuuming the
			 * current table (we're done with it, so it would make no sense to
			 * cancel at this point.)
2240 2241
			 */
			QueryCancelPending = false;
2242 2243 2244 2245
		}
		PG_CATCH();
		{
			/*
2246 2247
			 * Abort the transaction, start a new one, and proceed with the
			 * next table in our list.
2248
			 */
2249 2250 2251
			HOLD_INTERRUPTS();
			if (tab->at_dovacuum)
				errcontext("automatic vacuum of table \"%s.%s.%s\"",
2252
						   tab->at_datname, tab->at_nspname, tab->at_relname);
2253
			else
2254
				errcontext("automatic analyze of table \"%s.%s.%s\"",
2255
						   tab->at_datname, tab->at_nspname, tab->at_relname);
2256 2257
			EmitErrorReport();

2258
			/* this resets the PGPROC flags too */
2259 2260 2261 2262 2263 2264 2265
			AbortOutOfAnyTransaction();
			FlushErrorState();
			MemoryContextResetAndDeleteChildren(PortalContext);

			/* restart our transaction for the following operations */
			StartTransactionCommand();
			RESUME_INTERRUPTS();
2266 2267 2268
		}
		PG_END_TRY();

2269
		/* the PGPROC flags are reset at the next end of transaction */
2270

2271
		/* be tidy */
2272 2273 2274 2275 2276 2277 2278
deleted:
		if (tab->at_datname != NULL)
			pfree(tab->at_datname);
		if (tab->at_nspname != NULL)
			pfree(tab->at_nspname);
		if (tab->at_relname != NULL)
			pfree(tab->at_relname);
2279
		pfree(tab);
2280 2281 2282 2283 2284

		/* remove my info from shared memory */
		LWLockAcquire(AutovacuumLock, LW_EXCLUSIVE);
		MyWorkerInfo->wi_tableoid = InvalidOid;
		LWLockRelease(AutovacuumLock);
2285
	}
2286

2287
	/*
2288 2289
	 * We leak table_toast_map here (among other things), but since we're
	 * going away soon, it's not a problem.
2290 2291
	 */

2292
	/*
B
Bruce Momjian 已提交
2293 2294
	 * Update pg_database.datfrozenxid, and truncate pg_clog if possible. We
	 * only need to do this once, not after each table.
2295 2296 2297
	 */
	vac_update_datfrozenxid();

2298 2299 2300 2301
	/* Finally close out the last transaction. */
	CommitTransactionCommand();
}

2302
/*
2303
 * extract_autovac_opts
2304
 *
2305 2306
 * Given a relation's pg_class tuple, return the AutoVacOpts portion of
 * reloptions, if set; otherwise, return NULL.
2307
 */
2308
static AutoVacOpts *
2309
extract_autovac_opts(HeapTuple tup, TupleDesc pg_class_desc)
2310
{
2311 2312
	bytea	   *relopts;
	AutoVacOpts *av;
2313

2314 2315
	Assert(((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_RELATION ||
		   ((Form_pg_class) GETSTRUCT(tup))->relkind == RELKIND_TOASTVALUE);
2316

2317 2318 2319
	relopts = extractRelOptions(tup, pg_class_desc, InvalidOid);
	if (relopts == NULL)
		return NULL;
2320

2321 2322 2323
	av = palloc(sizeof(AutoVacOpts));
	memcpy(av, &(((StdRdOptions *) relopts)->autovacuum), sizeof(AutoVacOpts));
	pfree(relopts);
2324

2325
	return av;
2326 2327
}

2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
/*
 * get_pgstat_tabentry_relid
 *
 * Fetch the pgstat entry of a table, either local to a database or shared.
 */
static PgStat_StatTabEntry *
get_pgstat_tabentry_relid(Oid relid, bool isshared, PgStat_StatDBEntry *shared,
						  PgStat_StatDBEntry *dbentry)
{
	PgStat_StatTabEntry *tabentry = NULL;

	if (isshared)
	{
		if (PointerIsValid(shared))
			tabentry = hash_search(shared->tables, &relid,
								   HASH_FIND, NULL);
	}
	else if (PointerIsValid(dbentry))
		tabentry = hash_search(dbentry->tables, &relid,
							   HASH_FIND, NULL);

	return tabentry;
}

2352 2353 2354
/*
 * table_recheck_autovac
 *
2355 2356
 * Recheck whether a table still needs vacuum or analyze.  Return value is a
 * valid autovac_table pointer if it does, NULL otherwise.
2357 2358
 *
 * Note that the returned autovac_table does not have the name fields set.
2359 2360
 */
static autovac_table *
2361 2362
table_recheck_autovac(Oid relid, HTAB *table_toast_map,
					  TupleDesc pg_class_desc)
2363 2364 2365 2366 2367 2368 2369 2370 2371
{
	Form_pg_class classForm;
	HeapTuple	classTup;
	bool		dovacuum;
	bool		doanalyze;
	autovac_table *tab = NULL;
	PgStat_StatTabEntry *tabentry;
	PgStat_StatDBEntry *shared;
	PgStat_StatDBEntry *dbentry;
2372
	bool		wraparound;
2373
	AutoVacOpts *avopts;
2374

2375
	/* use fresh stats */
2376
	autovac_refresh_stats();
2377 2378 2379 2380 2381 2382

	shared = pgstat_fetch_stat_dbentry(InvalidOid);
	dbentry = pgstat_fetch_stat_dbentry(MyDatabaseId);

	/* fetch the relation's relcache entry */
	classTup = SearchSysCacheCopy(RELOID,
2383 2384
								  ObjectIdGetDatum(relid),
								  0, 0, 0);
2385 2386 2387 2388
	if (!HeapTupleIsValid(classTup))
		return NULL;
	classForm = (Form_pg_class) GETSTRUCT(classTup);

2389
	/*
2390 2391
	 * Get the applicable reloptions.  If it is a TOAST table, try to get the
	 * main table reloptions if the toast table itself doesn't have.
2392
	 */
2393
	avopts = extract_autovac_opts(classTup, pg_class_desc);
2394
	if (classForm->relkind == RELKIND_TOASTVALUE &&
2395 2396
		avopts == NULL && table_toast_map != NULL)
	{
2397 2398
		av_relation *hentry;
		bool		found;
2399

2400 2401 2402 2403
		hentry = hash_search(table_toast_map, &relid, HASH_FIND, &found);
		if (found && hentry->ar_hasrelopts)
			avopts = &hentry->ar_reloptions;
	}
2404 2405 2406 2407 2408

	/* fetch the pgstat table entry */
	tabentry = get_pgstat_tabentry_relid(relid, classForm->relisshared,
										 shared, dbentry);

2409
	relation_needs_vacanalyze(relid, avopts, classForm, tabentry,
2410
							  &dovacuum, &doanalyze, &wraparound);
2411

2412 2413 2414
	/* ignore ANALYZE for toast tables */
	if (classForm->relkind == RELKIND_TOASTVALUE)
		doanalyze = false;
2415

2416 2417
	/* OK, it needs something done */
	if (doanalyze || dovacuum)
2418 2419
	{
		int			freeze_min_age;
2420
		int			freeze_table_age;
2421 2422 2423 2424
		int			vac_cost_limit;
		int			vac_cost_delay;

		/*
2425 2426 2427 2428
		 * Calculate the vacuum cost parameters and the freeze ages.  If there
		 * are options set in pg_class.reloptions, use them; in the case of a
		 * toast table, try the main table too.  Otherwise use the GUC
		 * defaults, autovacuum's own first and plain vacuum second.
2429
		 */
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452

		/* -1 in autovac setting means use plain vacuum_cost_delay */
		vac_cost_delay = (avopts && avopts->vacuum_cost_delay >= 0)
			? avopts->vacuum_cost_delay
			: (autovacuum_vac_cost_delay >= 0)
				? autovacuum_vac_cost_delay
				: VacuumCostDelay;

		/* 0 or -1 in autovac setting means use plain vacuum_cost_limit */
		vac_cost_limit = (avopts && avopts->vacuum_cost_limit > 0)
			? avopts->vacuum_cost_limit
			: (autovacuum_vac_cost_limit > 0)
				? autovacuum_vac_cost_limit
				: VacuumCostLimit;

		/* these do not have autovacuum-specific settings */
		freeze_min_age = (avopts && avopts->freeze_min_age >= 0)
			? avopts->freeze_min_age
			: default_freeze_min_age;

		freeze_table_age = (avopts && avopts->freeze_table_age >= 0)
			? avopts->freeze_table_age
			: default_freeze_table_age;
2453 2454 2455 2456 2457 2458

		tab = palloc(sizeof(autovac_table));
		tab->at_relid = relid;
		tab->at_dovacuum = dovacuum;
		tab->at_doanalyze = doanalyze;
		tab->at_freeze_min_age = freeze_min_age;
2459
		tab->at_freeze_table_age = freeze_table_age;
2460 2461
		tab->at_vacuum_cost_limit = vac_cost_limit;
		tab->at_vacuum_cost_delay = vac_cost_delay;
2462
		tab->at_wraparound = wraparound;
2463 2464 2465
		tab->at_relname = NULL;
		tab->at_nspname = NULL;
		tab->at_datname = NULL;
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
	}

	heap_freetuple(classTup);

	return tab;
}

/*
 * relation_needs_vacanalyze
 *
 * Check whether a relation needs to be vacuumed or analyzed; return each into
2477
 * "dovacuum" and "doanalyze", respectively.  Also return whether the vacuum is
2478 2479 2480 2481 2482 2483
 * being forced because of Xid wraparound.
 *
 * relopts is a pointer to the AutoVacOpts options (either for itself in the
 * case of a plain table, or for either itself or its parent table in the case
 * of a TOAST table), NULL if none; tabentry is the pgstats entry, which can be
 * NULL.
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495
 *
 * A table needs to be vacuumed if the number of dead tuples exceeds a
 * threshold.  This threshold is calculated as
 *
 * threshold = vac_base_thresh + vac_scale_factor * reltuples
 *
 * For analyze, the analysis done is that the number of tuples inserted,
 * deleted and updated since the last analyze exceeds a threshold calculated
 * in the same fashion as above.  Note that the collector actually stores
 * the number of tuples (both live and dead) that there were as of the last
 * analyze.  This is asymmetric to the VACUUM case.
 *
2496 2497 2498
 * We also force vacuum if the table's relfrozenxid is more than freeze_max_age
 * transactions back.
 *
2499 2500
 * A table whose autovacuum_enabled option is false is
 * automatically skipped (unless we have to vacuum it due to freeze_max_age).
2501
 * Thus autovacuum can be disabled for specific tables. Also, when the stats
2502
 * collector does not have data about a table, it will be skipped.
2503
 *
2504
 * A table whose vac_base_thresh value is < 0 takes the base value from the
2505
 * autovacuum_vacuum_threshold GUC variable.  Similarly, a vac_scale_factor
2506
 * value < 0 is substituted with the value of
2507 2508 2509
 * autovacuum_vacuum_scale_factor GUC variable.  Ditto for analyze.
 */
static void
2510
relation_needs_vacanalyze(Oid relid,
2511
						  AutoVacOpts *relopts,
2512 2513
						  Form_pg_class classForm,
						  PgStat_StatTabEntry *tabentry,
B
Bruce Momjian 已提交
2514
 /* output params below */
2515
						  bool *dovacuum,
2516 2517
						  bool *doanalyze,
						  bool *wraparound)
2518
{
2519
	bool		force_vacuum;
2520
	bool		av_enabled;
B
Bruce Momjian 已提交
2521
	float4		reltuples;		/* pg_class.reltuples */
B
Bruce Momjian 已提交
2522

2523
	/* constants from reloptions or GUC variables */
B
Bruce Momjian 已提交
2524 2525 2526 2527
	int			vac_base_thresh,
				anl_base_thresh;
	float4		vac_scale_factor,
				anl_scale_factor;
B
Bruce Momjian 已提交
2528

2529
	/* thresholds calculated from above constants */
B
Bruce Momjian 已提交
2530 2531
	float4		vacthresh,
				anlthresh;
B
Bruce Momjian 已提交
2532

2533
	/* number of vacuum (resp. analyze) tuples at this time */
B
Bruce Momjian 已提交
2534 2535
	float4		vactuples,
				anltuples;
B
Bruce Momjian 已提交
2536

2537 2538 2539
	/* freeze parameters */
	int			freeze_max_age;
	TransactionId xidForceLimit;
2540 2541 2542

	AssertArg(classForm != NULL);
	AssertArg(OidIsValid(relid));
2543 2544

	/*
2545 2546 2547
	 * Determine vacuum/analyze equation parameters.  We have two possible
	 * sources: the passed reloptions (which could be a main table or a toast
	 * table), or the autovacuum GUC variables.
2548
	 */
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571

	/* -1 in autovac setting means use plain vacuum_cost_delay */
	vac_scale_factor = (relopts && relopts->vacuum_scale_factor >= 0)
		? relopts->vacuum_scale_factor
		: autovacuum_vac_scale;

	vac_base_thresh = (relopts && relopts->vacuum_threshold >= 0)
		? relopts->vacuum_threshold
		: autovacuum_vac_thresh;

	anl_scale_factor = (relopts && relopts->analyze_scale_factor >= 0)
		? relopts->analyze_scale_factor
		: autovacuum_anl_scale;

	anl_base_thresh = (relopts && relopts->analyze_threshold >= 0)
		? relopts->analyze_threshold
		: autovacuum_anl_thresh;

	freeze_max_age = (relopts && relopts->freeze_max_age >= 0)
		? Min(relopts->freeze_max_age, autovacuum_freeze_max_age)
		: autovacuum_freeze_max_age;

	av_enabled = (relopts ? relopts->enabled : true);
2572

2573 2574 2575 2576 2577 2578 2579
	/* Force vacuum if table is at risk of wraparound */
	xidForceLimit = recentXid - freeze_max_age;
	if (xidForceLimit < FirstNormalTransactionId)
		xidForceLimit -= FirstNormalTransactionId;
	force_vacuum = (TransactionIdIsNormal(classForm->relfrozenxid) &&
					TransactionIdPrecedes(classForm->relfrozenxid,
										  xidForceLimit));
2580
	*wraparound = force_vacuum;
2581

2582 2583
	/* User disabled it in pg_class.reloptions?  (But ignore if at risk) */
	if (!force_vacuum && !av_enabled)
2584 2585 2586
	{
		*doanalyze = false;
		*dovacuum = false;
2587
		return;
2588
	}
2589

2590 2591 2592 2593
	if (PointerIsValid(tabentry))
	{
		reltuples = classForm->reltuples;
		vactuples = tabentry->n_dead_tuples;
2594
		anltuples = tabentry->changes_since_analyze;
2595

2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608
		vacthresh = (float4) vac_base_thresh + vac_scale_factor * reltuples;
		anlthresh = (float4) anl_base_thresh + anl_scale_factor * reltuples;

		/*
		 * Note that we don't need to take special consideration for stat
		 * reset, because if that happens, the last vacuum and analyze counts
		 * will be reset too.
		 */
		elog(DEBUG3, "%s: vac: %.0f (threshold %.0f), anl: %.0f (threshold %.0f)",
			 NameStr(classForm->relname),
			 vactuples, vacthresh, anltuples, anlthresh);

		/* Determine if this table needs vacuum or analyze. */
2609 2610
		*dovacuum = force_vacuum || (vactuples > vacthresh);
		*doanalyze = (anltuples > anlthresh);
2611 2612 2613 2614
	}
	else
	{
		/*
B
Bruce Momjian 已提交
2615 2616 2617
		 * Skip a table not found in stat hash, unless we have to force vacuum
		 * for anti-wrap purposes.	If it's not acted upon, there's no need to
		 * vacuum it.
2618
		 */
2619 2620
		*dovacuum = force_vacuum;
		*doanalyze = false;
2621
	}
2622 2623 2624

	/* ANALYZE refuses to work with pg_statistics */
	if (relid == StatisticRelationId)
2625
		*doanalyze = false;
2626 2627 2628 2629
}

/*
 * autovacuum_do_vac_analyze
2630
 *		Vacuum and/or analyze the specified table
2631 2632
 */
static void
2633
autovacuum_do_vac_analyze(autovac_table *tab,
2634
						  BufferAccessStrategy bstrategy)
2635
{
2636
	VacuumStmt	vacstmt;
B
Bruce Momjian 已提交
2637

2638
	/* Set up command parameters --- use a local variable instead of palloc */
A
Alvaro Herrera 已提交
2639 2640 2641
	MemSet(&vacstmt, 0, sizeof(vacstmt));

	vacstmt.type = T_VacuumStmt;
2642 2643 2644 2645 2646
	vacstmt.options = 0;
	if (tab->at_dovacuum)
		vacstmt.options |= VACOPT_VACUUM;
	if (tab->at_doanalyze)
		vacstmt.options |= VACOPT_ANALYZE;
2647
	vacstmt.freeze_min_age = tab->at_freeze_min_age;
2648
	vacstmt.freeze_table_age = tab->at_freeze_table_age;
2649
	vacstmt.relation = NULL;	/* not used since we pass a relid */
2650
	vacstmt.va_cols = NIL;
2651

2652
	/* Let pgstat know what we're doing */
2653
	autovac_report_activity(tab);
2654

2655
	vacuum(&vacstmt, tab->at_relid, false, bstrategy, tab->at_wraparound, true);
2656 2657
}

2658 2659
/*
 * autovac_report_activity
B
Bruce Momjian 已提交
2660
 *		Report to pgstat what autovacuum is doing
2661 2662 2663 2664 2665
 *
 * We send a SQL string corresponding to what the user would see if the
 * equivalent command was to be issued manually.
 *
 * Note we assume that we are going to report the next command as soon as we're
2666
 * done with the current one, and exit right after the last one, so we don't
2667 2668 2669
 * bother to report "<IDLE>" or some such.
 */
static void
2670
autovac_report_activity(autovac_table *tab)
2671
{
2672
#define MAX_AUTOVAC_ACTIV_LEN (NAMEDATALEN * 2 + 56)
2673 2674
	char		activity[MAX_AUTOVAC_ACTIV_LEN];
	int			len;
2675 2676

	/* Report the command and possible options */
2677
	if (tab->at_dovacuum)
2678
		snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
2679 2680
				 "autovacuum: VACUUM%s",
				 tab->at_doanalyze ? " ANALYZE" : "");
2681
	else
2682
		snprintf(activity, MAX_AUTOVAC_ACTIV_LEN,
2683
				 "autovacuum: ANALYZE");
2684

2685 2686 2687
	/*
	 * Report the qualified name of the relation.
	 */
2688
	len = strlen(activity);
2689

2690
	snprintf(activity + len, MAX_AUTOVAC_ACTIV_LEN - len,
2691
			 " %s.%s%s", tab->at_nspname, tab->at_relname,
2692
			 tab->at_wraparound ? " (to prevent wraparound)" : "");
2693

2694 2695 2696
	/* Set statement_timestamp() to current time for pg_stat_activity */
	SetCurrentStatementStartTimestamp();

2697 2698 2699
	pgstat_report_activity(activity);
}

2700 2701
/*
 * AutoVacuumingActive
B
Bruce Momjian 已提交
2702 2703
 *		Check GUC vars and report whether the autovacuum process should be
 *		running.
2704 2705 2706 2707
 */
bool
AutoVacuumingActive(void)
{
2708
	if (!autovacuum_start_daemon || !pgstat_track_counts)
2709 2710 2711 2712 2713 2714
		return false;
	return true;
}

/*
 * autovac_init
B
Bruce Momjian 已提交
2715
 *		This is called at postmaster initialization.
2716
 *
2717
 * All we do here is annoy the user if he got it wrong.
2718 2719 2720 2721
 */
void
autovac_init(void)
{
2722
	if (autovacuum_start_daemon && !pgstat_track_counts)
2723 2724
		ereport(WARNING,
				(errmsg("autovacuum not started because of misconfiguration"),
2725
				 errhint("Enable the \"track_counts\" option.")));
2726 2727 2728
}

/*
2729 2730 2731
 * IsAutoVacuum functions
 *		Return whether this is either a launcher autovacuum process or a worker
 *		process.
2732 2733
 */
bool
2734 2735 2736 2737 2738 2739 2740
IsAutoVacuumLauncherProcess(void)
{
	return am_autovacuum_launcher;
}

bool
IsAutoVacuumWorkerProcess(void)
2741
{
2742 2743 2744 2745 2746 2747
	return am_autovacuum_worker;
}


/*
 * AutoVacuumShmemSize
B
Bruce Momjian 已提交
2748
 *		Compute space needed for autovacuum-related shared memory
2749 2750 2751 2752
 */
Size
AutoVacuumShmemSize(void)
{
B
Bruce Momjian 已提交
2753
	Size		size;
2754 2755 2756 2757 2758 2759 2760 2761 2762

	/*
	 * Need the fixed struct and the array of WorkerInfoData.
	 */
	size = sizeof(AutoVacuumShmemStruct);
	size = MAXALIGN(size);
	size = add_size(size, mul_size(autovacuum_max_workers,
								   sizeof(WorkerInfoData)));
	return size;
2763 2764 2765 2766 2767 2768 2769 2770 2771
}

/*
 * AutoVacuumShmemInit
 *		Allocate and initialize autovacuum-related shared memory
 */
void
AutoVacuumShmemInit(void)
{
B
Bruce Momjian 已提交
2772
	bool		found;
2773 2774 2775 2776 2777 2778 2779 2780 2781 2782

	AutoVacuumShmem = (AutoVacuumShmemStruct *)
		ShmemInitStruct("AutoVacuum Data",
						AutoVacuumShmemSize(),
						&found);
	if (AutoVacuumShmem == NULL)
		ereport(FATAL,
				(errcode(ERRCODE_OUT_OF_MEMORY),
				 errmsg("not enough shared memory for autovacuum")));

2783 2784 2785 2786 2787 2788 2789 2790
	if (!IsUnderPostmaster)
	{
		WorkerInfo	worker;
		int			i;

		Assert(!found);

		AutoVacuumShmem->av_launcherpid = 0;
2791
		AutoVacuumShmem->av_freeWorkers = NULL;
2792
		SHMQueueInit(&AutoVacuumShmem->av_runningWorkers);
2793
		AutoVacuumShmem->av_startingWorker = NULL;
2794 2795 2796 2797 2798 2799 2800

		worker = (WorkerInfo) ((char *) AutoVacuumShmem +
							   MAXALIGN(sizeof(AutoVacuumShmemStruct)));

		/* initialize the WorkerInfo free list */
		for (i = 0; i < autovacuum_max_workers; i++)
		{
2801 2802
			worker[i].wi_links.next = (SHM_QUEUE *) AutoVacuumShmem->av_freeWorkers;
			AutoVacuumShmem->av_freeWorkers = &worker[i];
2803 2804 2805 2806
		}
	}
	else
		Assert(found);
2807
}
2808 2809 2810

/*
 * autovac_refresh_stats
B
Bruce Momjian 已提交
2811
 *		Refresh pgstats data for an autovacuum process
2812 2813
 *
 * Cause the next pgstats read operation to obtain fresh data, but throttle
B
Bruce Momjian 已提交
2814
 * such refreshing in the autovacuum launcher.	This is mostly to avoid
2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
 * rereading the pgstats files too many times in quick succession when there
 * are many databases.
 *
 * Note: we avoid throttling in the autovac worker, as it would be
 * counterproductive in the recheck logic.
 */
static void
autovac_refresh_stats(void)
{
	if (IsAutoVacuumLauncherProcess())
	{
B
Bruce Momjian 已提交
2826 2827
		static TimestampTz last_read = 0;
		TimestampTz current_time;
2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839

		current_time = GetCurrentTimestamp();

		if (!TimestampDifferenceExceeds(last_read, current_time,
										STATS_READ_DELAY))
			return;

		last_read = current_time;
	}

	pgstat_clear_snapshot();
}