1 /*-------------------------------------------------------------------------
4 * Two-phase commit support functions.
6 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/access/transam/twophase.c
13 * Each global transaction is associated with a global transaction
14 * identifier (GID). The client assigns a GID to a postgres
15 * transaction with the PREPARE TRANSACTION command.
17 * We keep all active global transactions in a shared memory array.
18 * When the PREPARE TRANSACTION command is issued, the GID is
19 * reserved for the transaction in the array. This is done before
20 * a WAL entry is made, because the reservation checks for duplicate
21 * GIDs and aborts the transaction if there already is a global
22 * transaction in prepared state with the same GID.
24 * A global transaction (gxact) also has dummy PGXACT and PGPROC; this is
25 * what keeps the XID considered running by TransactionIdIsInProgress.
26 * It is also convenient as a PGPROC to hook the gxact's locks to.
28 * In order to survive crashes and shutdowns, all prepared
29 * transactions must be stored in permanent storage. This includes
30 * locking information, pending notifications etc. All that state
31 * information is written to the per-transaction state file in
32 * the pg_twophase directory.
34 *-------------------------------------------------------------------------
40 #include <sys/types.h>
44 #include "access/htup_details.h"
45 #include "access/subtrans.h"
46 #include "access/transam.h"
47 #include "access/twophase.h"
48 #include "access/twophase_rmgr.h"
49 #include "access/xact.h"
50 #include "access/xlogutils.h"
51 #include "catalog/pg_type.h"
52 #include "catalog/storage.h"
54 #include "miscadmin.h"
57 #include "replication/walsender.h"
58 #include "replication/syncrep.h"
59 #include "storage/fd.h"
60 #include "storage/predicate.h"
61 #include "storage/proc.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"
67 #include "utils/timestamp.h"
71 * Directory where Two-phase commit files reside within PGDATA
73 #define TWOPHASE_DIR "pg_twophase"
75 /* GUC variable, can't be changed after startup */
76 int max_prepared_xacts = 0;
79 * This struct describes one global transaction that is in prepared state
80 * or attempting to become prepared.
82 * The lifecycle of a global transaction is:
84 * 1. After checking that the requested GID is not in use, set up an
85 * entry in the TwoPhaseState->prepXacts array with the correct XID and GID,
86 * with locking_xid = my own XID and valid = false.
88 * 2. After successfully completing prepare, set valid = true and enter the
89 * referenced PGPROC into the global ProcArray.
91 * 3. To begin COMMIT PREPARED or ROLLBACK PREPARED, check that the entry
92 * is valid and its locking_xid is no longer active, then store my current
93 * XID into locking_xid. This prevents concurrent attempts to commit or
94 * rollback the same prepared xact.
96 * 4. On completion of COMMIT PREPARED or ROLLBACK PREPARED, remove the entry
97 * from the ProcArray and the TwoPhaseState->prepXacts array and return it to
100 * Note that if the preparing transaction fails between steps 1 and 2, the
101 * entry will remain in prepXacts until recycled. We can detect recyclable
102 * entries by checking for valid = false and locking_xid no longer active.
104 * typedef struct GlobalTransactionData *GlobalTransaction appears in
109 typedef struct GlobalTransactionData
111 GlobalTransaction next; /* list link for free list */
112 int pgprocno; /* ID of associated dummy PGPROC */
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 /* insert into linked list */
207 gxacts[i].next = TwoPhaseState->freeGXacts;
208 TwoPhaseState->freeGXacts = &gxacts[i];
210 /* associate it with a PGPROC assigned by InitProcGlobal */
211 gxacts[i].pgprocno = PreparedXactProcs[i].pgprocno;
214 * Assign a unique ID for each dummy proc, so that the range of
215 * dummy backend IDs immediately follows the range of normal
216 * backend IDs. We don't dare to assign a real backend ID to dummy
217 * procs, because prepared transactions don't take part in cache
218 * invalidation like a real backend ID would imply, but having a
219 * unique ID for them is nevertheless handy. This arrangement
220 * allows you to allocate an array of size (MaxBackends +
221 * max_prepared_xacts + 1), and have a slot for every backend and
222 * prepared transaction. Currently multixact.c uses that
225 gxacts[i].dummyBackendId = MaxBackends + 1 + i;
235 * Reserve the GID for the given transaction.
237 * Internally, this creates a gxact struct and puts it into the active array.
238 * NOTE: this is also used when reloading a gxact after a crash; so avoid
239 * assuming that we can use very much backend context.
242 MarkAsPreparing(TransactionId xid, const char *gid,
243 TimestampTz prepared_at, Oid owner, Oid databaseid)
245 GlobalTransaction gxact;
250 if (strlen(gid) >= GIDSIZE)
252 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
253 errmsg("transaction identifier \"%s\" is too long",
256 /* fail immediately if feature is disabled */
257 if (max_prepared_xacts == 0)
259 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
260 errmsg("prepared transactions are disabled"),
261 errhint("Set max_prepared_transactions to a nonzero value.")));
263 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
266 * First, find and recycle any gxacts that failed during prepare. We do
267 * this partly to ensure we don't mistakenly say their GIDs are still
268 * reserved, and partly so we don't fail on out-of-slots unnecessarily.
270 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
272 gxact = TwoPhaseState->prepXacts[i];
273 if (!gxact->valid && !TransactionIdIsActive(gxact->locking_xid))
275 /* It's dead Jim ... remove from the active array */
276 TwoPhaseState->numPrepXacts--;
277 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
278 /* and put it back in the freelist */
279 gxact->next = TwoPhaseState->freeGXacts;
280 TwoPhaseState->freeGXacts = gxact;
281 /* Back up index count too, so we don't miss scanning one */
286 /* Check for conflicting GID */
287 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
289 gxact = TwoPhaseState->prepXacts[i];
290 if (strcmp(gxact->gid, gid) == 0)
293 (errcode(ERRCODE_DUPLICATE_OBJECT),
294 errmsg("transaction identifier \"%s\" is already in use",
299 /* Get a free gxact from the freelist */
300 if (TwoPhaseState->freeGXacts == NULL)
302 (errcode(ERRCODE_OUT_OF_MEMORY),
303 errmsg("maximum number of prepared transactions reached"),
304 errhint("Increase max_prepared_transactions (currently %d).",
305 max_prepared_xacts)));
306 gxact = TwoPhaseState->freeGXacts;
307 TwoPhaseState->freeGXacts = gxact->next;
309 proc = &ProcGlobal->allProcs[gxact->pgprocno];
310 pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
312 /* Initialize the PGPROC entry */
313 MemSet(proc, 0, sizeof(PGPROC));
314 proc->pgprocno = gxact->pgprocno;
315 SHMQueueElemInit(&(proc->links));
316 proc->waitStatus = STATUS_OK;
317 /* We set up the gxact's VXID as InvalidBackendId/XID */
318 proc->lxid = (LocalTransactionId) xid;
320 pgxact->xmin = InvalidTransactionId;
321 pgxact->inCommit = false;
322 pgxact->vacuumFlags = 0;
324 proc->backendId = InvalidBackendId;
325 proc->databaseId = databaseid;
326 proc->roleId = owner;
327 proc->lwWaiting = false;
328 proc->lwWaitMode = 0;
329 proc->lwWaitLink = NULL;
330 proc->waitLock = NULL;
331 proc->waitProcLock = NULL;
332 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
333 SHMQueueInit(&(proc->myProcLocks[i]));
334 /* subxid data must be filled later by GXactLoadSubxactData */
335 pgxact->overflowed = false;
338 gxact->prepared_at = prepared_at;
339 /* initialize LSN to 0 (start of WAL) */
340 gxact->prepare_lsn = 0;
341 gxact->owner = owner;
342 gxact->locking_xid = xid;
343 gxact->valid = false;
344 strcpy(gxact->gid, gid);
346 /* And insert it into the active array */
347 Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
348 TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
350 LWLockRelease(TwoPhaseStateLock);
356 * GXactLoadSubxactData
358 * If the transaction being persisted had any subtransactions, this must
359 * be called before MarkAsPrepared() to load information into the dummy
363 GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts,
364 TransactionId *children)
366 PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
367 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
369 /* We need no extra lock since the GXACT isn't valid yet */
370 if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
372 pgxact->overflowed = true;
373 nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
377 memcpy(proc->subxids.xids, children,
378 nsubxacts * sizeof(TransactionId));
379 pgxact->nxids = nsubxacts;
385 * Mark the GXACT as fully valid, and enter it into the global ProcArray.
388 MarkAsPrepared(GlobalTransaction gxact)
390 /* Lock here may be overkill, but I'm not convinced of that ... */
391 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
392 Assert(!gxact->valid);
394 LWLockRelease(TwoPhaseStateLock);
397 * Put it into the global ProcArray so TransactionIdIsInProgress considers
398 * the XID as still running.
400 ProcArrayAdd(&ProcGlobal->allProcs[gxact->pgprocno]);
405 * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
407 static GlobalTransaction
408 LockGXact(const char *gid, Oid user)
412 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
414 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
416 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
417 PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
419 /* Ignore not-yet-valid GIDs */
422 if (strcmp(gxact->gid, gid) != 0)
425 /* Found it, but has someone else got it locked? */
426 if (TransactionIdIsValid(gxact->locking_xid))
428 if (TransactionIdIsActive(gxact->locking_xid))
430 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
431 errmsg("prepared transaction with identifier \"%s\" is busy",
433 gxact->locking_xid = InvalidTransactionId;
436 if (user != gxact->owner && !superuser_arg(user))
438 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
439 errmsg("permission denied to finish prepared transaction"),
440 errhint("Must be superuser or the user that prepared the transaction.")));
443 * Note: it probably would be possible to allow committing from
444 * another database; but at the moment NOTIFY is known not to work and
445 * there may be some other issues as well. Hence disallow until
446 * someone gets motivated to make it work.
448 if (MyDatabaseId != proc->databaseId)
450 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
451 errmsg("prepared transaction belongs to another database"),
452 errhint("Connect to the database where the transaction was prepared to finish it.")));
454 /* OK for me to lock it */
455 gxact->locking_xid = GetTopTransactionId();
457 LWLockRelease(TwoPhaseStateLock);
462 LWLockRelease(TwoPhaseStateLock);
465 (errcode(ERRCODE_UNDEFINED_OBJECT),
466 errmsg("prepared transaction with identifier \"%s\" does not exist",
475 * Remove the prepared transaction from the shared memory array.
477 * NB: caller should have already removed it from ProcArray
480 RemoveGXact(GlobalTransaction gxact)
484 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
486 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
488 if (gxact == TwoPhaseState->prepXacts[i])
490 /* remove from the active array */
491 TwoPhaseState->numPrepXacts--;
492 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
494 /* and put it back in the freelist */
495 gxact->next = TwoPhaseState->freeGXacts;
496 TwoPhaseState->freeGXacts = gxact;
498 LWLockRelease(TwoPhaseStateLock);
504 LWLockRelease(TwoPhaseStateLock);
506 elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
510 * TransactionIdIsPrepared
511 * True iff transaction associated with the identifier is prepared
512 * for two-phase commit
514 * Note: only gxacts marked "valid" are considered; but notice we do not
515 * check the locking status.
517 * This is not currently exported, because it is only needed internally.
520 TransactionIdIsPrepared(TransactionId xid)
525 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
527 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
529 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
530 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
532 if (gxact->valid && pgxact->xid == xid)
539 LWLockRelease(TwoPhaseStateLock);
545 * Returns an array of all prepared transactions for the user-level
546 * function pg_prepared_xact.
548 * The returned array and all its elements are copies of internal data
549 * structures, to minimize the time we need to hold the TwoPhaseStateLock.
551 * WARNING -- we return even those transactions that are not fully prepared
552 * yet. The caller should filter them out if he doesn't want them.
554 * The returned array is palloc'd.
557 GetPreparedTransactionList(GlobalTransaction *gxacts)
559 GlobalTransaction array;
563 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
565 if (TwoPhaseState->numPrepXacts == 0)
567 LWLockRelease(TwoPhaseStateLock);
573 num = TwoPhaseState->numPrepXacts;
574 array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
576 for (i = 0; i < num; i++)
577 memcpy(array + i, TwoPhaseState->prepXacts[i],
578 sizeof(GlobalTransactionData));
580 LWLockRelease(TwoPhaseStateLock);
586 /* Working status for pg_prepared_xact */
589 GlobalTransaction array;
596 * Produce a view with one row per prepared transaction.
598 * This function is here so we don't have to export the
599 * GlobalTransactionData struct definition.
602 pg_prepared_xact(PG_FUNCTION_ARGS)
604 FuncCallContext *funcctx;
605 Working_State *status;
607 if (SRF_IS_FIRSTCALL())
610 MemoryContext oldcontext;
612 /* create a function context for cross-call persistence */
613 funcctx = SRF_FIRSTCALL_INIT();
616 * Switch to memory context appropriate for multiple function calls
618 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
620 /* build tupdesc for result tuples */
621 /* this had better match pg_prepared_xacts view in system_views.sql */
622 tupdesc = CreateTemplateTupleDesc(5, false);
623 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
625 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
627 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
628 TIMESTAMPTZOID, -1, 0);
629 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
631 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
634 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
637 * Collect all the 2PC status information that we will format and send
638 * out as a result set.
640 status = (Working_State *) palloc(sizeof(Working_State));
641 funcctx->user_fctx = (void *) status;
643 status->ngxacts = GetPreparedTransactionList(&status->array);
646 MemoryContextSwitchTo(oldcontext);
649 funcctx = SRF_PERCALL_SETUP();
650 status = (Working_State *) funcctx->user_fctx;
652 while (status->array != NULL && status->currIdx < status->ngxacts)
654 GlobalTransaction gxact = &status->array[status->currIdx++];
655 PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
656 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
666 * Form tuple with appropriate data.
668 MemSet(values, 0, sizeof(values));
669 MemSet(nulls, 0, sizeof(nulls));
671 values[0] = TransactionIdGetDatum(pgxact->xid);
672 values[1] = CStringGetTextDatum(gxact->gid);
673 values[2] = TimestampTzGetDatum(gxact->prepared_at);
674 values[3] = ObjectIdGetDatum(gxact->owner);
675 values[4] = ObjectIdGetDatum(proc->databaseId);
677 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
678 result = HeapTupleGetDatum(tuple);
679 SRF_RETURN_NEXT(funcctx, result);
682 SRF_RETURN_DONE(funcctx);
687 * Get the GlobalTransaction struct for a prepared transaction
690 static GlobalTransaction
691 TwoPhaseGetGXact(TransactionId xid)
693 GlobalTransaction result = NULL;
696 static TransactionId cached_xid = InvalidTransactionId;
697 static GlobalTransaction cached_gxact = NULL;
700 * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
701 * repeatedly for the same XID. We can save work with a simple cache.
703 if (xid == cached_xid)
706 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
708 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
710 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
711 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
713 if (pgxact->xid == xid)
720 LWLockRelease(TwoPhaseStateLock);
722 if (result == NULL) /* should not happen */
723 elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
726 cached_gxact = result;
732 * TwoPhaseGetDummyProc
733 * Get the dummy backend ID for prepared transaction specified by XID
735 * Dummy backend IDs are similar to real backend IDs of real backends.
736 * They start at MaxBackends + 1, and are unique across all currently active
737 * real backends and prepared transactions.
740 TwoPhaseGetDummyBackendId(TransactionId xid)
742 GlobalTransaction gxact = TwoPhaseGetGXact(xid);
744 return gxact->dummyBackendId;
748 * TwoPhaseGetDummyProc
749 * Get the PGPROC that represents a prepared transaction specified by XID
752 TwoPhaseGetDummyProc(TransactionId xid)
754 GlobalTransaction gxact = TwoPhaseGetGXact(xid);
756 return &ProcGlobal->allProcs[gxact->pgprocno];
759 /************************************************************************/
760 /* State file support */
761 /************************************************************************/
763 #define TwoPhaseFilePath(path, xid) \
764 snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
767 * 2PC state file format:
769 * 1. TwoPhaseFileHeader
770 * 2. TransactionId[] (subtransactions)
771 * 3. RelFileNode[] (files to be deleted at commit)
772 * 4. RelFileNode[] (files to be deleted at abort)
773 * 5. SharedInvalidationMessage[] (inval messages to be sent at commit)
774 * 6. TwoPhaseRecordOnDisk
776 * 8. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
779 * Each segment except the final CRC32 is MAXALIGN'd.
783 * Header for a 2PC state file
785 #define TWOPHASE_MAGIC 0x57F94532 /* format identifier */
787 typedef struct TwoPhaseFileHeader
789 uint32 magic; /* format identifier */
790 uint32 total_len; /* actual file length */
791 TransactionId xid; /* original transaction XID */
792 Oid database; /* OID of database it was in */
793 TimestampTz prepared_at; /* time of preparation */
794 Oid owner; /* user running the transaction */
795 int32 nsubxacts; /* number of following subxact XIDs */
796 int32 ncommitrels; /* number of delete-on-commit rels */
797 int32 nabortrels; /* number of delete-on-abort rels */
798 int32 ninvalmsgs; /* number of cache invalidation messages */
799 bool initfileinval; /* does relcache init file need invalidation? */
800 char gid[GIDSIZE]; /* GID for transaction */
801 } TwoPhaseFileHeader;
804 * Header for each record in a state file
806 * NOTE: len counts only the rmgr data, not the TwoPhaseRecordOnDisk header.
807 * The rmgr data will be stored starting on a MAXALIGN boundary.
809 typedef struct TwoPhaseRecordOnDisk
811 uint32 len; /* length of rmgr data */
812 TwoPhaseRmgrId rmid; /* resource manager for this record */
813 uint16 info; /* flag bits for use by rmgr */
814 } TwoPhaseRecordOnDisk;
817 * During prepare, the state file is assembled in memory before writing it
818 * to WAL and the actual state file. We use a chain of XLogRecData blocks
819 * so that we will be able to pass the state file contents directly to
824 XLogRecData *head; /* first data block in the chain */
825 XLogRecData *tail; /* last block in chain */
826 uint32 bytes_free; /* free bytes left in tail block */
827 uint32 total_len; /* total data bytes in chain */
832 * Append a block of data to records data structure.
834 * NB: each block is padded to a MAXALIGN multiple. This must be
835 * accounted for when the file is later read!
837 * The data is copied, so the caller is free to modify it afterwards.
840 save_state_data(const void *data, uint32 len)
842 uint32 padlen = MAXALIGN(len);
844 if (padlen > records.bytes_free)
846 records.tail->next = palloc0(sizeof(XLogRecData));
847 records.tail = records.tail->next;
848 records.tail->buffer = InvalidBuffer;
849 records.tail->len = 0;
850 records.tail->next = NULL;
852 records.bytes_free = Max(padlen, 512);
853 records.tail->data = palloc(records.bytes_free);
856 memcpy(((char *) records.tail->data) + records.tail->len, data, len);
857 records.tail->len += padlen;
858 records.bytes_free -= padlen;
859 records.total_len += padlen;
863 * Start preparing a state file.
865 * Initializes data structure and inserts the 2PC file header record.
868 StartPrepare(GlobalTransaction gxact)
870 PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
871 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
872 TransactionId xid = pgxact->xid;
873 TwoPhaseFileHeader hdr;
874 TransactionId *children;
875 RelFileNode *commitrels;
876 RelFileNode *abortrels;
877 SharedInvalidationMessage *invalmsgs;
879 /* Initialize linked list */
880 records.head = palloc0(sizeof(XLogRecData));
881 records.head->buffer = InvalidBuffer;
882 records.head->len = 0;
883 records.head->next = NULL;
885 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
886 records.head->data = palloc(records.bytes_free);
888 records.tail = records.head;
890 records.total_len = 0;
893 hdr.magic = TWOPHASE_MAGIC;
894 hdr.total_len = 0; /* EndPrepare will fill this in */
896 hdr.database = proc->databaseId;
897 hdr.prepared_at = gxact->prepared_at;
898 hdr.owner = gxact->owner;
899 hdr.nsubxacts = xactGetCommittedChildren(&children);
900 hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
901 hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
902 hdr.ninvalmsgs = xactGetCommittedInvalidationMessages(&invalmsgs,
904 StrNCpy(hdr.gid, gxact->gid, GIDSIZE);
906 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
909 * Add the additional info about subxacts, deletable files and cache
910 * invalidation messages.
912 if (hdr.nsubxacts > 0)
914 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
915 /* While we have the child-xact data, stuff it in the gxact too */
916 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
918 if (hdr.ncommitrels > 0)
920 save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
923 if (hdr.nabortrels > 0)
925 save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
928 if (hdr.ninvalmsgs > 0)
930 save_state_data(invalmsgs,
931 hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
937 * Finish preparing state file.
939 * Calculates CRC and writes state file to WAL and in pg_twophase directory.
942 EndPrepare(GlobalTransaction gxact)
944 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
945 TransactionId xid = pgxact->xid;
946 TwoPhaseFileHeader *hdr;
947 char path[MAXPGPATH];
949 pg_crc32 statefile_crc;
953 /* Add the end sentinel to the list of 2PC records */
954 RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID, 0,
957 /* Go back and fill in total_len in the file header record */
958 hdr = (TwoPhaseFileHeader *) records.head->data;
959 Assert(hdr->magic == TWOPHASE_MAGIC);
960 hdr->total_len = records.total_len + sizeof(pg_crc32);
963 * If the file size exceeds MaxAllocSize, we won't be able to read it in
964 * ReadTwoPhaseFile. Check for that now, rather than fail at commit time.
966 if (hdr->total_len > MaxAllocSize)
968 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
969 errmsg("two-phase state file maximum length exceeded")));
972 * Create the 2PC state file.
974 TwoPhaseFilePath(path, xid);
976 fd = OpenTransientFile(path,
977 O_CREAT | O_EXCL | O_WRONLY | PG_BINARY,
981 (errcode_for_file_access(),
982 errmsg("could not create two-phase state file \"%s\": %m",
985 /* Write data to file, and calculate CRC as we pass over it */
986 INIT_CRC32(statefile_crc);
988 for (record = records.head; record != NULL; record = record->next)
990 COMP_CRC32(statefile_crc, record->data, record->len);
991 if ((write(fd, record->data, record->len)) != record->len)
993 CloseTransientFile(fd);
995 (errcode_for_file_access(),
996 errmsg("could not write two-phase state file: %m")));
1000 FIN_CRC32(statefile_crc);
1003 * Write a deliberately bogus CRC to the state file; this is just paranoia
1004 * to catch the case where four more bytes will run us out of disk space.
1006 bogus_crc = ~statefile_crc;
1008 if ((write(fd, &bogus_crc, sizeof(pg_crc32))) != sizeof(pg_crc32))
1010 CloseTransientFile(fd);
1012 (errcode_for_file_access(),
1013 errmsg("could not write two-phase state file: %m")));
1016 /* Back up to prepare for rewriting the CRC */
1017 if (lseek(fd, -((off_t) sizeof(pg_crc32)), SEEK_CUR) < 0)
1019 CloseTransientFile(fd);
1021 (errcode_for_file_access(),
1022 errmsg("could not seek in two-phase state file: %m")));
1026 * The state file isn't valid yet, because we haven't written the correct
1027 * CRC yet. Before we do that, insert entry in WAL and flush it to disk.
1029 * Between the time we have written the WAL entry and the time we write
1030 * out the correct state file CRC, we have an inconsistency: the xact is
1031 * prepared according to WAL but not according to our on-disk state. We
1032 * use a critical section to force a PANIC if we are unable to complete
1033 * the write --- then, WAL replay should repair the inconsistency. The
1034 * odds of a PANIC actually occurring should be very tiny given that we
1035 * were able to write the bogus CRC above.
1037 * We have to set inCommit here, too; otherwise a checkpoint starting
1038 * immediately after the WAL record is inserted could complete without
1039 * fsync'ing our state file. (This is essentially the same kind of race
1040 * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1041 * uses inCommit for; see notes there.)
1043 * We save the PREPARE record's location in the gxact for later use by
1044 * CheckPointTwoPhase.
1046 START_CRIT_SECTION();
1048 MyPgXact->inCommit = true;
1050 gxact->prepare_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE,
1052 XLogFlush(gxact->prepare_lsn);
1054 /* If we crash now, we have prepared: WAL replay will fix things */
1056 /* write correct CRC and close file */
1057 if ((write(fd, &statefile_crc, sizeof(pg_crc32))) != sizeof(pg_crc32))
1059 CloseTransientFile(fd);
1061 (errcode_for_file_access(),
1062 errmsg("could not write two-phase state file: %m")));
1065 if (CloseTransientFile(fd) != 0)
1067 (errcode_for_file_access(),
1068 errmsg("could not close two-phase state file: %m")));
1071 * Mark the prepared transaction as valid. As soon as xact.c marks
1072 * MyPgXact as not running our XID (which it will do immediately after
1073 * this function returns), others can commit/rollback the xact.
1075 * NB: a side effect of this is to make a dummy ProcArray entry for the
1076 * prepared XID. This must happen before we clear the XID from MyPgXact,
1077 * else there is a window where the XID is not running according to
1078 * TransactionIdIsInProgress, and onlookers would be entitled to assume
1079 * the xact crashed. Instead we have a window where the same XID appears
1080 * twice in ProcArray, which is OK.
1082 MarkAsPrepared(gxact);
1085 * Now we can mark ourselves as out of the commit critical section: a
1086 * checkpoint starting after this will certainly see the gxact as a
1087 * candidate for fsyncing.
1089 MyPgXact->inCommit = false;
1094 * Wait for synchronous replication, if required.
1096 * Note that at this stage we have marked the prepare, but still show as
1097 * running in the procarray (twice!) and continue to hold locks.
1099 SyncRepWaitForLSN(gxact->prepare_lsn);
1101 records.tail = records.head = NULL;
1105 * Register a 2PC record to be written to state file.
1108 RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info,
1109 const void *data, uint32 len)
1111 TwoPhaseRecordOnDisk record;
1116 save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1118 save_state_data(data, len);
1123 * Read and validate the state file for xid.
1125 * If it looks OK (has a valid magic number and CRC), return the palloc'd
1126 * contents of the file. Otherwise return NULL.
1129 ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
1131 char path[MAXPGPATH];
1133 TwoPhaseFileHeader *hdr;
1140 TwoPhaseFilePath(path, xid);
1142 fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
1147 (errcode_for_file_access(),
1148 errmsg("could not open two-phase state file \"%s\": %m",
1154 * Check file length. We can determine a lower bound pretty easily. We
1155 * set an upper bound to avoid palloc() failure on a corrupt file, though
1156 * we can't guarantee that we won't get an out of memory error anyway,
1157 * even on a valid file.
1159 if (fstat(fd, &stat))
1161 CloseTransientFile(fd);
1164 (errcode_for_file_access(),
1165 errmsg("could not stat two-phase state file \"%s\": %m",
1170 if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1171 MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1172 sizeof(pg_crc32)) ||
1173 stat.st_size > MaxAllocSize)
1175 CloseTransientFile(fd);
1179 crc_offset = stat.st_size - sizeof(pg_crc32);
1180 if (crc_offset != MAXALIGN(crc_offset))
1182 CloseTransientFile(fd);
1187 * OK, slurp in the file.
1189 buf = (char *) palloc(stat.st_size);
1191 if (read(fd, buf, stat.st_size) != stat.st_size)
1193 CloseTransientFile(fd);
1196 (errcode_for_file_access(),
1197 errmsg("could not read two-phase state file \"%s\": %m",
1203 CloseTransientFile(fd);
1205 hdr = (TwoPhaseFileHeader *) buf;
1206 if (hdr->magic != TWOPHASE_MAGIC || hdr->total_len != stat.st_size)
1212 INIT_CRC32(calc_crc);
1213 COMP_CRC32(calc_crc, buf, crc_offset);
1214 FIN_CRC32(calc_crc);
1216 file_crc = *((pg_crc32 *) (buf + crc_offset));
1218 if (!EQ_CRC32(calc_crc, file_crc))
1228 * Confirms an xid is prepared, during recovery
1231 StandbyTransactionIdIsPrepared(TransactionId xid)
1234 TwoPhaseFileHeader *hdr;
1237 Assert(TransactionIdIsValid(xid));
1239 if (max_prepared_xacts <= 0)
1240 return false; /* nothing to do */
1242 /* Read and validate file */
1243 buf = ReadTwoPhaseFile(xid, false);
1247 /* Check header also */
1248 hdr = (TwoPhaseFileHeader *) buf;
1249 result = TransactionIdEquals(hdr->xid, xid);
1256 * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1259 FinishPreparedTransaction(const char *gid, bool isCommit)
1261 GlobalTransaction gxact;
1267 TwoPhaseFileHeader *hdr;
1268 TransactionId latestXid;
1269 TransactionId *children;
1270 RelFileNode *commitrels;
1271 RelFileNode *abortrels;
1272 RelFileNode *delrels;
1274 SharedInvalidationMessage *invalmsgs;
1278 * Validate the GID, and lock the GXACT to ensure that two backends do not
1279 * try to commit the same GID at once.
1281 gxact = LockGXact(gid, GetUserId());
1282 proc = &ProcGlobal->allProcs[gxact->pgprocno];
1283 pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1287 * Read and validate the state file
1289 buf = ReadTwoPhaseFile(xid, true);
1292 (errcode(ERRCODE_DATA_CORRUPTED),
1293 errmsg("two-phase state file for transaction %u is corrupt",
1297 * Disassemble the header area
1299 hdr = (TwoPhaseFileHeader *) buf;
1300 Assert(TransactionIdEquals(hdr->xid, xid));
1301 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1302 children = (TransactionId *) bufptr;
1303 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1304 commitrels = (RelFileNode *) bufptr;
1305 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1306 abortrels = (RelFileNode *) bufptr;
1307 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1308 invalmsgs = (SharedInvalidationMessage *) bufptr;
1309 bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1311 /* compute latestXid among all children */
1312 latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1315 * The order of operations here is critical: make the XLOG entry for
1316 * commit or abort, then mark the transaction committed or aborted in
1317 * pg_clog, then remove its PGPROC from the global ProcArray (which means
1318 * TransactionIdIsInProgress will stop saying the prepared xact is in
1319 * progress), then run the post-commit or post-abort callbacks. The
1320 * callbacks will release the locks the transaction held.
1323 RecordTransactionCommitPrepared(xid,
1324 hdr->nsubxacts, children,
1325 hdr->ncommitrels, commitrels,
1326 hdr->ninvalmsgs, invalmsgs,
1327 hdr->initfileinval);
1329 RecordTransactionAbortPrepared(xid,
1330 hdr->nsubxacts, children,
1331 hdr->nabortrels, abortrels);
1333 ProcArrayRemove(proc, latestXid);
1336 * In case we fail while running the callbacks, mark the gxact invalid so
1337 * no one else will try to commit/rollback, and so it can be recycled
1338 * properly later. It is still locked by our XID so it won't go away yet.
1340 * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1342 gxact->valid = false;
1345 * We have to remove any files that were supposed to be dropped. For
1346 * consistency with the regular xact.c code paths, must do this before
1347 * releasing locks, so do it before running the callbacks.
1349 * NB: this code knows that we couldn't be dropping any temp rels ...
1353 delrels = commitrels;
1354 ndelrels = hdr->ncommitrels;
1358 delrels = abortrels;
1359 ndelrels = hdr->nabortrels;
1361 for (i = 0; i < ndelrels; i++)
1363 SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1365 smgrdounlink(srel, false);
1370 * Handle cache invalidation messages.
1372 * Relcache init file invalidation requires processing both before and
1373 * after we send the SI messages. See AtEOXact_Inval()
1375 if (hdr->initfileinval)
1376 RelationCacheInitFilePreInvalidate();
1377 SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1378 if (hdr->initfileinval)
1379 RelationCacheInitFilePostInvalidate();
1381 /* And now do the callbacks */
1383 ProcessRecords(bufptr, xid, twophase_postcommit_callbacks);
1385 ProcessRecords(bufptr, xid, twophase_postabort_callbacks);
1387 PredicateLockTwoPhaseFinish(xid, isCommit);
1389 /* Count the prepared xact as committed or aborted */
1390 AtEOXact_PgStat(isCommit);
1393 * And now we can clean up our mess.
1395 RemoveTwoPhaseFile(xid, true);
1403 * Scan a 2PC state file (already read into memory by ReadTwoPhaseFile)
1404 * and call the indicated callbacks for each 2PC record.
1407 ProcessRecords(char *bufptr, TransactionId xid,
1408 const TwoPhaseCallback callbacks[])
1412 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1414 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1415 if (record->rmid == TWOPHASE_RM_END_ID)
1418 bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1420 if (callbacks[record->rmid] != NULL)
1421 callbacks[record->rmid] (xid, record->info,
1422 (void *) bufptr, record->len);
1424 bufptr += MAXALIGN(record->len);
1429 * Remove the 2PC file for the specified XID.
1431 * If giveWarning is false, do not complain about file-not-present;
1432 * this is an expected case during WAL replay.
1435 RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
1437 char path[MAXPGPATH];
1439 TwoPhaseFilePath(path, xid);
1441 if (errno != ENOENT || giveWarning)
1443 (errcode_for_file_access(),
1444 errmsg("could not remove two-phase state file \"%s\": %m",
1449 * Recreates a state file. This is used in WAL replay.
1451 * Note: content and len don't include CRC.
1454 RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
1456 char path[MAXPGPATH];
1457 pg_crc32 statefile_crc;
1461 INIT_CRC32(statefile_crc);
1462 COMP_CRC32(statefile_crc, content, len);
1463 FIN_CRC32(statefile_crc);
1465 TwoPhaseFilePath(path, xid);
1467 fd = OpenTransientFile(path,
1468 O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY,
1472 (errcode_for_file_access(),
1473 errmsg("could not recreate two-phase state file \"%s\": %m",
1476 /* Write content and CRC */
1477 if (write(fd, content, len) != len)
1479 CloseTransientFile(fd);
1481 (errcode_for_file_access(),
1482 errmsg("could not write two-phase state file: %m")));
1484 if (write(fd, &statefile_crc, sizeof(pg_crc32)) != sizeof(pg_crc32))
1486 CloseTransientFile(fd);
1488 (errcode_for_file_access(),
1489 errmsg("could not write two-phase state file: %m")));
1493 * We must fsync the file because the end-of-replay checkpoint will not do
1494 * so, there being no GXACT in shared memory yet to tell it to.
1496 if (pg_fsync(fd) != 0)
1498 CloseTransientFile(fd);
1500 (errcode_for_file_access(),
1501 errmsg("could not fsync two-phase state file: %m")));
1504 if (CloseTransientFile(fd) != 0)
1506 (errcode_for_file_access(),
1507 errmsg("could not close two-phase state file: %m")));
1511 * CheckPointTwoPhase -- handle 2PC component of checkpointing.
1513 * We must fsync the state file of any GXACT that is valid and has a PREPARE
1514 * LSN <= the checkpoint's redo horizon. (If the gxact isn't valid yet or
1515 * has a later LSN, this checkpoint is not responsible for fsyncing it.)
1517 * This is deliberately run as late as possible in the checkpoint sequence,
1518 * because GXACTs ordinarily have short lifespans, and so it is quite
1519 * possible that GXACTs that were valid at checkpoint start will no longer
1520 * exist if we wait a little bit.
1522 * If a GXACT remains valid across multiple checkpoints, it'll be fsynced
1523 * each time. This is considered unusual enough that we don't bother to
1524 * expend any extra code to avoid the redundant fsyncs. (They should be
1525 * reasonably cheap anyway, since they won't cause I/O.)
1528 CheckPointTwoPhase(XLogRecPtr redo_horizon)
1530 TransactionId *xids;
1532 char path[MAXPGPATH];
1536 * We don't want to hold the TwoPhaseStateLock while doing I/O, so we grab
1537 * it just long enough to make a list of the XIDs that require fsyncing,
1538 * and then do the I/O afterwards.
1540 * This approach creates a race condition: someone else could delete a
1541 * GXACT between the time we release TwoPhaseStateLock and the time we try
1542 * to open its state file. We handle this by special-casing ENOENT
1543 * failures: if we see that, we verify that the GXACT is no longer valid,
1544 * and if so ignore the failure.
1546 if (max_prepared_xacts <= 0)
1547 return; /* nothing to do */
1549 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1551 xids = (TransactionId *) palloc(max_prepared_xacts * sizeof(TransactionId));
1554 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1556 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1558 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1559 PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1562 XLByteLE(gxact->prepare_lsn, redo_horizon))
1563 xids[nxids++] = pgxact->xid;
1566 LWLockRelease(TwoPhaseStateLock);
1568 for (i = 0; i < nxids; i++)
1570 TransactionId xid = xids[i];
1573 TwoPhaseFilePath(path, xid);
1575 fd = OpenTransientFile(path, O_RDWR | PG_BINARY, 0);
1578 if (errno == ENOENT)
1580 /* OK if gxact is no longer valid */
1581 if (!TransactionIdIsPrepared(xid))
1583 /* Restore errno in case it was changed */
1587 (errcode_for_file_access(),
1588 errmsg("could not open two-phase state file \"%s\": %m",
1592 if (pg_fsync(fd) != 0)
1594 CloseTransientFile(fd);
1596 (errcode_for_file_access(),
1597 errmsg("could not fsync two-phase state file \"%s\": %m",
1601 if (CloseTransientFile(fd) != 0)
1603 (errcode_for_file_access(),
1604 errmsg("could not close two-phase state file \"%s\": %m",
1610 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1614 * PrescanPreparedTransactions
1616 * Scan the pg_twophase directory and determine the range of valid XIDs
1617 * present. This is run during database startup, after we have completed
1618 * reading WAL. ShmemVariableCache->nextXid has been set to one more than
1619 * the highest XID for which evidence exists in WAL.
1621 * We throw away any prepared xacts with main XID beyond nextXid --- if any
1622 * are present, it suggests that the DBA has done a PITR recovery to an
1623 * earlier point in time without cleaning out pg_twophase. We dare not
1624 * try to recover such prepared xacts since they likely depend on database
1625 * state that doesn't exist now.
1627 * However, we will advance nextXid beyond any subxact XIDs belonging to
1628 * valid prepared xacts. We need to do this since subxact commit doesn't
1629 * write a WAL entry, and so there might be no evidence in WAL of those
1632 * Our other responsibility is to determine and return the oldest valid XID
1633 * among the prepared xacts (if none, return ShmemVariableCache->nextXid).
1634 * This is needed to synchronize pg_subtrans startup properly.
1636 * If xids_p and nxids_p are not NULL, pointer to a palloc'd array of all
1637 * top-level xids is stored in *xids_p. The number of entries in the array
1638 * is returned in *nxids_p.
1641 PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
1643 TransactionId origNextXid = ShmemVariableCache->nextXid;
1644 TransactionId result = origNextXid;
1646 struct dirent *clde;
1647 TransactionId *xids = NULL;
1651 cldir = AllocateDir(TWOPHASE_DIR);
1652 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1654 if (strlen(clde->d_name) == 8 &&
1655 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1659 TwoPhaseFileHeader *hdr;
1660 TransactionId *subxids;
1663 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1665 /* Reject XID if too new */
1666 if (TransactionIdFollowsOrEquals(xid, origNextXid))
1669 (errmsg("removing future two-phase state file \"%s\"",
1671 RemoveTwoPhaseFile(xid, true);
1676 * Note: we can't check if already processed because clog
1677 * subsystem isn't up yet.
1680 /* Read and validate file */
1681 buf = ReadTwoPhaseFile(xid, true);
1685 (errmsg("removing corrupt two-phase state file \"%s\"",
1687 RemoveTwoPhaseFile(xid, true);
1691 /* Deconstruct header */
1692 hdr = (TwoPhaseFileHeader *) buf;
1693 if (!TransactionIdEquals(hdr->xid, xid))
1696 (errmsg("removing corrupt two-phase state file \"%s\"",
1698 RemoveTwoPhaseFile(xid, true);
1704 * OK, we think this file is valid. Incorporate xid into the
1705 * running-minimum result.
1707 if (TransactionIdPrecedes(xid, result))
1711 * Examine subtransaction XIDs ... they should all follow main
1712 * XID, and they may force us to advance nextXid.
1714 * We don't expect anyone else to modify nextXid, hence we don't
1715 * need to hold a lock while examining it. We still acquire the
1716 * lock to modify it, though.
1718 subxids = (TransactionId *)
1719 (buf + MAXALIGN(sizeof(TwoPhaseFileHeader)));
1720 for (i = 0; i < hdr->nsubxacts; i++)
1722 TransactionId subxid = subxids[i];
1724 Assert(TransactionIdFollows(subxid, xid));
1725 if (TransactionIdFollowsOrEquals(subxid,
1726 ShmemVariableCache->nextXid))
1728 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
1729 ShmemVariableCache->nextXid = subxid;
1730 TransactionIdAdvance(ShmemVariableCache->nextXid);
1731 LWLockRelease(XidGenLock);
1738 if (nxids == allocsize)
1743 xids = palloc(allocsize * sizeof(TransactionId));
1747 allocsize = allocsize * 2;
1748 xids = repalloc(xids, allocsize * sizeof(TransactionId));
1751 xids[nxids++] = xid;
1769 * StandbyRecoverPreparedTransactions
1771 * Scan the pg_twophase directory and setup all the required information to
1772 * allow standby queries to treat prepared transactions as still active.
1773 * This is never called at the end of recovery - we use
1774 * RecoverPreparedTransactions() at that point.
1776 * Currently we simply call SubTransSetParent() for any subxids of prepared
1777 * transactions. If overwriteOK is true, it's OK if some XIDs have already
1778 * been marked in pg_subtrans.
1781 StandbyRecoverPreparedTransactions(bool overwriteOK)
1784 struct dirent *clde;
1786 cldir = AllocateDir(TWOPHASE_DIR);
1787 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1789 if (strlen(clde->d_name) == 8 &&
1790 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1794 TwoPhaseFileHeader *hdr;
1795 TransactionId *subxids;
1798 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1800 /* Already processed? */
1801 if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
1804 (errmsg("removing stale two-phase state file \"%s\"",
1806 RemoveTwoPhaseFile(xid, true);
1810 /* Read and validate file */
1811 buf = ReadTwoPhaseFile(xid, true);
1815 (errmsg("removing corrupt two-phase state file \"%s\"",
1817 RemoveTwoPhaseFile(xid, true);
1821 /* Deconstruct header */
1822 hdr = (TwoPhaseFileHeader *) buf;
1823 if (!TransactionIdEquals(hdr->xid, xid))
1826 (errmsg("removing corrupt two-phase state file \"%s\"",
1828 RemoveTwoPhaseFile(xid, true);
1834 * Examine subtransaction XIDs ... they should all follow main
1837 subxids = (TransactionId *)
1838 (buf + MAXALIGN(sizeof(TwoPhaseFileHeader)));
1839 for (i = 0; i < hdr->nsubxacts; i++)
1841 TransactionId subxid = subxids[i];
1843 Assert(TransactionIdFollows(subxid, xid));
1844 SubTransSetParent(xid, subxid, overwriteOK);
1852 * RecoverPreparedTransactions
1854 * Scan the pg_twophase directory and reload shared-memory state for each
1855 * prepared transaction (reacquire locks, etc). This is run during database
1859 RecoverPreparedTransactions(void)
1861 char dir[MAXPGPATH];
1863 struct dirent *clde;
1864 bool overwriteOK = false;
1866 snprintf(dir, MAXPGPATH, "%s", TWOPHASE_DIR);
1868 cldir = AllocateDir(dir);
1869 while ((clde = ReadDir(cldir, dir)) != NULL)
1871 if (strlen(clde->d_name) == 8 &&
1872 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1877 TwoPhaseFileHeader *hdr;
1878 TransactionId *subxids;
1879 GlobalTransaction gxact;
1882 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1884 /* Already processed? */
1885 if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
1888 (errmsg("removing stale two-phase state file \"%s\"",
1890 RemoveTwoPhaseFile(xid, true);
1894 /* Read and validate file */
1895 buf = ReadTwoPhaseFile(xid, true);
1899 (errmsg("removing corrupt two-phase state file \"%s\"",
1901 RemoveTwoPhaseFile(xid, true);
1906 (errmsg("recovering prepared transaction %u", xid)));
1908 /* Deconstruct header */
1909 hdr = (TwoPhaseFileHeader *) buf;
1910 Assert(TransactionIdEquals(hdr->xid, xid));
1911 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1912 subxids = (TransactionId *) bufptr;
1913 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1914 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1915 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1916 bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1919 * It's possible that SubTransSetParent has been set before, if
1920 * the prepared transaction generated xid assignment records. Test
1921 * here must match one used in AssignTransactionId().
1923 if (InHotStandby && hdr->nsubxacts >= PGPROC_MAX_CACHED_SUBXIDS)
1927 * Reconstruct subtrans state for the transaction --- needed
1928 * because pg_subtrans is not preserved over a restart. Note that
1929 * we are linking all the subtransactions directly to the
1930 * top-level XID; there may originally have been a more complex
1931 * hierarchy, but there's no need to restore that exactly.
1933 for (i = 0; i < hdr->nsubxacts; i++)
1934 SubTransSetParent(subxids[i], xid, overwriteOK);
1937 * Recreate its GXACT and dummy PGPROC
1939 * Note: since we don't have the PREPARE record's WAL location at
1940 * hand, we leave prepare_lsn zeroes. This means the GXACT will
1941 * be fsync'd on every future checkpoint. We assume this
1942 * situation is infrequent enough that the performance cost is
1943 * negligible (especially since we know the state file has already
1946 gxact = MarkAsPreparing(xid, hdr->gid,
1948 hdr->owner, hdr->database);
1949 GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1950 MarkAsPrepared(gxact);
1953 * Recover other state (notably locks) using resource managers
1955 ProcessRecords(bufptr, xid, twophase_recover_callbacks);
1958 * Release locks held by the standby process after we process each
1959 * prepared transaction. As a result, we don't need too many
1960 * additional locks at any one time.
1963 StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
1972 * RecordTransactionCommitPrepared
1974 * This is basically the same as RecordTransactionCommit: in particular,
1975 * we must set the inCommit flag to avoid a race condition.
1977 * We know the transaction made at least one XLOG entry (its PREPARE),
1978 * so it is never possible to optimize out the commit record.
1981 RecordTransactionCommitPrepared(TransactionId xid,
1983 TransactionId *children,
1987 SharedInvalidationMessage *invalmsgs,
1990 XLogRecData rdata[4];
1992 xl_xact_commit_prepared xlrec;
1995 START_CRIT_SECTION();
1997 /* See notes in RecordTransactionCommit */
1998 MyPgXact->inCommit = true;
2000 /* Emit the XLOG commit record */
2002 xlrec.crec.xact_time = GetCurrentTimestamp();
2003 xlrec.crec.xinfo = initfileinval ? XACT_COMPLETION_UPDATE_RELCACHE_FILE : 0;
2004 xlrec.crec.nmsgs = 0;
2005 xlrec.crec.nrels = nrels;
2006 xlrec.crec.nsubxacts = nchildren;
2007 xlrec.crec.nmsgs = ninvalmsgs;
2009 rdata[0].data = (char *) (&xlrec);
2010 rdata[0].len = MinSizeOfXactCommitPrepared;
2011 rdata[0].buffer = InvalidBuffer;
2012 /* dump rels to delete */
2015 rdata[0].next = &(rdata[1]);
2016 rdata[1].data = (char *) rels;
2017 rdata[1].len = nrels * sizeof(RelFileNode);
2018 rdata[1].buffer = InvalidBuffer;
2021 /* dump committed child Xids */
2024 rdata[lastrdata].next = &(rdata[2]);
2025 rdata[2].data = (char *) children;
2026 rdata[2].len = nchildren * sizeof(TransactionId);
2027 rdata[2].buffer = InvalidBuffer;
2030 /* dump cache invalidation messages */
2033 rdata[lastrdata].next = &(rdata[3]);
2034 rdata[3].data = (char *) invalmsgs;
2035 rdata[3].len = ninvalmsgs * sizeof(SharedInvalidationMessage);
2036 rdata[3].buffer = InvalidBuffer;
2039 rdata[lastrdata].next = NULL;
2041 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT_PREPARED, rdata);
2044 * We don't currently try to sleep before flush here ... nor is there any
2045 * support for async commit of a prepared xact (the very idea is probably
2049 /* Flush XLOG to disk */
2052 /* Mark the transaction committed in pg_clog */
2053 TransactionIdCommitTree(xid, nchildren, children);
2055 /* Checkpoint can proceed now */
2056 MyPgXact->inCommit = false;
2061 * Wait for synchronous replication, if required.
2063 * Note that at this stage we have marked clog, but still show as running
2064 * in the procarray and continue to hold locks.
2066 SyncRepWaitForLSN(recptr);
2070 * RecordTransactionAbortPrepared
2072 * This is basically the same as RecordTransactionAbort.
2074 * We know the transaction made at least one XLOG entry (its PREPARE),
2075 * so it is never possible to optimize out the abort record.
2078 RecordTransactionAbortPrepared(TransactionId xid,
2080 TransactionId *children,
2084 XLogRecData rdata[3];
2086 xl_xact_abort_prepared xlrec;
2090 * Catch the scenario where we aborted partway through
2091 * RecordTransactionCommitPrepared ...
2093 if (TransactionIdDidCommit(xid))
2094 elog(PANIC, "cannot abort transaction %u, it was already committed",
2097 START_CRIT_SECTION();
2099 /* Emit the XLOG abort record */
2101 xlrec.arec.xact_time = GetCurrentTimestamp();
2102 xlrec.arec.nrels = nrels;
2103 xlrec.arec.nsubxacts = nchildren;
2104 rdata[0].data = (char *) (&xlrec);
2105 rdata[0].len = MinSizeOfXactAbortPrepared;
2106 rdata[0].buffer = InvalidBuffer;
2107 /* dump rels to delete */
2110 rdata[0].next = &(rdata[1]);
2111 rdata[1].data = (char *) rels;
2112 rdata[1].len = nrels * sizeof(RelFileNode);
2113 rdata[1].buffer = InvalidBuffer;
2116 /* dump committed child Xids */
2119 rdata[lastrdata].next = &(rdata[2]);
2120 rdata[2].data = (char *) children;
2121 rdata[2].len = nchildren * sizeof(TransactionId);
2122 rdata[2].buffer = InvalidBuffer;
2125 rdata[lastrdata].next = NULL;
2127 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT_PREPARED, rdata);
2129 /* Always flush, since we're about to remove the 2PC state file */
2133 * Mark the transaction aborted in clog. This is not absolutely necessary
2134 * but we may as well do it while we are here.
2136 TransactionIdAbortTree(xid, nchildren, children);
2141 * Wait for synchronous replication, if required.
2143 * Note that at this stage we have marked clog, but still show as running
2144 * in the procarray and continue to hold locks.
2146 SyncRepWaitForLSN(recptr);