vacuumlazy.c 30.7 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
 * We are willing to use at most VacuumMem memory space to keep track of
14 15 16 17 18 19 20
 * 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.
 *
 * 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.
 *
 *
B
Bruce Momjian 已提交
29
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
30 31 32 33
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
34
 *	  $Header: /cvsroot/pgsql/src/backend/commands/vacuumlazy.c,v 1.19 2002/09/04 20:31:17 momjian Exp $
35 36 37 38 39 40 41 42 43 44 45 46 47
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include "access/genam.h"
#include "access/heapam.h"
#include "access/xlog.h"
#include "commands/vacuum.h"
#include "miscadmin.h"
#include "storage/freespace.h"
#include "storage/sinval.h"
#include "storage/smgr.h"
48
#include "utils/lsyscache.h"
49 50 51 52 53 54


/*
 * Space/time tradeoff parameters: do these need to be user-tunable?
 *
 * A page with less than PAGE_SPACE_THRESHOLD free space will be forgotten
55
 * immediately, and not even passed to the free space map.	Removing the
56
 * uselessly small entries early saves cycles, and in particular reduces
57
 * the amount of time we spend holding the FSM lock when we finally call
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
 * MultiRecordFreeSpace.  Since the FSM will ignore pages below its own
 * runtime threshold anyway, there's no point in making this really small.
 * XXX Is it worth trying to measure average tuple size, and using that to
 * set the threshold?  Problem is we don't know average tuple size very
 * accurately for the first few pages...
 *
 * To consider truncating the relation, we want there to be at least
 * relsize / REL_TRUNCATE_FRACTION potentially-freeable pages.
 */
#define PAGE_SPACE_THRESHOLD	((Size) (BLCKSZ / 32))

#define REL_TRUNCATE_FRACTION	16

/* MAX_TUPLES_PER_PAGE can be a conservative upper limit */
#define MAX_TUPLES_PER_PAGE		((int) (BLCKSZ / sizeof(HeapTupleHeaderData)))


typedef struct LVRelStats
{
	/* Overall statistics about rel */
78
	BlockNumber rel_pages;
79
	double		rel_tuples;
80
	BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
81 82
	/* List of TIDs of tuples we intend to delete */
	/* NB: this list is ordered by TID address */
83 84
	int			num_dead_tuples;	/* current # of entries */
	int			max_dead_tuples;	/* # slots allocated in array */
85
	ItemPointer dead_tuples;	/* array of ItemPointerData */
86 87
	/* Array or heap of per-page info about free space */
	/* We use a simple array until it fills up, then convert to heap */
88 89 90 91
	bool		fs_is_heap;		/* are we using heap organization? */
	int			num_free_pages; /* current # of entries */
	int			max_free_pages; /* # slots allocated in arrays */
	BlockNumber *free_pages;	/* array or heap of block numbers */
92
	Size	   *free_spaceavail;	/* array or heap of available space */
93 94 95
} LVRelStats;


B
Bruce Momjian 已提交
96
static int	elevel = -1;
97

98 99
static TransactionId OldestXmin;
static TransactionId FreezeLimit;
100 101 102 103


/* non-export function prototypes */
static void lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
104
			   Relation *Irel, int nindexes);
105
static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats);
106
static void lazy_scan_index(Relation indrel, LVRelStats *vacrelstats);
107
static void lazy_vacuum_index(Relation indrel, LVRelStats *vacrelstats);
108 109
static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer,
				 int tupindex, LVRelStats *vacrelstats);
110 111
static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats);
static BlockNumber count_nondeletable_pages(Relation onerel,
112
						 LVRelStats *vacrelstats);
113 114
static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks);
static void lazy_record_dead_tuple(LVRelStats *vacrelstats,
115
					   ItemPointer itemptr);
116
static void lazy_record_free_space(LVRelStats *vacrelstats,
117
					   BlockNumber page, Size avail);
118
static bool lazy_tid_reaped(ItemPointer itemptr, void *state);
119
static bool dummy_tid_reaped(ItemPointer itemptr, void *state);
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
static void lazy_update_fsm(Relation onerel, LVRelStats *vacrelstats);
static int	vac_cmp_itemptr(const void *left, const void *right);


/*
 *	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;
140
	BlockNumber possibly_freeable;
141 142

	if (vacstmt->verbose)
143
		elevel = INFO;
144
	else
145
		elevel = DEBUG1;
B
Bruce Momjian 已提交
146

147 148
	vacuum_set_xid_limits(vacstmt, onerel->rd_rel->relisshared,
						  &OldestXmin, &FreezeLimit);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

	vacrelstats = (LVRelStats *) palloc(sizeof(LVRelStats));
	MemSet(vacrelstats, 0, sizeof(LVRelStats));

	/* Open all indexes of the relation */
	vac_open_indexes(onerel, &nindexes, &Irel);
	hasindex = (nindexes > 0);

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

	/* Done with indexes */
	vac_close_indexes(nindexes, Irel);

	/*
	 * Optionally truncate the relation.
	 *
166 167
	 * 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.
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
	 */
	possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages;
	if (possibly_freeable > vacrelstats->rel_pages / REL_TRUNCATE_FRACTION)
		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 */
	vac_update_relstats(RelationGetRelid(onerel), vacrelstats->rel_pages,
						vacrelstats->rel_tuples, hasindex);
}


/*
 *	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;
198
	BlockNumber empty_pages,
199 200 201 202 203
				changed_pages;
	double		num_tuples,
				tups_vacuumed,
				nkeep,
				nunused;
204
	bool		did_vacuum_index = false;
205 206 207 208 209 210
	int			i;
	VacRUsage	ru0;

	vac_init_rusage(&ru0);

	relname = RelationGetRelationName(onerel);
211 212 213
	elog(elevel, "--Relation %s.%s--",
		 get_namespace_name(RelationGetNamespace(onerel)),
		 relname);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

	empty_pages = changed_pages = 0;
	num_tuples = tups_vacuumed = nkeep = nunused = 0;

	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;

235 236
		CHECK_FOR_INTERRUPTS();

237
		/*
238 239 240
		 * 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.
241 242 243 244 245 246 247
		 */
		if ((vacrelstats->max_dead_tuples - vacrelstats->num_dead_tuples) < MAX_TUPLES_PER_PAGE &&
			vacrelstats->num_dead_tuples > 0)
		{
			/* Remove index entries */
			for (i = 0; i < nindexes; i++)
				lazy_vacuum_index(Irel[i], vacrelstats);
248
			did_vacuum_index = true;
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
			/* 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))
		{
			/* Not sure we still need to handle this case, but... */
			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
			LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
			if (PageIsNew(page))
			{
B
Bruce Momjian 已提交
269
				elog(WARNING, "Rel %s: Uninitialized page %u - fixing",
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
					 relname, blkno);
				PageInit(page, BufferGetPageSize(buf), 0);
				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;
			uint16		sv_infomask;

			itemid = PageGetItemId(page, offnum);

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

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

			tupgone = false;
			sv_infomask = tuple.t_data->t_infomask;

317
			switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin))
318 319
			{
				case HEAPTUPLE_DEAD:
320
					tupgone = true;		/* we can delete the tuple */
321 322
					break;
				case HEAPTUPLE_LIVE:
323

324
					/*
325 326
					 * Tuple is good.  Consider whether to replace its
					 * xmin value with FrozenTransactionId.
T
Tom Lane 已提交
327
					 *
328 329 330 331
					 * 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
T
Tom Lane 已提交
332 333
					 * assumption by momentarily acquiring exclusive lock,
					 * but for the moment I see no need to.
334
					 */
335 336
					if (TransactionIdIsNormal(HeapTupleHeaderGetXmin(tuple.t_data)) &&
						TransactionIdPrecedes(HeapTupleHeaderGetXmin(tuple.t_data),
337 338
											  FreezeLimit))
					{
339
						HeapTupleHeaderSetXmin(tuple.t_data, FrozenTransactionId);
T
Tom Lane 已提交
340 341
						/* infomask should be okay already */
						Assert(tuple.t_data->t_infomask & HEAP_XMIN_COMMITTED);
342 343
						pgchanged = true;
					}
344 345
					break;
				case HEAPTUPLE_RECENTLY_DEAD:
346

347
					/*
348 349
					 * If tuple is recently deleted then we must not
					 * remove it from relation.
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
					 */
					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:
					elog(ERROR, "Unexpected HeapTupleSatisfiesVacuum result");
					break;
			}

			/* check for hint-bit update by HeapTupleSatisfiesVacuum */
			if (sv_infomask != tuple.t_data->t_infomask)
				pgchanged = true;

			/*
			 * Other checks...
			 */
371 372
			if (onerel->rd_rel->relhasoids &&
				!OidIsValid(HeapTupleGetOid(&tuple)))
B
Bruce Momjian 已提交
373
				elog(WARNING, "Rel %s: TID %u/%u: OID IS INVALID. TUPGONE %d.",
374 375 376 377 378 379 380 381 382 383 384 385
					 relname, blkno, offnum, (int) tupgone);

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

		/*
389 390
		 * If we remembered any tuples for deletion, then the page will be
		 * visited again by lazy_vacuum_heap, which will compute and
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
		 * record its post-compaction free space.  If not, then we're done
		 * with this page, so remember its free space as-is.
		 */
		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)
		{
408
			SetBufferCommitInfoNeedsSave(buf);
409 410
			changed_pages++;
		}
411 412

		ReleaseBuffer(buf);
413 414
	}

415 416 417
	/* save stats for use later */
	vacrelstats->rel_tuples = num_tuples;

418 419 420 421 422 423 424 425 426 427
	/* If any tuples need to be deleted, perform final vacuum cycle */
	/* XXX put a threshold on min nuber of tuples here? */
	if (vacrelstats->num_dead_tuples > 0)
	{
		/* Remove index entries */
		for (i = 0; i < nindexes; i++)
			lazy_vacuum_index(Irel[i], vacrelstats);
		/* Remove tuples from heap */
		lazy_vacuum_heap(onerel, vacrelstats);
	}
428
	else if (!did_vacuum_index)
429 430 431 432 433
	{
		/* Scan indexes just to update pg_class statistics about them */
		for (i = 0; i < nindexes; i++)
			lazy_scan_index(Irel[i], vacrelstats);
	}
434

435
	elog(elevel, "Pages %u: Changed %u, Empty %u; \
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
Tup %.0f: Vac %.0f, Keep %.0f, UnUsed %.0f.\n\tTotal %s",
		 nblocks, changed_pages, empty_pages,
		 num_tuples, tups_vacuumed, nkeep, nunused,
		 vac_show_rusage(&ru0));
}


/*
 *	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;
	VacRUsage	ru0;

	vac_init_rusage(&ru0);
	npages = 0;

	tupindex = 0;
	while (tupindex < vacrelstats->num_dead_tuples)
	{
467
		BlockNumber tblk;
468 469 470
		Buffer		buf;
		Page		page;

471 472
		CHECK_FOR_INTERRUPTS();

473 474 475 476 477 478 479 480 481 482 483 484 485
		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++;
	}

486
	elog(elevel, "Removed %d tuples in %d pages.\n\t%s", tupindex, npages,
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
		 vac_show_rusage(&ru0));
}

/*
 *	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)
{
504
	OffsetNumber unbuf[BLCKSZ / sizeof(OffsetNumber)];
505 506 507 508 509 510 511 512
	OffsetNumber *unused = unbuf;
	int			uncnt;
	Page		page = BufferGetPage(buffer);
	ItemId		itemid;

	START_CRIT_SECTION();
	for (; tupindex < vacrelstats->num_dead_tuples; tupindex++)
	{
513 514
		BlockNumber tblk;
		OffsetNumber toff;
515 516 517 518 519 520 521 522 523 524 525

		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);

526 527
	/* XLOG stuff */
	if (!onerel->rd_istemp)
528 529 530 531 532 533 534 535
	{
		XLogRecPtr	recptr;

		recptr = log_heap_clean(onerel, buffer, (char *) unused,
						  (char *) (&(unused[uncnt])) - (char *) unused);
		PageSetLSN(page, recptr);
		PageSetSUI(page, ThisStartUpID);
	}
536 537 538 539 540 541
	else
	{
		/* No XLOG record, but still need to flag that XID exists on disk */
		MyXactMadeTempRelUpdate = true;
	}

542 543 544 545 546
	END_CRIT_SECTION();

	return tupindex;
}

547 548 549 550 551 552 553 554 555 556 557 558 559 560
/*
 *	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;
	VacRUsage	ru0;

	vac_init_rusage(&ru0);

	/*
561 562
	 * If the index is not partial, skip the scan, and just assume it has
	 * the same number of tuples as the heap.
563
	 */
564
	if (!vac_is_partial_index(indrel))
565 566 567 568 569 570 571 572 573
	{
		vac_update_relstats(RelationGetRelid(indrel),
							RelationGetNumberOfBlocks(indrel),
							vacrelstats->rel_tuples,
							false);
		return;
	}

	/*
574 575
	 * If index is unsafe for concurrent access, must lock it; but a
	 * shared lock should be sufficient.
576
	 */
577
	if (!indrel->rd_am->amconcurrent)
578 579 580 581
		LockRelation(indrel, AccessShareLock);

	/*
	 * Even though we're not planning to delete anything, use the
582 583
	 * ambulkdelete call, so that the scan happens within the index AM for
	 * more speed.
584 585 586 587 588 589
	 */
	stats = index_bulk_delete(indrel, dummy_tid_reaped, NULL);

	/*
	 * Release lock acquired above.
	 */
590
	if (!indrel->rd_am->amconcurrent)
591 592 593 594 595 596 597 598 599 600
		UnlockRelation(indrel, AccessShareLock);

	if (!stats)
		return;

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

601
	elog(elevel, "Index %s: Pages %u; Tuples %.0f.\n\t%s",
602 603 604 605 606 607 608
		 RelationGetRelationName(indrel),
		 stats->num_pages, stats->num_index_tuples,
		 vac_show_rusage(&ru0));

	pfree(stats);
}

609 610 611 612 613 614 615 616 617 618 619 620
/*
 *	lazy_vacuum_index() -- vacuum one index relation.
 *
 *		Delete all the index entries pointing to tuples listed in
 *		vacrelstats->dead_tuples.
 *
 *		Finally, we arrange to update the index relation's statistics in
 *		pg_class.
 */
static void
lazy_vacuum_index(Relation indrel, LVRelStats *vacrelstats)
{
621
	IndexBulkDeleteResult *stats;
622 623 624 625 626
	VacRUsage	ru0;

	vac_init_rusage(&ru0);

	/*
627
	 * If index is unsafe for concurrent access, must lock it.
628
	 */
629
	if (!indrel->rd_am->amconcurrent)
630 631
		LockRelation(indrel, AccessExclusiveLock);

632 633
	/* Do bulk deletion */
	stats = index_bulk_delete(indrel, lazy_tid_reaped, (void *) vacrelstats);
634 635 636 637

	/*
	 * Release lock acquired above.
	 */
638
	if (!indrel->rd_am->amconcurrent)
639 640
		UnlockRelation(indrel, AccessExclusiveLock);

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

648
		elog(elevel, "Index %s: Pages %u; Tuples %.0f: Deleted %.0f.\n\t%s",
649 650 651 652 653 654
			 RelationGetRelationName(indrel), stats->num_pages,
			 stats->num_index_tuples, stats->tuples_removed,
			 vac_show_rusage(&ru0));

		pfree(stats);
	}
655 656 657 658 659 660 661 662
}

/*
 * lazy_truncate_heap - try to truncate off any empty pages at the end
 */
static void
lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
{
663 664
	BlockNumber old_rel_pages = vacrelstats->rel_pages;
	BlockNumber new_rel_pages;
665 666 667 668 669 670 671 672 673 674
	BlockNumber *pages;
	Size	   *spaceavail;
	int			n;
	int			i,
				j;
	VacRUsage	ru0;

	vac_init_rusage(&ru0);

	/*
675 676 677 678 679
	 * 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).
680
	 */
681
	if (!ConditionalLockRelation(onerel, AccessExclusiveLock))
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
		return;

	/*
	 * Now that we have exclusive lock, look to see if the rel has grown
	 * whilst we were vacuuming with non-exclusive lock.  If so, give up;
	 * the newly added pages presumably contain non-deletable tuples.
	 */
	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
700 701 702
	 * 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.
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
	 */
	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.
	 *
	 * First, flush any shared buffers for the blocks we intend to delete.
	 * FlushRelationBuffers is a bit more than we need for this, since it
	 * will also write out dirty buffers for blocks we aren't deleting,
	 * but it's the closest thing in bufmgr's API.
	 */
	i = FlushRelationBuffers(onerel, new_rel_pages);
	if (i < 0)
		elog(ERROR, "VACUUM (lazy_truncate_heap): FlushRelationBuffers returned %d",
			 i);

	/*
	 * Do the physical truncation.
	 */
	new_rel_pages = smgrtruncate(DEFAULT_SMGR, onerel, new_rel_pages);
730
	onerel->rd_nblocks = new_rel_pages; /* update relcache immediately */
731
	onerel->rd_targblock = InvalidBlockNumber;
732 733
	vacrelstats->rel_pages = new_rel_pages;		/* save new number of
												 * blocks */
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

	/*
	 * Drop free-space info for removed blocks; these must not get entered
	 * into the FSM!
	 */
	pages = vacrelstats->free_pages;
	spaceavail = vacrelstats->free_spaceavail;
	n = vacrelstats->num_free_pages;
	j = 0;
	for (i = 0; i < n; i++)
	{
		if (pages[i] < new_rel_pages)
		{
			pages[j] = pages[i];
			spaceavail[j] = spaceavail[i];
			j++;
		}
	}
	vacrelstats->num_free_pages = j;

	/*
	 * We keep the exclusive lock until commit (perhaps not necessary)?
	 */

758
	elog(elevel, "Truncated %u --> %u pages.\n\t%s", old_rel_pages,
B
Bruce Momjian 已提交
759
		 new_rel_pages, vac_show_rusage(&ru0));
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
}

/*
 * 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;
		bool		pgchanged,
					tupgone,
					hastup;

785 786
		CHECK_FOR_INTERRUPTS();

787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
		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))
		{
			/* PageIsNew robably shouldn't happen... */
			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
			ReleaseBuffer(buf);
			continue;
		}

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

			itemid = PageGetItemId(page, offnum);

			if (!ItemIdIsUsed(itemid))
				continue;

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

			tupgone = false;
			sv_infomask = tuple.t_data->t_infomask;

827
			switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin))
828 829
			{
				case HEAPTUPLE_DEAD:
830
					tupgone = true;		/* we can delete the tuple */
831 832
					break;
				case HEAPTUPLE_LIVE:
833
					/* Shouldn't be necessary to re-freeze anything */
834 835
					break;
				case HEAPTUPLE_RECENTLY_DEAD:
836

837
					/*
838 839
					 * If tuple is recently deleted then we must not
					 * remove it from relation.
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
					 */
					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:
					elog(ERROR, "Unexpected HeapTupleSatisfiesVacuum result");
					break;
			}

			/* check for hint-bit update by HeapTupleSatisfiesVacuum */
			if (sv_infomask != tuple.t_data->t_infomask)
				pgchanged = true;

			if (!tupgone)
			{
				hastup = true;
				break;			/* can stop scanning */
			}
862
		}						/* scan along page */
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

		LockBuffer(buf, BUFFER_LOCK_UNLOCK);

		if (pgchanged)
			WriteBuffer(buf);
		else
			ReleaseBuffer(buf);

		/* 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
878 879
	 * pages really are; we need not bother to look at the last
	 * known-nonempty page.
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
	 */
	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)
{
	int			maxtuples;
	int			maxpages;

895 896
	maxtuples = (int) ((VacuumMem * 1024L) / sizeof(ItemPointerData));
	/* stay sane if small VacuumMem */
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
	if (maxtuples < MAX_TUPLES_PER_PAGE)
		maxtuples = MAX_TUPLES_PER_PAGE;

	vacrelstats->num_dead_tuples = 0;
	vacrelstats->max_dead_tuples = maxtuples;
	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;
	/* avoid palloc(0) */
	if (maxpages < 1)
		maxpages = 1;

	vacrelstats->fs_is_heap = false;
	vacrelstats->num_free_pages = 0;
	vacrelstats->max_free_pages = maxpages;
	vacrelstats->free_pages = (BlockNumber *)
		palloc(maxpages * sizeof(BlockNumber));
	vacrelstats->free_spaceavail = (Size *)
		palloc(maxpages * sizeof(Size));
}

/*
 * lazy_record_dead_tuple - remember one deletable tuple
 */
static void
lazy_record_dead_tuple(LVRelStats *vacrelstats,
					   ItemPointer itemptr)
{
	/*
930 931 932
	 * The array shouldn't overflow under normal behavior, but perhaps it
	 * could if we are given a really small VacuumMem. In that case, just
	 * forget the last few tuples.
933 934 935 936 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
	 */
	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)
{
	BlockNumber *pages;
	Size	   *spaceavail;
	int			n;

	/* Ignore pages with little free space */
	if (avail < PAGE_SPACE_THRESHOLD)
		return;

	/* Copy pointers to local variables for notational simplicity */
	pages = vacrelstats->free_pages;
	spaceavail = vacrelstats->free_spaceavail;
	n = vacrelstats->max_free_pages;

	/* If we haven't filled the array yet, just keep adding entries */
	if (vacrelstats->num_free_pages < n)
	{
		pages[vacrelstats->num_free_pages] = page;
		spaceavail[vacrelstats->num_free_pages] = avail;
		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
	 *			spaceavail[(j-1) div 2] <= spaceavail[j]  for 0 < j < n.
	 * 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 */
983
	if (!vacrelstats->fs_is_heap)
984 985 986
	{
		/*
		 * Scan backwards through the array, "sift-up" each value into its
987 988
		 * correct position.  We can start the scan at n/2-1 since each
		 * entry above that position has no children to worry about.
989
		 */
990
		int			l = n / 2;
991 992 993

		while (--l >= 0)
		{
994
			BlockNumber R = pages[l];
995 996 997 998 999 1000
			Size		K = spaceavail[l];
			int			i;		/* i is where the "hole" is */

			i = l;
			for (;;)
			{
1001
				int			j = 2 * i + 1;
1002 1003 1004

				if (j >= n)
					break;
1005
				if (j + 1 < n && spaceavail[j] > spaceavail[j + 1])
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
					j++;
				if (K <= spaceavail[j])
					break;
				pages[i] = pages[j];
				spaceavail[i] = spaceavail[j];
				i = j;
			}
			pages[i] = R;
			spaceavail[i] = K;
		}

		vacrelstats->fs_is_heap = true;
	}

	/* If new page has more than zero'th entry, insert it into heap */
	if (avail > spaceavail[0])
	{
		/*
1024 1025 1026 1027
		 * Notionally, we replace the zero'th entry with the new data, and
		 * 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.
1028
		 */
1029
		int			i = 0;		/* i is where the "hole" is */
1030 1031 1032

		for (;;)
		{
1033
			int			j = 2 * i + 1;
1034 1035 1036

			if (j >= n)
				break;
1037
			if (j + 1 < n && spaceavail[j] > spaceavail[j + 1])
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
				j++;
			if (avail <= spaceavail[j])
				break;
			pages[i] = pages[j];
			spaceavail[i] = spaceavail[j];
			i = j;
		}
		pages[i] = page;
		spaceavail[i] = avail;
	}
}

/*
 *	lazy_tid_reaped() -- is a particular tid deletable?
 *
1053 1054
 *		This has the right signature to be an IndexBulkDeleteCallback.
 *
1055 1056 1057
 *		Assumes dead_tuples array is in sorted order.
 */
static bool
1058
lazy_tid_reaped(ItemPointer itemptr, void *state)
1059
{
1060
	LVRelStats *vacrelstats = (LVRelStats *) state;
1061
	ItemPointer res;
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

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

	return (res != NULL);
}

1072 1073 1074 1075 1076 1077 1078 1079 1080
/*
 * Dummy version for lazy_scan_index.
 */
static bool
dummy_tid_reaped(ItemPointer itemptr, void *state)
{
	return false;
}

1081 1082 1083 1084 1085 1086 1087 1088
/*
 * 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)
{
	/*
1089 1090 1091
	 * Since MultiRecordFreeSpace doesn't currently impose any
	 * restrictions on the ordering of the input, we can just pass it the
	 * arrays as-is, whether they are in heap or linear order.
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
	 */
	MultiRecordFreeSpace(&onerel->rd_node,
						 0, MaxBlockNumber,
						 vacrelstats->num_free_pages,
						 vacrelstats->free_pages,
						 vacrelstats->free_spaceavail);
}

/*
 * 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;
}