cdbtm.c 118.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*-------------------------------------------------------------------------
 *
 * cdbtm.c
 *	  Provides routines for performing distributed transaction
 *
 * Copyright (c) 2005-2009, Greenplum inc
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>

H
Heikki Linnakangas 已提交
18
#include "catalog/pg_authid.h"
19 20 21 22 23 24
#include "cdb/cdbtm.h"
#include "libpq/libpq-be.h"
#include "miscadmin.h"
#include "storage/shmem.h"
#include "storage/ipc.h"
#include "cdb/cdbdisp.h"
25 26
#include "cdb/cdbdisp_query.h"
#include "cdb/cdbdisp_dtx.h"
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include "cdb/cdbdtxcontextinfo.h"

#include "cdb/cdbvars.h"
#include "gp-libpq-fe.h"
#include "access/transam.h"
#include "access/xact.h"
#include "cdb/cdbfts.h"
#include "lib/stringinfo.h"
#include "access/twophase.h"
#include "access/distributedlog.h"
#include "postmaster/postmaster.h"
#include "cdb/cdbpersistentrecovery.h"
#include "cdb/cdbpersistentcheck.h"

#include "cdb/cdbllize.h"
#include "utils/faultinjector.h"
#include "utils/fmgroids.h"
#include "utils/memutils.h"
45
#include "utils/sharedsnapshot.h"
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

extern bool Test_print_direct_dispatch_info;
extern struct Port *MyProcPort;

#define DTM_DEBUG3 (Debug_print_full_dtm ? LOG : DEBUG3)
#define DTM_DEBUG5 (Debug_print_full_dtm ? LOG : DEBUG5)

/*
 * Directory where Utility Mode DTM REDO file reside within PGDATA
 */
#define UTILITYMODEDTMREDO_DIR "pg_utilitymodedtmredo"

/*
 * File name for Utility Mode DTM REDO
 */
#define UTILITYMODEDTMREDO_FILE "savedtmredo.file"

static LWLockId shmControlLock;
static volatile bool *shmTmRecoverred;
static volatile DistributedTransactionTimeStamp *shmDistribTimeStamp;
static volatile DistributedTransactionId *shmGIDSeq;
static volatile int *shmNumGxacts;
static int *shmCurrentPhase1Count;

static int	ControlLockCount = 0;

volatile int *shmSegmentCount;
volatile int *shmSegmentStatesByteLen;

DistributedTransactionId *shmXminAllDistributedSnapshots;
uint32 					 *shmNextSnapshotId;

volatile bool	*shmDtmStarted;
volatile bool	*shmDtmRecoveryDeferred; /* when starting in readonly mode */

/* global transaction array */
static TMGXACT **shmGxactArray;

/**
 * This pointer into shared memory is on the QD, and represents the current open transaction.
 */
static TMGXACT *currentGxact;

static bool duringRecovery = false;
static int	max_tm_gxacts = 100;

static int	redoFileFD = -1;
static int  redoFileOffset;

typedef struct InDoubtDtx
{
	char		gid[TMGIDSIZE];
}	InDoubtDtx;


/* here are some flag options relationed to the txnOptions field of
 * PQsendGpQuery
 */

/* bit 1 is for statement wants DTX transaction
 *
 * bits 2-3 for iso level  00 read-committed
 *						   01 read-uncommitted
 *						   10 repeatable-read
 *						   11 serializable
 * bit 4 is for read-only
 */
#define GP_OPT_NEED_TWO_PHASE                           0x0001

#define GP_OPT_READ_COMMITTED    						0x0002
#define GP_OPT_READ_UNCOMMITTED  						0x0004
#define GP_OPT_REPEATABLE_READ   						0x0006
#define GP_OPT_SERIALIZABLE 	  						0x0008

#define GP_OPT_READ_ONLY         						0x0010

#define GP_OPT_EXPLICT_BEGIN      						0x0020

/*=========================================================================
 * FUNCTIONS PROTOTYPES
 */
static void initGxact(TMGXACT * gxact);
static void releaseGxact_UnderLocks(void);
static void releaseGxact(void);
static void generateGID(char *gid, DistributedTransactionId *gxid);

static void recoverTM(void);
static bool recoverInDoubtTransactions(void);
static HTAB *gatherRMInDoubtTransactions(void);
static void abortRMInDoubtTransactions(HTAB *htab);

static void dumpAllDtx(void);
/* static void resolveInDoubtDtx(void); */
static void dumpRMOnlyDtx(HTAB *htab, StringInfoData *buff);

static bool doDispatchDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand, int flags,
										 char* gid, DistributedTransactionId gxid,
										 bool *badGangs, bool raiseError, CdbDispatchDirectDesc *direct,
144
										 char *serializedDtxContextInfo, int serializedDtxContextInfoLen);
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
static void doPrepareTransaction(void);
static void doInsertForgetCommitted(void);
static void doNotifyingCommitPrepared(void);
static void doNotifyingAbort(void);
static bool doNotifyCommittedInDoubt(char *gid);
static void doAbortInDoubt(char *gid);
static void doQEDistributedExplicitBegin(int txnOptions);

static bool isDtxQueryDispatcher(void);
static void UtilityModeSaveRedo(bool committed, TMGXACT_LOG * gxact_log);
static void ReplayRedoFromUtilityMode(void);
static void RemoveRedoUtilityModeFile(void);
static void performDtxProtocolCommitPrepared(const char *gid, bool raiseErrorIfNotFound);
static void performDtxProtocolAbortPrepared(const char *gid, bool raiseErrorIfNotFound);
static DistributedTransactionId determineSegmentMaxDistributedXid(void);

G
Gang Xiong 已提交
161
extern void resetSessionForPrimaryGangLoss(bool resetSession);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 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 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 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 692 693 694 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 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
extern void CheckForResetSession(void);

/**
 * All assignments of the global DistributedTransactionContext should go through this function
 *   (so we can add logging here to see all assignments)
 *
 * @param context the new value for DistributedTransactionContext
 */
static void
setDistributedTransactionContext(DtxContext context)
{
	// elog(INFO, "Setting DistributedTransactionContext to '%s'", DtxContextToString(context));
	DistributedTransactionContext = context;
}

static void
requireDistributedTransactionContext(DtxContext requiredCurrentContext)
{
	if (DistributedTransactionContext != requiredCurrentContext)
	{
		elog(FATAL, "Expected segment distributed transaction context to be '%s', found '%s'",
			 DtxContextToString(requiredCurrentContext),
			 DtxContextToString(DistributedTransactionContext));
	}
}

static void
setGxactState(TMGXACT *transaction, DtxState state)
{
	Assert(transaction != NULL);
	// elog(INFO, "Setting transaction state to '%s'", DtxStateToString(state));
	transaction->state = state;
}

/**
 * All assignments of currentGxact->state should go through this function
 *   (so we can add logging here to see all assignments)
 *
 * This should only be called when currentGxact is non-NULL
 *
 * @param state the new value for currentGxact->state
 */
static void
setCurrentGxactState(DtxState state)
{
	setGxactState(currentGxact, state);
}

/**
 * Does DistributedTransactionContext indicate that this is acting as a QD?
 */
static bool
isQDContext(void)
{
    switch (DistributedTransactionContext)
	{
		case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
		case DTX_CONTEXT_QD_RETRY_PHASE_2:
			return true;
		default:
			return false;
	}
}

/**
 * Does DistributedTransactionContext indicate that this is acting as a QE?
 */
static bool
isQEContext()
{
	switch(DistributedTransactionContext)
	{
		case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
		case DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT:
		case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
		case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
		case DTX_CONTEXT_QE_READER:
			return true;
		default:
			return false;
	}
}

/*=========================================================================
 * VISIBLE FUNCTIONS
 */

DistributedTransactionTimeStamp
getDtxStartTime(void)
{
	if (shmDistribTimeStamp != NULL)
		return *shmDistribTimeStamp;
	else
		return 0;
}

DistributedTransactionId
getDistributedTransactionId(void)
{
	if ( isQDContext())
	{
		return currentGxact == NULL
			? InvalidDistributedTransactionId
			: currentGxact->gxid;
	}
	else if ( isQEContext())
	{
		return QEDtxContextInfo.distributedXid;
	}
	else
	{
		return InvalidDistributedTransactionId;
	}
}

bool
getDistributedTransactionIdentifier(char *id)
{
	if ( isQDContext())
	{
		if (currentGxact != NULL)
		{
			/*
			 * The length check here requires the identifer have a trailing NUL character.
			 */
			if (strlen(currentGxact->gid) >= TMGIDSIZE)
				elog(PANIC, "Distribute transaction identifier too long (%d)",
					 (int)strlen(currentGxact->gid));
			memcpy(id, currentGxact->gid, TMGIDSIZE);
			return true;
		}
	}
	else if ( isQEContext())
	{
		if (QEDtxContextInfo.distributedXid != InvalidDistributedTransactionId)
		{
			if (strlen(QEDtxContextInfo.distributedId) >= TMGIDSIZE)
				elog(PANIC, "Distribute transaction identifier too long (%d)",
					 (int)strlen(QEDtxContextInfo.distributedId));
			memcpy(id, QEDtxContextInfo.distributedId, TMGIDSIZE);
			return true;
		}
	}

	MemSet(id, 0, TMGIDSIZE);
	return false;
}

bool
isPreparedDtxTransaction(void)
{
	if (Gp_role != GP_ROLE_DISPATCH ||
		DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE ||
		currentGxact == NULL)
		return false;

	return (currentGxact->state == DTX_STATE_PREPARED);
}

void
getDtxLogInfo(TMGXACT_LOG *gxact_log)
{
	if (currentGxact == NULL)
	{
		elog(FATAL, "getDtxLogInfo found current distributed transaction is NULL");
	}

	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
			 (int)strlen(currentGxact->gid));
	memcpy(gxact_log->gid, currentGxact->gid, TMGIDSIZE);
	gxact_log->gxid = currentGxact->gxid;
}

bool
notifyCommittedDtxTransactionIsNeeded(void)
{
	if (DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
	{
	    elog(DTM_DEBUG5, "notifyCommittedDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
			 DtxContextToString(DistributedTransactionContext));
		return false;
	}

	if (currentGxact == NULL)
	{
	    elog(DTM_DEBUG5, "notifyCommittedDtxTransaction nothing to do (currentGxact == NULL)");
		return false;
	}

	return true;
}

/*
 * Notify commited a global transaction, called by user commit
 * or by CommitTransaction
 */
void
notifyCommittedDtxTransaction(void)
{
	Assert (DistributedTransactionContext == DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE);

	Assert (currentGxact != NULL);

	doNotifyingCommitPrepared();
}

static inline void
copyDirectDispatchFromTransaction(CdbDispatchDirectDesc *dOut)
{
	if (currentGxact->directTransaction)
	{
		dOut->directed_dispatch = true;
		dOut->count = 1;
		dOut->content[0] = currentGxact->directTransactionContentId;
	}
	else
	{
		dOut->directed_dispatch = false;
	}
}

static bool
GetRootNodeIsDirectDispatch(PlannedStmt *stmt)
{
	if ( stmt == NULL )
		return false;

	if ( stmt->planTree == NULL)
		return false;

	return stmt->planTree->directDispatch.isDirectDispatch;
}

/**
 * note that the ability to look at the root node of a plan in order to determine
 *    direct dispatch overall depends on the way we assign direct dispatch.  Parent slices are
 *    never more directed than child slices.  This could be fixed with an iteration over all slices and
 *    combine from every slice.
 *
 * return true IFF the directDispatch data stored in n should be applied to the transaction
 */
static bool
GetPlannedStmtDirectDispatch_AndUsingNodeIsSufficient(PlannedStmt *stmt)
{
	if ( ! GetRootNodeIsDirectDispatch(stmt))
		return false;

	/*
	 * now look at number initplans .. we do something simple.  ANY initPlans means we don't do directDispatch
	 *  at the dtm level.  It's technically possible that the initPlan and the node share the same
	 *  direct dispatch set but we don't bother right now.
	 */
	if ( stmt->nInitPlans > 0 )
		return false;

	return true;
}

/*
 * @param needsTwoPhaseCommit if true then marks the current Distributed Transaction as needing to use the
 *       2 phase commit protocol.
 */
void
dtmPreCommand(const char *debugCaller, const char *debugDetail, PlannedStmt *stmt,
		bool needsTwoPhaseCommit, bool wantSnapshot, bool inCursor )
{
	bool needsPromotionFromDirectDispatch = false;
	const bool rootNodeIsDirectDispatch = GetRootNodeIsDirectDispatch(stmt);
	const bool nodeSaysDirectDispatch = GetPlannedStmtDirectDispatch_AndUsingNodeIsSufficient(stmt);

	Assert(debugCaller != NULL);
	Assert(debugDetail != NULL);

	/**
	 * update the information about what segments are participating in the transaction
	 */
	if (currentGxact == NULL)
	{
		/* no open transaction so don't do anything */
	}
	else if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
	{
		/* Can we direct this transaction to a single content-id ? */
		if (nodeSaysDirectDispatch)
		{
			currentGxact->directTransaction = true;
			currentGxact->directTransactionContentId = linitial_int(stmt->planTree->directDispatch.contentIds);

			elog(DTM_DEBUG5,
				 "dtmPreCommand going distributed (to content %d) for gid = %s (%s, detail = '%s')",
				 currentGxact->directTransactionContentId, currentGxact->gid, debugCaller, debugDetail);
		}
		else
		{
			currentGxact->directTransaction = false;

			if ( rootNodeIsDirectDispatch )
			{
			 	/* implicit write on the root, but some initPlan was to all contents...so send explicit start */
				needsPromotionFromDirectDispatch = true;
			}

			elog(DTM_DEBUG5,
				 "dtmPreCommand going distributed (all gangs) for gid = %s (%s, detail = '%s')",
				 currentGxact->gid, debugCaller, debugDetail);
		}
	}
	else if (currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED)
	{
		bool wasDirected = currentGxact->directTransaction;
		int wasPromotedFromDirectDispatchContentId = wasDirected ? currentGxact->directTransactionContentId : -1;

		/* Can we still direct this transaction to a single content-id ? */
		if ( currentGxact->directTransaction)
		{
			currentGxact->directTransaction = false; // turn off, but may be restored below

			if (nodeSaysDirectDispatch)
			{
				int contentId = linitial_int(stmt->planTree->directDispatch.contentIds);
				if ( contentId == currentGxact->directTransactionContentId)
				{
					// it was the same content!  Stay in a single direct transaction
					currentGxact->directTransaction = true;
				}
			}
		}

		if ( currentGxact->directTransaction)
		{
			/** was not actually promoted */
			wasPromotedFromDirectDispatchContentId = -1;
		}

		if ( wasPromotedFromDirectDispatchContentId != -1 )
			needsPromotionFromDirectDispatch = true;

		elog(DTM_DEBUG5,
			 "dtmPreCommand gid = %s is already distributed (%s, detail = '%s'), (was %s : now %s)",
			 currentGxact->gid, debugCaller, debugDetail,
			 wasDirected ? "directed" : "all gangs",
			 currentGxact->directTransaction ? "directed" : "all gangs"
		);
	}

	/**
	 * If two-phase commit then begin transaction.
	 */
	if ( needsTwoPhaseCommit )
	{
		if (currentGxact == NULL)
		{
			elog(ERROR, "DTM transaction is not active (%s, detail = '%s')", debugCaller, debugDetail);
		}
		else if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
		{
			setCurrentGxactState( DTX_STATE_ACTIVE_DISTRIBUTED );
		}
		else if (currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED)
		{
			/* already distributed, no need to change */
		}
		else
		{
			elog(ERROR, "DTM transaction is not active (state = %s, %s, detail = '%s')",
				 DtxStateToString(currentGxact->state), debugCaller, debugDetail);
		}
	}

	/**
	 * If promotion from direct-dispatch to whole-cluster dispatch was done then tell about it.
	 *
	 * FUTURE: note that this is only needed if the query we are going to run would not itself
	 *   do this (that is, if the query we are going to run is a read-only one)
	 */
	if ( currentGxact &&
			currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED &&
			needsPromotionFromDirectDispatch)
	{
		CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
		char *serializedDtxContextInfo;
		int serializedDtxContextInfoLen;
		bool badGangs, succeeded;

		serializedDtxContextInfo = qdSerializeDtxContextInfo(&serializedDtxContextInfoLen, wantSnapshot, inCursor,
				mppTxnOptions(true), "promoteTransactionIn_dtmPreCommand");

		succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_STAY_AT_OR_BECOME_IMPLIED_WRITER, /* flags */ 0,
												 currentGxact->gid, currentGxact->gxid,
												 &badGangs, /* raiseError */ false, &direct,
												 serializedDtxContextInfo, serializedDtxContextInfoLen);

		/* send a DTM command to others to tell them about the transaction */
		if (!succeeded)
		{
			ereport(ERROR, (errmsg("Global transaction upgrade from single segment to entire cluster failed for gid = \"%s\" due to error",
								   currentGxact->gid)));
		}
	}
}


/*
 * Routine to dispatch internal sub-transaction calls from UDFs to segments.
 * The calls are BeginInternalSubTransaction, ReleaseCurrentSubTransaction and
 * RollbackAndReleaseCurrentSubTransaction. 
 */
bool
doDispatchSubtransactionInternalCmd(DtxProtocolCommand cmdType)
{
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
	char *serializedDtxContextInfo = NULL;
	int serializedDtxContextInfoLen = 0;
	bool badGangs, succeeded = false;

	if (cmdType == DTX_PROTOCOL_COMMAND_SUBTRANSACTION_BEGIN_INTERNAL)
	{ 
		getTmLock();
		if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
		{
			setCurrentGxactState(DTX_STATE_ACTIVE_DISTRIBUTED);
		}
		releaseTmLock();
	}
		
	serializedDtxContextInfo = qdSerializeDtxContextInfo(
					&serializedDtxContextInfoLen, 
					false /* wantSnapshot */, 
					false /* inCursor */,
					mppTxnOptions(true), 
					"doDispatchSubtransactionInternalCmd");

	succeeded = doDispatchDtxProtocolCommand(
			cmdType, /* flags */ 0,
			currentGxact->gid, currentGxact->gxid,
			&badGangs, /* raiseError */ true, &direct,
			serializedDtxContextInfo, serializedDtxContextInfoLen);

	/* send a DTM command to others to tell them about the transaction */
	if (!succeeded)
	{
		ereport(ERROR, 
			(errmsg(
			"dispatching subtransaction internal command failed for gid = \"%s\" due to error",
			currentGxact->gid)));
	}

	return succeeded;
}

/*
 * The executor can avoid starting a distributed transaction if it knows that
 * the current dtx is clean and we aren't in a user-started global transaction.
 */
bool
isCurrentDtxTwoPhase(void)
{
	if (currentGxact == NULL)
	{
		return false;
	}
	else
	{
		return currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED;
	}
}

/*
 * When cleaning up FTS needs to know if there is a transaction active.
 */
bool
isCurrentDtxActive(void)
{
	return (currentGxact != NULL);
}

DtxState
getCurrentDtxState(void)
{
	if (currentGxact != NULL)
		return currentGxact->state;

	return DTX_STATE_NONE;
}

static void
doPrepareTransaction(void)
{
	bool succeeded;
	CdbDispatchDirectDesc direct=default_dispatch_direct_desc;

	CHECK_FOR_INTERRUPTS();

	elog(DTM_DEBUG5, "doPrepareTransaction entering in state = %s",
	     DtxStateToString(currentGxact->state));

	/* Don't allow a cancel while we're dispatching our prepare (we wrap our
	 * state change as well; for good measure. */
	HOLD_INTERRUPTS();

	copyDirectDispatchFromTransaction(&direct);

	getTmLock();
	Assert(currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED);
	setCurrentGxactState( DTX_STATE_PREPARING );

	/*
	 * We keep a current count of the number of DTX transactions between
	 * 'PREPARING' and confirmed 'COMMIT' or 'ABORT'.
	 *
	 * To simplify bookkeeping, we turn on a flag in the gxact object.
	 */
	(*shmCurrentPhase1Count)++;
	currentGxact->bumpedPhase1Count = true;
	releaseTmLock();

	elog(DTM_DEBUG5, "doPrepareTransaction moved to state = %s", DtxStateToString(currentGxact->state));

	succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_PREPARE, /* flags */ 0,
											 currentGxact->gid, currentGxact->gxid,
											 &currentGxact->badPrepareGangs, /* raiseError */ false, &direct, NULL, 0);

	/* Now we've cleaned up our dispatched statement, cancels are allowed again. */
	RESUME_INTERRUPTS();

	if (!succeeded)
	{
		elog(DTM_DEBUG5, "doPrepareTransaction error finds badPrimaryGangs = %s",
			 (currentGxact->badPrepareGangs ? "true" : "false"));
		elog(ERROR, "The distributed transaction 'Prepare' broadcast failed to one or more segments for gid = %s.",
			 currentGxact->gid);
	}
	elog(DTM_DEBUG5, "The distributed transaction 'Prepare' broadcast succeeded to the segments for gid = %s.",
		 currentGxact->gid);

	getTmLock();
	Assert(currentGxact->state == DTX_STATE_PREPARING);
	setCurrentGxactState( DTX_STATE_PREPARED );
	releaseTmLock();

#ifdef FAULT_INJECTOR
		FaultInjector_InjectFaultIfSet(
									   DtmBroadcastPrepare,
									   DDLNotSpecified,
									   "",	// databaseName
									   ""); // tableName
#endif

	elog(DTM_DEBUG5, "doPrepareTransaction leaving in state = %s", DtxStateToString(currentGxact->state));
}

/*
 * Insert FORGET COMMITTED into the xlog.
 * Call with both ProcArrayLock and DTM lock already held.
 */
static void
doInsertForgetCommitted(void)
{
	TMGXACT_LOG gxact_log;

	elog(DTM_DEBUG5, "doInsertForgetCommitted entering in state = %s", DtxStateToString(currentGxact->state));

	setCurrentGxactState( DTX_STATE_INSERTING_FORGET_COMMITTED );

	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
			 (int)strlen(currentGxact->gid));
	memcpy(&gxact_log.gid, currentGxact->gid, TMGIDSIZE);
	gxact_log.gxid = currentGxact->gxid;

	RecordDistributedForgetCommitted(&gxact_log);

	setCurrentGxactState( DTX_STATE_INSERTED_FORGET_COMMITTED );

	/*
	 * These two actions must be performed for a distributed transaction under the same
	 * locking of ProceArrayLock so the visibility of the transaction changes for local
	 * master readers (e.g. those using  SnapshotNow for reading) the same as for
	 * distributed transactions.
	 */
	ClearTransactionFromPgProc_UnderLock();
	releaseGxact_UnderLocks();

	elog(DTM_DEBUG5, "doInsertForgetCommitted called releaseGxact");
}

static void
doNotifyingCommitPrepared(void)
{
	bool succeeded;
	bool badGangs;

	CdbDispatchDirectDesc direct=default_dispatch_direct_desc;

	elog(DTM_DEBUG5, "doNotifyingCommitPrepared entering in state = %s", DtxStateToString(currentGxact->state));

	getTmLock();

	copyDirectDispatchFromTransaction(&direct);

	Assert(currentGxact->state == DTX_STATE_FORCED_COMMITTED);
	setCurrentGxactState( DTX_STATE_NOTIFYING_COMMIT_PREPARED );
	releaseTmLock();

	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
			 (int)strlen(currentGxact->gid));

#ifdef FAULT_INJECTOR
	FaultInjector_InjectFaultIfSet(
								   DtmBroadcastCommitPrepared,
								   DDLNotSpecified,
								   "",	// databaseName
								   ""); // tableName
#endif
	succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_COMMIT_PREPARED, /* flags */ 0,
											 currentGxact->gid, currentGxact->gxid,
											 &badGangs, /* raiseError */ false,
											 &direct, NULL, 0);
	if (!succeeded)
	{
		elog(WARNING, "The distributed transaction 'Commit Prepared' broadcast failed to one or more segments for gid = %s.",
			 currentGxact->gid);

		/*
		 * We must succeed in delivering the commit to all segment instances, or any failed
		 * segment instances must be marked INVALID.
		 */

		/*
		 * Reset the dispatch logic (i.e. deallocate gang) so later we can attempt a retry
		 * at the top in PostgresMain.
		 */
		elog(NOTICE, "Releasing segworker group to retry broadcast.");
G
Gang Xiong 已提交
797
		disconnectAndDestroyAllGangs(true);
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873

		/*
		 * This call will at a minimum change the session id so we will
		 * not have SharedSnapshotAdd colissions.
		 */
		CheckForResetSession();

		getTmLock();
		Assert(currentGxact->state == DTX_STATE_NOTIFYING_COMMIT_PREPARED);

		setCurrentGxactState( DTX_STATE_RETRY_COMMIT_PREPARED );

		releaseTmLock();

		elog(DTM_DEBUG5, "Marking retry needed for distributed transaction 'Commit Prepared' broadcast to the segments for gid = %s.",
			 currentGxact->gid);
		return;
	}
	else
	{
		elog(DTM_DEBUG5, "The distributed transaction 'Commit Prepared' broadcast succeeded to all the segments for gid = %s.",
			 currentGxact->gid);
	}

	/*
	 * Global locking order: ProcArrayLock then DTM lock since
	 * calls doInsertForgetCommitted calls releaseGxact.
	 */
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

	getTmLock();

	Assert(currentGxact->state == DTX_STATE_NOTIFYING_COMMIT_PREPARED);

	doInsertForgetCommitted();

	releaseTmLock();

	LWLockRelease(ProcArrayLock);
}

static void
doNotifyingAbort(void)
{
	bool succeeded;
	bool badGangs;

	CdbDispatchDirectDesc direct=default_dispatch_direct_desc;

	elog(DTM_DEBUG5, "doNotifyingAborted entering in state = %s", DtxStateToString(currentGxact->state));

	getTmLock();
	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
	       currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
	       currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);
	releaseTmLock();

	copyDirectDispatchFromTransaction(&direct);

	if (currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED)
	{
		if (gangsExist())
		{
			succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_ABORT_NO_PREPARED, /* flags */ 0,
													 currentGxact->gid, currentGxact->gxid,
													 &badGangs, /* raiseError */ false,
													 &direct, NULL, 0);
			if (!succeeded)
			{
				elog(WARNING, "The distributed transaction 'Abort' broadcast failed to one or more segments for gid = %s.",
					 currentGxact->gid);

				/*
				 * Reset the dispatch logic and disconnect from any segment that didn't respond to our abort.
				 */
				elog(NOTICE, "Releasing segworker groups to finish aborting the transaction.");
G
Gang Xiong 已提交
874
				disconnectAndDestroyAllGangs(true);
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932

				/*
				 * This call will at a minimum change the session id so we will
				 * not have SharedSnapshotAdd colissions.
				 */
				CheckForResetSession();
			}
			else
			{
				elog(DTM_DEBUG5,
					 "The distributed transaction 'Abort' broadcast succeeded to all the segments for gid = %s.",
					 currentGxact->gid);
			}
		}
		else
		{
			elog(DTM_DEBUG5,
				 "The distributed transaction 'Abort' broadcast was omitted (segworker group already dead) gid = %s.",
				 currentGxact->gid);
		}
	}
	else
	{
		DtxProtocolCommand dtxProtocolCommand;
		char *abortString;

		Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
		       currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);

		if (currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED)
		{
			dtxProtocolCommand = DTX_PROTOCOL_COMMAND_ABORT_SOME_PREPARED;
			abortString = "Abort [Prepared]";
		}
		else
		{
			dtxProtocolCommand = DTX_PROTOCOL_COMMAND_ABORT_PREPARED;
			abortString = "Abort Prepared";
		}

		succeeded = doDispatchDtxProtocolCommand(dtxProtocolCommand, /* flags */ 0,
												 currentGxact->gid, currentGxact->gxid,
												 &badGangs, /* raiseError */ false,
												 &direct, NULL, 0);
		if (!succeeded)
		{
			elog(WARNING, "The distributed transaction '%s' broadcast failed to one or more segments for gid = %s.",
				 abortString, currentGxact->gid);

			/*
			 * We must succeed in delivering the abort to all segment instances, or any failed
			 * segment instances must be marked INVALID.
			 */

			/*
			 * Reset the dispatch logic (i.e. deallocate gang) so we can attempt a retry.
			 */
			elog(NOTICE, "Releasing segworker groups to retry broadcast.");
G
Gang Xiong 已提交
933
			disconnectAndDestroyAllGangs(true);
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 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 1025 1026 1027 1028 1029 1030 1031

			/*
			 * This call will at a minimum change the session id so we will
			 * not have SharedSnapshotAdd colissions.
			 */
			CheckForResetSession();

			getTmLock();
			setCurrentGxactState( DTX_STATE_RETRY_ABORT_PREPARED );
			releaseTmLock();

			elog(DTM_DEBUG5, "Marking retry needed for distributed transaction for '%s' broadcast to the segments for gid = %s.",
				 abortString, currentGxact->gid);
			return;

		}

		elog(DTM_DEBUG5, "The distributed transaction '%s' broadcast succeeded to all the segments for gid = %s.",
			 abortString, currentGxact->gid);
	}

#ifdef FAULT_INJECTOR
	FaultInjector_InjectFaultIfSet(
								   DtmBroadcastAbortPrepared,
								   DDLNotSpecified,
								   "",	// databaseName
								   ""); // tableName
#endif

	/*
	 * Global locking order: ProcArrayLock then DTM lock.
	 */
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

	getTmLock();

	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
	       currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
	       currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);

	releaseGxact_UnderLocks();
	elog(DTM_DEBUG5, "doNotifyingAbort called releaseGxact");

	releaseTmLock();

	LWLockRelease(ProcArrayLock);
}

/*
 * Attempt to retry DTM messaging.
 */
void
doDtxPhase2Retry(void)
{
	bool succeeded;
	bool badGangs;

	CdbDispatchDirectDesc direct=default_dispatch_direct_desc;

	if (currentGxact == NULL)
	{
		elog(DTM_DEBUG5, "doDtxPhase2Retry found no work to do (currentGxact == NULL)");
		return;
	}

	copyDirectDispatchFromTransaction(&direct);

	switch (currentGxact->state)
	{
		case DTX_STATE_RETRY_COMMIT_PREPARED:
		case DTX_STATE_RETRY_ABORT_PREPARED:
			if (currentGxact->retryPhase2RecursionStop)
			{
				/*
				 * Take down GP Array.
				 */
				elog(PANIC, "Unable to complete '%s Prepared' broadcast for gid = %s",
					 (currentGxact->state == DTX_STATE_RETRY_COMMIT_PREPARED ? "Commit" : "Abort"),
					 currentGxact->gid);
			}
			PG_TRY();
			{
				bool commit = (currentGxact->state == DTX_STATE_RETRY_COMMIT_PREPARED);
				DtxProtocolCommand dtxProtocolCommand;
				char *prepareKind;

				if (commit)
				{
					dtxProtocolCommand = DTX_PROTOCOL_COMMAND_RETRY_COMMIT_PREPARED;
					prepareKind = "Commit";
				}
				else
				{
					dtxProtocolCommand = DTX_PROTOCOL_COMMAND_RETRY_ABORT_PREPARED;
					prepareKind = "Abort";
				}

				/*
G
Gang Xiong 已提交
1032
				 * Todo: Maybe we don't need DTX_CONTEXT_QD_RETRY_PHASE_2 anymore.
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
				 */
				setDistributedTransactionContext(DTX_CONTEXT_QD_RETRY_PHASE_2);
				elog(DTM_DEBUG5,
					 "doDtxPhase2Retry setting DistributedTransactionContext to '%s' for retry of '%s Prepared'.",
					 DtxContextToString(DistributedTransactionContext), prepareKind);

				StartTransactionCommand();

				currentGxact->retryPhase2RecursionStop = true;

G
Gang Xiong 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
				/*
				 * We don't want doDispatchDtxProtocolCommand to raise error. But it will call
				 * createGang to allocate a writer gang, which could fail and error out.
				 *
				 * We catch the error and log a FATAL error instead of a PANIC.
				 */
				PG_TRY();
				{
					succeeded = doDispatchDtxProtocolCommand(dtxProtocolCommand, /* flags */ 0,
															 currentGxact->gid, currentGxact->gxid,
															 &badGangs, /* raiseError */ false,
															 &direct, NULL, 0);
				}
				PG_CATCH();
				{
					succeeded = false;
				}
				PG_END_TRY();

1062 1063 1064 1065 1066
				if (!succeeded)
				{
					elog(FATAL, "A retry of the distributed transaction '%s Prepared' broadcast failed to one or more segments for gid = %s.",
						 prepareKind, currentGxact->gid);
				}
G
Gang Xiong 已提交
1067 1068 1069 1070 1071
				else
				{
					elog(NOTICE, "Retry of the distributed transaction '%s Prepared' broadcast succeeded to the segments for gid = %s.",
							prepareKind, currentGxact->gid);
				}
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 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 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260

				/*
				 * Global locking order: ProcArrayLock then DTM lock since
				 * calls doInsertForgetCommitted calls releaseGxact.
				 */
				LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

				getTmLock();

				if (commit)
				{
					doInsertForgetCommitted();
				}
				else
				{
					releaseGxact_UnderLocks();
				}
				Assert(currentGxact == NULL);
				releaseTmLock();

				LWLockRelease(ProcArrayLock);

				CommitTransactionCommand();
				Assert(DistributedTransactionContext == DTX_CONTEXT_LOCAL_ONLY);
			}
			PG_CATCH();
			{
				setDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
				PG_RE_THROW();
			}
			PG_END_TRY();
			break;

		case DTX_STATE_ACTIVE_NOT_DISTRIBUTED:
		case DTX_STATE_ACTIVE_DISTRIBUTED:
		case DTX_STATE_PREPARING:
		case DTX_STATE_PREPARED:
		case DTX_STATE_FORCED_COMMITTED:
		case DTX_STATE_NOTIFYING_COMMIT_PREPARED:
		case DTX_STATE_NOTIFYING_ABORT_PREPARED:
		case DTX_STATE_INSERTING_COMMITTED:
		case DTX_STATE_INSERTED_COMMITTED:
		case DTX_STATE_INSERTING_FORGET_COMMITTED:
		case DTX_STATE_INSERTED_FORGET_COMMITTED:
		case DTX_STATE_CRASH_COMMITTED:
			elog(DTM_DEBUG5, "doDtxPhase2Retry dtx state \"%s\" not applicable here",
				 DtxStateToString(currentGxact->state));
			break;

		default:
			elog(PANIC, "Unrecognized dtx state: %d",
				 (int) currentGxact->state);
			break;
	}
}

static bool
doNotifyCommittedInDoubt(char *gid)
{
	bool succeeded;
	bool badGangs;

	CdbDispatchDirectDesc direct=default_dispatch_direct_desc;

	/* UNDONE: Pass real gxid instead of InvalidDistributedTransactionId. */
	succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_RECOVERY_COMMIT_PREPARED, /* flags */ 0,
											 gid, InvalidDistributedTransactionId,
											 &badGangs, /* raiseError */ false,
											 &direct, NULL, 0);
	if (!succeeded)
	{
		elog(FATAL, "Crash recovery broadcast of the distributed transaction 'Commit Prepared' broadcast failed to one or more segments for gid = %s.", gid);
	}
	else
	{
		elog(LOG, "Crash recovery broadcast of the distributed transaction 'Commit Prepared' broadcast succeeded for gid = %s.", gid);
	}

	return succeeded;
}

static void
doAbortInDoubt(char *gid)
{
	bool succeeded;
	bool badGangs;

	CdbDispatchDirectDesc direct=default_dispatch_direct_desc;

	/* UNDONE: Pass real gxid instead of InvalidDistributedTransactionId. */
	succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_RECOVERY_ABORT_PREPARED, /* flags */ 0,
											 gid, InvalidDistributedTransactionId,
											 &badGangs, /* raiseError */ false,
											 &direct, NULL, 0);
	if (!succeeded)
	{
		elog(FATAL, "Crash recovery retry of the distributed transaction 'Abort Prepared' broadcast failed to one or more segments for gid = %s.  System will retry again later", gid);
	}
	else
	{
		elog(LOG, "Crash recovery broadcast of the distributed transaction 'Abort Prepared' broadcast succeeded for gid = %s", gid);
	}
}

/*
 * prepare a global transaction, called by user commit
 * or by CommitTransaction
 */
void
prepareDtxTransaction(void)
{
	if (DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
	{
	    elog(DTM_DEBUG5, "prepareDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
			 DtxContextToString(DistributedTransactionContext));
		return;
	}

	if (currentGxact == NULL)
	{
		return;
	}

	if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
	{
		/*
		 * This transaction did not go distributed.
		 */
		elog(DTM_DEBUG5, "prepareDtxTransaction ignoring not distributed gid = %s", currentGxact->gid);
		releaseGxact();
		return;
	}

	elog(DTM_DEBUG5,
		 "prepareDtxTransaction called with state = %s",
		 DtxStateToString(currentGxact->state));

	Assert(currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED);

	/*
	 * Broadcast PREPARE TRANSACTION to segments.
	 */
	doPrepareTransaction();
}

/*
 * rollback a global transaction, called by user rollback
 * or by AbortTransaction during Postgres automatic rollback
 */
void
rollbackDtxTransaction(void)
{
	if (DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
	{
	    elog(DTM_DEBUG5, "rollbackDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
			 DtxContextToString(DistributedTransactionContext));
		return;
	}
	if (currentGxact == NULL)
	{
	    elog(DTM_DEBUG5, "rollbackDtxTransaction nothing to do (currentGxact == NULL)");
		return;
	}

	elog(DTM_DEBUG5, "rollbackDtxTransaction called with state = %s, gid = %s",
		 DtxStateToString(currentGxact->state), currentGxact->gid);

	switch (currentGxact->state)
	{
	case DTX_STATE_ACTIVE_NOT_DISTRIBUTED:
		/*
		 * Let go of these...
		 */
		releaseGxact();
		return;

	case DTX_STATE_ACTIVE_DISTRIBUTED:
		setCurrentGxactState( DTX_STATE_NOTIFYING_ABORT_NO_PREPARED );
		break;

	case DTX_STATE_PREPARING:
		if (currentGxact->badPrepareGangs)
		{
			/*
			 * By deallocating the gang, we will force a new gang to connect to all the
			 * segment instances.  And, we will abort the transactions in the
			 * segments.  What's left are possibily prepared transactions.
			 */
			elog(WARNING, "Releasing segworker groups since one or more segment connections failed.  This will abort the transactions in the segments that did not get prepared.");
G
Gang Xiong 已提交
1261
			disconnectAndDestroyAllGangs(true);
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285

			/*
			 * This call will at a minimum change the session id so we will
			 * not have SharedSnapshotAdd colissions.
			 */
			CheckForResetSession();

			setCurrentGxactState( DTX_STATE_RETRY_ABORT_PREPARED );
			return;
		}
		setCurrentGxactState( DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED );
		break;

	case DTX_STATE_PREPARED:
		setCurrentGxactState( DTX_STATE_NOTIFYING_ABORT_PREPARED );
		break;

	case DTX_STATE_NOTIFYING_ABORT_NO_PREPARED:
		/*
		 * By deallocating the gang, we will force a new gang to connect to all the
		 * segment instances.  And, we will abort the transactions in the
		 * segments.
		 */
		elog(NOTICE, "Releasing segworker groups to finish aborting the transaction.");
G
Gang Xiong 已提交
1286
		disconnectAndDestroyAllGangs(true);
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353

		/*
		 * This call will at a minimum change the session id so we will
		 * not have SharedSnapshotAdd colissions.
		 */
		CheckForResetSession();

		releaseGxact();
		return;

	case DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED:
	case DTX_STATE_NOTIFYING_ABORT_PREPARED:
		elog(FATAL, "Unable to complete the 'Abort Prepared' broadcast for gid '%s'",
			 currentGxact->gid);
		break;

	case DTX_STATE_FORCED_COMMITTED:
	case DTX_STATE_NOTIFYING_COMMIT_PREPARED:
	case DTX_STATE_INSERTING_COMMITTED:
	case DTX_STATE_INSERTED_COMMITTED:
	case DTX_STATE_INSERTING_FORGET_COMMITTED:
	case DTX_STATE_INSERTED_FORGET_COMMITTED:
	case DTX_STATE_RETRY_COMMIT_PREPARED:
	case DTX_STATE_RETRY_ABORT_PREPARED:
	case DTX_STATE_CRASH_COMMITTED:
		elog(DTM_DEBUG5, "rollbackDtxTransaction dtx state \"%s\" not expected here",
			 DtxStateToString(currentGxact->state));
		releaseGxact();
		return;

	default:
		elog(PANIC, "Unrecognized dtx state: %d",
			(int) currentGxact->state);
		break;
	}


	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
	       currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
	       currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);

	/*
	 * if the process is in the middle of blowing up... then we don't do
	 * anything here.  we can resolve any in-doubt transactions later.
	 *
	 * We can't dispatch -- but we *do* need to free up shared-memory
	 * entries.
	 */
	if (proc_exit_inprogress)
	{
		/*
		 * Unable to complete distributed abort broadcast with possible
		 * prepared transactions...
		 */
		if (currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
	       currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED)
		{
			elog(FATAL, "Unable to complete the 'Abort Prepared' broadcast for gid '%s'",
				 currentGxact->gid);
		}

		Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED);
		/*
		 * By deallocating the gang, we will force a new gang to connect to all the
		 * segment instances.  And, we will abort the transactions in the
		 * segments.
		 */
G
Gang Xiong 已提交
1354
		disconnectAndDestroyAllGangs(true);
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580

		/*
		 * This call will at a minimum change the session id so we will
		 * not have SharedSnapshotAdd colissions.
		 */
		CheckForResetSession();

		releaseGxact();
		return;
	}

	doNotifyingAbort();

	return;
}

/*
 * Error handling in initTM() is our caller.
 *
 * recoverTM() may throw errors.
 */
static void
initTM_recover_as_needed(void)
{
	Assert(shmTmRecoverred != NULL);

	/* Need to recover ? */
	if (!*shmTmRecoverred)
	{
		getTmLock();

		/* Still need to recover? */
		if (!*shmTmRecoverred)
		{
			volatile int savedInterruptHoldoffCount = InterruptHoldoffCount;
			/*
			 * We have to catch errors here, otherwise the silly TmLock will
			 * stay in the backend process until this process goes away.
			 */
			PG_TRY();
			{
				recoverTM();
				*shmTmRecoverred = true;

				/*
				 * The in-doubt transactions are recovered. Perform
				 * PersistentTable-Catalog non-database specific verifications,
				 * if requested and if needed
				 */
				if (debug_persistent_ptcat_verification &&
					Persistent_PostDTMRecv_PTCatVerificationNeeded())
				{
					Persistent_PrintHash();
					Persistent_PostDTMRecv_NonDBSpecificPTCatVerification();
				}
			}
			PG_CATCH();
			{
				/*
				 * We can't simply use HOLD_INTERRUPTS as in LWLockRelease,
				 * because at this point we don't know if other LWLocks have
				 * been acquired by myself.  Also, we don't know if releaseTmLock
				 * actually releases the lock, depending on ControlLockCount.
				 * Instead, restore the previous value, which is reset to 0
				 * in errfinish.
				 */
				InterruptHoldoffCount = savedInterruptHoldoffCount;
				releaseTmLock();

				/* Assuming we have a catcher above... */
				PG_RE_THROW();
			}
			PG_END_TRY();
		}

		releaseTmLock();
	}
}

static char *
getSuperuser(Oid *userOid)
{
	char *suser = NULL;
	Relation auth_rel;
	HeapTuple       auth_tup;
	HeapScanDesc auth_scan;
	ScanKeyData key[2];
	bool    isNull;

	ScanKeyInit(&key[0],
		Anum_pg_authid_rolsuper,
		BTEqualStrategyNumber, F_BOOLEQ,
		BoolGetDatum(true));

	ScanKeyInit(&key[1],
		Anum_pg_authid_rolcanlogin,
		BTEqualStrategyNumber, F_BOOLEQ,
		BoolGetDatum(true));

	auth_rel = heap_open(AuthIdRelationId, AccessShareLock);
	auth_scan = heap_beginscan(auth_rel, SnapshotNow, 2, key);

	while (HeapTupleIsValid(auth_tup = heap_getnext(auth_scan,
		ForwardScanDirection)))
	{
		Datum   attrName;
		Datum   attrNameOid;

		(void) heap_getattr(auth_tup, Anum_pg_authid_rolvaliduntil,
							auth_rel->rd_att, &isNull);
		/* we actually want it to be NULL, that means always valid */
		if (!isNull)
			continue;

		attrName = heap_getattr(auth_tup, Anum_pg_authid_rolname,
					auth_rel->rd_att, &isNull);

		Assert(!isNull);

		suser = pstrdup(DatumGetCString(attrName));

		attrNameOid = heap_getattr(auth_tup, ObjectIdAttributeNumber,
					   auth_rel->rd_att, &isNull);
		Assert(!isNull);
		*userOid = DatumGetObjectId(attrNameOid);

		break;
	}

	heap_endscan(auth_scan);
	heap_close(auth_rel, AccessShareLock);

	return suser;
}

static char *
ChangeToSuperuser()
{
	char *olduser = NULL;
	char *newuser;
	Oid  userOid = InvalidOid;
	MemoryContext oldcontext;

	if (!IsAuthenticatedUserSuperUser())
	{
		oldcontext = MemoryContextSwitchTo(TopMemoryContext);
		newuser = getSuperuser(&userOid);
		MemoryContextSwitchTo(oldcontext);

		olduser = MyProcPort->user_name;
		SetSessionUserId(userOid, true);
		MyProcPort->user_name = newuser;
	}

	return olduser;
}

static void
RestoreToUser(char *olduser)
{
	MemoryContext oldcontext;

	if (!IsAuthenticatedUserSuperUser())
	{
		oldcontext = MemoryContextSwitchTo(TopMemoryContext);
		pfree(MyProcPort->user_name);
		MemoryContextSwitchTo(oldcontext);

		MyProcPort->user_name = olduser;
		SetSessionUserId(GetAuthenticatedUserId(), false);
	}
}

/*
 * Initialize TM, called by cdb_setup() for each QD process.
 *
 * First call to this function will trigger tm recovery.
 *
 * MPP-9894: in 4.0, if we've been started with enough segments to
 * run, but without having them in the right "roles" (see
 * gp_segment_configuration), we need to prober to convert them -- our
 * first attempt to dispatch will fail, we've got to catch that! The
 * retry should be fine, if not we're in serious "FATAL" trouble.
 */
void
initTM(void)
{
	char *olduser = NULL;
	bool exists = false;
	MemoryContext	oldcontext;
	bool			succeeded, first;

	Assert(shmTmRecoverred != NULL);

	/* Need to recover ? */
	if (!*shmTmRecoverred)
	{
		/*
		 * DTM initialization should be done in the context
		 * of the superuser, and not the user who initiated this
		 * backend (MPP-13866).
		 * Following code changes the context to superuser and
		 * and then restores it back.
		 */
		olduser = ChangeToSuperuser();
#ifdef FAULT_INJECTOR
	FaultInjector_InjectFaultIfSet(
		DtmInit,
		DDLNotSpecified,
		"", //databaseName,
		""); //tableName;
#endif

		oldcontext = CurrentMemoryContext;
		succeeded = false;
		first = true;
		while (true)
		{
			/*
			 * MPP-9894: during startup, we don't have a top-level
			 * PG_TRY/PG_CATCH block yet, the dispatcher may throw errors:
			 * we need to catch them.
			 */
			PG_TRY();
			{
				/*
G
Gang Xiong 已提交
1581
				 * FtsNotifyProber could throw ERROR, so
1582 1583 1584
				 * we should catch it if it happens.
				 */
				if (!first)
G
Gang Xiong 已提交
1585
					FtsNotifyProber();
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 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 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 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 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 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 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

				initTM_recover_as_needed();
				succeeded = true;
			}
			PG_CATCH();
			{
				ErrorData *edata;

				MemoryContextSwitchTo(oldcontext);
				edata = CopyErrorData();

				elog(LOG, "DTM initialization, caught exception: "
						  "looking for failed segments.");
				ereport(LOG,
						(edata->message ? errmsg("%s", edata->message) : 0,
						 edata->detail ? errdetail("%s", edata->detail) : 0,
						 edata->hint ? errhint("%s", edata->hint) : 0));
				FreeErrorData(edata);
				FlushErrorState();

				/*
				 * Keep going outside of PG_TRY block even if we want to
				 * retry; don't jumping out of this block without PG_END_TRY.
				 */
			}
			PG_END_TRY();

			if (!succeeded)
			{
				if (first)
				{
					first = false;
					continue;
				}
				else
				{
					elog(LOG, "DTM initialization, failed on retry.");
					elog(FATAL, "DTM initialization: failure during startup "
								"recovery, retry failed, check segment status");
				}
			}

			/*
			 * We are done with the recovery.
			 */
			break;
		}

		RestoreToUser(olduser);

		freeGangsForPortal(NULL);
	}
	else
	{
		PG_TRY();
		{
			/*
			 * Do Database-specific PTCat verification ?
			 * Yes,
			 * 		if 1- GUC is turned ON and
			 * 		if 2- DTM recovery INDEED happened and
			 * 		if 3- Current Database has not been verified before
			 * 		(If the Database is present in the Hash Table)
			 */
			Assert(MyDatabaseId != InvalidOid);
			if (debug_persistent_ptcat_verification &&
				Persistent_PostDTMRecv_PTCatVerificationNeeded())
			{
				getTmLock();
				Persistent_PostDTMRecv_LookupHashEntry(MyDatabaseId, &exists);
				if (exists)
				{
					olduser = ChangeToSuperuser();

					Persistent_PostDTMRecv_DBSpecificPTCatVerification();

					/*
					 * The current database is now verified. Remove its entry from the
					 * Hash table to avoid performing these verifications next time
					 * a session connects to the current database
					 */
					Persistent_PostDTMRecv_RemoveHashEntry(MyDatabaseId);

					RestoreToUser(olduser);
					freeGangsForPortal(NULL);
				}
				releaseTmLock();
			}
		}
		PG_CATCH();
		{
			elog(FATAL, " Failure during DTM Post Recovery PersistentTables-Catalog"
						" DB-specific Verification");
		}
		PG_END_TRY();
	}
}

/* get tm share memory size */
int
tmShmemSize(void)
{
	if ((Gp_role != GP_ROLE_DISPATCH) && (Gp_role != GP_ROLE_UTILITY))
		return 0;

	return
		MAXALIGN(TMCONTROLBLOCK_BYTES(max_tm_gxacts) + max_tm_gxacts * sizeof(TMGXACT));
}


/*
 * tmShmemInit - should be called only once from postmaster and inherit by all
 * postgres processes
 */
void
tmShmemInit(void)
{
	bool		found;
	TmControlBlock *shared;

	/*
	 * max_prepared_xacts is a guc which is postmaster-startup setable
	 * -- it can only be updated by restarting the system. Global
	 * transactions will all use two-phase commit, so the number of
	 * global transactions is bound to the number of prepared.
	 */
	max_tm_gxacts = max_prepared_xacts;

	if ((Gp_role != GP_ROLE_DISPATCH) && (Gp_role != GP_ROLE_UTILITY))
		return;

	shared = (TmControlBlock *) ShmemInitStruct("Transaction manager", tmShmemSize(), &found);
	if (!shared)
		elog(FATAL, "could not initialize transaction manager share memory");

	shmControlLock = shared->ControlLock;
	shmTmRecoverred = &shared->recoverred;
	shmDistribTimeStamp = &shared->distribTimeStamp;
	shmGIDSeq = &shared->seqno;
	/* Only initialize this if we are the creator of the shared memory */
	if (!found)
	{
		time_t		t = time(NULL);
		if (t == (time_t) -1)
		{
			elog(PANIC, "cannot generate global transaction id");
		}

		*shmDistribTimeStamp = (DistributedTransactionTimeStamp)t;
  		elog(DEBUG1, "DTM start timestamp %u", *shmDistribTimeStamp);

		*shmGIDSeq = FirstDistributedTransactionId;
	}
	shmDtmStarted = &shared->DtmStarted;
	shmDtmRecoveryDeferred = &shared->DtmDeferRecovery;
	shmSegmentCount = &shared->SegmentCount;
	shmSegmentStatesByteLen = &shared->SegmentsStatesByteLen;
	shmXminAllDistributedSnapshots = &shared->xminAllDistributedSnapshots;
	shmNextSnapshotId = &shared->NextSnapshotId;
	shmNumGxacts = &shared->num_active_xacts;
	shmCurrentPhase1Count = &shared->currentPhase1Count;
	shmGxactArray = shared->gxact_array;

	if (!IsUnderPostmaster)
		/* Initialize locks and shared memory area */
	{
		int				  i = 0;
		TMGXACT    *gxact = NULL;

		shared->ControlLock = LWLockAssign();
		shmControlLock = shared->ControlLock;

		/* initialize gxact array */
		gxact = (TMGXACT *) (shmGxactArray + max_tm_gxacts);
		for (i = 0; i < max_tm_gxacts; i++)
		{
			gxact->debugIndex = i;
			shmGxactArray[i] = gxact++;
		}
	}
}

/*
 * restore global transaction during tm log recovery
 */
void
restoreGxact(TMGXACT_LOG * gxact_log, DtxState state)
{
	Assert (gxact_log != NULL);

	initGxact(currentGxact);

	/*
	 * Copy the log fields.
	 *
	 * The length check here requires the identifer have a trailing NUL character.
	 */
	if (strlen(gxact_log->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
			 (int)strlen(gxact_log->gid));
	memcpy(currentGxact->gid, gxact_log->gid, TMGIDSIZE);
	currentGxact->gxid = gxact_log->gxid;

	setCurrentGxactState( state );
}

/* mppTxnOptions:
 * Generates an int containing the appropriate flags to direct the remote
 * segdb QE process to perform any needed transaction commands before or
 * after the statement.
 */
int
mppTxnOptions(bool needTwoPhase)
{
	int options = 0;

	elog(DTM_DEBUG5,
		 "mppTxnOptions DefaultXactIsoLevel = %s, DefaultXactReadOnly = %s, XactIsoLevel = %s, XactReadOnly = %s.",
		 IsoLevelAsUpperString(DefaultXactIsoLevel), (DefaultXactReadOnly ? "true" : "false"),
		 IsoLevelAsUpperString(XactIsoLevel), (XactReadOnly ? "true" : "false"));

	if (needTwoPhase)
		options |= GP_OPT_NEED_TWO_PHASE;

	if (XactIsoLevel == XACT_READ_COMMITTED)
		options |= GP_OPT_READ_COMMITTED;
	else if (XactIsoLevel == XACT_REPEATABLE_READ)
		options |= GP_OPT_REPEATABLE_READ;
	else if (XactIsoLevel == XACT_SERIALIZABLE)
		options |= GP_OPT_SERIALIZABLE;

	if (XactReadOnly)
		options |= GP_OPT_READ_ONLY;

	if (currentGxact != NULL && currentGxact->explicitBeginRemembered)
		options |= GP_OPT_EXPLICT_BEGIN;

	elog(DTM_DEBUG5,
		 "mppTxnOptions txnOptions = 0x%x, needTwoPhase = %s, explicitBegin = %s, isoLevel = %s, readOnly = %s.",
		 options,
		 (isMppTxOptions_NeedTwoPhase(options) ? "true" : "false"), (isMppTxOptions_ExplicitBegin(options) ? "true" : "false"),
		 IsoLevelAsUpperString(mppTxOptions_IsoLevel(options)), (isMppTxOptions_ReadOnly(options) ? "true" : "false"));

	return options;

}

int
mppTxOptions_IsoLevel(int txnOptions)
{
	if (txnOptions & GP_OPT_READ_COMMITTED)
		return XACT_READ_COMMITTED;
	else if (txnOptions & GP_OPT_SERIALIZABLE)
		return XACT_SERIALIZABLE;
	else if ( txnOptions & GP_OPT_REPEATABLE_READ)
		return XACT_REPEATABLE_READ;
	else
		return XACT_READ_UNCOMMITTED;
}

bool
isMppTxOptions_ReadOnly(int txnOptions)
{
	return ((txnOptions & GP_OPT_READ_ONLY) != 0);
}



/* unpackMppTxnOptions:
 * Unpack an int containing the appropriate flags to direct the remote
 * segdb QE process to perform any needed transaction commands before or
 * after the statement.
 */
void
unpackMppTxnOptions(int txnOptions, int *isoLevel, bool *readOnly)
{
	*isoLevel = mppTxOptions_IsoLevel(txnOptions);

	*readOnly = isMppTxOptions_ReadOnly(txnOptions);
}

/* isMppTxOptions_StatementWantsDtxTransaction:
 * Return the NeedTwoPhase flag.
 */
bool
isMppTxOptions_NeedTwoPhase(int txnOptions)
{
	return ((txnOptions & GP_OPT_NEED_TWO_PHASE) != 0);
}

/* isMppTxOptions_ExplicitBegin:
 * Return the ExplicitBegin flag.
 */
bool
isMppTxOptions_ExplicitBegin(int txnOptions)
{
	return ((txnOptions & GP_OPT_EXPLICT_BEGIN) != 0);
}


/* acquire tm lw lock */
void
getTmLock(void)
{

	if (ControlLockCount++ == 0)
		LWLockAcquire(shmControlLock, LW_EXCLUSIVE);
}

/* release tm lw lock */
void
releaseTmLock(void)
{
	if (--ControlLockCount == 0)
		LWLockRelease(shmControlLock);

}

bool
isTMInRecovery(void)
{
	return duringRecovery;
}

/*
 * Redo transaction commit log record.
 */
void
redoDtxCheckPoint(TMGXACT_CHECKPOINT *gxact_checkpoint)
{
	int committedCount;
	int segmentCount;

	int i;

	/*
	 * For checkpoint same as REDO, lets add entries to file in utility and in-memory if Dispatch.
	 */

	committedCount = gxact_checkpoint->committedCount;
	segmentCount = gxact_checkpoint->segmentCount;
	elog(DTM_DEBUG5, "redoDtxCheckPoint has committedCount = %d, "
		 "segmentCount = %d", committedCount, segmentCount);
	if (Debug_persistent_recovery_print)
	{
		elog(PersistentRecovery_DebugPrintLevel(),
			 "redoDtxCheckPoint: committedCount = %d",
			 committedCount);
	}

	for (i = 0; i < committedCount; i++)
	{
		redoDistributedCommitRecord(&gxact_checkpoint->committedGxactArray[i]);
	}
}

static void
GetRedoFileName(char *path)
{
	snprintf(path, MAXPGPATH,
		     "%s/" UTILITYMODEDTMREDO_DIR "/" UTILITYMODEDTMREDO_FILE, DataDir);
	elog(DTM_DEBUG3, "Returning save DTM redo file path = %s",path);
}

void
UtilityModeFindOrCreateDtmRedoFile(void)
{
	char		path[MAXPGPATH];

	if (Gp_role != GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "Not in Utility Mode (role = %s) -- skipping finding or creating DTM redo file",
			 role_to_string(Gp_role));
		return;
	}
	GetRedoFileName(path);

	redoFileFD = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
	if (redoFileFD < 0)
	{
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not create save DTM redo file \"%s\"",
						path)));
	}

	redoFileOffset = lseek(redoFileFD, 0, SEEK_END);
	elog(DTM_DEBUG3, "Succesfully opened DTM redo file %s (end offset %d)",
		 path, redoFileOffset);
}

/*
 *
 */
static void
UtilityModeSaveRedo(bool committed, TMGXACT_LOG * gxact_log)
{
	TMGXACT_UTILITY_MODE_REDO utilityModeRedo;
	int write_len;

	utilityModeRedo.committed = committed;
	memcpy(&utilityModeRedo.gxact_log, gxact_log, sizeof(TMGXACT_LOG));

	elog(DTM_DEBUG5, "Writing {committed = %s, gid = %s, gxid = %u} to DTM redo file",
	     (utilityModeRedo.committed ? "true" : "false"),
	     utilityModeRedo.gxact_log.gid,
	     utilityModeRedo.gxact_log.gxid);

	write_len = write(redoFileFD, &utilityModeRedo, sizeof(TMGXACT_UTILITY_MODE_REDO));
	if (write_len != sizeof(TMGXACT_UTILITY_MODE_REDO))
	{
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not write save DTM redo file : %m")));
	}

}

void
UtilityModeCloseDtmRedoFile(void)
{
	if (Gp_role != GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "Not in Utility Mode (role = %s)-- skipping closing DTM redo file",
			 role_to_string(Gp_role));
		return;
	}
	elog(DTM_DEBUG3, "Closing DTM redo file");
	close(redoFileFD);
}

static void
ReplayRedoFromUtilityMode(void)
{
	TMGXACT_UTILITY_MODE_REDO utilityModeRedo;

	int			fd;
	int			read_len;
	int	        errno;
	char		path[MAXPGPATH];
	int			entries;

	entries = 0;

	GetRedoFileName(path);

	fd = open(path, O_RDONLY, 0);
	if (fd < 0)
	{
		/* UNDONE: Distinquish "not found" from other errors. */
		elog(DTM_DEBUG3, "Could not open DTM redo file %s for reading",
		     path);
		return;
	}

	elog(DTM_DEBUG3, "Succesfully opened DTM redo file %s for reading",
		 path);

	while(true)
	{
		errno = 0;
		read_len = read(fd, &utilityModeRedo, sizeof(TMGXACT_UTILITY_MODE_REDO));

		if (read_len == 0)
			break;
		else if (read_len != sizeof(TMGXACT_UTILITY_MODE_REDO) && errno == 0)
			elog(ERROR, "Bad redo length (expected %d and found %d)",
			     (int)sizeof(TMGXACT_UTILITY_MODE_REDO), read_len);
		else if (errno != 0)
		{
			close(fd);
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("error reading DTM redo file: %m")));
		}

		elog(DTM_DEBUG5, "Read {committed = %s, gid = %s, gxid = %u} from DTM redo file",
		     (utilityModeRedo.committed ? "true" : "false"),
		     utilityModeRedo.gxact_log.gid,
		     utilityModeRedo.gxact_log.gxid);
		if (utilityModeRedo.committed)
		{
			redoDistributedCommitRecord(&utilityModeRedo.gxact_log);
		}
		else
		{
			redoDistributedForgetCommitRecord(&utilityModeRedo.gxact_log);
		}

		entries++;
	}

	elog(DTM_DEBUG5, "Processed %d entries from DTM redo file",
		 entries);
	close(fd);

}

static void
RemoveRedoUtilityModeFile(void)
{
	char		path[MAXPGPATH];
	bool        removed;

	GetRedoFileName(path);
	removed = (unlink(path) == 0);
	elog(DTM_DEBUG5, "Removed DTM redo file %s (%s)",
		 path, (removed ? "true" : "false"));
}

/*
 * Redo transaction commit log record.
 */
void
redoDistributedCommitRecord(TMGXACT_LOG * gxact_log)
{

	int			i;

	/*
	 * The length check here requires the identifer have a trailing NUL character.
	 */
	if (strlen(gxact_log->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
			 (int)strlen(gxact_log->gid));

	if (Gp_role == GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "DB in Utility mode.  Save DTM distributed commit until later.");
		UtilityModeSaveRedo(true, gxact_log);
		return;
	}

	for (i = 0; i < *shmNumGxacts; i++)
	{
		if (strcmp(gxact_log->gid, shmGxactArray[i]->gid) == 0)
		{
			/* found an active global transaction */
			currentGxact = shmGxactArray[i];
			break;
		}
	}
	if (i == *shmNumGxacts)
	{
		/*
		 * Transaction not found, this is the first log of this transaction.
		 */
		if (*shmNumGxacts >= max_tm_gxacts)
		{
			ereport(FATAL,
					(errmsg("the limit of %d distributed transactions has been reached.",
							max_tm_gxacts),
					 errdetail("The global user configuration (GUC) server parameter max_prepared_transactions controls this limit.")));
		}

		currentGxact = shmGxactArray[(*shmNumGxacts)++];
	}

	restoreGxact(gxact_log, DTX_STATE_CRASH_COMMITTED);

	elog((Debug_print_full_dtm ? LOG : DEBUG5),
		"Crash recovery redo added committed distributed transaction gid = %s",currentGxact->gid);

	elog((Debug_print_full_dtm ? INFO : DEBUG5),
		 "Crash recovery redo added committed distributed transaction gid = %s",currentGxact->gid);

	/*
	 * Don't leave the currentGxact point in-use.
	 */
    currentGxact = NULL;
}

/*
 * Redo transaction forget commit log record.
 */
void
redoDistributedForgetCommitRecord(TMGXACT_LOG * gxact_log)
{
	int			i;

	if (Gp_role == GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "DB in Utility mode.  Save DTM disributed forget until later.");
		UtilityModeSaveRedo(false, gxact_log);
		return;
	}

	for (i = 0; i < *shmNumGxacts; i++)
	{
		if (strcmp(gxact_log->gid, shmGxactArray[i]->gid) == 0)
		{
			/* found an active global transaction */
			currentGxact = shmGxactArray[i];
			elog((Debug_print_full_dtm ? INFO : DEBUG5),
				 "Crash recovery redo removed committed distributed transaction gid = %s for forget",
			     currentGxact->gid);
			releaseGxact();
			return;
		}
	}

	elog((Debug_print_full_dtm ? WARNING : DEBUG5),
		 "Crash recovery redo did not find committed distributed transaction gid = %s for forget",
		 gxact_log->gid);

}

static void
descGxactLog(StringInfo buf, TMGXACT_LOG * gxact_log)
{
	appendStringInfo(buf, " gid = %s, gxid = %u",
					 gxact_log->gid, gxact_log->gxid);
}

/*
 * Describe redo transaction commit log record.
 */
void
descDistributedCommitRecord(StringInfo buf, TMGXACT_LOG * gxact_log)
{
	descGxactLog(buf, gxact_log);
}

/*
 * Describe redo transaction forget commit log record.
 */
void
descDistributedForgetCommitRecord(StringInfo buf, TMGXACT_LOG * gxact_log)
{
	descGxactLog(buf, gxact_log);
}


/*=========================================================================
 * HELPER FUNCTIONS
 */

static bool
doDispatchDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand, int flags,
							 char* gid, DistributedTransactionId gxid,
							 bool *badGangs, bool raiseError,
							 CdbDispatchDirectDesc *direct,
2228 2229
							 char *serializedDtxContextInfo,
							 int serializedDtxContextInfoLen)
2230
{
2231
	int i, resultCount, numOfFailed = 0;
2232

2233
	char *dtxProtocolCommandStr = 0;
2234

2235 2236
	struct pg_result **results = NULL;
	StringInfoData errbuf;
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255

	dtxProtocolCommandStr = DtxProtocolCommandToString(dtxProtocolCommand);

	if ( Test_print_direct_dispatch_info )
	{
		if ( direct->directed_dispatch)
			elog(INFO, "Distributed transaction command '%s' to SINGLE content", dtxProtocolCommandStr);
		else elog(INFO, "Distributed transaction command '%s' to ALL contents", dtxProtocolCommandStr);
	}
	elog(DTM_DEBUG5,
		 "dispatchDtxProtocolCommand: %d ('%s'), direct content #: %d",
		 dtxProtocolCommand, dtxProtocolCommandStr,
				 direct->directed_dispatch ? direct->content[0] : -1);

	initStringInfo(&errbuf);
	results = cdbdisp_dispatchDtxProtocolCommand(dtxProtocolCommand, flags,
												 dtxProtocolCommandStr,
												 gid, gxid,
												 &errbuf, &resultCount, badGangs, direct,
2256
												 serializedDtxContextInfo, serializedDtxContextInfoLen);
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306

	if (errbuf.len > 0)
	{
		ereport((raiseError ? ERROR : LOG),
				(errmsg("DTM error (gathered %d results from cmd '%s')", resultCount, dtxProtocolCommandStr),
				 errdetail("%s", errbuf.data)));
		return false;
	}

	Assert(results != NULL);
	if (results == NULL)
	{
		numOfFailed++; /* If we got no results, we need to treat it as an error! */
	}
	for (i = 0; i < resultCount; i++)
	{
		char			*cmdStatus;
		ExecStatusType	resultStatus;

		/* note: PQresultStatus() is smart enough to deal with results[i] == NULL */
		resultStatus = PQresultStatus(results[i]);
		if (resultStatus != PGRES_COMMAND_OK &&
			resultStatus != PGRES_TUPLES_OK)
		{
			numOfFailed++;
		}
		else
		{
			/*
			 * success ? If an error happened during a transaction which
			 * hasn't already been caught when we try a prepare we'll get a
			 * rollback from our prepare ON ONE SEGMENT: so we go look at the
			 * status, otherwise we could issue a COMMIT when we don't want
			 * to!
			 */
			cmdStatus = PQcmdStatus(results[i]);

			elog(DEBUG3, "DTM: status message cmd '%s' [%d] result '%s'", dtxProtocolCommandStr, i, cmdStatus);
			if (strncmp(cmdStatus, dtxProtocolCommandStr, strlen(cmdStatus)) != 0)
			{
				/* failed */
				numOfFailed++;
			}
		}
	}

	/* discard the errbuf text */
	pfree(errbuf.data);

	/* Now we clean up the results array. */
2307 2308 2309
	for (i = 0; i < resultCount; i++)
		PQclear(results[i]);
	free(results);
2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 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

	return (numOfFailed == 0);
}


bool
dispatchDtxCommand(const char *cmd, bool withSnapshot, bool raiseError)
{
	int		i, resultCount, numOfFailed = 0;

	struct pg_result **results = NULL;
	StringInfoData errbuf;

	elog(DTM_DEBUG5, "dispatchDtxCommand: '%s'", cmd);

	initStringInfo(&errbuf);
	results = cdbdisp_dispatchRMCommand(cmd, withSnapshot,
										&errbuf, &resultCount);

	if (errbuf.len > 0)
	{
		ereport((raiseError ? ERROR : WARNING),
				(errmsg("DTM error (gathered %d results from cmd '%s')", resultCount, cmd),
				 errdetail("%s", errbuf.data)));
		return false;
	}

	Assert(results != NULL);
	if (results == NULL)
	{
		numOfFailed++; /* If we got no results, we need to treat it as an error! */
	}

	for (i = 0; i < resultCount; i++)
	{
		char			*cmdStatus;
		ExecStatusType	resultStatus;

		/* note: PQresultStatus() is smart enough to deal with results[i] == NULL */
		resultStatus = PQresultStatus(results[i]);
		if (resultStatus != PGRES_COMMAND_OK &&
			resultStatus != PGRES_TUPLES_OK)
		{
			numOfFailed++;
		}
		else
		{
			/*
			 * success ? If an error happened during a transaction which
			 * hasn't already been caught when we try a prepare we'll get a
			 * rollback from our prepare ON ONE SEGMENT: so we go look at the
			 * status, otherwise we could issue a COMMIT when we don't want
			 * to!
			 */
			cmdStatus = PQcmdStatus(results[i]);

			elog(DEBUG3, "DTM: status message cmd '%s' [%d] result '%s'", cmd, i, cmdStatus);
			if (strncmp(cmdStatus, cmd, strlen(cmdStatus)) != 0)
			{
				/* failed */
				numOfFailed++;
			}
		}
	}

	/* discard the errbuf text */
	pfree(errbuf.data);

	/* Now we clean up the results array. */
2379 2380 2381
	for (i = 0; i < resultCount; i++)
		PQclear(results[i]);
	free(results);
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 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 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184

	return (numOfFailed == 0);
}

/* initialize a global transaction context */
static void
initGxact(TMGXACT * gxact)
{
	MemSet(gxact->gid, 0, TMGIDSIZE);
	gxact->gxid = InvalidDistributedTransactionId;
	setGxactState(gxact, DTX_STATE_NONE);

	/*
	 * Memory only fields.
	 */

	gxact->sessionId = gp_session_id;

	gxact->localXid = InvalidTransactionId;

	gxact->explicitBeginRemembered = false;

	LocalDistribXactRef_Init(&gxact->localDistribXactRef);

    gxact->xminDistributedSnapshot = 0;

	gxact->bumpedPhase1Count = false;

	gxact->badPrepareGangs = false;

	gxact->retryPhase2RecursionStop = false;

	gxact->directTransaction = false;
	gxact->directTransactionContentId = 0;
}

void
getAllDistributedXactStatus(TMGALLXACTSTATUS **allDistributedXactStatus)
{
	TMGALLXACTSTATUS *all;
	int count;

	all = palloc(sizeof(TMGALLXACTSTATUS));
	all->next = 0;
	all->count = 0;
	all->statusArray = NULL;

	if (shmDtmStarted != NULL && *shmDtmStarted)
	{
		getTmLock();
		count = *shmNumGxacts;
		if (count > 0)
		{
			int i;

			all->statusArray =
				palloc(MAXALIGN(count * sizeof(TMGXACTSTATUS)));
			for (i = 0; i < count; i++)
			{
				TMGXACT *gxact = shmGxactArray[i];

				all->statusArray[i].gxid = gxact->gxid;
				if (strlen(gxact->gid) >= TMGIDSIZE)
					elog(PANIC, "Distribute transaction identifier too long (%d)",
						 (int)strlen(gxact->gid));
				memcpy(all->statusArray[i].gid, gxact->gid, TMGIDSIZE);
				all->statusArray[i].state = gxact->state;
				all->statusArray[i].sessionId = gxact->sessionId;
				all->statusArray[i].xminDistributedSnapshot = gxact->xminDistributedSnapshot;
			}

			all->count = count;
		}

		releaseTmLock();

	}

	*allDistributedXactStatus = all;
}

bool
getNextDistributedXactStatus(TMGALLXACTSTATUS *allDistributedXactStatus, TMGXACTSTATUS **distributedXactStatus)
{
	if (allDistributedXactStatus->next >= allDistributedXactStatus->count)
	{
		return false;
	}

	*distributedXactStatus = &allDistributedXactStatus->statusArray[allDistributedXactStatus->next];
	allDistributedXactStatus->next++;

	return true;
}

/*
 * DistributedSnapshotMappedEntry_Compare:
 * A compare function for array of DistributedSnapshotMapEntry
 * for use with qsort.
 */
static int
DistributedSnapshotMappedEntry_Compare(const void *p1, const void *p2)
{
	const DistributedSnapshotMapEntry *entry1 = (DistributedSnapshotMapEntry *) p1;
	const DistributedSnapshotMapEntry *entry2 = (DistributedSnapshotMapEntry *) p2;

	if (entry1->distribXid == entry2->distribXid)
		return 0;
	else if (entry1->distribXid > entry2->distribXid)
		return 1;
	else
		return -1;
}

bool
createDtxSnapshot(
	DistributedSnapshotWithLocalMapping	*distribSnapshotWithLocalMapping)
{
	int 						globalCount;
	int                         i;
	TMGXACT    					*gxact_candidate;
	DtxState      				state;
	int 						count;
	DistributedTransactionId	xmin;
	DistributedTransactionId	xmax;
	DistributedTransactionId	inProgressXid;
	DistributedSnapshotId		distribSnapshotId;
	DistributedTransactionId	xminAllDistributedSnapshots;

	DistributedSnapshotMapEntry 	*inProgressEntryArray;

	if (currentGxact == NULL)
	{
		elog(DTM_DEBUG5, "createDtxSnapshot found currentGxact is NULL");
		return false;
	}

	xmin = LastDistributedTransactionId;
	/*
	 * This is analogous to the code in GetSnapshotData() (which calls
	 * ReadNewTransactionId(), the distributed-xmax of a transaction
	 * is the last distributed-xmax available
	 */
	xmax = LocalDistribXact_GetMaxDistributedXid();
	count = 0;
	inProgressEntryArray = distribSnapshotWithLocalMapping->inProgressEntryArray;

	getTmLock();

	/*
	 * Gather up current in-progress global transactions for the
	 * distributed snapshot.
	 */
	globalCount = *shmNumGxacts;

	for (i = 0; i < globalCount; i++)
	{
		gxact_candidate = shmGxactArray[i];

		state = gxact_candidate->state;
		switch (state)
		{
			case DTX_STATE_ACTIVE_NOT_DISTRIBUTED:
			case DTX_STATE_ACTIVE_DISTRIBUTED:
			case DTX_STATE_PREPARING:
			case DTX_STATE_PREPARED:
			case DTX_STATE_INSERTED_COMMITTED:
			case DTX_STATE_FORCED_COMMITTED:
			case DTX_STATE_NOTIFYING_COMMIT_PREPARED:
			case DTX_STATE_NOTIFYING_ABORT_NO_PREPARED:
			case DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED:
			case DTX_STATE_NOTIFYING_ABORT_PREPARED:
			case DTX_STATE_RETRY_COMMIT_PREPARED:
			case DTX_STATE_RETRY_ABORT_PREPARED:
				/*
				 * Active or commit/abort not complete.  Keep this transaction
				 * considered for distributed snapshots.
				 */
				break;

			case DTX_STATE_INSERTED_FORGET_COMMITTED:
				elog(FATAL, "Should not see this transitional state with TM lock held -- dtx state \"%s\" not expected here",
					 DtxStateToString(state));
				break;

			case DTX_STATE_INSERTING_COMMITTED:
				elog(FATAL, "Cannot also be inserting COMMITTED into log buffer from another process with TM lock held");
				break;

			case DTX_STATE_INSERTING_FORGET_COMMITTED:
				elog(FATAL, "Cannot also be inserting FORGET COMMITTED into log buffer from another process with TM lock held");
				break;

			case DTX_STATE_CRASH_COMMITTED:
				/*
				 * From a previous system incarnation.
				 */
				continue;

			default:
				elog(PANIC, "Unexpected dtm state: %d",
					 (int) state);
				break;
		}

		/*
		 * Include the current distributed transaction in the min/max
		 * calculation.
		 */
		inProgressXid = gxact_candidate->gxid;
		if (inProgressXid < xmin)
		{
			xmin = inProgressXid;
		}
		if (inProgressXid > xmax)
		{
			xmax = inProgressXid;
		}

		if (gxact_candidate == currentGxact)
			continue;

		if (count >= distribSnapshotWithLocalMapping->header.maxCount)
			elog(ERROR, "Too many distributed transactions for snapshot");


		inProgressEntryArray[count].distribXid = inProgressXid;
		inProgressEntryArray[count].localXid = gxact_candidate->localXid;

		count++;

		elog(DTM_DEBUG5,
			 "createDtxSnapshot added inProgressXid = %u (and local xid = %u) to distributed snapshot",
			 inProgressEntryArray[count].distribXid,
			 inProgressEntryArray[count].localXid);
	}

	distribSnapshotId = (*shmNextSnapshotId)++;

	xminAllDistributedSnapshots = *shmXminAllDistributedSnapshots;

	releaseTmLock();

	/*
	 * Sort the entry {distribXid, localXid}
	 * to support the QEs doing culls on their DisribToLocalXact sorted lists.
	 */
	qsort(
		inProgressEntryArray,
	  	count,
	  	sizeof(DistributedSnapshotMapEntry),
	    DistributedSnapshotMappedEntry_Compare);

	/*
	 * Copy the information we just captured under lock and then sorted into
	 * the distributed snapshot.
	 */
	distribSnapshotWithLocalMapping->header.distribTransactionTimeStamp = *shmDistribTimeStamp;
	distribSnapshotWithLocalMapping->header.xminAllDistributedSnapshots = xminAllDistributedSnapshots;
	distribSnapshotWithLocalMapping->header.distribSnapshotId = distribSnapshotId;
	distribSnapshotWithLocalMapping->header.xmin = xmin;
	distribSnapshotWithLocalMapping->header.xmax = xmax;
	distribSnapshotWithLocalMapping->header.count = count;

	if (xmin < currentGxact->xminDistributedSnapshot)
		currentGxact->xminDistributedSnapshot = xmin;

	elog(DTM_DEBUG5,
		 "createDtxSnapshot distributed snapshot has xmin = %u, count = %u, xmax = %u.",
		 xmin, count, xmax);
	elog((Debug_print_snapshot_dtm ? LOG : DEBUG5),
		 "[Distributed Snapshot #%u] *Create* (gxid = %u, '%s')",
		 distribSnapshotId,
		 currentGxact->gxid,
		 DtxContextToString(DistributedTransactionContext));

	return true;
}

/*
 * Introduced by MPP-9829.
 *
 * Fail safe in regards to the shmControlLock and ProcArrayLock.
 *
 * Generally speaking, we defer to LWLockReleaseAll to clean up our held_lwlocks. In
 * the case of an ERROR, this results from AbortTransaction. And in the case of a FATAL,
 * this results from a ProcKill towards the end of proc_exit.
 *
 * Unfortunately, two subtleties are dealt with here. In the case of an ERROR where this
 * current process continues to exist, ControlLockCount must be reset to coincide with
 * the cleanup of shmControlLock. Also, during a FATAL, we'd like to release the ProcArrayLock;
 * otherwise, we'd PANIC when trying to reacquire the ProcArrayLock for the purposes
 * of the ProcArrayRemove nearing the end of proc_exit.
 */
static void
createDtxErrorCallback(int code, Datum arg)
{
	HOLD_INTERRUPTS();
	ControlLockCount = 1;
	releaseTmLock();

	HOLD_INTERRUPTS();
	LWLockRelease(ProcArrayLock);
}

/*
 * Create a global transaction context from share memory.
 */
void
createDtx(DistributedTransactionId		*distribXid,
		  TransactionId 				*localXid)
{
	TMGXACT    	*gxact;

	MIRRORED_LOCK_DECLARE;

	/*
	 * Global locking order: ProcArrayLock then DTM lock.
	 */
	MIRRORED_LOCK;

	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

	getTmLock();

	if (*shmNumGxacts >= max_tm_gxacts)
	{
		dumpAllDtx();
		releaseTmLock();
		LWLockRelease(ProcArrayLock);
		ereport(FATAL,
				(errmsg("the limit of %d distributed transactions has been reached.",
						max_tm_gxacts),
				 errdetail("The global user configuration (GUC) server parameter max_prepared_transactions controls this limit.")));
	}

	gxact = shmGxactArray[(*shmNumGxacts)++];
	initGxact(gxact);
	generateGID(gxact->gid, &gxact->gxid);

	/*
	 * MPP-9829: don't hold these if we're throwing an error. if
	 * we *do* hold them, we'll just cause a PANIC later.
	 */
	PG_ENSURE_ERROR_CLEANUP(createDtxErrorCallback, 0);
	{
		/*
		 * This routine requires the ProcArrayLock to already be held.
		 */
		LocalDistribXact_StartOnMaster(
			*shmDistribTimeStamp,
			gxact->gxid,
			&gxact->localXid,
			&gxact->localDistribXactRef);

		*distribXid = gxact->gxid;
		*localXid = gxact->localXid;
	}
	PG_END_ENSURE_ERROR_CLEANUP(createDtxErrorCallback, 0);

	/*
	 * Until we get our first distributed snapshot, we use our
	 * distributed transaction identifier for the minimum.
	 */
	gxact->xminDistributedSnapshot = gxact->gxid;

	setGxactState(gxact, DTX_STATE_ACTIVE_NOT_DISTRIBUTED);

	releaseTmLock();

	LWLockRelease(ProcArrayLock);

	MIRRORED_UNLOCK;

	currentGxact = gxact;

	elog(DTM_DEBUG5,
		 "createDtx created new distributed transaction gid = %s, gxid = %u.",
		 currentGxact->gid, currentGxact->gxid);
}


/*
 * Release global transaction's shared memory.
 * Must already hold ProcArrayLock and the DTM lock.
 */
static void
releaseGxact_UnderLocks(void)
{
	int			i;
	int			curr;

	if (currentGxact == NULL)
	{
		elog(FATAL, "releaseGxact expected currentGxact to not be NULL");
	}

	elog(DTM_DEBUG5,
		 "releaseGxact called for gid = %s (index = %d)", currentGxact->gid, currentGxact->debugIndex);

	/*
	 * Protected by ProcArrayLock.
	 */
	LocalDistribXactRef_ReleaseUnderLock(
		&currentGxact->localDistribXactRef);

	/* find slot of current transaction */

	/*
	 * To maintain shmXminAllDistributedSnapshots we need to re-calculate,
	 * so we must scan the whole array for that purpose.  When we see
	 * the current one, we note its index and exclude it from the xmin
	 * calculation.
	 */
	curr = *shmNumGxacts;	/* A bad value we can safely test. */
	*shmXminAllDistributedSnapshots = InvalidDistributedTransactionId;
	for (i = 0; i < *shmNumGxacts; i++)
	{
		if (shmGxactArray[i] == currentGxact)
		{
			curr = i;
		}
		else
		{
			DistributedTransactionId xminDistributedSnapshot = shmGxactArray[i]->xminDistributedSnapshot;

			if (xminDistributedSnapshot != InvalidDistributedTransactionId)
			{
				/*
				 * Check for minimum.
				 */
				if (*shmXminAllDistributedSnapshots == InvalidDistributedTransactionId)
				{
					/*
					 * Always set first one other than current being released.
					 */
					*shmXminAllDistributedSnapshots = xminDistributedSnapshot;
				}
				else if (xminDistributedSnapshot < *shmXminAllDistributedSnapshots)
				{
					*shmXminAllDistributedSnapshots = xminDistributedSnapshot;
				}
			}
		}
	}

	elog(DTM_DEBUG5,
		 "releaseGxact re-calculated all distributed snapshots xmin = %u for %d global transactions.",
		 *shmXminAllDistributedSnapshots, *shmNumGxacts-1);

	/* move this to the next available slot */
	(*shmNumGxacts)--;
	if (curr != *shmNumGxacts)
	{
		shmGxactArray[curr] = shmGxactArray[*shmNumGxacts];
		shmGxactArray[*shmNumGxacts] = currentGxact;
	}

	if (currentGxact->bumpedPhase1Count)
	{
		(*shmCurrentPhase1Count)--;
	}

	currentGxact = NULL;
}

/*
 * Release global transaction's shared memory.
 */
static void
releaseGxact(void)
{
	/*
	 * Global locking order: ProcArrayLock then DTM lock.
	 */
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

	getTmLock();

	releaseGxact_UnderLocks();

	releaseTmLock();

	LWLockRelease(ProcArrayLock);
}

/*
 * Get lock that serializes commits with DTM checkpoint info.
 * Change state to DTX_STATE_INSERTING_COMMITTED.
 */
void
insertingDistributedCommitted(void)
{
	elog(DTM_DEBUG5,
		 "insertingDistributedCommitted entering in state = %s",
	     DtxStateToString(currentGxact->state));

	getTmLock();
	Assert(currentGxact->state == DTX_STATE_PREPARED);
	setCurrentGxactState( DTX_STATE_INSERTING_COMMITTED );
}

/*
 * Change state to DTX_STATE_INSERTED_COMMITTED.
 * Release lock.
 */
void
insertedDistributedCommitted(void)
{
	elog(DTM_DEBUG5,
		 "insertedDistributedCommitted entering in state = %s for gid = %s",
	     DtxStateToString(currentGxact->state), currentGxact->gid);

	Assert(currentGxact->state == DTX_STATE_INSERTING_COMMITTED);
	setCurrentGxactState( DTX_STATE_INSERTED_COMMITTED );
	releaseTmLock();
}


/*
 * Change state to DTX_STATE_FORCED_COMMITTED.
 */
void
forcedDistributedCommitted(XLogRecPtr *recptr)
{
	elog(DTM_DEBUG5,
		 "forcedDistributedCommitted entering in state = %s for gid = %s (xlog record %X/%X)",
		DtxStateToString(currentGxact->state), currentGxact->gid, recptr->xlogid, recptr->xrecoff);

	getTmLock();
	Assert(currentGxact->state == DTX_STATE_INSERTED_COMMITTED);
	setCurrentGxactState( DTX_STATE_FORCED_COMMITTED );
	releaseTmLock();
}



/*
 * Get check point information
 *
 * Whether DTM started or not, we must always store DTM information in
 * this checkpoint record.  A possible case to consider is we might have
 * in-progress global transactions in shared memory after postmaster reset,
 * and shutting down without performing DTM recovery.  The subsequent
 * recovery after this shutdown will read this checkpoint, so we would
 * lose the in-progress global transaction information if we didn't write it
 * here.  Note we will certainly read this global transaction information
 * even if this is a clean shutdown (i.e. not performing multi-pass recovery.)
 */
void
getDtxCheckPointInfoAndLock(char **result, int *result_size)
{
	TMGXACT    	*gxact;
	DtxState	  	state;
	int				  	n;
	TMGXACT_CHECKPOINT 	*gxact_checkpoint;
	TMGXACT_LOG 	  	*gxact_log_array;
	int				  	i;
	int				  	actual;
	TMGXACT_LOG       	*gxact_log;

	getTmLock();	/* We will return with lock held below. */
	n = *shmNumGxacts;

	gxact_checkpoint = palloc(TMGXACT_CHECKPOINT_BYTES(n));
	gxact_log_array = &gxact_checkpoint->committedGxactArray[0];

	actual = 0;
	for (i = 0; i < n; i++)
	{
		gxact = shmGxactArray[i];

		gxact_log = &gxact_log_array[actual];

		state = gxact->state;
		switch (state)
		{
		case DTX_STATE_ACTIVE_NOT_DISTRIBUTED:
		case DTX_STATE_ACTIVE_DISTRIBUTED:
		case DTX_STATE_PREPARING:
		case DTX_STATE_PREPARED:
			/*
			 * Active or attempting to commit -- ignore.
			 */
			continue;

		case DTX_STATE_INSERTED_FORGET_COMMITTED:
			elog(FATAL, "Should not see this transitional state with TM lock held -- dtx state \"%s\" not expected here",
				 DtxStateToString(state));
			continue;

		case DTX_STATE_INSERTING_COMMITTED:
			elog(FATAL, "Cannot also be buffering COMMITTED from another process with TM lock held");
			continue;

		case DTX_STATE_INSERTING_FORGET_COMMITTED:
			elog(FATAL, "Cannot also be buffering FORGET COMMITTED from another process with TM lock held");
			continue;

		case DTX_STATE_INSERTED_COMMITTED:
		case DTX_STATE_FORCED_COMMITTED:
		case DTX_STATE_NOTIFYING_COMMIT_PREPARED:
		case DTX_STATE_RETRY_COMMIT_PREPARED:
		case DTX_STATE_CRASH_COMMITTED:
			break;

		case DTX_STATE_NOTIFYING_ABORT_NO_PREPARED:
		case DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED:
		case DTX_STATE_NOTIFYING_ABORT_PREPARED:
		case DTX_STATE_RETRY_ABORT_PREPARED:
			/*
			 * We don't checkpoint abort.
			 */
			continue;

		default:
			elog(PANIC, "Unexpected dtm state: %d",
				(int) state);
			break;
		}

		if (strlen(gxact->gid) >= TMGIDSIZE)
			elog(PANIC, "Distribute transaction identifier too long (%d)",
				 (int)strlen(gxact->gid));
		memcpy(gxact_log->gid, gxact->gid, TMGIDSIZE);
		gxact_log->gxid = gxact->gxid;

		elog(DTM_DEBUG5, "Add DTM checkpoint entry gid = %s.",
			 gxact->gid);
		if (Debug_persistent_recovery_print)
		{
			SUPPRESS_ERRCONTEXT_DECLARE;

			SUPPRESS_ERRCONTEXT_PUSH();

			elog(PersistentRecovery_DebugPrintLevel(),
				 "getDtxCheckPointInfoAndLock[%d]: distributed transaction identifier %s (distributed xid %u)",
				 actual,
				 gxact_log->gid,
				 gxact_log->gxid);

			SUPPRESS_ERRCONTEXT_POP();
		}

		actual++;
	}

	gxact_checkpoint->committedCount = actual;
	gxact_checkpoint->segmentCount = 0;		/* UNDONE: Not used yet. */

	*result = (char*)gxact_checkpoint;
	*result_size = TMGXACT_CHECKPOINT_BYTES(actual);

	/* Return with lock held. */

	elog(DTM_DEBUG5, "Filled in DTM checkpoint information (count = %d).",
	      actual);
}

void
freeDtxCheckPointInfoAndUnlock(char *info, int info_size  __attribute__((unused)) , XLogRecPtr *recptr)
{
	pfree(info);

	releaseTmLock();

	elog(DTM_DEBUG5, "Checkpoint with DTM information written at %X/%X.",
		 recptr->xlogid, recptr->xrecoff);
}

/* generate global transaction id */
static void
generateGID(char *gid, DistributedTransactionId *gxid)
{
	/* tm lock acquired by caller */
	if (*shmGIDSeq >= LastDistributedTransactionId)
	{
		releaseTmLock();
		ereport(FATAL,
			(errmsg("reached limit of %u global transactions per start", LastDistributedTransactionId)));
	}

	*gxid = (*shmGIDSeq)++;
	sprintf(gid, "%u-%.10u", *shmDistribTimeStamp, (*gxid));
	if (strlen(gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
			 (int)strlen(gid));
}

/*
 * recoverTM:
 * perform TM recovery, this connects to all QE and resolve all in-doubt txn.
 *
 * This gets called when there is not any other DTM activity going on.
 *
 * First, we'll replay the dtm log and get our shmem as up to date as possible
 * in order to help resolve in-doubt transactions.	Then we'll go through and
 * try and resolve in-doubt transactions based on information in the DTM log.
 * The remaining in-doubt transactions that remain (ones the DTM doesn't know
 * about) are all ABORTed.
 *
 * If we're in read-only mode; we need to get started, but we can't run the
 * full recovery. So we go get the highest distributed-xid, but don't run
 * the recovery.
 */
static void
recoverTM(void)
{
	DistributedTransactionId segmentMaxDistributedTransactionId = 0;

	/* intialize fts sync count */
	verifyFtsSyncCount();

	elog(DTM_DEBUG3, "Starting to Recover DTM...");

	/*
	 * do not do recovery if read only mode is set.
	 * in this case, there may be in-doubt transaction in down segdb
	 * , which will not be resolved at this time.
	 */
	if (isFtsReadOnlySet())
	{
		elog(DTM_DEBUG3, "FTS is Read Only.  Defer DTM recovery till later.");
		if (currentGxact != NULL)
		{
			elog(DTM_DEBUG5,
				 "recoverTM setting currentGxact to NULL for gid = %s (index = %d)",
				 currentGxact->gid, currentGxact->debugIndex);
		}
		currentGxact = NULL;

		*shmDtmRecoveryDeferred = true;
	}
	else
		*shmDtmRecoveryDeferred = false;

	if (Gp_role == GP_ROLE_UTILITY)
	{
		elog(DTM_DEBUG3, "DB in Utility mode.  Defer DTM recovery till later.");
		return;
	}

	if (!*shmDtmRecoveryDeferred)
	{
		/*
		 * Attempt to recover all in-doubt transactions.
		 *
		 * first resolve all in-doubt transactions from the DTM's perspective
		 * and then resolve any remaining in-doubt transactions that the
		 * RMs have.
		 */
		recoverInDoubtTransactions();
	}
	else
		elog(LOG, "DTM starting in readonly-mode: deferring recovery");

	/* finished recovery successfully. */

	segmentMaxDistributedTransactionId = determineSegmentMaxDistributedXid();
	if (segmentMaxDistributedTransactionId >= *shmGIDSeq)
	{
		*shmGIDSeq = segmentMaxDistributedTransactionId + 1;
	}

	elog(LOG, "Next distributed transaction id is %u", *shmGIDSeq);

	*shmDtmStarted = true;
	elog(LOG, "DTM Started");
}

static bool deferredRecoveryActive=false;

/*
 * When running in readonly-mode, we may wind up in a state where we've deferred
 * recovery waiting for a segment to come online.
 */
void
cdbtm_performDeferredRecovery(void)
{
	if (deferredRecoveryActive)
		return;

	if (*shmDtmRecoveryDeferred)
	{
		getTmLock();
		if (*shmDtmRecoveryDeferred)
		{
			deferredRecoveryActive=true;
			PG_TRY();
			{
				recoverInDoubtTransactions();

				deferredRecoveryActive=false;
			}
			PG_CATCH();
			{
				deferredRecoveryActive=false;
				PG_RE_THROW();
			}
			PG_END_TRY();

			*shmDtmRecoveryDeferred = false;
			elog(NOTICE, "Releasing segworker groups for deferred recovery.");
G
Gang Xiong 已提交
3185
			disconnectAndDestroyAllGangs(true);
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218
		}
		releaseTmLock();
		CheckForResetSession();
	}
}

/* recoverInDoubtTransactions:
 * Go through all in-doubt transactions that the DTM knows about and
 * resolve them.
 */
static bool
recoverInDoubtTransactions(void)
{
	int i;
	HTAB *htab;
	TMGXACT *saved_currentGxact;

	elog(DTM_DEBUG3, "recover in-doubt distributed transactions");

	ReplayRedoFromUtilityMode();

	/*
	 * For each committed transaction found in the redo pass that was not
	 * matched by a forget committed record, change its state indicating
	 * committed notification needed.  Attempt a notification.
	 */
	elog(DTM_DEBUG5,
		 "Going to retry commit notification for distributed transactions (count = %d)",
	     *shmNumGxacts);
	dumpAllDtx();

	saved_currentGxact = currentGxact;

3219
	for (i = 0; i < *shmNumGxacts; )
3220 3221 3222 3223 3224 3225 3226 3227
	{
		TMGXACT *gxact = shmGxactArray[i];

		/*
		 * MPP-4867: if we are running deferred, skip any transaction we're already inside.
		 */
		if (saved_currentGxact != NULL && gxact == saved_currentGxact)
		{
3228
			i++;
3229 3230 3231 3232 3233
			continue;
		}
		else if (gxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
		{
			/* should take care of other sessions. */
3234
			i++;
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
			continue;
		}

		if (gxact->state != DTX_STATE_CRASH_COMMITTED)
		{
			dumpAllDtx();
			elog(PANIC,
				 "recoverInDoubtTransactions found transaction in '%s' state and was expecting it to be in '%s' state",
				 DtxStateToString(gxact->state), DtxStateToString(DTX_STATE_CRASH_COMMITTED));
		}

		elog(DTM_DEBUG5,
			 "Recovering committed distributed transaction gid = %s",
		     gxact->gid);

		/*
		 * Can't start system if we cannot deliiver commits.
		 */
		doNotifyCommittedInDoubt(gxact->gid);

		/*
		 * This means there was atleast one in-doubt transactions for
		 * whom prepared commit was sent out. Hence, we've a chance to
		 * perform PT-Catalog verification if requested.
		 */
		if (debug_persistent_ptcat_verification)
			Persistent_Set_PostDTMRecv_PTCatVerificationNeeded();

		currentGxact = gxact;

		/*
		 * Global locking order: ProcArrayLock then DTM lock since
		 * calls doInsertForgetCommitted calls releaseGxact.
		 */
		LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);

		getTmLock();

3273 3274 3275
		/* This routine would call releaseGxact_UnderLocks, which
		 * would decrease *shmNumGxacts and do a swap, so no need
		 * to increase i */
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449
		doInsertForgetCommitted();

		releaseTmLock();

		LWLockRelease(ProcArrayLock);

	}

	currentGxact = saved_currentGxact;
	dumpAllDtx();

	/*
	 * UNDONE: Thus, any in-doubt transctions found will be for aborted transactions.
	 * UNDONE: Gather in-boubt transactions and issue aborts.
	 */
	htab = gatherRMInDoubtTransactions();

	/*
	 * go through and resolve any remaining in-doubt transactions that the
	 * RM's have AFTER recoverDTMInDoubtTransactions.  ALL of these in doubt
	 * transactions will be ABORT'd.  The fact that the DTM doesn't know about
	 * them means that something bad happened before everybody voted to
	 * COMMIT.
	 */
	abortRMInDoubtTransactions(htab);

	/*
	 * If there were any In-Doubt transactions collected from the segment
	 * instances and if the verification checks are requested then make the flag
	 * green so that the system is informed to run the verification
	 * checks post DTM is recovered
	 */
	if (debug_persistent_ptcat_verification && htab)
		Persistent_Set_PostDTMRecv_PTCatVerificationNeeded();

	/* get rid of the hashtable */
	hash_destroy(htab);

	/* yes... we are paranoid and will double check */
	htab = gatherRMInDoubtTransactions();

	/*
	 * Hmm.  we still have some remaining indoubt transactions.  For now we
	 * dont have an automated way to clean this mess up.  So we'll have to
	 * rely on smart Admins to do the job manually.  We'll error out of here
	 * and try and provide as much info as possible.
	 *
	 * TODO: We really want to be able to say this particular segdb has these
	 * remaining in-doubt transactions.
	 */
	if (htab != NULL)
	{
		StringInfoData indoubtBuff;

		initStringInfo(&indoubtBuff);

		dumpAllDtx();
		dumpRMOnlyDtx(htab, &indoubtBuff);

		ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
						errmsg("DTM Log recovery failed.  There are still unresolved "
							   "in-doubt transactions on some of the segment databaes "
							   "that were not able to be resolved for an unknown reason. "),
						errdetail("Here is a list of in-doubt transactions in the system: %s",
								  indoubtBuff.data),
						errhint("Try restarting the Greenplum Database array.  If the problem persists "
								" an Administrator will need to resolve these transactions "
								" manually.")));

	}

	RemoveRedoUtilityModeFile();

	return true;
}

/*
 * determineSegmentMaxDistributedXid:
 *
 * Since we don't know whether the Segment Databases were left over from
 * an earlier start or left over from a postmaster system reset due to
 * a server process failure, we must go out and determine the maximum
 * distributed transaction id currently in-use.
 */
static DistributedTransactionId
determineSegmentMaxDistributedXid(void)
{
	DistributedTransactionId max = 0;
	int		i;
	int 	resultCount = 0;
	struct pg_result **results = NULL;
	StringInfoData buffer;
	StringInfoData errbuf;

#define FUNCTION_DOES_NOT_EXIST "function gp_max_distributed_xid() does not exist"

	initStringInfo(&buffer);

	appendStringInfo(&buffer, "select gp_max_distributed_xid()");

	initStringInfo(&errbuf);

	results = cdbdisp_dispatchRMCommand(buffer.data, /* Snapshot */ false,
		                                &errbuf, &resultCount);

	if (errbuf.len > 0)
	{
		int cmplen = strlen(FUNCTION_DOES_NOT_EXIST);

		if (strlen(errbuf.data) >= cmplen &&
			strncmp(errbuf.data, FUNCTION_DOES_NOT_EXIST, cmplen ) == 0)
		{
			elog(LOG, "The function gp_max_distributed_xid is missing on one or more segments.  The beta 3.0 upgrade steps are necessary");

		}
		else
		{
			ereport(ERROR,
					(errmsg("gp_max_distributed_xid error (gathered %d results from cmd '%s')", resultCount, buffer.data),
					 errdetail("%s", errbuf.data)));
		}
	}
	else
	{
		elog(DTM_DEBUG5, "determineSegmentMaxDistributedXid resultCount = %d",resultCount);

		for (i = 0; i < resultCount; i++)
		{
			if (PQresultStatus(results[i]) != PGRES_TUPLES_OK)
			{
				elog(ERROR, "gp_max_distributed_xid: resultStatus not tuples_Ok");
			}
			else
			{
				/*
				 * Due to funkyness in the current dispatch agent code, instead of 1 result
				 * per QE with 1 row each, we can get back 1 result per dispatch agent, with
				 * one row per QE controlled by that agent.
				 */
				int j;
				for (j = 0; j < PQntuples(results[i]); j++)
				{
					DistributedTransactionId temp = 0;
					temp  =  atol(PQgetvalue(results[i], j, 0));
					elog(DTM_DEBUG5, "determineSegmentMaxDistributedXid value = %d",temp);
					if (temp  > max)
						max = temp;
				}
			}
		}
	}

	pfree(errbuf.data);

	for (i = 0; i < resultCount; i++)
		PQclear(results[i]);
	free(results);

	return max;
}



/*
 * gatherRMInDoubtTransactions:
 * Builds a hashtable of all of the in-doubt transactions that exist on the
 * segment databases.  The hashtable basically just serves as a single list
 * without duplicates of all the in-doubt transactions.  It does not keep track
 * of which seg db's have which transactions in-doubt.  It currently doesn't
 * need to due to the way we handle this information later.
 */
static HTAB *
gatherRMInDoubtTransactions(void)
{
3450 3451
	PGresult  **pgresultSets;
	int			nresultSets;
3452 3453
	StringInfoData errmsgbuf;
	const char *cmdbuf = "select gid from pg_prepared_xacts";
3454
	PGresult   *rs;
3455 3456 3457 3458 3459

	InDoubtDtx *lastDtx = NULL;

	HASHCTL		hctl;
	HTAB	   *htab = NULL;
3460
	int			i;
3461 3462 3463 3464 3465 3466 3467 3468
	int			j,
				rows;
	bool		found;

	initStringInfo(&errmsgbuf);

	/* call to all QE to get in-doubt transactions */
	pgresultSets = cdbdisp_dispatchRMCommand(cmdbuf, /* withSnapshot */false,
3469
											 &errmsgbuf, &nresultSets);
3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487

	/* display error messages */
	if (errmsgbuf.len > 0)
	{
		ereport(ERROR, (errcode(ERRCODE_GP_INTERCONNECTION_ERROR),
					errmsg("Unable to collect list of prepared transactions "
						   "from all segment databases."),
						errdetail("%s", errmsgbuf.data)));

		pfree(errmsgbuf.data);

		/* need recovery */
		return NULL;
	}

	pfree(errmsgbuf.data);

	/* If any result set is nonempty, there are in-doubt transactions. */
3488
	for (i = 0; i < nresultSets; i++)
3489
	{
3490 3491
		rs  = pgresultSets[i];
		rows = PQntuples(rs);
3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516

		for (j = 0; j < rows; j++)
		{
			char	   *gid;

			/*
			 * we dont setup our hashtable until we know we have at least one
			 * in doubt transaction
			 */
			if (htab == NULL)
			{

				/* setup a hash table */
				hctl.keysize = TMGIDSIZE;		/* GID */
				hctl.entrysize = sizeof(InDoubtDtx);

				htab = hash_create("InDoubtDtxHash", 10, &hctl, HASH_ELEM);

				if (htab == NULL)
				{
					ereport(FATAL, (errcode(ERRCODE_OUT_OF_MEMORY),
									errmsg("DTM could not allocate hash table for InDoubtDtxList.")));
				}
			}

3517
			gid = PQgetvalue(rs, j, 0);
3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535

			/* Now we can add entry to hash table */
			lastDtx = (InDoubtDtx *) hash_search(htab, gid, HASH_ENTER, &found);

			/*
			 * only need to bother doing work if there isn't already an entry
			 * for our GID
			 */
			if (!found)
			{
				elog(DEBUG3, "Found in-doubt transaction with GID: %s on remote RM", gid);

				strcpy(lastDtx->gid, gid);
			}

		}
	}

3536 3537 3538
	for (i = 0; i < nresultSets; i++)
		PQclear(pgresultSets[i]);
	free(pgresultSets);
3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472

	return htab;
}

static bool
FindRetryNotifyCommitted(char* gid, TMGXACT **gxact)
{
	int i;

	for (i = 0; i < *shmNumGxacts; i++)
	{
		if (strcmp(gid, shmGxactArray[i]->gid) == 0)
		{
			/* found an retry notify committed */
			*gxact = shmGxactArray[i];
			return true;
		}
	}

	return false;
}

/*
 * abortRMInDoubtTransactions:
 * Goes through all the InDoubtDtx's in the provided htab and ABORTs them
 * across all of the QEs by sending a ROLLBACK PREPARED.
 *
 */
static void
abortRMInDoubtTransactions(HTAB *htab)
{
	HASH_SEQ_STATUS status;
	InDoubtDtx *entry = NULL;
	TMGXACT	   *gxact = NULL;

	if (htab == NULL)
		return;

	/*
	 * now we have a nice hashtable full of in-doubt dtx's that we need to
	 * resolve.  so we'll use a nice big hammer to get this job done.  instead
	 * of keeping track of which QEs have a prepared txn to be aborted and
	 * which ones don't.  we just issue a ROLLBACK to all of them and ignore
	 * any pesky errors.  This is certainly not an elegant solution but is OK
	 * for now.
	 */
	hash_seq_init(&status, htab);


	while ((entry = (InDoubtDtx *) hash_seq_search(&status)) != NULL)
	{
		if (FindRetryNotifyCommitted(entry->gid, &gxact))
		{
			elog(DTM_DEBUG5, "Skipping in-doubt transaction gid = %s since it is \"%s\"",
				 gxact->gid, DtxStateToString(gxact->state));
			continue;
		}

		elog(DTM_DEBUG3, "Aborting in-doubt transaction with gid = %s", entry->gid);

		doAbortInDoubt(entry->gid);

	}
}

/*
 * dumpAllDtx:
 * used to log the current state (according to the DTM) of all the
 * global distributed transactions that are still active (in shmem).
 */
static void
dumpAllDtx(void)
{
	int			i;

	elog(LOG, "dumping all global transactions: ");
	for (i = 0; i < *shmNumGxacts; i++)
	{
		elog(LOG, "%d - GID: %s  STATE: %s",
			 i, shmGxactArray[i]->gid,
			 DtxStateToString(shmGxactArray[i]->state));
	}
}


static void
dumpRMOnlyDtx(HTAB *htab, StringInfoData *buff)
{
	HASH_SEQ_STATUS status;
	InDoubtDtx *entry = NULL;

	if (htab == NULL)
		return;

	hash_seq_init(&status, htab);

	appendStringInfo(buff, "List of In-doubt transactions remaining across the segdbs: (");

	while ((entry = (InDoubtDtx *) hash_seq_search(&status)) != NULL)
	{
		appendStringInfo(buff, "\"%s\" , ", entry->gid);
	}

	appendStringInfo(buff, ")");

}


/*
 * When called, a SET command is dispatched and the writer gang
 * writes the shared snapshot. This function actually does nothing
 * useful besides making sure that a writer gang is alive and has
 * set the shared snapshot so that the readers could access it.
 *
 * At this point this function is added as a helper for cursor
 * query execution since in MPP cursor queries don't use writer
 * gangs. However, it could be used for other purposes as well.
 *
 * See declaration of assign_gp_write_shared_snapshot(...) for more
 * information.
 */
void verify_shared_snapshot_ready(void)
{
	if (Gp_role == GP_ROLE_DISPATCH)
	{
		CdbDoCommand("set gp_write_shared_snapshot=true", true, true);

		dumpSharedLocalSnapshot_forCursor();

		/*
		 * To keep our readers in sync (since they will be dispatched
		 * separately) we need to rewind the segmate synchronizer.
		 */
		DtxContextInfo_RewindSegmateSync();
	}
}

/*
 * Force the writer QE to write the shared snapshot. Will get called
 * after a "set gp_write_shared_snapshot=<true/false>" is executed
 * in dispatch mode.
 *
 * See verify_shared_snapshot_ready(...) for additional information.
 */
bool
assign_gp_write_shared_snapshot(bool newval, bool doit, GucSource source __attribute__((unused)) )
{

#if FALSE
	elog(DEBUG1, "SET gp_write_shared_snapshot: %s, doit=%s",
		 (newval ? "true" : "false"), (doit ? "true" : "false"));
#endif
	/*
	 * Make sure newval is "true". if it's "false" this could be a
	 * part of a ROLLBACK so we don't want to set the snapshot then.
	 */
	if (doit && newval)
	{
		if (Gp_role == GP_ROLE_EXECUTE)
		{
			ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());

			if (Gp_is_writer)
			{
				dumpSharedLocalSnapshot_forCursor();
			}
		}
	}

	return true;
}

static void
doQEDistributedExplicitBegin(int txnOptions)
{
	int ExplicitIsoLevel;
	bool ExplicitReadOnly;

	/*
	 * Start a command.
	 */
	StartTransactionCommand();

	/* Here is the explicit BEGIN. */
	BeginTransactionBlock();

	unpackMppTxnOptions(txnOptions,
		&ExplicitIsoLevel, &ExplicitReadOnly);

	XactIsoLevel = ExplicitIsoLevel;
	XactReadOnly = ExplicitReadOnly;

	elog(DTM_DEBUG5, "doQEDistributedExplicitBegin setting XactIsoLevel = %s and XactReadOnly = %s",
		 IsoLevelAsUpperString(XactIsoLevel), (XactReadOnly ? "true" : "false"));

	/*
	 * Finish the BEGIN command.  It will leave the explict transaction
	 * in-progress.
	 */
	CommitTransactionCommand();

}

static bool
isDtxQueryDispatcher(void)
{
	bool isDtmStarted;
	bool isSharedLocalSnapshotSlotPresent;

	isDtmStarted = (shmDtmStarted != NULL && *shmDtmStarted);
	isSharedLocalSnapshotSlotPresent = (SharedLocalSnapshotSlot != NULL);

 	return (Gp_role == GP_ROLE_DISPATCH &&
		    isDtmStarted &&
		    isSharedLocalSnapshotSlotPresent);
}

/*
 * Called prior to handling a requested that comes to the QD, or a utility request to a QE.
 *
 * Sets up the distributed transaction context value and does some basic error checking.
 *
 * Essentially:
 *     if the DistributedTransactionContext is already QD_DISTRIBUTED_CAPABLE then leave it
 *     else if the DistributedTransactionContext is already QE_TWO_PHASE_EXPLICIT_WRITER then leave it
 *     else it MUST be a LOCAL_ONLY, and is converted to QD_DISTRIBUTED_CAPABLE if this process is acting
 *          as a QE.
 */
void
setupRegularDtxContext(void)
{
	switch(DistributedTransactionContext)
	{
		case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
			/* Continue in this context.  Do not touch QEDtxContextInfo, etc. */
			break;

		case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
			/* Allow this for copy...???  Do not touch QEDtxContextInfo, etc. */
			break;

		default:
			if (DistributedTransactionContext != DTX_CONTEXT_LOCAL_ONLY)
			{
				/* we must be one of:

				   DTX_CONTEXT_QD_RETRY_PHASE_2,
				   DTX_CONTEXT_QE_ENTRY_DB_SINGLETON,
				   DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT,
				   DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER,
				   DTX_CONTEXT_QE_READER,
				   DTX_CONTEXT_QE_PREPARED
				*/

				elog(ERROR, "setupRegularDtxContext finds unexpected DistributedTransactionContext = '%s'",
					 DtxContextToString(DistributedTransactionContext));
			}

			/* DistributedTransactionContext is DTX_CONTEXT_LOCAL_ONLY */

			Assert(QEDtxContextInfo.distributedXid == InvalidDistributedTransactionId);

			/*
			 * Determine if we are strictly local or a distributed capable QD.
			 */
			Assert(DistributedTransactionContext == DTX_CONTEXT_LOCAL_ONLY);

			if (isDtxQueryDispatcher())
			{
				setDistributedTransactionContext(DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE);
			}
			break;
	}

	elog(DTM_DEBUG5, "setupRegularDtxContext leaving with DistributedTransactionContext = '%s'.",
		 DtxContextToString(DistributedTransactionContext));
}

/**
 * Called on the QE when a query to process has been received.
 *
 * This will set up all distributed transaction information and set the state appropriately.
 */
void
setupQEDtxContext (DtxContextInfo *dtxContextInfo)
{
	DistributedSnapshot *distributedSnapshot;
	int txnOptions;
	bool needTwoPhase;
	bool explicitBegin;
	bool haveDistributedSnapshot;
	bool isEntryDbSingleton = false;
	bool isReaderQE = false;
	bool isWriterQE = false;
	bool isSharedLocalSnapshotSlotPresent;

	Assert (dtxContextInfo != NULL);

	/*
	 * DTX Context Info (even when empty) only comes in QE requests.
	 */
	distributedSnapshot = &dtxContextInfo->distributedSnapshot;
	txnOptions = dtxContextInfo->distributedTxnOptions;

	needTwoPhase = isMppTxOptions_NeedTwoPhase(txnOptions);
	explicitBegin = isMppTxOptions_ExplicitBegin(txnOptions);

	haveDistributedSnapshot =
		(dtxContextInfo->distributedXid!= InvalidDistributedTransactionId);
	isSharedLocalSnapshotSlotPresent = (SharedLocalSnapshotSlot != NULL);

	if (DEBUG5 >= log_min_messages || Debug_print_full_dtm)
	{
		elog(DTM_DEBUG5,
			 "setupQEDtxContext inputs (part 1): Gp_role = %s, Gp_is_writer = %s, "
			 "txnOptions = 0x%x, needTwoPhase = %s, explicitBegin = %s, isoLevel = %s, readOnly = %s, haveDistributedSnapshot = %s.",
			 role_to_string(Gp_role), (Gp_is_writer ? "true" : "false"), txnOptions,
			 (needTwoPhase ? "true" : "false"), (explicitBegin ? "true" : "false"),
			 IsoLevelAsUpperString(mppTxOptions_IsoLevel(txnOptions)), (isMppTxOptions_ReadOnly(txnOptions) ? "true" : "false"),
			 (haveDistributedSnapshot ? "true" : "false"));
	    elog(DTM_DEBUG5,
			 "setupQEDtxContext inputs (part 2): distributedXid = %u, isSharedLocalSnapshotSlotPresent = %s.",
			 dtxContextInfo->distributedXid,
		     (isSharedLocalSnapshotSlotPresent ? "true" : "false"));

		if (haveDistributedSnapshot)
		{
			elog(DTM_DEBUG5,
				 "setupQEDtxContext inputs (part 2a): distributedXid = %u, "
				 "distributedSnapshotData (xmin = %u, xmax = %u, xcnt = %u), distributedCommandId = %d",
				 dtxContextInfo->distributedXid,
				 distributedSnapshot->header.xmin, distributedSnapshot->header.xmax,
				 distributedSnapshot->header.count,
				 dtxContextInfo->curcid);
		}
		if (isSharedLocalSnapshotSlotPresent)
		{
			elog(DTM_DEBUG5,
				 "setupQEDtxContext inputs (part 2b):  shared local snapshot xid = %u "
				 "(xmin: %u xmax: %u xcnt: %u) curcid: %d, QDxid = %u/%u, QDcid = %u",
				 SharedLocalSnapshotSlot->xid,
				 SharedLocalSnapshotSlot->snapshot.xmin,
				 SharedLocalSnapshotSlot->snapshot.xmax,
	 			 SharedLocalSnapshotSlot->snapshot.xcnt,
				 SharedLocalSnapshotSlot->snapshot.curcid,
				 SharedLocalSnapshotSlot->QDxid, SharedLocalSnapshotSlot->segmateSync,
				 SharedLocalSnapshotSlot->QDcid);
		}
	}

	switch (Gp_role)
	{
		case GP_ROLE_EXECUTE:
			if (Gp_segment == -1 && !Gp_is_writer)
			{
				isEntryDbSingleton = true;
			}
			else
			{
				/*
				 * NOTE: this is a bit hackish. It appears as though
				 * StartTransaction() gets called during connection setup before
				 * we even have time to setup our shared snapshot slot.
				 */
				if (SharedLocalSnapshotSlot == NULL)
				{
					if (explicitBegin || haveDistributedSnapshot)
					{
						elog(ERROR, "setupQEDtxContext not expecting distributed begin or snapshot when no Snapshot slot exists");
					}
				}
				else
				{
					if (Gp_is_writer)
					{
						isWriterQE = true;
					}
					else
					{
						isReaderQE = true;
					}
				}
			}
			break;

		default:
			Assert(DistributedTransactionContext == DTX_CONTEXT_LOCAL_ONLY);
			elog(DTM_DEBUG5,
				 "setupQEDtxContext leaving context = 'Local Only' for Gp_role = %s", role_to_string(Gp_role) );
			return;
	}

	elog(DTM_DEBUG5,
		 "setupQEDtxContext intermediate result: isEntryDbSingleton = %s, isWriterQE = %s, isReaderQE = %s.",
		 (isEntryDbSingleton ? "true" : "false"),
		 (isWriterQE ? "true" : "false"), (isReaderQE ? "true" : "false"));

	/*
	 * Copy to our QE global variable.
	 */
	DtxContextInfo_Copy(&QEDtxContextInfo, dtxContextInfo);

	switch (DistributedTransactionContext)
	{
		case DTX_CONTEXT_LOCAL_ONLY:
			if (isEntryDbSingleton && haveDistributedSnapshot)
			{
				/*
				 * Later, in GetSnapshotData, we will adopt the QD's
				 * transaction and snapshot information.
				 */

				setDistributedTransactionContext( DTX_CONTEXT_QE_ENTRY_DB_SINGLETON );
			}
			else if (isReaderQE && haveDistributedSnapshot)
			{
				/*
				 * Later, in GetSnapshotData, we will adopt the QE Writer's
				 * transaction and snapshot information.
				 */

				setDistributedTransactionContext( DTX_CONTEXT_QE_READER );
			}
			else if (isWriterQE && (explicitBegin || needTwoPhase))
			{
				if (!haveDistributedSnapshot)
				{
					elog(DTM_DEBUG5,
						 "setupQEDtxContext Segment Writer is involved in a distributed transaction without a distributed snapshot...");
				}

				if (IsTransactionOrTransactionBlock())
				{
					elog(ERROR, "Starting an explicit distributed transaction in segment -- cannot already be in a transaction");
				}

				if (explicitBegin)
				{
					/*
					 * We set the DistributedTransactionContext BEFORE we create the
					 * transactions to influence the behavior of
					 * StartTransaction.
					 */
					setDistributedTransactionContext( DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER );

					doQEDistributedExplicitBegin(txnOptions);
				}
				else
				{
					Assert(needTwoPhase);
					setDistributedTransactionContext( DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER );
				}
			}
			else if (haveDistributedSnapshot)
			{
				if (IsTransactionOrTransactionBlock())
				{
					elog(ERROR,
						 "Going to start a local implicit transaction in segment using a distribute "
						 "snapshot -- cannot already be in a transaction");
				}

				/*
				 * Before executing the query, postgres.c make a standard call to
				 * StartTransactionCommand which will begin a local transaction with
				 * StartTransaction.  This is fine.
				 *
				 * However, when the snapshot is created later, the state below will
				 * tell GetSnapshotData to make the local snapshot from the
				 * distributed snapshot.
				 */
				setDistributedTransactionContext( DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT );
			}
			else
			{
				Assert (!haveDistributedSnapshot);

				/*
				 * A local implicit transaction without reference to
				 * a distributed snapshot.  Stay in NONE state.
				 */
				Assert(DistributedTransactionContext == DTX_CONTEXT_LOCAL_ONLY);
			}
			break;

		case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
/*
		elog(NOTICE, "We should have left this transition state '%s' at the end of the previous command...",
			 DtxContextToString(DistributedTransactionContext));
*/
			Assert (IsTransactionOrTransactionBlock());

			if (explicitBegin)
			{
				elog(ERROR, "Cannot have an explicit BEGIN statement...");
			}
			break;

		case DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT:
			elog(ERROR, "We should have left this transition state '%s' at the end of the previous command",
				 DtxContextToString(DistributedTransactionContext));
			break;

		case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
			Assert (IsTransactionOrTransactionBlock());
			break;

		case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
		case DTX_CONTEXT_QE_READER:
			/*
			 * We are playing games with the xact.c code, so we shouldn't test
			 * with the IsTransactionOrTransactionBlock() routine.
			 */
			break;

		case DTX_CONTEXT_QE_PREPARED:
		case DTX_CONTEXT_QE_FINISH_PREPARED:
			elog(ERROR, "We should not be trying to execute a query in state '%s'",
				 DtxContextToString(DistributedTransactionContext));
			break;

		default:
			elog(PANIC, "Unexpected segment distribute transaction context value: %d",
				 (int) DistributedTransactionContext);
			break;
	}

	elog(DTM_DEBUG5, "setupQEDtxContext final result: DistributedTransactionContext = '%s'.",
		 DtxContextToString(DistributedTransactionContext));

	if (haveDistributedSnapshot)
	{
		elog((Debug_print_snapshot_dtm ? LOG : DEBUG5), "[Distributed Snapshot #%u] *Set QE* currcid = %d (gxid = %u, '%s')",
			 dtxContextInfo->distributedSnapshot.header.distribSnapshotId,
			 dtxContextInfo->curcid,
			 getDistributedTransactionId(),
			 DtxContextToString(DistributedTransactionContext));
	}

}

void
finishDistributedTransactionContext (char* debugCaller, bool aborted)
{
	DistributedTransactionId gxid;

	/*
	 * We let the 2 retry states go up to PostgresMain.c, otherwise
	 * everything MUST be complete.
	 */
	if (currentGxact != NULL &&
	   (currentGxact->state != DTX_STATE_RETRY_COMMIT_PREPARED &&
	    currentGxact->state != DTX_STATE_RETRY_ABORT_PREPARED))
	{
/*		PleaseDebugMe("finishDistributedTransactionContext currentGxact == NULL"); */

		elog(FATAL, "Expected currentGxact to be NULL at this point.  Found gid =%s, gxid = %u (state = %s, caller = %s)",
			currentGxact->gid, currentGxact->gxid, DtxStateToString(currentGxact->state), debugCaller);
	}

	gxid = getDistributedTransactionId();
	elog(DTM_DEBUG5,
		 "finishDistributedTransactionContext called to change DistributedTransactionContext from %s to %s (caller = %s, gxid = %u)",
		 DtxContextToString(DistributedTransactionContext),
		 DtxContextToString(DTX_CONTEXT_LOCAL_ONLY),
		 debugCaller,
		 gxid);

	setDistributedTransactionContext( DTX_CONTEXT_LOCAL_ONLY );

	DtxContextInfo_Reset(&QEDtxContextInfo);

}

static void
rememberDtxExplicitBegin(void)
{
	if (currentGxact == NULL)
	{
		return;
	}

	if (!currentGxact->explicitBeginRemembered)
	{
		elog(DTM_DEBUG5, "rememberDtxExplicitBegin explicit BEGIN for gid = %s",
			 currentGxact->gid);
		currentGxact->explicitBeginRemembered = true;
	}
	else
	{
		elog(DTM_DEBUG5, "rememberDtxExplicitBegin already an explicit BEGIN for gid = %s",
			 currentGxact->gid);
	}
}

/*
 * This is mostly here because
 * cdbcopy doesn't use cdbdisp's services.
 */
void
sendDtxExplicitBegin(void)
{
	char		cmdbuf[100];

	if (currentGxact == NULL)
	{
		return;
	}

	rememberDtxExplicitBegin();

	dtmPreCommand("sendDtxExplicitBegin", "(none)", NULL,
			/* is two-phase */ true, /* withSnapshot */ true, /* inCursor */ false );

	/*
	 * Be explicit about both the isolation level and the access mode
	 * since in MPP our QEs are in a another process.
	 */
	sprintf(cmdbuf, "BEGIN ISOLATION LEVEL %s, READ %s",
			IsoLevelAsUpperString(XactIsoLevel),
			(XactReadOnly ? "ONLY" : "WRITE"));

	/*
	 * dispatch a DTX command, in the event of an error, this call
	 * will either exit via elog()/ereport() or return false
	 */
	if (!dispatchDtxCommand(cmdbuf, false, /* raiseError */ false))
	{
		ereport(ERROR, (errmsg("Global transaction BEGIN failed for gid = \"%s\" due to error",
							   currentGxact->gid)));
	}
}

int dtxCurrentPhase1Count(void)
{
	if (shmDtmStarted == NULL || !*shmDtmStarted)
	{
		return 0;
	}
	else
	{
		Assert(shmCurrentPhase1Count != NULL);
		return *shmCurrentPhase1Count;
	}
}

/**
 * On the QD, run the Prepare operation.
 */
static void
performDtxProtocolPrepare(const char *gid)
{
	StartTransactionCommand();

	elog(DTM_DEBUG5, "performDtxProtocolCommand going to call PrepareTransactionBlock for distributed transaction (id = '%s')", gid);
	if (!PrepareTransactionBlock((char *)gid))
	{
		elog(ERROR, "Prepare of distributed transaction %s failed", gid);
		return;
	}

	/*
	 * Calling CommitTransactionCommand will cause the actual
	 * COMMIT/PREPARE work to be performed.
	 */
	CommitTransactionCommand();

	elog(DTM_DEBUG5, "Prepare of distributed transaction succeeded (id = '%s')", gid);

	setDistributedTransactionContext( DTX_CONTEXT_QE_PREPARED );
}

/**
 * On the QD, run the Commit Prepared operation.
 */
static void
performDtxProtocolCommitPrepared(const char *gid, bool raiseErrorIfNotFound)
{
	elog(DTM_DEBUG5,
		 "performDtxProtocolCommitPrepared going to call FinishPreparedTransaction for distributed transaction %s", gid);

	StartTransactionCommand();

	/*
	 * Since this call may fail, lets setup a handler.
	 */
	PG_TRY();
	{
		FinishPreparedTransaction((char *)gid, /* isCommit */ true, raiseErrorIfNotFound);
	}
	PG_CATCH();
	{
		finishDistributedTransactionContext("performDtxProtocolCommitPrepared -- Commit Prepared (error case)", false);
		PG_RE_THROW();
	}
	PG_END_TRY();

	/*
	 * Calling CommitTransactionCommand will cause the actual
	 * COMMIT/PREPARE work to be performed.
	 */
	CommitTransactionCommand();

	finishDistributedTransactionContext("performDtxProtocolCommitPrepared -- Commit Prepared", false);
}

/**
 * On the QD, run the Abort Prepared operation.
 */
static void
performDtxProtocolAbortPrepared(const char *gid, bool raiseErrorIfNotFound)
{
	elog(DTM_DEBUG5, "performDtxProtocolAbortPrepared going to call FinishPreparedTransaction for distributed transaction %s", gid);

	StartTransactionCommand();

	/*
	 * Since this call may fail, lets setup a handler.
	 */
	PG_TRY();
	{
		FinishPreparedTransaction((char *)gid, /* isCommit */ false, raiseErrorIfNotFound);
	}
	PG_CATCH();
	{
		finishDistributedTransactionContext("performDtxProtocolAbortPrepared -- Commit Prepared (error case)", true);
		PG_RE_THROW();
	}
	PG_END_TRY();

	/*
	 * Calling CommitTransactionCommand will cause the actual
	 * COMMIT/PREPARE work to be performed.
	 */
	CommitTransactionCommand();

	finishDistributedTransactionContext("performDtxProtocolAbortPrepared -- Commit Prepared", true);
}

/**
 * On the QE, handle a DtxProtocolCommand
 */
void
performDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand,
						  int flags  __attribute__((unused)) ,
						  const char *loggingStr __attribute__((unused)) , const char *gid,
						  DistributedTransactionId gxid __attribute__((unused)),
						  DtxContextInfo *contextInfo)
{
	elog(DTM_DEBUG5,
		 "performDtxProtocolCommand called with DTX protocol = %s, segment distribute transaction context: '%s'",
		 DtxProtocolCommandToString(dtxProtocolCommand), DtxContextToString(DistributedTransactionContext));

	switch (dtxProtocolCommand)
	{
		case DTX_PROTOCOL_COMMAND_STAY_AT_OR_BECOME_IMPLIED_WRITER:
			switch(DistributedTransactionContext)
			{
			case DTX_CONTEXT_LOCAL_ONLY:
				/** convert to implicit_writer! */
				setupQEDtxContext(contextInfo);
				StartTransactionCommand();
				break;
			case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
				/** already the state we like */
				break;
			default:
				if ( isQEContext() || isQDContext())
				{
					elog(FATAL, "Unexpected segment distributed transaction context: '%s'",
						 DtxContextToString(DistributedTransactionContext));
				}
				else
				{
					elog(PANIC, "Unexpected segment distributed transaction context value: %d",
						 (int) DistributedTransactionContext);
				}
				break;
			}
			break;

		case DTX_PROTOCOL_COMMAND_ABORT_NO_PREPARED:
			elog(DTM_DEBUG5,
				 "performDtxProtocolCommand going to call AbortOutOfAnyTransaction for distributed transaction %s", gid);
			AbortOutOfAnyTransaction();
			break;

		case DTX_PROTOCOL_COMMAND_PREPARE:
			/*
			 * The QD has directed us to read-only commit or prepare an implicit or explicit
			 * distributed transaction.
			 */
			switch (DistributedTransactionContext)
			{
				case DTX_CONTEXT_LOCAL_ONLY:
					/*
					 * Spontaneously aborted while we were back at the QD?
					 */
					elog(ERROR, "Distributed transaction %s not found", gid);
					break;

				case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
				case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
					performDtxProtocolPrepare(gid);
					break;

				case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
				case DTX_CONTEXT_QD_RETRY_PHASE_2:
				case DTX_CONTEXT_QE_PREPARED:
				case DTX_CONTEXT_QE_FINISH_PREPARED:
				case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
				case DTX_CONTEXT_QE_READER:
					elog(FATAL, "Unexpected segment distribute transaction context: '%s'",
						 DtxContextToString(DistributedTransactionContext));

				default:
					elog(PANIC, "Unexpected segment distribute transaction context value: %d",
						 (int) DistributedTransactionContext);
					break;
			}
			break;

		case DTX_PROTOCOL_COMMAND_ABORT_SOME_PREPARED:
			switch (DistributedTransactionContext)
			{
				case DTX_CONTEXT_LOCAL_ONLY:
					/*
					 * Spontaneously aborted while we were back at the QD?
					 */
					elog(ERROR, "Distributed transaction %s not found", gid);
					break;

				case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
				case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
					AbortOutOfAnyTransaction();
					break;

				case DTX_CONTEXT_QE_PREPARED:
					setDistributedTransactionContext( DTX_CONTEXT_QE_FINISH_PREPARED );
					performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ true);
					break;

				case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE:
				case DTX_CONTEXT_QD_RETRY_PHASE_2:
				case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
				case DTX_CONTEXT_QE_READER:
					elog(PANIC, "Unexpected segment distribute transaction context: '%s'",
						 DtxContextToString(DistributedTransactionContext));

				default:
					elog(PANIC, "Unexpected segment distribute transaction context value: %d",
						 (int) DistributedTransactionContext);
					break;
			}
			break;

		case DTX_PROTOCOL_COMMAND_COMMIT_PREPARED:
			requireDistributedTransactionContext( DTX_CONTEXT_QE_PREPARED );
			setDistributedTransactionContext( DTX_CONTEXT_QE_FINISH_PREPARED );
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ true);
			break;

		case DTX_PROTOCOL_COMMAND_ABORT_PREPARED:
			requireDistributedTransactionContext( DTX_CONTEXT_QE_PREPARED );
			setDistributedTransactionContext( DTX_CONTEXT_QE_FINISH_PREPARED );
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ true);
			break;

		case DTX_PROTOCOL_COMMAND_RETRY_COMMIT_PREPARED:
			requireDistributedTransactionContext( DTX_CONTEXT_LOCAL_ONLY );
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RETRY_ABORT_PREPARED:
			requireDistributedTransactionContext( DTX_CONTEXT_LOCAL_ONLY );
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RECOVERY_COMMIT_PREPARED:
			requireDistributedTransactionContext( DTX_CONTEXT_LOCAL_ONLY );
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RECOVERY_ABORT_PREPARED:
			requireDistributedTransactionContext( DTX_CONTEXT_LOCAL_ONLY );
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_BEGIN_INTERNAL:
			switch(DistributedTransactionContext)
			{
				case DTX_CONTEXT_LOCAL_ONLY:
					/*
					 * QE is not aware of DTX yet.
					 * A typical case is SELECT foo(), where foo() opens internal subtransaction
					 */
					setupQEDtxContext(contextInfo);
					StartTransactionCommand();
					break;
				case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
				/* We already marked this QE to be writer, and transaction is open. */
				case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
				case DTX_CONTEXT_QE_READER:
					break;
				default:
					/* Lets flag this situation out, with explicit crash */
					Assert (DistributedTransactionContext != DistributedTransactionContext);
					elog(DTM_DEBUG5, 
						" SUBTRANSACTION_BEGIN_INTERNAL distributed transaction context invalid: %d",
						 (int) DistributedTransactionContext);
					break;
			}

			BeginInternalSubTransaction(NULL);
			Assert(contextInfo->nestingLevel+1 == GetCurrentTransactionNestLevel());
			break;

		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_RELEASE_INTERNAL:
			Assert(contextInfo->nestingLevel == GetCurrentTransactionNestLevel());
			ReleaseCurrentSubTransaction();
			break;
	
		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_ROLLBACK_INTERNAL:
			/* 
			 * Rollback performs work on master and then dispatches, 
			 * hence has nestingLevel its expecting post operation
			 */
			if ((contextInfo->nestingLevel + 1) > GetCurrentTransactionNestLevel())
			{
				ereport(ERROR, 
					(errmsg("transaction %s at level %d already processed (current level %d)",
						gid, contextInfo->nestingLevel, GetCurrentTransactionNestLevel())));
			}
			
4473
			unsigned int i = GetCurrentTransactionNestLevel() - contextInfo->nestingLevel;
4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489
			while (i > 0)
			{
				RollbackAndReleaseCurrentSubTransaction();
				i--;
			}

			Assert(contextInfo->nestingLevel == GetCurrentTransactionNestLevel());
			break;

		default:
			elog(ERROR, "Unrecognized dtx protocol command: %d",
				 (int) dtxProtocolCommand);
			break;
	}
	elog(DTM_DEBUG5, "performDtxProtocolCommand successful return for distributed transaction %s", gid);
}