1 /*-------------------------------------------------------------------------
4 * Two-phase commit support functions.
6 * Portions Copyright (c) 1996-2011, 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 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 "replication/walsender.h"
59 #include "replication/syncrep.h"
60 #include "storage/fd.h"
61 #include "storage/predicate.h"
62 #include "storage/procarray.h"
63 #include "storage/sinvaladt.h"
64 #include "storage/smgr.h"
65 #include "utils/builtins.h"
66 #include "utils/memutils.h"
70 * Directory where Two-phase commit files reside within PGDATA
72 #define TWOPHASE_DIR "pg_twophase"
74 /* GUC variable, can't be changed after startup */
75 int max_prepared_xacts = 0;
78 * This struct describes one global transaction that is in prepared state
79 * or attempting to become prepared.
81 * The first component of the struct is a dummy PGPROC that is inserted
82 * into the global ProcArray so that the transaction appears to still be
83 * running and holding locks. It must be first because we cast pointers
84 * to PGPROC and pointers to GlobalTransactionData back and forth.
86 * The lifecycle of a global transaction is:
88 * 1. After checking that the requested GID is not in use, set up an
89 * entry in the TwoPhaseState->prepXacts array with the correct XID and GID,
90 * with locking_xid = my own XID and valid = false.
92 * 2. After successfully completing prepare, set valid = true and enter the
93 * contained PGPROC into the global ProcArray.
95 * 3. To begin COMMIT PREPARED or ROLLBACK PREPARED, check that the entry
96 * is valid and its locking_xid is no longer active, then store my current
97 * XID into locking_xid. This prevents concurrent attempts to commit or
98 * rollback the same prepared xact.
100 * 4. On completion of COMMIT PREPARED or ROLLBACK PREPARED, remove the entry
101 * from the ProcArray and the TwoPhaseState->prepXacts array and return it to
104 * Note that if the preparing transaction fails between steps 1 and 2, the
105 * entry will remain in prepXacts until recycled. We can detect recyclable
106 * entries by checking for valid = false and locking_xid no longer active.
108 * typedef struct GlobalTransactionData *GlobalTransaction appears in
113 typedef struct GlobalTransactionData
115 PGPROC proc; /* dummy proc */
116 BackendId dummyBackendId; /* similar to backend id for backends */
117 TimestampTz prepared_at; /* time of preparation */
118 XLogRecPtr prepare_lsn; /* XLOG offset of prepare record */
119 Oid owner; /* ID of user that executed the xact */
120 TransactionId locking_xid; /* top-level XID of backend working on xact */
121 bool valid; /* TRUE if fully prepared */
122 char gid[GIDSIZE]; /* The GID assigned to the prepared xact */
123 } GlobalTransactionData;
126 * Two Phase Commit shared state. Access to this struct is protected
127 * by TwoPhaseStateLock.
129 typedef struct TwoPhaseStateData
131 /* Head of linked list of free GlobalTransactionData structs */
132 GlobalTransaction freeGXacts;
134 /* Number of valid prepXacts entries. */
138 * There are max_prepared_xacts items in this array, but C wants a
141 GlobalTransaction prepXacts[1]; /* VARIABLE LENGTH ARRAY */
142 } TwoPhaseStateData; /* VARIABLE LENGTH STRUCT */
144 static TwoPhaseStateData *TwoPhaseState;
147 static void RecordTransactionCommitPrepared(TransactionId xid,
149 TransactionId *children,
153 SharedInvalidationMessage *invalmsgs,
155 static void RecordTransactionAbortPrepared(TransactionId xid,
157 TransactionId *children,
160 static void ProcessRecords(char *bufptr, TransactionId xid,
161 const TwoPhaseCallback callbacks[]);
165 * Initialization of shared memory
168 TwoPhaseShmemSize(void)
172 /* Need the fixed struct, the array of pointers, and the GTD structs */
173 size = offsetof(TwoPhaseStateData, prepXacts);
174 size = add_size(size, mul_size(max_prepared_xacts,
175 sizeof(GlobalTransaction)));
176 size = MAXALIGN(size);
177 size = add_size(size, mul_size(max_prepared_xacts,
178 sizeof(GlobalTransactionData)));
184 TwoPhaseShmemInit(void)
188 TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
191 if (!IsUnderPostmaster)
193 GlobalTransaction gxacts;
197 TwoPhaseState->freeGXacts = NULL;
198 TwoPhaseState->numPrepXacts = 0;
201 * Initialize the linked list of free GlobalTransactionData structs
203 gxacts = (GlobalTransaction)
204 ((char *) TwoPhaseState +
205 MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
206 sizeof(GlobalTransaction) * max_prepared_xacts));
207 for (i = 0; i < max_prepared_xacts; i++)
209 gxacts[i].proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
210 TwoPhaseState->freeGXacts = &gxacts[i];
213 * Assign a unique ID for each dummy proc, so that the range of
214 * dummy backend IDs immediately follows the range of normal
215 * backend IDs. We don't dare to assign a real backend ID to dummy
216 * procs, because prepared transactions don't take part in cache
217 * invalidation like a real backend ID would imply, but having a
218 * unique ID for them is nevertheless handy. This arrangement
219 * allows you to allocate an array of size (MaxBackends +
220 * max_prepared_xacts + 1), and have a slot for every backend and
221 * prepared transaction. Currently multixact.c uses that
224 gxacts[i].dummyBackendId = MaxBackends + 1 + i;
234 * Reserve the GID for the given transaction.
236 * Internally, this creates a gxact struct and puts it into the active array.
237 * NOTE: this is also used when reloading a gxact after a crash; so avoid
238 * assuming that we can use very much backend context.
241 MarkAsPreparing(TransactionId xid, const char *gid,
242 TimestampTz prepared_at, Oid owner, Oid databaseid)
244 GlobalTransaction gxact;
247 if (strlen(gid) >= GIDSIZE)
249 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
250 errmsg("transaction identifier \"%s\" is too long",
253 /* fail immediately if feature is disabled */
254 if (max_prepared_xacts == 0)
256 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
257 errmsg("prepared transactions are disabled"),
258 errhint("Set max_prepared_transactions to a nonzero value.")));
260 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
263 * First, find and recycle any gxacts that failed during prepare. We do
264 * this partly to ensure we don't mistakenly say their GIDs are still
265 * reserved, and partly so we don't fail on out-of-slots unnecessarily.
267 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
269 gxact = TwoPhaseState->prepXacts[i];
270 if (!gxact->valid && !TransactionIdIsActive(gxact->locking_xid))
272 /* It's dead Jim ... remove from the active array */
273 TwoPhaseState->numPrepXacts--;
274 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
275 /* and put it back in the freelist */
276 gxact->proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
277 TwoPhaseState->freeGXacts = gxact;
278 /* Back up index count too, so we don't miss scanning one */
283 /* Check for conflicting GID */
284 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
286 gxact = TwoPhaseState->prepXacts[i];
287 if (strcmp(gxact->gid, gid) == 0)
290 (errcode(ERRCODE_DUPLICATE_OBJECT),
291 errmsg("transaction identifier \"%s\" is already in use",
296 /* Get a free gxact from the freelist */
297 if (TwoPhaseState->freeGXacts == NULL)
299 (errcode(ERRCODE_OUT_OF_MEMORY),
300 errmsg("maximum number of prepared transactions reached"),
301 errhint("Increase max_prepared_transactions (currently %d).",
302 max_prepared_xacts)));
303 gxact = TwoPhaseState->freeGXacts;
304 TwoPhaseState->freeGXacts = (GlobalTransaction) gxact->proc.links.next;
307 MemSet(&gxact->proc, 0, sizeof(PGPROC));
308 SHMQueueElemInit(&(gxact->proc.links));
309 gxact->proc.waitStatus = STATUS_OK;
310 /* We set up the gxact's VXID as InvalidBackendId/XID */
311 gxact->proc.lxid = (LocalTransactionId) xid;
312 gxact->proc.xid = xid;
313 gxact->proc.xmin = InvalidTransactionId;
315 gxact->proc.backendId = InvalidBackendId;
316 gxact->proc.databaseId = databaseid;
317 gxact->proc.roleId = owner;
318 gxact->proc.inCommit = false;
319 gxact->proc.vacuumFlags = 0;
320 gxact->proc.lwWaiting = false;
321 gxact->proc.lwExclusive = false;
322 gxact->proc.lwWaitLink = NULL;
323 gxact->proc.waitLock = NULL;
324 gxact->proc.waitProcLock = NULL;
325 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
326 SHMQueueInit(&(gxact->proc.myProcLocks[i]));
327 /* subxid data must be filled later by GXactLoadSubxactData */
328 gxact->proc.subxids.overflowed = false;
329 gxact->proc.subxids.nxids = 0;
331 gxact->prepared_at = prepared_at;
332 /* initialize LSN to 0 (start of WAL) */
333 gxact->prepare_lsn.xlogid = 0;
334 gxact->prepare_lsn.xrecoff = 0;
335 gxact->owner = owner;
336 gxact->locking_xid = xid;
337 gxact->valid = false;
338 strcpy(gxact->gid, gid);
340 /* And insert it into the active array */
341 Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
342 TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
344 LWLockRelease(TwoPhaseStateLock);
350 * GXactLoadSubxactData
352 * If the transaction being persisted had any subtransactions, this must
353 * be called before MarkAsPrepared() to load information into the dummy
357 GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts,
358 TransactionId *children)
360 /* We need no extra lock since the GXACT isn't valid yet */
361 if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
363 gxact->proc.subxids.overflowed = true;
364 nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
368 memcpy(gxact->proc.subxids.xids, children,
369 nsubxacts * sizeof(TransactionId));
370 gxact->proc.subxids.nxids = nsubxacts;
376 * Mark the GXACT as fully valid, and enter it into the global ProcArray.
379 MarkAsPrepared(GlobalTransaction gxact)
381 /* Lock here may be overkill, but I'm not convinced of that ... */
382 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
383 Assert(!gxact->valid);
385 LWLockRelease(TwoPhaseStateLock);
388 * Put it into the global ProcArray so TransactionIdIsInProgress considers
389 * the XID as still running.
391 ProcArrayAdd(&gxact->proc);
396 * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
398 static GlobalTransaction
399 LockGXact(const char *gid, Oid user)
403 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
405 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
407 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
409 /* Ignore not-yet-valid GIDs */
412 if (strcmp(gxact->gid, gid) != 0)
415 /* Found it, but has someone else got it locked? */
416 if (TransactionIdIsValid(gxact->locking_xid))
418 if (TransactionIdIsActive(gxact->locking_xid))
420 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
421 errmsg("prepared transaction with identifier \"%s\" is busy",
423 gxact->locking_xid = InvalidTransactionId;
426 if (user != gxact->owner && !superuser_arg(user))
428 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
429 errmsg("permission denied to finish prepared transaction"),
430 errhint("Must be superuser or the user that prepared the transaction.")));
433 * Note: it probably would be possible to allow committing from
434 * another database; but at the moment NOTIFY is known not to work and
435 * there may be some other issues as well. Hence disallow until
436 * someone gets motivated to make it work.
438 if (MyDatabaseId != gxact->proc.databaseId)
440 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
441 errmsg("prepared transaction belongs to another database"),
442 errhint("Connect to the database where the transaction was prepared to finish it.")));
444 /* OK for me to lock it */
445 gxact->locking_xid = GetTopTransactionId();
447 LWLockRelease(TwoPhaseStateLock);
452 LWLockRelease(TwoPhaseStateLock);
455 (errcode(ERRCODE_UNDEFINED_OBJECT),
456 errmsg("prepared transaction with identifier \"%s\" does not exist",
465 * Remove the prepared transaction from the shared memory array.
467 * NB: caller should have already removed it from ProcArray
470 RemoveGXact(GlobalTransaction gxact)
474 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
476 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
478 if (gxact == TwoPhaseState->prepXacts[i])
480 /* remove from the active array */
481 TwoPhaseState->numPrepXacts--;
482 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
484 /* and put it back in the freelist */
485 gxact->proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
486 TwoPhaseState->freeGXacts = gxact;
488 LWLockRelease(TwoPhaseStateLock);
494 LWLockRelease(TwoPhaseStateLock);
496 elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
500 * TransactionIdIsPrepared
501 * True iff transaction associated with the identifier is prepared
502 * for two-phase commit
504 * Note: only gxacts marked "valid" are considered; but notice we do not
505 * check the locking status.
507 * This is not currently exported, because it is only needed internally.
510 TransactionIdIsPrepared(TransactionId xid)
515 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
517 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
519 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
521 if (gxact->valid && gxact->proc.xid == xid)
528 LWLockRelease(TwoPhaseStateLock);
534 * Returns an array of all prepared transactions for the user-level
535 * function pg_prepared_xact.
537 * The returned array and all its elements are copies of internal data
538 * structures, to minimize the time we need to hold the TwoPhaseStateLock.
540 * WARNING -- we return even those transactions that are not fully prepared
541 * yet. The caller should filter them out if he doesn't want them.
543 * The returned array is palloc'd.
546 GetPreparedTransactionList(GlobalTransaction *gxacts)
548 GlobalTransaction array;
552 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
554 if (TwoPhaseState->numPrepXacts == 0)
556 LWLockRelease(TwoPhaseStateLock);
562 num = TwoPhaseState->numPrepXacts;
563 array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
565 for (i = 0; i < num; i++)
566 memcpy(array + i, TwoPhaseState->prepXacts[i],
567 sizeof(GlobalTransactionData));
569 LWLockRelease(TwoPhaseStateLock);
575 /* Working status for pg_prepared_xact */
578 GlobalTransaction array;
585 * Produce a view with one row per prepared transaction.
587 * This function is here so we don't have to export the
588 * GlobalTransactionData struct definition.
591 pg_prepared_xact(PG_FUNCTION_ARGS)
593 FuncCallContext *funcctx;
594 Working_State *status;
596 if (SRF_IS_FIRSTCALL())
599 MemoryContext oldcontext;
601 /* create a function context for cross-call persistence */
602 funcctx = SRF_FIRSTCALL_INIT();
605 * Switch to memory context appropriate for multiple function calls
607 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
609 /* build tupdesc for result tuples */
610 /* this had better match pg_prepared_xacts view in system_views.sql */
611 tupdesc = CreateTemplateTupleDesc(5, false);
612 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
614 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
616 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
617 TIMESTAMPTZOID, -1, 0);
618 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
620 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
623 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
626 * Collect all the 2PC status information that we will format and send
627 * out as a result set.
629 status = (Working_State *) palloc(sizeof(Working_State));
630 funcctx->user_fctx = (void *) status;
632 status->ngxacts = GetPreparedTransactionList(&status->array);
635 MemoryContextSwitchTo(oldcontext);
638 funcctx = SRF_PERCALL_SETUP();
639 status = (Working_State *) funcctx->user_fctx;
641 while (status->array != NULL && status->currIdx < status->ngxacts)
643 GlobalTransaction gxact = &status->array[status->currIdx++];
653 * Form tuple with appropriate data.
655 MemSet(values, 0, sizeof(values));
656 MemSet(nulls, 0, sizeof(nulls));
658 values[0] = TransactionIdGetDatum(gxact->proc.xid);
659 values[1] = CStringGetTextDatum(gxact->gid);
660 values[2] = TimestampTzGetDatum(gxact->prepared_at);
661 values[3] = ObjectIdGetDatum(gxact->owner);
662 values[4] = ObjectIdGetDatum(gxact->proc.databaseId);
664 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
665 result = HeapTupleGetDatum(tuple);
666 SRF_RETURN_NEXT(funcctx, result);
669 SRF_RETURN_DONE(funcctx);
673 * TwoPhaseGetDummyProc
674 * Get the dummy backend ID for prepared transaction specified by XID
676 * Dummy backend IDs are similar to real backend IDs of real backends.
677 * They start at MaxBackends + 1, and are unique across all currently active
678 * real backends and prepared transactions.
681 TwoPhaseGetDummyBackendId(TransactionId xid)
683 PGPROC *proc = TwoPhaseGetDummyProc(xid);
685 return ((GlobalTransaction) proc)->dummyBackendId;
689 * TwoPhaseGetDummyProc
690 * Get the PGPROC that represents a prepared transaction specified by XID
693 TwoPhaseGetDummyProc(TransactionId xid)
695 PGPROC *result = NULL;
698 static TransactionId cached_xid = InvalidTransactionId;
699 static PGPROC *cached_proc = NULL;
702 * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
703 * repeatedly for the same XID. We can save work with a simple cache.
705 if (xid == cached_xid)
708 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
710 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
712 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
714 if (gxact->proc.xid == xid)
716 result = &gxact->proc;
721 LWLockRelease(TwoPhaseStateLock);
723 if (result == NULL) /* should not happen */
724 elog(ERROR, "failed to find dummy PGPROC for xid %u", xid);
727 cached_proc = result;
732 /************************************************************************/
733 /* State file support */
734 /************************************************************************/
736 #define TwoPhaseFilePath(path, xid) \
737 snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
740 * 2PC state file format:
742 * 1. TwoPhaseFileHeader
743 * 2. TransactionId[] (subtransactions)
744 * 3. RelFileNode[] (files to be deleted at commit)
745 * 4. RelFileNode[] (files to be deleted at abort)
746 * 5. SharedInvalidationMessage[] (inval messages to be sent at commit)
747 * 6. TwoPhaseRecordOnDisk
749 * 8. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
752 * Each segment except the final CRC32 is MAXALIGN'd.
756 * Header for a 2PC state file
758 #define TWOPHASE_MAGIC 0x57F94532 /* format identifier */
760 typedef struct TwoPhaseFileHeader
762 uint32 magic; /* format identifier */
763 uint32 total_len; /* actual file length */
764 TransactionId xid; /* original transaction XID */
765 Oid database; /* OID of database it was in */
766 TimestampTz prepared_at; /* time of preparation */
767 Oid owner; /* user running the transaction */
768 int32 nsubxacts; /* number of following subxact XIDs */
769 int32 ncommitrels; /* number of delete-on-commit rels */
770 int32 nabortrels; /* number of delete-on-abort rels */
771 int32 ninvalmsgs; /* number of cache invalidation messages */
772 bool initfileinval; /* does relcache init file need invalidation? */
773 char gid[GIDSIZE]; /* GID for transaction */
774 } TwoPhaseFileHeader;
777 * Header for each record in a state file
779 * NOTE: len counts only the rmgr data, not the TwoPhaseRecordOnDisk header.
780 * The rmgr data will be stored starting on a MAXALIGN boundary.
782 typedef struct TwoPhaseRecordOnDisk
784 uint32 len; /* length of rmgr data */
785 TwoPhaseRmgrId rmid; /* resource manager for this record */
786 uint16 info; /* flag bits for use by rmgr */
787 } TwoPhaseRecordOnDisk;
790 * During prepare, the state file is assembled in memory before writing it
791 * to WAL and the actual state file. We use a chain of XLogRecData blocks
792 * so that we will be able to pass the state file contents directly to
797 XLogRecData *head; /* first data block in the chain */
798 XLogRecData *tail; /* last block in chain */
799 uint32 bytes_free; /* free bytes left in tail block */
800 uint32 total_len; /* total data bytes in chain */
805 * Append a block of data to records data structure.
807 * NB: each block is padded to a MAXALIGN multiple. This must be
808 * accounted for when the file is later read!
810 * The data is copied, so the caller is free to modify it afterwards.
813 save_state_data(const void *data, uint32 len)
815 uint32 padlen = MAXALIGN(len);
817 if (padlen > records.bytes_free)
819 records.tail->next = palloc0(sizeof(XLogRecData));
820 records.tail = records.tail->next;
821 records.tail->buffer = InvalidBuffer;
822 records.tail->len = 0;
823 records.tail->next = NULL;
825 records.bytes_free = Max(padlen, 512);
826 records.tail->data = palloc(records.bytes_free);
829 memcpy(((char *) records.tail->data) + records.tail->len, data, len);
830 records.tail->len += padlen;
831 records.bytes_free -= padlen;
832 records.total_len += padlen;
836 * Start preparing a state file.
838 * Initializes data structure and inserts the 2PC file header record.
841 StartPrepare(GlobalTransaction gxact)
843 TransactionId xid = gxact->proc.xid;
844 TwoPhaseFileHeader hdr;
845 TransactionId *children;
846 RelFileNode *commitrels;
847 RelFileNode *abortrels;
848 SharedInvalidationMessage *invalmsgs;
850 /* Initialize linked list */
851 records.head = palloc0(sizeof(XLogRecData));
852 records.head->buffer = InvalidBuffer;
853 records.head->len = 0;
854 records.head->next = NULL;
856 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
857 records.head->data = palloc(records.bytes_free);
859 records.tail = records.head;
861 records.total_len = 0;
864 hdr.magic = TWOPHASE_MAGIC;
865 hdr.total_len = 0; /* EndPrepare will fill this in */
867 hdr.database = gxact->proc.databaseId;
868 hdr.prepared_at = gxact->prepared_at;
869 hdr.owner = gxact->owner;
870 hdr.nsubxacts = xactGetCommittedChildren(&children);
871 hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
872 hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
873 hdr.ninvalmsgs = xactGetCommittedInvalidationMessages(&invalmsgs,
875 StrNCpy(hdr.gid, gxact->gid, GIDSIZE);
877 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
880 * Add the additional info about subxacts, deletable files and cache
881 * invalidation messages.
883 if (hdr.nsubxacts > 0)
885 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
886 /* While we have the child-xact data, stuff it in the gxact too */
887 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
889 if (hdr.ncommitrels > 0)
891 save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
894 if (hdr.nabortrels > 0)
896 save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
899 if (hdr.ninvalmsgs > 0)
901 save_state_data(invalmsgs,
902 hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
908 * Finish preparing state file.
910 * Calculates CRC and writes state file to WAL and in pg_twophase directory.
913 EndPrepare(GlobalTransaction gxact)
915 TransactionId xid = gxact->proc.xid;
916 TwoPhaseFileHeader *hdr;
917 char path[MAXPGPATH];
919 pg_crc32 statefile_crc;
923 /* Add the end sentinel to the list of 2PC records */
924 RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID, 0,
927 /* Go back and fill in total_len in the file header record */
928 hdr = (TwoPhaseFileHeader *) records.head->data;
929 Assert(hdr->magic == TWOPHASE_MAGIC);
930 hdr->total_len = records.total_len + sizeof(pg_crc32);
933 * If the file size exceeds MaxAllocSize, we won't be able to read it in
934 * ReadTwoPhaseFile. Check for that now, rather than fail at commit time.
936 if (hdr->total_len > MaxAllocSize)
938 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
939 errmsg("two-phase state file maximum length exceeded")));
942 * Create the 2PC state file.
944 * Note: because we use BasicOpenFile(), we are responsible for ensuring
945 * the FD gets closed in any error exit path. Once we get into the
946 * critical section, though, it doesn't matter since any failure causes
949 TwoPhaseFilePath(path, xid);
951 fd = BasicOpenFile(path,
952 O_CREAT | O_EXCL | O_WRONLY | PG_BINARY,
956 (errcode_for_file_access(),
957 errmsg("could not create two-phase state file \"%s\": %m",
960 /* Write data to file, and calculate CRC as we pass over it */
961 INIT_CRC32(statefile_crc);
963 for (record = records.head; record != NULL; record = record->next)
965 COMP_CRC32(statefile_crc, record->data, record->len);
966 if ((write(fd, record->data, record->len)) != record->len)
970 (errcode_for_file_access(),
971 errmsg("could not write two-phase state file: %m")));
975 FIN_CRC32(statefile_crc);
978 * Write a deliberately bogus CRC to the state file; this is just paranoia
979 * to catch the case where four more bytes will run us out of disk space.
981 bogus_crc = ~statefile_crc;
983 if ((write(fd, &bogus_crc, sizeof(pg_crc32))) != sizeof(pg_crc32))
987 (errcode_for_file_access(),
988 errmsg("could not write two-phase state file: %m")));
991 /* Back up to prepare for rewriting the CRC */
992 if (lseek(fd, -((off_t) sizeof(pg_crc32)), SEEK_CUR) < 0)
996 (errcode_for_file_access(),
997 errmsg("could not seek in two-phase state file: %m")));
1001 * The state file isn't valid yet, because we haven't written the correct
1002 * CRC yet. Before we do that, insert entry in WAL and flush it to disk.
1004 * Between the time we have written the WAL entry and the time we write
1005 * out the correct state file CRC, we have an inconsistency: the xact is
1006 * prepared according to WAL but not according to our on-disk state. We
1007 * use a critical section to force a PANIC if we are unable to complete
1008 * the write --- then, WAL replay should repair the inconsistency. The
1009 * odds of a PANIC actually occurring should be very tiny given that we
1010 * were able to write the bogus CRC above.
1012 * We have to set inCommit here, too; otherwise a checkpoint starting
1013 * immediately after the WAL record is inserted could complete without
1014 * fsync'ing our state file. (This is essentially the same kind of race
1015 * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1016 * uses inCommit for; see notes there.)
1018 * We save the PREPARE record's location in the gxact for later use by
1019 * CheckPointTwoPhase.
1021 START_CRIT_SECTION();
1023 MyProc->inCommit = true;
1025 gxact->prepare_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE,
1027 XLogFlush(gxact->prepare_lsn);
1029 /* If we crash now, we have prepared: WAL replay will fix things */
1032 * Wake up all walsenders to send WAL up to the PREPARE record immediately
1033 * if replication is enabled
1035 if (max_wal_senders > 0)
1038 /* write correct CRC and close file */
1039 if ((write(fd, &statefile_crc, sizeof(pg_crc32))) != sizeof(pg_crc32))
1043 (errcode_for_file_access(),
1044 errmsg("could not write two-phase state file: %m")));
1049 (errcode_for_file_access(),
1050 errmsg("could not close two-phase state file: %m")));
1053 * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
1054 * as not running our XID (which it will do immediately after this
1055 * function returns), others can commit/rollback the xact.
1057 * NB: a side effect of this is to make a dummy ProcArray entry for the
1058 * prepared XID. This must happen before we clear the XID from MyProc,
1059 * else there is a window where the XID is not running according to
1060 * TransactionIdIsInProgress, and onlookers would be entitled to assume
1061 * the xact crashed. Instead we have a window where the same XID appears
1062 * twice in ProcArray, which is OK.
1064 MarkAsPrepared(gxact);
1067 * Now we can mark ourselves as out of the commit critical section: a
1068 * checkpoint starting after this will certainly see the gxact as a
1069 * candidate for fsyncing.
1071 MyProc->inCommit = false;
1076 * Wait for synchronous replication, if required.
1078 * Note that at this stage we have marked the prepare, but still show as
1079 * running in the procarray (twice!) and continue to hold locks.
1081 SyncRepWaitForLSN(gxact->prepare_lsn);
1083 records.tail = records.head = NULL;
1087 * Register a 2PC record to be written to state file.
1090 RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info,
1091 const void *data, uint32 len)
1093 TwoPhaseRecordOnDisk record;
1098 save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1100 save_state_data(data, len);
1105 * Read and validate the state file for xid.
1107 * If it looks OK (has a valid magic number and CRC), return the palloc'd
1108 * contents of the file. Otherwise return NULL.
1111 ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
1113 char path[MAXPGPATH];
1115 TwoPhaseFileHeader *hdr;
1122 TwoPhaseFilePath(path, xid);
1124 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1129 (errcode_for_file_access(),
1130 errmsg("could not open two-phase state file \"%s\": %m",
1136 * Check file length. We can determine a lower bound pretty easily. We
1137 * set an upper bound to avoid palloc() failure on a corrupt file, though
1138 * we can't guarantee that we won't get an out of memory error anyway,
1139 * even on a valid file.
1141 if (fstat(fd, &stat))
1146 (errcode_for_file_access(),
1147 errmsg("could not stat two-phase state file \"%s\": %m",
1152 if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1153 MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1154 sizeof(pg_crc32)) ||
1155 stat.st_size > MaxAllocSize)
1161 crc_offset = stat.st_size - sizeof(pg_crc32);
1162 if (crc_offset != MAXALIGN(crc_offset))
1169 * OK, slurp in the file.
1171 buf = (char *) palloc(stat.st_size);
1173 if (read(fd, buf, stat.st_size) != stat.st_size)
1178 (errcode_for_file_access(),
1179 errmsg("could not read two-phase state file \"%s\": %m",
1187 hdr = (TwoPhaseFileHeader *) buf;
1188 if (hdr->magic != TWOPHASE_MAGIC || hdr->total_len != stat.st_size)
1194 INIT_CRC32(calc_crc);
1195 COMP_CRC32(calc_crc, buf, crc_offset);
1196 FIN_CRC32(calc_crc);
1198 file_crc = *((pg_crc32 *) (buf + crc_offset));
1200 if (!EQ_CRC32(calc_crc, file_crc))
1210 * Confirms an xid is prepared, during recovery
1213 StandbyTransactionIdIsPrepared(TransactionId xid)
1216 TwoPhaseFileHeader *hdr;
1219 Assert(TransactionIdIsValid(xid));
1221 if (max_prepared_xacts <= 0)
1222 return false; /* nothing to do */
1224 /* Read and validate file */
1225 buf = ReadTwoPhaseFile(xid, false);
1229 /* Check header also */
1230 hdr = (TwoPhaseFileHeader *) buf;
1231 result = TransactionIdEquals(hdr->xid, xid);
1238 * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1241 FinishPreparedTransaction(const char *gid, bool isCommit)
1243 GlobalTransaction gxact;
1247 TwoPhaseFileHeader *hdr;
1248 TransactionId latestXid;
1249 TransactionId *children;
1250 RelFileNode *commitrels;
1251 RelFileNode *abortrels;
1252 RelFileNode *delrels;
1254 SharedInvalidationMessage *invalmsgs;
1258 * Validate the GID, and lock the GXACT to ensure that two backends do not
1259 * try to commit the same GID at once.
1261 gxact = LockGXact(gid, GetUserId());
1262 xid = gxact->proc.xid;
1265 * Read and validate the state file
1267 buf = ReadTwoPhaseFile(xid, true);
1270 (errcode(ERRCODE_DATA_CORRUPTED),
1271 errmsg("two-phase state file for transaction %u is corrupt",
1275 * Disassemble the header area
1277 hdr = (TwoPhaseFileHeader *) buf;
1278 Assert(TransactionIdEquals(hdr->xid, xid));
1279 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1280 children = (TransactionId *) bufptr;
1281 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1282 commitrels = (RelFileNode *) bufptr;
1283 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1284 abortrels = (RelFileNode *) bufptr;
1285 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1286 invalmsgs = (SharedInvalidationMessage *) bufptr;
1287 bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1289 /* compute latestXid among all children */
1290 latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1293 * The order of operations here is critical: make the XLOG entry for
1294 * commit or abort, then mark the transaction committed or aborted in
1295 * pg_clog, then remove its PGPROC from the global ProcArray (which means
1296 * TransactionIdIsInProgress will stop saying the prepared xact is in
1297 * progress), then run the post-commit or post-abort callbacks. The
1298 * callbacks will release the locks the transaction held.
1301 RecordTransactionCommitPrepared(xid,
1302 hdr->nsubxacts, children,
1303 hdr->ncommitrels, commitrels,
1304 hdr->ninvalmsgs, invalmsgs,
1305 hdr->initfileinval);
1307 RecordTransactionAbortPrepared(xid,
1308 hdr->nsubxacts, children,
1309 hdr->nabortrels, abortrels);
1311 ProcArrayRemove(&gxact->proc, latestXid);
1314 * In case we fail while running the callbacks, mark the gxact invalid so
1315 * no one else will try to commit/rollback, and so it can be recycled
1316 * properly later. It is still locked by our XID so it won't go away yet.
1318 * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1320 gxact->valid = false;
1323 * We have to remove any files that were supposed to be dropped. For
1324 * consistency with the regular xact.c code paths, must do this before
1325 * releasing locks, so do it before running the callbacks.
1327 * NB: this code knows that we couldn't be dropping any temp rels ...
1331 delrels = commitrels;
1332 ndelrels = hdr->ncommitrels;
1336 delrels = abortrels;
1337 ndelrels = hdr->nabortrels;
1339 for (i = 0; i < ndelrels; i++)
1341 SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1344 for (fork = 0; fork <= MAX_FORKNUM; fork++)
1346 if (smgrexists(srel, fork))
1347 smgrdounlink(srel, fork, false);
1353 * Handle cache invalidation messages.
1355 * Relcache init file invalidation requires processing both before and
1356 * after we send the SI messages. See AtEOXact_Inval()
1358 if (hdr->initfileinval)
1359 RelationCacheInitFileInvalidate(true);
1360 SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1361 if (hdr->initfileinval)
1362 RelationCacheInitFileInvalidate(false);
1364 /* And now do the callbacks */
1366 ProcessRecords(bufptr, xid, twophase_postcommit_callbacks);
1368 ProcessRecords(bufptr, xid, twophase_postabort_callbacks);
1370 PredicateLockTwoPhaseFinish(xid, isCommit);
1372 /* Count the prepared xact as committed or aborted */
1373 AtEOXact_PgStat(isCommit);
1376 * And now we can clean up our mess.
1378 RemoveTwoPhaseFile(xid, true);
1386 * Scan a 2PC state file (already read into memory by ReadTwoPhaseFile)
1387 * and call the indicated callbacks for each 2PC record.
1390 ProcessRecords(char *bufptr, TransactionId xid,
1391 const TwoPhaseCallback callbacks[])
1395 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1397 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1398 if (record->rmid == TWOPHASE_RM_END_ID)
1401 bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1403 if (callbacks[record->rmid] != NULL)
1404 callbacks[record->rmid] (xid, record->info,
1405 (void *) bufptr, record->len);
1407 bufptr += MAXALIGN(record->len);
1412 * Remove the 2PC file for the specified XID.
1414 * If giveWarning is false, do not complain about file-not-present;
1415 * this is an expected case during WAL replay.
1418 RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
1420 char path[MAXPGPATH];
1422 TwoPhaseFilePath(path, xid);
1424 if (errno != ENOENT || giveWarning)
1426 (errcode_for_file_access(),
1427 errmsg("could not remove two-phase state file \"%s\": %m",
1432 * Recreates a state file. This is used in WAL replay.
1434 * Note: content and len don't include CRC.
1437 RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
1439 char path[MAXPGPATH];
1440 pg_crc32 statefile_crc;
1444 INIT_CRC32(statefile_crc);
1445 COMP_CRC32(statefile_crc, content, len);
1446 FIN_CRC32(statefile_crc);
1448 TwoPhaseFilePath(path, xid);
1450 fd = BasicOpenFile(path,
1451 O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY,
1455 (errcode_for_file_access(),
1456 errmsg("could not recreate two-phase state file \"%s\": %m",
1459 /* Write content and CRC */
1460 if (write(fd, content, len) != len)
1464 (errcode_for_file_access(),
1465 errmsg("could not write two-phase state file: %m")));
1467 if (write(fd, &statefile_crc, sizeof(pg_crc32)) != sizeof(pg_crc32))
1471 (errcode_for_file_access(),
1472 errmsg("could not write two-phase state file: %m")));
1476 * We must fsync the file because the end-of-replay checkpoint will not do
1477 * so, there being no GXACT in shared memory yet to tell it to.
1479 if (pg_fsync(fd) != 0)
1483 (errcode_for_file_access(),
1484 errmsg("could not fsync two-phase state file: %m")));
1489 (errcode_for_file_access(),
1490 errmsg("could not close two-phase state file: %m")));
1494 * CheckPointTwoPhase -- handle 2PC component of checkpointing.
1496 * We must fsync the state file of any GXACT that is valid and has a PREPARE
1497 * LSN <= the checkpoint's redo horizon. (If the gxact isn't valid yet or
1498 * has a later LSN, this checkpoint is not responsible for fsyncing it.)
1500 * This is deliberately run as late as possible in the checkpoint sequence,
1501 * because GXACTs ordinarily have short lifespans, and so it is quite
1502 * possible that GXACTs that were valid at checkpoint start will no longer
1503 * exist if we wait a little bit.
1505 * If a GXACT remains valid across multiple checkpoints, it'll be fsynced
1506 * each time. This is considered unusual enough that we don't bother to
1507 * expend any extra code to avoid the redundant fsyncs. (They should be
1508 * reasonably cheap anyway, since they won't cause I/O.)
1511 CheckPointTwoPhase(XLogRecPtr redo_horizon)
1513 TransactionId *xids;
1515 char path[MAXPGPATH];
1519 * We don't want to hold the TwoPhaseStateLock while doing I/O, so we grab
1520 * it just long enough to make a list of the XIDs that require fsyncing,
1521 * and then do the I/O afterwards.
1523 * This approach creates a race condition: someone else could delete a
1524 * GXACT between the time we release TwoPhaseStateLock and the time we try
1525 * to open its state file. We handle this by special-casing ENOENT
1526 * failures: if we see that, we verify that the GXACT is no longer valid,
1527 * and if so ignore the failure.
1529 if (max_prepared_xacts <= 0)
1530 return; /* nothing to do */
1532 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1534 xids = (TransactionId *) palloc(max_prepared_xacts * sizeof(TransactionId));
1537 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1539 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1541 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1544 XLByteLE(gxact->prepare_lsn, redo_horizon))
1545 xids[nxids++] = gxact->proc.xid;
1548 LWLockRelease(TwoPhaseStateLock);
1550 for (i = 0; i < nxids; i++)
1552 TransactionId xid = xids[i];
1555 TwoPhaseFilePath(path, xid);
1557 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
1560 if (errno == ENOENT)
1562 /* OK if gxact is no longer valid */
1563 if (!TransactionIdIsPrepared(xid))
1565 /* Restore errno in case it was changed */
1569 (errcode_for_file_access(),
1570 errmsg("could not open two-phase state file \"%s\": %m",
1574 if (pg_fsync(fd) != 0)
1578 (errcode_for_file_access(),
1579 errmsg("could not fsync two-phase state file \"%s\": %m",
1585 (errcode_for_file_access(),
1586 errmsg("could not close two-phase state file \"%s\": %m",
1592 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1596 * PrescanPreparedTransactions
1598 * Scan the pg_twophase directory and determine the range of valid XIDs
1599 * present. This is run during database startup, after we have completed
1600 * reading WAL. ShmemVariableCache->nextXid has been set to one more than
1601 * the highest XID for which evidence exists in WAL.
1603 * We throw away any prepared xacts with main XID beyond nextXid --- if any
1604 * are present, it suggests that the DBA has done a PITR recovery to an
1605 * earlier point in time without cleaning out pg_twophase. We dare not
1606 * try to recover such prepared xacts since they likely depend on database
1607 * state that doesn't exist now.
1609 * However, we will advance nextXid beyond any subxact XIDs belonging to
1610 * valid prepared xacts. We need to do this since subxact commit doesn't
1611 * write a WAL entry, and so there might be no evidence in WAL of those
1614 * Our other responsibility is to determine and return the oldest valid XID
1615 * among the prepared xacts (if none, return ShmemVariableCache->nextXid).
1616 * This is needed to synchronize pg_subtrans startup properly.
1618 * If xids_p and nxids_p are not NULL, pointer to a palloc'd array of all
1619 * top-level xids is stored in *xids_p. The number of entries in the array
1620 * is returned in *nxids_p.
1623 PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
1625 TransactionId origNextXid = ShmemVariableCache->nextXid;
1626 TransactionId result = origNextXid;
1628 struct dirent *clde;
1629 TransactionId *xids = NULL;
1633 cldir = AllocateDir(TWOPHASE_DIR);
1634 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1636 if (strlen(clde->d_name) == 8 &&
1637 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1641 TwoPhaseFileHeader *hdr;
1642 TransactionId *subxids;
1645 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1647 /* Reject XID if too new */
1648 if (TransactionIdFollowsOrEquals(xid, origNextXid))
1651 (errmsg("removing future two-phase state file \"%s\"",
1653 RemoveTwoPhaseFile(xid, true);
1658 * Note: we can't check if already processed because clog
1659 * subsystem isn't up yet.
1662 /* Read and validate file */
1663 buf = ReadTwoPhaseFile(xid, true);
1667 (errmsg("removing corrupt two-phase state file \"%s\"",
1669 RemoveTwoPhaseFile(xid, true);
1673 /* Deconstruct header */
1674 hdr = (TwoPhaseFileHeader *) buf;
1675 if (!TransactionIdEquals(hdr->xid, xid))
1678 (errmsg("removing corrupt two-phase state file \"%s\"",
1680 RemoveTwoPhaseFile(xid, true);
1686 * OK, we think this file is valid. Incorporate xid into the
1687 * running-minimum result.
1689 if (TransactionIdPrecedes(xid, result))
1693 * Examine subtransaction XIDs ... they should all follow main
1694 * XID, and they may force us to advance nextXid.
1696 subxids = (TransactionId *)
1697 (buf + MAXALIGN(sizeof(TwoPhaseFileHeader)));
1698 for (i = 0; i < hdr->nsubxacts; i++)
1700 TransactionId subxid = subxids[i];
1702 Assert(TransactionIdFollows(subxid, xid));
1703 if (TransactionIdFollowsOrEquals(subxid,
1704 ShmemVariableCache->nextXid))
1706 ShmemVariableCache->nextXid = subxid;
1707 TransactionIdAdvance(ShmemVariableCache->nextXid);
1714 if (nxids == allocsize)
1719 xids = palloc(allocsize * sizeof(TransactionId));
1723 allocsize = allocsize * 2;
1724 xids = repalloc(xids, allocsize * sizeof(TransactionId));
1727 xids[nxids++] = xid;
1745 * StandbyRecoverPreparedTransactions
1747 * Scan the pg_twophase directory and setup all the required information to
1748 * allow standby queries to treat prepared transactions as still active.
1749 * This is never called at the end of recovery - we use
1750 * RecoverPreparedTransactions() at that point.
1752 * Currently we simply call SubTransSetParent() for any subxids of prepared
1753 * transactions. If overwriteOK is true, it's OK if some XIDs have already
1754 * been marked in pg_subtrans.
1757 StandbyRecoverPreparedTransactions(bool overwriteOK)
1760 struct dirent *clde;
1762 cldir = AllocateDir(TWOPHASE_DIR);
1763 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1765 if (strlen(clde->d_name) == 8 &&
1766 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1770 TwoPhaseFileHeader *hdr;
1771 TransactionId *subxids;
1774 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1776 /* Already processed? */
1777 if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
1780 (errmsg("removing stale two-phase state file \"%s\"",
1782 RemoveTwoPhaseFile(xid, true);
1786 /* Read and validate file */
1787 buf = ReadTwoPhaseFile(xid, true);
1791 (errmsg("removing corrupt two-phase state file \"%s\"",
1793 RemoveTwoPhaseFile(xid, true);
1797 /* Deconstruct header */
1798 hdr = (TwoPhaseFileHeader *) buf;
1799 if (!TransactionIdEquals(hdr->xid, xid))
1802 (errmsg("removing corrupt two-phase state file \"%s\"",
1804 RemoveTwoPhaseFile(xid, true);
1810 * Examine subtransaction XIDs ... they should all follow main
1813 subxids = (TransactionId *)
1814 (buf + MAXALIGN(sizeof(TwoPhaseFileHeader)));
1815 for (i = 0; i < hdr->nsubxacts; i++)
1817 TransactionId subxid = subxids[i];
1819 Assert(TransactionIdFollows(subxid, xid));
1820 SubTransSetParent(xid, subxid, overwriteOK);
1828 * RecoverPreparedTransactions
1830 * Scan the pg_twophase directory and reload shared-memory state for each
1831 * prepared transaction (reacquire locks, etc). This is run during database
1835 RecoverPreparedTransactions(void)
1837 char dir[MAXPGPATH];
1839 struct dirent *clde;
1840 bool overwriteOK = false;
1842 snprintf(dir, MAXPGPATH, "%s", TWOPHASE_DIR);
1844 cldir = AllocateDir(dir);
1845 while ((clde = ReadDir(cldir, dir)) != NULL)
1847 if (strlen(clde->d_name) == 8 &&
1848 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1853 TwoPhaseFileHeader *hdr;
1854 TransactionId *subxids;
1855 GlobalTransaction gxact;
1858 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1860 /* Already processed? */
1861 if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
1864 (errmsg("removing stale two-phase state file \"%s\"",
1866 RemoveTwoPhaseFile(xid, true);
1870 /* Read and validate file */
1871 buf = ReadTwoPhaseFile(xid, true);
1875 (errmsg("removing corrupt two-phase state file \"%s\"",
1877 RemoveTwoPhaseFile(xid, true);
1882 (errmsg("recovering prepared transaction %u", xid)));
1884 /* Deconstruct header */
1885 hdr = (TwoPhaseFileHeader *) buf;
1886 Assert(TransactionIdEquals(hdr->xid, xid));
1887 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1888 subxids = (TransactionId *) bufptr;
1889 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1890 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1891 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1892 bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1895 * It's possible that SubTransSetParent has been set before, if
1896 * the prepared transaction generated xid assignment records. Test
1897 * here must match one used in AssignTransactionId().
1899 if (InHotStandby && hdr->nsubxacts >= PGPROC_MAX_CACHED_SUBXIDS)
1903 * Reconstruct subtrans state for the transaction --- needed
1904 * because pg_subtrans is not preserved over a restart. Note that
1905 * we are linking all the subtransactions directly to the
1906 * top-level XID; there may originally have been a more complex
1907 * hierarchy, but there's no need to restore that exactly.
1909 for (i = 0; i < hdr->nsubxacts; i++)
1910 SubTransSetParent(subxids[i], xid, overwriteOK);
1913 * Recreate its GXACT and dummy PGPROC
1915 * Note: since we don't have the PREPARE record's WAL location at
1916 * hand, we leave prepare_lsn zeroes. This means the GXACT will
1917 * be fsync'd on every future checkpoint. We assume this
1918 * situation is infrequent enough that the performance cost is
1919 * negligible (especially since we know the state file has already
1922 gxact = MarkAsPreparing(xid, hdr->gid,
1924 hdr->owner, hdr->database);
1925 GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1926 MarkAsPrepared(gxact);
1929 * Recover other state (notably locks) using resource managers
1931 ProcessRecords(bufptr, xid, twophase_recover_callbacks);
1934 * Release locks held by the standby process after we process each
1935 * prepared transaction. As a result, we don't need too many
1936 * additional locks at any one time.
1939 StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
1948 * RecordTransactionCommitPrepared
1950 * This is basically the same as RecordTransactionCommit: in particular,
1951 * we must set the inCommit flag to avoid a race condition.
1953 * We know the transaction made at least one XLOG entry (its PREPARE),
1954 * so it is never possible to optimize out the commit record.
1957 RecordTransactionCommitPrepared(TransactionId xid,
1959 TransactionId *children,
1963 SharedInvalidationMessage *invalmsgs,
1966 XLogRecData rdata[4];
1968 xl_xact_commit_prepared xlrec;
1971 START_CRIT_SECTION();
1973 /* See notes in RecordTransactionCommit */
1974 MyProc->inCommit = true;
1976 /* Emit the XLOG commit record */
1978 xlrec.crec.xact_time = GetCurrentTimestamp();
1979 xlrec.crec.xinfo = initfileinval ? XACT_COMPLETION_UPDATE_RELCACHE_FILE : 0;
1980 xlrec.crec.nmsgs = 0;
1981 xlrec.crec.nrels = nrels;
1982 xlrec.crec.nsubxacts = nchildren;
1983 xlrec.crec.nmsgs = ninvalmsgs;
1985 rdata[0].data = (char *) (&xlrec);
1986 rdata[0].len = MinSizeOfXactCommitPrepared;
1987 rdata[0].buffer = InvalidBuffer;
1988 /* dump rels to delete */
1991 rdata[0].next = &(rdata[1]);
1992 rdata[1].data = (char *) rels;
1993 rdata[1].len = nrels * sizeof(RelFileNode);
1994 rdata[1].buffer = InvalidBuffer;
1997 /* dump committed child Xids */
2000 rdata[lastrdata].next = &(rdata[2]);
2001 rdata[2].data = (char *) children;
2002 rdata[2].len = nchildren * sizeof(TransactionId);
2003 rdata[2].buffer = InvalidBuffer;
2006 /* dump cache invalidation messages */
2009 rdata[lastrdata].next = &(rdata[3]);
2010 rdata[3].data = (char *) invalmsgs;
2011 rdata[3].len = ninvalmsgs * sizeof(SharedInvalidationMessage);
2012 rdata[3].buffer = InvalidBuffer;
2015 rdata[lastrdata].next = NULL;
2017 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT_PREPARED, rdata);
2020 * We don't currently try to sleep before flush here ... nor is there any
2021 * support for async commit of a prepared xact (the very idea is probably
2025 /* Flush XLOG to disk */
2029 * Wake up all walsenders to send WAL up to the COMMIT PREPARED record
2030 * immediately if replication is enabled
2032 if (max_wal_senders > 0)
2035 /* Mark the transaction committed in pg_clog */
2036 TransactionIdCommitTree(xid, nchildren, children);
2038 /* Checkpoint can proceed now */
2039 MyProc->inCommit = false;
2044 * Wait for synchronous replication, if required.
2046 * Note that at this stage we have marked clog, but still show as running
2047 * in the procarray and continue to hold locks.
2049 SyncRepWaitForLSN(recptr);
2053 * RecordTransactionAbortPrepared
2055 * This is basically the same as RecordTransactionAbort.
2057 * We know the transaction made at least one XLOG entry (its PREPARE),
2058 * so it is never possible to optimize out the abort record.
2061 RecordTransactionAbortPrepared(TransactionId xid,
2063 TransactionId *children,
2067 XLogRecData rdata[3];
2069 xl_xact_abort_prepared xlrec;
2073 * Catch the scenario where we aborted partway through
2074 * RecordTransactionCommitPrepared ...
2076 if (TransactionIdDidCommit(xid))
2077 elog(PANIC, "cannot abort transaction %u, it was already committed",
2080 START_CRIT_SECTION();
2082 /* Emit the XLOG abort record */
2084 xlrec.arec.xact_time = GetCurrentTimestamp();
2085 xlrec.arec.nrels = nrels;
2086 xlrec.arec.nsubxacts = nchildren;
2087 rdata[0].data = (char *) (&xlrec);
2088 rdata[0].len = MinSizeOfXactAbortPrepared;
2089 rdata[0].buffer = InvalidBuffer;
2090 /* dump rels to delete */
2093 rdata[0].next = &(rdata[1]);
2094 rdata[1].data = (char *) rels;
2095 rdata[1].len = nrels * sizeof(RelFileNode);
2096 rdata[1].buffer = InvalidBuffer;
2099 /* dump committed child Xids */
2102 rdata[lastrdata].next = &(rdata[2]);
2103 rdata[2].data = (char *) children;
2104 rdata[2].len = nchildren * sizeof(TransactionId);
2105 rdata[2].buffer = InvalidBuffer;
2108 rdata[lastrdata].next = NULL;
2110 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT_PREPARED, rdata);
2112 /* Always flush, since we're about to remove the 2PC state file */
2116 * Wake up all walsenders to send WAL up to the ABORT PREPARED record
2117 * immediately if replication is enabled
2119 if (max_wal_senders > 0)
2123 * Mark the transaction aborted in clog. This is not absolutely necessary
2124 * but we may as well do it while we are here.
2126 TransactionIdAbortTree(xid, nchildren, children);
2131 * Wait for synchronous replication, if required.
2133 * Note that at this stage we have marked clog, but still show as running
2134 * in the procarray and continue to hold locks.
2136 SyncRepWaitForLSN(recptr);