1 /*-------------------------------------------------------------------------
4 * Two-phase commit support functions.
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/access/transam/twophase.c
13 * Each global transaction is associated with a global transaction
14 * identifier (GID). The client assigns a GID to a postgres
15 * transaction with the PREPARE TRANSACTION command.
17 * We keep all active global transactions in a shared memory array.
18 * When the PREPARE TRANSACTION command is issued, the GID is
19 * reserved for the transaction in the array. This is done before
20 * a WAL entry is made, because the reservation checks for duplicate
21 * GIDs and aborts the transaction if there already is a global
22 * transaction in prepared state with the same GID.
24 * A global transaction (gxact) also has dummy PGXACT and PGPROC; this is
25 * what keeps the XID considered running by TransactionIdIsInProgress.
26 * It is also convenient as a PGPROC to hook the gxact's locks to.
28 * Information to recover prepared transactions in case of crash is
29 * now stored in WAL for the common case. In some cases there will be
30 * an extended period between preparing a GXACT and commit/abort, in
31 * which case we need to separately record prepared transaction data
32 * in permanent storage. This includes locking information, pending
33 * notifications etc. All that state information is written to the
34 * per-transaction state file in the pg_twophase directory.
35 * All prepared transactions will be written prior to shutdown.
37 * Life track of state data is following:
39 * * On PREPARE TRANSACTION backend writes state data only to the WAL and
40 * stores pointer to the start of the WAL record in
41 * gxact->prepare_start_lsn.
42 * * If COMMIT occurs before checkpoint then backend reads data from WAL
43 * using prepare_start_lsn.
44 * * On checkpoint state data copied to files in pg_twophase directory and
46 * * If COMMIT happens after checkpoint then backend reads state data from
49 * During replay and replication, TwoPhaseState also holds information
50 * about active prepared transactions that haven't been moved to disk yet.
52 * Replay of twophase records happens by the following rules:
54 * * At the beginning of recovery, pg_twophase is scanned once, filling
55 * TwoPhaseState with entries marked with gxact->inredo and
56 * gxact->ondisk. Two-phase file data older than the XID horizon of
57 * the redo position are discarded.
58 * * On PREPARE redo, the transaction is added to TwoPhaseState->prepXacts.
59 * gxact->inredo is set to true for such entries.
60 * * On Checkpoint we iterate through TwoPhaseState->prepXacts entries
61 * that have gxact->inredo set and are behind the redo_horizon. We
62 * save them to disk and then switch gxact->ondisk to true.
63 * * On COMMIT/ABORT we delete the entry from TwoPhaseState->prepXacts.
64 * If gxact->ondisk is true, the corresponding entry from the disk
65 * is additionally deleted.
66 * * RecoverPreparedTransactions(), StandbyRecoverPreparedTransactions()
67 * and PrescanPreparedTransactions() have been modified to go through
68 * gxact->inredo entries that have not made it to disk.
70 *-------------------------------------------------------------------------
79 #include "access/commit_ts.h"
80 #include "access/htup_details.h"
81 #include "access/subtrans.h"
82 #include "access/transam.h"
83 #include "access/twophase.h"
84 #include "access/twophase_rmgr.h"
85 #include "access/xact.h"
86 #include "access/xlog.h"
87 #include "access/xloginsert.h"
88 #include "access/xlogutils.h"
89 #include "access/xlogreader.h"
90 #include "catalog/pg_type.h"
91 #include "catalog/storage.h"
93 #include "miscadmin.h"
96 #include "replication/origin.h"
97 #include "replication/syncrep.h"
98 #include "replication/walsender.h"
99 #include "storage/fd.h"
100 #include "storage/ipc.h"
101 #include "storage/predicate.h"
102 #include "storage/proc.h"
103 #include "storage/procarray.h"
104 #include "storage/sinvaladt.h"
105 #include "storage/smgr.h"
106 #include "utils/builtins.h"
107 #include "utils/memutils.h"
108 #include "utils/timestamp.h"
112 * Directory where Two-phase commit files reside within PGDATA
114 #define TWOPHASE_DIR "pg_twophase"
116 /* GUC variable, can't be changed after startup */
117 int max_prepared_xacts = 0;
120 * This struct describes one global transaction that is in prepared state
121 * or attempting to become prepared.
123 * The lifecycle of a global transaction is:
125 * 1. After checking that the requested GID is not in use, set up an entry in
126 * the TwoPhaseState->prepXacts array with the correct GID and valid = false,
127 * and mark it as locked by my backend.
129 * 2. After successfully completing prepare, set valid = true and enter the
130 * referenced PGPROC into the global ProcArray.
132 * 3. To begin COMMIT PREPARED or ROLLBACK PREPARED, check that the entry is
133 * valid and not locked, then mark the entry as locked by storing my current
134 * backend ID into locking_backend. This prevents concurrent attempts to
135 * commit or rollback the same prepared xact.
137 * 4. On completion of COMMIT PREPARED or ROLLBACK PREPARED, remove the entry
138 * from the ProcArray and the TwoPhaseState->prepXacts array and return it to
141 * Note that if the preparing transaction fails between steps 1 and 2, the
142 * entry must be removed so that the GID and the GlobalTransaction struct
143 * can be reused. See AtAbort_Twophase().
145 * typedef struct GlobalTransactionData *GlobalTransaction appears in
148 * Note that the max value of GIDSIZE must fit in the uint16 gidlen,
149 * specified in TwoPhaseFileHeader.
153 typedef struct GlobalTransactionData
155 GlobalTransaction next; /* list link for free list */
156 int pgprocno; /* ID of associated dummy PGPROC */
157 BackendId dummyBackendId; /* similar to backend id for backends */
158 TimestampTz prepared_at; /* time of preparation */
161 * Note that we need to keep track of two LSNs for each GXACT. We keep
162 * track of the start LSN because this is the address we must use to read
163 * state data back from WAL when committing a prepared GXACT. We keep
164 * track of the end LSN because that is the LSN we need to wait for prior
167 XLogRecPtr prepare_start_lsn; /* XLOG offset of prepare record start */
168 XLogRecPtr prepare_end_lsn; /* XLOG offset of prepare record end */
169 TransactionId xid; /* The GXACT id */
171 Oid owner; /* ID of user that executed the xact */
172 BackendId locking_backend; /* backend currently working on the xact */
173 bool valid; /* TRUE if PGPROC entry is in proc array */
174 bool ondisk; /* TRUE if prepare state file is on disk */
175 bool inredo; /* TRUE if entry was added via xlog_redo */
176 char gid[GIDSIZE]; /* The GID assigned to the prepared xact */
177 } GlobalTransactionData;
180 * Two Phase Commit shared state. Access to this struct is protected
181 * by TwoPhaseStateLock.
183 typedef struct TwoPhaseStateData
185 /* Head of linked list of free GlobalTransactionData structs */
186 GlobalTransaction freeGXacts;
188 /* Number of valid prepXacts entries. */
191 /* There are max_prepared_xacts items in this array */
192 GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER];
195 static TwoPhaseStateData *TwoPhaseState;
198 * Global transaction entry currently locked by us, if any. Note that any
199 * access to the entry pointed to by this variable must be protected by
200 * TwoPhaseStateLock, though obviously the pointer itself doesn't need to be
201 * (since it's just local memory).
203 static GlobalTransaction MyLockedGxact = NULL;
205 static bool twophaseExitRegistered = false;
207 static void RecordTransactionCommitPrepared(TransactionId xid,
209 TransactionId *children,
213 SharedInvalidationMessage *invalmsgs,
215 static void RecordTransactionAbortPrepared(TransactionId xid,
217 TransactionId *children,
220 static void ProcessRecords(char *bufptr, TransactionId xid,
221 const TwoPhaseCallback callbacks[]);
222 static void RemoveGXact(GlobalTransaction gxact);
224 static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len);
225 static char *ProcessTwoPhaseBuffer(TransactionId xid,
226 XLogRecPtr prepare_start_lsn,
227 bool fromdisk, bool setParent, bool setNextXid);
228 static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid,
229 const char *gid, TimestampTz prepared_at, Oid owner,
231 static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning);
232 static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len);
235 * Initialization of shared memory
238 TwoPhaseShmemSize(void)
242 /* Need the fixed struct, the array of pointers, and the GTD structs */
243 size = offsetof(TwoPhaseStateData, prepXacts);
244 size = add_size(size, mul_size(max_prepared_xacts,
245 sizeof(GlobalTransaction)));
246 size = MAXALIGN(size);
247 size = add_size(size, mul_size(max_prepared_xacts,
248 sizeof(GlobalTransactionData)));
254 TwoPhaseShmemInit(void)
258 TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
261 if (!IsUnderPostmaster)
263 GlobalTransaction gxacts;
267 TwoPhaseState->freeGXacts = NULL;
268 TwoPhaseState->numPrepXacts = 0;
271 * Initialize the linked list of free GlobalTransactionData structs
273 gxacts = (GlobalTransaction)
274 ((char *) TwoPhaseState +
275 MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
276 sizeof(GlobalTransaction) * max_prepared_xacts));
277 for (i = 0; i < max_prepared_xacts; i++)
279 /* insert into linked list */
280 gxacts[i].next = TwoPhaseState->freeGXacts;
281 TwoPhaseState->freeGXacts = &gxacts[i];
283 /* associate it with a PGPROC assigned by InitProcGlobal */
284 gxacts[i].pgprocno = PreparedXactProcs[i].pgprocno;
287 * Assign a unique ID for each dummy proc, so that the range of
288 * dummy backend IDs immediately follows the range of normal
289 * backend IDs. We don't dare to assign a real backend ID to dummy
290 * procs, because prepared transactions don't take part in cache
291 * invalidation like a real backend ID would imply, but having a
292 * unique ID for them is nevertheless handy. This arrangement
293 * allows you to allocate an array of size (MaxBackends +
294 * max_prepared_xacts + 1), and have a slot for every backend and
295 * prepared transaction. Currently multixact.c uses that
298 gxacts[i].dummyBackendId = MaxBackends + 1 + i;
306 * Exit hook to unlock the global transaction entry we're working on.
309 AtProcExit_Twophase(int code, Datum arg)
311 /* same logic as abort */
316 * Abort hook to unlock the global transaction entry we're working on.
319 AtAbort_Twophase(void)
321 if (MyLockedGxact == NULL)
325 * What to do with the locked global transaction entry? If we were in the
326 * process of preparing the transaction, but haven't written the WAL
327 * record and state file yet, the transaction must not be considered as
328 * prepared. Likewise, if we are in the process of finishing an
329 * already-prepared transaction, and fail after having already written the
330 * 2nd phase commit or rollback record to the WAL, the transaction should
331 * not be considered as prepared anymore. In those cases, just remove the
332 * entry from shared memory.
334 * Otherwise, the entry must be left in place so that the transaction can
335 * be finished later, so just unlock it.
337 * If we abort during prepare, after having written the WAL record, we
338 * might not have transferred all locks and other state to the prepared
339 * transaction yet. Likewise, if we abort during commit or rollback,
340 * after having written the WAL record, we might not have released all the
341 * resources held by the transaction yet. In those cases, the in-memory
342 * state can be wrong, but it's too late to back out.
344 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
345 if (!MyLockedGxact->valid)
346 RemoveGXact(MyLockedGxact);
348 MyLockedGxact->locking_backend = InvalidBackendId;
349 LWLockRelease(TwoPhaseStateLock);
351 MyLockedGxact = NULL;
355 * This is called after we have finished transferring state to the prepared
359 PostPrepare_Twophase(void)
361 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
362 MyLockedGxact->locking_backend = InvalidBackendId;
363 LWLockRelease(TwoPhaseStateLock);
365 MyLockedGxact = NULL;
371 * Reserve the GID for the given transaction.
374 MarkAsPreparing(TransactionId xid, const char *gid,
375 TimestampTz prepared_at, Oid owner, Oid databaseid)
377 GlobalTransaction gxact;
380 if (strlen(gid) >= GIDSIZE)
382 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
383 errmsg("transaction identifier \"%s\" is too long",
386 /* fail immediately if feature is disabled */
387 if (max_prepared_xacts == 0)
389 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
390 errmsg("prepared transactions are disabled"),
391 errhint("Set max_prepared_transactions to a nonzero value.")));
393 /* on first call, register the exit hook */
394 if (!twophaseExitRegistered)
396 before_shmem_exit(AtProcExit_Twophase, 0);
397 twophaseExitRegistered = true;
400 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
402 /* Check for conflicting GID */
403 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
405 gxact = TwoPhaseState->prepXacts[i];
406 if (strcmp(gxact->gid, gid) == 0)
409 (errcode(ERRCODE_DUPLICATE_OBJECT),
410 errmsg("transaction identifier \"%s\" is already in use",
415 /* Get a free gxact from the freelist */
416 if (TwoPhaseState->freeGXacts == NULL)
418 (errcode(ERRCODE_OUT_OF_MEMORY),
419 errmsg("maximum number of prepared transactions reached"),
420 errhint("Increase max_prepared_transactions (currently %d).",
421 max_prepared_xacts)));
422 gxact = TwoPhaseState->freeGXacts;
423 TwoPhaseState->freeGXacts = gxact->next;
425 MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
427 gxact->ondisk = false;
429 /* And insert it into the active array */
430 Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
431 TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
433 LWLockRelease(TwoPhaseStateLock);
439 * MarkAsPreparingGuts
441 * This uses a gxact struct and puts it into the active array.
442 * NOTE: this is also used when reloading a gxact after a crash; so avoid
443 * assuming that we can use very much backend context.
445 * Note: This function should be called with appropriate locks held.
448 MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid,
449 TimestampTz prepared_at, Oid owner, Oid databaseid)
455 Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
457 Assert(gxact != NULL);
458 proc = &ProcGlobal->allProcs[gxact->pgprocno];
459 pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
461 /* Initialize the PGPROC entry */
462 MemSet(proc, 0, sizeof(PGPROC));
463 proc->pgprocno = gxact->pgprocno;
464 SHMQueueElemInit(&(proc->links));
465 proc->waitStatus = STATUS_OK;
466 /* We set up the gxact's VXID as InvalidBackendId/XID */
467 proc->lxid = (LocalTransactionId) xid;
469 pgxact->xmin = InvalidTransactionId;
470 pgxact->delayChkpt = false;
471 pgxact->vacuumFlags = 0;
473 proc->backendId = InvalidBackendId;
474 proc->databaseId = databaseid;
475 proc->roleId = owner;
476 proc->isBackgroundWorker = false;
477 proc->lwWaiting = false;
478 proc->lwWaitMode = 0;
479 proc->waitLock = NULL;
480 proc->waitProcLock = NULL;
481 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
482 SHMQueueInit(&(proc->myProcLocks[i]));
483 /* subxid data must be filled later by GXactLoadSubxactData */
484 pgxact->overflowed = false;
487 gxact->prepared_at = prepared_at;
489 gxact->owner = owner;
490 gxact->locking_backend = MyBackendId;
491 gxact->valid = false;
492 gxact->inredo = false;
493 strcpy(gxact->gid, gid);
496 * Remember that we have this GlobalTransaction entry locked for us. If we
497 * abort after this, we must release it.
499 MyLockedGxact = gxact;
503 * GXactLoadSubxactData
505 * If the transaction being persisted had any subtransactions, this must
506 * be called before MarkAsPrepared() to load information into the dummy
510 GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts,
511 TransactionId *children)
513 PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
514 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
516 /* We need no extra lock since the GXACT isn't valid yet */
517 if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
519 pgxact->overflowed = true;
520 nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
524 memcpy(proc->subxids.xids, children,
525 nsubxacts * sizeof(TransactionId));
526 pgxact->nxids = nsubxacts;
532 * Mark the GXACT as fully valid, and enter it into the global ProcArray.
534 * lock_held indicates whether caller already holds TwoPhaseStateLock.
537 MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
539 /* Lock here may be overkill, but I'm not convinced of that ... */
541 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
542 Assert(!gxact->valid);
545 LWLockRelease(TwoPhaseStateLock);
548 * Put it into the global ProcArray so TransactionIdIsInProgress considers
549 * the XID as still running.
551 ProcArrayAdd(&ProcGlobal->allProcs[gxact->pgprocno]);
556 * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
558 static GlobalTransaction
559 LockGXact(const char *gid, Oid user)
563 /* on first call, register the exit hook */
564 if (!twophaseExitRegistered)
566 before_shmem_exit(AtProcExit_Twophase, 0);
567 twophaseExitRegistered = true;
570 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
572 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
574 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
575 PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
577 /* Ignore not-yet-valid GIDs */
580 if (strcmp(gxact->gid, gid) != 0)
583 /* Found it, but has someone else got it locked? */
584 if (gxact->locking_backend != InvalidBackendId)
586 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
587 errmsg("prepared transaction with identifier \"%s\" is busy",
590 if (user != gxact->owner && !superuser_arg(user))
592 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
593 errmsg("permission denied to finish prepared transaction"),
594 errhint("Must be superuser or the user that prepared the transaction.")));
597 * Note: it probably would be possible to allow committing from
598 * another database; but at the moment NOTIFY is known not to work and
599 * there may be some other issues as well. Hence disallow until
600 * someone gets motivated to make it work.
602 if (MyDatabaseId != proc->databaseId)
604 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
605 errmsg("prepared transaction belongs to another database"),
606 errhint("Connect to the database where the transaction was prepared to finish it.")));
608 /* OK for me to lock it */
609 gxact->locking_backend = MyBackendId;
610 MyLockedGxact = gxact;
612 LWLockRelease(TwoPhaseStateLock);
617 LWLockRelease(TwoPhaseStateLock);
620 (errcode(ERRCODE_UNDEFINED_OBJECT),
621 errmsg("prepared transaction with identifier \"%s\" does not exist",
630 * Remove the prepared transaction from the shared memory array.
632 * NB: caller should have already removed it from ProcArray
635 RemoveGXact(GlobalTransaction gxact)
639 Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
641 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
643 if (gxact == TwoPhaseState->prepXacts[i])
645 /* remove from the active array */
646 TwoPhaseState->numPrepXacts--;
647 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
649 /* and put it back in the freelist */
650 gxact->next = TwoPhaseState->freeGXacts;
651 TwoPhaseState->freeGXacts = gxact;
657 elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
661 * Returns an array of all prepared transactions for the user-level
662 * function pg_prepared_xact.
664 * The returned array and all its elements are copies of internal data
665 * structures, to minimize the time we need to hold the TwoPhaseStateLock.
667 * WARNING -- we return even those transactions that are not fully prepared
668 * yet. The caller should filter them out if he doesn't want them.
670 * The returned array is palloc'd.
673 GetPreparedTransactionList(GlobalTransaction *gxacts)
675 GlobalTransaction array;
679 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
681 if (TwoPhaseState->numPrepXacts == 0)
683 LWLockRelease(TwoPhaseStateLock);
689 num = TwoPhaseState->numPrepXacts;
690 array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
692 for (i = 0; i < num; i++)
693 memcpy(array + i, TwoPhaseState->prepXacts[i],
694 sizeof(GlobalTransactionData));
696 LWLockRelease(TwoPhaseStateLock);
702 /* Working status for pg_prepared_xact */
705 GlobalTransaction array;
712 * Produce a view with one row per prepared transaction.
714 * This function is here so we don't have to export the
715 * GlobalTransactionData struct definition.
718 pg_prepared_xact(PG_FUNCTION_ARGS)
720 FuncCallContext *funcctx;
721 Working_State *status;
723 if (SRF_IS_FIRSTCALL())
726 MemoryContext oldcontext;
728 /* create a function context for cross-call persistence */
729 funcctx = SRF_FIRSTCALL_INIT();
732 * Switch to memory context appropriate for multiple function calls
734 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
736 /* build tupdesc for result tuples */
737 /* this had better match pg_prepared_xacts view in system_views.sql */
738 tupdesc = CreateTemplateTupleDesc(5, false);
739 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
741 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
743 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
744 TIMESTAMPTZOID, -1, 0);
745 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
747 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
750 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
753 * Collect all the 2PC status information that we will format and send
754 * out as a result set.
756 status = (Working_State *) palloc(sizeof(Working_State));
757 funcctx->user_fctx = (void *) status;
759 status->ngxacts = GetPreparedTransactionList(&status->array);
762 MemoryContextSwitchTo(oldcontext);
765 funcctx = SRF_PERCALL_SETUP();
766 status = (Working_State *) funcctx->user_fctx;
768 while (status->array != NULL && status->currIdx < status->ngxacts)
770 GlobalTransaction gxact = &status->array[status->currIdx++];
771 PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
772 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
782 * Form tuple with appropriate data.
784 MemSet(values, 0, sizeof(values));
785 MemSet(nulls, 0, sizeof(nulls));
787 values[0] = TransactionIdGetDatum(pgxact->xid);
788 values[1] = CStringGetTextDatum(gxact->gid);
789 values[2] = TimestampTzGetDatum(gxact->prepared_at);
790 values[3] = ObjectIdGetDatum(gxact->owner);
791 values[4] = ObjectIdGetDatum(proc->databaseId);
793 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
794 result = HeapTupleGetDatum(tuple);
795 SRF_RETURN_NEXT(funcctx, result);
798 SRF_RETURN_DONE(funcctx);
803 * Get the GlobalTransaction struct for a prepared transaction
806 static GlobalTransaction
807 TwoPhaseGetGXact(TransactionId xid)
809 GlobalTransaction result = NULL;
812 static TransactionId cached_xid = InvalidTransactionId;
813 static GlobalTransaction cached_gxact = NULL;
816 * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
817 * repeatedly for the same XID. We can save work with a simple cache.
819 if (xid == cached_xid)
822 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
824 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
826 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
827 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
829 if (pgxact->xid == xid)
836 LWLockRelease(TwoPhaseStateLock);
838 if (result == NULL) /* should not happen */
839 elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
842 cached_gxact = result;
848 * TwoPhaseGetDummyProc
849 * Get the dummy backend ID for prepared transaction specified by XID
851 * Dummy backend IDs are similar to real backend IDs of real backends.
852 * They start at MaxBackends + 1, and are unique across all currently active
853 * real backends and prepared transactions.
856 TwoPhaseGetDummyBackendId(TransactionId xid)
858 GlobalTransaction gxact = TwoPhaseGetGXact(xid);
860 return gxact->dummyBackendId;
864 * TwoPhaseGetDummyProc
865 * Get the PGPROC that represents a prepared transaction specified by XID
868 TwoPhaseGetDummyProc(TransactionId xid)
870 GlobalTransaction gxact = TwoPhaseGetGXact(xid);
872 return &ProcGlobal->allProcs[gxact->pgprocno];
875 /************************************************************************/
876 /* State file support */
877 /************************************************************************/
879 #define TwoPhaseFilePath(path, xid) \
880 snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
883 * 2PC state file format:
885 * 1. TwoPhaseFileHeader
886 * 2. TransactionId[] (subtransactions)
887 * 3. RelFileNode[] (files to be deleted at commit)
888 * 4. RelFileNode[] (files to be deleted at abort)
889 * 5. SharedInvalidationMessage[] (inval messages to be sent at commit)
890 * 6. TwoPhaseRecordOnDisk
892 * 8. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
893 * 9. checksum (CRC-32C)
895 * Each segment except the final checksum is MAXALIGN'd.
899 * Header for a 2PC state file
901 #define TWOPHASE_MAGIC 0x57F94533 /* format identifier */
903 typedef struct TwoPhaseFileHeader
905 uint32 magic; /* format identifier */
906 uint32 total_len; /* actual file length */
907 TransactionId xid; /* original transaction XID */
908 Oid database; /* OID of database it was in */
909 TimestampTz prepared_at; /* time of preparation */
910 Oid owner; /* user running the transaction */
911 int32 nsubxacts; /* number of following subxact XIDs */
912 int32 ncommitrels; /* number of delete-on-commit rels */
913 int32 nabortrels; /* number of delete-on-abort rels */
914 int32 ninvalmsgs; /* number of cache invalidation messages */
915 bool initfileinval; /* does relcache init file need invalidation? */
916 uint16 gidlen; /* length of the GID - GID follows the header */
917 } TwoPhaseFileHeader;
920 * Header for each record in a state file
922 * NOTE: len counts only the rmgr data, not the TwoPhaseRecordOnDisk header.
923 * The rmgr data will be stored starting on a MAXALIGN boundary.
925 typedef struct TwoPhaseRecordOnDisk
927 uint32 len; /* length of rmgr data */
928 TwoPhaseRmgrId rmid; /* resource manager for this record */
929 uint16 info; /* flag bits for use by rmgr */
930 } TwoPhaseRecordOnDisk;
933 * During prepare, the state file is assembled in memory before writing it
934 * to WAL and the actual state file. We use a chain of StateFileChunk blocks
937 typedef struct StateFileChunk
941 struct StateFileChunk *next;
946 StateFileChunk *head; /* first data block in the chain */
947 StateFileChunk *tail; /* last block in chain */
949 uint32 bytes_free; /* free bytes left in tail block */
950 uint32 total_len; /* total data bytes in chain */
955 * Append a block of data to records data structure.
957 * NB: each block is padded to a MAXALIGN multiple. This must be
958 * accounted for when the file is later read!
960 * The data is copied, so the caller is free to modify it afterwards.
963 save_state_data(const void *data, uint32 len)
965 uint32 padlen = MAXALIGN(len);
967 if (padlen > records.bytes_free)
969 records.tail->next = palloc0(sizeof(StateFileChunk));
970 records.tail = records.tail->next;
971 records.tail->len = 0;
972 records.tail->next = NULL;
973 records.num_chunks++;
975 records.bytes_free = Max(padlen, 512);
976 records.tail->data = palloc(records.bytes_free);
979 memcpy(((char *) records.tail->data) + records.tail->len, data, len);
980 records.tail->len += padlen;
981 records.bytes_free -= padlen;
982 records.total_len += padlen;
986 * Start preparing a state file.
988 * Initializes data structure and inserts the 2PC file header record.
991 StartPrepare(GlobalTransaction gxact)
993 PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
994 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
995 TransactionId xid = pgxact->xid;
996 TwoPhaseFileHeader hdr;
997 TransactionId *children;
998 RelFileNode *commitrels;
999 RelFileNode *abortrels;
1000 SharedInvalidationMessage *invalmsgs;
1002 /* Initialize linked list */
1003 records.head = palloc0(sizeof(StateFileChunk));
1004 records.head->len = 0;
1005 records.head->next = NULL;
1007 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1008 records.head->data = palloc(records.bytes_free);
1010 records.tail = records.head;
1011 records.num_chunks = 1;
1013 records.total_len = 0;
1016 hdr.magic = TWOPHASE_MAGIC;
1017 hdr.total_len = 0; /* EndPrepare will fill this in */
1019 hdr.database = proc->databaseId;
1020 hdr.prepared_at = gxact->prepared_at;
1021 hdr.owner = gxact->owner;
1022 hdr.nsubxacts = xactGetCommittedChildren(&children);
1023 hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1024 hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1025 hdr.ninvalmsgs = xactGetCommittedInvalidationMessages(&invalmsgs,
1026 &hdr.initfileinval);
1027 hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1029 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1030 save_state_data(gxact->gid, hdr.gidlen);
1033 * Add the additional info about subxacts, deletable files and cache
1034 * invalidation messages.
1036 if (hdr.nsubxacts > 0)
1038 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1039 /* While we have the child-xact data, stuff it in the gxact too */
1040 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1042 if (hdr.ncommitrels > 0)
1044 save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1047 if (hdr.nabortrels > 0)
1049 save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1052 if (hdr.ninvalmsgs > 0)
1054 save_state_data(invalmsgs,
1055 hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1061 * Finish preparing state data and writing it to WAL.
1064 EndPrepare(GlobalTransaction gxact)
1066 TwoPhaseFileHeader *hdr;
1067 StateFileChunk *record;
1069 /* Add the end sentinel to the list of 2PC records */
1070 RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID, 0,
1073 /* Go back and fill in total_len in the file header record */
1074 hdr = (TwoPhaseFileHeader *) records.head->data;
1075 Assert(hdr->magic == TWOPHASE_MAGIC);
1076 hdr->total_len = records.total_len + sizeof(pg_crc32c);
1079 * If the data size exceeds MaxAllocSize, we won't be able to read it in
1080 * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1081 * where we write data to file and then re-read at commit time.
1083 if (hdr->total_len > MaxAllocSize)
1085 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1086 errmsg("two-phase state file maximum length exceeded")));
1089 * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1090 * cover us, so no need to calculate a separate CRC.
1092 * We have to set delayChkpt here, too; otherwise a checkpoint starting
1093 * immediately after the WAL record is inserted could complete without
1094 * fsync'ing our state file. (This is essentially the same kind of race
1095 * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1096 * uses delayChkpt for; see notes there.)
1098 * We save the PREPARE record's location in the gxact for later use by
1099 * CheckPointTwoPhase.
1101 XLogEnsureRecordSpace(0, records.num_chunks);
1103 START_CRIT_SECTION();
1105 MyPgXact->delayChkpt = true;
1108 for (record = records.head; record != NULL; record = record->next)
1109 XLogRegisterData(record->data, record->len);
1110 gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1111 XLogFlush(gxact->prepare_end_lsn);
1113 /* If we crash now, we have prepared: WAL replay will fix things */
1115 /* Store record's start location to read that later on Commit */
1116 gxact->prepare_start_lsn = ProcLastRecPtr;
1119 * Mark the prepared transaction as valid. As soon as xact.c marks
1120 * MyPgXact as not running our XID (which it will do immediately after
1121 * this function returns), others can commit/rollback the xact.
1123 * NB: a side effect of this is to make a dummy ProcArray entry for the
1124 * prepared XID. This must happen before we clear the XID from MyPgXact,
1125 * else there is a window where the XID is not running according to
1126 * TransactionIdIsInProgress, and onlookers would be entitled to assume
1127 * the xact crashed. Instead we have a window where the same XID appears
1128 * twice in ProcArray, which is OK.
1130 MarkAsPrepared(gxact, false);
1133 * Now we can mark ourselves as out of the commit critical section: a
1134 * checkpoint starting after this will certainly see the gxact as a
1135 * candidate for fsyncing.
1137 MyPgXact->delayChkpt = false;
1140 * Remember that we have this GlobalTransaction entry locked for us. If
1141 * we crash after this point, it's too late to abort, but we must unlock
1142 * it so that the prepared transaction can be committed or rolled back.
1144 MyLockedGxact = gxact;
1149 * Wait for synchronous replication, if required.
1151 * Note that at this stage we have marked the prepare, but still show as
1152 * running in the procarray (twice!) and continue to hold locks.
1154 SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1156 records.tail = records.head = NULL;
1157 records.num_chunks = 0;
1161 * Register a 2PC record to be written to state file.
1164 RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info,
1165 const void *data, uint32 len)
1167 TwoPhaseRecordOnDisk record;
1172 save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1174 save_state_data(data, len);
1179 * Read and validate the state file for xid.
1181 * If it looks OK (has a valid magic number and CRC), return the palloc'd
1182 * contents of the file. Otherwise return NULL.
1185 ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
1187 char path[MAXPGPATH];
1189 TwoPhaseFileHeader *hdr;
1196 TwoPhaseFilePath(path, xid);
1198 fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
1203 (errcode_for_file_access(),
1204 errmsg("could not open two-phase state file \"%s\": %m",
1210 * Check file length. We can determine a lower bound pretty easily. We
1211 * set an upper bound to avoid palloc() failure on a corrupt file, though
1212 * we can't guarantee that we won't get an out of memory error anyway,
1213 * even on a valid file.
1215 if (fstat(fd, &stat))
1217 CloseTransientFile(fd);
1220 (errcode_for_file_access(),
1221 errmsg("could not stat two-phase state file \"%s\": %m",
1226 if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1227 MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1228 sizeof(pg_crc32c)) ||
1229 stat.st_size > MaxAllocSize)
1231 CloseTransientFile(fd);
1235 crc_offset = stat.st_size - sizeof(pg_crc32c);
1236 if (crc_offset != MAXALIGN(crc_offset))
1238 CloseTransientFile(fd);
1243 * OK, slurp in the file.
1245 buf = (char *) palloc(stat.st_size);
1247 pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_READ);
1248 if (read(fd, buf, stat.st_size) != stat.st_size)
1250 pgstat_report_wait_end();
1251 CloseTransientFile(fd);
1254 (errcode_for_file_access(),
1255 errmsg("could not read two-phase state file \"%s\": %m",
1261 pgstat_report_wait_end();
1262 CloseTransientFile(fd);
1264 hdr = (TwoPhaseFileHeader *) buf;
1265 if (hdr->magic != TWOPHASE_MAGIC || hdr->total_len != stat.st_size)
1271 INIT_CRC32C(calc_crc);
1272 COMP_CRC32C(calc_crc, buf, crc_offset);
1273 FIN_CRC32C(calc_crc);
1275 file_crc = *((pg_crc32c *) (buf + crc_offset));
1277 if (!EQ_CRC32C(calc_crc, file_crc))
1288 * Reads 2PC data from xlog. During checkpoint this data will be moved to
1289 * twophase files and ReadTwoPhaseFile should be used instead.
1291 * Note clearly that this function can access WAL during normal operation,
1292 * similarly to the way WALSender or Logical Decoding would do.
1296 XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
1299 XLogReaderState *xlogreader;
1302 xlogreader = XLogReaderAllocate(&read_local_xlog_page, NULL);
1305 (errcode(ERRCODE_OUT_OF_MEMORY),
1306 errmsg("out of memory"),
1307 errdetail("Failed while allocating a WAL reading processor.")));
1309 record = XLogReadRecord(xlogreader, lsn, &errormsg);
1312 (errcode_for_file_access(),
1313 errmsg("could not read two-phase state from WAL at %X/%X",
1314 (uint32) (lsn >> 32),
1317 if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1318 (XLogRecGetInfo(xlogreader) & XLOG_XACT_OPMASK) != XLOG_XACT_PREPARE)
1320 (errcode_for_file_access(),
1321 errmsg("expected two-phase state data is not present in WAL at %X/%X",
1322 (uint32) (lsn >> 32),
1326 *len = XLogRecGetDataLen(xlogreader);
1328 *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1329 memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1331 XLogReaderFree(xlogreader);
1336 * Confirms an xid is prepared, during recovery
1339 StandbyTransactionIdIsPrepared(TransactionId xid)
1342 TwoPhaseFileHeader *hdr;
1345 Assert(TransactionIdIsValid(xid));
1347 if (max_prepared_xacts <= 0)
1348 return false; /* nothing to do */
1350 /* Read and validate file */
1351 buf = ReadTwoPhaseFile(xid, false);
1355 /* Check header also */
1356 hdr = (TwoPhaseFileHeader *) buf;
1357 result = TransactionIdEquals(hdr->xid, xid);
1364 * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1367 FinishPreparedTransaction(const char *gid, bool isCommit)
1369 GlobalTransaction gxact;
1375 TwoPhaseFileHeader *hdr;
1376 TransactionId latestXid;
1377 TransactionId *children;
1378 RelFileNode *commitrels;
1379 RelFileNode *abortrels;
1380 RelFileNode *delrels;
1382 SharedInvalidationMessage *invalmsgs;
1386 * Validate the GID, and lock the GXACT to ensure that two backends do not
1387 * try to commit the same GID at once.
1389 gxact = LockGXact(gid, GetUserId());
1390 proc = &ProcGlobal->allProcs[gxact->pgprocno];
1391 pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1395 * Read and validate 2PC state data. State data will typically be stored
1396 * in WAL files if the LSN is after the last checkpoint record, or moved
1397 * to disk if for some reason they have lived for a long time.
1400 buf = ReadTwoPhaseFile(xid, true);
1402 XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1406 * Disassemble the header area
1408 hdr = (TwoPhaseFileHeader *) buf;
1409 Assert(TransactionIdEquals(hdr->xid, xid));
1410 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1411 bufptr += MAXALIGN(hdr->gidlen);
1412 children = (TransactionId *) bufptr;
1413 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1414 commitrels = (RelFileNode *) bufptr;
1415 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1416 abortrels = (RelFileNode *) bufptr;
1417 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1418 invalmsgs = (SharedInvalidationMessage *) bufptr;
1419 bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1421 /* compute latestXid among all children */
1422 latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1425 * The order of operations here is critical: make the XLOG entry for
1426 * commit or abort, then mark the transaction committed or aborted in
1427 * pg_xact, then remove its PGPROC from the global ProcArray (which means
1428 * TransactionIdIsInProgress will stop saying the prepared xact is in
1429 * progress), then run the post-commit or post-abort callbacks. The
1430 * callbacks will release the locks the transaction held.
1433 RecordTransactionCommitPrepared(xid,
1434 hdr->nsubxacts, children,
1435 hdr->ncommitrels, commitrels,
1436 hdr->ninvalmsgs, invalmsgs,
1437 hdr->initfileinval);
1439 RecordTransactionAbortPrepared(xid,
1440 hdr->nsubxacts, children,
1441 hdr->nabortrels, abortrels);
1443 ProcArrayRemove(proc, latestXid);
1446 * In case we fail while running the callbacks, mark the gxact invalid so
1447 * no one else will try to commit/rollback, and so it will be recycled if
1448 * we fail after this point. It is still locked by our backend so it
1449 * won't go away yet.
1451 * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1453 gxact->valid = false;
1456 * We have to remove any files that were supposed to be dropped. For
1457 * consistency with the regular xact.c code paths, must do this before
1458 * releasing locks, so do it before running the callbacks.
1460 * NB: this code knows that we couldn't be dropping any temp rels ...
1464 delrels = commitrels;
1465 ndelrels = hdr->ncommitrels;
1469 delrels = abortrels;
1470 ndelrels = hdr->nabortrels;
1472 for (i = 0; i < ndelrels; i++)
1474 SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1476 smgrdounlink(srel, false);
1481 * Handle cache invalidation messages.
1483 * Relcache init file invalidation requires processing both before and
1484 * after we send the SI messages. See AtEOXact_Inval()
1486 if (hdr->initfileinval)
1487 RelationCacheInitFilePreInvalidate();
1488 SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1489 if (hdr->initfileinval)
1490 RelationCacheInitFilePostInvalidate();
1492 /* And now do the callbacks */
1494 ProcessRecords(bufptr, xid, twophase_postcommit_callbacks);
1496 ProcessRecords(bufptr, xid, twophase_postabort_callbacks);
1498 PredicateLockTwoPhaseFinish(xid, isCommit);
1500 /* Count the prepared xact as committed or aborted */
1501 AtEOXact_PgStat(isCommit);
1504 * And now we can clean up any files we may have left.
1507 RemoveTwoPhaseFile(xid, true);
1509 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1511 LWLockRelease(TwoPhaseStateLock);
1512 MyLockedGxact = NULL;
1518 * Scan 2PC state data in memory and call the indicated callbacks for each 2PC record.
1521 ProcessRecords(char *bufptr, TransactionId xid,
1522 const TwoPhaseCallback callbacks[])
1526 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1528 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1529 if (record->rmid == TWOPHASE_RM_END_ID)
1532 bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1534 if (callbacks[record->rmid] != NULL)
1535 callbacks[record->rmid] (xid, record->info,
1536 (void *) bufptr, record->len);
1538 bufptr += MAXALIGN(record->len);
1543 * Remove the 2PC file for the specified XID.
1545 * If giveWarning is false, do not complain about file-not-present;
1546 * this is an expected case during WAL replay.
1549 RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
1551 char path[MAXPGPATH];
1553 TwoPhaseFilePath(path, xid);
1555 if (errno != ENOENT || giveWarning)
1557 (errcode_for_file_access(),
1558 errmsg("could not remove two-phase state file \"%s\": %m",
1563 * Recreates a state file. This is used in WAL replay and during
1564 * checkpoint creation.
1566 * Note: content and len don't include CRC.
1569 RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
1571 char path[MAXPGPATH];
1572 pg_crc32c statefile_crc;
1576 INIT_CRC32C(statefile_crc);
1577 COMP_CRC32C(statefile_crc, content, len);
1578 FIN_CRC32C(statefile_crc);
1580 TwoPhaseFilePath(path, xid);
1582 fd = OpenTransientFile(path,
1583 O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY,
1587 (errcode_for_file_access(),
1588 errmsg("could not recreate two-phase state file \"%s\": %m",
1591 /* Write content and CRC */
1592 pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_WRITE);
1593 if (write(fd, content, len) != len)
1595 pgstat_report_wait_end();
1596 CloseTransientFile(fd);
1598 (errcode_for_file_access(),
1599 errmsg("could not write two-phase state file: %m")));
1601 if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1603 pgstat_report_wait_end();
1604 CloseTransientFile(fd);
1606 (errcode_for_file_access(),
1607 errmsg("could not write two-phase state file: %m")));
1609 pgstat_report_wait_end();
1612 * We must fsync the file because the end-of-replay checkpoint will not do
1613 * so, there being no GXACT in shared memory yet to tell it to.
1615 pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_SYNC);
1616 if (pg_fsync(fd) != 0)
1618 CloseTransientFile(fd);
1620 (errcode_for_file_access(),
1621 errmsg("could not fsync two-phase state file: %m")));
1623 pgstat_report_wait_end();
1625 if (CloseTransientFile(fd) != 0)
1627 (errcode_for_file_access(),
1628 errmsg("could not close two-phase state file: %m")));
1632 * CheckPointTwoPhase -- handle 2PC component of checkpointing.
1634 * We must fsync the state file of any GXACT that is valid or has been
1635 * generated during redo and has a PREPARE LSN <= the checkpoint's redo
1636 * horizon. (If the gxact isn't valid yet, has not been generated in
1637 * redo, or has a later LSN, this checkpoint is not responsible for
1640 * This is deliberately run as late as possible in the checkpoint sequence,
1641 * because GXACTs ordinarily have short lifespans, and so it is quite
1642 * possible that GXACTs that were valid at checkpoint start will no longer
1643 * exist if we wait a little bit. With typical checkpoint settings this
1644 * will be about 3 minutes for an online checkpoint, so as a result we
1645 * we expect that there will be no GXACTs that need to be copied to disk.
1647 * If a GXACT remains valid across multiple checkpoints, it will already
1648 * be on disk so we don't bother to repeat that write.
1651 CheckPointTwoPhase(XLogRecPtr redo_horizon)
1654 int serialized_xacts = 0;
1656 if (max_prepared_xacts <= 0)
1657 return; /* nothing to do */
1659 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1662 * We are expecting there to be zero GXACTs that need to be copied to
1663 * disk, so we perform all I/O while holding TwoPhaseStateLock for
1664 * simplicity. This prevents any new xacts from preparing while this
1665 * occurs, which shouldn't be a problem since the presence of long-lived
1666 * prepared xacts indicates the transaction manager isn't active.
1668 * It's also possible to move I/O out of the lock, but on every error we
1669 * should check whether somebody committed our transaction in different
1670 * backend. Let's leave this optimization for future, if somebody will
1671 * spot that this place cause bottleneck.
1673 * Note that it isn't possible for there to be a GXACT with a
1674 * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1675 * because of the efforts with delayChkpt.
1677 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1678 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1681 * Note that we are using gxact not pgxact so this works in recovery
1684 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1686 if ((gxact->valid || gxact->inredo) &&
1688 gxact->prepare_end_lsn <= redo_horizon)
1693 XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1694 RecreateTwoPhaseFile(gxact->xid, buf, len);
1695 gxact->ondisk = true;
1696 gxact->prepare_start_lsn = InvalidXLogRecPtr;
1697 gxact->prepare_end_lsn = InvalidXLogRecPtr;
1702 LWLockRelease(TwoPhaseStateLock);
1705 * Flush unconditionally the parent directory to make any information
1706 * durable on disk. Two-phase files could have been removed and those
1707 * removals need to be made persistent as well as any files newly created
1708 * previously since the last checkpoint.
1710 fsync_fname(TWOPHASE_DIR, true);
1712 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1714 if (log_checkpoints && serialized_xacts > 0)
1716 (errmsg_plural("%u two-phase state file was written "
1717 "for a long-running prepared transaction",
1718 "%u two-phase state files were written "
1719 "for long-running prepared transactions",
1721 serialized_xacts)));
1725 * restoreTwoPhaseData
1727 * Scan pg_twophase and fill TwoPhaseState depending on the on-disk data.
1728 * This is called once at the beginning of recovery, saving any extra
1729 * lookups in the future. Two-phase files that are newer than the
1730 * minimum XID horizon are discarded on the way.
1733 restoreTwoPhaseData(void)
1736 struct dirent *clde;
1738 cldir = AllocateDir(TWOPHASE_DIR);
1739 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1740 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1742 if (strlen(clde->d_name) == 8 &&
1743 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1748 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1750 buf = ProcessTwoPhaseBuffer(xid, InvalidXLogRecPtr,
1751 true, false, false);
1755 PrepareRedoAdd(buf, InvalidXLogRecPtr, InvalidXLogRecPtr);
1758 LWLockRelease(TwoPhaseStateLock);
1763 * PrescanPreparedTransactions
1765 * Scan the shared memory entries of TwoPhaseState and determine the range
1766 * of valid XIDs present. This is run during database startup, after we
1767 * have completed reading WAL. ShmemVariableCache->nextXid has been set to
1768 * one more than the highest XID for which evidence exists in WAL.
1770 * We throw away any prepared xacts with main XID beyond nextXid --- if any
1771 * are present, it suggests that the DBA has done a PITR recovery to an
1772 * earlier point in time without cleaning out pg_twophase. We dare not
1773 * try to recover such prepared xacts since they likely depend on database
1774 * state that doesn't exist now.
1776 * However, we will advance nextXid beyond any subxact XIDs belonging to
1777 * valid prepared xacts. We need to do this since subxact commit doesn't
1778 * write a WAL entry, and so there might be no evidence in WAL of those
1781 * Our other responsibility is to determine and return the oldest valid XID
1782 * among the prepared xacts (if none, return ShmemVariableCache->nextXid).
1783 * This is needed to synchronize pg_subtrans startup properly.
1785 * If xids_p and nxids_p are not NULL, pointer to a palloc'd array of all
1786 * top-level xids is stored in *xids_p. The number of entries in the array
1787 * is returned in *nxids_p.
1790 PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
1792 TransactionId origNextXid = ShmemVariableCache->nextXid;
1793 TransactionId result = origNextXid;
1794 TransactionId *xids = NULL;
1799 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1800 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1804 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1806 Assert(gxact->inredo);
1810 buf = ProcessTwoPhaseBuffer(xid,
1811 gxact->prepare_start_lsn,
1812 gxact->ondisk, false, true);
1818 * OK, we think this file is valid. Incorporate xid into the
1819 * running-minimum result.
1821 if (TransactionIdPrecedes(xid, result))
1826 if (nxids == allocsize)
1831 xids = palloc(allocsize * sizeof(TransactionId));
1835 allocsize = allocsize * 2;
1836 xids = repalloc(xids, allocsize * sizeof(TransactionId));
1839 xids[nxids++] = xid;
1844 LWLockRelease(TwoPhaseStateLock);
1856 * StandbyRecoverPreparedTransactions
1858 * Scan the shared memory entries of TwoPhaseState and setup all the required
1859 * information to allow standby queries to treat prepared transactions as still
1862 * This is never called at the end of recovery - we use
1863 * RecoverPreparedTransactions() at that point.
1865 * The lack of calls to SubTransSetParent() calls here is by design;
1866 * those calls are made by RecoverPreparedTransactions() at the end of recovery
1867 * for those xacts that need this.
1870 StandbyRecoverPreparedTransactions(void)
1874 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1875 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1879 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1881 Assert(gxact->inredo);
1885 buf = ProcessTwoPhaseBuffer(xid,
1886 gxact->prepare_start_lsn,
1887 gxact->ondisk, false, false);
1891 LWLockRelease(TwoPhaseStateLock);
1895 * RecoverPreparedTransactions
1897 * Scan the shared memory entries of TwoPhaseState and reload the state for
1898 * each prepared transaction (reacquire locks, etc).
1900 * This is run at the end of recovery, but before we allow backends to write
1903 * At the end of recovery the way we take snapshots will change. We now need
1904 * to mark all running transactions with their full SubTransSetParent() info
1905 * to allow normal snapshots to work correctly if snapshots overflow.
1906 * We do this here because by definition prepared transactions are the only
1907 * type of write transaction still running, so this is necessary and
1911 RecoverPreparedTransactions(void)
1915 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1916 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1920 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1922 TwoPhaseFileHeader *hdr;
1923 TransactionId *subxids;
1929 * Reconstruct subtrans state for the transaction --- needed because
1930 * pg_subtrans is not preserved over a restart. Note that we are
1931 * linking all the subtransactions directly to the top-level XID;
1932 * there may originally have been a more complex hierarchy, but
1933 * there's no need to restore that exactly. It's possible that
1934 * SubTransSetParent has been set before, if the prepared transaction
1935 * generated xid assignment records.
1937 buf = ProcessTwoPhaseBuffer(xid,
1938 gxact->prepare_start_lsn,
1939 gxact->ondisk, true, false);
1944 (errmsg("recovering prepared transaction %u from shared memory", xid)));
1946 hdr = (TwoPhaseFileHeader *) buf;
1947 Assert(TransactionIdEquals(hdr->xid, xid));
1948 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1949 gid = (const char *) bufptr;
1950 bufptr += MAXALIGN(hdr->gidlen);
1951 subxids = (TransactionId *) bufptr;
1952 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1953 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1954 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1955 bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1958 * Recreate its GXACT and dummy PGPROC. But, check whether it was
1959 * added in redo and already has a shmem entry for it.
1961 MarkAsPreparingGuts(gxact, xid, gid,
1963 hdr->owner, hdr->database);
1965 /* recovered, so reset the flag for entries generated by redo */
1966 gxact->inredo = false;
1968 GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1969 MarkAsPrepared(gxact, true);
1971 LWLockRelease(TwoPhaseStateLock);
1974 * Recover other state (notably locks) using resource managers.
1976 ProcessRecords(bufptr, xid, twophase_recover_callbacks);
1979 * Release locks held by the standby process after we process each
1980 * prepared transaction. As a result, we don't need too many
1981 * additional locks at any one time.
1984 StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
1987 * We're done with recovering this transaction. Clear MyLockedGxact,
1988 * like we do in PrepareTransaction() during normal operation.
1990 PostPrepare_Twophase();
1994 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1997 LWLockRelease(TwoPhaseStateLock);
2001 * ProcessTwoPhaseBuffer
2003 * Given a transaction id, read it either from disk or read it directly
2004 * via shmem xlog record pointer using the provided "prepare_start_lsn".
2006 * If setParent is true, set up subtransaction parent linkages.
2008 * If setNextXid is true, set ShmemVariableCache->nextXid to the newest
2012 ProcessTwoPhaseBuffer(TransactionId xid,
2013 XLogRecPtr prepare_start_lsn,
2015 bool setParent, bool setNextXid)
2017 TransactionId origNextXid = ShmemVariableCache->nextXid;
2018 TransactionId *subxids;
2020 TwoPhaseFileHeader *hdr;
2023 Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2026 Assert(prepare_start_lsn != InvalidXLogRecPtr);
2028 /* Already processed? */
2029 if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
2034 (errmsg("removing stale two-phase state file for \"%u\"",
2036 RemoveTwoPhaseFile(xid, true);
2041 (errmsg("removing stale two-phase state from shared memory for \"%u\"",
2043 PrepareRedoRemove(xid, true);
2048 /* Reject XID if too new */
2049 if (TransactionIdFollowsOrEquals(xid, origNextXid))
2054 (errmsg("removing future two-phase state file for \"%u\"",
2056 RemoveTwoPhaseFile(xid, true);
2061 (errmsg("removing future two-phase state from memory for \"%u\"",
2063 PrepareRedoRemove(xid, true);
2070 /* Read and validate file */
2071 buf = ReadTwoPhaseFile(xid, true);
2075 (errmsg("removing corrupt two-phase state file for \"%u\"",
2077 RemoveTwoPhaseFile(xid, true);
2083 /* Read xlog data */
2084 XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2087 /* Deconstruct header */
2088 hdr = (TwoPhaseFileHeader *) buf;
2089 if (!TransactionIdEquals(hdr->xid, xid))
2094 (errmsg("removing corrupt two-phase state file for \"%u\"",
2096 RemoveTwoPhaseFile(xid, true);
2101 (errmsg("removing corrupt two-phase state from memory for \"%u\"",
2103 PrepareRedoRemove(xid, true);
2110 * Examine subtransaction XIDs ... they should all follow main XID, and
2111 * they may force us to advance nextXid.
2113 subxids = (TransactionId *) (buf +
2114 MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2115 MAXALIGN(hdr->gidlen));
2116 for (i = 0; i < hdr->nsubxacts; i++)
2118 TransactionId subxid = subxids[i];
2120 Assert(TransactionIdFollows(subxid, xid));
2122 /* update nextXid if needed */
2124 TransactionIdFollowsOrEquals(subxid,
2125 ShmemVariableCache->nextXid))
2128 * We don't expect anyone else to modify nextXid, hence we don't
2129 * need to hold a lock while examining it. We still acquire the
2130 * lock to modify it, though, so we recheck.
2132 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
2133 if (TransactionIdFollowsOrEquals(subxid,
2134 ShmemVariableCache->nextXid))
2136 ShmemVariableCache->nextXid = subxid;
2137 TransactionIdAdvance(ShmemVariableCache->nextXid);
2139 LWLockRelease(XidGenLock);
2143 SubTransSetParent(subxid, xid);
2151 * RecordTransactionCommitPrepared
2153 * This is basically the same as RecordTransactionCommit (q.v. if you change
2154 * this function): in particular, we must set the delayChkpt flag to avoid a
2157 * We know the transaction made at least one XLOG entry (its PREPARE),
2158 * so it is never possible to optimize out the commit record.
2161 RecordTransactionCommitPrepared(TransactionId xid,
2163 TransactionId *children,
2167 SharedInvalidationMessage *invalmsgs,
2171 TimestampTz committs = GetCurrentTimestamp();
2175 * Are we using the replication origins feature? Or, in other words, are
2176 * we replaying remote actions?
2178 replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2179 replorigin_session_origin != DoNotReplicateId);
2181 START_CRIT_SECTION();
2183 /* See notes in RecordTransactionCommit */
2184 MyPgXact->delayChkpt = true;
2187 * Emit the XLOG commit record. Note that we mark 2PC commits as
2188 * potentially having AccessExclusiveLocks since we don't know whether or
2191 recptr = XactLogCommitRecord(committs,
2192 nchildren, children, nrels, rels,
2193 ninvalmsgs, invalmsgs,
2194 initfileinval, false,
2195 MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK,
2200 /* Move LSNs forward for this replication origin */
2201 replorigin_session_advance(replorigin_session_origin_lsn,
2205 * Record commit timestamp. The value comes from plain commit timestamp
2206 * if replorigin is not enabled, or replorigin already set a value for us
2207 * in replorigin_session_origin_timestamp otherwise.
2209 * We don't need to WAL-log anything here, as the commit record written
2210 * above already contains the data.
2212 if (!replorigin || replorigin_session_origin_timestamp == 0)
2213 replorigin_session_origin_timestamp = committs;
2215 TransactionTreeSetCommitTsData(xid, nchildren, children,
2216 replorigin_session_origin_timestamp,
2217 replorigin_session_origin, false);
2220 * We don't currently try to sleep before flush here ... nor is there any
2221 * support for async commit of a prepared xact (the very idea is probably
2225 /* Flush XLOG to disk */
2228 /* Mark the transaction committed in pg_xact */
2229 TransactionIdCommitTree(xid, nchildren, children);
2231 /* Checkpoint can proceed now */
2232 MyPgXact->delayChkpt = false;
2237 * Wait for synchronous replication, if required.
2239 * Note that at this stage we have marked clog, but still show as running
2240 * in the procarray and continue to hold locks.
2242 SyncRepWaitForLSN(recptr, true);
2246 * RecordTransactionAbortPrepared
2248 * This is basically the same as RecordTransactionAbort.
2250 * We know the transaction made at least one XLOG entry (its PREPARE),
2251 * so it is never possible to optimize out the abort record.
2254 RecordTransactionAbortPrepared(TransactionId xid,
2256 TransactionId *children,
2263 * Catch the scenario where we aborted partway through
2264 * RecordTransactionCommitPrepared ...
2266 if (TransactionIdDidCommit(xid))
2267 elog(PANIC, "cannot abort transaction %u, it was already committed",
2270 START_CRIT_SECTION();
2273 * Emit the XLOG commit record. Note that we mark 2PC aborts as
2274 * potentially having AccessExclusiveLocks since we don't know whether or
2277 recptr = XactLogAbortRecord(GetCurrentTimestamp(),
2278 nchildren, children,
2280 MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK,
2283 /* Always flush, since we're about to remove the 2PC state file */
2287 * Mark the transaction aborted in clog. This is not absolutely necessary
2288 * but we may as well do it while we are here.
2290 TransactionIdAbortTree(xid, nchildren, children);
2295 * Wait for synchronous replication, if required.
2297 * Note that at this stage we have marked clog, but still show as running
2298 * in the procarray and continue to hold locks.
2300 SyncRepWaitForLSN(recptr, false);
2306 * Store pointers to the start/end of the WAL record along with the xid in
2307 * a gxact entry in shared memory TwoPhaseState structure. If caller
2308 * specifies InvalidXLogRecPtr as WAL location to fetch the two-phase
2309 * data, the entry is marked as located on disk.
2312 PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
2314 TwoPhaseFileHeader *hdr = (TwoPhaseFileHeader *) buf;
2317 GlobalTransaction gxact;
2319 Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2320 Assert(RecoveryInProgress());
2322 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2323 gid = (const char *) bufptr;
2326 * Reserve the GID for the given transaction in the redo code path.
2328 * This creates a gxact struct and puts it into the active array.
2330 * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2331 * shared memory. Hence, we only fill up the bare minimum contents here.
2332 * The gxact also gets marked with gxact->inredo set to true to indicate
2333 * that it got added in the redo phase
2336 /* Get a free gxact from the freelist */
2337 if (TwoPhaseState->freeGXacts == NULL)
2339 (errcode(ERRCODE_OUT_OF_MEMORY),
2340 errmsg("maximum number of prepared transactions reached"),
2341 errhint("Increase max_prepared_transactions (currently %d).",
2342 max_prepared_xacts)));
2343 gxact = TwoPhaseState->freeGXacts;
2344 TwoPhaseState->freeGXacts = gxact->next;
2346 gxact->prepared_at = hdr->prepared_at;
2347 gxact->prepare_start_lsn = start_lsn;
2348 gxact->prepare_end_lsn = end_lsn;
2349 gxact->xid = hdr->xid;
2350 gxact->owner = hdr->owner;
2351 gxact->locking_backend = InvalidBackendId;
2352 gxact->valid = false;
2353 gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2354 gxact->inredo = true; /* yes, added in redo */
2355 strcpy(gxact->gid, gid);
2357 /* And insert it into the active array */
2358 Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
2359 TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
2361 elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2367 * Remove the corresponding gxact entry from TwoPhaseState. Also remove
2368 * the 2PC file if a prepared transaction was saved via an earlier checkpoint.
2370 * Caller must hold TwoPhaseStateLock in exclusive mode, because TwoPhaseState
2374 PrepareRedoRemove(TransactionId xid, bool giveWarning)
2376 GlobalTransaction gxact = NULL;
2380 Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2381 Assert(RecoveryInProgress());
2383 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2385 gxact = TwoPhaseState->prepXacts[i];
2387 if (gxact->xid == xid)
2389 Assert(gxact->inredo);
2396 * Just leave if there is nothing, this is expected during WAL replay.
2402 * And now we can clean up any files we may have left.
2404 elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2406 RemoveTwoPhaseFile(xid, giveWarning);