1 /*-------------------------------------------------------------------------
4 * Two-phase commit support functions.
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * $PostgreSQL: pgsql/src/backend/access/transam/twophase.c,v 1.57 2009/12/19 01:32:33 sriggs Exp $
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 a dummy PGPROC that is entered
25 * into the ProcArray array; this is what keeps the XID considered
26 * running by TransactionIdIsInProgress. It is also convenient as a
27 * PGPROC to hook the gxact's locks to.
29 * In order to survive crashes and shutdowns, all prepared
30 * transactions must be stored in permanent storage. This includes
31 * locking information, pending notifications etc. All that state
32 * information is written to the per-transaction state file in
33 * the pg_twophase directory.
35 *-------------------------------------------------------------------------
41 #include <sys/types.h>
45 #include "access/htup.h"
46 #include "access/subtrans.h"
47 #include "access/transam.h"
48 #include "access/twophase.h"
49 #include "access/twophase_rmgr.h"
50 #include "access/xact.h"
51 #include "access/xlogutils.h"
52 #include "catalog/pg_type.h"
53 #include "catalog/storage.h"
55 #include "miscadmin.h"
58 #include "storage/fd.h"
59 #include "storage/procarray.h"
60 #include "storage/sinvaladt.h"
61 #include "storage/smgr.h"
62 #include "utils/builtins.h"
63 #include "utils/memutils.h"
67 * Directory where Two-phase commit files reside within PGDATA
69 #define TWOPHASE_DIR "pg_twophase"
71 /* GUC variable, can't be changed after startup */
72 int max_prepared_xacts = 0;
75 * This struct describes one global transaction that is in prepared state
76 * or attempting to become prepared.
78 * The first component of the struct is a dummy PGPROC that is inserted
79 * into the global ProcArray so that the transaction appears to still be
80 * running and holding locks. It must be first because we cast pointers
81 * to PGPROC and pointers to GlobalTransactionData back and forth.
83 * The lifecycle of a global transaction is:
85 * 1. After checking that the requested GID is not in use, set up an
86 * entry in the TwoPhaseState->prepXacts array with the correct XID and GID,
87 * with locking_xid = my own XID and valid = false.
89 * 2. After successfully completing prepare, set valid = true and enter the
90 * contained PGPROC into the global ProcArray.
92 * 3. To begin COMMIT PREPARED or ROLLBACK PREPARED, check that the entry
93 * is valid and its locking_xid is no longer active, then store my current
94 * XID into locking_xid. This prevents concurrent attempts to commit or
95 * rollback the same prepared xact.
97 * 4. On completion of COMMIT PREPARED or ROLLBACK PREPARED, remove the entry
98 * from the ProcArray and the TwoPhaseState->prepXacts array and return it to
101 * Note that if the preparing transaction fails between steps 1 and 2, the
102 * entry will remain in prepXacts until recycled. We can detect recyclable
103 * entries by checking for valid = false and locking_xid no longer active.
105 * typedef struct GlobalTransactionData *GlobalTransaction appears in
110 typedef struct GlobalTransactionData
112 PGPROC proc; /* dummy proc */
113 BackendId dummyBackendId; /* similar to backend id for backends */
114 TimestampTz prepared_at; /* time of preparation */
115 XLogRecPtr prepare_lsn; /* XLOG offset of prepare record */
116 Oid owner; /* ID of user that executed the xact */
117 TransactionId locking_xid; /* top-level XID of backend working on xact */
118 bool valid; /* TRUE if fully prepared */
119 char gid[GIDSIZE]; /* The GID assigned to the prepared xact */
120 } GlobalTransactionData;
123 * Two Phase Commit shared state. Access to this struct is protected
124 * by TwoPhaseStateLock.
126 typedef struct TwoPhaseStateData
128 /* Head of linked list of free GlobalTransactionData structs */
129 GlobalTransaction freeGXacts;
131 /* Number of valid prepXacts entries. */
135 * There are max_prepared_xacts items in this array, but C wants a
138 GlobalTransaction prepXacts[1]; /* VARIABLE LENGTH ARRAY */
139 } TwoPhaseStateData; /* VARIABLE LENGTH STRUCT */
141 static TwoPhaseStateData *TwoPhaseState;
144 static void RecordTransactionCommitPrepared(TransactionId xid,
146 TransactionId *children,
150 SharedInvalidationMessage *invalmsgs,
152 static void RecordTransactionAbortPrepared(TransactionId xid,
154 TransactionId *children,
157 static void ProcessRecords(char *bufptr, TransactionId xid,
158 const TwoPhaseCallback callbacks[]);
162 * Initialization of shared memory
165 TwoPhaseShmemSize(void)
169 /* Need the fixed struct, the array of pointers, and the GTD structs */
170 size = offsetof(TwoPhaseStateData, prepXacts);
171 size = add_size(size, mul_size(max_prepared_xacts,
172 sizeof(GlobalTransaction)));
173 size = MAXALIGN(size);
174 size = add_size(size, mul_size(max_prepared_xacts,
175 sizeof(GlobalTransactionData)));
181 TwoPhaseShmemInit(void)
185 TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
188 if (!IsUnderPostmaster)
190 GlobalTransaction gxacts;
194 TwoPhaseState->freeGXacts = NULL;
195 TwoPhaseState->numPrepXacts = 0;
198 * Initialize the linked list of free GlobalTransactionData structs
200 gxacts = (GlobalTransaction)
201 ((char *) TwoPhaseState +
202 MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
203 sizeof(GlobalTransaction) * max_prepared_xacts));
204 for (i = 0; i < max_prepared_xacts; i++)
206 gxacts[i].proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
207 TwoPhaseState->freeGXacts = &gxacts[i];
210 * Assign a unique ID for each dummy proc, so that the range of
211 * dummy backend IDs immediately follows the range of normal
212 * backend IDs. We don't dare to assign a real backend ID to
213 * dummy procs, because prepared transactions don't take part in
214 * cache invalidation like a real backend ID would imply, but
215 * having a unique ID for them is nevertheless handy. This
216 * arrangement allows you to allocate an array of size
217 * (MaxBackends + max_prepared_xacts + 1), and have a slot for
218 * every backend and prepared transaction. Currently multixact.c
219 * uses that technique.
221 gxacts[i].dummyBackendId = MaxBackends + 1 + i;
231 * Reserve the GID for the given transaction.
233 * Internally, this creates a gxact struct and puts it into the active array.
234 * NOTE: this is also used when reloading a gxact after a crash; so avoid
235 * assuming that we can use very much backend context.
238 MarkAsPreparing(TransactionId xid, const char *gid,
239 TimestampTz prepared_at, Oid owner, Oid databaseid)
241 GlobalTransaction gxact;
244 if (strlen(gid) >= GIDSIZE)
246 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
247 errmsg("transaction identifier \"%s\" is too long",
250 /* fail immediately if feature is disabled */
251 if (max_prepared_xacts == 0)
253 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
254 errmsg("prepared transactions are disabled"),
255 errhint("Set max_prepared_transactions to a nonzero value.")));
257 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
260 * First, find and recycle any gxacts that failed during prepare. We do
261 * this partly to ensure we don't mistakenly say their GIDs are still
262 * reserved, and partly so we don't fail on out-of-slots unnecessarily.
264 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
266 gxact = TwoPhaseState->prepXacts[i];
267 if (!gxact->valid && !TransactionIdIsActive(gxact->locking_xid))
269 /* It's dead Jim ... remove from the active array */
270 TwoPhaseState->numPrepXacts--;
271 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
272 /* and put it back in the freelist */
273 gxact->proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
274 TwoPhaseState->freeGXacts = gxact;
275 /* Back up index count too, so we don't miss scanning one */
280 /* Check for conflicting GID */
281 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
283 gxact = TwoPhaseState->prepXacts[i];
284 if (strcmp(gxact->gid, gid) == 0)
287 (errcode(ERRCODE_DUPLICATE_OBJECT),
288 errmsg("transaction identifier \"%s\" is already in use",
293 /* Get a free gxact from the freelist */
294 if (TwoPhaseState->freeGXacts == NULL)
296 (errcode(ERRCODE_OUT_OF_MEMORY),
297 errmsg("maximum number of prepared transactions reached"),
298 errhint("Increase max_prepared_transactions (currently %d).",
299 max_prepared_xacts)));
300 gxact = TwoPhaseState->freeGXacts;
301 TwoPhaseState->freeGXacts = (GlobalTransaction) gxact->proc.links.next;
304 MemSet(&gxact->proc, 0, sizeof(PGPROC));
305 SHMQueueElemInit(&(gxact->proc.links));
306 gxact->proc.waitStatus = STATUS_OK;
307 /* We set up the gxact's VXID as InvalidBackendId/XID */
308 gxact->proc.lxid = (LocalTransactionId) xid;
309 gxact->proc.xid = xid;
310 gxact->proc.xmin = InvalidTransactionId;
312 gxact->proc.backendId = InvalidBackendId;
313 gxact->proc.databaseId = databaseid;
314 gxact->proc.roleId = owner;
315 gxact->proc.inCommit = false;
316 gxact->proc.vacuumFlags = 0;
317 gxact->proc.lwWaiting = false;
318 gxact->proc.lwExclusive = false;
319 gxact->proc.lwWaitLink = NULL;
320 gxact->proc.waitLock = NULL;
321 gxact->proc.waitProcLock = NULL;
322 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
323 SHMQueueInit(&(gxact->proc.myProcLocks[i]));
324 /* subxid data must be filled later by GXactLoadSubxactData */
325 gxact->proc.subxids.overflowed = false;
326 gxact->proc.subxids.nxids = 0;
328 gxact->prepared_at = prepared_at;
329 /* initialize LSN to 0 (start of WAL) */
330 gxact->prepare_lsn.xlogid = 0;
331 gxact->prepare_lsn.xrecoff = 0;
332 gxact->owner = owner;
333 gxact->locking_xid = xid;
334 gxact->valid = false;
335 strcpy(gxact->gid, gid);
337 /* And insert it into the active array */
338 Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
339 TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
341 LWLockRelease(TwoPhaseStateLock);
347 * GXactLoadSubxactData
349 * If the transaction being persisted had any subtransactions, this must
350 * be called before MarkAsPrepared() to load information into the dummy
354 GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts,
355 TransactionId *children)
357 /* We need no extra lock since the GXACT isn't valid yet */
358 if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
360 gxact->proc.subxids.overflowed = true;
361 nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
365 memcpy(gxact->proc.subxids.xids, children,
366 nsubxacts * sizeof(TransactionId));
367 gxact->proc.subxids.nxids = nsubxacts;
373 * Mark the GXACT as fully valid, and enter it into the global ProcArray.
376 MarkAsPrepared(GlobalTransaction gxact)
378 /* Lock here may be overkill, but I'm not convinced of that ... */
379 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
380 Assert(!gxact->valid);
382 LWLockRelease(TwoPhaseStateLock);
385 * Put it into the global ProcArray so TransactionIdIsInProgress considers
386 * the XID as still running.
388 ProcArrayAdd(&gxact->proc);
393 * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
395 static GlobalTransaction
396 LockGXact(const char *gid, Oid user)
400 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
402 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
404 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
406 /* Ignore not-yet-valid GIDs */
409 if (strcmp(gxact->gid, gid) != 0)
412 /* Found it, but has someone else got it locked? */
413 if (TransactionIdIsValid(gxact->locking_xid))
415 if (TransactionIdIsActive(gxact->locking_xid))
417 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
418 errmsg("prepared transaction with identifier \"%s\" is busy",
420 gxact->locking_xid = InvalidTransactionId;
423 if (user != gxact->owner && !superuser_arg(user))
425 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
426 errmsg("permission denied to finish prepared transaction"),
427 errhint("Must be superuser or the user that prepared the transaction.")));
430 * Note: it probably would be possible to allow committing from
431 * another database; but at the moment NOTIFY is known not to work and
432 * there may be some other issues as well. Hence disallow until
433 * someone gets motivated to make it work.
435 if (MyDatabaseId != gxact->proc.databaseId)
437 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
438 errmsg("prepared transaction belongs to another database"),
439 errhint("Connect to the database where the transaction was prepared to finish it.")));
441 /* OK for me to lock it */
442 gxact->locking_xid = GetTopTransactionId();
444 LWLockRelease(TwoPhaseStateLock);
449 LWLockRelease(TwoPhaseStateLock);
452 (errcode(ERRCODE_UNDEFINED_OBJECT),
453 errmsg("prepared transaction with identifier \"%s\" does not exist",
462 * Remove the prepared transaction from the shared memory array.
464 * NB: caller should have already removed it from ProcArray
467 RemoveGXact(GlobalTransaction gxact)
471 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
473 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
475 if (gxact == TwoPhaseState->prepXacts[i])
477 /* remove from the active array */
478 TwoPhaseState->numPrepXacts--;
479 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
481 /* and put it back in the freelist */
482 gxact->proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
483 TwoPhaseState->freeGXacts = gxact;
485 LWLockRelease(TwoPhaseStateLock);
491 LWLockRelease(TwoPhaseStateLock);
493 elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
497 * TransactionIdIsPrepared
498 * True iff transaction associated with the identifier is prepared
499 * for two-phase commit
501 * Note: only gxacts marked "valid" are considered; but notice we do not
502 * check the locking status.
504 * This is not currently exported, because it is only needed internally.
507 TransactionIdIsPrepared(TransactionId xid)
512 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
514 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
516 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
518 if (gxact->valid && gxact->proc.xid == xid)
525 LWLockRelease(TwoPhaseStateLock);
531 * Returns an array of all prepared transactions for the user-level
532 * function pg_prepared_xact.
534 * The returned array and all its elements are copies of internal data
535 * structures, to minimize the time we need to hold the TwoPhaseStateLock.
537 * WARNING -- we return even those transactions that are not fully prepared
538 * yet. The caller should filter them out if he doesn't want them.
540 * The returned array is palloc'd.
543 GetPreparedTransactionList(GlobalTransaction *gxacts)
545 GlobalTransaction array;
549 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
551 if (TwoPhaseState->numPrepXacts == 0)
553 LWLockRelease(TwoPhaseStateLock);
559 num = TwoPhaseState->numPrepXacts;
560 array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
562 for (i = 0; i < num; i++)
563 memcpy(array + i, TwoPhaseState->prepXacts[i],
564 sizeof(GlobalTransactionData));
566 LWLockRelease(TwoPhaseStateLock);
572 /* Working status for pg_prepared_xact */
575 GlobalTransaction array;
582 * Produce a view with one row per prepared transaction.
584 * This function is here so we don't have to export the
585 * GlobalTransactionData struct definition.
588 pg_prepared_xact(PG_FUNCTION_ARGS)
590 FuncCallContext *funcctx;
591 Working_State *status;
593 if (SRF_IS_FIRSTCALL())
596 MemoryContext oldcontext;
598 /* create a function context for cross-call persistence */
599 funcctx = SRF_FIRSTCALL_INIT();
602 * Switch to memory context appropriate for multiple function calls
604 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
606 /* build tupdesc for result tuples */
607 /* this had better match pg_prepared_xacts view in system_views.sql */
608 tupdesc = CreateTemplateTupleDesc(5, false);
609 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
611 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
613 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
614 TIMESTAMPTZOID, -1, 0);
615 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
617 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
620 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
623 * Collect all the 2PC status information that we will format and send
624 * out as a result set.
626 status = (Working_State *) palloc(sizeof(Working_State));
627 funcctx->user_fctx = (void *) status;
629 status->ngxacts = GetPreparedTransactionList(&status->array);
632 MemoryContextSwitchTo(oldcontext);
635 funcctx = SRF_PERCALL_SETUP();
636 status = (Working_State *) funcctx->user_fctx;
638 while (status->array != NULL && status->currIdx < status->ngxacts)
640 GlobalTransaction gxact = &status->array[status->currIdx++];
650 * Form tuple with appropriate data.
652 MemSet(values, 0, sizeof(values));
653 MemSet(nulls, 0, sizeof(nulls));
655 values[0] = TransactionIdGetDatum(gxact->proc.xid);
656 values[1] = CStringGetTextDatum(gxact->gid);
657 values[2] = TimestampTzGetDatum(gxact->prepared_at);
658 values[3] = ObjectIdGetDatum(gxact->owner);
659 values[4] = ObjectIdGetDatum(gxact->proc.databaseId);
661 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
662 result = HeapTupleGetDatum(tuple);
663 SRF_RETURN_NEXT(funcctx, result);
666 SRF_RETURN_DONE(funcctx);
670 * TwoPhaseGetDummyProc
671 * Get the dummy backend ID for prepared transaction specified by XID
673 * Dummy backend IDs are similar to real backend IDs of real backends.
674 * They start at MaxBackends + 1, and are unique across all currently active
675 * real backends and prepared transactions.
678 TwoPhaseGetDummyBackendId(TransactionId xid)
680 PGPROC *proc = TwoPhaseGetDummyProc(xid);
682 return ((GlobalTransaction) proc)->dummyBackendId;
686 * TwoPhaseGetDummyProc
687 * Get the PGPROC that represents a prepared transaction specified by XID
690 TwoPhaseGetDummyProc(TransactionId xid)
692 PGPROC *result = NULL;
695 static TransactionId cached_xid = InvalidTransactionId;
696 static PGPROC *cached_proc = NULL;
699 * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
700 * repeatedly for the same XID. We can save work with a simple cache.
702 if (xid == cached_xid)
705 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
707 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
709 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
711 if (gxact->proc.xid == xid)
713 result = &gxact->proc;
718 LWLockRelease(TwoPhaseStateLock);
720 if (result == NULL) /* should not happen */
721 elog(ERROR, "failed to find dummy PGPROC for xid %u", xid);
724 cached_proc = result;
729 /************************************************************************/
730 /* State file support */
731 /************************************************************************/
733 #define TwoPhaseFilePath(path, xid) \
734 snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
737 * 2PC state file format:
739 * 1. TwoPhaseFileHeader
740 * 2. TransactionId[] (subtransactions)
741 * 3. RelFileNode[] (files to be deleted at commit)
742 * 4. RelFileNode[] (files to be deleted at abort)
743 * 5. SharedInvalidationMessage[] (inval messages to be sent at commit)
744 * 6. TwoPhaseRecordOnDisk
746 * 8. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
749 * Each segment except the final CRC32 is MAXALIGN'd.
753 * Header for a 2PC state file
755 #define TWOPHASE_MAGIC 0x57F94532 /* format identifier */
757 typedef struct TwoPhaseFileHeader
759 uint32 magic; /* format identifier */
760 uint32 total_len; /* actual file length */
761 TransactionId xid; /* original transaction XID */
762 Oid database; /* OID of database it was in */
763 TimestampTz prepared_at; /* time of preparation */
764 Oid owner; /* user running the transaction */
765 int32 nsubxacts; /* number of following subxact XIDs */
766 int32 ncommitrels; /* number of delete-on-commit rels */
767 int32 nabortrels; /* number of delete-on-abort rels */
768 int32 ninvalmsgs; /* number of cache invalidation messages */
769 bool initfileinval; /* does relcache init file need invalidation? */
770 char gid[GIDSIZE]; /* GID for transaction */
771 } TwoPhaseFileHeader;
774 * Header for each record in a state file
776 * NOTE: len counts only the rmgr data, not the TwoPhaseRecordOnDisk header.
777 * The rmgr data will be stored starting on a MAXALIGN boundary.
779 typedef struct TwoPhaseRecordOnDisk
781 uint32 len; /* length of rmgr data */
782 TwoPhaseRmgrId rmid; /* resource manager for this record */
783 uint16 info; /* flag bits for use by rmgr */
784 } TwoPhaseRecordOnDisk;
787 * During prepare, the state file is assembled in memory before writing it
788 * to WAL and the actual state file. We use a chain of XLogRecData blocks
789 * so that we will be able to pass the state file contents directly to
794 XLogRecData *head; /* first data block in the chain */
795 XLogRecData *tail; /* last block in chain */
796 uint32 bytes_free; /* free bytes left in tail block */
797 uint32 total_len; /* total data bytes in chain */
802 * Append a block of data to records data structure.
804 * NB: each block is padded to a MAXALIGN multiple. This must be
805 * accounted for when the file is later read!
807 * The data is copied, so the caller is free to modify it afterwards.
810 save_state_data(const void *data, uint32 len)
812 uint32 padlen = MAXALIGN(len);
814 if (padlen > records.bytes_free)
816 records.tail->next = palloc0(sizeof(XLogRecData));
817 records.tail = records.tail->next;
818 records.tail->buffer = InvalidBuffer;
819 records.tail->len = 0;
820 records.tail->next = NULL;
822 records.bytes_free = Max(padlen, 512);
823 records.tail->data = palloc(records.bytes_free);
826 memcpy(((char *) records.tail->data) + records.tail->len, data, len);
827 records.tail->len += padlen;
828 records.bytes_free -= padlen;
829 records.total_len += padlen;
833 * Start preparing a state file.
835 * Initializes data structure and inserts the 2PC file header record.
838 StartPrepare(GlobalTransaction gxact)
840 TransactionId xid = gxact->proc.xid;
841 TwoPhaseFileHeader hdr;
842 TransactionId *children;
843 RelFileNode *commitrels;
844 RelFileNode *abortrels;
845 SharedInvalidationMessage *invalmsgs;
847 /* Initialize linked list */
848 records.head = palloc0(sizeof(XLogRecData));
849 records.head->buffer = InvalidBuffer;
850 records.head->len = 0;
851 records.head->next = NULL;
853 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
854 records.head->data = palloc(records.bytes_free);
856 records.tail = records.head;
858 records.total_len = 0;
861 hdr.magic = TWOPHASE_MAGIC;
862 hdr.total_len = 0; /* EndPrepare will fill this in */
864 hdr.database = gxact->proc.databaseId;
865 hdr.prepared_at = gxact->prepared_at;
866 hdr.owner = gxact->owner;
867 hdr.nsubxacts = xactGetCommittedChildren(&children);
868 hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels, NULL);
869 hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels, NULL);
870 hdr.ninvalmsgs = xactGetCommittedInvalidationMessages(&invalmsgs,
872 StrNCpy(hdr.gid, gxact->gid, GIDSIZE);
874 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
877 * Add the additional info about subxacts, deletable files and
878 * cache invalidation messages.
880 if (hdr.nsubxacts > 0)
882 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
883 /* While we have the child-xact data, stuff it in the gxact too */
884 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
886 if (hdr.ncommitrels > 0)
888 save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
891 if (hdr.nabortrels > 0)
893 save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
896 if (hdr.ninvalmsgs > 0)
898 save_state_data(invalmsgs,
899 hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
905 * Finish preparing state file.
907 * Calculates CRC and writes state file to WAL and in pg_twophase directory.
910 EndPrepare(GlobalTransaction gxact)
912 TransactionId xid = gxact->proc.xid;
913 TwoPhaseFileHeader *hdr;
914 char path[MAXPGPATH];
916 pg_crc32 statefile_crc;
920 /* Add the end sentinel to the list of 2PC records */
921 RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID, 0,
924 /* Go back and fill in total_len in the file header record */
925 hdr = (TwoPhaseFileHeader *) records.head->data;
926 Assert(hdr->magic == TWOPHASE_MAGIC);
927 hdr->total_len = records.total_len + sizeof(pg_crc32);
930 * If the file size exceeds MaxAllocSize, we won't be able to read it in
931 * ReadTwoPhaseFile. Check for that now, rather than fail at commit time.
933 if (hdr->total_len > MaxAllocSize)
935 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
936 errmsg("two-phase state file maximum length exceeded")));
939 * Create the 2PC state file.
941 * Note: because we use BasicOpenFile(), we are responsible for ensuring
942 * the FD gets closed in any error exit path. Once we get into the
943 * critical section, though, it doesn't matter since any failure causes
946 TwoPhaseFilePath(path, xid);
948 fd = BasicOpenFile(path,
949 O_CREAT | O_EXCL | O_WRONLY | PG_BINARY,
953 (errcode_for_file_access(),
954 errmsg("could not create two-phase state file \"%s\": %m",
957 /* Write data to file, and calculate CRC as we pass over it */
958 INIT_CRC32(statefile_crc);
960 for (record = records.head; record != NULL; record = record->next)
962 COMP_CRC32(statefile_crc, record->data, record->len);
963 if ((write(fd, record->data, record->len)) != record->len)
967 (errcode_for_file_access(),
968 errmsg("could not write two-phase state file: %m")));
972 FIN_CRC32(statefile_crc);
975 * Write a deliberately bogus CRC to the state file; this is just paranoia
976 * to catch the case where four more bytes will run us out of disk space.
978 bogus_crc = ~statefile_crc;
980 if ((write(fd, &bogus_crc, sizeof(pg_crc32))) != sizeof(pg_crc32))
984 (errcode_for_file_access(),
985 errmsg("could not write two-phase state file: %m")));
988 /* Back up to prepare for rewriting the CRC */
989 if (lseek(fd, -((off_t) sizeof(pg_crc32)), SEEK_CUR) < 0)
993 (errcode_for_file_access(),
994 errmsg("could not seek in two-phase state file: %m")));
998 * The state file isn't valid yet, because we haven't written the correct
999 * CRC yet. Before we do that, insert entry in WAL and flush it to disk.
1001 * Between the time we have written the WAL entry and the time we write
1002 * out the correct state file CRC, we have an inconsistency: the xact is
1003 * prepared according to WAL but not according to our on-disk state. We
1004 * use a critical section to force a PANIC if we are unable to complete
1005 * the write --- then, WAL replay should repair the inconsistency. The
1006 * odds of a PANIC actually occurring should be very tiny given that we
1007 * were able to write the bogus CRC above.
1009 * We have to set inCommit here, too; otherwise a checkpoint starting
1010 * immediately after the WAL record is inserted could complete without
1011 * fsync'ing our state file. (This is essentially the same kind of race
1012 * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1013 * uses inCommit for; see notes there.)
1015 * We save the PREPARE record's location in the gxact for later use by
1016 * CheckPointTwoPhase.
1018 START_CRIT_SECTION();
1020 MyProc->inCommit = true;
1022 gxact->prepare_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE,
1024 XLogFlush(gxact->prepare_lsn);
1026 /* If we crash now, we have prepared: WAL replay will fix things */
1028 /* write correct CRC and close file */
1029 if ((write(fd, &statefile_crc, sizeof(pg_crc32))) != sizeof(pg_crc32))
1033 (errcode_for_file_access(),
1034 errmsg("could not write two-phase state file: %m")));
1039 (errcode_for_file_access(),
1040 errmsg("could not close two-phase state file: %m")));
1043 * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
1044 * as not running our XID (which it will do immediately after this
1045 * function returns), others can commit/rollback the xact.
1047 * NB: a side effect of this is to make a dummy ProcArray entry for the
1048 * prepared XID. This must happen before we clear the XID from MyProc,
1049 * else there is a window where the XID is not running according to
1050 * TransactionIdIsInProgress, and onlookers would be entitled to assume
1051 * the xact crashed. Instead we have a window where the same XID appears
1052 * twice in ProcArray, which is OK.
1054 MarkAsPrepared(gxact);
1057 * Now we can mark ourselves as out of the commit critical section: a
1058 * checkpoint starting after this will certainly see the gxact as a
1059 * candidate for fsyncing.
1061 MyProc->inCommit = false;
1065 records.tail = records.head = NULL;
1069 * Register a 2PC record to be written to state file.
1072 RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info,
1073 const void *data, uint32 len)
1075 TwoPhaseRecordOnDisk record;
1080 save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1082 save_state_data(data, len);
1087 * Read and validate the state file for xid.
1089 * If it looks OK (has a valid magic number and CRC), return the palloc'd
1090 * contents of the file. Otherwise return NULL.
1093 ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
1095 char path[MAXPGPATH];
1097 TwoPhaseFileHeader *hdr;
1104 TwoPhaseFilePath(path, xid);
1106 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1111 (errcode_for_file_access(),
1112 errmsg("could not open two-phase state file \"%s\": %m",
1118 * Check file length. We can determine a lower bound pretty easily. We
1119 * set an upper bound to avoid palloc() failure on a corrupt file, though
1120 * we can't guarantee that we won't get an out of memory error anyway,
1121 * even on a valid file.
1123 if (fstat(fd, &stat))
1128 (errcode_for_file_access(),
1129 errmsg("could not stat two-phase state file \"%s\": %m",
1134 if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1135 MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1136 sizeof(pg_crc32)) ||
1137 stat.st_size > MaxAllocSize)
1143 crc_offset = stat.st_size - sizeof(pg_crc32);
1144 if (crc_offset != MAXALIGN(crc_offset))
1151 * OK, slurp in the file.
1153 buf = (char *) palloc(stat.st_size);
1155 if (read(fd, buf, stat.st_size) != stat.st_size)
1160 (errcode_for_file_access(),
1161 errmsg("could not read two-phase state file \"%s\": %m",
1169 hdr = (TwoPhaseFileHeader *) buf;
1170 if (hdr->magic != TWOPHASE_MAGIC || hdr->total_len != stat.st_size)
1176 INIT_CRC32(calc_crc);
1177 COMP_CRC32(calc_crc, buf, crc_offset);
1178 FIN_CRC32(calc_crc);
1180 file_crc = *((pg_crc32 *) (buf + crc_offset));
1182 if (!EQ_CRC32(calc_crc, file_crc))
1192 * Confirms an xid is prepared, during recovery
1195 StandbyTransactionIdIsPrepared(TransactionId xid)
1198 TwoPhaseFileHeader *hdr;
1201 Assert(TransactionIdIsValid(xid));
1203 /* Read and validate file */
1204 buf = ReadTwoPhaseFile(xid, false);
1208 /* Check header also */
1209 hdr = (TwoPhaseFileHeader *) buf;
1210 result = TransactionIdEquals(hdr->xid, xid);
1217 * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1220 FinishPreparedTransaction(const char *gid, bool isCommit)
1222 GlobalTransaction gxact;
1226 TwoPhaseFileHeader *hdr;
1227 TransactionId latestXid;
1228 TransactionId *children;
1229 RelFileNode *commitrels;
1230 RelFileNode *abortrels;
1231 RelFileNode *delrels;
1233 SharedInvalidationMessage *invalmsgs;
1237 * Validate the GID, and lock the GXACT to ensure that two backends do not
1238 * try to commit the same GID at once.
1240 gxact = LockGXact(gid, GetUserId());
1241 xid = gxact->proc.xid;
1244 * Read and validate the state file
1246 buf = ReadTwoPhaseFile(xid, true);
1249 (errcode(ERRCODE_DATA_CORRUPTED),
1250 errmsg("two-phase state file for transaction %u is corrupt",
1254 * Disassemble the header area
1256 hdr = (TwoPhaseFileHeader *) buf;
1257 Assert(TransactionIdEquals(hdr->xid, xid));
1258 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1259 children = (TransactionId *) bufptr;
1260 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1261 commitrels = (RelFileNode *) bufptr;
1262 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1263 abortrels = (RelFileNode *) bufptr;
1264 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1265 invalmsgs = (SharedInvalidationMessage *) bufptr;
1266 bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1268 /* compute latestXid among all children */
1269 latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1272 * The order of operations here is critical: make the XLOG entry for
1273 * commit or abort, then mark the transaction committed or aborted in
1274 * pg_clog, then remove its PGPROC from the global ProcArray (which means
1275 * TransactionIdIsInProgress will stop saying the prepared xact is in
1276 * progress), then run the post-commit or post-abort callbacks. The
1277 * callbacks will release the locks the transaction held.
1280 RecordTransactionCommitPrepared(xid,
1281 hdr->nsubxacts, children,
1282 hdr->ncommitrels, commitrels,
1283 hdr->ninvalmsgs, invalmsgs,
1284 hdr->initfileinval);
1286 RecordTransactionAbortPrepared(xid,
1287 hdr->nsubxacts, children,
1288 hdr->nabortrels, abortrels);
1290 ProcArrayRemove(&gxact->proc, latestXid);
1293 * In case we fail while running the callbacks, mark the gxact invalid so
1294 * no one else will try to commit/rollback, and so it can be recycled
1295 * properly later. It is still locked by our XID so it won't go away yet.
1297 * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1299 gxact->valid = false;
1302 * We have to remove any files that were supposed to be dropped. For
1303 * consistency with the regular xact.c code paths, must do this before
1304 * releasing locks, so do it before running the callbacks.
1306 * NB: this code knows that we couldn't be dropping any temp rels ...
1310 delrels = commitrels;
1311 ndelrels = hdr->ncommitrels;
1315 delrels = abortrels;
1316 ndelrels = hdr->nabortrels;
1318 for (i = 0; i < ndelrels; i++)
1320 SMgrRelation srel = smgropen(delrels[i]);
1323 for (fork = 0; fork <= MAX_FORKNUM; fork++)
1325 if (smgrexists(srel, fork))
1326 smgrdounlink(srel, fork, false, false);
1332 * Handle cache invalidation messages.
1334 * Relcache init file invalidation requires processing both
1335 * before and after we send the SI messages. See AtEOXact_Inval()
1337 if (hdr->initfileinval)
1338 RelationCacheInitFileInvalidate(true);
1339 SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1340 if (hdr->initfileinval)
1341 RelationCacheInitFileInvalidate(false);
1343 /* And now do the callbacks */
1345 ProcessRecords(bufptr, xid, twophase_postcommit_callbacks);
1347 ProcessRecords(bufptr, xid, twophase_postabort_callbacks);
1349 /* Count the prepared xact as committed or aborted */
1350 AtEOXact_PgStat(isCommit);
1353 * And now we can clean up our mess.
1355 RemoveTwoPhaseFile(xid, true);
1363 * Scan a 2PC state file (already read into memory by ReadTwoPhaseFile)
1364 * and call the indicated callbacks for each 2PC record.
1367 ProcessRecords(char *bufptr, TransactionId xid,
1368 const TwoPhaseCallback callbacks[])
1372 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1374 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1375 if (record->rmid == TWOPHASE_RM_END_ID)
1378 bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1380 if (callbacks[record->rmid] != NULL)
1381 callbacks[record->rmid] (xid, record->info,
1382 (void *) bufptr, record->len);
1384 bufptr += MAXALIGN(record->len);
1389 * Remove the 2PC file for the specified XID.
1391 * If giveWarning is false, do not complain about file-not-present;
1392 * this is an expected case during WAL replay.
1395 RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
1397 char path[MAXPGPATH];
1399 TwoPhaseFilePath(path, xid);
1401 if (errno != ENOENT || giveWarning)
1403 (errcode_for_file_access(),
1404 errmsg("could not remove two-phase state file \"%s\": %m",
1409 * Recreates a state file. This is used in WAL replay.
1411 * Note: content and len don't include CRC.
1414 RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
1416 char path[MAXPGPATH];
1417 pg_crc32 statefile_crc;
1421 INIT_CRC32(statefile_crc);
1422 COMP_CRC32(statefile_crc, content, len);
1423 FIN_CRC32(statefile_crc);
1425 TwoPhaseFilePath(path, xid);
1427 fd = BasicOpenFile(path,
1428 O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY,
1432 (errcode_for_file_access(),
1433 errmsg("could not recreate two-phase state file \"%s\": %m",
1436 /* Write content and CRC */
1437 if (write(fd, content, len) != len)
1441 (errcode_for_file_access(),
1442 errmsg("could not write two-phase state file: %m")));
1444 if (write(fd, &statefile_crc, sizeof(pg_crc32)) != sizeof(pg_crc32))
1448 (errcode_for_file_access(),
1449 errmsg("could not write two-phase state file: %m")));
1453 * We must fsync the file because the end-of-replay checkpoint will not do
1454 * so, there being no GXACT in shared memory yet to tell it to.
1456 if (pg_fsync(fd) != 0)
1460 (errcode_for_file_access(),
1461 errmsg("could not fsync two-phase state file: %m")));
1466 (errcode_for_file_access(),
1467 errmsg("could not close two-phase state file: %m")));
1471 * CheckPointTwoPhase -- handle 2PC component of checkpointing.
1473 * We must fsync the state file of any GXACT that is valid and has a PREPARE
1474 * LSN <= the checkpoint's redo horizon. (If the gxact isn't valid yet or
1475 * has a later LSN, this checkpoint is not responsible for fsyncing it.)
1477 * This is deliberately run as late as possible in the checkpoint sequence,
1478 * because GXACTs ordinarily have short lifespans, and so it is quite
1479 * possible that GXACTs that were valid at checkpoint start will no longer
1480 * exist if we wait a little bit.
1482 * If a GXACT remains valid across multiple checkpoints, it'll be fsynced
1483 * each time. This is considered unusual enough that we don't bother to
1484 * expend any extra code to avoid the redundant fsyncs. (They should be
1485 * reasonably cheap anyway, since they won't cause I/O.)
1488 CheckPointTwoPhase(XLogRecPtr redo_horizon)
1490 TransactionId *xids;
1492 char path[MAXPGPATH];
1496 * We don't want to hold the TwoPhaseStateLock while doing I/O, so we grab
1497 * it just long enough to make a list of the XIDs that require fsyncing,
1498 * and then do the I/O afterwards.
1500 * This approach creates a race condition: someone else could delete a
1501 * GXACT between the time we release TwoPhaseStateLock and the time we try
1502 * to open its state file. We handle this by special-casing ENOENT
1503 * failures: if we see that, we verify that the GXACT is no longer valid,
1504 * and if so ignore the failure.
1506 if (max_prepared_xacts <= 0)
1507 return; /* nothing to do */
1509 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1511 xids = (TransactionId *) palloc(max_prepared_xacts * sizeof(TransactionId));
1514 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1516 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1518 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1521 XLByteLE(gxact->prepare_lsn, redo_horizon))
1522 xids[nxids++] = gxact->proc.xid;
1525 LWLockRelease(TwoPhaseStateLock);
1527 for (i = 0; i < nxids; i++)
1529 TransactionId xid = xids[i];
1532 TwoPhaseFilePath(path, xid);
1534 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
1537 if (errno == ENOENT)
1539 /* OK if gxact is no longer valid */
1540 if (!TransactionIdIsPrepared(xid))
1542 /* Restore errno in case it was changed */
1546 (errcode_for_file_access(),
1547 errmsg("could not open two-phase state file \"%s\": %m",
1551 if (pg_fsync(fd) != 0)
1555 (errcode_for_file_access(),
1556 errmsg("could not fsync two-phase state file \"%s\": %m",
1562 (errcode_for_file_access(),
1563 errmsg("could not close two-phase state file \"%s\": %m",
1569 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1573 * PrescanPreparedTransactions
1575 * Scan the pg_twophase directory and determine the range of valid XIDs
1576 * present. This is run during database startup, after we have completed
1577 * reading WAL. ShmemVariableCache->nextXid has been set to one more than
1578 * the highest XID for which evidence exists in WAL.
1580 * We throw away any prepared xacts with main XID beyond nextXid --- if any
1581 * are present, it suggests that the DBA has done a PITR recovery to an
1582 * earlier point in time without cleaning out pg_twophase. We dare not
1583 * try to recover such prepared xacts since they likely depend on database
1584 * state that doesn't exist now.
1586 * However, we will advance nextXid beyond any subxact XIDs belonging to
1587 * valid prepared xacts. We need to do this since subxact commit doesn't
1588 * write a WAL entry, and so there might be no evidence in WAL of those
1591 * Our other responsibility is to determine and return the oldest valid XID
1592 * among the prepared xacts (if none, return ShmemVariableCache->nextXid).
1593 * This is needed to synchronize pg_subtrans startup properly.
1595 * If xids_p and nxids_p are not NULL, pointer to a palloc'd array of all
1596 * top-level xids is stored in *xids_p. The number of entries in the array
1597 * is returned in *nxids_p.
1600 PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
1602 TransactionId origNextXid = ShmemVariableCache->nextXid;
1603 TransactionId result = origNextXid;
1605 struct dirent *clde;
1606 TransactionId *xids = NULL;
1610 cldir = AllocateDir(TWOPHASE_DIR);
1611 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1613 if (strlen(clde->d_name) == 8 &&
1614 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1618 TwoPhaseFileHeader *hdr;
1619 TransactionId *subxids;
1622 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1624 /* Reject XID if too new */
1625 if (TransactionIdFollowsOrEquals(xid, origNextXid))
1628 (errmsg("removing future two-phase state file \"%s\"",
1630 RemoveTwoPhaseFile(xid, true);
1635 * Note: we can't check if already processed because clog
1636 * subsystem isn't up yet.
1639 /* Read and validate file */
1640 buf = ReadTwoPhaseFile(xid, true);
1644 (errmsg("removing corrupt two-phase state file \"%s\"",
1646 RemoveTwoPhaseFile(xid, true);
1650 /* Deconstruct header */
1651 hdr = (TwoPhaseFileHeader *) buf;
1652 if (!TransactionIdEquals(hdr->xid, xid))
1655 (errmsg("removing corrupt two-phase state file \"%s\"",
1657 RemoveTwoPhaseFile(xid, true);
1663 * OK, we think this file is valid. Incorporate xid into the
1664 * running-minimum result.
1666 if (TransactionIdPrecedes(xid, result))
1670 * Examine subtransaction XIDs ... they should all follow main
1671 * XID, and they may force us to advance nextXid.
1673 subxids = (TransactionId *)
1674 (buf + MAXALIGN(sizeof(TwoPhaseFileHeader)));
1675 for (i = 0; i < hdr->nsubxacts; i++)
1677 TransactionId subxid = subxids[i];
1679 Assert(TransactionIdFollows(subxid, xid));
1680 if (TransactionIdFollowsOrEquals(subxid,
1681 ShmemVariableCache->nextXid))
1683 ShmemVariableCache->nextXid = subxid;
1684 TransactionIdAdvance(ShmemVariableCache->nextXid);
1691 if (nxids == allocsize)
1696 xids = palloc(allocsize * sizeof(TransactionId));
1700 allocsize = allocsize * 2;
1701 xids = repalloc(xids, allocsize * sizeof(TransactionId));
1704 xids[nxids++] = xid;
1722 * RecoverPreparedTransactions
1724 * Scan the pg_twophase directory and reload shared-memory state for each
1725 * prepared transaction (reacquire locks, etc). This is run during database
1729 RecoverPreparedTransactions(void)
1731 char dir[MAXPGPATH];
1733 struct dirent *clde;
1734 bool overwriteOK = false;
1736 snprintf(dir, MAXPGPATH, "%s", TWOPHASE_DIR);
1738 cldir = AllocateDir(dir);
1739 while ((clde = ReadDir(cldir, dir)) != NULL)
1741 if (strlen(clde->d_name) == 8 &&
1742 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1747 TwoPhaseFileHeader *hdr;
1748 TransactionId *subxids;
1749 GlobalTransaction gxact;
1752 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1754 /* Already processed? */
1755 if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
1758 (errmsg("removing stale two-phase state file \"%s\"",
1760 RemoveTwoPhaseFile(xid, true);
1764 /* Read and validate file */
1765 buf = ReadTwoPhaseFile(xid, true);
1769 (errmsg("removing corrupt two-phase state file \"%s\"",
1771 RemoveTwoPhaseFile(xid, true);
1776 (errmsg("recovering prepared transaction %u", xid)));
1778 /* Deconstruct header */
1779 hdr = (TwoPhaseFileHeader *) buf;
1780 Assert(TransactionIdEquals(hdr->xid, xid));
1781 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1782 subxids = (TransactionId *) bufptr;
1783 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1784 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1785 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1786 bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1789 * It's possible that SubTransSetParent has been set before, if the
1790 * prepared transaction generated xid assignment records. Test
1791 * here must match one used in AssignTransactionId().
1793 if (InHotStandby && hdr->nsubxacts >= PGPROC_MAX_CACHED_SUBXIDS)
1797 * Reconstruct subtrans state for the transaction --- needed
1798 * because pg_subtrans is not preserved over a restart. Note that
1799 * we are linking all the subtransactions directly to the
1800 * top-level XID; there may originally have been a more complex
1801 * hierarchy, but there's no need to restore that exactly.
1803 for (i = 0; i < hdr->nsubxacts; i++)
1804 SubTransSetParent(subxids[i], xid, overwriteOK);
1807 * Recreate its GXACT and dummy PGPROC
1809 * Note: since we don't have the PREPARE record's WAL location at
1810 * hand, we leave prepare_lsn zeroes. This means the GXACT will
1811 * be fsync'd on every future checkpoint. We assume this
1812 * situation is infrequent enough that the performance cost is
1813 * negligible (especially since we know the state file has already
1816 gxact = MarkAsPreparing(xid, hdr->gid,
1818 hdr->owner, hdr->database);
1819 GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1820 MarkAsPrepared(gxact);
1823 * Recover other state (notably locks) using resource managers
1825 ProcessRecords(bufptr, xid, twophase_recover_callbacks);
1828 * Release locks held by the standby process after we process each
1829 * prepared transaction. As a result, we don't need too many
1830 * additional locks at any one time.
1833 StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
1842 * RecordTransactionCommitPrepared
1844 * This is basically the same as RecordTransactionCommit: in particular,
1845 * we must set the inCommit flag to avoid a race condition.
1847 * We know the transaction made at least one XLOG entry (its PREPARE),
1848 * so it is never possible to optimize out the commit record.
1851 RecordTransactionCommitPrepared(TransactionId xid,
1853 TransactionId *children,
1857 SharedInvalidationMessage *invalmsgs,
1860 XLogRecData rdata[4];
1862 xl_xact_commit_prepared xlrec;
1865 START_CRIT_SECTION();
1867 /* See notes in RecordTransactionCommit */
1868 MyProc->inCommit = true;
1870 /* Emit the XLOG commit record */
1872 xlrec.crec.xact_time = GetCurrentTimestamp();
1873 xlrec.crec.xinfo = initfileinval ? XACT_COMPLETION_UPDATE_RELCACHE_FILE : 0;
1874 xlrec.crec.nmsgs = 0;
1875 xlrec.crec.nrels = nrels;
1876 xlrec.crec.nsubxacts = nchildren;
1877 xlrec.crec.nmsgs = ninvalmsgs;
1879 rdata[0].data = (char *) (&xlrec);
1880 rdata[0].len = MinSizeOfXactCommitPrepared;
1881 rdata[0].buffer = InvalidBuffer;
1882 /* dump rels to delete */
1885 rdata[0].next = &(rdata[1]);
1886 rdata[1].data = (char *) rels;
1887 rdata[1].len = nrels * sizeof(RelFileNode);
1888 rdata[1].buffer = InvalidBuffer;
1891 /* dump committed child Xids */
1894 rdata[lastrdata].next = &(rdata[2]);
1895 rdata[2].data = (char *) children;
1896 rdata[2].len = nchildren * sizeof(TransactionId);
1897 rdata[2].buffer = InvalidBuffer;
1900 /* dump cache invalidation messages */
1903 rdata[lastrdata].next = &(rdata[3]);
1904 rdata[3].data = (char *) invalmsgs;
1905 rdata[3].len = ninvalmsgs * sizeof(SharedInvalidationMessage);
1906 rdata[3].buffer = InvalidBuffer;
1909 rdata[lastrdata].next = NULL;
1911 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT_PREPARED, rdata);
1914 * We don't currently try to sleep before flush here ... nor is there any
1915 * support for async commit of a prepared xact (the very idea is probably
1919 /* Flush XLOG to disk */
1922 /* Mark the transaction committed in pg_clog */
1923 TransactionIdCommitTree(xid, nchildren, children);
1925 /* Checkpoint can proceed now */
1926 MyProc->inCommit = false;
1932 * RecordTransactionAbortPrepared
1934 * This is basically the same as RecordTransactionAbort.
1936 * We know the transaction made at least one XLOG entry (its PREPARE),
1937 * so it is never possible to optimize out the abort record.
1940 RecordTransactionAbortPrepared(TransactionId xid,
1942 TransactionId *children,
1946 XLogRecData rdata[3];
1948 xl_xact_abort_prepared xlrec;
1952 * Catch the scenario where we aborted partway through
1953 * RecordTransactionCommitPrepared ...
1955 if (TransactionIdDidCommit(xid))
1956 elog(PANIC, "cannot abort transaction %u, it was already committed",
1959 START_CRIT_SECTION();
1961 /* Emit the XLOG abort record */
1963 xlrec.arec.xact_time = GetCurrentTimestamp();
1964 xlrec.arec.nrels = nrels;
1965 xlrec.arec.nsubxacts = nchildren;
1966 rdata[0].data = (char *) (&xlrec);
1967 rdata[0].len = MinSizeOfXactAbortPrepared;
1968 rdata[0].buffer = InvalidBuffer;
1969 /* dump rels to delete */
1972 rdata[0].next = &(rdata[1]);
1973 rdata[1].data = (char *) rels;
1974 rdata[1].len = nrels * sizeof(RelFileNode);
1975 rdata[1].buffer = InvalidBuffer;
1978 /* dump committed child Xids */
1981 rdata[lastrdata].next = &(rdata[2]);
1982 rdata[2].data = (char *) children;
1983 rdata[2].len = nchildren * sizeof(TransactionId);
1984 rdata[2].buffer = InvalidBuffer;
1987 rdata[lastrdata].next = NULL;
1989 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT_PREPARED, rdata);
1991 /* Always flush, since we're about to remove the 2PC state file */
1995 * Mark the transaction aborted in clog. This is not absolutely necessary
1996 * but we may as well do it while we are here.
1998 TransactionIdAbortTree(xid, nchildren, children);