The code to unlink dropped relations in FinishPreparedTransaction() was
[PostgreSQL.git] / src / backend / access / transam / twophase.c
blob9434f8ff2ef9825243c42d034dd7eca7d8c2e831
1 /*-------------------------------------------------------------------------
3 * twophase.c
4 * Two-phase commit support functions.
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
9 * IDENTIFICATION
10 * $PostgreSQL$
12 * NOTES
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 *-------------------------------------------------------------------------
37 #include "postgres.h"
39 #include <fcntl.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <time.h>
43 #include <unistd.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"
54 #include "funcapi.h"
55 #include "miscadmin.h"
56 #include "pg_trace.h"
57 #include "pgstat.h"
58 #include "storage/fd.h"
59 #include "storage/procarray.h"
60 #include "storage/smgr.h"
61 #include "utils/builtins.h"
62 #include "utils/memutils.h"
66 * Directory where Two-phase commit files reside within PGDATA
68 #define TWOPHASE_DIR "pg_twophase"
70 /* GUC variable, can't be changed after startup */
71 int max_prepared_xacts = 0;
74 * This struct describes one global transaction that is in prepared state
75 * or attempting to become prepared.
77 * The first component of the struct is a dummy PGPROC that is inserted
78 * into the global ProcArray so that the transaction appears to still be
79 * running and holding locks. It must be first because we cast pointers
80 * to PGPROC and pointers to GlobalTransactionData back and forth.
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 * contained 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
98 * the freelist.
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
105 * twophase.h
107 #define GIDSIZE 200
109 typedef struct GlobalTransactionData
111 PGPROC proc; /* dummy proc */
112 TimestampTz prepared_at; /* time of preparation */
113 XLogRecPtr prepare_lsn; /* XLOG offset of prepare record */
114 Oid owner; /* ID of user that executed the xact */
115 TransactionId locking_xid; /* top-level XID of backend working on xact */
116 bool valid; /* TRUE if fully prepared */
117 char gid[GIDSIZE]; /* The GID assigned to the prepared xact */
118 } GlobalTransactionData;
121 * Two Phase Commit shared state. Access to this struct is protected
122 * by TwoPhaseStateLock.
124 typedef struct TwoPhaseStateData
126 /* Head of linked list of free GlobalTransactionData structs */
127 GlobalTransaction freeGXacts;
129 /* Number of valid prepXacts entries. */
130 int numPrepXacts;
133 * There are max_prepared_xacts items in this array, but C wants a
134 * fixed-size array.
136 GlobalTransaction prepXacts[1]; /* VARIABLE LENGTH ARRAY */
137 } TwoPhaseStateData; /* VARIABLE LENGTH STRUCT */
139 static TwoPhaseStateData *TwoPhaseState;
142 static void RecordTransactionCommitPrepared(TransactionId xid,
143 int nchildren,
144 TransactionId *children,
145 int nrels,
146 RelFileNode *rels);
147 static void RecordTransactionAbortPrepared(TransactionId xid,
148 int nchildren,
149 TransactionId *children,
150 int nrels,
151 RelFileNode *rels);
152 static void ProcessRecords(char *bufptr, TransactionId xid,
153 const TwoPhaseCallback callbacks[]);
157 * Initialization of shared memory
159 Size
160 TwoPhaseShmemSize(void)
162 Size size;
164 /* Need the fixed struct, the array of pointers, and the GTD structs */
165 size = offsetof(TwoPhaseStateData, prepXacts);
166 size = add_size(size, mul_size(max_prepared_xacts,
167 sizeof(GlobalTransaction)));
168 size = MAXALIGN(size);
169 size = add_size(size, mul_size(max_prepared_xacts,
170 sizeof(GlobalTransactionData)));
172 return size;
175 void
176 TwoPhaseShmemInit(void)
178 bool found;
180 TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
181 TwoPhaseShmemSize(),
182 &found);
183 if (!IsUnderPostmaster)
185 GlobalTransaction gxacts;
186 int i;
188 Assert(!found);
189 TwoPhaseState->freeGXacts = NULL;
190 TwoPhaseState->numPrepXacts = 0;
193 * Initialize the linked list of free GlobalTransactionData structs
195 gxacts = (GlobalTransaction)
196 ((char *) TwoPhaseState +
197 MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
198 sizeof(GlobalTransaction) * max_prepared_xacts));
199 for (i = 0; i < max_prepared_xacts; i++)
201 gxacts[i].proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
202 TwoPhaseState->freeGXacts = &gxacts[i];
205 else
206 Assert(found);
211 * MarkAsPreparing
212 * Reserve the GID for the given transaction.
214 * Internally, this creates a gxact struct and puts it into the active array.
215 * NOTE: this is also used when reloading a gxact after a crash; so avoid
216 * assuming that we can use very much backend context.
218 GlobalTransaction
219 MarkAsPreparing(TransactionId xid, const char *gid,
220 TimestampTz prepared_at, Oid owner, Oid databaseid)
222 GlobalTransaction gxact;
223 int i;
225 if (strlen(gid) >= GIDSIZE)
226 ereport(ERROR,
227 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
228 errmsg("transaction identifier \"%s\" is too long",
229 gid)));
231 /* fail immediately if feature is disabled */
232 if (max_prepared_xacts == 0)
233 ereport(ERROR,
234 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
235 errmsg("prepared transactions are disabled"),
236 errhint("Set max_prepared_transactions to a nonzero value.")));
238 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
241 * First, find and recycle any gxacts that failed during prepare. We do
242 * this partly to ensure we don't mistakenly say their GIDs are still
243 * reserved, and partly so we don't fail on out-of-slots unnecessarily.
245 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
247 gxact = TwoPhaseState->prepXacts[i];
248 if (!gxact->valid && !TransactionIdIsActive(gxact->locking_xid))
250 /* It's dead Jim ... remove from the active array */
251 TwoPhaseState->numPrepXacts--;
252 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
253 /* and put it back in the freelist */
254 gxact->proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
255 TwoPhaseState->freeGXacts = gxact;
256 /* Back up index count too, so we don't miss scanning one */
257 i--;
261 /* Check for conflicting GID */
262 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
264 gxact = TwoPhaseState->prepXacts[i];
265 if (strcmp(gxact->gid, gid) == 0)
267 ereport(ERROR,
268 (errcode(ERRCODE_DUPLICATE_OBJECT),
269 errmsg("transaction identifier \"%s\" is already in use",
270 gid)));
274 /* Get a free gxact from the freelist */
275 if (TwoPhaseState->freeGXacts == NULL)
276 ereport(ERROR,
277 (errcode(ERRCODE_OUT_OF_MEMORY),
278 errmsg("maximum number of prepared transactions reached"),
279 errhint("Increase max_prepared_transactions (currently %d).",
280 max_prepared_xacts)));
281 gxact = TwoPhaseState->freeGXacts;
282 TwoPhaseState->freeGXacts = (GlobalTransaction) gxact->proc.links.next;
284 /* Initialize it */
285 MemSet(&gxact->proc, 0, sizeof(PGPROC));
286 SHMQueueElemInit(&(gxact->proc.links));
287 gxact->proc.waitStatus = STATUS_OK;
288 /* We set up the gxact's VXID as InvalidBackendId/XID */
289 gxact->proc.lxid = (LocalTransactionId) xid;
290 gxact->proc.xid = xid;
291 gxact->proc.xmin = InvalidTransactionId;
292 gxact->proc.pid = 0;
293 gxact->proc.backendId = InvalidBackendId;
294 gxact->proc.databaseId = databaseid;
295 gxact->proc.roleId = owner;
296 gxact->proc.inCommit = false;
297 gxact->proc.vacuumFlags = 0;
298 gxact->proc.lwWaiting = false;
299 gxact->proc.lwExclusive = false;
300 gxact->proc.lwWaitLink = NULL;
301 gxact->proc.waitLock = NULL;
302 gxact->proc.waitProcLock = NULL;
303 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
304 SHMQueueInit(&(gxact->proc.myProcLocks[i]));
305 /* subxid data must be filled later by GXactLoadSubxactData */
306 gxact->proc.subxids.overflowed = false;
307 gxact->proc.subxids.nxids = 0;
309 gxact->prepared_at = prepared_at;
310 /* initialize LSN to 0 (start of WAL) */
311 gxact->prepare_lsn.xlogid = 0;
312 gxact->prepare_lsn.xrecoff = 0;
313 gxact->owner = owner;
314 gxact->locking_xid = xid;
315 gxact->valid = false;
316 strcpy(gxact->gid, gid);
318 /* And insert it into the active array */
319 Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
320 TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
322 LWLockRelease(TwoPhaseStateLock);
324 return gxact;
328 * GXactLoadSubxactData
330 * If the transaction being persisted had any subtransactions, this must
331 * be called before MarkAsPrepared() to load information into the dummy
332 * PGPROC.
334 static void
335 GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts,
336 TransactionId *children)
338 /* We need no extra lock since the GXACT isn't valid yet */
339 if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
341 gxact->proc.subxids.overflowed = true;
342 nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
344 if (nsubxacts > 0)
346 memcpy(gxact->proc.subxids.xids, children,
347 nsubxacts * sizeof(TransactionId));
348 gxact->proc.subxids.nxids = nsubxacts;
353 * MarkAsPrepared
354 * Mark the GXACT as fully valid, and enter it into the global ProcArray.
356 static void
357 MarkAsPrepared(GlobalTransaction gxact)
359 /* Lock here may be overkill, but I'm not convinced of that ... */
360 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
361 Assert(!gxact->valid);
362 gxact->valid = true;
363 LWLockRelease(TwoPhaseStateLock);
366 * Put it into the global ProcArray so TransactionIdIsInProgress considers
367 * the XID as still running.
369 ProcArrayAdd(&gxact->proc);
373 * LockGXact
374 * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
376 static GlobalTransaction
377 LockGXact(const char *gid, Oid user)
379 int i;
381 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
383 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
385 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
387 /* Ignore not-yet-valid GIDs */
388 if (!gxact->valid)
389 continue;
390 if (strcmp(gxact->gid, gid) != 0)
391 continue;
393 /* Found it, but has someone else got it locked? */
394 if (TransactionIdIsValid(gxact->locking_xid))
396 if (TransactionIdIsActive(gxact->locking_xid))
397 ereport(ERROR,
398 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
399 errmsg("prepared transaction with identifier \"%s\" is busy",
400 gid)));
401 gxact->locking_xid = InvalidTransactionId;
404 if (user != gxact->owner && !superuser_arg(user))
405 ereport(ERROR,
406 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
407 errmsg("permission denied to finish prepared transaction"),
408 errhint("Must be superuser or the user that prepared the transaction.")));
411 * Note: it probably would be possible to allow committing from
412 * another database; but at the moment NOTIFY is known not to work and
413 * there may be some other issues as well. Hence disallow until
414 * someone gets motivated to make it work.
416 if (MyDatabaseId != gxact->proc.databaseId)
417 ereport(ERROR,
418 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
419 errmsg("prepared transaction belongs to another database"),
420 errhint("Connect to the database where the transaction was prepared to finish it.")));
422 /* OK for me to lock it */
423 gxact->locking_xid = GetTopTransactionId();
425 LWLockRelease(TwoPhaseStateLock);
427 return gxact;
430 LWLockRelease(TwoPhaseStateLock);
432 ereport(ERROR,
433 (errcode(ERRCODE_UNDEFINED_OBJECT),
434 errmsg("prepared transaction with identifier \"%s\" does not exist",
435 gid)));
437 /* NOTREACHED */
438 return NULL;
442 * RemoveGXact
443 * Remove the prepared transaction from the shared memory array.
445 * NB: caller should have already removed it from ProcArray
447 static void
448 RemoveGXact(GlobalTransaction gxact)
450 int i;
452 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
454 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
456 if (gxact == TwoPhaseState->prepXacts[i])
458 /* remove from the active array */
459 TwoPhaseState->numPrepXacts--;
460 TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
462 /* and put it back in the freelist */
463 gxact->proc.links.next = (SHM_QUEUE *) TwoPhaseState->freeGXacts;
464 TwoPhaseState->freeGXacts = gxact;
466 LWLockRelease(TwoPhaseStateLock);
468 return;
472 LWLockRelease(TwoPhaseStateLock);
474 elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
478 * TransactionIdIsPrepared
479 * True iff transaction associated with the identifier is prepared
480 * for two-phase commit
482 * Note: only gxacts marked "valid" are considered; but notice we do not
483 * check the locking status.
485 * This is not currently exported, because it is only needed internally.
487 static bool
488 TransactionIdIsPrepared(TransactionId xid)
490 bool result = false;
491 int i;
493 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
495 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
497 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
499 if (gxact->valid && gxact->proc.xid == xid)
501 result = true;
502 break;
506 LWLockRelease(TwoPhaseStateLock);
508 return result;
512 * Returns an array of all prepared transactions for the user-level
513 * function pg_prepared_xact.
515 * The returned array and all its elements are copies of internal data
516 * structures, to minimize the time we need to hold the TwoPhaseStateLock.
518 * WARNING -- we return even those transactions that are not fully prepared
519 * yet. The caller should filter them out if he doesn't want them.
521 * The returned array is palloc'd.
523 static int
524 GetPreparedTransactionList(GlobalTransaction *gxacts)
526 GlobalTransaction array;
527 int num;
528 int i;
530 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
532 if (TwoPhaseState->numPrepXacts == 0)
534 LWLockRelease(TwoPhaseStateLock);
536 *gxacts = NULL;
537 return 0;
540 num = TwoPhaseState->numPrepXacts;
541 array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
542 *gxacts = array;
543 for (i = 0; i < num; i++)
544 memcpy(array + i, TwoPhaseState->prepXacts[i],
545 sizeof(GlobalTransactionData));
547 LWLockRelease(TwoPhaseStateLock);
549 return num;
553 /* Working status for pg_prepared_xact */
554 typedef struct
556 GlobalTransaction array;
557 int ngxacts;
558 int currIdx;
559 } Working_State;
562 * pg_prepared_xact
563 * Produce a view with one row per prepared transaction.
565 * This function is here so we don't have to export the
566 * GlobalTransactionData struct definition.
568 Datum
569 pg_prepared_xact(PG_FUNCTION_ARGS)
571 FuncCallContext *funcctx;
572 Working_State *status;
574 if (SRF_IS_FIRSTCALL())
576 TupleDesc tupdesc;
577 MemoryContext oldcontext;
579 /* create a function context for cross-call persistence */
580 funcctx = SRF_FIRSTCALL_INIT();
583 * Switch to memory context appropriate for multiple function calls
585 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
587 /* build tupdesc for result tuples */
588 /* this had better match pg_prepared_xacts view in system_views.sql */
589 tupdesc = CreateTemplateTupleDesc(5, false);
590 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
591 XIDOID, -1, 0);
592 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
593 TEXTOID, -1, 0);
594 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
595 TIMESTAMPTZOID, -1, 0);
596 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
597 OIDOID, -1, 0);
598 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
599 OIDOID, -1, 0);
601 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
604 * Collect all the 2PC status information that we will format and send
605 * out as a result set.
607 status = (Working_State *) palloc(sizeof(Working_State));
608 funcctx->user_fctx = (void *) status;
610 status->ngxacts = GetPreparedTransactionList(&status->array);
611 status->currIdx = 0;
613 MemoryContextSwitchTo(oldcontext);
616 funcctx = SRF_PERCALL_SETUP();
617 status = (Working_State *) funcctx->user_fctx;
619 while (status->array != NULL && status->currIdx < status->ngxacts)
621 GlobalTransaction gxact = &status->array[status->currIdx++];
622 Datum values[5];
623 bool nulls[5];
624 HeapTuple tuple;
625 Datum result;
627 if (!gxact->valid)
628 continue;
631 * Form tuple with appropriate data.
633 MemSet(values, 0, sizeof(values));
634 MemSet(nulls, 0, sizeof(nulls));
636 values[0] = TransactionIdGetDatum(gxact->proc.xid);
637 values[1] = CStringGetTextDatum(gxact->gid);
638 values[2] = TimestampTzGetDatum(gxact->prepared_at);
639 values[3] = ObjectIdGetDatum(gxact->owner);
640 values[4] = ObjectIdGetDatum(gxact->proc.databaseId);
642 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
643 result = HeapTupleGetDatum(tuple);
644 SRF_RETURN_NEXT(funcctx, result);
647 SRF_RETURN_DONE(funcctx);
651 * TwoPhaseGetDummyProc
652 * Get the PGPROC that represents a prepared transaction specified by XID
654 PGPROC *
655 TwoPhaseGetDummyProc(TransactionId xid)
657 PGPROC *result = NULL;
658 int i;
660 static TransactionId cached_xid = InvalidTransactionId;
661 static PGPROC *cached_proc = NULL;
664 * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
665 * repeatedly for the same XID. We can save work with a simple cache.
667 if (xid == cached_xid)
668 return cached_proc;
670 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
672 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
674 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
676 if (gxact->proc.xid == xid)
678 result = &gxact->proc;
679 break;
683 LWLockRelease(TwoPhaseStateLock);
685 if (result == NULL) /* should not happen */
686 elog(ERROR, "failed to find dummy PGPROC for xid %u", xid);
688 cached_xid = xid;
689 cached_proc = result;
691 return result;
694 /************************************************************************/
695 /* State file support */
696 /************************************************************************/
698 #define TwoPhaseFilePath(path, xid) \
699 snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
702 * 2PC state file format:
704 * 1. TwoPhaseFileHeader
705 * 2. TransactionId[] (subtransactions)
706 * 3. RelFileNode[] (files to be deleted at commit)
707 * 4. RelFileNode[] (files to be deleted at abort)
708 * 5. TwoPhaseRecordOnDisk
709 * 6. ...
710 * 7. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
711 * 8. CRC32
713 * Each segment except the final CRC32 is MAXALIGN'd.
717 * Header for a 2PC state file
719 #define TWOPHASE_MAGIC 0x57F94531 /* format identifier */
721 typedef struct TwoPhaseFileHeader
723 uint32 magic; /* format identifier */
724 uint32 total_len; /* actual file length */
725 TransactionId xid; /* original transaction XID */
726 Oid database; /* OID of database it was in */
727 TimestampTz prepared_at; /* time of preparation */
728 Oid owner; /* user running the transaction */
729 int32 nsubxacts; /* number of following subxact XIDs */
730 int32 ncommitrels; /* number of delete-on-commit rels */
731 int32 nabortrels; /* number of delete-on-abort rels */
732 char gid[GIDSIZE]; /* GID for transaction */
733 } TwoPhaseFileHeader;
736 * Header for each record in a state file
738 * NOTE: len counts only the rmgr data, not the TwoPhaseRecordOnDisk header.
739 * The rmgr data will be stored starting on a MAXALIGN boundary.
741 typedef struct TwoPhaseRecordOnDisk
743 uint32 len; /* length of rmgr data */
744 TwoPhaseRmgrId rmid; /* resource manager for this record */
745 uint16 info; /* flag bits for use by rmgr */
746 } TwoPhaseRecordOnDisk;
749 * During prepare, the state file is assembled in memory before writing it
750 * to WAL and the actual state file. We use a chain of XLogRecData blocks
751 * so that we will be able to pass the state file contents directly to
752 * XLogInsert.
754 static struct xllist
756 XLogRecData *head; /* first data block in the chain */
757 XLogRecData *tail; /* last block in chain */
758 uint32 bytes_free; /* free bytes left in tail block */
759 uint32 total_len; /* total data bytes in chain */
760 } records;
764 * Append a block of data to records data structure.
766 * NB: each block is padded to a MAXALIGN multiple. This must be
767 * accounted for when the file is later read!
769 * The data is copied, so the caller is free to modify it afterwards.
771 static void
772 save_state_data(const void *data, uint32 len)
774 uint32 padlen = MAXALIGN(len);
776 if (padlen > records.bytes_free)
778 records.tail->next = palloc0(sizeof(XLogRecData));
779 records.tail = records.tail->next;
780 records.tail->buffer = InvalidBuffer;
781 records.tail->len = 0;
782 records.tail->next = NULL;
784 records.bytes_free = Max(padlen, 512);
785 records.tail->data = palloc(records.bytes_free);
788 memcpy(((char *) records.tail->data) + records.tail->len, data, len);
789 records.tail->len += padlen;
790 records.bytes_free -= padlen;
791 records.total_len += padlen;
795 * Start preparing a state file.
797 * Initializes data structure and inserts the 2PC file header record.
799 void
800 StartPrepare(GlobalTransaction gxact)
802 TransactionId xid = gxact->proc.xid;
803 TwoPhaseFileHeader hdr;
804 TransactionId *children;
805 RelFileNode *commitrels;
806 RelFileNode *abortrels;
808 /* Initialize linked list */
809 records.head = palloc0(sizeof(XLogRecData));
810 records.head->buffer = InvalidBuffer;
811 records.head->len = 0;
812 records.head->next = NULL;
814 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
815 records.head->data = palloc(records.bytes_free);
817 records.tail = records.head;
819 records.total_len = 0;
821 /* Create header */
822 hdr.magic = TWOPHASE_MAGIC;
823 hdr.total_len = 0; /* EndPrepare will fill this in */
824 hdr.xid = xid;
825 hdr.database = gxact->proc.databaseId;
826 hdr.prepared_at = gxact->prepared_at;
827 hdr.owner = gxact->owner;
828 hdr.nsubxacts = xactGetCommittedChildren(&children);
829 hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels, NULL);
830 hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels, NULL);
831 StrNCpy(hdr.gid, gxact->gid, GIDSIZE);
833 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
835 /* Add the additional info about subxacts and deletable files */
836 if (hdr.nsubxacts > 0)
838 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
839 /* While we have the child-xact data, stuff it in the gxact too */
840 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
842 if (hdr.ncommitrels > 0)
844 save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
845 pfree(commitrels);
847 if (hdr.nabortrels > 0)
849 save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
850 pfree(abortrels);
855 * Finish preparing state file.
857 * Calculates CRC and writes state file to WAL and in pg_twophase directory.
859 void
860 EndPrepare(GlobalTransaction gxact)
862 TransactionId xid = gxact->proc.xid;
863 TwoPhaseFileHeader *hdr;
864 char path[MAXPGPATH];
865 XLogRecData *record;
866 pg_crc32 statefile_crc;
867 pg_crc32 bogus_crc;
868 int fd;
870 /* Add the end sentinel to the list of 2PC records */
871 RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID, 0,
872 NULL, 0);
874 /* Go back and fill in total_len in the file header record */
875 hdr = (TwoPhaseFileHeader *) records.head->data;
876 Assert(hdr->magic == TWOPHASE_MAGIC);
877 hdr->total_len = records.total_len + sizeof(pg_crc32);
880 * If the file size exceeds MaxAllocSize, we won't be able to read it in
881 * ReadTwoPhaseFile. Check for that now, rather than fail at commit time.
883 if (hdr->total_len > MaxAllocSize)
884 ereport(ERROR,
885 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
886 errmsg("two-phase state file maximum length exceeded")));
889 * Create the 2PC state file.
891 * Note: because we use BasicOpenFile(), we are responsible for ensuring
892 * the FD gets closed in any error exit path. Once we get into the
893 * critical section, though, it doesn't matter since any failure causes
894 * PANIC anyway.
896 TwoPhaseFilePath(path, xid);
898 fd = BasicOpenFile(path,
899 O_CREAT | O_EXCL | O_WRONLY | PG_BINARY,
900 S_IRUSR | S_IWUSR);
901 if (fd < 0)
902 ereport(ERROR,
903 (errcode_for_file_access(),
904 errmsg("could not create two-phase state file \"%s\": %m",
905 path)));
907 /* Write data to file, and calculate CRC as we pass over it */
908 INIT_CRC32(statefile_crc);
910 for (record = records.head; record != NULL; record = record->next)
912 COMP_CRC32(statefile_crc, record->data, record->len);
913 if ((write(fd, record->data, record->len)) != record->len)
915 close(fd);
916 ereport(ERROR,
917 (errcode_for_file_access(),
918 errmsg("could not write two-phase state file: %m")));
922 FIN_CRC32(statefile_crc);
925 * Write a deliberately bogus CRC to the state file; this is just paranoia
926 * to catch the case where four more bytes will run us out of disk space.
928 bogus_crc = ~statefile_crc;
930 if ((write(fd, &bogus_crc, sizeof(pg_crc32))) != sizeof(pg_crc32))
932 close(fd);
933 ereport(ERROR,
934 (errcode_for_file_access(),
935 errmsg("could not write two-phase state file: %m")));
938 /* Back up to prepare for rewriting the CRC */
939 if (lseek(fd, -((off_t) sizeof(pg_crc32)), SEEK_CUR) < 0)
941 close(fd);
942 ereport(ERROR,
943 (errcode_for_file_access(),
944 errmsg("could not seek in two-phase state file: %m")));
948 * The state file isn't valid yet, because we haven't written the correct
949 * CRC yet. Before we do that, insert entry in WAL and flush it to disk.
951 * Between the time we have written the WAL entry and the time we write
952 * out the correct state file CRC, we have an inconsistency: the xact is
953 * prepared according to WAL but not according to our on-disk state. We
954 * use a critical section to force a PANIC if we are unable to complete
955 * the write --- then, WAL replay should repair the inconsistency. The
956 * odds of a PANIC actually occurring should be very tiny given that we
957 * were able to write the bogus CRC above.
959 * We have to set inCommit here, too; otherwise a checkpoint starting
960 * immediately after the WAL record is inserted could complete without
961 * fsync'ing our state file. (This is essentially the same kind of race
962 * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
963 * uses inCommit for; see notes there.)
965 * We save the PREPARE record's location in the gxact for later use by
966 * CheckPointTwoPhase.
968 START_CRIT_SECTION();
970 MyProc->inCommit = true;
972 gxact->prepare_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE,
973 records.head);
974 XLogFlush(gxact->prepare_lsn);
976 /* If we crash now, we have prepared: WAL replay will fix things */
978 /* write correct CRC and close file */
979 if ((write(fd, &statefile_crc, sizeof(pg_crc32))) != sizeof(pg_crc32))
981 close(fd);
982 ereport(ERROR,
983 (errcode_for_file_access(),
984 errmsg("could not write two-phase state file: %m")));
987 if (close(fd) != 0)
988 ereport(ERROR,
989 (errcode_for_file_access(),
990 errmsg("could not close two-phase state file: %m")));
993 * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
994 * as not running our XID (which it will do immediately after this
995 * function returns), others can commit/rollback the xact.
997 * NB: a side effect of this is to make a dummy ProcArray entry for the
998 * prepared XID. This must happen before we clear the XID from MyProc,
999 * else there is a window where the XID is not running according to
1000 * TransactionIdIsInProgress, and onlookers would be entitled to assume
1001 * the xact crashed. Instead we have a window where the same XID appears
1002 * twice in ProcArray, which is OK.
1004 MarkAsPrepared(gxact);
1007 * Now we can mark ourselves as out of the commit critical section: a
1008 * checkpoint starting after this will certainly see the gxact as a
1009 * candidate for fsyncing.
1011 MyProc->inCommit = false;
1013 END_CRIT_SECTION();
1015 records.tail = records.head = NULL;
1019 * Register a 2PC record to be written to state file.
1021 void
1022 RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info,
1023 const void *data, uint32 len)
1025 TwoPhaseRecordOnDisk record;
1027 record.rmid = rmid;
1028 record.info = info;
1029 record.len = len;
1030 save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1031 if (len > 0)
1032 save_state_data(data, len);
1037 * Read and validate the state file for xid.
1039 * If it looks OK (has a valid magic number and CRC), return the palloc'd
1040 * contents of the file. Otherwise return NULL.
1042 static char *
1043 ReadTwoPhaseFile(TransactionId xid)
1045 char path[MAXPGPATH];
1046 char *buf;
1047 TwoPhaseFileHeader *hdr;
1048 int fd;
1049 struct stat stat;
1050 uint32 crc_offset;
1051 pg_crc32 calc_crc,
1052 file_crc;
1054 TwoPhaseFilePath(path, xid);
1056 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1057 if (fd < 0)
1059 ereport(WARNING,
1060 (errcode_for_file_access(),
1061 errmsg("could not open two-phase state file \"%s\": %m",
1062 path)));
1063 return NULL;
1067 * Check file length. We can determine a lower bound pretty easily. We
1068 * set an upper bound to avoid palloc() failure on a corrupt file, though
1069 * we can't guarantee that we won't get an out of memory error anyway,
1070 * even on a valid file.
1072 if (fstat(fd, &stat))
1074 close(fd);
1075 ereport(WARNING,
1076 (errcode_for_file_access(),
1077 errmsg("could not stat two-phase state file \"%s\": %m",
1078 path)));
1079 return NULL;
1082 if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1083 MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1084 sizeof(pg_crc32)) ||
1085 stat.st_size > MaxAllocSize)
1087 close(fd);
1088 return NULL;
1091 crc_offset = stat.st_size - sizeof(pg_crc32);
1092 if (crc_offset != MAXALIGN(crc_offset))
1094 close(fd);
1095 return NULL;
1099 * OK, slurp in the file.
1101 buf = (char *) palloc(stat.st_size);
1103 if (read(fd, buf, stat.st_size) != stat.st_size)
1105 close(fd);
1106 ereport(WARNING,
1107 (errcode_for_file_access(),
1108 errmsg("could not read two-phase state file \"%s\": %m",
1109 path)));
1110 pfree(buf);
1111 return NULL;
1114 close(fd);
1116 hdr = (TwoPhaseFileHeader *) buf;
1117 if (hdr->magic != TWOPHASE_MAGIC || hdr->total_len != stat.st_size)
1119 pfree(buf);
1120 return NULL;
1123 INIT_CRC32(calc_crc);
1124 COMP_CRC32(calc_crc, buf, crc_offset);
1125 FIN_CRC32(calc_crc);
1127 file_crc = *((pg_crc32 *) (buf + crc_offset));
1129 if (!EQ_CRC32(calc_crc, file_crc))
1131 pfree(buf);
1132 return NULL;
1135 return buf;
1140 * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1142 void
1143 FinishPreparedTransaction(const char *gid, bool isCommit)
1145 GlobalTransaction gxact;
1146 TransactionId xid;
1147 char *buf;
1148 char *bufptr;
1149 TwoPhaseFileHeader *hdr;
1150 TransactionId latestXid;
1151 TransactionId *children;
1152 RelFileNode *commitrels;
1153 RelFileNode *abortrels;
1154 RelFileNode *delrels;
1155 int ndelrels;
1156 int i;
1159 * Validate the GID, and lock the GXACT to ensure that two backends do not
1160 * try to commit the same GID at once.
1162 gxact = LockGXact(gid, GetUserId());
1163 xid = gxact->proc.xid;
1166 * Read and validate the state file
1168 buf = ReadTwoPhaseFile(xid);
1169 if (buf == NULL)
1170 ereport(ERROR,
1171 (errcode(ERRCODE_DATA_CORRUPTED),
1172 errmsg("two-phase state file for transaction %u is corrupt",
1173 xid)));
1176 * Disassemble the header area
1178 hdr = (TwoPhaseFileHeader *) buf;
1179 Assert(TransactionIdEquals(hdr->xid, xid));
1180 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1181 children = (TransactionId *) bufptr;
1182 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1183 commitrels = (RelFileNode *) bufptr;
1184 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1185 abortrels = (RelFileNode *) bufptr;
1186 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1188 /* compute latestXid among all children */
1189 latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1192 * The order of operations here is critical: make the XLOG entry for
1193 * commit or abort, then mark the transaction committed or aborted in
1194 * pg_clog, then remove its PGPROC from the global ProcArray (which means
1195 * TransactionIdIsInProgress will stop saying the prepared xact is in
1196 * progress), then run the post-commit or post-abort callbacks. The
1197 * callbacks will release the locks the transaction held.
1199 if (isCommit)
1200 RecordTransactionCommitPrepared(xid,
1201 hdr->nsubxacts, children,
1202 hdr->ncommitrels, commitrels);
1203 else
1204 RecordTransactionAbortPrepared(xid,
1205 hdr->nsubxacts, children,
1206 hdr->nabortrels, abortrels);
1208 ProcArrayRemove(&gxact->proc, latestXid);
1211 * In case we fail while running the callbacks, mark the gxact invalid so
1212 * no one else will try to commit/rollback, and so it can be recycled
1213 * properly later. It is still locked by our XID so it won't go away yet.
1215 * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1217 gxact->valid = false;
1220 * We have to remove any files that were supposed to be dropped. For
1221 * consistency with the regular xact.c code paths, must do this before
1222 * releasing locks, so do it before running the callbacks.
1224 * NB: this code knows that we couldn't be dropping any temp rels ...
1226 if (isCommit)
1228 delrels = commitrels;
1229 ndelrels = hdr->ncommitrels;
1231 else
1233 delrels = abortrels;
1234 ndelrels = hdr->nabortrels;
1236 for (i = 0; i < ndelrels; i++)
1238 SMgrRelation srel = smgropen(delrels[i]);
1239 ForkNumber fork;
1241 for (fork = 0; fork <= MAX_FORKNUM; fork++)
1243 if (smgrexists(srel, fork))
1244 smgrdounlink(srel, fork, false, false);
1246 smgrclose(srel);
1249 /* And now do the callbacks */
1250 if (isCommit)
1251 ProcessRecords(bufptr, xid, twophase_postcommit_callbacks);
1252 else
1253 ProcessRecords(bufptr, xid, twophase_postabort_callbacks);
1255 /* Count the prepared xact as committed or aborted */
1256 AtEOXact_PgStat(isCommit);
1259 * And now we can clean up our mess.
1261 RemoveTwoPhaseFile(xid, true);
1263 RemoveGXact(gxact);
1265 pfree(buf);
1269 * Scan a 2PC state file (already read into memory by ReadTwoPhaseFile)
1270 * and call the indicated callbacks for each 2PC record.
1272 static void
1273 ProcessRecords(char *bufptr, TransactionId xid,
1274 const TwoPhaseCallback callbacks[])
1276 for (;;)
1278 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1280 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1281 if (record->rmid == TWOPHASE_RM_END_ID)
1282 break;
1284 bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1286 if (callbacks[record->rmid] != NULL)
1287 callbacks[record->rmid] (xid, record->info,
1288 (void *) bufptr, record->len);
1290 bufptr += MAXALIGN(record->len);
1295 * Remove the 2PC file for the specified XID.
1297 * If giveWarning is false, do not complain about file-not-present;
1298 * this is an expected case during WAL replay.
1300 void
1301 RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
1303 char path[MAXPGPATH];
1305 TwoPhaseFilePath(path, xid);
1306 if (unlink(path))
1307 if (errno != ENOENT || giveWarning)
1308 ereport(WARNING,
1309 (errcode_for_file_access(),
1310 errmsg("could not remove two-phase state file \"%s\": %m",
1311 path)));
1315 * Recreates a state file. This is used in WAL replay.
1317 * Note: content and len don't include CRC.
1319 void
1320 RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
1322 char path[MAXPGPATH];
1323 pg_crc32 statefile_crc;
1324 int fd;
1326 /* Recompute CRC */
1327 INIT_CRC32(statefile_crc);
1328 COMP_CRC32(statefile_crc, content, len);
1329 FIN_CRC32(statefile_crc);
1331 TwoPhaseFilePath(path, xid);
1333 fd = BasicOpenFile(path,
1334 O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY,
1335 S_IRUSR | S_IWUSR);
1336 if (fd < 0)
1337 ereport(ERROR,
1338 (errcode_for_file_access(),
1339 errmsg("could not recreate two-phase state file \"%s\": %m",
1340 path)));
1342 /* Write content and CRC */
1343 if (write(fd, content, len) != len)
1345 close(fd);
1346 ereport(ERROR,
1347 (errcode_for_file_access(),
1348 errmsg("could not write two-phase state file: %m")));
1350 if (write(fd, &statefile_crc, sizeof(pg_crc32)) != sizeof(pg_crc32))
1352 close(fd);
1353 ereport(ERROR,
1354 (errcode_for_file_access(),
1355 errmsg("could not write two-phase state file: %m")));
1359 * We must fsync the file because the end-of-replay checkpoint will not do
1360 * so, there being no GXACT in shared memory yet to tell it to.
1362 if (pg_fsync(fd) != 0)
1364 close(fd);
1365 ereport(ERROR,
1366 (errcode_for_file_access(),
1367 errmsg("could not fsync two-phase state file: %m")));
1370 if (close(fd) != 0)
1371 ereport(ERROR,
1372 (errcode_for_file_access(),
1373 errmsg("could not close two-phase state file: %m")));
1377 * CheckPointTwoPhase -- handle 2PC component of checkpointing.
1379 * We must fsync the state file of any GXACT that is valid and has a PREPARE
1380 * LSN <= the checkpoint's redo horizon. (If the gxact isn't valid yet or
1381 * has a later LSN, this checkpoint is not responsible for fsyncing it.)
1383 * This is deliberately run as late as possible in the checkpoint sequence,
1384 * because GXACTs ordinarily have short lifespans, and so it is quite
1385 * possible that GXACTs that were valid at checkpoint start will no longer
1386 * exist if we wait a little bit.
1388 * If a GXACT remains valid across multiple checkpoints, it'll be fsynced
1389 * each time. This is considered unusual enough that we don't bother to
1390 * expend any extra code to avoid the redundant fsyncs. (They should be
1391 * reasonably cheap anyway, since they won't cause I/O.)
1393 void
1394 CheckPointTwoPhase(XLogRecPtr redo_horizon)
1396 TransactionId *xids;
1397 int nxids;
1398 char path[MAXPGPATH];
1399 int i;
1402 * We don't want to hold the TwoPhaseStateLock while doing I/O, so we grab
1403 * it just long enough to make a list of the XIDs that require fsyncing,
1404 * and then do the I/O afterwards.
1406 * This approach creates a race condition: someone else could delete a
1407 * GXACT between the time we release TwoPhaseStateLock and the time we try
1408 * to open its state file. We handle this by special-casing ENOENT
1409 * failures: if we see that, we verify that the GXACT is no longer valid,
1410 * and if so ignore the failure.
1412 if (max_prepared_xacts <= 0)
1413 return; /* nothing to do */
1415 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1417 xids = (TransactionId *) palloc(max_prepared_xacts * sizeof(TransactionId));
1418 nxids = 0;
1420 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1422 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1424 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1426 if (gxact->valid &&
1427 XLByteLE(gxact->prepare_lsn, redo_horizon))
1428 xids[nxids++] = gxact->proc.xid;
1431 LWLockRelease(TwoPhaseStateLock);
1433 for (i = 0; i < nxids; i++)
1435 TransactionId xid = xids[i];
1436 int fd;
1438 TwoPhaseFilePath(path, xid);
1440 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
1441 if (fd < 0)
1443 if (errno == ENOENT)
1445 /* OK if gxact is no longer valid */
1446 if (!TransactionIdIsPrepared(xid))
1447 continue;
1448 /* Restore errno in case it was changed */
1449 errno = ENOENT;
1451 ereport(ERROR,
1452 (errcode_for_file_access(),
1453 errmsg("could not open two-phase state file \"%s\": %m",
1454 path)));
1457 if (pg_fsync(fd) != 0)
1459 close(fd);
1460 ereport(ERROR,
1461 (errcode_for_file_access(),
1462 errmsg("could not fsync two-phase state file \"%s\": %m",
1463 path)));
1466 if (close(fd) != 0)
1467 ereport(ERROR,
1468 (errcode_for_file_access(),
1469 errmsg("could not close two-phase state file \"%s\": %m",
1470 path)));
1473 pfree(xids);
1475 TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1479 * PrescanPreparedTransactions
1481 * Scan the pg_twophase directory and determine the range of valid XIDs
1482 * present. This is run during database startup, after we have completed
1483 * reading WAL. ShmemVariableCache->nextXid has been set to one more than
1484 * the highest XID for which evidence exists in WAL.
1486 * We throw away any prepared xacts with main XID beyond nextXid --- if any
1487 * are present, it suggests that the DBA has done a PITR recovery to an
1488 * earlier point in time without cleaning out pg_twophase. We dare not
1489 * try to recover such prepared xacts since they likely depend on database
1490 * state that doesn't exist now.
1492 * However, we will advance nextXid beyond any subxact XIDs belonging to
1493 * valid prepared xacts. We need to do this since subxact commit doesn't
1494 * write a WAL entry, and so there might be no evidence in WAL of those
1495 * subxact XIDs.
1497 * Our other responsibility is to determine and return the oldest valid XID
1498 * among the prepared xacts (if none, return ShmemVariableCache->nextXid).
1499 * This is needed to synchronize pg_subtrans startup properly.
1501 TransactionId
1502 PrescanPreparedTransactions(void)
1504 TransactionId origNextXid = ShmemVariableCache->nextXid;
1505 TransactionId result = origNextXid;
1506 DIR *cldir;
1507 struct dirent *clde;
1509 cldir = AllocateDir(TWOPHASE_DIR);
1510 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1512 if (strlen(clde->d_name) == 8 &&
1513 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1515 TransactionId xid;
1516 char *buf;
1517 TwoPhaseFileHeader *hdr;
1518 TransactionId *subxids;
1519 int i;
1521 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1523 /* Reject XID if too new */
1524 if (TransactionIdFollowsOrEquals(xid, origNextXid))
1526 ereport(WARNING,
1527 (errmsg("removing future two-phase state file \"%s\"",
1528 clde->d_name)));
1529 RemoveTwoPhaseFile(xid, true);
1530 continue;
1534 * Note: we can't check if already processed because clog
1535 * subsystem isn't up yet.
1538 /* Read and validate file */
1539 buf = ReadTwoPhaseFile(xid);
1540 if (buf == NULL)
1542 ereport(WARNING,
1543 (errmsg("removing corrupt two-phase state file \"%s\"",
1544 clde->d_name)));
1545 RemoveTwoPhaseFile(xid, true);
1546 continue;
1549 /* Deconstruct header */
1550 hdr = (TwoPhaseFileHeader *) buf;
1551 if (!TransactionIdEquals(hdr->xid, xid))
1553 ereport(WARNING,
1554 (errmsg("removing corrupt two-phase state file \"%s\"",
1555 clde->d_name)));
1556 RemoveTwoPhaseFile(xid, true);
1557 pfree(buf);
1558 continue;
1562 * OK, we think this file is valid. Incorporate xid into the
1563 * running-minimum result.
1565 if (TransactionIdPrecedes(xid, result))
1566 result = xid;
1569 * Examine subtransaction XIDs ... they should all follow main
1570 * XID, and they may force us to advance nextXid.
1572 subxids = (TransactionId *)
1573 (buf + MAXALIGN(sizeof(TwoPhaseFileHeader)));
1574 for (i = 0; i < hdr->nsubxacts; i++)
1576 TransactionId subxid = subxids[i];
1578 Assert(TransactionIdFollows(subxid, xid));
1579 if (TransactionIdFollowsOrEquals(subxid,
1580 ShmemVariableCache->nextXid))
1582 ShmemVariableCache->nextXid = subxid;
1583 TransactionIdAdvance(ShmemVariableCache->nextXid);
1587 pfree(buf);
1590 FreeDir(cldir);
1592 return result;
1596 * RecoverPreparedTransactions
1598 * Scan the pg_twophase directory and reload shared-memory state for each
1599 * prepared transaction (reacquire locks, etc). This is run during database
1600 * startup.
1602 void
1603 RecoverPreparedTransactions(void)
1605 char dir[MAXPGPATH];
1606 DIR *cldir;
1607 struct dirent *clde;
1609 snprintf(dir, MAXPGPATH, "%s", TWOPHASE_DIR);
1611 cldir = AllocateDir(dir);
1612 while ((clde = ReadDir(cldir, dir)) != NULL)
1614 if (strlen(clde->d_name) == 8 &&
1615 strspn(clde->d_name, "0123456789ABCDEF") == 8)
1617 TransactionId xid;
1618 char *buf;
1619 char *bufptr;
1620 TwoPhaseFileHeader *hdr;
1621 TransactionId *subxids;
1622 GlobalTransaction gxact;
1623 int i;
1625 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1627 /* Already processed? */
1628 if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
1630 ereport(WARNING,
1631 (errmsg("removing stale two-phase state file \"%s\"",
1632 clde->d_name)));
1633 RemoveTwoPhaseFile(xid, true);
1634 continue;
1637 /* Read and validate file */
1638 buf = ReadTwoPhaseFile(xid);
1639 if (buf == NULL)
1641 ereport(WARNING,
1642 (errmsg("removing corrupt two-phase state file \"%s\"",
1643 clde->d_name)));
1644 RemoveTwoPhaseFile(xid, true);
1645 continue;
1648 ereport(LOG,
1649 (errmsg("recovering prepared transaction %u", xid)));
1651 /* Deconstruct header */
1652 hdr = (TwoPhaseFileHeader *) buf;
1653 Assert(TransactionIdEquals(hdr->xid, xid));
1654 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1655 subxids = (TransactionId *) bufptr;
1656 bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1657 bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1658 bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1661 * Reconstruct subtrans state for the transaction --- needed
1662 * because pg_subtrans is not preserved over a restart. Note that
1663 * we are linking all the subtransactions directly to the
1664 * top-level XID; there may originally have been a more complex
1665 * hierarchy, but there's no need to restore that exactly.
1667 for (i = 0; i < hdr->nsubxacts; i++)
1668 SubTransSetParent(subxids[i], xid);
1671 * Recreate its GXACT and dummy PGPROC
1673 * Note: since we don't have the PREPARE record's WAL location at
1674 * hand, we leave prepare_lsn zeroes. This means the GXACT will
1675 * be fsync'd on every future checkpoint. We assume this
1676 * situation is infrequent enough that the performance cost is
1677 * negligible (especially since we know the state file has already
1678 * been fsynced).
1680 gxact = MarkAsPreparing(xid, hdr->gid,
1681 hdr->prepared_at,
1682 hdr->owner, hdr->database);
1683 GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1684 MarkAsPrepared(gxact);
1687 * Recover other state (notably locks) using resource managers
1689 ProcessRecords(bufptr, xid, twophase_recover_callbacks);
1691 pfree(buf);
1694 FreeDir(cldir);
1698 * RecordTransactionCommitPrepared
1700 * This is basically the same as RecordTransactionCommit: in particular,
1701 * we must set the inCommit flag to avoid a race condition.
1703 * We know the transaction made at least one XLOG entry (its PREPARE),
1704 * so it is never possible to optimize out the commit record.
1706 static void
1707 RecordTransactionCommitPrepared(TransactionId xid,
1708 int nchildren,
1709 TransactionId *children,
1710 int nrels,
1711 RelFileNode *rels)
1713 XLogRecData rdata[3];
1714 int lastrdata = 0;
1715 xl_xact_commit_prepared xlrec;
1716 XLogRecPtr recptr;
1718 START_CRIT_SECTION();
1720 /* See notes in RecordTransactionCommit */
1721 MyProc->inCommit = true;
1723 /* Emit the XLOG commit record */
1724 xlrec.xid = xid;
1725 xlrec.crec.xact_time = GetCurrentTimestamp();
1726 xlrec.crec.nrels = nrels;
1727 xlrec.crec.nsubxacts = nchildren;
1728 rdata[0].data = (char *) (&xlrec);
1729 rdata[0].len = MinSizeOfXactCommitPrepared;
1730 rdata[0].buffer = InvalidBuffer;
1731 /* dump rels to delete */
1732 if (nrels > 0)
1734 rdata[0].next = &(rdata[1]);
1735 rdata[1].data = (char *) rels;
1736 rdata[1].len = nrels * sizeof(RelFileNode);
1737 rdata[1].buffer = InvalidBuffer;
1738 lastrdata = 1;
1740 /* dump committed child Xids */
1741 if (nchildren > 0)
1743 rdata[lastrdata].next = &(rdata[2]);
1744 rdata[2].data = (char *) children;
1745 rdata[2].len = nchildren * sizeof(TransactionId);
1746 rdata[2].buffer = InvalidBuffer;
1747 lastrdata = 2;
1749 rdata[lastrdata].next = NULL;
1751 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT_PREPARED, rdata);
1754 * We don't currently try to sleep before flush here ... nor is there any
1755 * support for async commit of a prepared xact (the very idea is probably
1756 * a contradiction)
1759 /* Flush XLOG to disk */
1760 XLogFlush(recptr);
1762 /* Mark the transaction committed in pg_clog */
1763 TransactionIdCommitTree(xid, nchildren, children);
1765 /* Checkpoint can proceed now */
1766 MyProc->inCommit = false;
1768 END_CRIT_SECTION();
1772 * RecordTransactionAbortPrepared
1774 * This is basically the same as RecordTransactionAbort.
1776 * We know the transaction made at least one XLOG entry (its PREPARE),
1777 * so it is never possible to optimize out the abort record.
1779 static void
1780 RecordTransactionAbortPrepared(TransactionId xid,
1781 int nchildren,
1782 TransactionId *children,
1783 int nrels,
1784 RelFileNode *rels)
1786 XLogRecData rdata[3];
1787 int lastrdata = 0;
1788 xl_xact_abort_prepared xlrec;
1789 XLogRecPtr recptr;
1792 * Catch the scenario where we aborted partway through
1793 * RecordTransactionCommitPrepared ...
1795 if (TransactionIdDidCommit(xid))
1796 elog(PANIC, "cannot abort transaction %u, it was already committed",
1797 xid);
1799 START_CRIT_SECTION();
1801 /* Emit the XLOG abort record */
1802 xlrec.xid = xid;
1803 xlrec.arec.xact_time = GetCurrentTimestamp();
1804 xlrec.arec.nrels = nrels;
1805 xlrec.arec.nsubxacts = nchildren;
1806 rdata[0].data = (char *) (&xlrec);
1807 rdata[0].len = MinSizeOfXactAbortPrepared;
1808 rdata[0].buffer = InvalidBuffer;
1809 /* dump rels to delete */
1810 if (nrels > 0)
1812 rdata[0].next = &(rdata[1]);
1813 rdata[1].data = (char *) rels;
1814 rdata[1].len = nrels * sizeof(RelFileNode);
1815 rdata[1].buffer = InvalidBuffer;
1816 lastrdata = 1;
1818 /* dump committed child Xids */
1819 if (nchildren > 0)
1821 rdata[lastrdata].next = &(rdata[2]);
1822 rdata[2].data = (char *) children;
1823 rdata[2].len = nchildren * sizeof(TransactionId);
1824 rdata[2].buffer = InvalidBuffer;
1825 lastrdata = 2;
1827 rdata[lastrdata].next = NULL;
1829 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT_PREPARED, rdata);
1831 /* Always flush, since we're about to remove the 2PC state file */
1832 XLogFlush(recptr);
1835 * Mark the transaction aborted in clog. This is not absolutely necessary
1836 * but we may as well do it while we are here.
1838 TransactionIdAbortTree(xid, nchildren, children);
1840 END_CRIT_SECTION();