vacuumlazy.c 33.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/*-------------------------------------------------------------------------
 *
 * vacuumlazy.c
 *	  Concurrent ("lazy") vacuuming.
 *
 *
 * The major space usage for LAZY VACUUM is storage for the array of dead
 * tuple TIDs, with the next biggest need being storage for per-disk-page
 * free space info.  We want to ensure we can vacuum even the very largest
 * relations with finite memory space usage.  To do that, we set upper bounds
 * on the number of tuples and pages we will keep track of at once.
 *
13 14 15 16 17
 * We are willing to use at most maintenance_work_mem memory space to keep
 * track of dead tuples.  We initially allocate an array of TIDs of that size.
 * If the array threatens to overflow, we suspend the heap scan phase and
 * perform a pass of index cleanup and page compaction, then resume the heap
 * scan with an empty TID array.
18 19 20
 *
 * We can limit the storage for page free space to MaxFSMPages entries,
 * since that's the most the free space map will be willing to remember
21 22
 * anyway.	If the relation has fewer than that many pages with free space,
 * life is easy: just build an array of per-page info.	If it has more,
23 24 25 26 27 28
 * we store the free space info as a heap ordered by amount of free space,
 * so that we can discard the pages with least free space to ensure we never
 * have more than MaxFSMPages entries in all.  The surviving page entries
 * are passed to the free space map at conclusion of the scan.
 *
 *
P
 
PostgreSQL Daemon 已提交
29
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
30 31 32 33
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
34
 *	  $PostgreSQL: pgsql/src/backend/commands/vacuumlazy.c,v 1.62 2005/11/20 19:49:07 tgl Exp $
35 36 37 38 39
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

40 41
#include <math.h>

42 43 44 45 46
#include "access/genam.h"
#include "access/heapam.h"
#include "access/xlog.h"
#include "commands/vacuum.h"
#include "miscadmin.h"
47
#include "pgstat.h"
48 49
#include "storage/freespace.h"
#include "storage/smgr.h"
50
#include "utils/lsyscache.h"
51
#include "utils/pg_rusage.h"
52 53 54 55 56 57


/*
 * Space/time tradeoff parameters: do these need to be user-tunable?
 *
 * To consider truncating the relation, we want there to be at least
58 59
 * REL_TRUNCATE_MINIMUM or (relsize / REL_TRUNCATE_FRACTION) (whichever
 * is less) potentially-freeable pages.
60
 */
61
#define REL_TRUNCATE_MINIMUM	1000
62 63 64 65 66 67
#define REL_TRUNCATE_FRACTION	16


typedef struct LVRelStats
{
	/* Overall statistics about rel */
68
	BlockNumber rel_pages;
69
	double		rel_tuples;
B
Bruce Momjian 已提交
70
	BlockNumber pages_removed;
71
	double		tuples_deleted;
72
	BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
73
	Size		threshold;		/* minimum interesting free space */
74 75
	/* List of TIDs of tuples we intend to delete */
	/* NB: this list is ordered by TID address */
76 77
	int			num_dead_tuples;	/* current # of entries */
	int			max_dead_tuples;	/* # slots allocated in array */
78
	ItemPointer dead_tuples;	/* array of ItemPointerData */
79 80
	/* Array or heap of per-page info about free space */
	/* We use a simple array until it fills up, then convert to heap */
81 82
	bool		fs_is_heap;		/* are we using heap organization? */
	int			num_free_pages; /* current # of entries */
83
	int			max_free_pages; /* # slots allocated in array */
B
Bruce Momjian 已提交
84
	PageFreeSpaceInfo *free_pages;		/* array or heap of blkno/avail */
85 86 87
} LVRelStats;


B
Bruce Momjian 已提交
88
static int	elevel = -1;
89

90 91
static TransactionId OldestXmin;
static TransactionId FreezeLimit;
92 93 94 95


/* non-export function prototypes */
static void lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
96
			   Relation *Irel, int nindexes);
97
static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats);
98
static void lazy_scan_index(Relation indrel, LVRelStats *vacrelstats);
99
static void lazy_vacuum_index(Relation indrel,
B
Bruce Momjian 已提交
100 101 102
				  double *index_tups_vacuumed,
				  BlockNumber *index_pages_removed,
				  LVRelStats *vacrelstats);
103 104
static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer,
				 int tupindex, LVRelStats *vacrelstats);
105 106
static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats);
static BlockNumber count_nondeletable_pages(Relation onerel,
107
						 LVRelStats *vacrelstats);
108 109
static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks);
static void lazy_record_dead_tuple(LVRelStats *vacrelstats,
110
					   ItemPointer itemptr);
111
static void lazy_record_free_space(LVRelStats *vacrelstats,
112
					   BlockNumber page, Size avail);
113
static bool lazy_tid_reaped(ItemPointer itemptr, void *state);
114
static bool dummy_tid_reaped(ItemPointer itemptr, void *state);
115 116
static void lazy_update_fsm(Relation onerel, LVRelStats *vacrelstats);
static int	vac_cmp_itemptr(const void *left, const void *right);
117
static int	vac_cmp_page_spaces(const void *left, const void *right);
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135


/*
 *	lazy_vacuum_rel() -- perform LAZY VACUUM for one heap relation
 *
 *		This routine vacuums a single heap, cleans out its indexes, and
 *		updates its num_pages and num_tuples statistics.
 *
 *		At entry, we have already established a transaction and opened
 *		and locked the relation.
 */
void
lazy_vacuum_rel(Relation onerel, VacuumStmt *vacstmt)
{
	LVRelStats *vacrelstats;
	Relation   *Irel;
	int			nindexes;
	bool		hasindex;
136
	BlockNumber possibly_freeable;
137 138

	if (vacstmt->verbose)
139
		elevel = INFO;
140
	else
141
		elevel = DEBUG2;
B
Bruce Momjian 已提交
142

143 144
	vacuum_set_xid_limits(vacstmt, onerel->rd_rel->relisshared,
						  &OldestXmin, &FreezeLimit);
145

146
	vacrelstats = (LVRelStats *) palloc0(sizeof(LVRelStats));
147

148 149 150 151
	/* Set threshold for interesting free space = average request size */
	/* XXX should we scale it up or down?  Adjust vacuum.c too, if so */
	vacrelstats->threshold = GetAvgFSMRequestSize(&onerel->rd_node);

152
	/* Open all indexes of the relation */
153
	vac_open_indexes(onerel, ShareUpdateExclusiveLock, &nindexes, &Irel);
154 155 156 157 158 159
	hasindex = (nindexes > 0);

	/* Do the vacuuming */
	lazy_scan_heap(onerel, vacrelstats, Irel, nindexes);

	/* Done with indexes */
160
	vac_close_indexes(nindexes, Irel, NoLock);
161 162 163 164

	/*
	 * Optionally truncate the relation.
	 *
165 166
	 * Don't even think about it unless we have a shot at releasing a goodly
	 * number of pages.  Otherwise, the time taken isn't worth it.
167 168
	 */
	possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages;
169
	if (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
B
Bruce Momjian 已提交
170
		possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION)
171 172 173 174 175 176
		lazy_truncate_heap(onerel, vacrelstats);

	/* Update shared free space map with final free space info */
	lazy_update_fsm(onerel, vacrelstats);

	/* Update statistics in pg_class */
177 178 179 180
	vac_update_relstats(RelationGetRelid(onerel),
						vacrelstats->rel_pages,
						vacrelstats->rel_tuples,
						hasindex);
181 182

	/* report results to the stats collector, too */
183
	pgstat_report_vacuum(RelationGetRelid(onerel), onerel->rd_rel->relisshared,
B
Bruce Momjian 已提交
184
						 vacstmt->analyze, vacrelstats->rel_tuples);
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
}


/*
 *	lazy_scan_heap() -- scan an open heap relation
 *
 *		This routine sets commit status bits, builds lists of dead tuples
 *		and pages with free space, and calculates statistics on the number
 *		of live tuples in the heap.  When done, or when we run low on space
 *		for dead-tuple TIDs, invoke vacuuming of indexes and heap.
 */
static void
lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
			   Relation *Irel, int nindexes)
{
	BlockNumber nblocks,
				blkno;
	HeapTupleData tuple;
	char	   *relname;
204
	BlockNumber empty_pages;
205 206 207 208
	double		num_tuples,
				tups_vacuumed,
				nkeep,
				nunused;
209 210 211
	double	   *index_tups_vacuumed;
	BlockNumber *index_pages_removed;
	bool		did_vacuum_index = false;
212
	int			i;
213
	PGRUsage	ru0;
214

215
	pg_rusage_init(&ru0);
216 217

	relname = RelationGetRelationName(onerel);
218 219 220 221
	ereport(elevel,
			(errmsg("vacuuming \"%s.%s\"",
					get_namespace_name(RelationGetNamespace(onerel)),
					relname)));
222

223
	empty_pages = 0;
224 225
	num_tuples = tups_vacuumed = nkeep = nunused = 0;

226 227 228 229 230
	/*
	 * Because index vacuuming is done in multiple passes, we have to keep
	 * track of the total number of rows and pages removed from each index.
	 * index_tups_vacuumed[i] is the number removed so far from the i'th
	 * index.  (For partial indexes this could well be different from
B
Bruce Momjian 已提交
231
	 * tups_vacuumed.)	Likewise for index_pages_removed[i].
232 233 234 235
	 */
	index_tups_vacuumed = (double *) palloc0(nindexes * sizeof(double));
	index_pages_removed = (BlockNumber *) palloc0(nindexes * sizeof(BlockNumber));

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
	nblocks = RelationGetNumberOfBlocks(onerel);
	vacrelstats->rel_pages = nblocks;
	vacrelstats->nonempty_pages = 0;

	lazy_space_alloc(vacrelstats, nblocks);

	for (blkno = 0; blkno < nblocks; blkno++)
	{
		Buffer		buf;
		Page		page;
		OffsetNumber offnum,
					maxoff;
		bool		pgchanged,
					tupgone,
					hastup;
		int			prev_dead_count;

253
		vacuum_delay_point();
J
Jan Wieck 已提交
254

255
		/*
B
Bruce Momjian 已提交
256 257
		 * If we are close to overrunning the available space for dead-tuple
		 * TIDs, pause and do a cycle of vacuuming before we tackle this page.
258
		 */
259
		if ((vacrelstats->max_dead_tuples - vacrelstats->num_dead_tuples) < MaxHeapTuplesPerPage &&
260 261 262 263
			vacrelstats->num_dead_tuples > 0)
		{
			/* Remove index entries */
			for (i = 0; i < nindexes; i++)
264 265 266 267 268
				lazy_vacuum_index(Irel[i],
								  &index_tups_vacuumed[i],
								  &index_pages_removed[i],
								  vacrelstats);
			did_vacuum_index = true;
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
			/* Remove tuples from heap */
			lazy_vacuum_heap(onerel, vacrelstats);
			/* Forget the now-vacuumed tuples, and press on */
			vacrelstats->num_dead_tuples = 0;
		}

		buf = ReadBuffer(onerel, blkno);

		/* In this phase we only need shared access to the buffer */
		LockBuffer(buf, BUFFER_LOCK_SHARE);

		page = BufferGetPage(buf);

		if (PageIsNew(page))
		{
284
			/*
B
Bruce Momjian 已提交
285 286 287
			 * An all-zeroes page could be left over if a backend extends the
			 * relation but crashes before initializing the page. Reclaim such
			 * pages for use.
288
			 *
B
Bruce Momjian 已提交
289 290 291 292 293 294 295 296
			 * We have to be careful here because we could be looking at a page
			 * that someone has just added to the relation and not yet been
			 * able to initialize (see RelationGetBufferForTuple). To
			 * interlock against that, release the buffer read lock (which we
			 * must do anyway) and grab the relation extension lock before
			 * re-locking in exclusive mode.  If the page is still
			 * uninitialized by then, it must be left over from a crashed
			 * backend, and we can initialize it.
297
			 *
B
Bruce Momjian 已提交
298 299 300
			 * We don't really need the relation lock when this is a new or temp
			 * relation, but it's probably not worth the code space to check
			 * that, since this surely isn't a critical path.
301
			 *
B
Bruce Momjian 已提交
302 303
			 * Note: the comparable code in vacuum.c need not worry because it's
			 * got exclusive lock on the whole relation.
304
			 */
305
			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
306 307
			LockRelationForExtension(onerel, ExclusiveLock);
			UnlockRelationForExtension(onerel, ExclusiveLock);
308 309 310
			LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
			if (PageIsNew(page))
			{
311
				ereport(WARNING,
B
Bruce Momjian 已提交
312 313
				(errmsg("relation \"%s\" page %u is uninitialized --- fixing",
						relname, blkno)));
314
				PageInit(page, BufferGetPageSize(buf), 0);
315
				empty_pages++;
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
				lazy_record_free_space(vacrelstats, blkno,
									   PageGetFreeSpace(page));
			}
			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
			WriteBuffer(buf);
			continue;
		}

		if (PageIsEmpty(page))
		{
			empty_pages++;
			lazy_record_free_space(vacrelstats, blkno,
								   PageGetFreeSpace(page));
			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
			ReleaseBuffer(buf);
			continue;
		}

		pgchanged = false;
		hastup = false;
		prev_dead_count = vacrelstats->num_dead_tuples;
		maxoff = PageGetMaxOffsetNumber(page);
		for (offnum = FirstOffsetNumber;
			 offnum <= maxoff;
			 offnum = OffsetNumberNext(offnum))
		{
			ItemId		itemid;

			itemid = PageGetItemId(page, offnum);

			if (!ItemIdIsUsed(itemid))
			{
				nunused += 1;
				continue;
			}

			tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
			tuple.t_len = ItemIdGetLength(itemid);
			ItemPointerSet(&(tuple.t_self), blkno, offnum);

			tupgone = false;

358
			switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin, buf))
359 360
			{
				case HEAPTUPLE_DEAD:
361
					tupgone = true;		/* we can delete the tuple */
362 363
					break;
				case HEAPTUPLE_LIVE:
364

365
					/*
B
Bruce Momjian 已提交
366 367
					 * Tuple is good.  Consider whether to replace its xmin
					 * value with FrozenTransactionId.
T
Tom Lane 已提交
368
					 *
B
Bruce Momjian 已提交
369 370 371 372 373 374
					 * NB: Since we hold only a shared buffer lock here, we are
					 * assuming that TransactionId read/write is atomic.  This
					 * is not the only place that makes such an assumption.
					 * It'd be possible to avoid the assumption by momentarily
					 * acquiring exclusive lock, but for the moment I see no
					 * need to.
375
					 */
376 377
					if (TransactionIdIsNormal(HeapTupleHeaderGetXmin(tuple.t_data)) &&
						TransactionIdPrecedes(HeapTupleHeaderGetXmin(tuple.t_data),
378 379
											  FreezeLimit))
					{
380
						HeapTupleHeaderSetXmin(tuple.t_data, FrozenTransactionId);
T
Tom Lane 已提交
381 382
						/* infomask should be okay already */
						Assert(tuple.t_data->t_infomask & HEAP_XMIN_COMMITTED);
383 384
						pgchanged = true;
					}
385 386 387 388 389 390 391 392

					/*
					 * Other checks...
					 */
					if (onerel->rd_rel->relhasoids &&
						!OidIsValid(HeapTupleGetOid(&tuple)))
						elog(WARNING, "relation \"%s\" TID %u/%u: OID is invalid",
							 relname, blkno, offnum);
393 394
					break;
				case HEAPTUPLE_RECENTLY_DEAD:
395

396
					/*
B
Bruce Momjian 已提交
397 398
					 * If tuple is recently deleted then we must not remove it
					 * from relation.
399 400 401 402 403 404 405 406 407 408
					 */
					nkeep += 1;
					break;
				case HEAPTUPLE_INSERT_IN_PROGRESS:
					/* This is an expected case during concurrent vacuum */
					break;
				case HEAPTUPLE_DELETE_IN_PROGRESS:
					/* This is an expected case during concurrent vacuum */
					break;
				default:
409
					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
410 411 412 413 414 415 416 417 418 419 420 421 422
					break;
			}

			if (tupgone)
			{
				lazy_record_dead_tuple(vacrelstats, &(tuple.t_self));
				tups_vacuumed += 1;
			}
			else
			{
				num_tuples += 1;
				hastup = true;
			}
423
		}						/* scan along page */
424 425

		/*
426
		 * If we remembered any tuples for deletion, then the page will be
B
Bruce Momjian 已提交
427 428 429
		 * visited again by lazy_vacuum_heap, which will compute and record
		 * its post-compaction free space.	If not, then we're done with this
		 * page, so remember its free space as-is.
430 431 432 433 434 435 436 437 438 439 440 441 442 443
		 */
		if (vacrelstats->num_dead_tuples == prev_dead_count)
		{
			lazy_record_free_space(vacrelstats, blkno,
								   PageGetFreeSpace(page));
		}

		/* Remember the location of the last page with nonremovable tuples */
		if (hastup)
			vacrelstats->nonempty_pages = blkno + 1;

		LockBuffer(buf, BUFFER_LOCK_UNLOCK);

		if (pgchanged)
444 445 446
			WriteBuffer(buf);
		else
			ReleaseBuffer(buf);
447 448
	}

449 450
	/* save stats for use later */
	vacrelstats->rel_tuples = num_tuples;
451
	vacrelstats->tuples_deleted = tups_vacuumed;
452

453
	/* If any tuples need to be deleted, perform final vacuum cycle */
454
	/* XXX put a threshold on min number of tuples here? */
455 456 457 458
	if (vacrelstats->num_dead_tuples > 0)
	{
		/* Remove index entries */
		for (i = 0; i < nindexes; i++)
459 460 461 462
			lazy_vacuum_index(Irel[i],
							  &index_tups_vacuumed[i],
							  &index_pages_removed[i],
							  vacrelstats);
463 464 465
		/* Remove tuples from heap */
		lazy_vacuum_heap(onerel, vacrelstats);
	}
466
	else if (!did_vacuum_index)
467
	{
468
		/* Must do post-vacuum cleanup and statistics update anyway */
469 470 471
		for (i = 0; i < nindexes; i++)
			lazy_scan_index(Irel[i], vacrelstats);
	}
472

473
	ereport(elevel,
474
			(errmsg("\"%s\": found %.0f removable, %.0f nonremovable row versions in %u pages",
475 476
					RelationGetRelationName(onerel),
					tups_vacuumed, num_tuples, nblocks),
477
			 errdetail("%.0f dead row versions cannot be removed yet.\n"
478 479
					   "There were %.0f unused item pointers.\n"
					   "%u pages are entirely empty.\n"
480
					   "%s.",
481 482 483
					   nkeep,
					   nunused,
					   empty_pages,
484
					   pg_rusage_show(&ru0))));
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
}


/*
 *	lazy_vacuum_heap() -- second pass over the heap
 *
 *		This routine marks dead tuples as unused and compacts out free
 *		space on their pages.  Pages not having dead tuples recorded from
 *		lazy_scan_heap are not visited at all.
 *
 * Note: the reason for doing this as a second pass is we cannot remove
 * the tuples until we've removed their index entries, and we want to
 * process index entry removal in batches as large as possible.
 */
static void
lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats)
{
	int			tupindex;
	int			npages;
504
	PGRUsage	ru0;
505

506
	pg_rusage_init(&ru0);
507 508 509 510 511
	npages = 0;

	tupindex = 0;
	while (tupindex < vacrelstats->num_dead_tuples)
	{
512
		BlockNumber tblk;
513 514 515
		Buffer		buf;
		Page		page;

516
		vacuum_delay_point();
J
Jan Wieck 已提交
517

518 519 520 521 522 523 524 525 526 527 528 529 530
		tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]);
		buf = ReadBuffer(onerel, tblk);
		LockBufferForCleanup(buf);
		tupindex = lazy_vacuum_page(onerel, tblk, buf, tupindex, vacrelstats);
		/* Now that we've compacted the page, record its available space */
		page = BufferGetPage(buf);
		lazy_record_free_space(vacrelstats, tblk,
							   PageGetFreeSpace(page));
		LockBuffer(buf, BUFFER_LOCK_UNLOCK);
		WriteBuffer(buf);
		npages++;
	}

531
	ereport(elevel,
532
			(errmsg("\"%s\": removed %d row versions in %d pages",
533 534
					RelationGetRelationName(onerel),
					tupindex, npages),
535 536
			 errdetail("%s.",
					   pg_rusage_show(&ru0))));
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
}

/*
 *	lazy_vacuum_page() -- free dead tuples on a page
 *					 and repair its fragmentation.
 *
 * Caller is expected to handle reading, locking, and writing the buffer.
 *
 * tupindex is the index in vacrelstats->dead_tuples of the first dead
 * tuple for this page.  We assume the rest follow sequentially.
 * The return value is the first tupindex after the tuples of this page.
 */
static int
lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer,
				 int tupindex, LVRelStats *vacrelstats)
{
553
	OffsetNumber unused[MaxOffsetNumber];
554 555 556 557 558 559 560
	int			uncnt;
	Page		page = BufferGetPage(buffer);
	ItemId		itemid;

	START_CRIT_SECTION();
	for (; tupindex < vacrelstats->num_dead_tuples; tupindex++)
	{
561 562
		BlockNumber tblk;
		OffsetNumber toff;
563 564 565 566 567 568 569 570 571 572 573

		tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]);
		if (tblk != blkno)
			break;				/* past end of tuples for this block */
		toff = ItemPointerGetOffsetNumber(&vacrelstats->dead_tuples[tupindex]);
		itemid = PageGetItemId(page, toff);
		itemid->lp_flags &= ~LP_USED;
	}

	uncnt = PageRepairFragmentation(page, unused);

574 575
	/* XLOG stuff */
	if (!onerel->rd_istemp)
576 577 578
	{
		XLogRecPtr	recptr;

579
		recptr = log_heap_clean(onerel, buffer, unused, uncnt);
580
		PageSetLSN(page, recptr);
581
		PageSetTLI(page, ThisTimeLineID);
582
	}
583 584 585 586 587 588
	else
	{
		/* No XLOG record, but still need to flag that XID exists on disk */
		MyXactMadeTempRelUpdate = true;
	}

589 590 591 592 593
	END_CRIT_SECTION();

	return tupindex;
}

594 595 596 597 598 599 600 601 602
/*
 *	lazy_scan_index() -- scan one index relation to update pg_class statistic.
 *
 * We use this when we have no deletions to do.
 */
static void
lazy_scan_index(Relation indrel, LVRelStats *vacrelstats)
{
	IndexBulkDeleteResult *stats;
603
	IndexVacuumCleanupInfo vcinfo;
604
	PGRUsage	ru0;
605

606
	pg_rusage_init(&ru0);
607 608

	/*
B
Bruce Momjian 已提交
609 610
	 * Acquire appropriate type of lock on index: must be exclusive if index
	 * AM isn't concurrent-safe.
611
	 */
612 613 614
	if (indrel->rd_am->amconcurrent)
		LockRelation(indrel, RowExclusiveLock);
	else
615
		LockRelation(indrel, AccessExclusiveLock);
616 617

	/*
618
	 * Even though we're not planning to delete anything, we use the
B
Bruce Momjian 已提交
619 620 621
	 * ambulkdelete call, because (a) the scan happens within the index AM for
	 * more speed, and (b) it may want to pass private statistics to the
	 * amvacuumcleanup call.
622 623 624
	 */
	stats = index_bulk_delete(indrel, dummy_tid_reaped, NULL);

625 626 627 628 629 630
	/* Do post-VACUUM cleanup, even though we deleted nothing */
	vcinfo.vacuum_full = false;
	vcinfo.message_level = elevel;

	stats = index_vacuum_cleanup(indrel, &vcinfo, stats);

631 632 633
	/*
	 * Release lock acquired above.
	 */
634 635 636
	if (indrel->rd_am->amconcurrent)
		UnlockRelation(indrel, RowExclusiveLock);
	else
637
		UnlockRelation(indrel, AccessExclusiveLock);
638 639 640 641 642

	if (!stats)
		return;

	/* now update statistics in pg_class */
643 644 645 646
	vac_update_relstats(RelationGetRelid(indrel),
						stats->num_pages,
						stats->num_index_tuples,
						false);
647

648
	ereport(elevel,
B
Bruce Momjian 已提交
649 650 651 652 653 654 655 656
			(errmsg("index \"%s\" now contains %.0f row versions in %u pages",
					RelationGetRelationName(indrel),
					stats->num_index_tuples,
					stats->num_pages),
	errdetail("%u index pages have been deleted, %u are currently reusable.\n"
			  "%s.",
			  stats->pages_deleted, stats->pages_free,
			  pg_rusage_show(&ru0))));
657 658 659 660

	pfree(stats);
}

661 662 663 664 665 666
/*
 *	lazy_vacuum_index() -- vacuum one index relation.
 *
 *		Delete all the index entries pointing to tuples listed in
 *		vacrelstats->dead_tuples.
 *
667 668 669
 *		Increment *index_tups_vacuumed by the number of index entries
 *		removed, and *index_pages_removed by the number of pages removed.
 *
670 671 672 673
 *		Finally, we arrange to update the index relation's statistics in
 *		pg_class.
 */
static void
674 675 676 677
lazy_vacuum_index(Relation indrel,
				  double *index_tups_vacuumed,
				  BlockNumber *index_pages_removed,
				  LVRelStats *vacrelstats)
678
{
679
	IndexBulkDeleteResult *stats;
680
	IndexVacuumCleanupInfo vcinfo;
681
	PGRUsage	ru0;
682

683
	pg_rusage_init(&ru0);
684 685

	/*
B
Bruce Momjian 已提交
686 687
	 * Acquire appropriate type of lock on index: must be exclusive if index
	 * AM isn't concurrent-safe.
688
	 */
689 690 691
	if (indrel->rd_am->amconcurrent)
		LockRelation(indrel, RowExclusiveLock);
	else
692 693
		LockRelation(indrel, AccessExclusiveLock);

694 695
	/* Do bulk deletion */
	stats = index_bulk_delete(indrel, lazy_tid_reaped, (void *) vacrelstats);
696

697 698 699 700 701 702
	/* Do post-VACUUM cleanup */
	vcinfo.vacuum_full = false;
	vcinfo.message_level = elevel;

	stats = index_vacuum_cleanup(indrel, &vcinfo, stats);

703 704 705
	/*
	 * Release lock acquired above.
	 */
706 707 708
	if (indrel->rd_am->amconcurrent)
		UnlockRelation(indrel, RowExclusiveLock);
	else
709 710
		UnlockRelation(indrel, AccessExclusiveLock);

711 712 713
	if (!stats)
		return;

714 715 716 717
	/* accumulate total removed over multiple index-cleaning cycles */
	*index_tups_vacuumed += stats->tuples_removed;
	*index_pages_removed += stats->pages_removed;

718
	/* now update statistics in pg_class */
719 720 721 722
	vac_update_relstats(RelationGetRelid(indrel),
						stats->num_pages,
						stats->num_index_tuples,
						false);
723

724
	ereport(elevel,
B
Bruce Momjian 已提交
725 726 727 728 729 730 731 732 733 734
			(errmsg("index \"%s\" now contains %.0f row versions in %u pages",
					RelationGetRelationName(indrel),
					stats->num_index_tuples,
					stats->num_pages),
			 errdetail("%.0f index row versions were removed.\n"
			 "%u index pages have been deleted, %u are currently reusable.\n"
					   "%s.",
					   stats->tuples_removed,
					   stats->pages_deleted, stats->pages_free,
					   pg_rusage_show(&ru0))));
735

736
	pfree(stats);
737 738 739 740 741 742 743 744
}

/*
 * lazy_truncate_heap - try to truncate off any empty pages at the end
 */
static void
lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
{
745 746
	BlockNumber old_rel_pages = vacrelstats->rel_pages;
	BlockNumber new_rel_pages;
747
	PageFreeSpaceInfo *pageSpaces;
748 749 750
	int			n;
	int			i,
				j;
751
	PGRUsage	ru0;
752

753
	pg_rusage_init(&ru0);
754 755

	/*
B
Bruce Momjian 已提交
756 757 758 759
	 * We need full exclusive lock on the relation in order to do truncation.
	 * If we can't get it, give up rather than waiting --- we don't want to
	 * block other backends, and we don't want to deadlock (which is quite
	 * possible considering we already hold a lower-grade lock).
760
	 */
761
	if (!ConditionalLockRelation(onerel, AccessExclusiveLock))
762 763 764 765
		return;

	/*
	 * Now that we have exclusive lock, look to see if the rel has grown
B
Bruce Momjian 已提交
766 767
	 * whilst we were vacuuming with non-exclusive lock.  If so, give up; the
	 * newly added pages presumably contain non-deletable tuples.
768 769 770 771 772 773 774 775 776 777 778 779
	 */
	new_rel_pages = RelationGetNumberOfBlocks(onerel);
	if (new_rel_pages != old_rel_pages)
	{
		/* might as well use the latest news when we update pg_class stats */
		vacrelstats->rel_pages = new_rel_pages;
		UnlockRelation(onerel, AccessExclusiveLock);
		return;
	}

	/*
	 * Scan backwards from the end to verify that the end pages actually
B
Bruce Momjian 已提交
780 781 782
	 * contain nothing we need to keep.  This is *necessary*, not optional,
	 * because other backends could have added tuples to these pages whilst we
	 * were vacuuming.
783 784 785 786 787 788 789 790 791 792 793 794 795
	 */
	new_rel_pages = count_nondeletable_pages(onerel, vacrelstats);

	if (new_rel_pages >= old_rel_pages)
	{
		/* can't do anything after all */
		UnlockRelation(onerel, AccessExclusiveLock);
		return;
	}

	/*
	 * Okay to truncate.
	 */
796
	RelationTruncate(onerel, new_rel_pages);
797 798 799 800 801

	/*
	 * Drop free-space info for removed blocks; these must not get entered
	 * into the FSM!
	 */
802
	pageSpaces = vacrelstats->free_pages;
803 804 805 806
	n = vacrelstats->num_free_pages;
	j = 0;
	for (i = 0; i < n; i++)
	{
807
		if (pageSpaces[i].blkno < new_rel_pages)
808
		{
809
			pageSpaces[j] = pageSpaces[i];
810 811 812 813
			j++;
		}
	}
	vacrelstats->num_free_pages = j;
814 815
	/* We destroyed the heap ordering, so mark array unordered */
	vacrelstats->fs_is_heap = false;
816

817 818 819 820
	/* update statistics */
	vacrelstats->rel_pages = new_rel_pages;
	vacrelstats->pages_removed = old_rel_pages - new_rel_pages;

821 822 823 824
	/*
	 * We keep the exclusive lock until commit (perhaps not necessary)?
	 */

825 826 827 828
	ereport(elevel,
			(errmsg("\"%s\": truncated %u to %u pages",
					RelationGetRelationName(onerel),
					old_rel_pages, new_rel_pages),
829 830
			 errdetail("%s.",
					   pg_rusage_show(&ru0))));
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
}

/*
 * Rescan end pages to verify that they are (still) empty of needed tuples.
 *
 * Returns number of nondeletable pages (last nonempty page + 1).
 */
static BlockNumber
count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats)
{
	BlockNumber blkno;
	HeapTupleData tuple;

	/* Strange coding of loop control is needed because blkno is unsigned */
	blkno = vacrelstats->rel_pages;
	while (blkno > vacrelstats->nonempty_pages)
	{
		Buffer		buf;
		Page		page;
		OffsetNumber offnum,
					maxoff;
852
		bool		tupgone,
853 854
					hastup;

855
		vacuum_delay_point();
J
Jan Wieck 已提交
856

857 858 859 860 861 862 863 864 865 866 867
		blkno--;

		buf = ReadBuffer(onerel, blkno);

		/* In this phase we only need shared access to the buffer */
		LockBuffer(buf, BUFFER_LOCK_SHARE);

		page = BufferGetPage(buf);

		if (PageIsNew(page) || PageIsEmpty(page))
		{
868
			/* PageIsNew probably shouldn't happen... */
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
			ReleaseBuffer(buf);
			continue;
		}

		hastup = false;
		maxoff = PageGetMaxOffsetNumber(page);
		for (offnum = FirstOffsetNumber;
			 offnum <= maxoff;
			 offnum = OffsetNumberNext(offnum))
		{
			ItemId		itemid;

			itemid = PageGetItemId(page, offnum);

			if (!ItemIdIsUsed(itemid))
				continue;

			tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
			tuple.t_len = ItemIdGetLength(itemid);
			ItemPointerSet(&(tuple.t_self), blkno, offnum);

			tupgone = false;

893
			switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin, buf))
894 895
			{
				case HEAPTUPLE_DEAD:
896
					tupgone = true;		/* we can delete the tuple */
897 898
					break;
				case HEAPTUPLE_LIVE:
899
					/* Shouldn't be necessary to re-freeze anything */
900 901
					break;
				case HEAPTUPLE_RECENTLY_DEAD:
902

903
					/*
B
Bruce Momjian 已提交
904 905
					 * If tuple is recently deleted then we must not remove it
					 * from relation.
906 907 908 909 910 911 912 913 914
					 */
					break;
				case HEAPTUPLE_INSERT_IN_PROGRESS:
					/* This is an expected case during concurrent vacuum */
					break;
				case HEAPTUPLE_DELETE_IN_PROGRESS:
					/* This is an expected case during concurrent vacuum */
					break;
				default:
915
					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
916 917 918 919 920 921 922 923
					break;
			}

			if (!tupgone)
			{
				hastup = true;
				break;			/* can stop scanning */
			}
924
		}						/* scan along page */
925 926 927

		LockBuffer(buf, BUFFER_LOCK_UNLOCK);

928
		ReleaseBuffer(buf);
929 930 931 932 933 934 935 936

		/* Done scanning if we found a tuple here */
		if (hastup)
			return blkno + 1;
	}

	/*
	 * If we fall out of the loop, all the previously-thought-to-be-empty
B
Bruce Momjian 已提交
937 938
	 * pages really are; we need not bother to look at the last known-nonempty
	 * page.
939 940 941 942 943 944 945 946 947 948 949 950
	 */
	return vacrelstats->nonempty_pages;
}

/*
 * lazy_space_alloc - space allocation decisions for lazy vacuum
 *
 * See the comments at the head of this file for rationale.
 */
static void
lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks)
{
951
	long		maxtuples;
952 953
	int			maxpages;

954 955
	maxtuples = (maintenance_work_mem * 1024L) / sizeof(ItemPointerData);
	maxtuples = Min(maxtuples, INT_MAX);
956
	/* stay sane if small maintenance_work_mem */
957
	maxtuples = Max(maxtuples, MaxHeapTuplesPerPage);
958 959

	vacrelstats->num_dead_tuples = 0;
960
	vacrelstats->max_dead_tuples = (int) maxtuples;
961 962 963 964 965 966 967 968 969 970 971
	vacrelstats->dead_tuples = (ItemPointer)
		palloc(maxtuples * sizeof(ItemPointerData));

	maxpages = MaxFSMPages;
	/* No need to allocate more pages than the relation has blocks */
	if (relblocks < (BlockNumber) maxpages)
		maxpages = (int) relblocks;

	vacrelstats->fs_is_heap = false;
	vacrelstats->num_free_pages = 0;
	vacrelstats->max_free_pages = maxpages;
972 973
	vacrelstats->free_pages = (PageFreeSpaceInfo *)
		palloc(maxpages * sizeof(PageFreeSpaceInfo));
974 975 976 977 978 979 980 981 982 983
}

/*
 * lazy_record_dead_tuple - remember one deletable tuple
 */
static void
lazy_record_dead_tuple(LVRelStats *vacrelstats,
					   ItemPointer itemptr)
{
	/*
984
	 * The array shouldn't overflow under normal behavior, but perhaps it
985 986
	 * could if we are given a really small maintenance_work_mem. In that
	 * case, just forget the last few tuples.
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
	 */
	if (vacrelstats->num_dead_tuples < vacrelstats->max_dead_tuples)
	{
		vacrelstats->dead_tuples[vacrelstats->num_dead_tuples] = *itemptr;
		vacrelstats->num_dead_tuples++;
	}
}

/*
 * lazy_record_free_space - remember free space on one page
 */
static void
lazy_record_free_space(LVRelStats *vacrelstats,
					   BlockNumber page,
					   Size avail)
{
1003
	PageFreeSpaceInfo *pageSpaces;
1004 1005
	int			n;

1006 1007 1008
	/*
	 * A page with less than stats->threshold free space will be forgotten
	 * immediately, and never passed to the free space map.  Removing the
B
Bruce Momjian 已提交
1009 1010 1011 1012
	 * uselessly small entries early saves cycles, and in particular reduces
	 * the amount of time we spend holding the FSM lock when we finally call
	 * RecordRelationFreeSpace.  Since the FSM will probably drop pages with
	 * little free space anyway, there's no point in making this really small.
1013
	 *
B
Bruce Momjian 已提交
1014 1015 1016 1017 1018
	 * XXX Is it worth trying to measure average tuple size, and using that to
	 * adjust the threshold?  Would be worthwhile if FSM has no stats yet for
	 * this relation.  But changing the threshold as we scan the rel might
	 * lead to bizarre behavior, too.  Also, it's probably better if vacuum.c
	 * has the same thresholding behavior as we do here.
1019 1020
	 */
	if (avail < vacrelstats->threshold)
1021 1022 1023
		return;

	/* Copy pointers to local variables for notational simplicity */
1024
	pageSpaces = vacrelstats->free_pages;
1025 1026 1027 1028 1029
	n = vacrelstats->max_free_pages;

	/* If we haven't filled the array yet, just keep adding entries */
	if (vacrelstats->num_free_pages < n)
	{
1030 1031
		pageSpaces[vacrelstats->num_free_pages].blkno = page;
		pageSpaces[vacrelstats->num_free_pages].avail = avail;
1032 1033 1034 1035 1036 1037 1038
		vacrelstats->num_free_pages++;
		return;
	}

	/*----------
	 * The rest of this routine works with "heap" organization of the
	 * free space arrays, wherein we maintain the heap property
B
Bruce Momjian 已提交
1039
	 *			avail[(j-1) div 2] <= avail[j]	for 0 < j < n.
1040 1041 1042 1043 1044 1045 1046 1047
	 * In particular, the zero'th element always has the smallest available
	 * space and can be discarded to make room for a new page with more space.
	 * See Knuth's discussion of heap-based priority queues, sec 5.2.3;
	 * but note he uses 1-origin array subscripts, not 0-origin.
	 *----------
	 */

	/* If we haven't yet converted the array to heap organization, do it */
1048
	if (!vacrelstats->fs_is_heap)
1049 1050 1051
	{
		/*
		 * Scan backwards through the array, "sift-up" each value into its
B
Bruce Momjian 已提交
1052 1053
		 * correct position.  We can start the scan at n/2-1 since each entry
		 * above that position has no children to worry about.
1054
		 */
1055
		int			l = n / 2;
1056 1057 1058

		while (--l >= 0)
		{
1059 1060
			BlockNumber R = pageSpaces[l].blkno;
			Size		K = pageSpaces[l].avail;
1061 1062 1063 1064 1065
			int			i;		/* i is where the "hole" is */

			i = l;
			for (;;)
			{
1066
				int			j = 2 * i + 1;
1067 1068 1069

				if (j >= n)
					break;
1070
				if (j + 1 < n && pageSpaces[j].avail > pageSpaces[j + 1].avail)
1071
					j++;
1072
				if (K <= pageSpaces[j].avail)
1073
					break;
1074
				pageSpaces[i] = pageSpaces[j];
1075 1076
				i = j;
			}
1077 1078
			pageSpaces[i].blkno = R;
			pageSpaces[i].avail = K;
1079 1080 1081 1082 1083 1084
		}

		vacrelstats->fs_is_heap = true;
	}

	/* If new page has more than zero'th entry, insert it into heap */
1085
	if (avail > pageSpaces[0].avail)
1086 1087
	{
		/*
1088
		 * Notionally, we replace the zero'th entry with the new data, and
B
Bruce Momjian 已提交
1089 1090 1091
		 * then sift-up to maintain the heap property.	Physically, the new
		 * data doesn't get stored into the arrays until we find the right
		 * location for it.
1092
		 */
1093
		int			i = 0;		/* i is where the "hole" is */
1094 1095 1096

		for (;;)
		{
1097
			int			j = 2 * i + 1;
1098 1099 1100

			if (j >= n)
				break;
1101
			if (j + 1 < n && pageSpaces[j].avail > pageSpaces[j + 1].avail)
1102
				j++;
1103
			if (avail <= pageSpaces[j].avail)
1104
				break;
1105
			pageSpaces[i] = pageSpaces[j];
1106 1107
			i = j;
		}
1108 1109
		pageSpaces[i].blkno = page;
		pageSpaces[i].avail = avail;
1110 1111 1112 1113 1114 1115
	}
}

/*
 *	lazy_tid_reaped() -- is a particular tid deletable?
 *
1116 1117
 *		This has the right signature to be an IndexBulkDeleteCallback.
 *
1118 1119 1120
 *		Assumes dead_tuples array is in sorted order.
 */
static bool
1121
lazy_tid_reaped(ItemPointer itemptr, void *state)
1122
{
1123
	LVRelStats *vacrelstats = (LVRelStats *) state;
1124
	ItemPointer res;
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

	res = (ItemPointer) bsearch((void *) itemptr,
								(void *) vacrelstats->dead_tuples,
								vacrelstats->num_dead_tuples,
								sizeof(ItemPointerData),
								vac_cmp_itemptr);

	return (res != NULL);
}

1135 1136 1137 1138 1139 1140 1141 1142 1143
/*
 * Dummy version for lazy_scan_index.
 */
static bool
dummy_tid_reaped(ItemPointer itemptr, void *state)
{
	return false;
}

1144 1145 1146 1147 1148 1149 1150
/*
 * Update the shared Free Space Map with the info we now have about
 * free space in the relation, discarding any old info the map may have.
 */
static void
lazy_update_fsm(Relation onerel, LVRelStats *vacrelstats)
{
1151 1152 1153
	PageFreeSpaceInfo *pageSpaces = vacrelstats->free_pages;
	int			nPages = vacrelstats->num_free_pages;

1154
	/*
1155
	 * Sort data into order, as required by RecordRelationFreeSpace.
1156
	 */
1157 1158 1159 1160
	if (nPages > 1)
		qsort(pageSpaces, nPages, sizeof(PageFreeSpaceInfo),
			  vac_cmp_page_spaces);

1161
	RecordRelationFreeSpace(&onerel->rd_node, nPages, pageSpaces);
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
}

/*
 * Comparator routines for use with qsort() and bsearch().
 */
static int
vac_cmp_itemptr(const void *left, const void *right)
{
	BlockNumber lblk,
				rblk;
	OffsetNumber loff,
				roff;

	lblk = ItemPointerGetBlockNumber((ItemPointer) left);
	rblk = ItemPointerGetBlockNumber((ItemPointer) right);

	if (lblk < rblk)
		return -1;
	if (lblk > rblk)
		return 1;

	loff = ItemPointerGetOffsetNumber((ItemPointer) left);
	roff = ItemPointerGetOffsetNumber((ItemPointer) right);

	if (loff < roff)
		return -1;
	if (loff > roff)
		return 1;

	return 0;
}
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205

static int
vac_cmp_page_spaces(const void *left, const void *right)
{
	PageFreeSpaceInfo *linfo = (PageFreeSpaceInfo *) left;
	PageFreeSpaceInfo *rinfo = (PageFreeSpaceInfo *) right;

	if (linfo->blkno < rinfo->blkno)
		return -1;
	else if (linfo->blkno > rinfo->blkno)
		return 1;
	return 0;
}