cdbtm.c 91.2 KB
Newer Older
1 2 3 4 5
/*-------------------------------------------------------------------------
 *
 * cdbtm.c
 *	  Provides routines for performing distributed transaction
 *
6 7 8 9 10 11
 * Portions Copyright (c) 2005-2009, Greenplum inc
 * Portions Copyright (c) 2012-Present Pivotal Software, Inc.
 *
 *
 * IDENTIFICATION
 *	    src/backend/cdb/cdbtm.c
12 13 14 15 16 17
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <time.h>
18
#include <sys/types.h>
19 20
#include <unistd.h>

H
Heikki Linnakangas 已提交
21
#include "catalog/pg_authid.h"
22 23 24 25 26 27
#include "cdb/cdbtm.h"
#include "libpq/libpq-be.h"
#include "miscadmin.h"
#include "storage/shmem.h"
#include "storage/ipc.h"
#include "cdb/cdbdisp.h"
28 29
#include "cdb/cdbdisp_query.h"
#include "cdb/cdbdisp_dtx.h"
30
#include "cdb/cdbdispatchresult.h"
31 32 33 34 35
#include "cdb/cdbdtxcontextinfo.h"

#include "cdb/cdbvars.h"
#include "access/transam.h"
#include "access/xact.h"
36 37
#include "libpq-fe.h"
#include "libpq-int.h"
38 39 40 41 42
#include "cdb/cdbfts.h"
#include "lib/stringinfo.h"
#include "access/twophase.h"
#include "access/distributedlog.h"
#include "postmaster/postmaster.h"
43
#include "storage/procarray.h"
44 45 46 47

#include "cdb/cdbllize.h"
#include "utils/faultinjector.h"
#include "utils/fmgroids.h"
48
#include "utils/sharedsnapshot.h"
49
#include "utils/snapmgr.h"
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

extern bool Test_print_direct_dispatch_info;

#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;
G
Gang Xiong 已提交
67
static slock_t *shmControlSeqnoLock;
68
static volatile bool *shmTmRecoverred;
G
Gang Xiong 已提交
69
volatile DistributedTransactionTimeStamp *shmDistribTimeStamp;
70
static volatile DistributedTransactionId *shmGIDSeq = NULL;
71

A
Ashwin Agrawal 已提交
72
volatile bool *shmDtmStarted;
G
Gang Xiong 已提交
73
uint32 *shmNextSnapshotId;
74

G
Gang Xiong 已提交
75 76 77
/* transactions need recover */
TMGXACT_LOG *shmCommittedGxactArray;
volatile int *shmNumCommittedGxacts;
78 79 80 81 82 83 84 85 86

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

static int	max_tm_gxacts = 100;

static int	redoFileFD = -1;
A
Ashwin Agrawal 已提交
87
static int	redoFileOffset;
88 89 90 91

typedef struct InDoubtDtx
{
	char		gid[TMGIDSIZE];
A
Ashwin Agrawal 已提交
92
} InDoubtDtx;
93 94 95 96 97 98


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

99 100 101 102
/*
 * bit 1 is for statement wants DTX transaction
 * bits 2-4 for iso level
 * bit 5 is for read-only
103 104 105
 */
#define GP_OPT_NEED_TWO_PHASE                           0x0001

106 107 108 109 110
#define GP_OPT_ISOLATION_LEVEL_MASK   					0x000E
#define GP_OPT_READ_UNCOMMITTED							(1 << 1)
#define GP_OPT_READ_COMMITTED							(2 << 1)
#define GP_OPT_REPEATABLE_READ							(3 << 1)
#define GP_OPT_SERIALIZABLE								(4 << 1)
111 112 113 114 115 116 117 118

#define GP_OPT_READ_ONLY         						0x0010

#define GP_OPT_EXPLICT_BEGIN      						0x0020

/*=========================================================================
 * FUNCTIONS PROTOTYPES
 */
G
Gang Xiong 已提交
119 120 121
static DistributedTransactionId generateGID(void);
static void clearAndResetGxact(void);
static void resetCurrentGxact(void);
122 123 124 125 126 127 128 129 130
static void recoverTM(void);
static bool recoverInDoubtTransactions(void);
static HTAB *gatherRMInDoubtTransactions(void);
static void abortRMInDoubtTransactions(HTAB *htab);

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

static bool doDispatchDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand, int flags,
A
Ashwin Agrawal 已提交
131 132 133
							 char *gid, DistributedTransactionId gxid,
							 bool *badGangs, bool raiseError, CdbDispatchDirectDesc *direct,
							 char *serializedDtxContextInfo, int serializedDtxContextInfoLen);
134 135
static void doPrepareTransaction(void);
static void doInsertForgetCommitted(void);
G
Gang Xiong 已提交
136
static void clearTransactionState(void);
137 138
static void doNotifyingCommitPrepared(void);
static void doNotifyingAbort(void);
139
static void retryAbortPrepared(void);
140 141
static bool doNotifyCommittedInDoubt(char *gid);
static void doAbortInDoubt(char *gid);
142
static void doQEDistributedExplicitBegin();
143 144

static bool isDtxQueryDispatcher(void);
A
Ashwin Agrawal 已提交
145
static void UtilityModeSaveRedo(bool committed, TMGXACT_LOG *gxact_log);
146 147 148 149 150
static void ReplayRedoFromUtilityMode(void);
static void RemoveRedoUtilityModeFile(void);
static void performDtxProtocolCommitPrepared(const char *gid, bool raiseErrorIfNotFound);
static void performDtxProtocolAbortPrepared(const char *gid, bool raiseErrorIfNotFound);

G
Gang Xiong 已提交
151
extern void resetSessionForPrimaryGangLoss(bool resetSession);
152 153 154 155 156 157 158 159 160 161 162
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)
{
A
Ashwin Agrawal 已提交
163 164 165 166
	/*
	 * elog(INFO, "Setting DistributedTransactionContext to '%s'",
	 * DtxContextToString(context));
	 */
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
	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);
A
Ashwin Agrawal 已提交
185 186 187 188 189

	/*
	 * elog(INFO, "Setting transaction state to '%s'",
	 * DtxStateToString(state));
	 */
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	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)
{
A
Ashwin Agrawal 已提交
213
	switch (DistributedTransactionContext)
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
	{
		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()
{
A
Ashwin Agrawal 已提交
229
	switch (DistributedTransactionContext)
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
	{
		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)
{
A
Ashwin Agrawal 已提交
258
	if (isQDContext())
259 260 261 262 263
	{
		return currentGxact == NULL
			? InvalidDistributedTransactionId
			: currentGxact->gxid;
	}
A
Ashwin Agrawal 已提交
264
	else if (isQEContext())
265 266 267 268 269 270 271 272 273 274 275 276
	{
		return QEDtxContextInfo.distributedXid;
	}
	else
	{
		return InvalidDistributedTransactionId;
	}
}

bool
getDistributedTransactionIdentifier(char *id)
{
A
Ashwin Agrawal 已提交
277
	if (isQDContext())
278 279 280 281
	{
		if (currentGxact != NULL)
		{
			/*
A
Ashwin Agrawal 已提交
282 283
			 * The length check here requires the identifer have a trailing
			 * NUL character.
284 285 286
			 */
			if (strlen(currentGxact->gid) >= TMGIDSIZE)
				elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
287
					 (int) strlen(currentGxact->gid));
288 289 290 291
			memcpy(id, currentGxact->gid, TMGIDSIZE);
			return true;
		}
	}
A
Ashwin Agrawal 已提交
292
	else if (isQEContext())
293 294 295 296 297
	{
		if (QEDtxContextInfo.distributedXid != InvalidDistributedTransactionId)
		{
			if (strlen(QEDtxContextInfo.distributedId) >= TMGIDSIZE)
				elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
298
					 (int) strlen(QEDtxContextInfo.distributedId));
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
			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)",
A
Ashwin Agrawal 已提交
329
			 (int) strlen(currentGxact->gid));
330 331 332 333 334 335 336 337 338
	memcpy(gxact_log->gid, currentGxact->gid, TMGIDSIZE);
	gxact_log->gxid = currentGxact->gxid;
}

bool
notifyCommittedDtxTransactionIsNeeded(void)
{
	if (DistributedTransactionContext != DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE)
	{
A
Ashwin Agrawal 已提交
339
		elog(DTM_DEBUG5, "notifyCommittedDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
340 341 342 343 344 345
			 DtxContextToString(DistributedTransactionContext));
		return false;
	}

	if (currentGxact == NULL)
	{
A
Ashwin Agrawal 已提交
346
		elog(DTM_DEBUG5, "notifyCommittedDtxTransaction nothing to do (currentGxact == NULL)");
347 348 349 350 351 352
		return false;
	}

	return true;
}

G
Gang Xiong 已提交
353 354 355 356 357 358 359 360
bool
includeInCheckpointIsNeeded(TMGXACT *gxact)
{
	volatile DtxState state = gxact->state;
	return ((state >= DTX_STATE_INSERTED_COMMITTED &&
			 state < DTX_STATE_INSERTED_FORGET_COMMITTED) ||
			state == DTX_STATE_RETRY_COMMIT_PREPARED);
}
361 362 363 364 365 366 367
/*
 * Notify commited a global transaction, called by user commit
 * or by CommitTransaction
 */
void
notifyCommittedDtxTransaction(void)
{
A
Ashwin Agrawal 已提交
368
	Assert(DistributedTransactionContext == DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE);
369

A
Ashwin Agrawal 已提交
370
	Assert(currentGxact != NULL);
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

	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)
{
A
Ashwin Agrawal 已提交
393
	if (stmt == NULL)
394 395
		return false;

A
Ashwin Agrawal 已提交
396
	if (stmt->planTree == NULL)
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
		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)
{
A
Ashwin Agrawal 已提交
413
	if (!GetRootNodeIsDirectDispatch(stmt))
414 415 416
		return false;

	/*
A
Ashwin Agrawal 已提交
417 418 419 420
	 * 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.
421
	 */
A
Ashwin Agrawal 已提交
422
	if (stmt->nInitPlans > 0)
423 424 425 426 427 428 429 430 431 432 433
		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,
A
Ashwin Agrawal 已提交
434
			  bool needsTwoPhaseCommit, bool wantSnapshot, bool inCursor)
435
{
A
Ashwin Agrawal 已提交
436 437 438
	bool		needsPromotionFromDirectDispatch = false;
	const bool	rootNodeIsDirectDispatch = GetRootNodeIsDirectDispatch(stmt);
	const bool	nodeSaysDirectDispatch = GetPlannedStmtDirectDispatch_AndUsingNodeIsSufficient(stmt);
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

	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;

A
Ashwin Agrawal 已提交
466
			if (rootNodeIsDirectDispatch)
467
			{
A
Ashwin Agrawal 已提交
468 469 470 471
				/*
				 * implicit write on the root, but some initPlan was to all
				 * contents...so send explicit start
				 */
472 473 474 475 476 477 478 479 480 481
				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)
	{
A
Ashwin Agrawal 已提交
482 483
		bool		wasDirected = currentGxact->directTransaction;
		int			wasPromotedFromDirectDispatchContentId = wasDirected ? currentGxact->directTransactionContentId : -1;
484 485

		/* Can we still direct this transaction to a single content-id ? */
A
Ashwin Agrawal 已提交
486
		if (currentGxact->directTransaction)
487
		{
A
Ashwin Agrawal 已提交
488 489
			currentGxact->directTransaction = false;
			/* turn off, but may be restored below */
490 491 492

			if (nodeSaysDirectDispatch)
			{
A
Ashwin Agrawal 已提交
493 494 495
				int			contentId = linitial_int(stmt->planTree->directDispatch.contentIds);

				if (contentId == currentGxact->directTransactionContentId)
496
				{
A
Ashwin Agrawal 已提交
497 498 499 500
					/*
					 * it was the same content!  Stay in a single direct
					 * transaction
					 */
501 502 503 504 505
					currentGxact->directTransaction = true;
				}
			}
		}

A
Ashwin Agrawal 已提交
506
		if (currentGxact->directTransaction)
507 508 509 510 511
		{
			/** was not actually promoted */
			wasPromotedFromDirectDispatchContentId = -1;
		}

A
Ashwin Agrawal 已提交
512
		if (wasPromotedFromDirectDispatchContentId != -1)
513 514 515 516 517 518 519
			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"
A
Ashwin Agrawal 已提交
520
			);
521 522 523 524 525
	}

	/**
	 * If two-phase commit then begin transaction.
	 */
A
Ashwin Agrawal 已提交
526
	if (needsTwoPhaseCommit)
527 528 529 530 531 532 533
	{
		if (currentGxact == NULL)
		{
			elog(ERROR, "DTM transaction is not active (%s, detail = '%s')", debugCaller, debugDetail);
		}
		else if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
		{
A
Ashwin Agrawal 已提交
534
			setCurrentGxactState(DTX_STATE_ACTIVE_DISTRIBUTED);
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
		}
		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)
	 */
A
Ashwin Agrawal 已提交
553 554 555
	if (currentGxact &&
		currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED &&
		needsPromotionFromDirectDispatch)
556 557
	{
		CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
A
Ashwin Agrawal 已提交
558 559 560 561
		char	   *serializedDtxContextInfo;
		int			serializedDtxContextInfoLen;
		bool		badGangs,
					succeeded;
562 563

		serializedDtxContextInfo = qdSerializeDtxContextInfo(&serializedDtxContextInfoLen, wantSnapshot, inCursor,
A
Ashwin Agrawal 已提交
564
															 mppTxnOptions(true), "promoteTransactionIn_dtmPreCommand");
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

		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
A
Ashwin Agrawal 已提交
584
 * RollbackAndReleaseCurrentSubTransaction.
585 586 587 588 589
 */
bool
doDispatchSubtransactionInternalCmd(DtxProtocolCommand cmdType)
{
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
A
Ashwin Agrawal 已提交
590 591 592 593
	char	   *serializedDtxContextInfo = NULL;
	int			serializedDtxContextInfoLen = 0;
	bool		badGangs,
				succeeded = false;
594

G
Gang Xiong 已提交
595 596 597
	if (cmdType == DTX_PROTOCOL_COMMAND_SUBTRANSACTION_BEGIN_INTERNAL &&
		currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
		setCurrentGxactState(DTX_STATE_ACTIVE_DISTRIBUTED);
A
Ashwin Agrawal 已提交
598

599
	serializedDtxContextInfo = qdSerializeDtxContextInfo(
A
Ashwin Agrawal 已提交
600 601 602 603 604
														 &serializedDtxContextInfoLen,
														 false /* wantSnapshot */ ,
														 false /* inCursor */ ,
														 mppTxnOptions(true),
														 "doDispatchSubtransactionInternalCmd");
605 606

	succeeded = doDispatchDtxProtocolCommand(
A
Ashwin Agrawal 已提交
607 608 609 610
											 cmdType, /* flags */ 0,
											 currentGxact->gid, currentGxact->gxid,
											 &badGangs, /* raiseError */ true, &direct,
											 serializedDtxContextInfo, serializedDtxContextInfoLen);
611 612 613 614

	/* send a DTM command to others to tell them about the transaction */
	if (!succeeded)
	{
A
Ashwin Agrawal 已提交
615 616 617 618
		ereport(ERROR,
				(errmsg(
						"dispatching subtransaction internal command failed for gid = \"%s\" due to error",
						currentGxact->gid)));
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
	}

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

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

	return DTX_STATE_NONE;
}

static void
doPrepareTransaction(void)
{
A
Ashwin Agrawal 已提交
653 654
	bool		succeeded;
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
655 656 657 658

	CHECK_FOR_INTERRUPTS();

	elog(DTM_DEBUG5, "doPrepareTransaction entering in state = %s",
A
Ashwin Agrawal 已提交
659
		 DtxStateToString(currentGxact->state));
660

A
Ashwin Agrawal 已提交
661 662 663 664
	/*
	 * Don't allow a cancel while we're dispatching our prepare (we wrap our
	 * state change as well; for good measure.
	 */
665 666 667 668 669
	HOLD_INTERRUPTS();

	copyDirectDispatchFromTransaction(&direct);

	Assert(currentGxact->state == DTX_STATE_ACTIVE_DISTRIBUTED);
A
Ashwin Agrawal 已提交
670
	setCurrentGxactState(DTX_STATE_PREPARING);
671 672 673 674 675

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

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

A
Ashwin Agrawal 已提交
678 679 680 681
	/*
	 * Now we've cleaned up our dispatched statement, cancels are allowed
	 * again.
	 */
682 683 684 685 686 687 688 689 690 691 692 693 694
	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);

	Assert(currentGxact->state == DTX_STATE_PREPARING);
A
Ashwin Agrawal 已提交
695
	setCurrentGxactState(DTX_STATE_PREPARED);
696

697
	SIMPLE_FAULT_INJECTOR(DtmBroadcastPrepare);
698 699 700 701 702 703 704 705 706 707 708 709 710 711

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

/*
 * Insert FORGET COMMITTED into the xlog.
 */
static void
doInsertForgetCommitted(void)
{
	TMGXACT_LOG gxact_log;

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

A
Ashwin Agrawal 已提交
712
	setCurrentGxactState(DTX_STATE_INSERTING_FORGET_COMMITTED);
713 714 715

	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
716
			 (int) strlen(currentGxact->gid));
717 718 719 720 721
	memcpy(&gxact_log.gid, currentGxact->gid, TMGIDSIZE);
	gxact_log.gxid = currentGxact->gxid;

	RecordDistributedForgetCommitted(&gxact_log);

A
Ashwin Agrawal 已提交
722
	setCurrentGxactState(DTX_STATE_INSERTED_FORGET_COMMITTED);
G
Gang Xiong 已提交
723
}
724

G
Gang Xiong 已提交
725 726 727
static void
clearTransactionState(void)
{
728
	/*
A
Ashwin Agrawal 已提交
729 730 731 732
	 * 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.
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
	 *
	 *
	 * In upstream Postgres, proc->xid is cleared in ProcArrayEndTransaction.
	 * But there would have a small window in Greenplum that allows inconsistency
	 * between ProcArrayEndTransaction and notifying prepared commit to segments.
	 * In between, the master has new tuple visible while the segments are seeing
	 * old tuples.
	 *
	 * For example, session 1 runs:
	 *    RENAME from a_new to a;
	 * session 2 runs:
	 *    DROP TABLE a;
	 *
	 * When session 1 goes to just before notifyCommittedDtxTransaction, the new
	 * coming session 2 can see a new tuple for renamed table "a" in pg_class,
	 * and can drop it in master. However, dispatching DROP to segments, at this
	 * point of time segments still have old tuple for "a_new" visible in
	 * pg_class and DROP process just fails to drop "a". Then DTX is notified
	 * later and committed in the segments, the new tuple for "a" is visible
	 * now, but nobody wants to DROP it anymore, so the master has no tuple for
	 * "a" while the segments have it.
	 *
	 * To fix this, transactions require two-phase commit should defer clear 
	 * proc->xid here with ProcArryLock held.
757
	 */
G
Gang Xiong 已提交
758
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
759
	ClearTransactionFromPgProc_UnderLock(MyProc, true);
G
Gang Xiong 已提交
760
	ProcArrayEndGxact();
761
	LWLockRelease(ProcArrayLock);
762 763 764 765 766
}

static void
doNotifyingCommitPrepared(void)
{
A
Ashwin Agrawal 已提交
767 768 769
	bool		succeeded;
	bool		badGangs;
	int			retry = 0;
A
Ashwin Agrawal 已提交
770
	volatile int savedInterruptHoldoffCount;
771

A
Ashwin Agrawal 已提交
772
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
773 774 775 776 777

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

	copyDirectDispatchFromTransaction(&direct);

778
	Assert(currentGxact->state == DTX_STATE_INSERTED_COMMITTED);
A
Ashwin Agrawal 已提交
779
	setCurrentGxactState(DTX_STATE_NOTIFYING_COMMIT_PREPARED);
780 781 782

	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
783
			 (int) strlen(currentGxact->gid));
784

785
	SIMPLE_FAULT_INJECTOR(DtmBroadcastCommitPrepared);
A
Ashwin Agrawal 已提交
786
	savedInterruptHoldoffCount = InterruptHoldoffCount;
787

788 789 790 791 792 793 794 795 796
	PG_TRY();
	{
		succeeded = doDispatchDtxProtocolCommand(DTX_PROTOCOL_COMMAND_COMMIT_PREPARED, /* flags */ 0,
												 currentGxact->gid, currentGxact->gxid,
												 &badGangs, /* raiseError */ false,
												 &direct, NULL, 0);
	}
	PG_CATCH();
	{
A
Ashwin Agrawal 已提交
797 798 799 800
		/*
		 * restore the previous value, which is reset to 0 in errfinish.
		 */
		InterruptHoldoffCount = savedInterruptHoldoffCount;
801 802 803 804
		succeeded = false;
	}
	PG_END_TRY();

805 806
	if (!succeeded)
	{
807 808 809
		Assert(currentGxact->state == DTX_STATE_NOTIFYING_COMMIT_PREPARED);
		elog(DTM_DEBUG5, "marking retry needed for distributed transaction"
			 " 'Commit Prepared' broadcast to the segments for gid = %s.",
810
			 currentGxact->gid);
811 812 813 814 815 816 817 818 819
		setCurrentGxactState(DTX_STATE_RETRY_COMMIT_PREPARED);
		setDistributedTransactionContext(DTX_CONTEXT_QD_RETRY_PHASE_2);
	}

	while (!succeeded && dtx_phase2_retry_count > retry++)
	{
		elog(WARNING, "the distributed transaction 'Commit Prepared' broadcast "
			 "failed to one or more segments for gid = %s.  Retrying ... try %d",
			 currentGxact->gid, retry);
820 821

		/*
A
Ashwin Agrawal 已提交
822 823
		 * We must succeed in delivering the commit to all segment instances,
		 * or any failed segment instances must be marked INVALID.
824 825
		 */
		elog(NOTICE, "Releasing segworker group to retry broadcast.");
826
		DisconnectAndDestroyAllGangs(true);
827 828

		/*
A
Ashwin Agrawal 已提交
829 830
		 * This call will at a minimum change the session id so we will not
		 * have SharedSnapshotAdd colissions.
831 832
		 */
		CheckForResetSession();
A
Ashwin Agrawal 已提交
833
		savedInterruptHoldoffCount = InterruptHoldoffCount;
834

835 836 837
		PG_TRY();
		{
			succeeded = doDispatchDtxProtocolCommand(
A
Ashwin Agrawal 已提交
838 839 840 841
													 DTX_PROTOCOL_COMMAND_RETRY_COMMIT_PREPARED, /* flags */ 0,
													 currentGxact->gid, currentGxact->gxid,
													 &badGangs, /* raiseError */ false,
													 &direct, NULL, 0);
842 843 844
		}
		PG_CATCH();
		{
A
Ashwin Agrawal 已提交
845 846 847 848
			/*
			 * restore the previous value, which is reset to 0 in errfinish.
			 */
			InterruptHoldoffCount = savedInterruptHoldoffCount;
849 850 851
			succeeded = false;
		}
		PG_END_TRY();
852 853
	}

854 855
	if (!succeeded)
		elog(PANIC, "unable to complete 'Commit Prepared' broadcast for gid = %s",
A
Ashwin Agrawal 已提交
856
			 currentGxact->gid);
857 858 859
	elog(DTM_DEBUG5, "the distributed transaction 'Commit Prepared' broadcast "
		 "succeeded to all the segments for gid = %s.", currentGxact->gid);

860
	doInsertForgetCommitted();
G
Gang Xiong 已提交
861 862 863

	clearTransactionState();
	resetCurrentGxact();
864 865
}

866 867 868
static void
retryAbortPrepared(void)
{
A
Ashwin Agrawal 已提交
869 870 871
	int			retry = 0;
	bool		succeeded = false;
	bool		badGangs = false;
A
Ashwin Agrawal 已提交
872
	volatile int savedInterruptHoldoffCount;
873 874 875 876 877 878

	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;

	while (!succeeded && dtx_phase2_retry_count > retry++)
	{
		/*
A
Ashwin Agrawal 已提交
879 880 881
		 * 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.
882
		 */
883 884
		if (retry > 1)
			elog(NOTICE, "Releasing segworker groups to retry broadcast.");
885 886 887
		DisconnectAndDestroyAllGangs(true);

		/*
A
Ashwin Agrawal 已提交
888 889
		 * This call will at a minimum change the session id so we will not
		 * have SharedSnapshotAdd colissions.
890 891 892
		 */
		CheckForResetSession();

A
Ashwin Agrawal 已提交
893 894
		savedInterruptHoldoffCount = InterruptHoldoffCount;

895 896 897
		PG_TRY();
		{
			succeeded = doDispatchDtxProtocolCommand(
A
Ashwin Agrawal 已提交
898 899 900 901
													 DTX_PROTOCOL_COMMAND_RETRY_ABORT_PREPARED, /* flags */ 0,
													 currentGxact->gid, currentGxact->gxid,
													 &badGangs, /* raiseError */ false,
													 &direct, NULL, 0);
902 903 904 905 906 907 908
			if (!succeeded)
				elog(WARNING, "the distributed transaction 'Abort' broadcast "
					 "failed to one or more segments for gid = %s.  "
					 "Retrying ... try %d", currentGxact->gid, retry);
		}
		PG_CATCH();
		{
A
Ashwin Agrawal 已提交
909 910 911 912
			/*
			 * restore the previous value, which is reset to 0 in errfinish.
			 */
			InterruptHoldoffCount = savedInterruptHoldoffCount;
913 914 915 916 917 918 919 920 921 922 923 924 925
			succeeded = false;
		}
		PG_END_TRY();
	}

	if (!succeeded)
		elog(PANIC, "unable to complete 'Abort' broadcast for gid = %s",
			 currentGxact->gid);
	elog(DTM_DEBUG5, "The distributed transaction 'Abort' broadcast succeeded to "
		 "all the segments for gid = %s.", currentGxact->gid);
}


926 927 928
static void
doNotifyingAbort(void)
{
A
Ashwin Agrawal 已提交
929 930
	bool		succeeded;
	bool		badGangs;
A
Ashwin Agrawal 已提交
931
	volatile int savedInterruptHoldoffCount;
932

A
Ashwin Agrawal 已提交
933
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
934 935 936 937

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

	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
A
Ashwin Agrawal 已提交
938 939
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);
940 941 942 943 944

	copyDirectDispatchFromTransaction(&direct);

	if (currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED)
	{
945
		if (GangsExist())
946 947 948 949 950 951 952 953 954 955 956
		{
			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);

				/*
A
Ashwin Agrawal 已提交
957 958
				 * Reset the dispatch logic and disconnect from any segment
				 * that didn't respond to our abort.
959 960
				 */
				elog(NOTICE, "Releasing segworker groups to finish aborting the transaction.");
961
				DisconnectAndDestroyAllGangs(true);
962 963

				/*
A
Ashwin Agrawal 已提交
964 965
				 * This call will at a minimum change the session id so we
				 * will not have SharedSnapshotAdd colissions.
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
				 */
				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;
A
Ashwin Agrawal 已提交
986 987
		char	   *abortString;
		int			retry = 0;
988 989

		Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
A
Ashwin Agrawal 已提交
990
			   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);
991 992 993 994 995 996 997 998 999 1000 1001 1002

		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";
		}

A
Ashwin Agrawal 已提交
1003 1004
		savedInterruptHoldoffCount = InterruptHoldoffCount;

1005
		PG_TRY();
1006
		{
1007 1008 1009 1010 1011 1012 1013
			succeeded = doDispatchDtxProtocolCommand(dtxProtocolCommand, /* flags */ 0,
													 currentGxact->gid, currentGxact->gxid,
													 &badGangs, /* raiseError */ false,
													 &direct, NULL, 0);
		}
		PG_CATCH();
		{
A
Ashwin Agrawal 已提交
1014 1015 1016 1017
			/*
			 * restore the previous value, which is reset to 0 in errfinish.
			 */
			InterruptHoldoffCount = savedInterruptHoldoffCount;
1018 1019 1020
			succeeded = false;
		}
		PG_END_TRY();
1021

1022 1023 1024 1025 1026
		if (!succeeded)
		{
			elog(WARNING, "the distributed transaction '%s' broadcast failed"
				 " to one or more segments for gid = %s.  Retrying ... try %d",
				 abortString, currentGxact->gid, retry);
1027

A
Ashwin Agrawal 已提交
1028
			setCurrentGxactState(DTX_STATE_RETRY_ABORT_PREPARED);
1029
			setDistributedTransactionContext(DTX_CONTEXT_QD_RETRY_PHASE_2);
1030
		}
1031
		retryAbortPrepared();
1032 1033
	}

1034
	SIMPLE_FAULT_INJECTOR(DtmBroadcastAbortPrepared);
1035 1036

	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
A
Ashwin Agrawal 已提交
1037 1038
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED ||
1039
		   currentGxact->state == DTX_STATE_RETRY_ABORT_PREPARED);
G
Gang Xiong 已提交
1040
	elog(DTM_DEBUG5, "doNotifyingAbort called resetCurrentGxact");
1041 1042 1043 1044 1045
}

static bool
doNotifyCommittedInDoubt(char *gid)
{
A
Ashwin Agrawal 已提交
1046 1047
	bool		succeeded;
	bool		badGangs;
1048

A
Ashwin Agrawal 已提交
1049
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

	/* 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)
{
A
Ashwin Agrawal 已提交
1071 1072
	bool		succeeded;
	bool		badGangs;
1073

A
Ashwin Agrawal 已提交
1074
	CdbDispatchDirectDesc direct = default_dispatch_direct_desc;
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

	/* 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)
	{
A
Ashwin Agrawal 已提交
1100
		elog(DTM_DEBUG5, "prepareDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
			 DtxContextToString(DistributedTransactionContext));
		return;
	}

	if (currentGxact == NULL)
	{
		return;
	}

	if (currentGxact->state == DTX_STATE_ACTIVE_NOT_DISTRIBUTED)
	{
		/*
		 * This transaction did not go distributed.
		 */
G
Gang Xiong 已提交
1115
		clearAndResetGxact();
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
		elog(DTM_DEBUG5, "prepareDtxTransaction ignoring not distributed gid = %s", currentGxact->gid);
		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)
	{
A
Ashwin Agrawal 已提交
1141
		elog(DTM_DEBUG5, "rollbackDtxTransaction nothing to do (DistributedTransactionContext = '%s')",
1142 1143 1144 1145 1146
			 DtxContextToString(DistributedTransactionContext));
		return;
	}
	if (currentGxact == NULL)
	{
A
Ashwin Agrawal 已提交
1147
		elog(DTM_DEBUG5, "rollbackDtxTransaction nothing to do (currentGxact == NULL)");
1148 1149 1150 1151 1152 1153 1154 1155
		return;
	}

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

	switch (currentGxact->state)
	{
A
Ashwin Agrawal 已提交
1156
		case DTX_STATE_ACTIVE_NOT_DISTRIBUTED:
1157 1158

			/*
A
Ashwin Agrawal 已提交
1159
			 * Let go of these...
1160
			 */
G
Gang Xiong 已提交
1161
			clearAndResetGxact();
1162 1163
			return;

A
Ashwin Agrawal 已提交
1164 1165 1166
		case DTX_STATE_ACTIVE_DISTRIBUTED:
			setCurrentGxactState(DTX_STATE_NOTIFYING_ABORT_NO_PREPARED);
			break;
1167

A
Ashwin Agrawal 已提交
1168 1169 1170 1171
		case DTX_STATE_PREPARING:
			if (currentGxact->badPrepareGangs)
			{
				setCurrentGxactState(DTX_STATE_RETRY_ABORT_PREPARED);
1172

A
Ashwin Agrawal 已提交
1173 1174 1175 1176 1177
				/*
				 * DisconnectAndDestroyAllGangs and ResetSession happens
				 * inside retryAbortPrepared.
				 */
				retryAbortPrepared();
G
Gang Xiong 已提交
1178
				clearAndResetGxact();
A
Ashwin Agrawal 已提交
1179 1180 1181 1182
				return;
			}
			setCurrentGxactState(DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED);
			break;
1183

A
Ashwin Agrawal 已提交
1184 1185 1186
		case DTX_STATE_PREPARED:
			setCurrentGxactState(DTX_STATE_NOTIFYING_ABORT_PREPARED);
			break;
1187

A
Ashwin Agrawal 已提交
1188
		case DTX_STATE_NOTIFYING_ABORT_NO_PREPARED:
1189

A
Ashwin Agrawal 已提交
1190 1191 1192 1193 1194 1195 1196
			/*
			 * 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.");
			DisconnectAndDestroyAllGangs(true);
1197

A
Ashwin Agrawal 已提交
1198 1199 1200 1201 1202 1203
			/*
			 * This call will at a minimum change the session id so we will
			 * not have SharedSnapshotAdd colissions.
			 */
			CheckForResetSession();

G
Gang Xiong 已提交
1204
			clearAndResetGxact();
A
Ashwin Agrawal 已提交
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
			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_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:
			elog(DTM_DEBUG5, "rollbackDtxTransaction dtx state \"%s\" not expected here",
				 DtxStateToString(currentGxact->state));
G
Gang Xiong 已提交
1222
			clearAndResetGxact();
A
Ashwin Agrawal 已提交
1223 1224 1225 1226 1227 1228
			return;

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


	Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED ||
A
Ashwin Agrawal 已提交
1233 1234
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
		   currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED);
1235 1236 1237 1238 1239

	/*
	 * 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.
	 *
A
Ashwin Agrawal 已提交
1240
	 * We can't dispatch -- but we *do* need to free up shared-memory entries.
1241 1242 1243 1244 1245 1246 1247 1248
	 */
	if (proc_exit_inprogress)
	{
		/*
		 * Unable to complete distributed abort broadcast with possible
		 * prepared transactions...
		 */
		if (currentGxact->state == DTX_STATE_NOTIFYING_ABORT_SOME_PREPARED ||
A
Ashwin Agrawal 已提交
1249
			currentGxact->state == DTX_STATE_NOTIFYING_ABORT_PREPARED)
1250 1251 1252 1253 1254 1255
		{
			elog(FATAL, "Unable to complete the 'Abort Prepared' broadcast for gid '%s'",
				 currentGxact->gid);
		}

		Assert(currentGxact->state == DTX_STATE_NOTIFYING_ABORT_NO_PREPARED);
A
Ashwin Agrawal 已提交
1256

1257
		/*
A
Ashwin Agrawal 已提交
1258 1259 1260
		 * 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.
1261
		 */
1262
		DisconnectAndDestroyAllGangs(true);
1263 1264

		/*
A
Ashwin Agrawal 已提交
1265 1266
		 * This call will at a minimum change the session id so we will not
		 * have SharedSnapshotAdd colissions.
1267 1268 1269
		 */
		CheckForResetSession();

G
Gang Xiong 已提交
1270
		clearAndResetGxact();
1271 1272 1273 1274
		return;
	}

	doNotifyingAbort();
G
Gang Xiong 已提交
1275
	clearAndResetGxact();
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292

	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)
	{
G
Gang Xiong 已提交
1293
		LWLockAcquire(shmControlLock, LW_EXCLUSIVE);
1294 1295 1296 1297 1298

		/* Still need to recover? */
		if (!*shmTmRecoverred)
		{
			volatile int savedInterruptHoldoffCount = InterruptHoldoffCount;
A
Ashwin Agrawal 已提交
1299

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
			/*
			 * 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;
			}
			PG_CATCH();
			{
				/*
				 * We can't simply use HOLD_INTERRUPTS as in LWLockRelease,
				 * because at this point we don't know if other LWLocks have
A
Ashwin Agrawal 已提交
1314 1315 1316 1317
				 * 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.
1318 1319
				 */
				InterruptHoldoffCount = savedInterruptHoldoffCount;
G
Gang Xiong 已提交
1320
				LWLockRelease(shmControlLock);
1321 1322 1323 1324 1325 1326 1327

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

G
Gang Xiong 已提交
1328
		LWLockRelease(shmControlLock);
1329 1330 1331 1332 1333 1334
	}
}

static char *
getSuperuser(Oid *userOid)
{
A
Ashwin Agrawal 已提交
1335 1336 1337
	char	   *suser = NULL;
	Relation	auth_rel;
	HeapTuple	auth_tup;
1338 1339
	HeapScanDesc auth_scan;
	ScanKeyData key[2];
A
Ashwin Agrawal 已提交
1340
	bool		isNull;
1341 1342

	ScanKeyInit(&key[0],
A
Ashwin Agrawal 已提交
1343 1344 1345
				Anum_pg_authid_rolsuper,
				BTEqualStrategyNumber, F_BOOLEQ,
				BoolGetDatum(true));
1346 1347

	ScanKeyInit(&key[1],
A
Ashwin Agrawal 已提交
1348 1349 1350
				Anum_pg_authid_rolcanlogin,
				BTEqualStrategyNumber, F_BOOLEQ,
				BoolGetDatum(true));
1351 1352 1353 1354 1355

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

	while (HeapTupleIsValid(auth_tup = heap_getnext(auth_scan,
A
Ashwin Agrawal 已提交
1356
													ForwardScanDirection)))
1357
	{
A
Ashwin Agrawal 已提交
1358 1359
		Datum		attrName;
		Datum		attrNameOid;
1360 1361 1362 1363 1364 1365 1366 1367

		(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,
A
Ashwin Agrawal 已提交
1368
								auth_rel->rd_att, &isNull);
1369 1370 1371 1372 1373 1374

		Assert(!isNull);

		suser = pstrdup(DatumGetCString(attrName));

		attrNameOid = heap_getattr(auth_tup, ObjectIdAttributeNumber,
A
Ashwin Agrawal 已提交
1375
								   auth_rel->rd_att, &isNull);
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
		Assert(!isNull);
		*userOid = DatumGetObjectId(attrNameOid);

		break;
	}

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

	return suser;
}

static char *
ChangeToSuperuser()
{
A
Ashwin Agrawal 已提交
1391 1392 1393
	char	   *olduser = NULL;
	char	   *newuser;
	Oid			userOid = InvalidOid;
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
	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)
{
A
Ashwin Agrawal 已提交
1440 1441 1442 1443
	char	   *olduser = NULL;
	MemoryContext oldcontext;
	bool		succeeded,
				first;
1444 1445 1446 1447 1448 1449 1450

	Assert(shmTmRecoverred != NULL);

	/* Need to recover ? */
	if (!*shmTmRecoverred)
	{
		/*
A
Ashwin Agrawal 已提交
1451 1452 1453 1454
		 * 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.
1455 1456
		 */
		olduser = ChangeToSuperuser();
1457 1458

		SIMPLE_FAULT_INJECTOR(DtmInit);
1459 1460 1461 1462 1463 1464 1465 1466

		oldcontext = CurrentMemoryContext;
		succeeded = false;
		first = true;
		while (true)
		{
			/*
			 * MPP-9894: during startup, we don't have a top-level
A
Ashwin Agrawal 已提交
1467 1468
			 * PG_TRY/PG_CATCH block yet, the dispatcher may throw errors: we
			 * need to catch them.
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
			 */
			PG_TRY();
			{
				initTM_recover_as_needed();
				succeeded = true;
			}
			PG_CATCH();
			{
				MemoryContextSwitchTo(oldcontext);

				elog(LOG, "DTM initialization, caught exception: "
A
Ashwin Agrawal 已提交
1480
					 "looking for failed segments.");
1481 1482

				/* Log the error. */
1483
				elog_demote(LOG);
1484
				EmitErrorReport();
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
				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 "
A
Ashwin Agrawal 已提交
1505
						 "recovery, retry failed, check segment status");
1506 1507 1508
				}
			}

1509
			Assert(!LWLockHeldByMe(shmControlLock));
A
Ashwin Agrawal 已提交
1510

1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
			/*
			 * We are done with the recovery.
			 */
			break;
		}

		RestoreToUser(olduser);

		freeGangsForPortal(NULL);
	}
}

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

	return
G
Gang Xiong 已提交
1531
		MAXALIGN(TMCONTROLBLOCK_BYTES(max_tm_gxacts));
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
}


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

	/*
A
Ashwin Agrawal 已提交
1546 1547 1548 1549
	 * 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.
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
	 */
	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;
G
Gang Xiong 已提交
1561
	shmControlSeqnoLock = &shared->ControlSeqnoLock;
1562 1563 1564 1565 1566 1567 1568
	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);
A
Ashwin Agrawal 已提交
1569

1570 1571 1572 1573 1574
		if (t == (time_t) -1)
		{
			elog(PANIC, "cannot generate global transaction id");
		}

A
Ashwin Agrawal 已提交
1575 1576
		*shmDistribTimeStamp = (DistributedTransactionTimeStamp) t;
		elog(DEBUG1, "DTM start timestamp %u", *shmDistribTimeStamp);
1577 1578 1579 1580 1581

		*shmGIDSeq = FirstDistributedTransactionId;
	}
	shmDtmStarted = &shared->DtmStarted;
	shmNextSnapshotId = &shared->NextSnapshotId;
G
Gang Xiong 已提交
1582 1583
	shmNumCommittedGxacts = &shared->num_committed_xacts;
	shmCommittedGxactArray = &shared->committed_gxact_array[0];
1584 1585 1586 1587 1588 1589 1590

	if (!IsUnderPostmaster)
		/* Initialize locks and shared memory area */
	{
		shared->ControlLock = LWLockAssign();
		shmControlLock = shared->ControlLock;

G
Gang Xiong 已提交
1591 1592 1593 1594 1595
		SpinLockInit(shmControlSeqnoLock);
		*shmNextSnapshotId = 0;
		*shmDtmStarted = false;
		*shmTmRecoverred = false;
		*shmNumCommittedGxacts = 0;
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
	}
}

/* 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)
{
A
Ashwin Agrawal 已提交
1607
	int			options = 0;
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622

	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;
1623 1624
	else if (XactIsoLevel == XACT_READ_UNCOMMITTED)
		options |= GP_OPT_READ_UNCOMMITTED;
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644

	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)
{
1645
	if ((txnOptions & GP_OPT_ISOLATION_LEVEL_MASK) == GP_OPT_SERIALIZABLE)
1646
		return XACT_SERIALIZABLE;
1647
	else if ((txnOptions & GP_OPT_ISOLATION_LEVEL_MASK) == GP_OPT_REPEATABLE_READ)
1648
		return XACT_REPEATABLE_READ;
1649
	else if ((txnOptions & GP_OPT_ISOLATION_LEVEL_MASK) == GP_OPT_READ_COMMITTED)
1650
		return XACT_READ_COMMITTED;
1651
	else if ((txnOptions & GP_OPT_ISOLATION_LEVEL_MASK) == GP_OPT_READ_UNCOMMITTED)
1652
		return XACT_READ_UNCOMMITTED;
1653 1654
	/* QD must set transaction isolation level */
	elog(ERROR, "transaction options from QD did not include isolation level");
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
}

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

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

/*
 * Redo transaction commit log record.
 */
void
redoDtxCheckPoint(TMGXACT_CHECKPOINT *gxact_checkpoint)
{
A
Ashwin Agrawal 已提交
1684
	int			committedCount;
1685

A
Ashwin Agrawal 已提交
1686
	int			i;
1687 1688

	/*
A
Ashwin Agrawal 已提交
1689 1690
	 * For checkpoint same as REDO, lets add entries to file in utility and
	 * in-memory if Dispatch.
1691 1692 1693
	 */

	committedCount = gxact_checkpoint->committedCount;
1694
	elog(DTM_DEBUG5, "redoDtxCheckPoint has committedCount = %d", committedCount);
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

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

static void
GetRedoFileName(char *path)
{
	snprintf(path, MAXPGPATH,
A
Ashwin Agrawal 已提交
1706 1707
			 "%s/" UTILITYMODEDTMREDO_DIR "/" UTILITYMODEDTMREDO_FILE, DataDir);
	elog(DTM_DEBUG3, "Returning save DTM redo file path = %s", path);
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
}

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
A
Ashwin Agrawal 已提交
1741
UtilityModeSaveRedo(bool committed, TMGXACT_LOG *gxact_log)
1742 1743
{
	TMGXACT_UTILITY_MODE_REDO utilityModeRedo;
A
Ashwin Agrawal 已提交
1744
	int			write_len;
1745 1746 1747 1748 1749

	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",
A
Ashwin Agrawal 已提交
1750 1751 1752
		 (utilityModeRedo.committed ? "true" : "false"),
		 utilityModeRedo.gxact_log.gid,
		 utilityModeRedo.gxact_log.gxid);
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

	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;
A
Ashwin Agrawal 已提交
1784
	int			errno;
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
	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",
A
Ashwin Agrawal 已提交
1797
			 path);
1798 1799 1800 1801 1802 1803
		return;
	}

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

A
Ashwin Agrawal 已提交
1804
	while (true)
1805 1806 1807 1808 1809 1810 1811 1812
	{
		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)",
A
Ashwin Agrawal 已提交
1813
				 (int) sizeof(TMGXACT_UTILITY_MODE_REDO), read_len);
1814 1815 1816 1817 1818 1819 1820 1821 1822
		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",
A
Ashwin Agrawal 已提交
1823 1824 1825
			 (utilityModeRedo.committed ? "true" : "false"),
			 utilityModeRedo.gxact_log.gid,
			 utilityModeRedo.gxact_log.gxid);
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
		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];
A
Ashwin Agrawal 已提交
1848
	bool		removed;
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859

	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
A
Ashwin Agrawal 已提交
1860
redoDistributedCommitRecord(TMGXACT_LOG *gxact_log)
1861 1862 1863 1864 1865
{

	int			i;

	/*
A
Ashwin Agrawal 已提交
1866 1867
	 * The length check here requires the identifer have a trailing NUL
	 * character.
1868 1869 1870
	 */
	if (strlen(gxact_log->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
A
Ashwin Agrawal 已提交
1871
			 (int) strlen(gxact_log->gid));
1872 1873 1874 1875 1876 1877 1878 1879

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

G
Gang Xiong 已提交
1880
	for (i = 0; i < *shmNumCommittedGxacts; i++)
1881
	{
G
Gang Xiong 已提交
1882 1883
		if (strcmp(gxact_log->gid, shmCommittedGxactArray[i].gid) == 0)
			return;
1884
	}
G
Gang Xiong 已提交
1885 1886

	if (i == *shmNumCommittedGxacts)
1887 1888 1889 1890
	{
		/*
		 * Transaction not found, this is the first log of this transaction.
		 */
G
Gang Xiong 已提交
1891
		if (*shmNumCommittedGxacts >= max_tm_gxacts)
1892 1893 1894 1895 1896 1897 1898
		{
			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.")));
		}

G
Gang Xiong 已提交
1899 1900 1901
		shmCommittedGxactArray[(*shmNumCommittedGxacts)++] = *gxact_log;
		elog((Debug_print_full_dtm ? LOG : DEBUG5),
				"Crash recovery redo added committed distributed transaction gid = %s", gxact_log->gid);
1902 1903 1904 1905 1906 1907 1908
	}
}

/*
 * Redo transaction forget commit log record.
 */
void
A
Ashwin Agrawal 已提交
1909
redoDistributedForgetCommitRecord(TMGXACT_LOG *gxact_log)
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
{
	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;
	}

G
Gang Xiong 已提交
1920
	for (i = 0; i < *shmNumCommittedGxacts; i++)
1921
	{
G
Gang Xiong 已提交
1922
		if (strcmp(gxact_log->gid, shmCommittedGxactArray[i].gid) == 0)
1923 1924 1925 1926
		{
			/* found an active global transaction */
			elog((Debug_print_full_dtm ? INFO : DEBUG5),
				 "Crash recovery redo removed committed distributed transaction gid = %s for forget",
G
Gang Xiong 已提交
1927 1928 1929 1930 1931 1932 1933
				 gxact_log->gid);

			/* there's no concurrent access to shmCommittedGxactArray during recovery */
			(*shmNumCommittedGxacts)--;
			if (i != *shmNumCommittedGxacts)
				shmCommittedGxactArray[i] = shmCommittedGxactArray[*shmNumCommittedGxacts];

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
			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
A
Ashwin Agrawal 已提交
1945
descGxactLog(StringInfo buf, TMGXACT_LOG *gxact_log)
1946 1947 1948 1949 1950 1951 1952 1953 1954
{
	appendStringInfo(buf, " gid = %s, gxid = %u",
					 gxact_log->gid, gxact_log->gxid);
}

/*
 * Describe redo transaction commit log record.
 */
void
A
Ashwin Agrawal 已提交
1955
descDistributedCommitRecord(StringInfo buf, TMGXACT_LOG *gxact_log)
1956 1957 1958 1959 1960 1961 1962 1963
{
	descGxactLog(buf, gxact_log);
}

/*
 * Describe redo transaction forget commit log record.
 */
void
A
Ashwin Agrawal 已提交
1964
descDistributedForgetCommitRecord(StringInfo buf, TMGXACT_LOG *gxact_log)
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
{
	descGxactLog(buf, gxact_log);
}


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

static bool
doDispatchDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand, int flags,
A
Ashwin Agrawal 已提交
1976
							 char *gid, DistributedTransactionId gxid,
1977 1978
							 bool *badGangs, bool raiseError,
							 CdbDispatchDirectDesc *direct,
1979 1980
							 char *serializedDtxContextInfo,
							 int serializedDtxContextInfoLen)
1981
{
A
Ashwin Agrawal 已提交
1982 1983 1984
	int			i,
				resultCount,
				numOfFailed = 0;
1985

A
Ashwin Agrawal 已提交
1986
	char	   *dtxProtocolCommandStr = 0;
1987

1988
	struct pg_result **results = NULL;
1989 1990 1991

	dtxProtocolCommandStr = DtxProtocolCommandToString(dtxProtocolCommand);

A
Ashwin Agrawal 已提交
1992
	if (Test_print_direct_dispatch_info)
1993
	{
A
Ashwin Agrawal 已提交
1994
		if (direct->directed_dispatch)
1995
			elog(INFO, "Distributed transaction command '%s' to SINGLE content", dtxProtocolCommandStr);
A
Ashwin Agrawal 已提交
1996 1997
		else
			elog(INFO, "Distributed transaction command '%s' to ALL contents", dtxProtocolCommandStr);
1998 1999 2000 2001
	}
	elog(DTM_DEBUG5,
		 "dispatchDtxProtocolCommand: %d ('%s'), direct content #: %d",
		 dtxProtocolCommand, dtxProtocolCommandStr,
A
Ashwin Agrawal 已提交
2002
		 direct->directed_dispatch ? direct->content[0] : -1);
2003

2004
	ErrorData *qeError;
2005
	results = CdbDispatchDtxProtocolCommand(dtxProtocolCommand, flags,
A
Ashwin Agrawal 已提交
2006 2007
											dtxProtocolCommandStr,
											gid, gxid,
2008
											&qeError, &resultCount, badGangs, direct,
A
Ashwin Agrawal 已提交
2009
											serializedDtxContextInfo, serializedDtxContextInfoLen);
2010

2011
	if (qeError)
2012
	{
2013 2014 2015 2016 2017 2018 2019 2020
		if (!raiseError)
		{
			ereport(LOG,
					(errmsg("DTM error (gathered results from cmd '%s')", dtxProtocolCommandStr),
					 errdetail("QE reported error: %s", qeError->message)));
		}
		else
			ReThrowError(qeError);
2021 2022 2023 2024 2025
		return false;
	}

	if (results == NULL)
	{
A
Ashwin Agrawal 已提交
2026 2027
		numOfFailed++;			/* If we got no results, we need to treat it
								 * as an error! */
2028
	}
2029

2030 2031
	for (i = 0; i < resultCount; i++)
	{
A
Ashwin Agrawal 已提交
2032 2033
		char	   *cmdStatus;
		ExecStatusType resultStatus;
2034

A
Ashwin Agrawal 已提交
2035 2036 2037 2038
		/*
		 * note: PQresultStatus() is smart enough to deal with results[i] ==
		 * NULL
		 */
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
		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++;
			}
		}
	}

2065 2066
	for (i = 0; i < resultCount; i++)
		PQclear(results[i]);
2067 2068 2069

	if (results)
		free(results);
2070 2071 2072 2073 2074 2075

	return (numOfFailed == 0);
}


bool
2076
dispatchDtxCommand(const char *cmd)
2077
{
A
Ashwin Agrawal 已提交
2078 2079
	int			i,
				numOfFailed = 0;
2080

2081
	CdbPgResults cdb_pgresults = {NULL, 0};
2082 2083 2084

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

2085
	CdbDispatchCommand(cmd, DF_NONE, &cdb_pgresults);
2086

2087
	if (cdb_pgresults.numResults == 0)
2088
	{
A
Ashwin Agrawal 已提交
2089 2090
		return false;			/* If we got no results, we need to treat it
								 * as an error! */
2091 2092
	}

2093
	for (i = 0; i < cdb_pgresults.numResults; i++)
2094
	{
A
Ashwin Agrawal 已提交
2095 2096
		char	   *cmdStatus;
		ExecStatusType resultStatus;
2097

A
Ashwin Agrawal 已提交
2098 2099 2100 2101
		/*
		 * note: PQresultStatus() is smart enough to deal with results[i] ==
		 * NULL
		 */
2102
		resultStatus = PQresultStatus(cdb_pgresults.pg_results[i]);
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
		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!
			 */
2117
			cmdStatus = PQcmdStatus(cdb_pgresults.pg_results[i]);
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127

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

2128
	cdbdisp_clearCdbPgResults(&cdb_pgresults);
2129 2130 2131 2132 2133

	return (numOfFailed == 0);
}

/* initialize a global transaction context */
G
Gang Xiong 已提交
2134
void
A
Ashwin Agrawal 已提交
2135
initGxact(TMGXACT *gxact)
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
{
	MemSet(gxact->gid, 0, TMGIDSIZE);
	gxact->gxid = InvalidDistributedTransactionId;
	setGxactState(gxact, DTX_STATE_NONE);

	/*
	 * Memory only fields.
	 */

	gxact->sessionId = gp_session_id;

	gxact->explicitBeginRemembered = false;

2149
	gxact->xminDistributedSnapshot = InvalidDistributedTransactionId;
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171

	gxact->badPrepareGangs = false;

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

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

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

	return true;
}

void
G
Gang Xiong 已提交
2172
setCurrentGxact(void)
2173
{
G
Gang Xiong 已提交
2174 2175
	DistributedTransactionId gxid = generateGID();
	Assert(gxid != InvalidDistributedTransactionId);
2176

G
Gang Xiong 已提交
2177
	currentGxact = &MyProc->gxact;
2178

G
Gang Xiong 已提交
2179 2180 2181 2182 2183
	Assert(*shmDistribTimeStamp != 0);
	sprintf(currentGxact->gid, "%u-%.10u", *shmDistribTimeStamp, gxid);
	if (strlen(currentGxact->gid) >= TMGIDSIZE)
		elog(PANIC, "Distribute transaction identifier too long (%d)",
				(int) strlen(currentGxact->gid));
2184 2185

	/*
A
Ashwin Agrawal 已提交
2186 2187
	 * Until we get our first distributed snapshot, we use our distributed
	 * transaction identifier for the minimum.
2188
	 */
G
Gang Xiong 已提交
2189
	currentGxact->xminDistributedSnapshot = gxid;
2190

G
Gang Xiong 已提交
2191
	setCurrentGxactState(DTX_STATE_ACTIVE_NOT_DISTRIBUTED);
2192

G
Gang Xiong 已提交
2193
	currentGxact->gxid = gxid;
2194 2195 2196
}

static void
G
Gang Xiong 已提交
2197
resetCurrentGxact(void)
2198
{
G
Gang Xiong 已提交
2199 2200
	Assert (currentGxact != NULL);
	Assert (currentGxact->gxid == InvalidDistributedTransactionId);
2201 2202 2203 2204
	currentGxact = NULL;
}

static void
G
Gang Xiong 已提交
2205
clearAndResetGxact(void)
2206
{
G
Gang Xiong 已提交
2207
	Assert(currentGxact != NULL);
2208

G
Gang Xiong 已提交
2209 2210 2211
	LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
	ProcArrayEndGxact();
	LWLockRelease(ProcArrayLock);
2212

G
Gang Xiong 已提交
2213
	resetCurrentGxact();
2214 2215 2216
}

/*
G
Gang Xiong 已提交
2217
 * serializes commits with checkpoint info using PGPROC->inCommit
2218 2219 2220 2221 2222 2223 2224
 * Change state to DTX_STATE_INSERTING_COMMITTED.
 */
void
insertingDistributedCommitted(void)
{
	elog(DTM_DEBUG5,
		 "insertingDistributedCommitted entering in state = %s",
A
Ashwin Agrawal 已提交
2225
		 DtxStateToString(currentGxact->state));
2226 2227

	Assert(currentGxact->state == DTX_STATE_PREPARED);
A
Ashwin Agrawal 已提交
2228
	setCurrentGxactState(DTX_STATE_INSERTING_COMMITTED);
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
}

/*
 * Change state to DTX_STATE_INSERTED_COMMITTED.
 */
void
insertedDistributedCommitted(void)
{
	elog(DTM_DEBUG5,
		 "insertedDistributedCommitted entering in state = %s for gid = %s",
A
Ashwin Agrawal 已提交
2239
		 DtxStateToString(currentGxact->state), currentGxact->gid);
2240 2241

	Assert(currentGxact->state == DTX_STATE_INSERTING_COMMITTED);
A
Ashwin Agrawal 已提交
2242
	setCurrentGxactState(DTX_STATE_INSERTED_COMMITTED);
2243 2244
}

G
Gang Xiong 已提交
2245 2246 2247
/* generate global transaction id */
static DistributedTransactionId
generateGID(void)
2248
{
G
Gang Xiong 已提交
2249
	DistributedTransactionId gxid;
2250

G
Gang Xiong 已提交
2251
	SpinLockAcquire(shmControlSeqnoLock);
2252 2253 2254 2255

	/* tm lock acquired by caller */
	if (*shmGIDSeq >= LastDistributedTransactionId)
	{
G
Gang Xiong 已提交
2256
		SpinLockRelease(shmControlSeqnoLock);
2257
		ereport(FATAL,
A
Ashwin Agrawal 已提交
2258
				(errmsg("reached limit of %u global transactions per start", LastDistributedTransactionId)));
2259
	}
G
Gang Xiong 已提交
2260
	gxid = ++(*shmGIDSeq);
2261

G
Gang Xiong 已提交
2262 2263
	SpinLockRelease(shmControlSeqnoLock);
	return gxid;
2264 2265
}

2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
/*
 * Return the highest global transaction id that has been generated.
 */
DistributedTransactionId
getMaxDistributedXid(void)
{
	if (!shmGIDSeq)
		return 0;

	return *shmGIDSeq;
}

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
/*
 * 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)
{
	elog(DTM_DEBUG3, "Starting to Recover DTM...");

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

2305 2306 2307 2308 2309 2310 2311 2312
	/*
	 * 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();
2313 2314 2315

	/* finished recovery successfully. */

2316
	*shmGIDSeq = 1;
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328

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

/* recoverInDoubtTransactions:
 * Go through all in-doubt transactions that the DTM knows about and
 * resolve them.
 */
static bool
recoverInDoubtTransactions(void)
{
A
Ashwin Agrawal 已提交
2329 2330
	int			i;
	HTAB	   *htab;
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342

	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)",
G
Gang Xiong 已提交
2343
		 *shmNumCommittedGxacts);
2344

G
Gang Xiong 已提交
2345
	for (i = 0; i < *shmNumCommittedGxacts; i++)
2346
	{
G
Gang Xiong 已提交
2347
		TMGXACT_LOG    *gxact_log = &shmCommittedGxactArray[i];
2348

G
Gang Xiong 已提交
2349
		Assert(gxact_log->gxid != InvalidDistributedTransactionId);
2350 2351 2352

		elog(DTM_DEBUG5,
			 "Recovering committed distributed transaction gid = %s",
G
Gang Xiong 已提交
2353
			 gxact_log->gid);
2354

G
Gang Xiong 已提交
2355
		doNotifyCommittedInDoubt(gxact_log->gid);
2356

G
Gang Xiong 已提交
2357
		RecordDistributedForgetCommitted(gxact_log);
2358 2359
	}

G
Gang Xiong 已提交
2360
	*shmNumCommittedGxacts = 0;
2361
	/*
A
Ashwin Agrawal 已提交
2362 2363
	 * UNDONE: Thus, any in-doubt transctions found will be for aborted
	 * transactions. UNDONE: Gather in-boubt transactions and issue aborts.
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 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
	 */
	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);

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

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

/*
 * 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)
{
2427
	CdbPgResults cdb_pgresults = {NULL, 0};
2428
	const char *cmdbuf = "select gid from pg_prepared_xacts";
2429
	PGresult   *rs;
2430 2431 2432 2433 2434

	InDoubtDtx *lastDtx = NULL;

	HASHCTL		hctl;
	HTAB	   *htab = NULL;
2435
	int			i;
2436 2437 2438 2439 2440
	int			j,
				rows;
	bool		found;

	/* call to all QE to get in-doubt transactions */
2441
	CdbDispatchCommand(cmdbuf, DF_NONE, &cdb_pgresults);
2442 2443

	/* If any result set is nonempty, there are in-doubt transactions. */
2444
	for (i = 0; i < cdb_pgresults.numResults; i++)
2445
	{
A
Ashwin Agrawal 已提交
2446
		rs = cdb_pgresults.pg_results[i];
2447
		rows = PQntuples(rs);
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460

		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 */
A
Ashwin Agrawal 已提交
2461
				hctl.keysize = TMGIDSIZE;	/* GID */
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
				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.")));
				}
			}

2473
			gid = PQgetvalue(rs, j, 0);
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491

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

		}
	}

2492
	cdbdisp_clearCdbPgResults(&cdb_pgresults);
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

	return htab;
}

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

	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)
	{
		elog(DTM_DEBUG3, "Aborting in-doubt transaction with gid = %s", entry->gid);

		doAbortInDoubt(entry->gid);

	}
}

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.
 */
A
Ashwin Agrawal 已提交
2568 2569
void
verify_shared_snapshot_ready(void)
2570 2571 2572
{
	if (Gp_role == GP_ROLE_DISPATCH)
	{
2573
		CdbDispatchCommand("set gp_write_shared_snapshot=true",
A
Ashwin Agrawal 已提交
2574 2575 2576 2577
						   DF_CANCEL_ON_ERROR |
						   DF_WITH_SNAPSHOT |
						   DF_NEED_TWO_PHASE,
						   NULL);
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596

		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
A
Ashwin Agrawal 已提交
2597
assign_gp_write_shared_snapshot(bool newval, bool doit, GucSource source __attribute__((unused)))
2598 2599 2600 2601 2602 2603
{

#if FALSE
	elog(DEBUG1, "SET gp_write_shared_snapshot: %s, doit=%s",
		 (newval ? "true" : "false"), (doit ? "true" : "false"));
#endif
A
Ashwin Agrawal 已提交
2604

2605
	/*
A
Ashwin Agrawal 已提交
2606 2607
	 * 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.
2608 2609 2610 2611 2612
	 */
	if (doit && newval)
	{
		if (Gp_role == GP_ROLE_EXECUTE)
		{
2613
			PushActiveSnapshot(GetTransactionSnapshot());
2614 2615 2616 2617 2618

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

			PopActiveSnapshot();
2621 2622 2623 2624 2625 2626 2627
		}
	}

	return true;
}

static void
2628
doQEDistributedExplicitBegin()
2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
{
	/*
	 * Start a command.
	 */
	StartTransactionCommand();

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

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

static bool
isDtxQueryDispatcher(void)
{
A
Ashwin Agrawal 已提交
2648 2649
	bool		isDtmStarted;
	bool		isSharedLocalSnapshotSlotPresent;
2650 2651 2652 2653

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

A
Ashwin Agrawal 已提交
2654 2655 2656
	return (Gp_role == GP_ROLE_DISPATCH &&
			isDtmStarted &&
			isSharedLocalSnapshotSlotPresent);
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
}

/*
 * 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)
{
A
Ashwin Agrawal 已提交
2673
	switch (DistributedTransactionContext)
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
	{
		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)
			{
A
Ashwin Agrawal 已提交
2686 2687 2688 2689 2690 2691 2692 2693 2694
				/*
				 * 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
				 */
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

				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
A
Ashwin Agrawal 已提交
2726
setupQEDtxContext(DtxContextInfo *dtxContextInfo)
2727 2728
{
	DistributedSnapshot *distributedSnapshot;
A
Ashwin Agrawal 已提交
2729 2730 2731 2732 2733 2734 2735 2736
	int			txnOptions;
	bool		needTwoPhase;
	bool		explicitBegin;
	bool		haveDistributedSnapshot;
	bool		isEntryDbSingleton = false;
	bool		isReaderQE = false;
	bool		isWriterQE = false;
	bool		isSharedLocalSnapshotSlotPresent;
2737

A
Ashwin Agrawal 已提交
2738
	Assert(dtxContextInfo != NULL);
2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749

	/*
	 * 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 =
A
Ashwin Agrawal 已提交
2750
		(dtxContextInfo->distributedXid != InvalidDistributedTransactionId);
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
	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"));
A
Ashwin Agrawal 已提交
2762
		elog(DTM_DEBUG5,
2763 2764
			 "setupQEDtxContext inputs (part 2): distributedXid = %u, isSharedLocalSnapshotSlotPresent = %s.",
			 dtxContextInfo->distributedXid,
A
Ashwin Agrawal 已提交
2765
			 (isSharedLocalSnapshotSlotPresent ? "true" : "false"));
2766 2767 2768 2769 2770 2771 2772

		if (haveDistributedSnapshot)
		{
			elog(DTM_DEBUG5,
				 "setupQEDtxContext inputs (part 2a): distributedXid = %u, "
				 "distributedSnapshotData (xmin = %u, xmax = %u, xcnt = %u), distributedCommandId = %d",
				 dtxContextInfo->distributedXid,
2773 2774
				 distributedSnapshot->xmin, distributedSnapshot->xmax,
				 distributedSnapshot->count,
2775 2776 2777 2778
				 dtxContextInfo->curcid);
		}
		if (isSharedLocalSnapshotSlotPresent)
		{
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
			if (DTM_DEBUG5 >= log_min_messages)
			{
				LWLockAcquire(SharedLocalSnapshotSlot->slotLock, LW_SHARED);
				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);
				LWLockRelease(SharedLocalSnapshotSlot->slotLock);
			}
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
		}
	}

	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
A
Ashwin Agrawal 已提交
2809 2810
				 * StartTransaction() gets called during connection setup
				 * before we even have time to setup our shared snapshot slot.
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
				 */
				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,
A
Ashwin Agrawal 已提交
2836
				 "setupQEDtxContext leaving context = 'Local Only' for Gp_role = %s", role_to_string(Gp_role));
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
			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.
				 */

A
Ashwin Agrawal 已提交
2860
				setDistributedTransactionContext(DTX_CONTEXT_QE_ENTRY_DB_SINGLETON);
2861 2862 2863 2864 2865 2866 2867 2868
			}
			else if (isReaderQE && haveDistributedSnapshot)
			{
				/*
				 * Later, in GetSnapshotData, we will adopt the QE Writer's
				 * transaction and snapshot information.
				 */

A
Ashwin Agrawal 已提交
2869
				setDistributedTransactionContext(DTX_CONTEXT_QE_READER);
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
			}
			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)
				{
					/*
A
Ashwin Agrawal 已提交
2887 2888
					 * We set the DistributedTransactionContext BEFORE we
					 * create the transactions to influence the behavior of
2889 2890
					 * StartTransaction.
					 */
A
Ashwin Agrawal 已提交
2891
					setDistributedTransactionContext(DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER);
2892

2893
					doQEDistributedExplicitBegin();
2894 2895 2896 2897
				}
				else
				{
					Assert(needTwoPhase);
A
Ashwin Agrawal 已提交
2898
					setDistributedTransactionContext(DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER);
2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
				}
			}
			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");
				}

				/*
A
Ashwin Agrawal 已提交
2911 2912 2913
				 * Before executing the query, postgres.c make a standard call
				 * to StartTransactionCommand which will begin a local
				 * transaction with StartTransaction.  This is fine.
2914
				 *
A
Ashwin Agrawal 已提交
2915 2916 2917
				 * However, when the snapshot is created later, the state
				 * below will tell GetSnapshotData to make the local snapshot
				 * from the distributed snapshot.
2918
				 */
A
Ashwin Agrawal 已提交
2919
				setDistributedTransactionContext(DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT);
2920 2921 2922
			}
			else
			{
A
Ashwin Agrawal 已提交
2923
				Assert(!haveDistributedSnapshot);
2924 2925

				/*
A
Ashwin Agrawal 已提交
2926 2927
				 * A local implicit transaction without reference to a
				 * distributed snapshot.  Stay in NONE state.
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
				 */
				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));
*/
A
Ashwin Agrawal 已提交
2938
			Assert(IsTransactionOrTransactionBlock());
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951

			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:
A
Ashwin Agrawal 已提交
2952
			Assert(IsTransactionOrTransactionBlock());
2953 2954 2955 2956
			break;

		case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON:
		case DTX_CONTEXT_QE_READER:
A
Ashwin Agrawal 已提交
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
			/*
			 * 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')",
2982
			 dtxContextInfo->distributedSnapshot.distribSnapshotId,
2983 2984 2985 2986 2987 2988 2989 2990
			 dtxContextInfo->curcid,
			 getDistributedTransactionId(),
			 DtxContextToString(DistributedTransactionContext));
	}

}

void
A
Ashwin Agrawal 已提交
2991
finishDistributedTransactionContext(char *debugCaller, bool aborted)
2992 2993 2994 2995
{
	DistributedTransactionId gxid;

	/*
A
Ashwin Agrawal 已提交
2996 2997
	 * We let the 2 retry states go up to PostgresMain.c, otherwise everything
	 * MUST be complete.
2998 2999
	 */
	if (currentGxact != NULL &&
A
Ashwin Agrawal 已提交
3000 3001
		(currentGxact->state != DTX_STATE_RETRY_COMMIT_PREPARED &&
		 currentGxact->state != DTX_STATE_RETRY_ABORT_PREPARED))
3002 3003
	{
		elog(FATAL, "Expected currentGxact to be NULL at this point.  Found gid =%s, gxid = %u (state = %s, caller = %s)",
A
Ashwin Agrawal 已提交
3004
			 currentGxact->gid, currentGxact->gxid, DtxStateToString(currentGxact->state), debugCaller);
3005 3006 3007 3008 3009 3010 3011 3012 3013 3014
	}

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

A
Ashwin Agrawal 已提交
3015
	setDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
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

	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,
A
Ashwin Agrawal 已提交
3059
				   /* is two-phase */ true, /* withSnapshot */ true, /* inCursor */ false);
3060 3061

	/*
A
Ashwin Agrawal 已提交
3062 3063
	 * Be explicit about both the isolation level and the access mode since in
	 * MPP our QEs are in a another process.
3064 3065 3066 3067 3068 3069
	 */
	sprintf(cmdbuf, "BEGIN ISOLATION LEVEL %s, READ %s",
			IsoLevelAsUpperString(XactIsoLevel),
			(XactReadOnly ? "ONLY" : "WRITE"));

	/*
A
Ashwin Agrawal 已提交
3070 3071
	 * dispatch a DTX command, in the event of an error, this call will either
	 * exit via elog()/ereport() or return false
3072
	 */
3073
	if (!dispatchDtxCommand(cmdbuf))
3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088
	{
		ereport(ERROR, (errmsg("Global transaction BEGIN failed for gid = \"%s\" due to error",
							   currentGxact->gid)));
	}
}

/**
 * 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);
A
Ashwin Agrawal 已提交
3089
	if (!PrepareTransactionBlock((char *) gid))
3090 3091 3092 3093 3094 3095
	{
		elog(ERROR, "Prepare of distributed transaction %s failed", gid);
		return;
	}

	/*
A
Ashwin Agrawal 已提交
3096 3097
	 * Calling CommitTransactionCommand will cause the actual COMMIT/PREPARE
	 * work to be performed.
3098 3099 3100 3101 3102
	 */
	CommitTransactionCommand();

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

A
Ashwin Agrawal 已提交
3103
	setDistributedTransactionContext(DTX_CONTEXT_QE_PREPARED);
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121
}

/**
 * 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();
	{
A
Ashwin Agrawal 已提交
3122
		FinishPreparedTransaction((char *) gid, /* isCommit */ true, raiseErrorIfNotFound);
3123 3124 3125 3126 3127 3128 3129 3130 3131
	}
	PG_CATCH();
	{
		finishDistributedTransactionContext("performDtxProtocolCommitPrepared -- Commit Prepared (error case)", false);
		PG_RE_THROW();
	}
	PG_END_TRY();

	/*
A
Ashwin Agrawal 已提交
3132 3133
	 * Calling CommitTransactionCommand will cause the actual COMMIT/PREPARE
	 * work to be performed.
3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
	 */
	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();
	{
A
Ashwin Agrawal 已提交
3155
		FinishPreparedTransaction((char *) gid, /* isCommit */ false, raiseErrorIfNotFound);
3156 3157 3158 3159 3160 3161 3162 3163 3164
	}
	PG_CATCH();
	{
		finishDistributedTransactionContext("performDtxProtocolAbortPrepared -- Commit Prepared (error case)", true);
		PG_RE_THROW();
	}
	PG_END_TRY();

	/*
A
Ashwin Agrawal 已提交
3165 3166
	 * Calling CommitTransactionCommand will cause the actual COMMIT/PREPARE
	 * work to be performed.
3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
	 */
	CommitTransactionCommand();

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

/**
 * On the QE, handle a DtxProtocolCommand
 */
void
performDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand,
A
Ashwin Agrawal 已提交
3178 3179
						  int flags __attribute__((unused)),
						  const char *loggingStr __attribute__((unused)), const char *gid,
3180 3181 3182 3183 3184 3185 3186 3187 3188 3189
						  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:
A
Ashwin Agrawal 已提交
3190
			switch (DistributedTransactionContext)
3191
			{
A
Ashwin Agrawal 已提交
3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211
				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;
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
			}
			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:
A
Ashwin Agrawal 已提交
3222

3223
			/*
A
Ashwin Agrawal 已提交
3224 3225
			 * The QD has directed us to read-only commit or prepare an
			 * implicit or explicit distributed transaction.
3226 3227 3228 3229
			 */
			switch (DistributedTransactionContext)
			{
				case DTX_CONTEXT_LOCAL_ONLY:
A
Ashwin Agrawal 已提交
3230

3231 3232 3233 3234 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
					/*
					 * 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:
A
Ashwin Agrawal 已提交
3262

3263 3264
					/*
					 * Spontaneously aborted while we were back at the QD?
3265 3266 3267 3268
					 *
					 * It's normal if the transaction doesn't exist. The QD will
					 * call abort on us, even if we didn't finish the prepare yet,
					 * if some other QE reported failure already.
3269
					 */
3270 3271
					elog(DTM_DEBUG3, "Distributed transaction %s not found during abort", gid);
					AbortOutOfAnyTransaction();
3272 3273 3274 3275 3276 3277 3278 3279
					break;

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

				case DTX_CONTEXT_QE_PREPARED:
A
Ashwin Agrawal 已提交
3280
					setDistributedTransactionContext(DTX_CONTEXT_QE_FINISH_PREPARED);
3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
					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:
A
Ashwin Agrawal 已提交
3299 3300
			requireDistributedTransactionContext(DTX_CONTEXT_QE_PREPARED);
			setDistributedTransactionContext(DTX_CONTEXT_QE_FINISH_PREPARED);
3301 3302 3303 3304
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ true);
			break;

		case DTX_PROTOCOL_COMMAND_ABORT_PREPARED:
A
Ashwin Agrawal 已提交
3305 3306
			requireDistributedTransactionContext(DTX_CONTEXT_QE_PREPARED);
			setDistributedTransactionContext(DTX_CONTEXT_QE_FINISH_PREPARED);
3307 3308 3309 3310
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ true);
			break;

		case DTX_PROTOCOL_COMMAND_RETRY_COMMIT_PREPARED:
A
Ashwin Agrawal 已提交
3311
			requireDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3312 3313 3314 3315
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RETRY_ABORT_PREPARED:
A
Ashwin Agrawal 已提交
3316
			requireDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3317 3318 3319 3320
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RECOVERY_COMMIT_PREPARED:
A
Ashwin Agrawal 已提交
3321
			requireDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3322 3323 3324 3325
			performDtxProtocolCommitPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_RECOVERY_ABORT_PREPARED:
A
Ashwin Agrawal 已提交
3326
			requireDistributedTransactionContext(DTX_CONTEXT_LOCAL_ONLY);
3327 3328 3329 3330
			performDtxProtocolAbortPrepared(gid, /* raiseErrorIfNotFound */ false);
			break;

		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_BEGIN_INTERNAL:
A
Ashwin Agrawal 已提交
3331
			switch (DistributedTransactionContext)
3332 3333
			{
				case DTX_CONTEXT_LOCAL_ONLY:
A
Ashwin Agrawal 已提交
3334

3335
					/*
A
Ashwin Agrawal 已提交
3336 3337
					 * QE is not aware of DTX yet. A typical case is SELECT
					 * foo(), where foo() opens internal subtransaction
3338 3339 3340 3341 3342
					 */
					setupQEDtxContext(contextInfo);
					StartTransactionCommand();
					break;
				case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER:
A
Ashwin Agrawal 已提交
3343 3344 3345 3346 3347

					/*
					 * We already marked this QE to be writer, and transaction
					 * is open.
					 */
3348 3349 3350 3351 3352
				case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER:
				case DTX_CONTEXT_QE_READER:
					break;
				default:
					/* Lets flag this situation out, with explicit crash */
A
Ashwin Agrawal 已提交
3353 3354 3355
					Assert(false);
					elog(DTM_DEBUG5,
						 " SUBTRANSACTION_BEGIN_INTERNAL distributed transaction context invalid: %d",
3356 3357 3358 3359 3360
						 (int) DistributedTransactionContext);
					break;
			}

			BeginInternalSubTransaction(NULL);
A
Ashwin Agrawal 已提交
3361
			Assert(contextInfo->nestingLevel + 1 == GetCurrentTransactionNestLevel());
3362 3363 3364 3365 3366 3367
			break;

		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_RELEASE_INTERNAL:
			Assert(contextInfo->nestingLevel == GetCurrentTransactionNestLevel());
			ReleaseCurrentSubTransaction();
			break;
A
Ashwin Agrawal 已提交
3368

3369
		case DTX_PROTOCOL_COMMAND_SUBTRANSACTION_ROLLBACK_INTERNAL:
A
Ashwin Agrawal 已提交
3370 3371 3372 3373

			/*
			 * Rollback performs work on master and then dispatches, hence has
			 * nestingLevel its expecting post operation
3374 3375 3376
			 */
			if ((contextInfo->nestingLevel + 1) > GetCurrentTransactionNestLevel())
			{
A
Ashwin Agrawal 已提交
3377 3378 3379
				ereport(ERROR,
						(errmsg("transaction %s at level %d already processed (current level %d)",
								gid, contextInfo->nestingLevel, GetCurrentTransactionNestLevel())));
3380
			}
A
Ashwin Agrawal 已提交
3381

3382
			unsigned int i = GetCurrentTransactionNestLevel() - contextInfo->nestingLevel;
A
Ashwin Agrawal 已提交
3383

3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399
			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);
}