procarray.c 67.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/*-------------------------------------------------------------------------
 *
 * procarray.c
 *	  POSTGRES process array code.
 *
 *
 * This module maintains an unsorted array of the PGPROC structures for all
 * active backends.  Although there are several uses for this, the principal
 * one is as a means of determining the set of currently running transactions.
 *
 * Because of various subtle race conditions it is critical that a backend
 * hold the correct locks while setting or clearing its MyProc->xid field.
13
 * See notes in src/backend/access/transam/README.
14 15 16
 *
 * The process array now also includes PGPROC structures representing
 * prepared transactions.  The xid and subxids fields of these are valid,
17 18
 * as are the myProcLocks lists.  They can be distinguished from regular
 * backend PGPROCs at need by checking for pid == 0.
B
Bruce Momjian 已提交
19
 *
20
 *
21
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
22 23 24 25
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
26
 *	  $PostgreSQL: pgsql/src/backend/storage/ipc/procarray.c,v 1.47 2009/01/01 17:23:47 momjian Exp $
27 28 29 30 31
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

32
#include <signal.h>
33

34
#include "access/distributedlog.h"
35
#include "access/subtrans.h"
36 37
#include "access/transam.h"
#include "access/xact.h"
38
#include "access/twophase.h"
39 40
#include "miscadmin.h"
#include "storage/procarray.h"
41
#include "utils/combocid.h"
42
#include "utils/snapmgr.h"
43
#include "utils/tqual.h"
44 45 46 47
#include "utils/guc.h"
#include "utils/memutils.h"

#include "access/xact.h"		/* setting the shared xid */
48

49
#include "cdb/cdbtm.h"
50
#include "cdb/cdbvars.h"
51 52
#include "utils/faultinjector.h"
#include "utils/sharedsnapshot.h"
53 54 55 56 57 58 59 60

/* Our shared memory area */
typedef struct ProcArrayStruct
{
	int			numProcs;		/* number of valid procs entries */
	int			maxProcs;		/* allocated size of procs array */

	/*
B
Bruce Momjian 已提交
61 62
	 * We declare procs[] as 1 entry because C wants a fixed-size array, but
	 * actually it is maxProcs entries long.
63 64 65 66 67 68 69 70 71 72 73
	 */
	PGPROC	   *procs[1];		/* VARIABLE LENGTH ARRAY */
} ProcArrayStruct;

static ProcArrayStruct *procArray;


#ifdef XIDCACHE_DEBUG

/* counters for XidCache measurement */
static long xc_by_recent_xmin = 0;
74
static long xc_by_known_xact = 0;
75
static long xc_by_my_xact = 0;
76
static long xc_by_latest_xid = 0;
77 78
static long xc_by_main_xid = 0;
static long xc_by_child_xid = 0;
79
static long xc_no_overflow = 0;
80 81 82
static long xc_slow_answer = 0;

#define xc_by_recent_xmin_inc()		(xc_by_recent_xmin++)
83
#define xc_by_known_xact_inc()		(xc_by_known_xact++)
84
#define xc_by_my_xact_inc()			(xc_by_my_xact++)
85
#define xc_by_latest_xid_inc()		(xc_by_latest_xid++)
86 87
#define xc_by_main_xid_inc()		(xc_by_main_xid++)
#define xc_by_child_xid_inc()		(xc_by_child_xid++)
88
#define xc_no_overflow_inc()		(xc_no_overflow++)
89 90 91 92 93 94
#define xc_slow_answer_inc()		(xc_slow_answer++)

static void DisplayXidCache(void);
#else							/* !XIDCACHE_DEBUG */

#define xc_by_recent_xmin_inc()		((void) 0)
95
#define xc_by_known_xact_inc()		((void) 0)
96
#define xc_by_my_xact_inc()			((void) 0)
97
#define xc_by_latest_xid_inc()		((void) 0)
98 99
#define xc_by_main_xid_inc()		((void) 0)
#define xc_by_child_xid_inc()		((void) 0)
100
#define xc_no_overflow_inc()		((void) 0)
101 102 103
#define xc_slow_answer_inc()		((void) 0)
#endif   /* XIDCACHE_DEBUG */

104

105 106 107
/*
 * Report shared-memory space needed by CreateSharedProcArray.
 */
108
Size
109
ProcArrayShmemSize(void)
110
{
111 112 113 114
	Size		size;

	size = offsetof(ProcArrayStruct, procs);
	size = add_size(size, mul_size(sizeof(PGPROC *),
B
Bruce Momjian 已提交
115
								 add_size(MaxBackends, max_prepared_xacts)));
116 117

	return size;
118 119 120 121 122 123
}

/*
 * Initialize the shared PGPROC array during postmaster startup.
 */
void
124
CreateSharedProcArray(void)
125 126 127 128 129
{
	bool		found;

	/* Create or attach to the ProcArray shared structure */
	procArray = (ProcArrayStruct *)
130
		ShmemInitStruct("Proc Array", ProcArrayShmemSize(), &found);
131 132 133 134 135 136 137

	if (!found)
	{
		/*
		 * We're the first - initialize.
		 */
		procArray->numProcs = 0;
138
		procArray->maxProcs = MaxBackends + max_prepared_xacts;
139 140 141 142
	}
}

/*
143
 * Add the specified PGPROC to the shared array.
144 145
 */
void
146
ProcArrayAdd(PGPROC *proc)
147 148 149 150 151
{
	ProcArrayStruct *arrayP = procArray;

	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

152
	SIMPLE_FAULT_INJECTOR(ProcArray_Add);
153

154 155 156
	if (arrayP->numProcs >= arrayP->maxProcs)
	{
		/*
B
Bruce Momjian 已提交
157 158 159
		 * Ooops, no room.	(This really shouldn't happen, since there is a
		 * fixed supply of PGPROC structs too, and so we should have failed
		 * earlier.)
160 161 162 163 164 165 166
		 */
		LWLockRelease(ProcArrayLock);
		ereport(FATAL,
				(errcode(ERRCODE_TOO_MANY_CONNECTIONS),
				 errmsg("sorry, too many clients already")));
	}

167
	arrayP->procs[arrayP->numProcs] = proc;
168 169 170 171 172 173
	arrayP->numProcs++;

	LWLockRelease(ProcArrayLock);
}

/*
174
 * Remove the specified PGPROC from the shared array.
175 176 177 178 179 180 181
 *
 * When latestXid is a valid XID, we are removing a live 2PC gxact from the
 * array, and thus causing it to appear as "not running" anymore.  In this
 * case we must advance latestCompletedXid.  (This is essentially the same
 * as ProcArrayEndTransaction followed by removal of the PGPROC, but we take
 * the ProcArrayLock only once, and don't damage the content of the PGPROC;
 * twophase.c depends on the latter.)
182 183
 */
void
184
ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
185 186 187 188 189
{
	ProcArrayStruct *arrayP = procArray;
	int			index;

#ifdef XIDCACHE_DEBUG
190 191 192
	/* dump stats at backend shutdown, but not prepared-xact end */
	if (proc->pid != 0)
		DisplayXidCache();
193 194 195 196
#endif

	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
	if (TransactionIdIsValid(latestXid))
	{
		Assert(TransactionIdIsValid(proc->xid));

		/* Advance global latestCompletedXid while holding the lock */
		if (TransactionIdPrecedes(ShmemVariableCache->latestCompletedXid,
								  latestXid))
			ShmemVariableCache->latestCompletedXid = latestXid;
	}
	else
	{
		/* Shouldn't be trying to remove a live transaction here */
		Assert(!TransactionIdIsValid(proc->xid));
	}

212 213
	for (index = 0; index < arrayP->numProcs; index++)
	{
214
		if (arrayP->procs[index] == proc)
215 216
		{
			arrayP->procs[index] = arrayP->procs[arrayP->numProcs - 1];
217
			arrayP->procs[arrayP->numProcs - 1] = NULL; /* for debugging */
218 219 220 221 222 223 224 225 226
			arrayP->numProcs--;
			LWLockRelease(ProcArrayLock);
			return;
		}
	}

	/* Ooops */
	LWLockRelease(ProcArrayLock);

227
	elog(LOG, "failed to find proc %p in ProcArray", proc);
228 229 230
}


231 232 233 234 235 236 237 238 239 240 241 242
/*
 * ProcArrayEndTransaction -- mark a transaction as no longer running
 *
 * This is used interchangeably for commit and abort cases.  The transaction
 * commit/abort must already be reported to WAL and pg_clog.
 *
 * proc is currently always MyProc, but we pass it explicitly for flexibility.
 * latestXid is the latest Xid among the transaction's main XID and
 * subtransactions, or InvalidTransactionId if it has no XID.  (We must ask
 * the caller to pass latestXid, instead of computing it from the PGPROC's
 * contents, because the subxid information in the PGPROC might be
 * incomplete.)
243 244
 *
 * GPDB: If this is a global transaction, we might need to do this action
245 246 247 248
 * later, rather than now. In that case, this function returns true for
 * needNotifyCommittedDtxTransaction, and does *not* change the state of the
 * PGPROC entry. This can only happen for commit; when !isCommit, this always
 * clears the PGPROC entry.
249
 */
250 251
bool
ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid, bool isCommit)
252
{
253
	bool needNotifyCommittedDtxTransaction;
254

255 256 257 258 259
	/*
	 * MyProc->localDistribXactData is only used for debugging purpose by
	 * backend itself on segments only hence okay to modify without holding
	 * the lock.
	 */
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
	if (MyProc->localDistribXactData.state != LOCALDISTRIBXACT_STATE_NONE)
	{
		switch (DistributedTransactionContext)
		{
			case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
			case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
			case DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT:
				LocalDistribXact_ChangeState(MyProc,
											 isCommit ?
											 LOCALDISTRIBXACT_STATE_COMMITTED :
											 LOCALDISTRIBXACT_STATE_ABORTED);
				break;

			case DTX_CONTEXT_QE_READER:
			case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
				// QD or QE Writer will handle it.
				break;

278
			case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
279 280 281 282 283 284 285 286 287 288 289 290 291
			case DTX_CONTEXT_QD_RETRY_PHASE_2:
			case DTX_CONTEXT_QE_PREPARED:
			case DTX_CONTEXT_QE_FINISH_PREPARED:
				elog(PANIC, "Unexpected distribute transaction context: '%s'",
					 DtxContextToString(DistributedTransactionContext));

			default:
				elog(PANIC, "Unrecognized DTX transaction context: %d",
					 (int) DistributedTransactionContext);
		}
	}

	if (isCommit && notifyCommittedDtxTransactionIsNeeded())
292 293 294
		needNotifyCommittedDtxTransaction = true;
	else
		needNotifyCommittedDtxTransaction = false;
295
	
296 297
	if (TransactionIdIsValid(latestXid))
	{
298
		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
299
		/*
B
Bruce Momjian 已提交
300 301 302
		 * We must lock ProcArrayLock while clearing proc->xid, so that we do
		 * not exit the set of "running" transactions while someone else is
		 * taking a snapshot.  See discussion in
303 304
		 * src/backend/access/transam/README.
		 */
305 306
		Assert(TransactionIdIsValid(proc->xid) ||
			   (IsBootstrapProcessingMode() && latestXid == BootstrapTransactionId));
307

308
		if (! needNotifyCommittedDtxTransaction)
309 310 311 312 313 314 315 316 317 318 319 320 321 322
		{
			proc->xid = InvalidTransactionId;
			proc->lxid = InvalidLocalTransactionId;
			proc->xmin = InvalidTransactionId;
			/* must be cleared with xid/xmin: */
			proc->vacuumFlags &= ~PROC_VACUUM_STATE_MASK;
			proc->inCommit = false; /* be sure this is cleared in abort */
			proc->serializableIsoLevel = false;
			proc->inDropTransaction = false;

			/* Clear the subtransaction-XID cache too while holding the lock */
			proc->subxids.nxids = 0;
			proc->subxids.overflowed = false;
		}
323 324

		/* Also advance global latestCompletedXid while holding the lock */
325 326 327 328 329 330 331
		/*
		 * Note: we do this in GPDB even if we didn't clear our XID entry
		 * just yet. There is no harm in advancing latestCompletedXid a
		 * little bit earlier than strictly necessary, and this way we don't
		 * need to remember out latest XID when we later actually clear the
		 * entry.
		 */
332 333 334
		if (TransactionIdPrecedes(ShmemVariableCache->latestCompletedXid,
								  latestXid))
			ShmemVariableCache->latestCompletedXid = latestXid;
335 336

		LWLockRelease(ProcArrayLock);
337 338 339 340
	}
	else
	{
		/*
B
Bruce Momjian 已提交
341 342 343
		 * If we have no XID, we don't need to lock, since we won't affect
		 * anyone else's calculation of a snapshot.  We might change their
		 * estimate of global xmin, but that's OK.
344 345 346 347 348
		 */
		Assert(!TransactionIdIsValid(proc->xid));

		proc->lxid = InvalidLocalTransactionId;
		proc->xmin = InvalidTransactionId;
349 350
		/* must be cleared with xid/xmin: */
		proc->vacuumFlags &= ~PROC_VACUUM_STATE_MASK;
B
Bruce Momjian 已提交
351
		proc->inCommit = false; /* be sure this is cleared in abort */
352 353
		proc->serializableIsoLevel = false;
		proc->inDropTransaction = false;
354 355 356 357

		Assert(proc->subxids.nxids == 0);
		Assert(proc->subxids.overflowed == false);
	}
358 359

	return needNotifyCommittedDtxTransaction;
360 361 362 363 364 365 366 367 368 369
}


/*
 * ProcArrayClearTransaction -- clear the transaction fields
 *
 * This is used after successfully preparing a 2-phase transaction.  We are
 * not actually reporting the transaction's XID as no longer running --- it
 * will still appear as running because the 2PC's gxact is in the ProcArray
 * too.  We just have to clear out our own PGPROC.
370
 *
371 372
 */
void
373
ProcArrayClearTransaction(PGPROC *proc, bool commit)
374 375 376
{
	/*
	 * We can skip locking ProcArrayLock here, because this action does not
B
Bruce Momjian 已提交
377 378
	 * actually change anyone's view of the set of running XIDs: our entry is
	 * duplicate with the gxact that has already been inserted into the
379 380 381 382
	 * ProcArray.
	 */
	proc->xid = InvalidTransactionId;
	proc->xmin = InvalidTransactionId;
383

384 385
	proc->localDistribXactData.state = LOCALDISTRIBXACT_STATE_NONE;

386 387
	/* redundant, but just in case */
	proc->vacuumFlags &= ~PROC_VACUUM_STATE_MASK;
388 389
	proc->serializableIsoLevel = false;
	proc->inDropTransaction = false;
390 391 392 393

	/* Clear the subtransaction-XID cache too */
	proc->subxids.nxids = 0;
	proc->subxids.overflowed = false;
394 395 396 397 398 399 400 401 402 403 404

	/* For commit, inCommit and lxid are cleared in CommitTransaction after
	 * performing PT operations. It's done this way to correctly block
	 * checkpoint till CommitTransaction completes the persistent table
	 * updates.
	 */
	if (! commit)
	{
		proc->lxid = InvalidLocalTransactionId;
		proc->inCommit = false;
	}
405 406
}

407 408 409 410 411 412
/*
 * Clears the current transaction from PGPROC.
 *
 * Must be called while holding the ProcArrayLock.
 */
void
413
ClearTransactionFromPgProc_UnderLock(PGPROC *proc, bool commit)
414 415 416 417 418
{
	/*
	 * ProcArrayClearTransaction() doesn't take the lock, so we can just call it
	 * directly.
	 */
419
	ProcArrayClearTransaction(proc, commit);
420
}
421

422 423 424
/*
 * TransactionIdIsInProgress -- is given transaction running in some backend
 *
425 426
 * Aside from some shortcuts such as checking RecentXmin and our own Xid,
 * there are three possibilities for finding a running transaction:
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
 *
 * 1. the given Xid is a main transaction Id.  We will find this out cheaply
 * by looking at the PGPROC struct for each backend.
 *
 * 2. the given Xid is one of the cached subxact Xids in the PGPROC array.
 * We can find this out cheaply too.
 *
 * 3. Search the SubTrans tree to find the Xid's topmost parent, and then
 * see if that is running according to PGPROC.	This is the slowest, but
 * sadly it has to be done always if the other two failed, unless we see
 * that the cached subxact sets are complete (none have overflowed).
 *
 * ProcArrayLock has to be held while we do 1 and 2.  If we save the top Xids
 * while doing 1, we can release the ProcArrayLock while we do 3.  This buys
 * back some concurrency (we can't retrieve the main Xids from PGPROC again
 * anyway; see GetNewTransactionId).
 */
bool
TransactionIdIsInProgress(TransactionId xid)
{
447 448
	static TransactionId *xids = NULL;
	int			nxids = 0;
449
	ProcArrayStruct *arrayP = procArray;
450
	TransactionId topxid;
451 452 453 454
	int			i,
				j;

	/*
B
Bruce Momjian 已提交
455
	 * Don't bother checking a transaction older than RecentXmin; it could not
456 457 458
	 * possibly still be running.  (Note: in particular, this guarantees that
	 * we reject InvalidTransactionId, FrozenTransactionId, etc as not
	 * running.)
459 460 461 462 463 464 465
	 */
	if (TransactionIdPrecedes(xid, RecentXmin))
	{
		xc_by_recent_xmin_inc();
		return false;
	}

466 467 468 469 470 471 472 473 474 475 476
	/*
	 * We may have just checked the status of this transaction, so if it is
	 * already known to be completed, we can fall out without any access to
	 * shared memory.
	 */
	if (TransactionIdIsKnownCompleted(xid))
	{
		xc_by_known_xact_inc();
		return false;
	}

477 478 479 480 481 482 483 484 485 486 487
	/*
	 * Also, we can handle our own transaction (and subtransactions) without
	 * any access to shared memory.
	 */
	if (TransactionIdIsCurrentTransactionId(xid))
	{
		xc_by_my_xact_inc();
		return true;
	}

	/*
B
Bruce Momjian 已提交
488 489
	 * If not first time through, get workspace to remember main XIDs in. We
	 * malloc it permanently to avoid repeated palloc/pfree overhead.
490 491 492 493 494 495 496 497 498 499
	 */
	if (xids == NULL)
	{
		xids = (TransactionId *)
			malloc(arrayP->maxProcs * sizeof(TransactionId));
		if (xids == NULL)
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
	}
500 501 502

	LWLockAcquire(ProcArrayLock, LW_SHARED);

503 504 505 506 507 508 509 510 511 512 513 514
	/*
	 * Now that we have the lock, we can check latestCompletedXid; if the
	 * target Xid is after that, it's surely still running.
	 */
	if (TransactionIdPrecedes(ShmemVariableCache->latestCompletedXid, xid))
	{
		LWLockRelease(ProcArrayLock);
		xc_by_latest_xid_inc();
		return true;
	}

	/* No shortcuts, gotta grovel through the array */
515 516
	for (i = 0; i < arrayP->numProcs; i++)
	{
517
		volatile PGPROC *proc = arrayP->procs[i];
518 519 520 521 522
		TransactionId pxid;

		/* Ignore my own proc --- dealt with it above */
		if (proc == MyProc)
			continue;
523 524

		/* Fetch xid just once - see GetNewTransactionId */
525
		pxid = proc->xid;
526 527 528 529 530 531 532 533 534

		if (!TransactionIdIsValid(pxid))
			continue;

		/*
		 * Step 1: check the main Xid
		 */
		if (TransactionIdEquals(pxid, xid))
		{
535
			LWLockRelease(ProcArrayLock);
536
			xc_by_main_xid_inc();
537
			return true;
538 539 540
		}

		/*
B
Bruce Momjian 已提交
541 542
		 * We can ignore main Xids that are younger than the target Xid, since
		 * the target could not possibly be their child.
543 544 545 546 547 548 549 550 551 552 553 554 555 556
		 */
		if (TransactionIdPrecedes(xid, pxid))
			continue;

		/*
		 * Step 2: check the cached child-Xids arrays
		 */
		for (j = proc->subxids.nxids - 1; j >= 0; j--)
		{
			/* Fetch xid just once - see GetNewTransactionId */
			TransactionId cxid = proc->subxids.xids[j];

			if (TransactionIdEquals(cxid, xid))
			{
557
				LWLockRelease(ProcArrayLock);
558
				xc_by_child_xid_inc();
559
				return true;
560 561 562 563
			}
		}

		/*
B
Bruce Momjian 已提交
564 565 566 567 568
		 * Save the main Xid for step 3.  We only need to remember main Xids
		 * that have uncached children.  (Note: there is no race condition
		 * here because the overflowed flag cannot be cleared, only set, while
		 * we hold ProcArrayLock.  So we can't miss an Xid that we need to
		 * worry about.)
569 570 571 572 573 574 575 576 577 578 579 580
		 */
		if (proc->subxids.overflowed)
			xids[nxids++] = pxid;
	}

	LWLockRelease(ProcArrayLock);

	/*
	 * If none of the relevant caches overflowed, we know the Xid is not
	 * running without looking at pg_subtrans.
	 */
	if (nxids == 0)
581 582
	{
		xc_no_overflow_inc();
583
		return false;
584
	}
585 586 587 588

	/*
	 * Step 3: have to check pg_subtrans.
	 *
589 590 591 592
	 * At this point, we know it's either a subtransaction of one of the Xids
	 * in xids[], or it's not running.  If it's an already-failed
	 * subtransaction, we want to say "not running" even though its parent may
	 * still be running.  So first, check pg_clog to see if it's been aborted.
593 594 595 596
	 */
	xc_slow_answer_inc();

	if (TransactionIdDidAbort(xid))
597
		return false;
598 599

	/*
B
Bruce Momjian 已提交
600
	 * It isn't aborted, so check whether the transaction tree it belongs to
601 602
	 * is still running (or, more precisely, whether it was running when we
	 * held ProcArrayLock).
603 604 605 606 607 608 609 610
	 */
	topxid = SubTransGetTopmostTransaction(xid);
	Assert(TransactionIdIsValid(topxid));
	if (!TransactionIdEquals(topxid, xid))
	{
		for (i = 0; i < nxids; i++)
		{
			if (TransactionIdEquals(xids[i], topxid))
611
				return true;
612 613 614
		}
	}

615
	return false;
616 617
}

618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
/*
 * TransactionIdIsActive -- is xid the top-level XID of an active backend?
 *
 * This differs from TransactionIdIsInProgress in that it ignores prepared
 * transactions.  Also, we ignore subtransactions since that's not needed
 * for current uses.
 */
bool
TransactionIdIsActive(TransactionId xid)
{
	bool		result = false;
	ProcArrayStruct *arrayP = procArray;
	int			i;

	/*
B
Bruce Momjian 已提交
633 634
	 * Don't bother checking a transaction older than RecentXmin; it could not
	 * possibly still be running.
635 636 637 638 639 640 641 642
	 */
	if (TransactionIdPrecedes(xid, RecentXmin))
		return false;

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (i = 0; i < arrayP->numProcs; i++)
	{
643
		volatile PGPROC *proc = arrayP->procs[i];
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

		/* Fetch xid just once - see GetNewTransactionId */
		TransactionId pxid = proc->xid;

		if (!TransactionIdIsValid(pxid))
			continue;

		if (proc->pid == 0)
			continue;			/* ignore prepared transactions */

		if (TransactionIdEquals(pxid, xid))
		{
			result = true;
			break;
		}
	}

	LWLockRelease(ProcArrayLock);

	return result;
}

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
/*
 * Returns true if there are any UAO drop transaction active (except the current
 * one).
 *
 * If allDbs is TRUE then all backends are considered; if allDbs is FALSE
 * then only backends running in my own database are considered.
 */
bool
HasDropTransaction(bool allDbs)
{
	ProcArrayStruct *arrayP = procArray;
	bool result = false; /* Assumes */
	int			index;

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
		volatile PGPROC *proc = arrayP->procs[index];
		if (proc->pid == 0)
			continue;			/* do not count prepared xacts */

		if (allDbs || proc->databaseId == MyDatabaseId)
		{
			if (proc->inDropTransaction && proc != MyProc)
			{
692 693 694
				ereport((Debug_print_snapshot_dtm ? LOG : DEBUG3),
						(errmsg("Found drop transaction: database %d, pid %d, xid %d, xmin %d",
								proc->databaseId, proc->pid, proc->xid, proc->xmin)));
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
				result = true;
			}
		}
	}

	LWLockRelease(ProcArrayLock);

	return result;
}

/*
 * Returns true if there are of serializable backends (except the current
 * one).
 *
 * If allDbs is TRUE then all backends are considered; if allDbs is FALSE
 * then only backends running in my own database are considered.
 */
bool
HasSerializableBackends(bool allDbs)
{
	ProcArrayStruct *arrayP = procArray;
	bool result = false; /* Assumes */
	int			index;

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
		volatile PGPROC *proc = arrayP->procs[index];
		if (proc->pid == 0)
			continue;			/* do not count prepared xacts */

		if (allDbs || proc->databaseId == MyDatabaseId)
		{
			if (proc->serializableIsoLevel && proc != MyProc)
			{
731 732 733
				ereport((Debug_print_snapshot_dtm ? LOG : DEBUG3),
						(errmsg("Found serializable transaction: database %d, pid %d, xid %d, xmin %d",
								proc->databaseId, proc->pid, proc->xid, proc->xmin)));
734 735 736 737 738 739 740 741 742
				result = true;
			}
		}
	}

	LWLockRelease(ProcArrayLock);

	return result;
}
743

744 745 746 747 748 749 750 751 752 753
/*
 * GetOldestXmin -- returns oldest transaction that was running
 *					when any current transaction was started.
 *
 * If allDbs is TRUE then all backends are considered; if allDbs is FALSE
 * then only backends running in my own database are considered.
 *
 * This is used by VACUUM to decide which deleted tuples must be preserved
 * in a table.	allDbs = TRUE is needed for shared relations, but allDbs =
 * FALSE is sufficient for non-shared relations, since only backends in my
B
Bruce Momjian 已提交
754
 * own database could ever see the tuples in them.	Also, we can ignore
755 756
 * concurrently running lazy VACUUMs because (a) they must be working on other
 * tables, and (b) they don't need to do snapshot-based lookups.
757 758
 *
 * This is also used to determine where to truncate pg_subtrans.  allDbs
759
 * must be TRUE for that case, and ignoreVacuum FALSE.
760
 *
761 762
 * GPDB: ignoreVacuum is ignored.
 *
763
 * Note: we include all currently running xids in the set of considered xids.
764 765
 * This ensures that if a just-started xact has not yet set its snapshot,
 * when it does set the snapshot it cannot set xmin less than what we compute.
766
 * See notes in src/backend/access/transam/README.
767 768
 */
TransactionId
769
GetOldestXmin(bool allDbs, bool ignoreVacuum)
770 771 772 773 774
{
	ProcArrayStruct *arrayP = procArray;
	TransactionId result;
	int			index;

775 776
	LWLockAcquire(ProcArrayLock, LW_SHARED);

777
	/*
B
Bruce Momjian 已提交
778 779 780 781
	 * We initialize the MIN() calculation with latestCompletedXid + 1. This
	 * is a lower bound for the XIDs that might appear in the ProcArray later,
	 * and so protects us against overestimating the result due to future
	 * additions.
782
	 */
783 784 785
	result = ShmemVariableCache->latestCompletedXid;
	Assert(TransactionIdIsNormal(result));
	TransactionIdAdvance(result);
786 787 788

	for (index = 0; index < arrayP->numProcs; index++)
	{
789
		volatile PGPROC *proc = arrayP->procs[index];
790

791 792 793 794 795
		if (allDbs || proc->databaseId == MyDatabaseId)
		{
			/* Fetch xid just once - see GetNewTransactionId */
			TransactionId xid = proc->xid;

796 797 798 799 800 801 802 803 804
			/* First consider the transaction's own Xid, if any */
			if (TransactionIdIsNormal(xid) &&
				TransactionIdPrecedes(xid, result))
				result = xid;

			/*
			 * Also consider the transaction's Xmin, if set.
			 *
			 * We must check both Xid and Xmin because a transaction might
B
Bruce Momjian 已提交
805 806
			 * have an Xmin but not (yet) an Xid; conversely, if it has an
			 * Xid, that could determine some not-yet-set Xmin.
807 808 809 810 811
			 */
			xid = proc->xmin;	/* Fetch just once */
			if (TransactionIdIsNormal(xid) &&
				TransactionIdPrecedes(xid, result))
				result = xid;
812 813 814 815 816 817 818 819
		}
	}

	LWLockRelease(ProcArrayLock);

	return result;
}

820 821 822 823 824 825 826 827 828
void
updateSharedLocalSnapshot(DtxContextInfo *dtxContextInfo, Snapshot snapshot, char *debugCaller)
{
	int combocidSize;

	Assert(SharedLocalSnapshotSlot != NULL);

	Assert(snapshot != NULL);

829 830 831 832 833 834 835
	ereport((Debug_print_full_dtm ? LOG : DEBUG5),
			(errmsg("updateSharedLocalSnapshot for DistributedTransactionContext = '%s' passed local snapshot (xmin: %u xmax: %u xcnt: %u) curcid: %d",
					DtxContextToString(DistributedTransactionContext),
					snapshot->xmin,
					snapshot->xmax,
					snapshot->xcnt,
					snapshot->curcid)));
836 837 838

	LWLockAcquire(SharedLocalSnapshotSlot->slotLock, LW_EXCLUSIVE);

839 840 841 842 843 844 845 846
	SharedLocalSnapshotSlot->snapshot.xmin = snapshot->xmin;
	SharedLocalSnapshotSlot->snapshot.xmax = snapshot->xmax;
	SharedLocalSnapshotSlot->snapshot.xcnt = snapshot->xcnt;

	if (snapshot->xcnt > 0)
	{
		Assert(snapshot->xip != NULL);

847 848 849
		ereport((Debug_print_full_dtm ? LOG : DEBUG5),
				(errmsg("updateSharedLocalSnapshot count of in-doubt ids %u",
						SharedLocalSnapshotSlot->snapshot.xcnt)));
850 851 852 853 854 855 856 857 858 859 860 861 862

		memcpy(SharedLocalSnapshotSlot->snapshot.xip, snapshot->xip, snapshot->xcnt * sizeof(TransactionId));
	}
	
	/* combocid stuff */
	combocidSize = ((usedComboCids < MaxComboCids) ? usedComboCids : MaxComboCids );

	SharedLocalSnapshotSlot->combocidcnt = combocidSize;	
	memcpy((void *)SharedLocalSnapshotSlot->combocids, comboCids,
		   combocidSize * sizeof(ComboCidKeyData));

	SharedLocalSnapshotSlot->snapshot.curcid = snapshot->curcid;

863 864 865
	ereport((Debug_print_full_dtm ? LOG : DEBUG5),
			(errmsg("updateSharedLocalSnapshot: combocidsize is now %d max %d segmateSync %d->%d",
					combocidSize, MaxComboCids, SharedLocalSnapshotSlot->segmateSync, dtxContextInfo->segmateSync)));
866

867
	SetSharedTransactionId_writer();
868 869 870 871 872 873 874 875
	
	SharedLocalSnapshotSlot->QDcid = dtxContextInfo->curcid;
	SharedLocalSnapshotSlot->QDxid = dtxContextInfo->distributedXid;
		
	SharedLocalSnapshotSlot->ready = true;

	SharedLocalSnapshotSlot->segmateSync = dtxContextInfo->segmateSync;

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
	ereport((Debug_print_full_dtm ? LOG : DEBUG5),
			(errmsg("updateSharedLocalSnapshot for DistributedTransactionContext = '%s' setting shared local snapshot xid = %u (xmin: %u xmax: %u xcnt: %u) curcid: %d, QDxid = %u, QDcid = %u",
					DtxContextToString(DistributedTransactionContext),
					SharedLocalSnapshotSlot->xid,
					SharedLocalSnapshotSlot->snapshot.xmin,
					SharedLocalSnapshotSlot->snapshot.xmax,
					SharedLocalSnapshotSlot->snapshot.xcnt,
					SharedLocalSnapshotSlot->snapshot.curcid,
					SharedLocalSnapshotSlot->QDxid,
					SharedLocalSnapshotSlot->QDcid)));

	ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
			(errmsg("[Distributed Snapshot #%u] *Writer Set Shared* gxid %u, currcid %d (gxid = %u, slot #%d, '%s', '%s')",
					QEDtxContextInfo.distributedSnapshot.distribSnapshotId,
					SharedLocalSnapshotSlot->QDxid,
					SharedLocalSnapshotSlot->QDcid,
					getDistributedTransactionId(),
					SharedLocalSnapshotSlot->slotid,
					debugCaller,
					DtxContextToString(DistributedTransactionContext))));
896
	LWLockRelease(SharedLocalSnapshotSlot->slotLock);
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916
}

static int
GetDistributedSnapshotMaxCount(void)
{
	switch (DistributedTransactionContext)
	{
	case DTX_CONTEXT_LOCAL_ONLY:
	case DTX_CONTEXT_QD_RETRY_PHASE_2:
	case DTX_CONTEXT_QE_FINISH_PREPARED:
		return 0;

	case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
		return max_prepared_xacts;

	case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
	case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
	case DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT:
	case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
	case DTX_CONTEXT_QE_READER:
917 918
		if (QEDtxContextInfo.distributedSnapshot.distribSnapshotId != 0)
			return QEDtxContextInfo.distributedSnapshot.maxCount;
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
		else
			return max_prepared_xacts;		/* UNDONE: For now? */
	
	case DTX_CONTEXT_QE_PREPARED:
		elog(FATAL, "Unexpected segment distribute transaction context: '%s'",
			 DtxContextToString(DistributedTransactionContext));
		break;
	
	default:
		elog(FATAL, "Unrecognized DTX transaction context: %d",
			(int) DistributedTransactionContext);
		break;
	}

	return 0;
}

936 937 938 939
/*
 * Fill in the array of in-progress distributed XIDS in 'snapshot' from the
 * information that the QE sent us (if any).
 */
940 941 942
static void
FillInDistributedSnapshot(Snapshot snapshot)
{
943 944 945 946
	ereport((Debug_print_full_dtm ? LOG : DEBUG5),
			(errmsg("FillInDistributedSnapshot DTX Context = '%s'",
					DtxContextToString(DistributedTransactionContext))));

947 948 949 950 951 952 953 954 955
	switch (DistributedTransactionContext)
	{
	case DTX_CONTEXT_LOCAL_ONLY:
	case DTX_CONTEXT_QD_RETRY_PHASE_2:
	case DTX_CONTEXT_QE_FINISH_PREPARED:
		/*
		 * No distributed snapshot.
		 */
		snapshot->haveDistribSnapshot = false;
956
		snapshot->distribSnapshotWithLocalMapping.ds.count = 0;
957 958 959 960
		break;

	case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
		/*
961 962
		 * GetSnapshotData() should've acquired the distributed snapshot
		 * while holding ProcArrayLock, not here.
963
		 */
964 965
		elog(ERROR, "FillInDistributedSnapshot called in context '%s'",
			 DtxContextToString(DistributedTransactionContext));
966 967 968 969 970 971 972 973 974 975 976 977 978
		break;

	case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
	case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
	case DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT:
	case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
	case DTX_CONTEXT_QE_READER:
		/*
		 * Copy distributed snapshot from the one sent by the QD.
		 */
		{
			DistributedSnapshot *ds = &QEDtxContextInfo.distributedSnapshot;

979
			if (ds->distribSnapshotId != 0)
980 981 982
			{
				snapshot->haveDistribSnapshot = true;

983 984
				Assert(ds->xminAllDistributedSnapshots);
				Assert(ds->xminAllDistributedSnapshots <= ds->xmin);
985

986
				DistributedSnapshot_Copy(&snapshot->distribSnapshotWithLocalMapping.ds, ds);
987 988 989 990
			}
			else
			{
				snapshot->haveDistribSnapshot = false;
991
				snapshot->distribSnapshotWithLocalMapping.ds.count = 0;
992 993 994
			}
		}
		break;
995

996 997 998 999
	case DTX_CONTEXT_QE_PREPARED:
		elog(FATAL, "Unexpected segment distribute transaction context: '%s'",
			 DtxContextToString(DistributedTransactionContext));
		break;
1000

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
	default:
		elog(FATAL, "Unrecognized DTX transaction context: %d",
			(int) DistributedTransactionContext);
		break;
	}

	/*
	 * Nice that we may have collected it, but turn it off...
	 */
	if (Debug_disable_distributed_snapshot)
		snapshot->haveDistribSnapshot = false;
}

/*
 * QEDtxContextInfo and SharedLocalSnapshotSlot are both global.
 */
static bool
QEwriterSnapshotUpToDate(void)
{
	Assert(!Gp_is_writer);

	if (SharedLocalSnapshotSlot == NULL)
		elog(ERROR, "SharedLocalSnapshotSlot is NULL");

1025 1026
	LWLockAcquire(SharedLocalSnapshotSlot->slotLock, LW_SHARED);
	bool result = QEDtxContextInfo.distributedXid == SharedLocalSnapshotSlot->QDxid &&
1027 1028
		QEDtxContextInfo.curcid == SharedLocalSnapshotSlot->QDcid &&
		QEDtxContextInfo.segmateSync == SharedLocalSnapshotSlot->segmateSync &&
1029 1030
		SharedLocalSnapshotSlot->ready;
	LWLockRelease(SharedLocalSnapshotSlot->slotLock);
1031

1032
	return result;
1033 1034
}

1035 1036 1037 1038
/*----------
 * GetSnapshotData -- returns information about running transactions.
 *
 * The returned snapshot includes xmin (lowest still-running xact ID),
1039
 * xmax (highest completed xact ID + 1), and a list of running xact IDs
1040 1041 1042 1043 1044 1045 1046 1047
 * in the range xmin <= xid < xmax.  It is used as follows:
 *		All xact IDs < xmin are considered finished.
 *		All xact IDs >= xmax are considered still running.
 *		For an xact ID xmin <= xid < xmax, consult list to see whether
 *		it is considered running or not.
 * This ensures that the set of transactions seen as "running" by the
 * current xact will not change after it takes the snapshot.
 *
1048 1049 1050 1051 1052 1053 1054
 * All running top-level XIDs are included in the snapshot, except for lazy
 * VACUUM processes.  We also try to include running subtransaction XIDs,
 * but since PGPROC has only a limited cache area for subxact XIDs, full
 * information may not be available.  If we find any overflowed subxid arrays,
 * we have to mark the snapshot's subxid data as overflowed, and extra work
 * will need to be done to determine what's running (see XidInMVCCSnapshot()
 * in tqual.c).
1055 1056 1057
 *
 * We also update the following backend-global variables:
 *		TransactionXmin: the oldest xmin of any snapshot in use in the
1058
 *			current transaction (this is the same as MyProc->xmin).
1059 1060 1061
 *		RecentXmin: the xmin computed for the most recent snapshot.  XIDs
 *			older than this are known not running any more.
 *		RecentGlobalXmin: the global xmin (oldest TransactionXmin across all
1062
 *			running transactions, except those running LAZY VACUUM).  This is
T
Tom Lane 已提交
1063
 *			the same computation done by GetOldestXmin(true, true).
1064 1065 1066
 *
 * Note: this function should probably not be called with an argument that's
 * not statically allocated (see xip allocation below).
1067 1068
 */
Snapshot
1069
GetSnapshotData(Snapshot snapshot)
1070 1071 1072 1073 1074 1075 1076
{
	ProcArrayStruct *arrayP = procArray;
	TransactionId xmin;
	TransactionId xmax;
	TransactionId globalxmin;
	int			index;
	int			count = 0;
1077
	int			subcount = 0;
1078 1079 1080 1081

	Assert(snapshot != NULL);

	/*
B
Bruce Momjian 已提交
1082 1083
	 * Allocating space for maxProcs xids is usually overkill; numProcs would
	 * be sufficient.  But it seems better to do the malloc while not holding
1084 1085
	 * the lock, so we can't look at numProcs.  Likewise, we allocate much
	 * more subxip storage than is probably needed.
1086 1087
	 *
	 * This does open a possibility for avoiding repeated malloc/free: since
B
Bruce Momjian 已提交
1088
	 * maxProcs does not change at runtime, we can simply reuse the previous
1089
	 * xip arrays if any.  (This relies on the fact that all callers pass
B
Bruce Momjian 已提交
1090
	 * static SnapshotData structs.)
1091 1092 1093 1094 1095 1096
	 */
	if (snapshot->xip == NULL)
	{
		/*
		 * First call for this snapshot
		 */
1097 1098
		snapshot->xip = (TransactionId *)
			malloc(arrayP->maxProcs * sizeof(TransactionId));
1099
		if (snapshot->xip == NULL)
1100 1101 1102
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
1103

1104
		Assert(snapshot->subxip == NULL);
1105 1106 1107 1108
	}

	if (snapshot->subxip == NULL)
	{
1109 1110 1111
		snapshot->subxip = (TransactionId *)
			malloc(arrayP->maxProcs * PGPROC_MAX_CACHED_SUBXIDS * sizeof(TransactionId));
		if (snapshot->subxip == NULL)
1112 1113 1114
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
1115 1116 1117 1118 1119
	}

	/*
	 * GP: Distributed snapshot.
	 */
1120 1121 1122 1123
	ereport((Debug_print_full_dtm ? LOG : DEBUG5),
			(errmsg("GetSnapshotData maxCount %d, inProgressEntryArray %p",
					snapshot->distribSnapshotWithLocalMapping.ds.maxCount,
					snapshot->distribSnapshotWithLocalMapping.ds.inProgressXidArray)));
1124 1125

	if (snapshot->distribSnapshotWithLocalMapping.ds.inProgressXidArray == NULL)
1126
	{
1127
		int maxCount = GetDistributedSnapshotMaxCount();
1128 1129
		if (maxCount > 0)
		{
1130 1131 1132 1133 1134 1135 1136
			snapshot->distribSnapshotWithLocalMapping.ds.inProgressXidArray =
				(DistributedTransactionId*)malloc(maxCount * sizeof(DistributedTransactionId));
			if (snapshot->distribSnapshotWithLocalMapping.ds.inProgressXidArray == NULL)
			{
				ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory")));
			}
			snapshot->distribSnapshotWithLocalMapping.ds.maxCount = maxCount;
1137

1138 1139 1140 1141 1142 1143 1144
			/*
			 * Allocate memory for local xid cache, currently allocating it
			 * same size as distributed, not necessary.
			 */
			snapshot->distribSnapshotWithLocalMapping.inProgressMappedLocalXids =
				(TransactionId*)malloc(maxCount * sizeof(TransactionId));
			if (snapshot->distribSnapshotWithLocalMapping.inProgressMappedLocalXids == NULL)
1145 1146 1147
			{
				ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory")));
			}
1148
			snapshot->distribSnapshotWithLocalMapping.maxLocalXidsCount = maxCount;
1149 1150 1151 1152
		}
	}

	/*
1153
	 * MPP Addition. if we are in EXECUTE mode and not the writer... then we
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
	 * want to just get the shared snapshot and make it our own.
	 *
	 * code for the writer is at the bottom of this function.
	 *
	 * NOTE: we could be dispatched and get here before the WRITER can set the
	 * shared snapshot.  if this happens we'll have to wait around, hopefully
	 * its never for a very long time.
	 *
	 */
	if (DistributedTransactionContext == DTX_CONTEXT_QE_READER ||
		DistributedTransactionContext == DTX_CONTEXT_QE_ENTRY_DB_SINGLETON)
	{
		/* the pg_usleep() call below is in units of us (microseconds), interconnect
		 * timeout is in seconds.  Start with 1 millisecond. */
		uint64		segmate_timeout_us;
		uint64		sleep_per_check_us = 1 * 1000;
		uint64	   	total_sleep_time_us = 0;
		uint64		warning_sleep_time_us = 0;

		segmate_timeout_us = (3 * (uint64)Max(interconnect_setup_timeout, 1) * 1000* 1000) / 4;

		/*
		 * Make a copy of the distributed snapshot information; this
		 * doesn't use the shared-snapshot-slot stuff it is just
		 * making copies from the QEDtxContextInfo structure sent by
		 * the QD.
		 */
		FillInDistributedSnapshot(snapshot);

		/*
		 * If we're a cursor-reader, we get out snapshot from the
		 * writer via a tempfile in the filesystem. Otherwise it is
		 * too easy for the writer to race ahead of cursor readers.
		 */
		if (QEDtxContextInfo.cursorContext)
		{
			readSharedLocalSnapshot_forCursor(snapshot);

			return snapshot;
		}

1195 1196 1197 1198 1199 1200
		ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
				(errmsg("[Distributed Snapshot #%u] *Start Reader Match* gxid = %u and currcid %d (%s)",
						QEDtxContextInfo.distributedSnapshot.distribSnapshotId,
						QEDtxContextInfo.distributedXid,
						QEDtxContextInfo.curcid,
						DtxContextToString(DistributedTransactionContext))));
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223

		/*
		 * This is the second phase of the handshake we started in
		 * StartTransaction().  Here we get a "good" snapshot from our
		 * writer. In the process it is possible that we will change
		 * our transaction's xid (see phase-one in StartTransaction()).
		 *
		 * Here we depend on the absolute correctness of our
		 * writer-gang's info. We need the segmateSync to match *as
		 * well* as the distributed-xid since the QD may send multiple
		 * statements with the same distributed-xid/cid but
		 * *different* local-xids (MPP-3228). The dispatcher will
		 * distinguish such statements by the segmateSync.
		 *
		 * I believe that we still want the older sync mechanism ("ready" flag).
		 * since it tells the code in TransactionIdIsCurrentTransactionId() that the
		 * writer may be changing the local-xid (otherwise it would be possible for
		 * cursor reader gangs to get confused).
		 */
		for (;;)
		{
			if (QEwriterSnapshotUpToDate())
			{
1224 1225
				LWLockAcquire(SharedLocalSnapshotSlot->slotLock, LW_SHARED);

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
				/*
				 * YAY we found it.  set the contents of the
				 * SharedLocalSnapshot to this and move on.
				 */
				snapshot->xmin = SharedLocalSnapshotSlot->snapshot.xmin;
				snapshot->xmax = SharedLocalSnapshotSlot->snapshot.xmax;
				snapshot->xcnt = SharedLocalSnapshotSlot->snapshot.xcnt;

				/* We now capture our current view of the xip/combocid arrays */
				memcpy(snapshot->xip, SharedLocalSnapshotSlot->snapshot.xip, snapshot->xcnt * sizeof(TransactionId));
				memset(snapshot->xip + snapshot->xcnt, 0, (arrayP->maxProcs - snapshot->xcnt) * sizeof(TransactionId));

				snapshot->curcid = SharedLocalSnapshotSlot->snapshot.curcid;

1240 1241
				snapshot->subxcnt = -1;

1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
				/* combocid */
				if (usedComboCids != SharedLocalSnapshotSlot->combocidcnt)
				{
					if (usedComboCids == 0)
					{
						MemoryContext oldCtx =  MemoryContextSwitchTo(TopTransactionContext);
						comboCids = palloc(SharedLocalSnapshotSlot->combocidcnt * sizeof(ComboCidKeyData));
						MemoryContextSwitchTo(oldCtx);
					}
					else
						repalloc(comboCids, SharedLocalSnapshotSlot->combocidcnt * sizeof(ComboCidKeyData));
				}
				memcpy(comboCids, (char *)SharedLocalSnapshotSlot->combocids, SharedLocalSnapshotSlot->combocidcnt * sizeof(ComboCidKeyData));
				usedComboCids = ((SharedLocalSnapshotSlot->combocidcnt < MaxComboCids) ? SharedLocalSnapshotSlot->combocidcnt : MaxComboCids);

1257 1258 1259 1260 1261
				uint32 segmateSync = SharedLocalSnapshotSlot->segmateSync;
				uint32 comboCidCnt = SharedLocalSnapshotSlot->combocidcnt;

				LWLockRelease(SharedLocalSnapshotSlot->slotLock);

1262 1263 1264 1265
				ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
						(errmsg("Reader qExec usedComboCids: %d shared %d segmateSync %d",
								usedComboCids, comboCidCnt, segmateSync)));

1266 1267
				SetSharedTransactionId_reader(SharedLocalSnapshotSlot->xid,
											  SharedLocalSnapshotSlot->snapshot.curcid);
1268

1269 1270 1271
				ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
						(errmsg("Reader qExec setting shared local snapshot to: xmin: %d xmax: %d curcid: %d",
								snapshot->xmin, snapshot->xmax, snapshot->curcid)));
1272

1273 1274 1275
				ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
						(errmsg("GetSnapshotData(): READER currentcommandid %d curcid %d segmatesync %d",
								GetCurrentCommandId(false), snapshot->curcid, segmateSync)));
1276 1277 1278 1279 1280 1281

				return snapshot;
			}
			else
			{
				/*
1282
				 * didn't find it. we'll sleep for a small amount of time and
1283 1284
				 * then try again.
				 *
1285
				 * TODO: is there a semaphore or something better we can do here.
1286 1287 1288 1289 1290 1291 1292 1293
				 */
				pg_usleep(sleep_per_check_us);

				CHECK_FOR_INTERRUPTS();

				warning_sleep_time_us += sleep_per_check_us;
				total_sleep_time_us += sleep_per_check_us;

1294 1295
				LWLockAcquire(SharedLocalSnapshotSlot->slotLock, LW_SHARED);

1296 1297 1298 1299 1300 1301
				if (total_sleep_time_us >= segmate_timeout_us)
				{
					ereport(ERROR,
							(errcode(ERRCODE_GP_INTERCONNECTION_ERROR),
							 errmsg("GetSnapshotData timed out waiting for Writer to set the shared snapshot."),
							 errdetail("We are waiting for the shared snapshot to have XID: %d but the value "
1302
									   "is currently: %d."
1303 1304 1305 1306 1307
									   " waiting for cid to be %d but is currently %d.  ready=%d."
									   "DistributedTransactionContext = %s. "
									   " Our slotindex is: %d \n"
									   "Dump of all sharedsnapshots in shmem: %s",
									   QEDtxContextInfo.distributedXid, SharedLocalSnapshotSlot->QDxid,
1308
									   QEDtxContextInfo.curcid,
1309
									   SharedLocalSnapshotSlot->QDcid, SharedLocalSnapshotSlot->ready,
1310 1311 1312 1313 1314 1315 1316 1317
									   DtxContextToString(DistributedTransactionContext),
									   SharedLocalSnapshotSlot->slotindex, SharedSnapshotDump())));
				}
				else if (warning_sleep_time_us > 1000 * 1000)
				{
					/*
					 * Every second issue warning.
					 */
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
					ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
							(errmsg("[Distributed Snapshot #%u] *No Match* gxid %u = %u and currcid %d = %d (%s)",
									QEDtxContextInfo.distributedSnapshot.distribSnapshotId,
									QEDtxContextInfo.distributedXid,
									SharedLocalSnapshotSlot->QDxid,
									QEDtxContextInfo.curcid,
									SharedLocalSnapshotSlot->QDcid,
									DtxContextToString(DistributedTransactionContext))));


					ereport(LOG,
							(errmsg("GetSnapshotData did not find shared local snapshot information. "
									"We are waiting for the shared snapshot to have XID: %d/%u but the value "
									"is currently: %d/%u."
									" waiting for cid to be %d but is currently %d.  ready=%d."
									" Our slotindex is: %d \n"
									"DistributedTransactionContext = %s.",
									QEDtxContextInfo.distributedXid, QEDtxContextInfo.segmateSync,
									SharedLocalSnapshotSlot->QDxid, SharedLocalSnapshotSlot->segmateSync,
									QEDtxContextInfo.curcid,
									SharedLocalSnapshotSlot->QDcid,
									SharedLocalSnapshotSlot->ready,
									SharedLocalSnapshotSlot->slotindex,
									DtxContextToString(DistributedTransactionContext))));
1342 1343 1344
					warning_sleep_time_us = 0;
				}

1345
				LWLockRelease(SharedLocalSnapshotSlot->slotLock);
1346 1347 1348
				/* UNDONE: Back-off from checking every millisecond... */
			}
		}
1349 1350
	}

1351 1352 1353 1354
	/* We must not be a reader. */
	Assert(DistributedTransactionContext != DTX_CONTEXT_QE_READER);
	Assert(DistributedTransactionContext != DTX_CONTEXT_QE_ENTRY_DB_SINGLETON);

1355
	/*
B
Bruce Momjian 已提交
1356
	 * It is sufficient to get shared lock on ProcArrayLock, even if we are
1357
	 * going to set MyProc->xmin.
1358
	 */
1359
	LWLockAcquire(ProcArrayLock, LW_SHARED);
1360

1361 1362 1363 1364
	/* xmax is always latestCompletedXid + 1 */
	xmax = ShmemVariableCache->latestCompletedXid;
	Assert(TransactionIdIsNormal(xmax));
	TransactionIdAdvance(xmax);
1365

1366 1367
	/* initialize xmin calculation with xmax */
	globalxmin = xmin = xmax;
1368

1369 1370 1371
	ereport((Debug_print_full_dtm ? LOG : DEBUG5),
			(errmsg("GetSnapshotData setting globalxmin and xmin to %u",
					xmin)));
1372

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
	/*
	 * Get the distributed snapshot if needed and copy it into the field 
	 * called distribSnapshotWithLocalMapping in the snapshot structure.
	 *
	 * For a distributed transaction:
	 *   => The corrresponding distributed snapshot is made up of distributed
	 *      xids from the DTM that are considered in-progress will be kept in
	 *      the snapshot structure separately from any local in-progress xact.
	 *
	 *      The MVCC function XidInSnapshot is used to evaluate whether
1383 1384
	 *      a tuple is visible through a snapshot. Only committed xids are
	 *      given to XidInSnapshot for evaluation. XidInSnapshot will first
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
	 *      determine if the committed tuple is for a distributed transaction.  
	 *      If the xact is distributed it will be evaluated only against the
	 *      distributed snapshot and not the local snapshot.
	 *
	 *      Otherwise, when the committed transaction being evaluated is local,
	 *      then it will be evaluated only against the local portion of the
	 *      snapshot.
	 *
	 * For a local transaction:
	 *   => Only the local portion of the snapshot: xmin, xmax, xcnt,
	 *      in-progress (xip), etc, will be filled in.
	 *
	 *      Note that in-progress distributed transactions that have reached
	 *      this database instance and are active will be represented in the
	 *      local in-progress (xip) array with the distributed transaction's
	 *      local xid.
	 *
	 * In summary: This 2 snapshot scheme (optional distributed, required local)
	 * handles late arriving distributed transactions properly since that work
1404
	 * is only evaluated against the distributed snapshot. And, the scheme
1405 1406 1407 1408
	 * handles local transaction work seeing distributed work properly by
	 * including distributed transactions in the local snapshot via their
	 * local xids.
	 */
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
	if (DistributedTransactionContext == DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
	{
		snapshot->haveDistribSnapshot = CreateDistributedSnapshot(&snapshot->distribSnapshotWithLocalMapping);

		ereport((Debug_print_full_dtm ? LOG : DEBUG5),
				(errmsg("Got distributed snapshot from DistributedSnapshotWithLocalXids_Create = %s",
						(snapshot->haveDistribSnapshot ? "true" : "false"))));

		/* Nice that we may have collected it, but turn it off... */
		if (Debug_disable_distributed_snapshot)
			snapshot->haveDistribSnapshot = false;
	}
1421 1422

	/*
B
Bruce Momjian 已提交
1423 1424
	 * Spin over procArray checking xid, xmin, and subxids.  The goal is to
	 * gather all active xids, find the lowest xmin, and try to record
B
Bruce Momjian 已提交
1425
	 * subxids.
1426
	 */
1427 1428
	for (index = 0; index < arrayP->numProcs; index++)
	{
1429
		volatile PGPROC *proc = arrayP->procs[index];
1430 1431
		TransactionId xid;

1432
#if 0 /* Upstream code not applicable to GPDB, why explained in vacuumStatement_Relation */
1433
		/* Ignore procs running LAZY VACUUM */
1434
		if (proc->vacuumFlags & PROC_IN_VACUUM)
1435
			continue;
1436
#endif
1437 1438

		/* Update globalxmin to be the smallest valid xmin */
1439
		xid = proc->xmin;		/* fetch just once */
1440 1441 1442
		if (TransactionIdIsNormal(xid) &&
			TransactionIdPrecedes(xid, globalxmin))
			globalxmin = xid;
1443 1444

		/* Fetch xid just once - see GetNewTransactionId */
1445
		xid = proc->xid;
1446 1447

		/*
1448
		 * If the transaction has been assigned an xid < xmax we add it to the
B
Bruce Momjian 已提交
1449
		 * snapshot, and update xmin if necessary.	There's no need to store
1450 1451
		 * XIDs >= xmax, since we'll treat them as running anyway.  We don't
		 * bother to examine their subxids either.
1452 1453 1454
		 *
		 * We don't include our own XID (if any) in the snapshot, but we must
		 * include it into xmin.
1455 1456
		 */
		if (TransactionIdIsNormal(xid))
1457
		{
1458 1459 1460 1461 1462 1463
			if (TransactionIdFollowsOrEquals(xid, xmax))
				continue;
			if (proc != MyProc)
				snapshot->xip[count++] = xid;
			if (TransactionIdPrecedes(xid, xmin))
				xmin = xid;
1464
		}
1465 1466 1467 1468

		/*
		 * Save subtransaction XIDs if possible (if we've already overflowed,
		 * there's no point).  Note that the subxact XIDs must be later than
1469 1470 1471
		 * their parent, so no need to check them against xmin.  We could
		 * filter against xmax, but it seems better not to do that much work
		 * while holding the ProcArrayLock.
1472 1473
		 *
		 * The other backend can add more subxids concurrently, but cannot
B
Bruce Momjian 已提交
1474 1475 1476
		 * remove any.	Hence it's important to fetch nxids just once. Should
		 * be safe to use memcpy, though.  (We needn't worry about missing any
		 * xids added concurrently, because they must postdate xmax.)
1477 1478
		 *
		 * Again, our own XIDs are not included in the snapshot.
1479
		 */
1480
		if (subcount >= 0 && proc != MyProc)
1481 1482
		{
			if (proc->subxids.overflowed)
B
Bruce Momjian 已提交
1483
				subcount = -1;	/* overflowed */
1484 1485
			else
			{
B
Bruce Momjian 已提交
1486
				int			nxids = proc->subxids.nxids;
1487 1488 1489 1490

				if (nxids > 0)
				{
					memcpy(snapshot->subxip + subcount,
1491
						   (void *) proc->subxids.xids,
1492 1493 1494 1495 1496
						   nxids * sizeof(TransactionId));
					subcount += nxids;
				}
			}
		}
1497 1498
	}

1499
	if (!TransactionIdIsValid(MyProc->xmin))
1500 1501 1502
	{
		/* Not that these values are not set atomically. However,
		 * each of these assignments is itself assumed to be atomic. */
1503
		MyProc->xmin = TransactionXmin = xmin;
1504 1505 1506 1507 1508
	}
	if (IsXactIsoLevelSerializable)
	{
		MyProc->serializableIsoLevel = true;

1509 1510 1511
		ereport((Debug_print_snapshot_dtm ? LOG : DEBUG3),
				(errmsg("Got serializable snapshot: database %d, pid %d, xid %d, xmin %d",
						MyProc->databaseId, MyProc->pid, MyProc->xid, MyProc->xmin)));
1512
	}
1513 1514 1515

	LWLockRelease(ProcArrayLock);

1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
	/*
	 * Fill in the distributed snapshot information we received from the the QD.
	 * Unless we are the QD, in which case we already created a new distributed
	 * snapshot above.
	 *
	 * (We do this after releasing ProcArrayLock, reduce contention.)
	 */
	if (DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
		FillInDistributedSnapshot(snapshot);

1526
	/*
B
Bruce Momjian 已提交
1527 1528 1529
	 * Update globalxmin to include actual process xids.  This is a slightly
	 * different way of computing it than GetOldestXmin uses, but should give
	 * the same result.
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
	 */
	if (TransactionIdPrecedes(xmin, globalxmin))
		globalxmin = xmin;

	/* Update global variables too */
	RecentGlobalXmin = globalxmin;
	RecentXmin = xmin;

	snapshot->xmin = xmin;
	snapshot->xmax = xmax;
	snapshot->xcnt = count;
1541
	snapshot->subxcnt = subcount;
1542

1543
	snapshot->curcid = GetCurrentCommandId(false);
1544

1545 1546 1547 1548 1549 1550 1551 1552
	/*
	 * This is a new snapshot, so set both refcounts are zero, and mark it
	 * as not copied in persistent memory.
	 */
	snapshot->active_count = 0;
	snapshot->regd_count = 0;
	snapshot->copied = false;

1553
	/*
1554 1555
	 * MPP Addition. If we are the chief then we'll save our local snapshot
	 * into the shared snapshot. Note: we need to use the shared local
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
	 * snapshot for the "Local Implicit using Distributed Snapshot" case, too.
	 */
	
	if ((DistributedTransactionContext == DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER ||
		 DistributedTransactionContext == DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER ||
		 DistributedTransactionContext == DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT) &&
		SharedLocalSnapshotSlot != NULL)
	{
		updateSharedLocalSnapshot(&QEDtxContextInfo, snapshot, "GetSnapshotData");
	}

1567 1568 1569
	ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
			(errmsg("GetSnapshotData(): WRITER currentcommandid %d curcid %d segmatesync %d",
					GetCurrentCommandId(false), snapshot->curcid, QEDtxContextInfo.segmateSync)));
1570

1571 1572 1573
	return snapshot;
}

1574
/*
1575 1576
 * GetVirtualXIDsDelayingChkpt -- Get the VXIDs of transactions that are
 * delaying checkpoint because they have critical actions in progress.
1577
 *
1578 1579
 * Constructs an array of VXIDs of transactions that are currently in commit
 * critical sections, as shown by having inCommit set in their PGXACT.
1580
 *
1581 1582
 * Returns a palloc'd array that should be freed by the caller.
 * *nvxids is the number of valid entries.
1583 1584 1585 1586 1587
 *
 * Note that because backends set or clear inCommit without holding any lock,
 * the result is somewhat indeterminate, but we don't really care.  Even in
 * a multiprocessor with delayed writes to shared memory, it should be certain
 * that setting of inCommit will propagate to shared memory when the backend
1588
 * takes a lock, so we cannot fail to see a virtual xact as inCommit if
1589 1590 1591
 * it's already inserted its commit record.  Whether it takes a little while
 * for clearing of inCommit to propagate is unimportant for correctness.
 */
1592 1593
VirtualTransactionId *
GetVirtualXIDsDelayingChkpt(int *nvxids)
1594
{
1595
	VirtualTransactionId *vxids;
1596
	ProcArrayStruct *arrayP = procArray;
1597
	int			count = 0;
B
Bruce Momjian 已提交
1598
	int			index;
1599

1600 1601 1602
	/* allocate what's certainly enough result space */
	vxids = (VirtualTransactionId *)
		palloc(sizeof(VirtualTransactionId) * arrayP->maxProcs);
1603 1604 1605 1606 1607

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
B
Bruce Momjian 已提交
1608 1609
		volatile PGPROC *proc = arrayP->procs[index];

1610 1611 1612
		if (proc->inCommit)
		{
			VirtualTransactionId vxid;
1613

1614 1615 1616 1617
			GET_VXID_FROM_PGPROC(vxid, *proc);
			if (VirtualTransactionIdIsValid(vxid))
				vxids[count++] = vxid;
		}
1618 1619 1620 1621
	}

	LWLockRelease(ProcArrayLock);

1622 1623
	*nvxids = count;
	return vxids;
1624 1625 1626
}

/*
1627
 * HaveVirtualXIDsDelayingChkpt -- Are any of the specified VXIDs delaying?
1628
 *
1629 1630
 * This is used with the results of GetVirtualXIDsDelayingChkpt to see if any
 * of the specified VXIDs are still in critical sections of code.
1631
 *
1632
 * Note: this is O(N^2) in the number of vxacts that are/were delaying, but
1633 1634 1635
 * those numbers should be small enough for it not to be a problem.
 */
bool
1636
HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids)
1637
{
B
Bruce Momjian 已提交
1638
	bool		result = false;
1639
	ProcArrayStruct *arrayP = procArray;
B
Bruce Momjian 已提交
1640
	int			index;
1641 1642 1643 1644 1645

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
B
Bruce Momjian 已提交
1646
		volatile PGPROC *proc = arrayP->procs[index];
1647
		VirtualTransactionId vxid;
B
Bruce Momjian 已提交
1648

1649
		GET_VXID_FROM_PGPROC(vxid, *proc);
1650

1651
		if (proc->inCommit && VirtualTransactionIdIsValid(vxid))
1652
		{
B
Bruce Momjian 已提交
1653
			int			i;
1654

1655
			for (i = 0; i < nvxids; i++)
1656
			{
1657
				if (VirtualTransactionIdEquals(vxid, vxids[i]))
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
				{
					result = true;
					break;
				}
			}
			if (result)
				break;
		}
	}

	LWLockRelease(ProcArrayLock);

	return result;
}

1673 1674 1675 1676
/*
 * MPP: Special code to update the command id in the SharedLocalSnapshot
 * when we are in SERIALIZABLE isolation mode.
 */
1677 1678
void
UpdateSerializableCommandId(CommandId curcid)
1679 1680 1681 1682
{
	if ((DistributedTransactionContext == DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER ||
		 DistributedTransactionContext == DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER) &&
		 SharedLocalSnapshotSlot != NULL &&
1683
		 FirstSnapshotSet)
1684 1685 1686
	{
		int combocidSize;

1687 1688
		LWLockAcquire(SharedLocalSnapshotSlot->slotLock, LW_EXCLUSIVE);

1689 1690
		if (SharedLocalSnapshotSlot->QDxid != QEDtxContextInfo.distributedXid)
		{
1691 1692 1693 1694 1695 1696
			ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
					(errmsg("[Distributed Snapshot #%u] *Can't Update Serializable Command Id* QDxid = %u (gxid = %u, '%s')",
							QEDtxContextInfo.distributedSnapshot.distribSnapshotId,
							SharedLocalSnapshotSlot->QDxid,
							getDistributedTransactionId(),
							DtxContextToString(DistributedTransactionContext))));
1697
			LWLockRelease(SharedLocalSnapshotSlot->slotLock);
1698 1699 1700
			return;
		}

1701
		ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
1702
				(errmsg("[Distributed Snapshot #%u] *Update Serializable Command Id* segment currcid = %d, QDcid = %d, TransactionSnapshot currcid = %d, Shared currcid = %d (gxid = %u, '%s')",
1703 1704 1705
						QEDtxContextInfo.distributedSnapshot.distribSnapshotId,
						QEDtxContextInfo.curcid,
						SharedLocalSnapshotSlot->QDcid,
1706
						curcid,
1707 1708 1709 1710 1711 1712 1713
						SharedLocalSnapshotSlot->snapshot.curcid,
						getDistributedTransactionId(),
						DtxContextToString(DistributedTransactionContext))));

		ereport((Debug_print_snapshot_dtm ? LOG : DEBUG5),
				(errmsg("serializable writer updating combocid: used combocids %d shared %d",
						usedComboCids, SharedLocalSnapshotSlot->combocidcnt)));
1714 1715 1716 1717 1718 1719 1720

		combocidSize = ((usedComboCids < MaxComboCids) ? usedComboCids : MaxComboCids );

		SharedLocalSnapshotSlot->combocidcnt = combocidSize;	
		memcpy((void *)SharedLocalSnapshotSlot->combocids, comboCids,
			   combocidSize * sizeof(ComboCidKeyData));

1721
		SharedLocalSnapshotSlot->snapshot.curcid = curcid;
1722 1723 1724
		SharedLocalSnapshotSlot->QDcid = QEDtxContextInfo.curcid;
		SharedLocalSnapshotSlot->segmateSync = QEDtxContextInfo.segmateSync;

1725
		LWLockRelease(SharedLocalSnapshotSlot->slotLock);
1726 1727 1728
	}
}

1729 1730
/*
 * BackendPidGetProc -- get a backend's PGPROC given its PID
1731 1732 1733 1734
 *
 * Returns NULL if not found.  Note that it is up to the caller to be
 * sure that the question remains meaningful for long enough for the
 * answer to be used ...
1735
 */
1736
PGPROC *
1737 1738 1739 1740 1741 1742
BackendPidGetProc(int pid)
{
	PGPROC	   *result = NULL;
	ProcArrayStruct *arrayP = procArray;
	int			index;

1743 1744 1745
	if (pid == 0)				/* never match dummy PGPROCs */
		return NULL;

1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
		PGPROC	   *proc = arrayP->procs[index];

		if (proc->pid == pid)
		{
			result = proc;
			break;
		}
	}

	LWLockRelease(ProcArrayLock);

	return result;
}

T
Tatsuo Ishii 已提交
1764 1765 1766 1767 1768 1769
/*
 * BackendXidGetPid -- get a backend's pid given its XID
 *
 * Returns 0 if not found or it's a prepared transaction.  Note that
 * it is up to the caller to be sure that the question remains
 * meaningful for long enough for the answer to be used ...
B
Bruce Momjian 已提交
1770
 *
T
Tatsuo Ishii 已提交
1771 1772
 * Only main transaction Ids are considered.  This function is mainly
 * useful for determining what backend owns a lock.
1773
 *
B
Bruce Momjian 已提交
1774
 * Beware that not every xact has an XID assigned.	However, as long as you
1775
 * only call this using an XID found on disk, you're safe.
T
Tatsuo Ishii 已提交
1776 1777 1778 1779
 */
int
BackendXidGetPid(TransactionId xid)
{
B
Bruce Momjian 已提交
1780
	int			result = 0;
T
Tatsuo Ishii 已提交
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
	ProcArrayStruct *arrayP = procArray;
	int			index;

	if (xid == InvalidTransactionId)	/* never match invalid xid */
		return 0;

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
1791
		volatile PGPROC *proc = arrayP->procs[index];
T
Tatsuo Ishii 已提交
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804

		if (proc->xid == xid)
		{
			result = proc->pid;
			break;
		}
	}

	LWLockRelease(ProcArrayLock);

	return result;
}

1805 1806 1807 1808 1809 1810 1811 1812 1813
/*
 * IsBackendPid -- is a given pid a running backend
 */
bool
IsBackendPid(int pid)
{
	return (BackendPidGetProc(pid) != NULL);
}

1814 1815 1816 1817 1818 1819 1820

/*
 * GetCurrentVirtualXIDs -- returns an array of currently active VXIDs.
 *
 * The array is palloc'd and is terminated with an invalid VXID.
 *
 * If limitXmin is not InvalidTransactionId, we skip any backends
B
Bruce Momjian 已提交
1821
 * with xmin >= limitXmin.	If allDbs is false, we skip backends attached
1822 1823 1824
 * to other databases.  If excludeVacuum isn't zero, we skip processes for
 * which (excludeVacuum & vacuumFlags) is not zero.  Also, our own process
 * is always skipped.
1825 1826
 */
VirtualTransactionId *
1827
GetCurrentVirtualXIDs(TransactionId limitXmin, bool allDbs, int excludeVacuum)
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
{
	VirtualTransactionId *vxids;
	ProcArrayStruct *arrayP = procArray;
	int			count = 0;
	int			index;

	/* allocate result space with room for a terminator */
	vxids = (VirtualTransactionId *)
		palloc(sizeof(VirtualTransactionId) * (arrayP->maxProcs + 1));

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
B
Bruce Momjian 已提交
1842
		volatile PGPROC *proc = arrayP->procs[index];
1843 1844 1845 1846

		if (proc == MyProc)
			continue;

1847 1848 1849
		if (excludeVacuum & proc->vacuumFlags)
			continue;

1850
		if (allDbs || proc->databaseId == MyDatabaseId)
1851
		{
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
			/* Fetch xmin just once - might change on us? */
			TransactionId pxmin = proc->xmin;

			/*
			 * Note that InvalidTransactionId precedes all other XIDs, so a
			 * proc that hasn't set xmin yet will always be included.
			 */
			if (!TransactionIdIsValid(limitXmin) ||
				TransactionIdPrecedes(pxmin, limitXmin))
			{
				VirtualTransactionId vxid;
1863

1864 1865 1866 1867
				GET_VXID_FROM_PGPROC(vxid, *proc);
				if (VirtualTransactionIdIsValid(vxid))
					vxids[count++] = vxid;
			}
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
		}
	}

	LWLockRelease(ProcArrayLock);

	/* add the terminator */
	vxids[count].backendId = InvalidBackendId;
	vxids[count].localTransactionId = InvalidLocalTransactionId;

	return vxids;
}


1881 1882 1883 1884 1885
/*
 * CountActiveBackends --- count backends (other than myself) that are in
 *		active transactions.  This is used as a heuristic to decide if
 *		a pre-XLOG-flush delay is worthwhile during commit.
 *
1886 1887
 * Do not count backends that are blocked waiting for locks, since they are
 * not going to get to run until someone else commits.
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
 */
int
CountActiveBackends(void)
{
	ProcArrayStruct *arrayP = procArray;
	int			count = 0;
	int			index;

	/*
	 * Note: for speed, we don't acquire ProcArrayLock.  This is a little bit
B
Bruce Momjian 已提交
1898 1899
	 * bogus, but since we are only testing fields for zero or nonzero, it
	 * should be OK.  The result is only used for heuristic purposes anyway...
1900 1901 1902
	 */
	for (index = 0; index < arrayP->numProcs; index++)
	{
1903 1904 1905 1906 1907 1908 1909 1910 1911
		volatile PGPROC *proc = arrayP->procs[index];

		/*
		 * Since we're not holding a lock, need to check that the pointer is
		 * valid. Someone holding the lock could have incremented numProcs
		 * already, but not yet inserted a valid pointer to the array.
		 *
		 * If someone just decremented numProcs, 'proc' could also point to a
		 * PGPROC entry that's no longer in the array. It still points to a
1912 1913 1914
		 * PGPROC struct, though, because freed PGPPROC entries just go to
		 * the free list and are recycled. Its contents are nonsense in that
		 * case, but that's acceptable for this function.
1915 1916 1917
		 */
		if (proc == NULL)
			continue;
1918 1919 1920

		if (proc == MyProc)
			continue;			/* do not count myself */
1921 1922 1923
		if (proc->pid == 0)
			continue;			/* do not count prepared xacts */
		if (proc->xid == InvalidTransactionId)
1924
			continue;			/* do not count if no XID assigned */
1925 1926 1927 1928 1929 1930 1931 1932
		if (proc->waitLock != NULL)
			continue;			/* do not count if blocked on a lock */
		count++;
	}

	return count;
}

1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
/*
 * CountDBBackends --- count backends that are using specified database
 */
int
CountDBBackends(Oid databaseid)
{
	ProcArrayStruct *arrayP = procArray;
	int			count = 0;
	int			index;

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
1947
		volatile PGPROC *proc = arrayP->procs[index];
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973

		if (proc->pid == 0)
			continue;			/* do not count prepared xacts */
		if (proc->databaseId == databaseid)
			count++;
	}

	LWLockRelease(ProcArrayLock);

	return count;
}

/*
 * CountUserBackends --- count backends that are used by specified user
 */
int
CountUserBackends(Oid roleid)
{
	ProcArrayStruct *arrayP = procArray;
	int			count = 0;
	int			index;

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
1974
		volatile PGPROC *proc = arrayP->procs[index];
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986

		if (proc->pid == 0)
			continue;			/* do not count prepared xacts */
		if (proc->roleId == roleid)
			count++;
	}

	LWLockRelease(ProcArrayLock);

	return count;
}

1987
/*
1988
 * CountOtherDBBackends -- check for other backends running in the given DB
1989 1990 1991 1992 1993 1994 1995 1996 1997
 *
 * If there are other backends in the DB, we will wait a maximum of 5 seconds
 * for them to exit.  Autovacuum backends are encouraged to exit early by
 * sending them SIGTERM, but normal user backends are just waited for.
 *
 * The current backend is always ignored; it is caller's responsibility to
 * check whether the current backend uses the given DB, if it's important.
 *
 * Returns TRUE if there are (still) other backends in the DB, FALSE if not.
1998 1999
 * Also, *nbackends and *nprepared are set to the number of other backends
 * and prepared transactions in the DB, respectively.
2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
 *
 * This function is used to interlock DROP DATABASE and related commands
 * against there being any active backends in the target DB --- dropping the
 * DB while active backends remain would be a Bad Thing.  Note that we cannot
 * detect here the possibility of a newly-started backend that is trying to
 * connect to the doomed database, so additional interlocking is needed during
 * backend startup.  The caller should normally hold an exclusive lock on the
 * target DB before calling this, which is one reason we mustn't wait
 * indefinitely.
 */
bool
2011
CountOtherDBBackends(Oid databaseId, int *nbackends, int *nprepared)
2012 2013
{
	ProcArrayStruct *arrayP = procArray;
2014 2015
#define MAXAUTOVACPIDS  10		/* max autovacs to SIGTERM per iteration */
	int			autovac_pids[MAXAUTOVACPIDS];
2016 2017 2018 2019 2020
	int			tries;

	/* 50 tries with 100ms sleep between tries makes 5 sec total wait */
	for (tries = 0; tries < 50; tries++)
	{
2021
		int			nautovacs = 0;
2022 2023 2024 2025 2026
		bool		found = false;
		int			index;

		CHECK_FOR_INTERRUPTS();

2027 2028
		*nbackends = *nprepared = 0;

2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
		LWLockAcquire(ProcArrayLock, LW_SHARED);

		for (index = 0; index < arrayP->numProcs; index++)
		{
			volatile PGPROC *proc = arrayP->procs[index];

			if (proc->databaseId != databaseId)
				continue;
			if (proc == MyProc)
				continue;

			found = true;

2042 2043
			if (proc->pid == 0)
				(*nprepared)++;
2044 2045
			else
			{
2046 2047 2048 2049
				(*nbackends)++;
				if ((proc->vacuumFlags & PROC_IS_AUTOVACUUM) &&
					nautovacs < MAXAUTOVACPIDS)
					autovac_pids[nautovacs++] = proc->pid;
2050 2051 2052
			}
		}

2053 2054
		LWLockRelease(ProcArrayLock);

2055 2056 2057
		if (!found)
			return false;		/* no conflicting backends, so done */

2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
		/*
		 * Send SIGTERM to any conflicting autovacuums before sleeping.
		 * We postpone this step until after the loop because we don't
		 * want to hold ProcArrayLock while issuing kill().
		 * We have no idea what might block kill() inside the kernel...
		 */
		for (index = 0; index < nautovacs; index++)
			(void) kill(autovac_pids[index], SIGTERM);	/* ignore any error */

		/* sleep, then try again */
2068 2069 2070 2071 2072 2073
		pg_usleep(100 * 1000L); /* 100ms */
	}

	return true;				/* timed out, still conflicts */
}

2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086

#define XidCacheRemove(i) \
	do { \
		MyProc->subxids.xids[i] = MyProc->subxids.xids[MyProc->subxids.nxids - 1]; \
		MyProc->subxids.nxids--; \
	} while (0)

/*
 * XidCacheRemoveRunningXids
 *
 * Remove a bunch of TransactionIds from the list of known-running
 * subtransactions for my backend.	Both the specified xid and those in
 * the xids[] array (of length nxids) are removed from the subxids cache.
2087
 * latestXid must be the latest XID among the group.
2088 2089
 */
void
2090 2091 2092
XidCacheRemoveRunningXids(TransactionId xid,
						  int nxids, const TransactionId *xids,
						  TransactionId latestXid)
2093 2094 2095 2096
{
	int			i,
				j;

2097
	Assert(TransactionIdIsValid(xid));
2098 2099 2100

	/*
	 * We must hold ProcArrayLock exclusively in order to remove transactions
2101 2102 2103 2104
	 * from the PGPROC array.  (See src/backend/access/transam/README.)  It's
	 * possible this could be relaxed since we know this routine is only used
	 * to abort subtransactions, but pending closer analysis we'd best be
	 * conservative.
2105 2106 2107 2108
	 */
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

	/*
B
Bruce Momjian 已提交
2109 2110 2111
	 * Under normal circumstances xid and xids[] will be in increasing order,
	 * as will be the entries in subxids.  Scan backwards to avoid O(N^2)
	 * behavior when removing a lot of xids.
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
	 */
	for (i = nxids - 1; i >= 0; i--)
	{
		TransactionId anxid = xids[i];

		for (j = MyProc->subxids.nxids - 1; j >= 0; j--)
		{
			if (TransactionIdEquals(MyProc->subxids.xids[j], anxid))
			{
				XidCacheRemove(j);
				break;
			}
		}
B
Bruce Momjian 已提交
2125

2126
		/*
B
Bruce Momjian 已提交
2127 2128 2129 2130 2131
		 * Ordinarily we should have found it, unless the cache has
		 * overflowed. However it's also possible for this routine to be
		 * invoked multiple times for the same subtransaction, in case of an
		 * error during AbortSubTransaction.  So instead of Assert, emit a
		 * debug warning.
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
		 */
		if (j < 0 && !MyProc->subxids.overflowed)
			elog(WARNING, "did not find subXID %u in MyProc", anxid);
	}

	for (j = MyProc->subxids.nxids - 1; j >= 0; j--)
	{
		if (TransactionIdEquals(MyProc->subxids.xids[j], xid))
		{
			XidCacheRemove(j);
			break;
		}
	}
	/* Ordinarily we should have found it, unless the cache has overflowed */
	if (j < 0 && !MyProc->subxids.overflowed)
		elog(WARNING, "did not find subXID %u in MyProc", xid);

2149 2150 2151 2152 2153
	/* Also advance global latestCompletedXid while holding the lock */
	if (TransactionIdPrecedes(ShmemVariableCache->latestCompletedXid,
							  latestXid))
		ShmemVariableCache->latestCompletedXid = latestXid;

2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
	LWLockRelease(ProcArrayLock);
}

#ifdef XIDCACHE_DEBUG

/*
 * Print stats about effectiveness of XID cache
 */
static void
DisplayXidCache(void)
{
	fprintf(stderr,
2166
			"XidCache: xmin: %ld, known: %ld, myxact: %ld, latest: %ld, mainxid: %ld, childxid: %ld, nooflo: %ld, slow: %ld\n",
2167
			xc_by_recent_xmin,
2168
			xc_by_known_xact,
2169
			xc_by_my_xact,
2170
			xc_by_latest_xid,
2171 2172
			xc_by_main_xid,
			xc_by_child_xid,
2173
			xc_no_overflow,
2174 2175 2176 2177
			xc_slow_answer);
}

#endif   /* XIDCACHE_DEBUG */
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258

PGPROC *
FindProcByGpSessionId(long gp_session_id)
{
	/* Find the guy who should manage our locks */
	ProcArrayStruct *arrayP = procArray;
	int			index;

	Assert(gp_session_id > 0);
		
	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (index = 0; index < arrayP->numProcs; index++)
	{
		PGPROC	   *proc = arrayP->procs[index];
			
		if (proc->pid == MyProc->pid)
			continue;
				
		if (!proc->mppIsWriter)
			continue;
				
		if (proc->mppSessionId == gp_session_id)
		{
			LWLockRelease(ProcArrayLock);
			return proc;
		}
	}
		
	LWLockRelease(ProcArrayLock);
	return NULL;
}

/*
 * FindAndSignalProcess
 *     Find the PGPROC entry in procArray which contains the given sessionId and commandId,
 *     and send the corresponding process an interrupt signal.
 *
 * This function returns false if not such an entry found in procArray or the interrupt
 * signal can not be sent to the process.
 */
bool
FindAndSignalProcess(int sessionId, int commandId)
{
	Assert(sessionId > 0 && commandId > 0);
	bool queryCancelled = false;
	int pid = 0;

	LWLockAcquire(ProcArrayLock, LW_SHARED);

	for (int index = 0; index < procArray->numProcs; index++)
	{
		PGPROC *proc = procArray->procs[index];
		
		if (proc->mppSessionId == sessionId &&
			proc->queryCommandId == commandId)
		{
			/* If we have setsid(), signal the backend's whole process group */
#ifdef HAVE_SETSID
			if (kill(-proc->pid, SIGINT) == 0)
#else
			if (kill(proc->pid, SIGINT) == 0)
#endif
			{
				pid = proc->pid;
				queryCancelled = true;
			}
			
			break;
		}
	}

	LWLockRelease(ProcArrayLock);

	if (gp_cancel_query_print_log && queryCancelled)
	{
		elog(NOTICE, "sent an interrupt to process %d", pid);
	}

	return queryCancelled;
}