vacuumlazy.c 37.2 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 maintenance_work_mem memory space to keep
14 15
 * track of dead tuples.  We initially allocate an array of TIDs of that size,
 * with an upper limit that depends on table size (this limit ensures we don't
B
Bruce Momjian 已提交
16
 * allocate a huge area uselessly for vacuuming small tables).	If the array
17 18 19
 * 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.
20 21 22
 *
 * 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
23 24
 * 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,
25 26 27 28 29
 * 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.
 *
30 31 32 33 34
 * If we're processing a table with no indexes, we can just vacuum each page
 * as we go; there's no need to save up multiple tuples to minimize the number
 * of index scans performed.  So we don't use maintenance_work_mem memory for
 * the TID array, just enough to hold as many heap tuples as fit on one page.
 *
35
 *
36
 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
37 38 39 40
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
41
 *	  $PostgreSQL: pgsql/src/backend/commands/vacuumlazy.c,v 1.105 2008/03/24 19:12:49 tgl Exp $
42 43 44 45 46
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

47 48
#include <math.h>

49 50
#include "access/genam.h"
#include "access/heapam.h"
51
#include "access/transam.h"
52
#include "commands/dbcommands.h"
53 54
#include "commands/vacuum.h"
#include "miscadmin.h"
55
#include "pgstat.h"
56
#include "postmaster/autovacuum.h"
57
#include "storage/freespace.h"
58
#include "utils/lsyscache.h"
59
#include "utils/memutils.h"
60
#include "utils/pg_rusage.h"
61 62 63 64 65 66


/*
 * Space/time tradeoff parameters: do these need to be user-tunable?
 *
 * To consider truncating the relation, we want there to be at least
67 68
 * REL_TRUNCATE_MINIMUM or (relsize / REL_TRUNCATE_FRACTION) (whichever
 * is less) potentially-freeable pages.
69
 */
70
#define REL_TRUNCATE_MINIMUM	1000
71 72
#define REL_TRUNCATE_FRACTION	16

73 74 75 76 77
/*
 * Guesstimation of number of dead tuples per page.  This is used to
 * provide an upper limit to memory allocated when vacuuming small
 * tables.
 */
78
#define LAZY_ALLOC_TUPLES		MaxHeapTuplesPerPage
79 80 81

typedef struct LVRelStats
{
82 83
	/* hasindex = true means two-pass strategy; false means one-pass */
	bool		hasindex;
84
	/* Overall statistics about rel */
85
	BlockNumber rel_pages;
86
	double		rel_tuples;
B
Bruce Momjian 已提交
87
	BlockNumber pages_removed;
88
	double		tuples_deleted;
89
	BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */
90
	Size		threshold;		/* minimum interesting free space */
91 92
	/* List of TIDs of tuples we intend to delete */
	/* NB: this list is ordered by TID address */
93 94
	int			num_dead_tuples;	/* current # of entries */
	int			max_dead_tuples;	/* # slots allocated in array */
95
	ItemPointer dead_tuples;	/* array of ItemPointerData */
96 97
	/* Array or heap of per-page info about free space */
	/* We use a simple array until it fills up, then convert to heap */
98 99
	bool		fs_is_heap;		/* are we using heap organization? */
	int			num_free_pages; /* current # of entries */
100
	int			max_free_pages; /* # slots allocated in array */
101
	FSMPageData *free_pages;	/* array or heap of blkno/avail */
B
Bruce Momjian 已提交
102
	BlockNumber tot_free_pages; /* total pages with >= threshold space */
103
	int			num_index_scans;
104 105 106
} LVRelStats;


107
/* A few variables that don't seem worth passing around as parameters */
B
Bruce Momjian 已提交
108
static int	elevel = -1;
109

110 111 112
static TransactionId OldestXmin;
static TransactionId FreezeLimit;

113 114
static BufferAccessStrategy vac_strategy;

115 116 117

/* non-export function prototypes */
static void lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
118
			   Relation *Irel, int nindexes);
119
static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats);
120
static void lazy_vacuum_index(Relation indrel,
B
Bruce Momjian 已提交
121 122
				  IndexBulkDeleteResult **stats,
				  LVRelStats *vacrelstats);
123
static void lazy_cleanup_index(Relation indrel,
B
Bruce Momjian 已提交
124 125
				   IndexBulkDeleteResult *stats,
				   LVRelStats *vacrelstats);
126 127
static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer,
				 int tupindex, LVRelStats *vacrelstats);
128
static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats);
129
static BlockNumber count_nondeletable_pages(Relation onerel,
130
						 LVRelStats *vacrelstats);
131
static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks);
132
static void lazy_record_dead_tuple(LVRelStats *vacrelstats,
133
					   ItemPointer itemptr);
134
static void lazy_record_free_space(LVRelStats *vacrelstats,
135
					   BlockNumber page, Size avail);
136
static bool lazy_tid_reaped(ItemPointer itemptr, void *state);
137 138
static void lazy_update_fsm(Relation onerel, LVRelStats *vacrelstats);
static int	vac_cmp_itemptr(const void *left, const void *right);
139
static int	vac_cmp_page_spaces(const void *left, const void *right);
140 141 142 143 144 145


/*
 *	lazy_vacuum_rel() -- perform LAZY VACUUM for one heap relation
 *
 *		This routine vacuums a single heap, cleans out its indexes, and
146
 *		updates its relpages and reltuples statistics.
147 148 149 150 151
 *
 *		At entry, we have already established a transaction and opened
 *		and locked the relation.
 */
void
152 153
lazy_vacuum_rel(Relation onerel, VacuumStmt *vacstmt,
				BufferAccessStrategy bstrategy)
154 155 156 157
{
	LVRelStats *vacrelstats;
	Relation   *Irel;
	int			nindexes;
158
	BlockNumber possibly_freeable;
159
	PGRUsage	ru0;
B
Bruce Momjian 已提交
160
	TimestampTz starttime = 0;
161 162 163 164

	pg_rusage_init(&ru0);

	/* measure elapsed time iff autovacuum logging requires it */
165
	if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration > 0)
166
		starttime = GetCurrentTimestamp();
167 168

	if (vacstmt->verbose)
169
		elevel = INFO;
170
	else
171
		elevel = DEBUG2;
B
Bruce Momjian 已提交
172

173 174
	vac_strategy = bstrategy;

175
	vacuum_set_xid_limits(vacstmt->freeze_min_age, onerel->rd_rel->relisshared,
176
						  &OldestXmin, &FreezeLimit);
177

178
	vacrelstats = (LVRelStats *) palloc0(sizeof(LVRelStats));
179

180 181 182 183
	/* 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);

184 185
	vacrelstats->num_index_scans = 0;

186
	/* Open all indexes of the relation */
187
	vac_open_indexes(onerel, RowExclusiveLock, &nindexes, &Irel);
188
	vacrelstats->hasindex = (nindexes > 0);
189 190

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

	/* Done with indexes */
194
	vac_close_indexes(nindexes, Irel, NoLock);
195 196 197 198

	/*
	 * Optionally truncate the relation.
	 *
199 200
	 * 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.
201 202
	 */
	possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages;
203
	if (possibly_freeable >= REL_TRUNCATE_MINIMUM ||
B
Bruce Momjian 已提交
204
		possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION)
205
		lazy_truncate_heap(onerel, vacrelstats);
206 207 208 209

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

210 211 212 213 214
	if (vacrelstats->tot_free_pages > MaxFSMPages)
		ereport(WARNING,
				(errmsg("relation \"%s.%s\" contains more than \"max_fsm_pages\" pages with useful free space",
						get_namespace_name(RelationGetNamespace(onerel)),
						RelationGetRelationName(onerel)),
215 216 217 218
				 /* Only suggest VACUUM FULL if > 20% free */
				 (vacrelstats->tot_free_pages > vacrelstats->rel_pages * 0.20) ?
				 errhint("Consider using VACUUM FULL on this relation or increasing the configuration parameter \"max_fsm_pages\".") :
				 errhint("Consider increasing the configuration parameter \"max_fsm_pages\".")));
219

220
	/* Update statistics in pg_class */
221 222 223
	vac_update_relstats(RelationGetRelid(onerel),
						vacrelstats->rel_pages,
						vacrelstats->rel_tuples,
224
						vacrelstats->hasindex,
225
						FreezeLimit);
226 227

	/* report results to the stats collector, too */
228
	pgstat_report_vacuum(RelationGetRelid(onerel), onerel->rd_rel->relisshared,
B
Bruce Momjian 已提交
229
						 vacstmt->analyze, vacrelstats->rel_tuples);
230 231

	/* and log the action if appropriate */
232
	if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
233
	{
234
		if (Log_autovacuum_min_duration == 0 ||
235
			TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
236
									   Log_autovacuum_min_duration))
237 238 239 240 241 242 243 244 245
			ereport(LOG,
					(errmsg("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n"
							"pages: %d removed, %d remain\n"
							"tuples: %.0f removed, %.0f remain\n"
							"system usage: %s",
							get_database_name(MyDatabaseId),
							get_namespace_name(RelationGetNamespace(onerel)),
							RelationGetRelationName(onerel),
							vacrelstats->num_index_scans,
B
Bruce Momjian 已提交
246 247
						  vacrelstats->pages_removed, vacrelstats->rel_pages,
						vacrelstats->tuples_deleted, vacrelstats->rel_tuples,
248 249
							pg_rusage_show(&ru0))));
	}
250 251 252 253 254 255 256 257 258
}


/*
 *	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
259
 *		for dead-tuple TIDs, invoke vacuuming of indexes and heap.
260
 *
261 262
 *		If there are no indexes then we just vacuum each dirty page as we
 *		process it, since there's no point in gathering many tuples.
263 264 265
 */
static void
lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats,
266
			   Relation *Irel, int nindexes)
267 268 269 270 271
{
	BlockNumber nblocks,
				blkno;
	HeapTupleData tuple;
	char	   *relname;
272 273
	BlockNumber empty_pages,
				vacuumed_pages;
274 275 276 277
	double		num_tuples,
				tups_vacuumed,
				nkeep,
				nunused;
278
	IndexBulkDeleteResult **indstats;
279
	int			i;
280
	PGRUsage	ru0;
281

282
	pg_rusage_init(&ru0);
283 284

	relname = RelationGetRelationName(onerel);
285 286 287 288
	ereport(elevel,
			(errmsg("vacuuming \"%s.%s\"",
					get_namespace_name(RelationGetNamespace(onerel)),
					relname)));
289

290
	empty_pages = vacuumed_pages = 0;
291 292
	num_tuples = tups_vacuumed = nkeep = nunused = 0;

293 294
	indstats = (IndexBulkDeleteResult **)
		palloc0(nindexes * sizeof(IndexBulkDeleteResult *));
295

296 297 298 299
	nblocks = RelationGetNumberOfBlocks(onerel);
	vacrelstats->rel_pages = nblocks;
	vacrelstats->nonempty_pages = 0;

300
	lazy_space_alloc(vacrelstats, nblocks);
301 302 303 304 305 306 307

	for (blkno = 0; blkno < nblocks; blkno++)
	{
		Buffer		buf;
		Page		page;
		OffsetNumber offnum,
					maxoff;
308
		bool		tupgone,
309 310
					hastup;
		int			prev_dead_count;
311 312
		OffsetNumber frozen[MaxOffsetNumber];
		int			nfrozen;
313

314
		vacuum_delay_point();
J
Jan Wieck 已提交
315

316
		/*
B
Bruce Momjian 已提交
317 318
		 * 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.
319
		 */
320
		if ((vacrelstats->max_dead_tuples - vacrelstats->num_dead_tuples) < MaxHeapTuplesPerPage &&
321 322 323 324
			vacrelstats->num_dead_tuples > 0)
		{
			/* Remove index entries */
			for (i = 0; i < nindexes; i++)
325
				lazy_vacuum_index(Irel[i],
326
								  &indstats[i],
327
								  vacrelstats);
328 329 330 331
			/* Remove tuples from heap */
			lazy_vacuum_heap(onerel, vacrelstats);
			/* Forget the now-vacuumed tuples, and press on */
			vacrelstats->num_dead_tuples = 0;
332
			vacrelstats->num_index_scans++;
333 334
		}

335
		buf = ReadBufferWithStrategy(onerel, blkno, vac_strategy);
336

337 338
		/* We need buffer cleanup lock so that we can prune HOT chains. */
		LockBufferForCleanup(buf);
339 340 341 342 343

		page = BufferGetPage(buf);

		if (PageIsNew(page))
		{
344
			/*
B
Bruce Momjian 已提交
345 346 347
			 * 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.
348
			 *
349 350 351
			 * 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
352
			 * protect against that, release the buffer lock, grab the
B
Bruce Momjian 已提交
353 354 355
			 * relation extension lock momentarily, and re-lock the buffer. If
			 * the page is still uninitialized by then, it must be left over
			 * from a crashed backend, and we can initialize it.
356
			 *
357 358 359
			 * 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.
360
			 *
361 362
			 * Note: the comparable code in vacuum.c need not worry because
			 * it's got exclusive lock on the whole relation.
363
			 */
364
			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
365 366
			LockRelationForExtension(onerel, ExclusiveLock);
			UnlockRelationForExtension(onerel, ExclusiveLock);
367
			LockBufferForCleanup(buf);
368 369
			if (PageIsNew(page))
			{
370
				ereport(WARNING,
B
Bruce Momjian 已提交
371 372
				(errmsg("relation \"%s\" page %u is uninitialized --- fixing",
						relname, blkno)));
373
				PageInit(page, BufferGetPageSize(buf), 0);
374
				empty_pages++;
375
				lazy_record_free_space(vacrelstats, blkno,
376
									   PageGetHeapFreeSpace(page));
377
			}
378 379
			MarkBufferDirty(buf);
			UnlockReleaseBuffer(buf);
380 381 382 383 384 385 386
			continue;
		}

		if (PageIsEmpty(page))
		{
			empty_pages++;
			lazy_record_free_space(vacrelstats, blkno,
387
								   PageGetHeapFreeSpace(page));
388
			UnlockReleaseBuffer(buf);
389 390 391
			continue;
		}

B
Bruce Momjian 已提交
392
		/*
393 394 395 396 397 398 399 400
		 * Prune all HOT-update chains in this page.
		 *
		 * We count tuples removed by the pruning step as removed by VACUUM.
		 */
		tups_vacuumed += heap_page_prune(onerel, buf, OldestXmin,
										 false, false);

		/*
B
Bruce Momjian 已提交
401 402
		 * Now scan the page to collect vacuumable items and check for tuples
		 * requiring freezing.
403
		 */
404
		nfrozen = 0;
405 406 407 408 409 410 411 412 413 414 415
		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);

416
			/* Unused items require no processing, but we count 'em */
417 418 419 420 421 422
			if (!ItemIdIsUsed(itemid))
			{
				nunused += 1;
				continue;
			}

423
			/* Redirect items mustn't be touched */
B
Bruce Momjian 已提交
424 425
			if (ItemIdIsRedirected(itemid))
			{
426
				hastup = true;	/* this page won't be truncatable */
B
Bruce Momjian 已提交
427 428
				continue;
			}
429

B
Bruce Momjian 已提交
430
			ItemPointerSet(&(tuple.t_self), blkno, offnum);
431 432 433

			/*
			 * DEAD item pointers are to be vacuumed normally; but we don't
B
Bruce Momjian 已提交
434 435 436
			 * count them in tups_vacuumed, else we'd be double-counting (at
			 * least in the common case where heap_page_prune() just freed up
			 * a non-HOT tuple).
437 438 439 440 441 442 443 444 445
			 */
			if (ItemIdIsDead(itemid))
			{
				lazy_record_dead_tuple(vacrelstats, &(tuple.t_self));
				continue;
			}

			Assert(ItemIdIsNormal(itemid));

446 447 448 449 450
			tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
			tuple.t_len = ItemIdGetLength(itemid);

			tupgone = false;

451
			switch (HeapTupleSatisfiesVacuum(tuple.t_data, OldestXmin, buf))
452 453
			{
				case HEAPTUPLE_DEAD:
B
Bruce Momjian 已提交
454

455 456 457 458 459 460 461 462 463
					/*
					 * Ordinarily, DEAD tuples would have been removed by
					 * heap_page_prune(), but it's possible that the tuple
					 * state changed since heap_page_prune() looked.  In
					 * particular an INSERT_IN_PROGRESS tuple could have
					 * changed to DEAD if the inserter aborted.  So this
					 * cannot be considered an error condition.
					 *
					 * If the tuple is HOT-updated then it must only be
B
Bruce Momjian 已提交
464 465 466 467 468
					 * removed by a prune operation; so we keep it just as if
					 * it were RECENTLY_DEAD.  Also, if it's a heap-only
					 * tuple, we choose to keep it, because it'll be a lot
					 * cheaper to get rid of it in the next pruning pass than
					 * to treat it like an indexed tuple.
469 470 471 472 473
					 */
					if (HeapTupleIsHotUpdated(&tuple) ||
						HeapTupleIsHeapOnly(&tuple))
						nkeep += 1;
					else
B
Bruce Momjian 已提交
474
						tupgone = true; /* we can delete the tuple */
475 476
					break;
				case HEAPTUPLE_LIVE:
477
					/* Tuple is good --- but let's do some validity checks */
478 479 480 481
					if (onerel->rd_rel->relhasoids &&
						!OidIsValid(HeapTupleGetOid(&tuple)))
						elog(WARNING, "relation \"%s\" TID %u/%u: OID is invalid",
							 relname, blkno, offnum);
482 483
					break;
				case HEAPTUPLE_RECENTLY_DEAD:
484

485
					/*
B
Bruce Momjian 已提交
486 487
					 * If tuple is recently deleted then we must not remove it
					 * from relation.
488 489 490 491 492 493 494 495 496 497
					 */
					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:
498
					elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
499 500 501 502 503 504 505 506 507 508 509 510
					break;
			}

			if (tupgone)
			{
				lazy_record_dead_tuple(vacrelstats, &(tuple.t_self));
				tups_vacuumed += 1;
			}
			else
			{
				num_tuples += 1;
				hastup = true;
511

B
Bruce Momjian 已提交
512
				/*
B
Bruce Momjian 已提交
513 514
				 * Each non-removable tuple must be checked to see if it needs
				 * freezing.  Note we already have exclusive buffer lock.
515
				 */
516
				if (heap_freeze_tuple(tuple.t_data, FreezeLimit,
517
									  InvalidBuffer))
518
					frozen[nfrozen++] = offnum;
519
			}
520
		}						/* scan along page */
521

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
		/*
		 * If we froze any tuples, mark the buffer dirty, and write a WAL
		 * record recording the changes.  We must log the changes to be
		 * crash-safe against future truncation of CLOG.
		 */
		if (nfrozen > 0)
		{
			MarkBufferDirty(buf);
			/* no XLOG for temp tables, though */
			if (!onerel->rd_istemp)
			{
				XLogRecPtr	recptr;

				recptr = log_heap_freeze(onerel, buf, FreezeLimit,
										 frozen, nfrozen);
				PageSetLSN(page, recptr);
				PageSetTLI(page, ThisTimeLineID);
			}
		}

542 543 544 545 546 547 548 549 550 551 552 553 554 555
		/*
		 * If there are no indexes then we can vacuum the page right now
		 * instead of doing a second scan.
		 */
		if (nindexes == 0 &&
			vacrelstats->num_dead_tuples > 0)
		{
			/* Remove tuples from heap */
			lazy_vacuum_page(onerel, blkno, buf, 0, vacrelstats);
			/* Forget the now-vacuumed tuples, and press on */
			vacrelstats->num_dead_tuples = 0;
			vacuumed_pages++;
		}

556
		/*
557
		 * If we remembered any tuples for deletion, then the page will be
B
Bruce Momjian 已提交
558 559
		 * visited again by lazy_vacuum_heap, which will compute and record
		 * its post-compaction free space.	If not, then we're done with this
B
Bruce Momjian 已提交
560 561
		 * page, so remember its free space as-is.	(This path will always be
		 * taken if there are no indexes.)
562 563 564 565
		 */
		if (vacrelstats->num_dead_tuples == prev_dead_count)
		{
			lazy_record_free_space(vacrelstats, blkno,
566
								   PageGetHeapFreeSpace(page));
567 568 569 570 571 572
		}

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

573
		UnlockReleaseBuffer(buf);
574 575
	}

576 577
	/* save stats for use later */
	vacrelstats->rel_tuples = num_tuples;
578
	vacrelstats->tuples_deleted = tups_vacuumed;
579

580
	/* If any tuples need to be deleted, perform final vacuum cycle */
581
	/* XXX put a threshold on min number of tuples here? */
582 583 584 585
	if (vacrelstats->num_dead_tuples > 0)
	{
		/* Remove index entries */
		for (i = 0; i < nindexes; i++)
586
			lazy_vacuum_index(Irel[i],
587
							  &indstats[i],
588
							  vacrelstats);
589 590
		/* Remove tuples from heap */
		lazy_vacuum_heap(onerel, vacrelstats);
591
		vacrelstats->num_index_scans++;
592
	}
593 594 595 596

	/* Do post-vacuum cleanup and statistics update for each index */
	for (i = 0; i < nindexes; i++)
		lazy_cleanup_index(Irel[i], indstats[i], vacrelstats);
597

598 599 600 601 602 603 604
	/* If no indexes, make log report that lazy_vacuum_heap would've made */
	if (vacuumed_pages)
		ereport(elevel,
				(errmsg("\"%s\": removed %.0f row versions in %u pages",
						RelationGetRelationName(onerel),
						tups_vacuumed, vacuumed_pages)));

605
	ereport(elevel,
606
			(errmsg("\"%s\": found %.0f removable, %.0f nonremovable row versions in %u pages",
607 608
					RelationGetRelationName(onerel),
					tups_vacuumed, num_tuples, nblocks),
609
			 errdetail("%.0f dead row versions cannot be removed yet.\n"
610
					   "There were %.0f unused item pointers.\n"
611
					   "%u pages contain useful free space.\n"
612
					   "%u pages are entirely empty.\n"
613
					   "%s.",
614 615
					   nkeep,
					   nunused,
616
					   vacrelstats->tot_free_pages,
617
					   empty_pages,
618
					   pg_rusage_show(&ru0))));
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
}


/*
 *	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;
638
	PGRUsage	ru0;
639

640
	pg_rusage_init(&ru0);
641 642 643 644 645
	npages = 0;

	tupindex = 0;
	while (tupindex < vacrelstats->num_dead_tuples)
	{
646
		BlockNumber tblk;
647 648 649
		Buffer		buf;
		Page		page;

650
		vacuum_delay_point();
J
Jan Wieck 已提交
651

652
		tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]);
653
		buf = ReadBufferWithStrategy(onerel, tblk, vac_strategy);
654 655 656 657 658
		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,
659
							   PageGetHeapFreeSpace(page));
660
		UnlockReleaseBuffer(buf);
661 662 663
		npages++;
	}

664
	ereport(elevel,
665
			(errmsg("\"%s\": removed %d row versions in %d pages",
666 667
					RelationGetRelationName(onerel),
					tupindex, npages),
668 669
			 errdetail("%s.",
					   pg_rusage_show(&ru0))));
670 671 672 673 674 675
}

/*
 *	lazy_vacuum_page() -- free dead tuples on a page
 *					 and repair its fragmentation.
 *
676
 * Caller must hold pin and buffer cleanup lock on the buffer.
677 678 679 680 681 682 683 684 685 686
 *
 * 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)
{
	Page		page = BufferGetPage(buffer);
687 688
	OffsetNumber unused[MaxOffsetNumber];
	int			uncnt = 0;
689 690

	START_CRIT_SECTION();
691

692 693
	for (; tupindex < vacrelstats->num_dead_tuples; tupindex++)
	{
694 695
		BlockNumber tblk;
		OffsetNumber toff;
696
		ItemId		itemid;
697 698 699 700 701 702

		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);
703
		ItemIdSetUnused(itemid);
704
		unused[uncnt++] = toff;
705 706
	}

707
	PageRepairFragmentation(page);
708

709 710
	MarkBufferDirty(buffer);

711 712
	/* XLOG stuff */
	if (!onerel->rd_istemp)
713 714 715
	{
		XLogRecPtr	recptr;

716 717 718 719
		recptr = log_heap_clean(onerel, buffer,
								NULL, 0, NULL, 0,
								unused, uncnt,
								false);
720
		PageSetLSN(page, recptr);
721
		PageSetTLI(page, ThisTimeLineID);
722
	}
723

724 725 726 727 728
	END_CRIT_SECTION();

	return tupindex;
}

729
/*
730
 *	lazy_vacuum_index() -- vacuum one index relation.
731
 *
732 733
 *		Delete all the index entries pointing to tuples listed in
 *		vacrelstats->dead_tuples, and update running statistics.
734 735
 */
static void
736 737 738
lazy_vacuum_index(Relation indrel,
				  IndexBulkDeleteResult **stats,
				  LVRelStats *vacrelstats)
739
{
740
	IndexVacuumInfo ivinfo;
741
	PGRUsage	ru0;
742

743
	pg_rusage_init(&ru0);
744

745 746 747 748 749
	ivinfo.index = indrel;
	ivinfo.vacuum_full = false;
	ivinfo.message_level = elevel;
	/* We don't yet know rel_tuples, so pass -1 */
	ivinfo.num_heap_tuples = -1;
750
	ivinfo.strategy = vac_strategy;
751

752 753 754
	/* Do bulk deletion */
	*stats = index_bulk_delete(&ivinfo, *stats,
							   lazy_tid_reaped, (void *) vacrelstats);
755

756
	ereport(elevel,
757
			(errmsg("scanned index \"%s\" to remove %d row versions",
B
Bruce Momjian 已提交
758
					RelationGetRelationName(indrel),
759 760
					vacrelstats->num_dead_tuples),
			 errdetail("%s.", pg_rusage_show(&ru0))));
761 762
}

763
/*
764
 *	lazy_cleanup_index() -- do post-vacuum cleanup for one index relation.
765 766
 */
static void
767 768 769
lazy_cleanup_index(Relation indrel,
				   IndexBulkDeleteResult *stats,
				   LVRelStats *vacrelstats)
770
{
771
	IndexVacuumInfo ivinfo;
772
	PGRUsage	ru0;
773

774
	pg_rusage_init(&ru0);
775

776 777 778 779
	ivinfo.index = indrel;
	ivinfo.vacuum_full = false;
	ivinfo.message_level = elevel;
	ivinfo.num_heap_tuples = vacrelstats->rel_tuples;
780
	ivinfo.strategy = vac_strategy;
781

782
	stats = index_vacuum_cleanup(&ivinfo, stats);
783 784 785 786

	if (!stats)
		return;

787
	/* now update statistics in pg_class */
788 789 790
	vac_update_relstats(RelationGetRelid(indrel),
						stats->num_pages,
						stats->num_index_tuples,
791
						false, InvalidTransactionId);
792

793
	ereport(elevel,
B
Bruce Momjian 已提交
794 795 796 797 798 799 800 801 802 803
			(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))));
804

805
	pfree(stats);
806 807 808 809 810 811
}

/*
 * lazy_truncate_heap - try to truncate off any empty pages at the end
 */
static void
812
lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats)
813
{
814 815
	BlockNumber old_rel_pages = vacrelstats->rel_pages;
	BlockNumber new_rel_pages;
816
	FSMPageData *pageSpaces;
817 818 819
	int			n;
	int			i,
				j;
820
	PGRUsage	ru0;
821

822
	pg_rusage_init(&ru0);
823 824

	/*
B
Bruce Momjian 已提交
825 826 827 828
	 * 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).
829
	 */
830
	if (!ConditionalLockRelation(onerel, AccessExclusiveLock))
831 832 833 834
		return;

	/*
	 * Now that we have exclusive lock, look to see if the rel has grown
B
Bruce Momjian 已提交
835 836
	 * whilst we were vacuuming with non-exclusive lock.  If so, give up; the
	 * newly added pages presumably contain non-deletable tuples.
837 838 839 840 841 842 843 844 845 846 847 848
	 */
	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
849 850 851
	 * contain no tuples.  This is *necessary*, not optional, because other
	 * backends could have added tuples to these pages whilst we were
	 * vacuuming.
852
	 */
853
	new_rel_pages = count_nondeletable_pages(onerel, vacrelstats);
854 855 856 857 858 859 860 861 862 863 864

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

	/*
	 * Okay to truncate.
	 */
865
	RelationTruncate(onerel, new_rel_pages);
866

867
	/*
B
Bruce Momjian 已提交
868 869 870 871 872
	 * Note: once we have truncated, we *must* keep the exclusive lock until
	 * commit.	The sinval message that will be sent at commit (as a result of
	 * vac_update_relstats()) must be received by other backends, to cause
	 * them to reset their rd_targblock values, before they can safely access
	 * the table again.
873
	 */
874

875 876 877 878
	/*
	 * Drop free-space info for removed blocks; these must not get entered
	 * into the FSM!
	 */
879
	pageSpaces = vacrelstats->free_pages;
880 881 882 883
	n = vacrelstats->num_free_pages;
	j = 0;
	for (i = 0; i < n; i++)
	{
884
		if (FSMPageGetPageNum(&pageSpaces[i]) < new_rel_pages)
885
		{
886
			pageSpaces[j] = pageSpaces[i];
887 888 889 890
			j++;
		}
	}
	vacrelstats->num_free_pages = j;
B
Bruce Momjian 已提交
891

892 893 894
	/*
	 * If tot_free_pages was more than num_free_pages, we can't tell for sure
	 * what its correct value is now, because we don't know which of the
B
Bruce Momjian 已提交
895 896
	 * forgotten pages are getting truncated.  Conservatively set it equal to
	 * num_free_pages.
897 898 899
	 */
	vacrelstats->tot_free_pages = j;

900 901
	/* We destroyed the heap ordering, so mark array unordered */
	vacrelstats->fs_is_heap = false;
902

903 904 905 906
	/* update statistics */
	vacrelstats->rel_pages = new_rel_pages;
	vacrelstats->pages_removed = old_rel_pages - new_rel_pages;

907 908 909 910
	ereport(elevel,
			(errmsg("\"%s\": truncated %u to %u pages",
					RelationGetRelationName(onerel),
					old_rel_pages, new_rel_pages),
911 912
			 errdetail("%s.",
					   pg_rusage_show(&ru0))));
913 914 915
}

/*
916
 * Rescan end pages to verify that they are (still) empty of tuples.
917 918 919 920
 *
 * Returns number of nondeletable pages (last nonempty page + 1).
 */
static BlockNumber
921
count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats)
922 923 924 925 926 927 928 929 930 931 932
{
	BlockNumber blkno;

	/* 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;
933
		bool		hastup;
934

935 936
		/*
		 * We don't insert a vacuum delay point here, because we have an
B
Bruce Momjian 已提交
937 938
		 * exclusive lock on the table which we want to hold for as short a
		 * time as possible.  We still need to check for interrupts however.
939
		 */
940
		CHECK_FOR_INTERRUPTS();
J
Jan Wieck 已提交
941

942 943
		blkno--;

944
		buf = ReadBufferWithStrategy(onerel, blkno, vac_strategy);
945 946 947 948 949 950 951 952

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

		page = BufferGetPage(buf);

		if (PageIsNew(page) || PageIsEmpty(page))
		{
953
			/* PageIsNew probably shouldn't happen... */
954
			UnlockReleaseBuffer(buf);
955 956 957 958 959 960 961 962 963 964 965 966 967
			continue;
		}

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

			itemid = PageGetItemId(page, offnum);

968 969 970 971 972 973 974
			/*
			 * Note: any non-unused item should be taken as a reason to keep
			 * this page.  We formerly thought that DEAD tuples could be
			 * thrown away, but that's not so, because we'd not have cleaned
			 * out their index entries.
			 */
			if (ItemIdIsUsed(itemid))
975 976 977 978
			{
				hastup = true;
				break;			/* can stop scanning */
			}
979
		}						/* scan along page */
980

981
		UnlockReleaseBuffer(buf);
982 983 984 985 986 987 988 989

		/* 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
990
	 * pages still are; we need not bother to look at the last known-nonempty
B
Bruce Momjian 已提交
991
	 * page.
992 993 994 995 996 997 998 999 1000 1001
	 */
	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
1002
lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks)
1003
{
1004
	long		maxtuples;
1005 1006
	int			maxpages;

1007 1008
	if (vacrelstats->hasindex)
	{
1009 1010 1011
		maxtuples = (maintenance_work_mem * 1024L) / sizeof(ItemPointerData);
		maxtuples = Min(maxtuples, INT_MAX);
		maxtuples = Min(maxtuples, MaxAllocSize / sizeof(ItemPointerData));
1012 1013 1014 1015 1016

		/* curious coding here to ensure the multiplication can't overflow */
		if ((BlockNumber) (maxtuples / LAZY_ALLOC_TUPLES) > relblocks)
			maxtuples = relblocks * LAZY_ALLOC_TUPLES;

1017 1018
		/* stay sane if small maintenance_work_mem */
		maxtuples = Max(maxtuples, MaxHeapTuplesPerPage);
1019 1020 1021
	}
	else
	{
1022 1023
		maxtuples = MaxHeapTuplesPerPage;
	}
1024 1025

	vacrelstats->num_dead_tuples = 0;
1026
	vacrelstats->max_dead_tuples = (int) maxtuples;
1027 1028 1029 1030
	vacrelstats->dead_tuples = (ItemPointer)
		palloc(maxtuples * sizeof(ItemPointerData));

	maxpages = MaxFSMPages;
1031
	maxpages = Min(maxpages, MaxAllocSize / sizeof(FSMPageData));
1032 1033 1034 1035 1036 1037 1038
	/* 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;
1039 1040
	vacrelstats->free_pages = (FSMPageData *)
		palloc(maxpages * sizeof(FSMPageData));
1041
	vacrelstats->tot_free_pages = 0;
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
}

/*
 * lazy_record_dead_tuple - remember one deletable tuple
 */
static void
lazy_record_dead_tuple(LVRelStats *vacrelstats,
					   ItemPointer itemptr)
{
	/*
1052
	 * The array shouldn't overflow under normal behavior, but perhaps it
1053
	 * could if we are given a really small maintenance_work_mem. In that
1054
	 * case, just forget the last few tuples (we'll get 'em next time).
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	 */
	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)
{
1071
	FSMPageData *pageSpaces;
1072 1073
	int			n;

1074 1075 1076
	/*
	 * 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 已提交
1077 1078 1079 1080
	 * 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.
1081
	 *
B
Bruce Momjian 已提交
1082 1083 1084 1085 1086
	 * 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.
1087 1088
	 */
	if (avail < vacrelstats->threshold)
1089 1090
		return;

1091 1092 1093
	/* Count all pages over threshold, even if not enough space in array */
	vacrelstats->tot_free_pages++;

1094
	/* Copy pointers to local variables for notational simplicity */
1095
	pageSpaces = vacrelstats->free_pages;
1096 1097 1098 1099 1100
	n = vacrelstats->max_free_pages;

	/* If we haven't filled the array yet, just keep adding entries */
	if (vacrelstats->num_free_pages < n)
	{
1101 1102
		FSMPageSetPageNum(&pageSpaces[vacrelstats->num_free_pages], page);
		FSMPageSetSpace(&pageSpaces[vacrelstats->num_free_pages], avail);
1103 1104 1105 1106 1107 1108 1109
		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 已提交
1110
	 *			avail[(j-1) div 2] <= avail[j]	for 0 < j < n.
1111 1112 1113 1114 1115 1116 1117 1118
	 * 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 */
1119
	if (!vacrelstats->fs_is_heap)
1120 1121 1122
	{
		/*
		 * Scan backwards through the array, "sift-up" each value into its
B
Bruce Momjian 已提交
1123 1124
		 * correct position.  We can start the scan at n/2-1 since each entry
		 * above that position has no children to worry about.
1125
		 */
1126
		int			l = n / 2;
1127 1128 1129

		while (--l >= 0)
		{
1130 1131
			BlockNumber R = FSMPageGetPageNum(&pageSpaces[l]);
			Size		K = FSMPageGetSpace(&pageSpaces[l]);
1132 1133 1134 1135 1136
			int			i;		/* i is where the "hole" is */

			i = l;
			for (;;)
			{
1137
				int			j = 2 * i + 1;
1138 1139 1140

				if (j >= n)
					break;
1141
				if (j + 1 < n && FSMPageGetSpace(&pageSpaces[j]) > FSMPageGetSpace(&pageSpaces[j + 1]))
1142
					j++;
1143
				if (K <= FSMPageGetSpace(&pageSpaces[j]))
1144
					break;
1145
				pageSpaces[i] = pageSpaces[j];
1146 1147
				i = j;
			}
1148 1149
			FSMPageSetPageNum(&pageSpaces[i], R);
			FSMPageSetSpace(&pageSpaces[i], K);
1150 1151 1152 1153 1154 1155
		}

		vacrelstats->fs_is_heap = true;
	}

	/* If new page has more than zero'th entry, insert it into heap */
1156
	if (avail > FSMPageGetSpace(&pageSpaces[0]))
1157 1158
	{
		/*
1159
		 * Notionally, we replace the zero'th entry with the new data, and
B
Bruce Momjian 已提交
1160 1161 1162
		 * 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.
1163
		 */
1164
		int			i = 0;		/* i is where the "hole" is */
1165 1166 1167

		for (;;)
		{
1168
			int			j = 2 * i + 1;
1169 1170 1171

			if (j >= n)
				break;
1172
			if (j + 1 < n && FSMPageGetSpace(&pageSpaces[j]) > FSMPageGetSpace(&pageSpaces[j + 1]))
1173
				j++;
1174
			if (avail <= FSMPageGetSpace(&pageSpaces[j]))
1175
				break;
1176
			pageSpaces[i] = pageSpaces[j];
1177 1178
			i = j;
		}
1179 1180
		FSMPageSetPageNum(&pageSpaces[i], page);
		FSMPageSetSpace(&pageSpaces[i], avail);
1181 1182 1183 1184 1185 1186
	}
}

/*
 *	lazy_tid_reaped() -- is a particular tid deletable?
 *
1187 1188
 *		This has the right signature to be an IndexBulkDeleteCallback.
 *
1189 1190 1191
 *		Assumes dead_tuples array is in sorted order.
 */
static bool
1192
lazy_tid_reaped(ItemPointer itemptr, void *state)
1193
{
1194
	LVRelStats *vacrelstats = (LVRelStats *) state;
1195
	ItemPointer res;
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212

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

	return (res != NULL);
}

/*
 * 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)
{
1213
	FSMPageData *pageSpaces = vacrelstats->free_pages;
1214 1215
	int			nPages = vacrelstats->num_free_pages;

1216
	/*
1217
	 * Sort data into order, as required by RecordRelationFreeSpace.
1218
	 */
1219
	if (nPages > 1)
1220
		qsort(pageSpaces, nPages, sizeof(FSMPageData),
1221 1222
			  vac_cmp_page_spaces);

1223 1224
	RecordRelationFreeSpace(&onerel->rd_node, vacrelstats->tot_free_pages,
							nPages, pageSpaces);
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
}

/*
 * 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;
}
1256 1257 1258 1259

static int
vac_cmp_page_spaces(const void *left, const void *right)
{
1260 1261 1262 1263
	FSMPageData *linfo = (FSMPageData *) left;
	FSMPageData *rinfo = (FSMPageData *) right;
	BlockNumber	lblkno = FSMPageGetPageNum(linfo);
	BlockNumber	rblkno = FSMPageGetPageNum(rinfo);
1264

1265
	if (lblkno < rblkno)
1266
		return -1;
1267
	else if (lblkno > rblkno)
1268 1269 1270
		return 1;
	return 0;
}