vacuum.c 97.7 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * vacuum.c
4 5
 *	  The postgres vacuum cleaner.
 *
6 7 8 9
 * This file now includes only control and dispatch code for VACUUM and
 * ANALYZE commands.  Regular VACUUM is implemented in vacuumlazy.c,
 * ANALYZE in analyze.c, and VACUUM FULL is a variant of CLUSTER, handled
 * in cluster.c.
10
 *
11
 *
12
 * Portions Copyright (c) 2005-2010, Greenplum inc
13
 * Portions Copyright (c) 2012-Present Pivotal Software, Inc.
B
Bruce Momjian 已提交
14
 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
15
 * Portions Copyright (c) 1994, Regents of the University of California
16 17 18
 *
 *
 * IDENTIFICATION
19
 *	  src/backend/commands/vacuum.c
20 21 22
 *
 *-------------------------------------------------------------------------
 */
23 24
#include "postgres.h"

25 26
#include <math.h>

27
#include "access/clog.h"
B
Bruce Momjian 已提交
28 29
#include "access/genam.h"
#include "access/heapam.h"
30 31
#include "access/appendonlywriter.h"
#include "access/appendonlytid.h"
R
Richard Guo 已提交
32
#include "access/visibilitymap.h"
33
#include "access/htup_details.h"
34
#include "access/multixact.h"
35 36
#include "access/transam.h"
#include "access/xact.h"
37 38 39 40
#include "access/appendonly_compaction.h"
#include "access/appendonly_visimap.h"
#include "access/aocs_compaction.h"
#include "catalog/catalog.h"
41
#include "catalog/namespace.h"
42
#include "catalog/pg_appendonly_fn.h"
43
#include "catalog/pg_database.h"
44 45 46
#include "catalog/pg_index.h"
#include "catalog/indexing.h"
#include "catalog/pg_namespace.h"
47
#include "commands/analyzeutils.h"
48
#include "commands/cluster.h"
49
#include "commands/tablecmds.h"
B
Bruce Momjian 已提交
50
#include "commands/vacuum.h"
51
#include "cdb/cdbdisp_query.h"
52
#include "cdb/cdbpartition.h"
53
#include "cdb/cdbutil.h"
54 55 56 57 58 59
#include "cdb/cdbvars.h"
#include "cdb/cdbsrlz.h"
#include "cdb/cdbdispatchresult.h"      /* CdbDispatchResults */
#include "cdb/cdbappendonlyblockdirectory.h"
#include "lib/stringinfo.h"
#include "libpq/pqformat.h"             /* pq_beginmessage() etc. */
B
Bruce Momjian 已提交
60
#include "miscadmin.h"
61
#include "pgstat.h"
O
Omer Arap 已提交
62
#include "parser/parse_relation.h"
63
#include "postmaster/autovacuum.h"
64 65
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
66
#include "storage/proc.h"
67
#include "storage/procarray.h"
68
#include "utils/acl.h"
69
#include "utils/fmgroids.h"
70
#include "utils/guc.h"
71
#include "utils/memutils.h"
72
#include "utils/snapmgr.h"
B
Bruce Momjian 已提交
73
#include "utils/syscache.h"
74
#include "utils/tqual.h"
75

76
#include "access/distributedlog.h"
77 78
#include "catalog/heap.h"
#include "catalog/oid_dispatch.h"
79
#include "catalog/pg_inherits_fn.h"
80 81
#include "libpq-fe.h"
#include "libpq-int.h"
82 83
#include "nodes/makefuncs.h"     /* makeRangeVar */
#include "pgstat.h"
84 85 86
#include "utils/faultinjector.h"
#include "utils/lsyscache.h"
#include "utils/pg_rusage.h"
87

88

89 90 91 92
/*
 * GUC parameters
 */
int			vacuum_freeze_min_age;
93
int			vacuum_freeze_table_age;
94 95
int			vacuum_multixact_freeze_min_age;
int			vacuum_multixact_freeze_table_age;
96

B
Bruce Momjian 已提交
97

98 99 100 101 102
typedef struct VacuumStatsContext
{
	List	   *updated_stats;
} VacuumStatsContext;

103 104 105 106 107 108
/*
 * State information used during the (full)
 * vacuum of indexes on append-only tables
 */
typedef struct AppendOnlyIndexVacuumState
{
109
	Snapshot	appendOnlyMetaDataSnapshot;
110 111 112 113 114 115
	AppendOnlyVisimap visiMap;
	AppendOnlyBlockDirectory blockDirectory;
	AppendOnlyBlockDirectoryEntry blockDirectoryEntry;
} AppendOnlyIndexVacuumState;

/* A few variables that don't seem worth passing around as parameters */
116
static MemoryContext vac_context = NULL;
117

118
static BufferAccessStrategy vac_strategy;
119

120
/* non-export function prototypes */
A
Asim R P 已提交
121
static List *get_rel_oids(Oid relid, VacuumStmt *vacstmt, int stmttype);
122
static void vac_truncate_clog(TransactionId frozenXID,
123 124 125
							  MultiXactId minMulti,
							  TransactionId lastSaneFrozenXid,
							  MultiXactId lastSaneMinMulti);
A
Asim R P 已提交
126
static bool vacuum_rel(Relation onerel, Oid relid, VacuumStmt *vacstmt, LOCKMODE lmode,
127
		   bool for_wraparound);
128 129
static void scan_index(Relation indrel, double num_tuples,
					   bool check_stats, int elevel);
130 131
static bool appendonly_tid_reaped(ItemPointer itemptr, void *state);
static void dispatchVacuum(VacuumStmt *vacstmt, VacuumStatsContext *ctx);
132 133
static void vacuumStatement_Relation(VacuumStmt *vacstmt, Oid relid,
						 List *relations, BufferAccessStrategy bstrategy,
134
						 bool do_toast,
135
						 bool for_wraparound, bool isTopLevel);
136

137 138 139 140 141 142
static void
vacuum_rel_ao_phase(Relation onerel, Oid relid, VacuumStmt *vacstmt, LOCKMODE lmode,
					bool for_wraparound,
					List *compaction_insert_segno,
					List *compaction_segno,
					AOVacuumPhase phase);
143

144
static void
145 146
vacuum_combine_stats(VacuumStatsContext *stats_context,
					CdbPgResults* cdb_pgresults);
147

148
static void vacuum_appendonly_index(Relation indexRelation,
149 150
						AppendOnlyIndexVacuumState *vacuumIndexState,
						double rel_tuple_count, int elevel);
151

152 153 154
/*
 * Primary entry point for VACUUM and ANALYZE commands.
 *
155 156 157
 * relid is normally InvalidOid; if it is not, then it provides the relation
 * OID to be processed, and vacstmt->relation is ignored.  (The non-invalid
 * case is currently only used by autovacuum.)
158
 *
159 160 161
 * do_toast is passed as FALSE by autovacuum, because it processes TOAST
 * tables separately.
 *
162
 * for_wraparound is used by autovacuum to let us know when it's forcing
163
 * a vacuum for wraparound, which should not be auto-canceled.
164
 *
165 166 167
 * bstrategy is normally given as NULL, but in autovacuum it can be passed
 * in to use the same buffer strategy object across multiple vacuum() calls.
 *
168 169
 * isTopLevel should be passed down from ProcessUtility.
 *
170
 * It is the caller's responsibility that vacstmt and bstrategy
171
 * (if given) be allocated in a memory context that won't disappear
172
 * at transaction commit.
173
 */
174
void
175
vacuum(VacuumStmt *vacstmt, Oid relid, bool do_toast,
176
	   BufferAccessStrategy bstrategy, bool for_wraparound, bool isTopLevel)
177
{
178
	const char *stmttype;
179
	volatile bool in_outer_xact,
180
				use_own_xacts;
181 182
	List	   *vacuum_relations = NIL;
	List	   *analyze_relations = NIL;
183

184 185
	if ((vacstmt->options & VACOPT_VACUUM) &&
		(vacstmt->options & VACOPT_ROOTONLY))
186 187 188
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("ROOTPARTITION option cannot be used together with VACUUM, try ANALYZE ROOTPARTITION")));
189
	static bool in_vacuum = false;
190

191 192 193 194 195 196 197
	/* sanity checks on options */
	Assert(vacstmt->options & (VACOPT_VACUUM | VACOPT_ANALYZE));
	Assert((vacstmt->options & VACOPT_VACUUM) ||
		   !(vacstmt->options & (VACOPT_FULL | VACOPT_FREEZE)));
	Assert((vacstmt->options & VACOPT_ANALYZE) || vacstmt->va_cols == NIL);

	stmttype = (vacstmt->options & VACOPT_VACUUM) ? "VACUUM" : "ANALYZE";
198

199 200 201
	/*
	 * We cannot run VACUUM inside a user transaction block; if we were inside
	 * a transaction, then our commit- and start-transaction-command calls
B
Bruce Momjian 已提交
202
	 * would not have the intended effect!	There are numerous other subtle
203
	 * dependencies on this, too.
204 205 206
	 *
	 * ANALYZE (without VACUUM) can run either way.
	 */
207
	if (vacstmt->options & VACOPT_VACUUM)
208 209
	{
		if (Gp_role == GP_ROLE_DISPATCH)
210
			PreventTransactionChain(isTopLevel, stmttype);
211 212 213
		in_outer_xact = false;
	}
	else
214
		in_outer_xact = IsInTransactionChain(isTopLevel);
215

216 217 218 219 220 221 222 223
	/*
	 * Due to static variables vac_context, anl_context and vac_strategy,
	 * vacuum() is not reentrant.  This matters when VACUUM FULL or ANALYZE
	 * calls a hostile index expression that itself calls ANALYZE.
	 */
	if (in_vacuum)
		elog(ERROR, "%s cannot be executed from VACUUM or ANALYZE", stmttype);

224 225 226 227
	/*
	 * Send info about dead objects to the statistics collector, unless we are
	 * in autovacuum --- autovacuum.c does this for itself.
	 */
228
	if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
229 230 231 232 233 234 235 236 237 238 239 240 241 242
		pgstat_vacuum_stat();

	/*
	 * Create special memory context for cross-transaction storage.
	 *
	 * Since it is a child of PortalContext, it will go away eventually even
	 * if we suffer an error; there's no need for special abort cleanup logic.
	 */
	vac_context = AllocSetContextCreate(PortalContext,
										"Vacuum",
										ALLOCSET_DEFAULT_MINSIZE,
										ALLOCSET_DEFAULT_INITSIZE,
										ALLOCSET_DEFAULT_MAXSIZE);

243 244 245 246 247 248 249 250 251 252 253 254 255
	/*
	 * If caller didn't give us a buffer strategy object, make one in the
	 * cross-transaction memory context.
	 */
	if (bstrategy == NULL)
	{
		MemoryContext old_context = MemoryContextSwitchTo(vac_context);

		bstrategy = GetAccessStrategy(BAS_VACUUM);
		MemoryContextSwitchTo(old_context);
	}
	vac_strategy = bstrategy;

256 257 258
	/*
	 * Build list of relations to process, unless caller gave us one. (If we
	 * build one, we put it in vac_context for safekeeping.)
259
	 */
260 261 262 263 264 265 266 267

	/*
	 * Analyze on midlevel partition is not allowed directly so
	 * vacuum_relations and analyze_relations may be different.  In case of
	 * partitioned tables, vacuum_relation will contain all OIDs of the
	 * partitions of a partitioned table. However, analyze_relation will
	 * contain all the OIDs of partition of a partitioned table except midlevel
	 * partition unless GUC optimizer_analyze_midlevel_partition is set to on.
268
	 */
269
	if (vacstmt->options & VACOPT_VACUUM)
A
Asim R P 已提交
270 271 272
	{
		vacuum_relations = get_rel_oids(relid, vacstmt, VACOPT_VACUUM);
	}
273
	if (vacstmt->options & VACOPT_ANALYZE)
A
Asim R P 已提交
274
		analyze_relations = get_rel_oids(relid, vacstmt, VACOPT_ANALYZE);
275

276 277 278
	/*
	 * Decide whether we need to start/commit our own transactions.
	 *
279 280 281 282 283
	 * For VACUUM (with or without ANALYZE): always do so on the query
	 * dispatcher, so that we can release locks as soon as possible.  On the
	 * query executor we skip this and use the outer transaction when skipping
	 * two phase commit, as the expectation is that it will be a separate
	 * dispatch for every table to be vacuumed.
284 285 286 287
	 *
	 * For ANALYZE (no VACUUM): if inside a transaction block, we cannot
	 * start/commit our own transactions.  Also, there's no need to do so if
	 * only processing one relation.  For multiple relations when not within a
288 289
	 * transaction block, and also in an autovacuum worker, use own
	 * transactions so we can release locks sooner.
290
	 */
291
	if (vacstmt->options & VACOPT_VACUUM)
292 293 294 295
		if (Gp_role == GP_ROLE_EXECUTE && vacstmt->skip_twophase)
			use_own_xacts = false;
		else
			use_own_xacts = true;
296
	else
297
	{
298
		Assert(vacstmt->options & VACOPT_ANALYZE);
299 300 301
		if (IsAutoVacuumWorkerProcess())
			use_own_xacts = true;
		else if (in_outer_xact)
302
			use_own_xacts = false;
303
		else if (list_length(analyze_relations) > 1)
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
			use_own_xacts = true;
		else
			use_own_xacts = false;
	}

	/*
	 * vacuum_rel expects to be entered with no transaction active; it will
	 * start and commit its own transaction.  But we are called by an SQL
	 * command, and so we are executing inside a transaction already. We
	 * commit the transaction started in PostgresMain() here, and start
	 * another one before exiting to match the commit waiting for us back in
	 * PostgresMain().
	 */
	if (use_own_xacts)
	{
319 320
		Assert(!in_outer_xact);

321 322 323 324
		/* ActiveSnapshot is not set by autovacuum */
		if (ActiveSnapshotSet())
			PopActiveSnapshot();

325 326 327 328 329
		/* matches the StartTransaction in PostgresMain() */
		if (Gp_role != GP_ROLE_EXECUTE)
			CommitTransactionCommand();
	}

330
	/* Turn vacuum cost accounting on or off */
331 332 333 334
	PG_TRY();
	{
		ListCell   *cur;

335
		in_vacuum = true;
336 337
		VacuumCostActive = (VacuumCostDelay > 0);
		VacuumCostBalance = 0;
338 339 340
		VacuumPageHit = 0;
		VacuumPageMiss = 0;
		VacuumPageDirty = 0;
341

342
		if (vacstmt->options & VACOPT_VACUUM)
343
		{
344
			/*
345 346
			 * Loop to process each selected relation which needs to be
			 * vacuumed.
347
			 */
348 349 350
			foreach(cur, vacuum_relations)
			{
				Oid			relid = lfirst_oid(cur);
351 352

				vacuumStatement_Relation(vacstmt, relid, vacuum_relations, bstrategy, do_toast, for_wraparound, isTopLevel);
353 354
			}
		}
355

356
		if (vacstmt->options & VACOPT_ANALYZE)
357
		{
358
			/*
359 360 361
			 * If there are no partition tables in the database and ANALYZE
			 * ROOTPARTITION ALL is executed, report a WARNING as no root
			 * partitions are there to be analyzed
362
			 */
363
			if ((vacstmt->options & VACOPT_ROOTONLY) && NIL == analyze_relations && !vacstmt->relation)
364 365 366 367 368 369 370 371
			{
				ereport(NOTICE,
						(errmsg("there are no partitioned tables in database to ANALYZE ROOTPARTITION")));
			}

			/*
			 * Loop to process each selected relation which needs to be analyzed.
			 */
372
			foreach(cur, analyze_relations)
373
			{
374
				Oid			relid = lfirst_oid(cur);
375 376 377

				/*
				 * If using separate xacts, start one for analyze. Otherwise,
378
				 * we can use the outer transaction.
379 380 381 382 383
				 */
				if (use_own_xacts)
				{
					StartTransactionCommand();
					/* functions in indexes may want a snapshot set */
384
					PushActiveSnapshot(GetTransactionSnapshot());
385 386
				}

387
				analyze_rel(relid, vacstmt, in_outer_xact, vac_strategy);
388 389

				if (use_own_xacts)
390 391
				{
					PopActiveSnapshot();
392
					CommitTransactionCommand();
393
				}
394
			}
395
		}
396
	}
397 398
	PG_CATCH();
	{
399
		in_vacuum = false;
400 401 402 403
		VacuumCostActive = false;
		PG_RE_THROW();
	}
	PG_END_TRY();
404

405
	in_vacuum = false;
406 407 408 409 410 411
	VacuumCostActive = false;

	/*
	 * Finish up processing.
	 */
	if (use_own_xacts)
412
	{
413 414 415
		/* here, we are not in a transaction */

		StartTransactionCommand();
416
	}
417

418
	if ((vacstmt->options & VACOPT_VACUUM) && !IsAutoVacuumWorkerProcess())
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
	{
		/*
		 * Update pg_database.datfrozenxid, and truncate pg_clog if possible.
		 * (autovacuum.c does this for itself.)
		 */
		vac_update_datfrozenxid();
	}

	/*
	 * Clean up working storage --- note we must do this after
	 * StartTransactionCommand, else we might be trying to delete the active
	 * context!
	 */
	MemoryContextDelete(vac_context);
	vac_context = NULL;
434
}
435

436 437 438
/*
 * Assigns the compaction segment information.
 *
439 440
 * The segment to compact is returned in *compact_segno, and
 * the segment to move rows to, is returned in *insert_segno.
441
 */
442 443 444 445 446 447
static bool
vacuum_assign_compaction_segno(Relation onerel,
							   List *compactedSegmentFileList,
							   List *insertedSegmentFileList,
							   List **compactNowList,
							   int *insert_segno)
448 449 450
{
	List *new_compaction_list;
	bool is_drop;
T
ARGH!  
Tom Lane 已提交
451

452
	Assert(Gp_role != GP_ROLE_EXECUTE);
453
	Assert(RelationIsValid(onerel));
454
	Assert(RelationIsAppendOptimized(onerel));
455

456
	/*
457 458
	 * Assign a compaction segment num and insert segment num
	 * on master or on segment if in utility mode
459
	 */
460
	if (!gp_appendonly_compaction)
461
	{
462 463
		*insert_segno = -1;
		*compactNowList = NIL;
464
		return true;
465 466
	}

467 468 469 470 471
	if (HasSerializableBackends(false))
	{
		elog(LOG, "Skip compaction because of concurrent serializable transactions");
		return false;
	}
472

473
	new_compaction_list = SetSegnoForCompaction(onerel,
474 475
			compactedSegmentFileList, insertedSegmentFileList, &is_drop);
	if (new_compaction_list)
476
	{
477 478
		if (!is_drop)
		{
479 480
			*insert_segno = SetSegnoForCompactionInsert(onerel,
														new_compaction_list,
481
														compactedSegmentFileList);
482 483 484 485 486 487 488
		}
		else
		{
			/*
			 * If we continue an aborted drop phase, we do not assign a real
			 * insert segment file.
			 */
489
			*insert_segno = APPENDONLY_COMPACTION_SEGNO_INVALID;
490
		}
491
		*compactNowList = new_compaction_list;
492 493 494

		elogif(Debug_appendonly_print_compaction, LOG,
				"Schedule compaction on AO table: "
495 496 497
				"compact segno list length %d, insert segno %d",
				list_length(new_compaction_list), *insert_segno);
		return true;
498
	}
499
	else
500
	{
501
		elog(DEBUG3, "No valid compact segno for relation %s (%d)",
502 503 504 505 506
				RelationGetRelationName(onerel),
				RelationGetRelid(onerel));
		return false;
	}
}
507

508 509
bool
vacuumStatement_IsTemporary(Relation onerel)
510 511 512
{
	bool bTemp = false;
	/* MPP-7576: don't track internal namespace tables */
513
	switch (RelationGetNamespace(onerel))
514 515 516 517 518
	{
		case PG_CATALOG_NAMESPACE:
			/* MPP-7773: don't track objects in system namespace
			 * if modifying system tables (eg during upgrade)
			 */
519
			if (allowSystemTableMods)
520 521
				bTemp = true;
			break;
522

523 524 525 526 527 528 529 530
		case PG_TOAST_NAMESPACE:
		case PG_BITMAPINDEX_NAMESPACE:
		case PG_AOSEGMENT_NAMESPACE:
			bTemp = true;
			break;
		default:
			break;
	}
531

532 533 534 535
	/* MPP-7572: Don't track metadata if table in any
	 * temporary namespace
	 */
	if (!bTemp)
536
		bTemp = isAnyTempNamespace(RelationGetNamespace(onerel));
537 538
	return bTemp;
}
539

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
/*
 * Modify the Vacuum statement to vacuum an individual
 * relation. This ensures that only one relation will be
 * locked for vacuum, when the user issues a "vacuum <db>"
 * command, or a "vacuum <parent_partition_table>"
 * command.
 */
static void
vacuumStatement_AssignRelation(VacuumStmt *vacstmt, Oid relid, List *relations)
{
	if (list_length(relations) > 1 || vacstmt->relation == NULL)
	{
		char	*relname		= get_rel_name(relid);
		char	*namespace_name =
			get_namespace_name(get_rel_namespace(relid));
555

556 557 558 559 560
		if (relname == NULL)
		{
			elog(ERROR, "Relation name does not exist for relation with oid %d", relid);
			return;
		}
561

562 563 564 565 566
		if (namespace_name == NULL)
		{
			elog(ERROR, "Namespace does not exist for relation with oid %d", relid);
			return;
		}
567

568 569 570 571
		/* XXX: dispatch OID than name */
		vacstmt->relation = makeRangeVar(namespace_name, relname, -1);
	}
}
572

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
/*
 * Processing of the vacuumStatement for given relid.
 *
 * The function is called by vacuumStatement once for each relation to vacuum.
 * In order to connect QD and QE work for vacuum, we employ a little
 * complicated mechanism here; we separate one relation vacuum process
 * to a separate steps, depending on the type of storage (heap/AO),
 * and perform each step in separate transactions, so that QD can open
 * a distributed transaction and embrace QE work inside it.  As opposed to
 * old postgres code, where one transaction is opened and closed for each
 * auxiliary relation, here a transaction processes them as a set starting
 * from the base relation.  This is the entry point of one base relation,
 * and QD makes some decision what kind of stage we perform, and tells it
 * to QE with vacstmt fields through dispatch.
 *
588 589 590 591 592
 * For heap VACUUM we disable two-phase commit, because we do not actually make
 * any logical changes to the tables. Even if a VACUUM transaction fails on one
 * of the QE segments, it should not matter, because the data has not logically
 * changed on disk. VACUUM FULL and lazy vacuum are both completed in one
 * transaction.
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
 *
 * AO compaction is rather complicated.  There are four phases.
 *   - prepare phase
 *   - compaction phase
 *   - drop phase
 *   - cleanup phase
 * Out of these, compaction and drop phase might repeat multiple times.
 * We go through the list of available segment files by looking up catalog,
 * and perform a compaction operation, which appends the whole segfile
 * to another available one, if the source segfile looks to be dirty enough.
 * If we find such one and perform compaction, the next step is drop. In
 * order to allow concurrent read it is required for the drop phase to
 * be a separate transaction.  We mark the segfile as an awaiting-drop
 * in the catalog, and the drop phase actually drops the segfile from the
 * disk.  There are some cases where we cannot drop the segfile immediately,
 * in which case we just skip it and leave the catalog to have awaiting-drop
 * state for this segfile.  Aside from the compaction and drop phases, the
 * rest is much simpler.  The prepare phase is to truncate unnecessary
 * blocks after the logical EOF, and the cleanup phase does normal heap
 * vacuum on auxiliary relations (toast, aoseg, block directory, visimap,)
 * as well as updating stats info in catalog.  Keep in mind that if the
 * vacuum is full, we need the same two steps as the heap base relation
 * case.  So cleanup phase in AO may consume two transactions.
 *
 * While executing these multiple transactions, we acquire a session
 * lock across transactions, in order to keep concurrent work on the
 * same relation away.  It doesn't look intuitive, though, if you look
 * at QE work, because from its perspective it is always one step, therefore
 * there is no session lock technically (we actually acquire and release
 * it as it's harmless.)  Session lock doesn't work here, because QE
 * is under a distributed transaction and we haven't supported session
 * lock recording in transaction prepare.  This should be ok as far as
 * we are dealing with user table, because other MPP work also tries
 * to take a relation lock, which would conflict with this vacuum work
 * on master.  Be careful with catalog tables, because we take locks on
 * them and release soon much before the end of transaction.  That means
 * QE still needs to deal with concurrent work well.
 */
static void
632 633
vacuumStatement_Relation(VacuumStmt *vacstmt, Oid relid,
						 List *relations, BufferAccessStrategy bstrategy,
634
						 bool do_toast, bool for_wraparound, bool isTopLevel)
635 636
{
	LOCKMODE			lmode = NoLock;
637
	Relation			onerel;
638
	LockRelId			onerelid;
639 640 641
	MemoryContext oldcontext;

	oldcontext = MemoryContextSwitchTo(vac_context);
642

643
	vacstmt = copyObject(vacstmt);
644 645 646 647
	/* VACUUM, without ANALYZE */
	vacstmt->options &= ~VACOPT_ANALYZE;
	vacstmt->options |= VACOPT_VACUUM;
	vacstmt->va_cols = NIL;		/* A plain VACUUM cannot list columns */
648

649
	MemoryContextSwitchTo(oldcontext);
650

651
	/*
652 653 654 655 656 657
	 * For each iteration we start/commit our own transactions,
	 * so that we can release resources such as locks and memories,
	 * and we can also safely perform non-transactional work
	 * along with transactional work. If we are a query executor and skipping
	 * a two phase commit, the expectation is that we will vacuum one relation
	 * per dispatch, so we can use the outer transaction for this instead.
658
	 */
659 660
	if (Gp_role != GP_ROLE_EXECUTE || !vacstmt->skip_twophase)
		StartTransactionCommand();
661

662 663 664 665 666
	/*
	 * Functions in indexes may want a snapshot set. Also, setting
	 * a snapshot ensures that RecentGlobalXmin is kept truly recent.
	 */
	PushActiveSnapshot(GetTransactionSnapshot());
667

668
	/*
669 670 671 672
	 * Determine the type of lock we want --- hard exclusive lock for a FULL
	 * vacuum, but just ShareUpdateExclusiveLock for concurrent vacuum. Either
	 * way, we can be sure that no other backend is vacuuming the same table.
	 * For analyze, we use ShareUpdateExclusiveLock.
673
	 */
674 675 676 677
	if (vacstmt->appendonly_phase == AOVAC_DROP)
	{
		Assert(Gp_role == GP_ROLE_EXECUTE);
		lmode = AccessExclusiveLock;
678
		SIMPLE_FAULT_INJECTOR(VacuumRelationOpenRelationDuringDropPhase);
679 680 681 682 683
	}
	else if (!(vacstmt->options & VACOPT_VACUUM))
		lmode = ShareUpdateExclusiveLock;
	else
		lmode = (vacstmt->options & VACOPT_FULL) ? AccessExclusiveLock : ShareUpdateExclusiveLock;
684

685
	/*
686 687 688 689
	 * Open the relation and get the appropriate lock on it.
	 *
	 * There's a race condition here: the rel may have gone away since the
	 * last time we saw it.  If so, we don't need to vacuum it.
690
	 */
691 692 693 694 695 696 697
	onerel = try_relation_open(relid, lmode, false /* dontwait */);
	if (!onerel)
	{
		PopActiveSnapshot();
		CommitTransactionCommand();
		return;
	}
698

699
	/*
700 701 702 703 704 705 706 707
	 * Check permissions.
	 *
	 * We allow the user to vacuum a table if he is superuser, the table
	 * owner, or the database owner (but in the latter case, only if it's not
	 * a shared relation).	pg_class_ownercheck includes the superuser case.
	 *
	 * Note we choose to treat permissions failure as a WARNING and keep
	 * trying to vacuum the rest of the DB --- is this appropriate?
708
	 */
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
	if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
		  (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
	{
		if (Gp_role != GP_ROLE_EXECUTE)
		{
			if (onerel->rd_rel->relisshared)
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only superuser can vacuum it",
								RelationGetRelationName(onerel))));
			else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only superuser or database owner can vacuum it",
								RelationGetRelationName(onerel))));
			else
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only table or database owner can vacuum it",
								RelationGetRelationName(onerel))));
		}
		relation_close(onerel, lmode);
		PopActiveSnapshot();
		CommitTransactionCommand();
		return;
	}
732

733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
	/*
	 * Get a session-level lock too. This will protect our access to the
	 * relation across multiple transactions, so that we can vacuum the
	 * relation's TOAST table (if any) secure in the knowledge that no one is
	 * deleting the parent relation.
	 *
	 * NOTE: this cannot block, even if someone else is waiting for access,
	 * because the lock manager knows that both lock requests are from the
	 * same process.
	 */
	onerelid = onerel->rd_lockInfo.lockRelId;
	LockRelationIdForSession(&onerelid, lmode);

	oldcontext = MemoryContextSwitchTo(vac_context);
	vacuumStatement_AssignRelation(vacstmt, relid, relations);
	MemoryContextSwitchTo(oldcontext);

	if (RelationIsHeap(onerel) || Gp_role == GP_ROLE_EXECUTE)
751
	{
752 753 754
		/* skip two-phase commit on heap table VACUUM */
		if (Gp_role == GP_ROLE_DISPATCH)
			vacstmt->skip_twophase = true;
755

756
		if (vacstmt->appendonly_phase == AOVAC_DROP)
757
		{
758
			SIMPLE_FAULT_INJECTOR(VacuumRelationOpenRelationDuringDropPhase);
759 760
		}

761 762 763 764 765 766 767 768 769 770 771 772
		vacuum_rel(onerel, relid, vacstmt, lmode, for_wraparound);
		onerel = NULL;
	}
	else
	{
		List	   *compactedSegmentFileList = NIL;
		List	   *insertedSegmentFileList = NIL;

		vacstmt->appendonly_compaction_segno = NIL;
		vacstmt->appendonly_compaction_insert_segno = NIL;
		vacstmt->appendonly_relation_empty = false;
		vacstmt->skip_twophase = false;
773

774
		/*
775
		 * 1. Prepare phase
776
		 */
777 778 779 780 781
		vacuum_rel_ao_phase(onerel, relid, vacstmt, lmode, for_wraparound,
							NIL,
							NIL,
							AOVAC_PREPARE);
		onerel = NULL;
782

783
		/*
784 785
		 * Loop between compaction and drop phases, until there is nothing more left
		 * to do for this relation.
786
		 */
787
		for (;;)
788
		{
789 790
			List	   *compactNowList = NIL;
			int			insertSegNo = -1;
791

792
			if (gp_appendonly_compaction)
793 794
			{
				/*
795
				 * 2. Compaction phase
796
				 */
797 798 799 800 801 802 803 804 805 806
				StartTransactionCommand();
				PushActiveSnapshot(GetTransactionSnapshot());
				onerel = try_relation_open(relid, lmode, false /* dontwait */);

				/* Chose a source and destination segfile for compaction. */
				if (!vacuum_assign_compaction_segno(onerel,
													compactedSegmentFileList,
													insertedSegmentFileList,
													&compactNowList,
													&insertSegNo))
807
				{
808 809 810 811 812
					/*
					 * There is nothing left to do for this relation. Proceed to
					 * the cleanup phase.
					 */
					break;
813
				}
814

815
				oldcontext = MemoryContextSwitchTo(vac_context);
816

817
				compactNowList = list_copy(compactNowList);
818

819 820 821 822
				compactedSegmentFileList =
					list_union_int(compactedSegmentFileList, compactNowList);
				insertedSegmentFileList =
					lappend_int(insertedSegmentFileList, insertSegNo);
823

824 825 826 827 828 829 830
				MemoryContextSwitchTo(oldcontext);

				vacuum_rel_ao_phase(onerel, relid, vacstmt, lmode, for_wraparound,
									list_make1_int(insertSegNo),
									compactNowList,
									AOVAC_COMPACT);
				onerel = NULL;
831
			}
832 833

			/*
834
			 * 3. Drop phase
835 836
			 */

837 838
			StartTransactionCommand();
			PushActiveSnapshot(GetTransactionSnapshot());
839 840

			/*
J
Jimmy Yih 已提交
841 842 843 844 845 846
			 * Upgrade to AccessExclusiveLock from SharedAccessExclusive here
			 * before doing the drops. We set the dontwait flag here to
			 * prevent deadlock scenarios such as a concurrent transaction
			 * holding AccessShareLock and then upgrading to ExclusiveLock to
			 * run DELETE/UPDATE while VACUUM is waiting here for
			 * AccessExclusiveLock.
847
			 *
J
Jimmy Yih 已提交
848 849 850 851 852
			 * Skipping when we are not able to upgrade to AccessExclusivelock
			 * can be an issue though because it is possible to accumulate a
			 * large amount of segfiles marked AOSEG_STATE_AWAITING_DROP.
			 * However, we do not expect this to happen too frequently such
			 * that all segfiles are marked.
853
			 */
J
Jimmy Yih 已提交
854 855
			SIMPLE_FAULT_INJECTOR(VacuumRelationOpenRelationDuringDropPhase);
			onerel = try_relation_open(relid, AccessExclusiveLock, true /* dontwait */);
856

J
Jimmy Yih 已提交
857
			if (!RelationIsValid(onerel))
858
			{
859
				/* Couldn't get AccessExclusiveLock. */
860 861 862 863
				PopActiveSnapshot();
				CommitTransactionCommand();

				/*
J
Jimmy Yih 已提交
864 865 866
				 * Skip performing DROP and continue with other segfiles in
				 * case they have crossed threshold and need to be compacted
				 * or marked as AOSEG_STATE_AWAITING_DROP. To ensure that
867 868 869 870
				 * vacuum decreases the age for appendonly tables even if drop
				 * phase is getting skipped, perform cleanup phase when done
				 * iterating through all segfiles so that the relfrozenxid
				 * value is updated correctly in pg_class.
871
				 */
872
				continue;
873
			}
874

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
			if (HasSerializableBackends(false))
			{
				/*
				 * Checking at this point is safe because
				 * any serializable transaction that could start afterwards
				 * will already see the state with AWAITING_DROP. We
				 * have only to deal with transactions that started before
				 * our transaction.
				 *
				 * We immediatelly get the next relation. There is no
				 * reason to stay in this relation. Actually, all
				 * other ao relation will skip the compaction step.
				 */
				elogif(Debug_appendonly_print_compaction, LOG,
					   "Skipping freeing compacted append-only segment file "
					   "because of concurrent serializable transaction");
891

892 893 894
				DeregisterSegnoForCompactionDrop(relid, compactNowList);
				break;
			}
895

896 897 898
			elogif(Debug_appendonly_print_compaction, LOG,
				   "Dispatch drop transaction on append-only relation %s",
				   RelationGetRelationName(onerel));
899

900 901 902 903 904 905 906 907 908 909 910 911
			/* Perform the DROP phase */
			RegisterSegnoForCompactionDrop(relid, compactNowList);

			vacuum_rel_ao_phase(onerel, relid, vacstmt, lmode, for_wraparound,
								NIL,	/* insert segno */
								compactNowList,
								AOVAC_DROP);
			onerel = NULL;

			if (!gp_appendonly_compaction)
				break;
		}
912

913
		/*
914 915 916 917 918 919
		 * 4. Cleanup phase.
		 *
		 * This vacuums all the auxiliary tables, like TOAST, AO segment tables etc.
		 *
		 * We can skip this, if we didn't compact anything. XXX: Really? Shouldn't we
		 * still process the aux tables?
920
		 */
921
		if (list_length(compactedSegmentFileList) > 0)
922
		{
923 924 925 926 927 928
			/* Provide the list of all compacted segment numbers with it */
			vacuum_rel_ao_phase(onerel, relid, vacstmt, lmode, for_wraparound,
								insertedSegmentFileList,
								compactedSegmentFileList,
								AOVAC_CLEANUP);
			onerel = NULL;
929 930 931 932 933 934 935 936
		}
	}

	if (lmode != NoLock)
	{
		UnlockRelationIdForSession(&onerelid, lmode);
	}

937
	if (Gp_role == GP_ROLE_DISPATCH)
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
		/*
		 * We need some transaction to update the catalog.  We could do
		 * it on the outer vacuumStatement, but it is useful to track
		 * relation by relation.
		 */
		//if (!istemp) // FIXME
		{
			char *vsubtype = ""; /* NOFULL */
			bool		start_xact = false;

			if (!onerel)
			{
				StartTransactionCommand();
				start_xact = true;
			}

			if (IsAutoVacuumWorkerProcess())
				vsubtype = "AUTO";
			else
			{
				if ((vacstmt->options & VACOPT_FULL) &&
					(0 == vacstmt->freeze_min_age))
					vsubtype = "FULL FREEZE";
				else if ((vacstmt->options & VACOPT_FULL))
					vsubtype = "FULL";
				else if (0 == vacstmt->freeze_min_age)
					vsubtype = "FREEZE";
			}
			MetaTrackUpdObject(RelationRelationId,
							   relid,
							   GetUserId(),
							   "VACUUM",
							   vsubtype);
			if (start_xact)
				CommitTransactionCommand();
		}
975
	}
976 977

	if (onerel)
978
	{
979 980 981
		relation_close(onerel, NoLock);
		PopActiveSnapshot();
		CommitTransactionCommand();
982 983 984
	}
}

985
/*
986
 * Build a list of Oids for each relation to be processed
987 988 989
 *
 * The list is built in vac_context so that it will survive across our
 * per-relation transactions.
A
Asim R P 已提交
990 991 992 993 994
 *
 * 'stmttype' is either VACOPT_VACUUM or VACOPT_ANALYZE, to indicate
 * whether we should fetch the list for VACUUM or ANALYZE. It's
 * passed as a separate argument, so that the caller can build
 * separate lists for a combined "VACUUM ANALYZE".
995
 */
996
static List *
A
Asim R P 已提交
997
get_rel_oids(Oid relid, VacuumStmt *vacstmt, int stmttype)
998
{
N
Neil Conway 已提交
999
	List	   *oid_list = NIL;
1000 1001
	MemoryContext oldcontext;

A
Asim R P 已提交
1002 1003
	Assert(stmttype == VACOPT_VACUUM || stmttype == VACOPT_ANALYZE);

1004 1005 1006 1007 1008 1009 1010 1011
	/* OID supplied by VACUUM's caller? */
	if (OidIsValid(relid))
	{
		oldcontext = MemoryContextSwitchTo(vac_context);
		oid_list = lappend_oid(oid_list, relid);
		MemoryContextSwitchTo(oldcontext);
	}
	else if (vacstmt->relation)
1012
	{
A
Asim R P 已提交
1013
		if (stmttype == VACOPT_VACUUM)
1014 1015 1016 1017
		{
			/* Process a specific relation */
			Oid			relid;
			List	   *prels = NIL;
1018

R
Richard Guo 已提交
1019 1020 1021 1022
			/*
			 * Since we don't take a lock here, the relation might be gone, or the
			 * RangeVar might no longer refer to the OID we look up here.  In the
			 * former case, VACUUM will do nothing; in the latter case, it will
1023 1024 1025 1026
			 * process the OID we looked up here, rather than the new one. Neither
			 * is ideal, but there's little practical alternative, since we're
			 * going to commit this transaction and begin a new one between now
			 * and then.
A
Asim R P 已提交
1027
			 */
R
Richard Guo 已提交
1028
			relid = RangeVarGetRelid(vacstmt->relation, NoLock, false);
1029

1030 1031 1032 1033 1034
			if (rel_is_partitioned(relid))
			{
				PartitionNode *pn;

				pn = get_parts(relid, 0, 0, false, true /*includesubparts*/);
1035

1036 1037 1038 1039 1040
				prels = all_partition_relids(pn);
			}
			else if (rel_is_child_partition(relid))
			{
				/* get my children */
1041
				prels = find_all_inheritors(relid, NoLock, NULL);
1042
			}
1043

1044 1045 1046 1047 1048
			/* Make a relation list entry for this relation */
			oldcontext = MemoryContextSwitchTo(vac_context);
			oid_list = lappend_oid(oid_list, relid);
			oid_list = list_concat_unique_oid(oid_list, prels);
			MemoryContextSwitchTo(oldcontext);
1049
		}
1050
		else
1051
		{
1052 1053 1054 1055 1056 1057
			oldcontext = MemoryContextSwitchTo(vac_context);
			/**
			 * ANALYZE one relation (optionally, a list of columns).
			 */
			Oid relationOid = InvalidOid;

R
Richard Guo 已提交
1058
			relationOid = RangeVarGetRelid(vacstmt->relation, NoLock, false);
1059
			PartStatus ps = rel_part_status(relationOid);
1060

1061
			if (ps != PART_STATUS_ROOT && (vacstmt->options & VACOPT_ROOTONLY))
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
			{
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- cannot analyze a non-root partition using ANALYZE ROOTPARTITION",
								get_rel_name(relationOid))));
			}
			else if (ps == PART_STATUS_ROOT)
			{
				PartitionNode *pn = get_parts(relationOid, 0 /*level*/ ,
											  0 /*parent*/, false /* inctemplate */, true /*includesubparts*/);
				Assert(pn);
1072
				if (!(vacstmt->options & VACOPT_ROOTONLY))
1073 1074
				{
					oid_list = all_leaf_partition_relids(pn); /* all leaves */
1075 1076 1077 1078 1079

					if (optimizer_analyze_midlevel_partition)
					{
						oid_list = list_concat(oid_list, all_interior_partition_relids(pn)); /* interior partitions */
					}
1080
				}
1081 1082
				if (optimizer_analyze_root_partition || (vacstmt->options & VACOPT_ROOTONLY))
					oid_list = lappend_oid(oid_list, relationOid); /* root partition */
1083
			}
1084 1085 1086 1087
			else if (ps == PART_STATUS_LEAF)
			{
				Oid root_rel_oid = rel_partition_get_master(relationOid);
				oid_list = list_make1_oid(relationOid);
O
Omer Arap 已提交
1088 1089

				List *va_root_attnums = NIL;
1090 1091
				if (vacstmt->va_cols != NIL)
				{
O
Omer Arap 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
					ListCell *lc;
					int i;
					foreach(lc, vacstmt->va_cols)
					{
						char	   *col = strVal(lfirst(lc));

						i = get_attnum(root_rel_oid, col);
						if (i == InvalidAttrNumber)
							ereport(ERROR,
									(errcode(ERRCODE_UNDEFINED_COLUMN),
									 errmsg("column \"%s\" of relation \"%s\" does not exist",
											col, get_rel_name(root_rel_oid))));
						va_root_attnums = lappend_int(va_root_attnums, i);
					}
1106 1107 1108
				}
				else
				{
O
Omer Arap 已提交
1109
					Relation onerel = RelationIdGetRelation(root_rel_oid);
1110 1111 1112 1113 1114 1115
					int attr_cnt = onerel->rd_att->natts;
					for (int i = 1; i <= attr_cnt; i++)
					{
						Form_pg_attribute attr = onerel->rd_att->attrs[i-1];
						if (attr->attisdropped)
							continue;
O
Omer Arap 已提交
1116
						va_root_attnums = lappend_int(va_root_attnums, i);
1117 1118 1119
					}
					RelationClose(onerel);
				}
1120 1121
				if (optimizer_analyze_root_partition || (vacstmt->options & VACOPT_ROOTONLY))
				{
1122 1123 1124
					int		elevel = ((vacstmt->options & VACOPT_VERBOSE) ? LOG : DEBUG2);

					if (leaf_parts_analyzed(root_rel_oid, relationOid, va_root_attnums, elevel))
1125 1126
						oid_list = lappend_oid(oid_list, root_rel_oid);
				}
1127
			}
1128 1129 1130 1131 1132 1133
			else if (ps == PART_STATUS_INTERIOR) /* analyze an interior partition directly */
			{
				/* disable analyzing mid-level partitions directly since the users are encouraged
				 * to work with the root partition only. To gather stats on mid-level partitions
				 * (for Orca's use), the user should run ANALYZE or ANALYZE ROOTPARTITION on the
				 * root level with optimizer_analyze_midlevel_partition GUC set to ON.
D
Daniel Gustafsson 已提交
1134
				 * Planner uses the stats on leaf partitions, so it's unnecessary to collect stats on
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
				 * midlevel partitions.
				 */
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- cannot analyze a mid-level partition. "
								"Please run ANALYZE on the root partition table.",
								get_rel_name(relationOid))));
			}
			else
			{
				oid_list = list_make1_oid(relationOid);
			}
			MemoryContextSwitchTo(oldcontext);
		}
1148 1149 1150
	}
	else
	{
1151 1152 1153 1154
		/*
		 * Process all plain relations and materialized views listed in
		 * pg_class
		 */
1155 1156
		Relation	pgclass;
		HeapScanDesc scan;
1157
		HeapTuple	tuple;
1158
		Oid candidateOid;
1159
		List	   *rootParts = NIL;
1160 1161 1162

		pgclass = heap_open(RelationRelationId, AccessShareLock);

1163
		scan = heap_beginscan_catalog(pgclass, 0, NULL);
1164 1165

		while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
1166 1167
		{
			Form_pg_class classForm = (Form_pg_class) GETSTRUCT(tuple);
1168

1169 1170 1171 1172 1173 1174
			/*
			 * Don't include non-vacuum-able relations:
			 *   - External tables
			 *   - Foreign tables
			 *   - etc.
			 */
1175 1176 1177 1178 1179 1180
			if (classForm->relkind != RELKIND_RELATION &&
				classForm->relkind != RELKIND_MATVIEW)
				continue;
			if (classForm->relstorage == RELSTORAGE_EXTERNAL ||
				classForm->relstorage == RELSTORAGE_FOREIGN  ||
				classForm->relstorage == RELSTORAGE_VIRTUAL)
1181
				continue;
1182

1183
			/* Make a relation list entry for this guy */
1184 1185 1186
			candidateOid = HeapTupleGetOid(tuple);

			/* Skip non root partition tables if ANALYZE ROOTPARTITION ALL is executed */
1187
			if ((vacstmt->options & VACOPT_ROOTONLY) && !rel_is_partitioned(candidateOid))
1188 1189 1190
			{
				continue;
			}
1191 1192 1193 1194 1195 1196 1197 1198

			// skip mid-level partition tables if we have disabled collecting statistics for them
			PartStatus ps = rel_part_status(candidateOid);
			if (!optimizer_analyze_midlevel_partition && ps == PART_STATUS_INTERIOR)
			{
				continue;
			}

1199 1200 1201 1202 1203 1204
			// Likewise, skip root partition, if disabled.
			if (!optimizer_analyze_root_partition && (vacstmt->options & VACOPT_ROOTONLY) == 0 && ps == PART_STATUS_ROOT)
			{
				continue;
			}

1205
			oldcontext = MemoryContextSwitchTo(vac_context);
1206 1207 1208 1209
			if (ps == PART_STATUS_ROOT)
				rootParts = lappend_oid(rootParts, candidateOid);
			else
				oid_list = lappend_oid(oid_list, candidateOid);
1210
			MemoryContextSwitchTo(oldcontext);
1211
		}
1212

1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
		/*
		 * Schedule the root partitions to be analyzed after all the leaves.
		 * A root partition can often be analyzed by combining the HLL
		 * counters from all the leaves, which is much cheaper than scanning
		 * the whole partitioned table, but that only works if the leaves
		 * have already been analyzed.
		 */
		oldcontext = MemoryContextSwitchTo(vac_context);
		oid_list = list_concat(oid_list, rootParts);
		MemoryContextSwitchTo(oldcontext);

1224 1225
		heap_endscan(scan);
		heap_close(pgclass, AccessShareLock);
1226 1227
	}

N
Neil Conway 已提交
1228
	return oid_list;
1229 1230
}

1231 1232
/*
 * vacuum_set_xid_limits() -- compute oldest-Xmin and freeze cutoff points
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
 *
 * The output parameters are:
 * - oldestXmin is the cutoff value used to distinguish whether tuples are
 *	 DEAD or RECENTLY_DEAD (see HeapTupleSatisfiesVacuum).
 * - freezeLimit is the Xid below which all Xids are replaced by
 *	 FrozenTransactionId during vacuum.
 * - xidFullScanLimit (computed from table_freeze_age parameter)
 *	 represents a minimum Xid value; a table whose relfrozenxid is older than
 *	 this will have a full-table vacuum applied to it, to freeze tuples across
 *	 the whole table.  Vacuuming a table younger than this value can use a
 *	 partial scan.
 * - multiXactCutoff is the value below which all MultiXactIds are removed from
 *	 Xmax.
 * - mxactFullScanLimit is a value against which a table's relminmxid value is
 *	 compared to produce a full-table vacuum, as with xidFullScanLimit.
 *
 * xidFullScanLimit and mxactFullScanLimit can be passed as NULL if caller is
 * not interested.
1251 1252
 */
void
1253 1254
vacuum_set_xid_limits(Relation rel,
					  int freeze_min_age,
1255
					  int freeze_table_age,
1256 1257
					  int multixact_freeze_min_age,
					  int multixact_freeze_table_age,
1258
					  TransactionId *oldestXmin,
1259
					  TransactionId *freezeLimit,
1260 1261 1262
					  TransactionId *xidFullScanLimit,
					  MultiXactId *multiXactCutoff,
					  MultiXactId *mxactFullScanLimit)
1263
{
1264
	int			freezemin;
1265
	int			mxid_freezemin;
1266
	int			effective_multixact_freeze_max_age;
1267
	TransactionId limit;
1268
	TransactionId safeLimit;
1269 1270
	MultiXactId mxactLimit;
	MultiXactId safeMxactLimit;
1271

1272
	/*
1273
	 * We can always ignore processes running lazy vacuum.  This is because we
1274
	 * use these values only for deciding which tuples we must keep in the
1275
	 * tables.  Since lazy vacuum doesn't write its XID anywhere, it's safe to
1276
	 * ignore it.  In theory it could be problematic to ignore lazy vacuums in
1277 1278 1279
	 * a full vacuum, but keep in mind that only one vacuum process can be
	 * working on a particular table at any time, and that each vacuum is
	 * always an independent transaction.
1280
	 */
1281
	*oldestXmin = GetOldestXmin(rel, true);
1282 1283 1284

	Assert(TransactionIdIsNormal(*oldestXmin));

1285
	/*
1286 1287
	 * Determine the minimum freeze age to use: as specified by the caller, or
	 * vacuum_freeze_min_age, but in any case not more than half
1288 1289 1290
	 * autovacuum_freeze_max_age, so that autovacuums to prevent XID
	 * wraparound won't occur too frequently.
	 */
1291
	freezemin = freeze_min_age;
1292 1293 1294 1295
	if (freezemin < 0)
		freezemin = vacuum_freeze_min_age;
	freezemin = Min(freezemin, autovacuum_freeze_max_age / 2);
	Assert(freezemin >= 0);
1296

1297
	/*
1298
	 * Compute the cutoff XID, being careful not to generate a "permanent" XID
1299
	 */
1300
	limit = *oldestXmin - freezemin;
1301 1302 1303
	if (!TransactionIdIsNormal(limit))
		limit = FirstNormalTransactionId;

1304
	/*
1305
	 * If oldestXmin is very far back (in practice, more than
1306 1307
	 * autovacuum_freeze_max_age / 2 XIDs old), complain and force a minimum
	 * freeze age of zero.
1308
	 */
1309 1310 1311 1312 1313
	safeLimit = ReadNewTransactionId() - autovacuum_freeze_max_age;
	if (!TransactionIdIsNormal(safeLimit))
		safeLimit = FirstNormalTransactionId;

	if (TransactionIdPrecedes(limit, safeLimit))
1314
	{
1315
		ereport(WARNING,
1316
				(errmsg("oldest xmin is far in the past"),
1317
				 errhint("Close open transactions soon to avoid wraparound problems.")));
1318 1319 1320 1321
		limit = *oldestXmin;
	}

	*freezeLimit = limit;
1322

1323 1324 1325 1326 1327 1328 1329
	/*
	 * Compute the multixact age for which freezing is urgent.  This is
	 * normally autovacuum_multixact_freeze_max_age, but may be less if we
	 * are short of multixact member space.
	 */
	effective_multixact_freeze_max_age = MultiXactMemberFreezeThreshold();

1330 1331 1332
	/*
	 * Determine the minimum multixact freeze age to use: as specified by
	 * caller, or vacuum_multixact_freeze_min_age, but in any case not more
1333
	 * than half effective_multixact_freeze_max_age, so that autovacuums to
1334 1335 1336 1337 1338 1339
	 * prevent MultiXact wraparound won't occur too frequently.
	 */
	mxid_freezemin = multixact_freeze_min_age;
	if (mxid_freezemin < 0)
		mxid_freezemin = vacuum_multixact_freeze_min_age;
	mxid_freezemin = Min(mxid_freezemin,
1340
						 effective_multixact_freeze_max_age / 2);
1341 1342 1343 1344 1345 1346 1347 1348
	Assert(mxid_freezemin >= 0);

	/* compute the cutoff multi, being careful to generate a valid value */
	mxactLimit = GetOldestMultiXactId() - mxid_freezemin;
	if (mxactLimit < FirstMultiXactId)
		mxactLimit = FirstMultiXactId;

	safeMxactLimit =
1349
		ReadNextMultiXactId() - effective_multixact_freeze_max_age;
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
	if (safeMxactLimit < FirstMultiXactId)
		safeMxactLimit = FirstMultiXactId;

	if (MultiXactIdPrecedes(mxactLimit, safeMxactLimit))
	{
		ereport(WARNING,
				(errmsg("oldest multixact is far in the past"),
				 errhint("Close open transactions with multixacts soon to avoid wraparound problems.")));
		mxactLimit = safeMxactLimit;
	}

	*multiXactCutoff = mxactLimit;

	if (xidFullScanLimit != NULL)
1364 1365 1366
	{
		int			freezetable;

1367
		Assert(mxactFullScanLimit != NULL);
1368

1369 1370 1371 1372 1373 1374 1375
		/*
		 * Determine the table freeze age to use: as specified by the caller,
		 * or vacuum_freeze_table_age, but in any case not more than
		 * autovacuum_freeze_max_age * 0.95, so that if you have e.g nightly
		 * VACUUM schedule, the nightly VACUUM gets a chance to freeze tuples
		 * before anti-wraparound autovacuum is launched.
		 */
1376
		freezetable = freeze_table_age;
1377 1378 1379 1380 1381 1382
		if (freezetable < 0)
			freezetable = vacuum_freeze_table_age;
		freezetable = Min(freezetable, autovacuum_freeze_max_age * 0.95);
		Assert(freezetable >= 0);

		/*
1383 1384
		 * Compute XID limit causing a full-table vacuum, being careful not to
		 * generate a "permanent" XID.
1385 1386 1387 1388 1389
		 */
		limit = ReadNewTransactionId() - freezetable;
		if (!TransactionIdIsNormal(limit))
			limit = FirstNormalTransactionId;

1390
		*xidFullScanLimit = limit;
1391

1392
		/*
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
		 * Similar to the above, determine the table freeze age to use for
		 * multixacts: as specified by the caller, or
		 * vacuum_multixact_freeze_table_age, but in any case not more than
		 * autovacuum_multixact_freeze_table_age * 0.95, so that if you have
		 * e.g. nightly VACUUM schedule, the nightly VACUUM gets a chance to
		 * freeze multixacts before anti-wraparound autovacuum is launched.
		 */
		freezetable = multixact_freeze_table_age;
		if (freezetable < 0)
			freezetable = vacuum_multixact_freeze_table_age;
		freezetable = Min(freezetable,
1404
						  effective_multixact_freeze_max_age * 0.95);
1405
		Assert(freezetable >= 0);
1406 1407

		/*
1408 1409
		 * Compute MultiXact limit causing a full-table vacuum, being careful
		 * to generate a valid MultiXact value.
1410
		 */
1411 1412 1413
		mxactLimit = ReadNextMultiXactId() - freezetable;
		if (mxactLimit < FirstMultiXactId)
			mxactLimit = FirstMultiXactId;
1414

1415
		*mxactFullScanLimit = mxactLimit;
1416
	}
1417 1418 1419
	else
	{
		Assert(mxactFullScanLimit == NULL);
1420 1421
	}
}
1422 1423 1424 1425 1426

/*
 * vac_estimate_reltuples() -- estimate the new value for pg_class.reltuples
 *
 *		If we scanned the whole relation then we should just use the count of
1427 1428 1429 1430
 *		live tuples seen; but if we did not, we should not blindly extrapolate
 *		from that number, since VACUUM may have scanned a quite nonrandom
 *		subset of the table.  When we have only partial information, we take
 *		the old value of pg_class.reltuples as a measurement of the
1431 1432
 *		tuple density in the unscanned pages.
 *
1433
 *		The is_analyze argument is historical.
1434 1435 1436 1437 1438 1439 1440
 */
double
vac_estimate_reltuples(Relation relation, bool is_analyze,
					   BlockNumber total_pages,
					   BlockNumber scanned_pages,
					   double scanned_tuples)
{
B
Bruce Momjian 已提交
1441
	BlockNumber old_rel_pages = relation->rd_rel->relpages;
1442 1443
	double		old_rel_tuples = relation->rd_rel->reltuples;
	double		old_density;
1444 1445
	double		unscanned_pages;
	double		total_tuples;
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468

	/* If we did scan the whole table, just use the count as-is */
	if (scanned_pages >= total_pages)
		return scanned_tuples;

	/*
	 * If scanned_pages is zero but total_pages isn't, keep the existing value
	 * of reltuples.  (Note: callers should avoid updating the pg_class
	 * statistics in this situation, since no new information has been
	 * provided.)
	 */
	if (scanned_pages == 0)
		return old_rel_tuples;

	/*
	 * If old value of relpages is zero, old density is indeterminate; we
	 * can't do much except scale up scanned_tuples to match total_pages.
	 */
	if (old_rel_pages == 0)
		return floor((scanned_tuples / scanned_pages) * total_pages + 0.5);

	/*
	 * Okay, we've covered the corner cases.  The normal calculation is to
1469 1470 1471
	 * convert the old measurement to a density (tuples per page), then
	 * estimate the number of tuples in the unscanned pages using that figure,
	 * and finally add on the number of tuples in the scanned pages.
1472 1473
	 */
	old_density = old_rel_tuples / old_rel_pages;
1474 1475 1476
	unscanned_pages = (double) total_pages - (double) scanned_pages;
	total_tuples = old_density * unscanned_pages + scanned_tuples;
	return floor(total_tuples + 0.5);
1477 1478 1479
}


1480 1481 1482 1483 1484
/*
 * Update relpages/reltuples of all the relations in the list.
 */
static void
vac_update_relstats_from_list(List *updated_stats)
H
Heikki Linnakangas 已提交
1485
{
1486 1487
	ListCell *lc;

1488 1489 1490 1491 1492 1493
	/*
	 * This function is only called in the context of the QD, so let's be
	 * explicit about that given the assumptions taken.
	 */
	Assert(Gp_role == GP_ROLE_DISPATCH);

1494
	foreach (lc, updated_stats)
H
Heikki Linnakangas 已提交
1495
	{
1496 1497 1498 1499
		VPgClassStats *stats = (VPgClassStats *) lfirst(lc);
		Relation	rel;

		rel = relation_open(stats->relid, AccessShareLock);
H
Heikki Linnakangas 已提交
1500

P
Pengzhou Tang 已提交
1501 1502
		if (GpPolicyIsReplicated(rel->rd_cdbpolicy))
		{
1503 1504 1505
			stats->rel_pages = stats->rel_pages / rel->rd_cdbpolicy->numsegments;
			stats->rel_tuples = stats->rel_tuples / rel->rd_cdbpolicy->numsegments;
			stats->relallvisible = stats->relallvisible / rel->rd_cdbpolicy->numsegments;
P
Pengzhou Tang 已提交
1506 1507
		}

1508 1509 1510 1511 1512 1513
		/*
		 * Pass 'false' for isvacuum, so that the stats are
		 * actually updated.
		 */
		vac_update_relstats(rel,
							stats->rel_pages, stats->rel_tuples,
R
Richard Guo 已提交
1514
							stats->relallvisible,
1515 1516 1517
							rel->rd_rel->relhasindex,
							InvalidTransactionId,
							InvalidMultiXactId,
1518
							false,
1519 1520 1521
							false /* isvacuum */);
		relation_close(rel, AccessShareLock);
	}
H
Heikki Linnakangas 已提交
1522
}
1523

1524
/*
1525
 *	vac_update_relstats() -- update statistics for one relation
1526
 *
1527 1528 1529 1530 1531
 *		Update the whole-relation statistics that are kept in its pg_class
 *		row.  There are additional stats that will be updated if we are
 *		doing ANALYZE, but we always update these stats.  This routine works
 *		for both index and heap relation entries in pg_class.
 *
1532 1533
 *		We violate transaction semantics here by overwriting the rel's
 *		existing pg_class tuple with the new values.  This is reasonably
1534 1535 1536 1537 1538 1539
 *		safe as long as we're sure that the new values are correct whether or
 *		not this transaction commits.  The reason for doing this is that if
 *		we updated these tuples in the usual way, vacuuming pg_class itself
 *		wouldn't work very well --- by the time we got done with a vacuum
 *		cycle, most of the tuples in pg_class would've been obsoleted.  Of
 *		course, this only works for fixed-size not-null columns, but these are.
1540
 *
1541
 *		Another reason for doing it this way is that when we are in a lazy
1542 1543
 *		VACUUM and have PROC_IN_VACUUM set, we mustn't do any regular updates.
 *		Somebody vacuuming pg_class might think they could delete a tuple
1544
 *		marked with xmin = our xid.
1545
 *
1546 1547 1548 1549 1550
 *		In addition to fundamentally nontransactional statistics such as
 *		relpages and relallvisible, we try to maintain certain lazily-updated
 *		DDL flags such as relhasindex, by clearing them if no longer correct.
 *		It's safe to do this in VACUUM, which can't run in parallel with
 *		CREATE INDEX/RULE/TRIGGER and can't be part of a transaction block.
1551 1552
 *		However, it's *not* safe to do it in an ANALYZE that's within an
 *		outer transaction, because for example the current transaction might
1553 1554
 *		have dropped the last index; then we'd think relhasindex should be
 *		cleared, but if the transaction later rolls back this would be wrong.
1555 1556 1557
 *		So we refrain from updating the DDL flags if we're inside an outer
 *		transaction.  This is OK since postponing the flag maintenance is
 *		always allowable.
1558
 *
1559
 *		This routine is shared by VACUUM and ANALYZE.
1560 1561
 */
void
1562 1563
vac_update_relstats(Relation relation,
					BlockNumber num_pages, double num_tuples,
1564
					BlockNumber num_all_visible_pages,
1565
					bool hasindex, TransactionId frozenxid,
1566
					MultiXactId minmulti,
1567 1568
					bool in_outer_xact,
					bool isvacuum)
1569
{
1570
	Oid			relid = RelationGetRelid(relation);
1571 1572 1573
	Relation	rd;
	HeapTuple	ctup;
	Form_pg_class pgcform;
1574
	bool		dirty;
1575 1576 1577 1578

	Assert(relid != InvalidOid);

	/*
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
	 * In GPDB, all the data is stored in the segments, and the
	 * relpages/reltuples in the master reflect the sum of the values in
	 * all the segments. In VACUUM, don't overwrite relpages/reltuples with
	 * the values we counted in the QD node itself. We will dispatch the
	 * VACUUM to the segments after processing the QD node, and we will
	 * update relpages/reltuples then.
	 *
	 * Update stats for system tables normally, though (it'd better say
	 * "non-distributed" tables than system relations here, but for now
	 * it's effectively the same.)
1589
	 */
1590
	if (!IsSystemRelation(relation) && isvacuum)
1591
	{
1592 1593 1594 1595
		if (Gp_role == GP_ROLE_DISPATCH)
		{
			num_pages = relation->rd_rel->relpages;
			num_tuples = relation->rd_rel->reltuples;
R
Richard Guo 已提交
1596
			num_all_visible_pages = relation->rd_rel->relallvisible;
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
		}
		else if (Gp_role == GP_ROLE_EXECUTE)
		{
			/*
			 * CDB: Build a special message, to send the number of tuples
			 * and the number of pages in pg_class located at QEs through
			 * the dispatcher.
			 */
			StringInfoData buf;
			VPgClassStats stats;

			pq_beginmessage(&buf, 'y');
			pq_sendstring(&buf, "VACUUM");
			stats.relid = RelationGetRelid(relation);
			stats.rel_pages = num_pages;
			stats.rel_tuples = num_tuples;
R
Richard Guo 已提交
1613
			stats.relallvisible = num_all_visible_pages;
1614 1615 1616 1617
			pq_sendint(&buf, sizeof(VPgClassStats), sizeof(int));
			pq_sendbytes(&buf, (char *) &stats, sizeof(VPgClassStats));
			pq_endmessage(&buf);
		}
1618
	}
1619

1620 1621 1622 1623 1624 1625 1626 1627
	/*
	 * We need a way to distinguish these 2 cases:
	 * a) ANALYZEd/VACUUMed table is empty
	 * b) Table has never been ANALYZEd/VACUUMed
	 * To do this, in case (a), we set relPages = 1. For case (b), relPages = 0.
	 */
	if (num_pages < 1.0)
	{
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
		/*
		 * When running in utility mode in the QD node, we get the number of
		 * tuples of an AO table from the pg_aoseg table, but we don't know
		 * the file size, so that's always 0. Ignore the tuple count we got,
		 * and set reltuples to 0 instead, to avoid storing a confusing
		 * combination, and to avoid hitting the Assert below (which we
		 * inherited from upstream).
		 *
		 * It's perhaps not such a great idea to overwrite perfectly good
		 * relpages/reltuples estimates in utility mode, but that's what we
		 * do for heap tables, too, because we don't have even a tuple count
		 * for them. At least this is consistent.
		 */
		if (num_tuples >= 1.0)
		{
			Assert(Gp_role == GP_ROLE_UTILITY);
			Assert(!IsSystemRelation(relation));
			Assert(RelationIsAppendOptimized(relation));
			num_tuples = 0;
		}

1649 1650 1651 1652 1653 1654 1655
		Assert(num_tuples < 1.0);
		num_pages = 1.0;
	}

	/*
	 * update number of tuples and number of pages in pg_class
	 */
1656
	rd = heap_open(RelationRelationId, RowExclusiveLock);
1657

1658
	/* Fetch a copy of the tuple to scribble on */
1659
	ctup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
1660 1661 1662
	if (!HeapTupleIsValid(ctup))
		elog(ERROR, "pg_class entry for relid %u vanished during vacuuming",
			 relid);
1663
	pgcform = (Form_pg_class) GETSTRUCT(ctup);
1664

1665
	/* Apply statistical updates, if any, to copied tuple */
1666

1667 1668 1669 1670 1671 1672
	/* GPDB-specific not allow change relpages and reltuples when vacuum in utility mode on QD
	 * Because there's a chance that we overwrite perfectly good stats with zeros
	 */

	bool ifUpdate = ! (IS_QUERY_DISPATCHER() && Gp_role == GP_ROLE_UTILITY);

1673
	dirty = false;
1674
	if (pgcform->relpages != (int32) num_pages && ifUpdate)
1675 1676 1677 1678
	{
		pgcform->relpages = (int32) num_pages;
		dirty = true;
	}
1679
	if (pgcform->reltuples != (float4) num_tuples && ifUpdate)
1680 1681 1682 1683
	{
		pgcform->reltuples = (float4) num_tuples;
		dirty = true;
	}
1684 1685 1686 1687 1688
	if (pgcform->relallvisible != (int32) num_all_visible_pages)
	{
		pgcform->relallvisible = (int32) num_all_visible_pages;
		dirty = true;
	}
B
Bruce Momjian 已提交
1689

1690 1691
	elog(DEBUG2, "Vacuum oid=%u pages=%d tuples=%f",
		 relid, pgcform->relpages, pgcform->reltuples);
1692
	/*
1693
	 * If we have discovered that there are no indexes, then there's no
B
Bruce Momjian 已提交
1694
	 * primary key either.  This could be done more thoroughly...
1695
	 */
1696
	if (pgcform->relhaspkey && !hasindex)
1697
	{
1698 1699
		pgcform->relhaspkey = false;
		dirty = true;
1700
	}
1701

1702
	if (!in_outer_xact)
1703
	{
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
		/*
		 * If we didn't find any indexes, reset relhasindex.
		 */
		if (pgcform->relhasindex && !hasindex)
		{
			pgcform->relhasindex = false;
			dirty = true;
		}

		/*
		 * If we have discovered that there are no indexes, then there's no
		 * primary key either.  This could be done more thoroughly...
		 */
		if (pgcform->relhaspkey && !hasindex)
		{
			pgcform->relhaspkey = false;
			dirty = true;
		}

		/* We also clear relhasrules and relhastriggers if needed */
		if (pgcform->relhasrules && relation->rd_rules == NULL)
		{
			pgcform->relhasrules = false;
			dirty = true;
		}
		if (pgcform->relhastriggers && relation->trigdesc == NULL)
		{
			pgcform->relhastriggers = false;
			dirty = true;
		}
1734 1735
	}

1736
	/*
1737 1738 1739 1740 1741 1742 1743 1744 1745
	 * Update relfrozenxid, unless caller passed InvalidTransactionId
	 * indicating it has no new data.
	 *
	 * Ordinarily, we don't let relfrozenxid go backwards: if things are
	 * working correctly, the only way the new frozenxid could be older would
	 * be if a previous VACUUM was done with a tighter freeze_min_age, in
	 * which case we don't want to forget the work it already did.  However,
	 * if the stored relfrozenxid is "in the future", then it must be corrupt
	 * and it seems best to overwrite it with the cutoff we used this time.
1746 1747
	 * This should match vac_update_datfrozenxid() concerning what we consider
	 * to be "in the future".
1748 1749
	 */
	if (TransactionIdIsNormal(frozenxid) &&
1750
		TransactionIdIsValid(pgcform->relfrozenxid) &&
1751 1752
		pgcform->relfrozenxid != frozenxid &&
		(TransactionIdPrecedes(pgcform->relfrozenxid, frozenxid) ||
1753
		 TransactionIdPrecedes(ReadNewTransactionId(),
1754
							   pgcform->relfrozenxid)))
1755
	{
1756
		pgcform->relfrozenxid = frozenxid;
1757 1758
		dirty = true;
	}
1759

1760
	/* Similarly for relminmxid */
1761
	if (MultiXactIdIsValid(minmulti) &&
1762 1763
		pgcform->relminmxid != minmulti &&
		(MultiXactIdPrecedes(pgcform->relminmxid, minmulti) ||
1764
		 MultiXactIdPrecedes(ReadNextMultiXactId(), pgcform->relminmxid)))
1765 1766 1767 1768 1769
	{
		pgcform->relminmxid = minmulti;
		dirty = true;
	}

1770
	/* If anything changed, write out the tuple. */
1771 1772
	if (dirty)
		heap_inplace_update(rd, ctup);
1773 1774 1775 1776 1777

	heap_close(rd, RowExclusiveLock);
}


1778
/*
1779
 *	vac_update_datfrozenxid() -- update pg_database.datfrozenxid for our DB
1780
 *
1781
 *		Update pg_database's datfrozenxid entry for our database to be the
1782 1783
 *		minimum of the pg_class.relfrozenxid values.
 *
1784 1785
 *		Similarly, update our datminmxid to be the minimum of the
 *		pg_class.relminmxid values.
1786 1787 1788
 *
 *		If we are able to advance either pg_database value, also try to
 *		truncate pg_clog and pg_multixact.
1789
 *
1790
 *		We violate transaction semantics here by overwriting the database's
1791 1792
 *		existing pg_database tuple with the new values.  This is reasonably
 *		safe since the new values are correct whether or not this transaction
1793 1794
 *		commits.  As with vac_update_relstats, this avoids leaving dead tuples
 *		behind after a VACUUM.
1795
 */
1796 1797
void
vac_update_datfrozenxid(void)
1798 1799 1800
{
	HeapTuple	tuple;
	Form_pg_database dbform;
1801
	Relation	relation;
1802
	SysScanDesc scan;
1803
	HeapTuple	classTup;
1804
	TransactionId newFrozenXid;
1805
	MultiXactId newMinMulti;
1806
	TransactionId lastSaneFrozenXid;
1807 1808
	MultiXactId lastSaneMinMulti;
	bool		bogus = false;
1809 1810
	bool		dirty = false;

1811
	/*
1812 1813 1814
	 * Initialize the "min" calculation with GetOldestXmin, which is a
	 * reasonable approximation to the minimum relfrozenxid for not-yet-
	 * committed pg_class entries for new tables; see AddNewRelationTuple().
1815
	 * So we cannot produce a wrong minimum by starting with this.
1816 1817 1818 1819 1820 1821
	 *
	 * GPDB: Use GetLocalOldestXmin here, rather than GetOldestXmin. We don't
	 * want to include effects of distributed transactions in this. If a
	 * database's datfrozenxid is past the oldest XID as determined by
	 * distributed transactions, we will nevertheless never encounter such
	 * XIDs on disk.
1822
	 */
1823
	newFrozenXid = GetLocalOldestXmin(NULL, true);
1824

1825
	/*
B
Bruce Momjian 已提交
1826 1827
	 * Similarly, initialize the MultiXact "min" with the value that would be
	 * used on pg_class for new tables.  See AddNewRelationTuple().
1828
	 */
1829
	newMinMulti = GetOldestMultiXactId();
1830

1831 1832 1833 1834 1835 1836 1837
	/*
	 * Identify the latest relfrozenxid and relminmxid values that we could
	 * validly see during the scan.  These are conservative values, but it's
	 * not really worth trying to be more exact.
	 */
	lastSaneFrozenXid = ReadNewTransactionId();
	lastSaneMinMulti = ReadNextMultiXactId();
1838

B
Bruce Momjian 已提交
1839 1840 1841
	/*
	 * We must seqscan pg_class to find the minimum Xid, because there is no
	 * index that can help us here.
1842
	 */
1843 1844 1845
	relation = heap_open(RelationRelationId, AccessShareLock);

	scan = systable_beginscan(relation, InvalidOid, false,
1846
							  NULL, 0, NULL);
1847

1848
	while ((classTup = systable_getnext(scan)) != NULL)
1849
	{
1850
		Form_pg_class classForm = (Form_pg_class) GETSTRUCT(classTup);
1851

1852
#if 0
1853
		/*
1854 1855
		 * Only consider relations able to hold unfrozen XIDs (anything else
		 * should have InvalidTransactionId in relfrozenxid anyway.)
1856 1857
		 */
		if (classForm->relkind != RELKIND_RELATION &&
1858
			classForm->relkind != RELKIND_MATVIEW &&
1859 1860
			classForm->relkind != RELKIND_TOASTVALUE)
			continue;
1861 1862 1863
#endif

		/* GPDB_94_MERGE_FIXME: We have had this check here, instead of the above
D
Daniel Gustafsson 已提交
1864
		 * check that upstream has. I would be more comfortable if we would list
1865 1866
		 * the relkinds here explicitly, like in upstream..
		 */
1867
		if (!TransactionIdIsValid(classForm->relfrozenxid))
1868 1869
			continue;

1870
		Assert(TransactionIdIsNormal(classForm->relfrozenxid));
1871
		Assert(MultiXactIdIsValid(classForm->relminmxid));
1872 1873 1874 1875 1876 1877
		/*
		 * Don't know partition parent or not here but passing false is perfect
		 * for assertion, as valid relfrozenxid means it shouldn't be parent.
		 */
		Assert(should_have_valid_relfrozenxid(classForm->relkind,
											  classForm->relstorage, false));
1878

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
		/*
		 * If things are working properly, no relation should have a
		 * relfrozenxid or relminmxid that is "in the future".  However, such
		 * cases have been known to arise due to bugs in pg_upgrade.  If we
		 * see any entries that are "in the future", chicken out and don't do
		 * anything.  This ensures we won't truncate clog before those
		 * relations have been scanned and cleaned up.
		 */
		if (TransactionIdPrecedes(lastSaneFrozenXid, classForm->relfrozenxid) ||
			MultiXactIdPrecedes(lastSaneMinMulti, classForm->relminmxid))
		{
			bogus = true;
			break;
		}

1894 1895
		if (TransactionIdPrecedes(classForm->relfrozenxid, newFrozenXid))
			newFrozenXid = classForm->relfrozenxid;
1896

1897 1898
		if (MultiXactIdPrecedes(classForm->relminmxid, newMinMulti))
			newMinMulti = classForm->relminmxid;
1899
	}
1900

1901
	/* we're done with pg_class */
1902 1903
	systable_endscan(scan);
	heap_close(relation, AccessShareLock);
1904

1905 1906 1907 1908
	/* chicken out if bogus data found */
	if (bogus)
		return;

1909
	Assert(TransactionIdIsNormal(newFrozenXid));
1910
	Assert(MultiXactIdIsValid(newMinMulti));
1911 1912

	/* Now fetch the pg_database tuple we need to update. */
1913
	relation = heap_open(DatabaseRelationId, RowExclusiveLock);
1914

1915
	/* Fetch a copy of the tuple to scribble on */
1916
	tuple = SearchSysCacheCopy1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
1917
	if (!HeapTupleIsValid(tuple))
1918
		elog(ERROR, "could not find tuple for database %u", MyDatabaseId);
1919 1920
	dbform = (Form_pg_database) GETSTRUCT(tuple);

1921
	/*
1922 1923 1924
	 * As in vac_update_relstats(), we ordinarily don't want to let
	 * datfrozenxid go backward; but if it's "in the future" then it must be
	 * corrupt and it seems best to overwrite it.
1925
	 */
1926 1927 1928
	if (dbform->datfrozenxid != newFrozenXid &&
		(TransactionIdPrecedes(dbform->datfrozenxid, newFrozenXid) ||
		 TransactionIdPrecedes(lastSaneFrozenXid, dbform->datfrozenxid)))
1929
	{
1930
		dbform->datfrozenxid = newFrozenXid;
1931 1932
		dirty = true;
	}
1933 1934
	else
		newFrozenXid = dbform->datfrozenxid;
1935

1936 1937 1938 1939
	/* Ditto for datminmxid */
	if (dbform->datminmxid != newMinMulti &&
		(MultiXactIdPrecedes(dbform->datminmxid, newMinMulti) ||
		 MultiXactIdPrecedes(lastSaneMinMulti, dbform->datminmxid)))
1940
	{
1941
		dbform->datminmxid = newMinMulti;
1942 1943
		dirty = true;
	}
1944 1945
	else
		newMinMulti = dbform->datminmxid;
1946

1947
	if (dirty)
1948
	{
1949
		heap_inplace_update(relation, tuple);
1950 1951
		SIMPLE_FAULT_INJECTOR(VacuumUpdateDatFrozenXid);
	}
1952

1953
	heap_freetuple(tuple);
1954
	heap_close(relation, RowExclusiveLock);
1955

1956
	/*
1957 1958 1959
	 * If we were able to advance datfrozenxid or datminmxid, see if we can
	 * truncate pg_clog and/or pg_multixact.  Also do it if the shared
	 * XID-wrap-limit info is stale, since this action will update that too.
1960
	 */
1961
	if (dirty || ForceTransactionIdLimitUpdate())
1962 1963
		vac_truncate_clog(newFrozenXid, newMinMulti,
						  lastSaneFrozenXid, lastSaneMinMulti);
1964 1965 1966 1967 1968 1969
}


/*
 *	vac_truncate_clog() -- attempt to truncate the commit log
 *
1970
 *		Scan pg_database to determine the system-wide oldest datfrozenxid,
1971
 *		and use it to truncate the transaction commit log (pg_clog).
1972
 *		Also update the XID wrap limit info maintained by varsup.c.
1973
 *		Likewise for datminmxid.
1974
 *
1975 1976 1977 1978
 *		The passed frozenXID and minMulti are the updated values for my own
 *		pg_database entry. They're used to initialize the "min" calculations.
 *		The caller also passes the "last sane" XID and MXID, since it has
 *		those at hand already.
1979
 *
A
Alvaro Herrera 已提交
1980
 *		This routine is only invoked when we've managed to change our
1981 1982
 *		DB's datfrozenxid/datminmxid values, or we found that the shared
 *		XID-wrap-limit info is stale.
1983 1984
 */
static void
1985 1986 1987 1988
vac_truncate_clog(TransactionId frozenXID,
				  MultiXactId minMulti,
				  TransactionId lastSaneFrozenXid,
				  MultiXactId lastSaneMinMulti)
1989
{
1990
	TransactionId nextXID = ReadNewTransactionId();
1991 1992
	Relation	relation;
	HeapScanDesc scan;
1993
	HeapTuple	tuple;
1994
	Oid			oldestxid_datoid;
1995
	Oid			minmulti_datoid;
1996
	bool		bogus = false;
1997
	bool		frozenAlreadyWrapped = false;
1998

1999
	/* init oldest datoids to sync with my frozenXID/minMulti values */
2000
	oldestxid_datoid = MyDatabaseId;
2001
	minmulti_datoid = MyDatabaseId;
2002 2003

	/*
2004
	 * Scan pg_database to compute the minimum datfrozenxid/datminmxid
2005
	 *
2006 2007 2008 2009 2010
	 * Since vac_update_datfrozenxid updates datfrozenxid/datminmxid in-place,
	 * the values could change while we look at them.  Fetch each one just
	 * once to ensure sane behavior of the comparison logic.  (Here, as in
	 * many other places, we assume that fetching or updating an XID in shared
	 * storage is atomic.)
2011 2012 2013 2014 2015
	 *
	 * Note: we need not worry about a race condition with new entries being
	 * inserted by CREATE DATABASE.  Any such entry will have a copy of some
	 * existing DB's datfrozenxid, and that source DB cannot be ours because
	 * of the interlock against copying a DB containing an active backend.
2016 2017 2018 2019
	 * Hence the new entry will not reduce the minimum.  Also, if two VACUUMs
	 * concurrently modify the datfrozenxid's of different databases, the
	 * worst possible outcome is that pg_clog is not truncated as aggressively
	 * as it could be.
2020
	 */
2021 2022
	relation = heap_open(DatabaseRelationId, AccessShareLock);

2023
	scan = heap_beginscan_catalog(relation, 0, NULL);
2024

2025
	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
2026
	{
2027 2028 2029
		volatile FormData_pg_database *dbform = (Form_pg_database) GETSTRUCT(tuple);
		TransactionId datfrozenxid = dbform->datfrozenxid;
		TransactionId datminmxid = dbform->datminmxid;
2030

2031 2032
		Assert(TransactionIdIsNormal(datfrozenxid));
		Assert(MultiXactIdIsValid(datminmxid));
2033

2034 2035 2036 2037 2038 2039 2040 2041 2042
		/*
		 * If things are working properly, no database should have a
		 * datfrozenxid or datminmxid that is "in the future".  However, such
		 * cases have been known to arise due to bugs in pg_upgrade.  If we
		 * see any entries that are "in the future", chicken out and don't do
		 * anything.  This ensures we won't truncate clog before those
		 * databases have been scanned and cleaned up.  (We will issue the
		 * "already wrapped" warning if appropriate, though.)
		 */
2043 2044
		if (TransactionIdPrecedes(lastSaneFrozenXid, datfrozenxid) ||
			MultiXactIdPrecedes(lastSaneMinMulti, datminmxid))
2045
			bogus = true;
2046

2047
		if (TransactionIdPrecedes(nextXID, datfrozenxid))
2048
			frozenAlreadyWrapped = true;
2049
		else if (TransactionIdPrecedes(datfrozenxid, frozenXID))
2050
		{
2051
			frozenXID = datfrozenxid;
2052 2053 2054
			oldestxid_datoid = HeapTupleGetOid(tuple);
		}

2055
		if (MultiXactIdPrecedes(datminmxid, minMulti))
2056
		{
2057
			minMulti = datminmxid;
2058
			minmulti_datoid = HeapTupleGetOid(tuple);
2059 2060 2061
		}
	}

2062 2063 2064
	heap_endscan(scan);

	heap_close(relation, AccessShareLock);
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075

	/*
	 * Do not truncate CLOG if we seem to have suffered wraparound already;
	 * the computed minimum XID might be bogus.  This case should now be
	 * impossible due to the defenses in GetNewTransactionId, but we keep the
	 * test anyway.
	 */
	if (frozenAlreadyWrapped)
	{
		ereport(WARNING,
				(errmsg("some databases have not been vacuumed in over 2 billion transactions"),
2076
				 errdetail("You might have already suffered transaction-wraparound data loss.")));
2077 2078 2079
		return;
	}

2080 2081 2082 2083
	/* chicken out if data is bogus in any other way */
	if (bogus)
		return;

2084 2085 2086 2087
	/*
	 * Truncate CLOG to the oldest computed value.  Note we don't truncate
	 * multixacts; that will be done by the next checkpoint.
	 */
2088 2089 2090
	TruncateCLOG(frozenXID);

	/*
2091
	 * Update the wrap limit for GetNewTransactionId and creation of new
B
Bruce Momjian 已提交
2092
	 * MultiXactIds.  Note: these functions will also signal the postmaster
B
Bruce Momjian 已提交
2093
	 * for an(other) autovac cycle if needed.   XXX should we avoid possibly
2094
	 * signalling twice?
2095
	 */
2096
	SetTransactionIdLimit(frozenXID, oldestxid_datoid);
2097
	SetMultiXactIdLimit(minMulti, minmulti_datoid);
2098 2099
}

2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
static void
vacuum_rel_ao_phase(Relation onerel, Oid relid, VacuumStmt *vacstmt, LOCKMODE lmode,
					bool for_wraparound,
					List *compaction_insert_segno,
					List *compaction_segno,
					AOVacuumPhase phase)
{
	vacstmt->appendonly_compaction_insert_segno = compaction_insert_segno;
	vacstmt->appendonly_compaction_segno = compaction_segno;
	vacstmt->appendonly_phase = phase;
2110

2111 2112
	vacuum_rel(onerel, relid, vacstmt, lmode, for_wraparound);
}
2113

2114

2115 2116 2117 2118
/*
 *	vacuum_rel() -- vacuum one heap relation
 *
 *		Doing one heap at a time incurs extra overhead, since we need to
B
Bruce Momjian 已提交
2119
 *		check that the heap exists again just before we vacuum it.  The
2120 2121 2122
 *		reason that we do this is so that vacuuming can be spread across
 *		many small transactions.  Otherwise, two-phase locking would require
 *		us to lock the entire database during one pass of the vacuum cleaner.
2123
 *
2124 2125 2126 2127
 * GPDB: On entry, we should already hold a session-level lock on the table.
 * If 'onerel' is valid, then we should also hold an appropriate regular lock on
 * the table, and have a transaction open.
 * On exit, the 'onere' will be closed, and the transaction is closed.
2128
 */
2129
static bool
2130
vacuum_rel(Relation onerel, Oid relid, VacuumStmt *vacstmt, LOCKMODE lmode,
2131
		   bool for_wraparound)
2132 2133 2134 2135 2136
{
	Oid			toast_relid;
	Oid			aoseg_relid = InvalidOid;
	Oid         aoblkdir_relid = InvalidOid;
	Oid         aovisimap_relid = InvalidOid;
2137 2138 2139 2140 2141
	RangeVar	*toast_rangevar = NULL;
	RangeVar	*aoseg_rangevar = NULL;
	RangeVar	*aoblkdir_rangevar = NULL;
	RangeVar	*aovisimap_rangevar = NULL;
	bool		is_heap;
2142 2143 2144
	Oid			save_userid;
	int			save_sec_context;
	int			save_nestlevel;
2145
	MemoryContext oldcontext;
2146

2147
	if (!onerel)
2148
	{
2149
		/*
2150 2151 2152 2153
		 * For each iteration we start/commit our own transactions,
		 * so that we can release resources such as locks and memories,
		 * and we can also safely perform non-transactional work
		 * along with transactional work.
2154
		 */
2155
		StartTransactionCommand();
2156

2157 2158 2159 2160 2161
		/*
		 * Functions in indexes may want a snapshot set. Also, setting
		 * a snapshot ensures that RecentGlobalXmin is kept truly recent.
		 */
		PushActiveSnapshot(GetTransactionSnapshot());
2162

2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194
		if (!(vacstmt->options & VACOPT_FULL))
		{
			/*
			 * PostgreSQL does this:
			 * During a lazy VACUUM we can set the PROC_IN_VACUUM flag, which lets other
			 * concurrent VACUUMs know that they can ignore this one while
			 * determining their OldestXmin.  (The reason we don't set it during a
			 * full VACUUM is exactly that we may have to run user- defined
			 * functions for functional indexes, and we want to make sure that if
			 * they use the snapshot set above, any tuples it requires can't get
			 * removed from other tables.  An index function that depends on the
			 * contents of other tables is arguably broken, but we won't break it
			 * here by violating transaction semantics.)
			 *
			 * GPDB doesn't use PROC_IN_VACUUM, as lazy vacuum for bitmap
			 * indexed tables performs reindex causing updates to pg_class
			 * tuples for index entries.
			 *
			 * We also set the VACUUM_FOR_WRAPAROUND flag, which is passed down
			 * by autovacuum; it's used to avoid cancelling a vacuum that was
			 * invoked in an emergency.
			 *
			 * Note: this flag remains set until CommitTransaction or
			 * AbortTransaction.  We don't want to clear it until we reset
			 * MyProc->xid/xmin, else OldestXmin might appear to go backwards,
			 * which is probably Not Good.
			 */
			LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
#if 0 /* Upstream code not applicable to GPDB */
			MyProc->vacuumFlags |= PROC_IN_VACUUM;
#endif
			if (for_wraparound)
R
Richard Guo 已提交
2195
				MyPgXact->vacuumFlags |= PROC_VACUUM_FOR_WRAPAROUND;
2196 2197
			LWLockRelease(ProcArrayLock);
		}
2198

2199
		/*
2200
		 * Check for user-requested abort.  Note we want this to be inside a
2201 2202 2203
		 * transaction, so xact.c doesn't issue useless WARNING.
		 */
		CHECK_FOR_INTERRUPTS();
2204

2205 2206 2207 2208 2209
		/*
		 * Open the relation and get the appropriate lock on it.
		 *
		 * There's a race condition here: the rel may have gone away since the
		 * last time we saw it.  If so, we don't need to vacuum it.
A
Asim R P 已提交
2210 2211 2212
		 *
		 * If we've been asked not to wait for the relation lock, acquire it first
		 * in non-blocking mode, before calling try_relation_open().
2213
		 */
A
Asim R P 已提交
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
		if (!(vacstmt->options & VACOPT_NOWAIT))
			onerel = try_relation_open(relid, lmode, false /* nowait */);
		else if (ConditionalLockRelationOid(relid, lmode))
			onerel = try_relation_open(relid, NoLock, false /* nowait */);
		else
		{
			onerel = NULL;
			if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
				ereport(LOG,
						(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
						 errmsg("skipping vacuum of \"%s\" --- lock not available",
								vacstmt->relation->relname)));
		}
2227 2228 2229 2230 2231

		if (!onerel)
		{
			PopActiveSnapshot();
			CommitTransactionCommand();
A
Asim R P 已提交
2232
			return false;
2233
		}
2234 2235 2236 2237
	}

	/*
	 * Check permissions.
2238
	 *
2239 2240
	 * We allow the user to vacuum a table if he is superuser, the table
	 * owner, or the database owner (but in the latter case, only if it's not
B
Bruce Momjian 已提交
2241
	 * a shared relation).  pg_class_ownercheck includes the superuser case.
2242
	 *
2243 2244
	 * Note we choose to treat permissions failure as a WARNING and keep
	 * trying to vacuum the rest of the DB --- is this appropriate?
2245
	 */
2246
	if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
2247
		  (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
2248
	{
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
		if (Gp_role != GP_ROLE_EXECUTE)
		{
			if (onerel->rd_rel->relisshared)
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only superuser can vacuum it",
								RelationGetRelationName(onerel))));
			else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only superuser or database owner can vacuum it",
								RelationGetRelationName(onerel))));
			else
				ereport(WARNING,
						(errmsg("skipping \"%s\" --- only table or database owner can vacuum it",
								RelationGetRelationName(onerel))));
		}
2264
		relation_close(onerel, lmode);
2265
		PopActiveSnapshot();
2266
		CommitTransactionCommand();
2267
		return false;
2268 2269 2270
	}

	/*
2271
	 * Check that it's a vacuumable relation; we used to do this in
2272 2273
	 * get_rel_oids() but seems safer to check after we've locked the
	 * relation.
2274
	 */
2275
	if ((onerel->rd_rel->relkind != RELKIND_RELATION &&
2276
		 onerel->rd_rel->relkind != RELKIND_MATVIEW &&
2277 2278 2279 2280 2281
		 onerel->rd_rel->relkind != RELKIND_TOASTVALUE &&
		 onerel->rd_rel->relkind != RELKIND_AOSEGMENTS &&
		 onerel->rd_rel->relkind != RELKIND_AOBLOCKDIR &&
		 onerel->rd_rel->relkind != RELKIND_AOVISIMAP)
		|| RelationIsExternal(onerel))
2282
	{
2283
		ereport(WARNING,
R
Robert Haas 已提交
2284
				(errmsg("skipping \"%s\" --- cannot vacuum non-tables or special system tables",
2285
						RelationGetRelationName(onerel))));
2286
		relation_close(onerel, lmode);
2287
		PopActiveSnapshot();
2288
		CommitTransactionCommand();
2289
		return false;
2290 2291
	}

2292 2293 2294 2295 2296 2297 2298
	/*
	 * Silently ignore tables that are temp tables of other backends ---
	 * trying to vacuum these will lead to great unhappiness, since their
	 * contents are probably not up-to-date on disk.  (We don't throw a
	 * warning here; it would just lead to chatter during a database-wide
	 * VACUUM.)
	 */
2299 2300 2301 2302 2303
	if (isOtherTempNamespace(RelationGetNamespace(onerel)))
	{
		relation_close(onerel, lmode);
		PopActiveSnapshot();
		CommitTransactionCommand();
A
Asim R P 已提交
2304
		return false;
2305
	}
2306

2307
	/*
2308
	 * Remember the relation's TOAST and AO segments relations for later
2309
	 */
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
	toast_relid = onerel->rd_rel->reltoastrelid;
	is_heap = RelationIsHeap(onerel);
	oldcontext = MemoryContextSwitchTo(vac_context);
	toast_rangevar = makeRangeVar(get_namespace_name(get_rel_namespace(toast_relid)),
								  get_rel_name(toast_relid),
								  -1);
	MemoryContextSwitchTo(oldcontext);


	if (!is_heap)
	{
2321
		Assert(RelationIsAppendOptimized(onerel));
2322
		GetAppendOnlyEntryAuxOids(RelationGetRelid(onerel), NULL,
2323
								  &aoseg_relid,
2324 2325
								  &aoblkdir_relid, NULL,
								  &aovisimap_relid, NULL);
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
		oldcontext = MemoryContextSwitchTo(vac_context);
		aoseg_rangevar = makeRangeVar(get_namespace_name(get_rel_namespace(aoseg_relid)),
									  get_rel_name(aoseg_relid),
									  -1);
		aoblkdir_rangevar = makeRangeVar(get_namespace_name(get_rel_namespace(aoblkdir_relid)),
										 get_rel_name(aoblkdir_relid),
										 -1);
		aovisimap_rangevar = makeRangeVar(get_namespace_name(get_rel_namespace(aovisimap_relid)),
										  get_rel_name(aovisimap_relid),
										  -1);
		MemoryContextSwitchTo(oldcontext);
2337 2338 2339 2340 2341 2342 2343
		vacstmt->appendonly_relation_empty =
				AppendOnlyCompaction_IsRelationEmpty(onerel);
	}

	/*
	 * Switch to the table owner's userid, so that any index functions are run
	 * as that user.  Also lock down security-restricted operations and
2344
	 * arrange to make GUC variable changes local to this command.
2345 2346 2347 2348 2349 2350
	 */
	GetUserIdAndSecContext(&save_userid, &save_sec_context);
	SetUserIdAndSecContext(onerel->rd_rel->relowner,
						   save_sec_context | SECURITY_RESTRICTED_OPERATION);
	save_nestlevel = NewGUCNestLevel();

2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384

	/*
	 * If we are in the dispatch mode, dispatch this modified
	 * vacuum statement to QEs, and wait for them to finish.
	 */
	if (Gp_role == GP_ROLE_DISPATCH)
	{
		int 		i, nindexes;
		bool 		has_bitmap = false;
		Relation   *i_rel = NULL;

		vac_open_indexes(onerel, AccessShareLock, &nindexes, &i_rel);
		if (i_rel != NULL)
		{
			for (i = 0; i < nindexes; i++)
			{
				if (RelationIsBitmapIndex(i_rel[i]))
				{
					has_bitmap = true;
					break;
				}
			}
		}
		vac_close_indexes(nindexes, i_rel, AccessShareLock);

		/*
		 * We have to acquire a ShareLock for the relation which has bitmap
		 * indexes, since reindex is used later. Otherwise, concurrent
		 * vacuum and inserts may cause deadlock. MPP-5960
		 */
		if (has_bitmap)
			LockRelation(onerel, ShareLock);
	}

2385 2386
	/*
	 * Do the actual work --- either FULL or "lazy" vacuum
2387 2388 2389 2390 2391 2392
	 *
	 * Append-only relations don't support, nor need, a FULL vacuum, so perform
	 * a lazy vacuum instead, even if FULL was requested. Note that we have
	 * already locked the table, and if FULL was requested, we got an
	 * AccessExclusiveLock. Therefore, FULL isn't exactly the same as non-FULL
	 * on AO tables.
2393
	 */
2394
	if (is_heap && (vacstmt->options & VACOPT_FULL))
2395
	{
2396 2397
		Oid			relid = RelationGetRelid(onerel);

2398
		/* close relation before vacuuming, but hold lock until commit */
2399 2400 2401
		relation_close(onerel, NoLock);
		onerel = NULL;

2402
		/* VACUUM FULL is now a variant of CLUSTER; see cluster.c */
2403
		cluster_rel(relid, InvalidOid, false,
2404
					(vacstmt->options & VACOPT_VERBOSE) != 0,
2405
					true /* printError */);
2406 2407 2408 2409 2410 2411

		if (Gp_role == GP_ROLE_DISPATCH)
		{
			VacuumStatsContext stats_context;

			stats_context.updated_stats = NIL;
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
			/*
			 * Revert back to original userid before dispatching vacuum to QEs.
			 * Dispatcher includes CurrentUserId in the serialized dispatch
			 * command (see buildGpQueryString()).  QEs assume this userid
			 * before starting to execute the dispatched command.  If the
			 * original userid has superuser privileges and owner of the table
			 * being vacuumed does not, and if the command is dispatched with
			 * owner's userid, it may lead to spurious permission denied error
			 * on QE even when a super user is running the vacuum.
			 */
			SetUserIdAndSecContext(
								   save_userid,
								   save_sec_context | SECURITY_RESTRICTED_OPERATION);
2425
			dispatchVacuum(vacstmt, &stats_context);
2426 2427

			vac_update_relstats_from_list(stats_context.updated_stats);
2428
		}
2429
	}
2430
	else
2431 2432 2433 2434 2435 2436 2437 2438
	{
		lazy_vacuum_rel(onerel, vacstmt, vac_strategy);

		if (Gp_role == GP_ROLE_DISPATCH)
		{
			VacuumStatsContext stats_context;

			stats_context.updated_stats = NIL;
2439 2440 2441
			SetUserIdAndSecContext(
								   save_userid,
								   save_sec_context | SECURITY_RESTRICTED_OPERATION);
2442 2443 2444 2445
			dispatchVacuum(vacstmt, &stats_context);
			vac_update_relstats_from_list(stats_context.updated_stats);
		}
	}
2446 2447 2448 2449 2450 2451 2452

	/* Roll back any GUC changes executed by index functions */
	AtEOXact_GUC(false, save_nestlevel);

	/* Restore userid and security context */
	SetUserIdAndSecContext(save_userid, save_sec_context);

2453
	/*
2454 2455
	 * Update ao master tupcount the hard way after the compaction and
	 * after the drop.
2456
	 */
2457
	if (Gp_role == GP_ROLE_DISPATCH && vacstmt->appendonly_compaction_segno &&
2458
		RelationIsAppendOptimized(onerel))
2459
	{
2460 2461
		Snapshot	appendOnlyMetaDataSnapshot = RegisterSnapshot(GetCatalogSnapshot(InvalidOid));

2462 2463 2464 2465 2466 2467 2468 2469 2470
		if (vacstmt->appendonly_phase == AOVAC_COMPACT)
		{
			/* In the compact phase, we need to update the information of the segment file we inserted into */
			if (list_length(vacstmt->appendonly_compaction_insert_segno) == 1 &&
				linitial_int(vacstmt->appendonly_compaction_insert_segno) == APPENDONLY_COMPACTION_SEGNO_INVALID)
			{
				/* this was a "pseudo" compaction phase. */
			}
			else
2471
				UpdateMasterAosegTotalsFromSegments(onerel, appendOnlyMetaDataSnapshot, vacstmt->appendonly_compaction_insert_segno, 0);
2472 2473 2474 2475
		}
		else if (vacstmt->appendonly_phase == AOVAC_DROP)
		{
			/* In the drop phase, we need to update the information of the compacted segment file(s) */
2476
			UpdateMasterAosegTotalsFromSegments(onerel, appendOnlyMetaDataSnapshot, vacstmt->appendonly_compaction_segno, 0);
2477
		}
2478 2479

		UnregisterSnapshot(appendOnlyMetaDataSnapshot);
2480 2481
	}

2482
	/* all done with this class, but hold lock until commit */
2483 2484
	if (onerel)
		relation_close(onerel, NoLock);
2485

2486 2487 2488
	/*
	 * Complete the transaction and free all temporary memory used.
	 */
2489
	PopActiveSnapshot();
2490 2491 2492 2493 2494
	/*
	 * Transaction commit is always executed on QD.
	 */
	if (Gp_role != GP_ROLE_EXECUTE)
		CommitTransactionCommand();
2495

2496
	/*
2497 2498 2499 2500
	 * If the relation has a secondary toast rel, vacuum that too while we
	 * still hold the session lock on the master table.  We do this in
	 * cleanup phase when it's AO table or in prepare phase if it's an
	 * empty AO table.
2501 2502 2503 2504 2505
	 *
	 * A VacuumStmt object for secondary toast relation is constructed and
	 * dispatched separately by the QD, when vacuuming the master relation.  A
	 * backend executing dispatched VacuumStmt (GP_ROLE_EXECUTE), therefore,
	 * should not execute this block of code.
2506
	 */
2507
	if (Gp_role != GP_ROLE_EXECUTE && (is_heap ||
2508 2509
		(!is_heap && (vacstmt->appendonly_phase == AOVAC_CLEANUP ||
					  vacstmt->appendonly_relation_empty))))
2510
	{
2511
		if (toast_relid != InvalidOid && toast_rangevar != NULL)
2512
		{
2513 2514 2515 2516 2517
			VacuumStmt *vacstmt_toast = makeNode(VacuumStmt);
			vacstmt_toast->options = vacstmt->options;
			vacstmt_toast->freeze_min_age = vacstmt->freeze_min_age;
			vacstmt_toast->freeze_table_age = vacstmt->freeze_table_age;
			vacstmt_toast->skip_twophase = vacstmt->skip_twophase;
2518

2519 2520
			vacstmt_toast->relation = toast_rangevar;
			vacuum_rel(NULL, toast_relid, vacstmt_toast, lmode, for_wraparound);
2521 2522 2523
		}
	}

2524 2525 2526 2527 2528 2529 2530 2531 2532
	/*
	 * If an AO/CO table is empty on a segment,
	 * vacstmt->appendonly_relation_empty will get set to true even in the
	 * compaction phase. In such a case, we end up updating the auxiliary
	 * tables and try to vacuum them all in the same transaction. This causes
	 * the auxiliary relation to not get vacuumed and it generates a notice to
	 * the user saying that transaction is already in progress. Hence we want
	 * to vacuum the auxliary relations only in cleanup phase or if we are in
	 * the prepare phase and the AO/CO table is empty.
2533 2534 2535
	 *
	 * We alter the vacuum statement here since the AO auxiliary tables
	 * vacuuming will be dispatched to the primaries.
2536 2537 2538 2539 2540
	 *
	 * Similar to toast, a VacuumStmt object for each AO auxiliary relation is
	 * constructed and dispatched separately by the QD, when vacuuming the
	 * base AO relation.  A backend executing dispatched VacuumStmt
	 * (GP_ROLE_EXECUTE), therefore, should not execute this block of code.
2541
	 */
2542
	if (Gp_role != GP_ROLE_EXECUTE &&
2543 2544 2545
		(vacstmt->appendonly_phase == AOVAC_CLEANUP ||
		 (vacstmt->appendonly_relation_empty &&
		  vacstmt->appendonly_phase == AOVAC_PREPARE)))
2546
	{
2547 2548 2549 2550 2551
		VacuumStmt *vacstmt_ao_aux = makeNode(VacuumStmt);
		vacstmt_ao_aux->options = vacstmt->options;
		vacstmt_ao_aux->freeze_min_age = vacstmt->freeze_min_age;
		vacstmt_ao_aux->freeze_table_age = vacstmt->freeze_table_age;

2552
		/* do the same for an AO segments table, if any */
2553
		if (aoseg_relid != InvalidOid && aoseg_rangevar != NULL)
2554
		{
2555 2556
			vacstmt_ao_aux->relation = aoseg_rangevar;
			vacuum_rel(NULL, aoseg_relid, vacstmt_ao_aux, lmode, for_wraparound);
2557 2558 2559
		}

		/* do the same for an AO block directory table, if any */
2560
		if (aoblkdir_relid != InvalidOid && aoblkdir_rangevar != NULL)
2561
		{
2562 2563
			vacstmt_ao_aux->relation = aoblkdir_rangevar;
			vacuum_rel(NULL, aoblkdir_relid, vacstmt_ao_aux, lmode, for_wraparound);
2564 2565 2566
		}

		/* do the same for an AO visimap, if any */
2567
		if (aovisimap_relid != InvalidOid && aovisimap_rangevar != NULL)
2568
		{
2569 2570
			vacstmt_ao_aux->relation = aovisimap_rangevar;
			vacuum_rel(NULL, aovisimap_relid, vacstmt_ao_aux, lmode, for_wraparound);
2571 2572
		}
	}
2573 2574 2575

	/* Report that we really did it. */
	return true;
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
}


/****************************************************************************
 *																			*
 *			Code for VACUUM FULL (only)										*
 *																			*
 ****************************************************************************
 */

static bool vacuum_appendonly_index_should_vacuum(Relation aoRelation,
		VacuumStmt *vacstmt,
		AppendOnlyIndexVacuumState *vacuumIndexState, double *rel_tuple_count)
{
	int64 hidden_tupcount;
	FileSegTotals *totals;

2593
	Assert(RelationIsAppendOptimized(aoRelation));
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605

	if(Gp_role == GP_ROLE_DISPATCH)
	{
		if (rel_tuple_count)
		{
			*rel_tuple_count = 0.0;
		}
		return false;
	}

	if(RelationIsAoRows(aoRelation))
	{
2606
		totals = GetSegFilesTotals(aoRelation, vacuumIndexState->appendOnlyMetaDataSnapshot);
2607 2608 2609 2610
	}
	else
	{
		Assert(RelationIsAoCols(aoRelation));
2611
		totals = GetAOCSSSegFilesTotals(aoRelation, vacuumIndexState->appendOnlyMetaDataSnapshot);
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
	}
	hidden_tupcount = AppendOnlyVisimap_GetRelationHiddenTupleCount(&vacuumIndexState->visiMap);

	if(rel_tuple_count)
	{
		*rel_tuple_count = (double)(totals->totaltuples - hidden_tupcount);
		Assert((*rel_tuple_count) > -1.0);
	}

	pfree(totals);

2623
	if(hidden_tupcount > 0 || (vacstmt->options & VACOPT_FULL))
2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640
	{
		return true;
	}
	return false;
}

/*
 * vacuum_appendonly_indexes()
 *
 * Perform a vacuum on all indexes of an append-only relation.
 *
 * The page and tuplecount information in vacrelstats are used, the
 * nindex value is set by this function.
 *
 * It returns the number of indexes on the relation.
 */
int
2641
vacuum_appendonly_indexes(Relation aoRelation, VacuumStmt *vacstmt)
2642 2643 2644 2645 2646 2647 2648 2649 2650
{
	int reindex_count = 1;
	int i;
	Relation   *Irel;
	int			nindexes;
	AppendOnlyIndexVacuumState vacuumIndexState;
	FileSegInfo **segmentFileInfo = NULL; /* Might be a casted AOCSFileSegInfo */
	int totalSegfiles;

2651
	Assert(RelationIsAppendOptimized(aoRelation));
2652 2653 2654 2655 2656 2657 2658 2659 2660
	Assert(vacstmt);

	memset(&vacuumIndexState, 0, sizeof(vacuumIndexState));

	elogif (Debug_appendonly_print_compaction, LOG,
			"Vacuum indexes for append-only relation %s",
			RelationGetRelationName(aoRelation));

	/* Now open all indexes of the relation */
2661
	if ((vacstmt->options & VACOPT_FULL))
2662 2663 2664 2665
		vac_open_indexes(aoRelation, AccessExclusiveLock, &nindexes, &Irel);
	else
		vac_open_indexes(aoRelation, RowExclusiveLock, &nindexes, &Irel);

2666 2667
	vacuumIndexState.appendOnlyMetaDataSnapshot = GetActiveSnapshot();

2668 2669
	if (RelationIsAoRows(aoRelation))
	{
2670 2671 2672
		segmentFileInfo = GetAllFileSegInfo(aoRelation,
											vacuumIndexState.appendOnlyMetaDataSnapshot,
											&totalSegfiles);
2673 2674 2675 2676
	}
	else
	{
		Assert(RelationIsAoCols(aoRelation));
2677 2678 2679
		segmentFileInfo = (FileSegInfo **) GetAllAOCSFileSegInfo(aoRelation,
																vacuumIndexState.appendOnlyMetaDataSnapshot,
																&totalSegfiles);
2680 2681 2682 2683
	}

	AppendOnlyVisimap_Init(
			&vacuumIndexState.visiMap,
2684 2685
			aoRelation->rd_appendonly->visimaprelid,
			aoRelation->rd_appendonly->visimapidxid,
2686
			AccessShareLock,
2687
			vacuumIndexState.appendOnlyMetaDataSnapshot);
2688 2689

	AppendOnlyBlockDirectory_Init_forSearch(&vacuumIndexState.blockDirectory,
2690
			vacuumIndexState.appendOnlyMetaDataSnapshot,
2691 2692 2693 2694
			segmentFileInfo,
			totalSegfiles,
			aoRelation,
			1,
2695 2696
			RelationIsAoCols(aoRelation),
			NULL);
2697 2698 2699 2700 2701

	/* Clean/scan index relation(s) */
	if (Irel != NULL)
	{
		double rel_tuple_count = 0.0;
2702 2703 2704 2705 2706 2707 2708 2709
		int			elevel;

		/* just scan indexes to update statistic */
		if (vacstmt->options & VACOPT_VERBOSE)
			elevel = INFO;
		else
			elevel = DEBUG2;

2710 2711 2712 2713 2714 2715 2716
		if (vacuum_appendonly_index_should_vacuum(aoRelation, vacstmt,
					&vacuumIndexState, &rel_tuple_count))
		{
			Assert(rel_tuple_count > -1.0);

			for (i = 0; i < nindexes; i++)
			{
2717 2718 2719
				vacuum_appendonly_index(Irel[i], &vacuumIndexState,
										rel_tuple_count,
										elevel);
2720 2721 2722 2723 2724 2725
			}
			reindex_count++;
		}
		else
		{
			for (i = 0; i < nindexes; i++)
2726
				scan_index(Irel[i], rel_tuple_count, true, elevel);
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
		}
	}

	AppendOnlyVisimap_Finish(&vacuumIndexState.visiMap, AccessShareLock);
	AppendOnlyBlockDirectory_End_forSearch(&vacuumIndexState.blockDirectory);

	if (segmentFileInfo)
	{
		if (RelationIsAoRows(aoRelation))
		{
			FreeAllSegFileInfo(segmentFileInfo, totalSegfiles);
		}
		else
		{
			FreeAllAOCSSegFileInfo((AOCSFileSegInfo **)segmentFileInfo, totalSegfiles);
		}
		pfree(segmentFileInfo);
	}

	vac_close_indexes(nindexes, Irel, NoLock);
	return nindexes;
}

2750

2751
/* GPDB_91_MERGE_FIXME: 'amindexnulls' is gone. Do we need this function anymore? */
A
Asim R P 已提交
2752
#if 0
2753
/*
2754
 * Is an index partial (ie, could it contain fewer tuples than the heap?)
2755
 */
2756
static bool
2757
vac_is_partial_index(Relation indrel)
2758
{
2759
	/*
2760
	 * If the index's AM doesn't support nulls, it's partial for our purposes
2761
	 */
2762 2763
	if (!indrel->rd_am->amindexnulls)
		return true;
2764

2765 2766 2767
	/* Otherwise, look to see if there's a partial-index predicate */
	if (!heap_attisnull(indrel->rd_indextuple, Anum_pg_index_indpred))
		return true;
2768

2769 2770
	return false;
}
A
Asim R P 已提交
2771
#endif
2772

2773
/*
2774
 *	scan_index() -- scan one index relation to update pg_class statistics.
2775 2776
 *
 * We use this when we have no deletions to do.
2777 2778
 */
static void
2779
scan_index(Relation indrel, double num_tuples, bool check_stats, int elevel)
2780
{
2781
	IndexBulkDeleteResult *stats;
2782
	IndexVacuumInfo ivinfo;
2783
	PGRUsage	ru0;
2784

2785
	pg_rusage_init(&ru0);
2786

2787
	ivinfo.index = indrel;
2788
	ivinfo.analyze_only = false;
2789
	ivinfo.estimated_count = false;
2790 2791
	ivinfo.message_level = elevel;
	ivinfo.num_heap_tuples = num_tuples;
2792
	ivinfo.strategy = vac_strategy;
2793

2794
	stats = index_vacuum_cleanup(&ivinfo, NULL);
2795

2796 2797
	if (!stats)
		return;
2798

2799
	/*
2800 2801
	 * Now update statistics in pg_class, but only if the index says the count
	 * is accurate.
2802 2803
	 */
	if (!stats->estimated_count)
2804
		vac_update_relstats(indrel,
2805
							stats->num_pages, stats->num_index_tuples,
R
Richard Guo 已提交
2806
							visibilitymap_count(indrel),
2807 2808 2809
							false,
							InvalidTransactionId,
							InvalidMultiXactId,
2810
							false,
2811
							true /* isvacuum */);
2812

2813
	ereport(elevel,
B
Bruce Momjian 已提交
2814 2815
			(errmsg("index \"%s\" now contains %.0f row versions in %u pages",
					RelationGetRelationName(indrel),
2816
					stats->num_index_tuples,
B
Bruce Momjian 已提交
2817 2818 2819 2820 2821
					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))));
2822

2823
	/* GPDB_91_MERGE_FIXME: vac_is_partial_index() doesn't work. Do we need this sanity check? */
A
Asim R P 已提交
2824
#if 0 	
2825
	/*
B
Bruce Momjian 已提交
2826 2827
	 * Check for tuple count mismatch.	If the index is partial, then it's OK
	 * for it to have fewer tuples than the heap; else we got trouble.
2828
	 */
2829 2830
	if (check_stats &&
		!stats->estimated_count &&
2831
		stats->num_index_tuples != num_tuples)
2832
	{
2833 2834 2835 2836 2837 2838 2839 2840
		if (stats->num_index_tuples > num_tuples ||
			!vac_is_partial_index(indrel))
			ereport(WARNING,
					(errmsg("index \"%s\" contains %.0f row versions, but table contains %.0f row versions",
							RelationGetRelationName(indrel),
							stats->num_index_tuples, num_tuples),
					 errhint("Rebuild the index with REINDEX.")));
	}
A
Asim R P 已提交
2841
#endif
2842 2843 2844 2845

	pfree(stats);
}

2846
/*
2847
 * Vacuums an index on an append-only table.
2848
 *
2849 2850 2851
 * This is called after an append-only segment file compaction to move
 * all tuples from the compacted segment files.
 * The segmentFileList is an
2852 2853
 */
static void
2854 2855 2856 2857
vacuum_appendonly_index(Relation indexRelation,
						AppendOnlyIndexVacuumState *vacuumIndexState,
						double rel_tuple_count,
						int elevel)
2858
{
2859 2860 2861
	Assert(RelationIsValid(indexRelation));
	Assert(vacuumIndexState);

2862
	IndexBulkDeleteResult *stats;
2863
	IndexVacuumInfo ivinfo;
2864
	PGRUsage	ru0;
2865

2866
	pg_rusage_init(&ru0);
2867

2868
	ivinfo.index = indexRelation;
2869
	ivinfo.message_level = elevel;
2870
	ivinfo.num_heap_tuples = rel_tuple_count;
2871
	ivinfo.strategy = vac_strategy;
2872

2873
	/* Do bulk deletion */
2874 2875
	stats = index_bulk_delete(&ivinfo, NULL, appendonly_tid_reaped,
			(void *) vacuumIndexState);
2876

2877
	/* Do post-VACUUM cleanup */
2878
	stats = index_vacuum_cleanup(&ivinfo, stats);
2879

2880 2881
	if (!stats)
		return;
2882

2883
	/*
2884 2885
	 * Now update statistics in pg_class, but only if the index says the count
	 * is accurate.
2886 2887
	 */
	if (!stats->estimated_count)
2888 2889
		vac_update_relstats(indexRelation,
							stats->num_pages, stats->num_index_tuples,
R
Richard Guo 已提交
2890
							visibilitymap_count(indexRelation),
2891 2892 2893
							false,
							InvalidTransactionId,
							InvalidMultiXactId,
2894
							false,
2895
							true /* isvacuum */);
2896

2897
	ereport(elevel,
B
Bruce Momjian 已提交
2898
			(errmsg("index \"%s\" now contains %.0f row versions in %u pages",
2899
					RelationGetRelationName(indexRelation),
B
Bruce Momjian 已提交
2900 2901 2902 2903 2904 2905 2906 2907
					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))));
2908

2909
	pfree(stats);
2910

B
Bruce Momjian 已提交
2911
}
V
Vadim B. Mikheev 已提交
2912

2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974
static bool
appendonly_tid_reapded_check_block_directory(AppendOnlyIndexVacuumState* vacuumState,
		AOTupleId* aoTupleId)
{
	if (vacuumState->blockDirectory.currentSegmentFileNum ==
			AOTupleIdGet_segmentFileNum(aoTupleId) &&
			AppendOnlyBlockDirectoryEntry_RangeHasRow(&vacuumState->blockDirectoryEntry,
				AOTupleIdGet_rowNum(aoTupleId)))
	{
		return true;
	}

	if (!AppendOnlyBlockDirectory_GetEntry(&vacuumState->blockDirectory,
		aoTupleId,
		0,
		&vacuumState->blockDirectoryEntry))
	{
		return false;
	}
	return (vacuumState->blockDirectory.currentSegmentFileNum ==
			AOTupleIdGet_segmentFileNum(aoTupleId) &&
			AppendOnlyBlockDirectoryEntry_RangeHasRow(&vacuumState->blockDirectoryEntry,
				AOTupleIdGet_rowNum(aoTupleId)));
}

/*
 * appendonly_tid_reaped()
 *
 * Is a particular tid for an appendonly reaped?
 * state should contain an integer list of all compacted
 * segment files.
 *
 * This has the right signature to be an IndexBulkDeleteCallback.
 */
static bool
appendonly_tid_reaped(ItemPointer itemptr, void *state)
{
	AOTupleId* aoTupleId;
	AppendOnlyIndexVacuumState* vacuumState;
	bool reaped;

	Assert(itemptr);
	Assert(state);

	aoTupleId = (AOTupleId *)itemptr;
	vacuumState = (AppendOnlyIndexVacuumState *)state;

	reaped = !appendonly_tid_reapded_check_block_directory(vacuumState,
			aoTupleId);
	if (!reaped)
	{
		/* Also check visi map */
		reaped = !AppendOnlyVisimap_IsVisible(&vacuumState->visiMap,
		aoTupleId);
	}

	elogif(Debug_appendonly_print_compaction, DEBUG3,
			"Index vacuum %s %d",
			AOTupleIdToString(aoTupleId), reaped);
	return reaped;
}

2975
/*
2976
 * Open all the vacuumable indexes of the given relation, obtaining the
B
Bruce Momjian 已提交
2977
 * specified kind of lock on each.  Return an array of Relation pointers for
2978 2979 2980 2981 2982 2983 2984 2985
 * the indexes into *Irel, and the number of indexes into *nindexes.
 *
 * We consider an index vacuumable if it is marked insertable (IndexIsReady).
 * If it isn't, probably a CREATE INDEX CONCURRENTLY command failed early in
 * execution, and what we have is too corrupt to be processable.  We will
 * vacuum even if the index isn't indisvalid; this is important because in a
 * unique index, uniqueness checks will be performed anyway and had better not
 * hit dangling index pointers.
2986
 */
2987
void
2988 2989
vac_open_indexes(Relation relation, LOCKMODE lockmode,
				 int *nindexes, Relation **Irel)
V
Vadim B. Mikheev 已提交
2990
{
2991 2992
	List	   *indexoidlist;
	ListCell   *indexoidscan;
2993
	int			i;
V
Vadim B. Mikheev 已提交
2994

2995 2996
	Assert(lockmode != NoLock);

2997
	indexoidlist = RelationGetIndexList(relation);
2998

2999 3000
	/* allocate enough memory for all indexes */
	i = list_length(indexoidlist);
3001

3002 3003
	if (i > 0)
		*Irel = (Relation *) palloc(i * sizeof(Relation));
3004 3005
	else
		*Irel = NULL;
3006

3007
	/* collect just the ready indexes */
3008 3009
	i = 0;
	foreach(indexoidscan, indexoidlist)
3010
	{
3011
		Oid			indexoid = lfirst_oid(indexoidscan);
3012
		Relation	indrel;
V
Vadim B. Mikheev 已提交
3013

3014 3015 3016 3017 3018
		indrel = index_open(indexoid, lockmode);
		if (IndexIsReady(indrel->rd_index))
			(*Irel)[i++] = indrel;
		else
			index_close(indrel, lockmode);
3019 3020
	}

3021 3022
	*nindexes = i;

3023
	list_free(indexoidlist);
B
Bruce Momjian 已提交
3024
}
V
Vadim B. Mikheev 已提交
3025

3026
/*
B
Bruce Momjian 已提交
3027
 * Release the resources acquired by vac_open_indexes.  Optionally release
3028 3029
 * the locks (say NoLock to keep 'em).
 */
3030
void
3031
vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode)
V
Vadim B. Mikheev 已提交
3032
{
3033
	if (Irel == NULL)
3034
		return;
V
Vadim B. Mikheev 已提交
3035

3036
	while (nindexes--)
3037 3038 3039
	{
		Relation	ind = Irel[nindexes];

3040
		index_close(ind, lockmode);
3041
	}
3042
	pfree(Irel);
B
Bruce Momjian 已提交
3043
}
V
Vadim B. Mikheev 已提交
3044

3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060
/*
 * vacuum_delay_point --- check for interrupts and cost-based delay.
 *
 * This should be called in each major loop of VACUUM processing,
 * typically once per page processed.
 */
void
vacuum_delay_point(void)
{
	/* Always check for interrupts */
	CHECK_FOR_INTERRUPTS();

	/* Nap if appropriate */
	if (VacuumCostActive && !InterruptPending &&
		VacuumCostBalance >= VacuumCostLimit)
	{
B
Bruce Momjian 已提交
3061
		int			msec;
3062

3063 3064 3065
		msec = VacuumCostDelay * VacuumCostBalance / VacuumCostLimit;
		if (msec > VacuumCostDelay * 4)
			msec = VacuumCostDelay * 4;
3066 3067 3068 3069 3070

		pg_usleep(msec * 1000L);

		VacuumCostBalance = 0;

3071 3072 3073
		/* update balance values for workers */
		AutoVacuumUpdateDelay();

3074 3075 3076 3077
		/* Might have gotten an interrupt while sleeping */
		CHECK_FOR_INTERRUPTS();
	}
}
3078 3079 3080 3081 3082 3083 3084

/*
 * Dispatch a Vacuum command.
 */
static void
dispatchVacuum(VacuumStmt *vacstmt, VacuumStatsContext *ctx)
{
3085
	CdbPgResults cdb_pgresults;
3086

3087 3088
	int flags = DF_CANCEL_ON_ERROR | DF_WITH_SNAPSHOT;

3089 3090 3091 3092
	/* should these be marked volatile ? */

	Assert(Gp_role == GP_ROLE_DISPATCH);
	Assert(vacstmt);
3093 3094
	Assert(vacstmt->options & VACOPT_VACUUM);
	Assert(!(vacstmt->options & VACOPT_ANALYZE));
3095

3096 3097 3098
	if (!vacstmt->skip_twophase)
		flags |= DF_NEED_TWO_PHASE;

3099
	/* XXX: Some kinds of VACUUM assign a new relfilenode. bitmap indexes maybe? */
3100
	CdbDispatchUtilityStatement((Node *) vacstmt, flags,
3101 3102
								GetAssignedOidsForDispatch(),
								&cdb_pgresults);
3103

3104
	vacuum_combine_stats(ctx, &cdb_pgresults);
3105

3106
	cdbdisp_clearCdbPgResults(&cdb_pgresults);
3107 3108 3109
}

/*
3110
 * vacuum_combine_stats
3111 3112 3113 3114 3115
 * This function combine the stats information sent by QEs to generate
 * the final stats for QD relations.
 *
 * Note that the mirrorResults is ignored by this function.
 */
3116
static void
3117
vacuum_combine_stats(VacuumStatsContext *stats_context, CdbPgResults* cdb_pgresults)
3118 3119 3120 3121 3122
{
	int result_no;

	Assert(Gp_role == GP_ROLE_DISPATCH);

3123
	if (cdb_pgresults == NULL || cdb_pgresults->numResults <= 0)
3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136
		return;

	/*
	 * Process the dispatch results from the primary. Note that the QE
	 * processes also send back the new stats info, such as stats on
	 * pg_class, for the relevant table and its
	 * indexes. We parse this information, and compute the final stats
	 * for the QD.
	 *
	 * For pg_class stats, we compute the maximum number of tuples and
	 * maximum number of pages after processing the stats from each QE.
	 *
	 */
3137
	for(result_no = 0; result_no < cdb_pgresults->numResults; result_no++)
3138
	{
3139

3140
		VPgClassStats *pgclass_stats = NULL;
3141 3142
		ListCell *lc = NULL;
		struct pg_result *pgresult = cdb_pgresults->pg_results[result_no];
3143

3144 3145
		if (pgresult->extras == NULL)
			continue;
3146

3147
		Assert(pgresult->extraslen > sizeof(int));
3148

3149
		/*
D
Daniel Gustafsson 已提交
3150
		 * Process the stats for pg_class. We simply compute the maximum
3151 3152 3153 3154 3155 3156
		 * number of rel_tuples and rel_pages.
		 */
		pgclass_stats = (VPgClassStats *) pgresult->extras;
		foreach (lc, stats_context->updated_stats)
		{
			VPgClassStats *tmp_stats = (VPgClassStats *) lfirst(lc);
3157

3158
			if (tmp_stats->relid == pgclass_stats->relid)
3159
			{
3160 3161
				tmp_stats->rel_pages += pgclass_stats->rel_pages;
				tmp_stats->rel_tuples += pgclass_stats->rel_tuples;
R
Richard Guo 已提交
3162
				tmp_stats->relallvisible += pgclass_stats->relallvisible;
3163
				break;
3164
			}
3165
		}
3166

3167 3168 3169
		if (lc == NULL)
		{
			Assert(pgresult->extraslen == sizeof(VPgClassStats));
3170

3171 3172
			pgclass_stats = palloc(sizeof(VPgClassStats));
			memcpy(pgclass_stats, pgresult->extras, pgresult->extraslen);
3173

3174 3175
			stats_context->updated_stats =
					lappend(stats_context->updated_stats, pgclass_stats);
3176 3177 3178
		}
	}
}