1 /*-------------------------------------------------------------------------
4 * Two-phase commit support functions.
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 * Each global transaction is associated with a global transaction
14 * identifier (GID). The client assigns a GID to a postgres
15 * transaction with the PREPARE TRANSACTION command.
17 * We keep all active global transactions in a shared memory array.
18 * When the PREPARE TRANSACTION command is issued, the GID is
19 * reserved for the transaction in the array. This is done before
20 * a WAL entry is made, because the reservation checks for duplicate
21 * GIDs and aborts the transaction if there already is a global
22 * transaction in prepared state with the same GID.
24 * A global transaction (gxact) also has a dummy PGPROC that is entered
25 * into the ProcArray array; this is what keeps the XID considered
26 * running by TransactionIdIsInProgress. It is also convenient as a
27 * PGPROC to hook the gxact's locks to.
29 * In order to survive crashes and shutdowns, all prepared
30 * transactions must be stored in permanent storage. This includes
31 * locking information, pending notifications etc. All that state
32 * information is written to the per-transaction state file in
33 * the pg_twophase directory.
35 *-------------------------------------------------------------------------
41 #include <sys/types.h>
45 #include "access/htup.h"
46 #include "access/subtrans.h"
47 #include "access/transam.h"
48 #include "access/twophase.h"
49 #include "access/twophase_rmgr.h"
50 #include "access/xact.h"
51 #include "catalog/pg_type.h"
53 #include "miscadmin.h"
55 #include "storage/fd.h"
56 #include "storage/procarray.h"
57 #include "storage/smgr.h"
58 #include "utils/builtins.h"
59 #include "utils/memutils.h"
63 * Directory where Two-phase commit files reside within PGDATA
65 #define TWOPHASE_DIR "pg_twophase"
67 /* GUC variable, can't be changed after startup */
68 int max_prepared_xacts
= 5;
71 * This struct describes one global transaction that is in prepared state
72 * or attempting to become prepared.
74 * The first component of the struct is a dummy PGPROC that is inserted
75 * into the global ProcArray so that the transaction appears to still be
76 * running and holding locks. It must be first because we cast pointers
77 * to PGPROC and pointers to GlobalTransactionData back and forth.
79 * The lifecycle of a global transaction is:
81 * 1. After checking that the requested GID is not in use, set up an
82 * entry in the TwoPhaseState->prepXacts array with the correct XID and GID,
83 * with locking_xid = my own XID and valid = false.
85 * 2. After successfully completing prepare, set valid = true and enter the
86 * contained PGPROC into the global ProcArray.
88 * 3. To begin COMMIT PREPARED or ROLLBACK PREPARED, check that the entry
89 * is valid and its locking_xid is no longer active, then store my current
90 * XID into locking_xid. This prevents concurrent attempts to commit or
91 * rollback the same prepared xact.
93 * 4. On completion of COMMIT PREPARED or ROLLBACK PREPARED, remove the entry
94 * from the ProcArray and the TwoPhaseState->prepXacts array and return it to
97 * Note that if the preparing transaction fails between steps 1 and 2, the
98 * entry will remain in prepXacts until recycled. We can detect recyclable
99 * entries by checking for valid = false and locking_xid no longer active.
101 * typedef struct GlobalTransactionData *GlobalTransaction appears in
106 typedef struct GlobalTransactionData
108 PGPROC proc
; /* dummy proc */
109 TimestampTz prepared_at
; /* time of preparation */
110 XLogRecPtr prepare_lsn
; /* XLOG offset of prepare record */
111 Oid owner
; /* ID of user that executed the xact */
112 TransactionId locking_xid
; /* top-level XID of backend working on xact */
113 bool valid
; /* TRUE if fully prepared */
114 char gid
[GIDSIZE
]; /* The GID assigned to the prepared xact */
115 } GlobalTransactionData
;
118 * Two Phase Commit shared state. Access to this struct is protected
119 * by TwoPhaseStateLock.
121 typedef struct TwoPhaseStateData
123 /* Head of linked list of free GlobalTransactionData structs */
124 SHMEM_OFFSET freeGXacts
;
126 /* Number of valid prepXacts entries. */
130 * There are max_prepared_xacts items in this array, but C wants a
133 GlobalTransaction prepXacts
[1]; /* VARIABLE LENGTH ARRAY */
134 } TwoPhaseStateData
; /* VARIABLE LENGTH STRUCT */
136 static TwoPhaseStateData
*TwoPhaseState
;
139 static void RecordTransactionCommitPrepared(TransactionId xid
,
141 TransactionId
*children
,
144 static void RecordTransactionAbortPrepared(TransactionId xid
,
146 TransactionId
*children
,
149 static void ProcessRecords(char *bufptr
, TransactionId xid
,
150 const TwoPhaseCallback callbacks
[]);
154 * Initialization of shared memory
157 TwoPhaseShmemSize(void)
161 /* Need the fixed struct, the array of pointers, and the GTD structs */
162 size
= offsetof(TwoPhaseStateData
, prepXacts
);
163 size
= add_size(size
, mul_size(max_prepared_xacts
,
164 sizeof(GlobalTransaction
)));
165 size
= MAXALIGN(size
);
166 size
= add_size(size
, mul_size(max_prepared_xacts
,
167 sizeof(GlobalTransactionData
)));
173 TwoPhaseShmemInit(void)
177 TwoPhaseState
= ShmemInitStruct("Prepared Transaction Table",
180 if (!IsUnderPostmaster
)
182 GlobalTransaction gxacts
;
186 TwoPhaseState
->freeGXacts
= INVALID_OFFSET
;
187 TwoPhaseState
->numPrepXacts
= 0;
190 * Initialize the linked list of free GlobalTransactionData structs
192 gxacts
= (GlobalTransaction
)
193 ((char *) TwoPhaseState
+
194 MAXALIGN(offsetof(TwoPhaseStateData
, prepXacts
) +
195 sizeof(GlobalTransaction
) * max_prepared_xacts
));
196 for (i
= 0; i
< max_prepared_xacts
; i
++)
198 gxacts
[i
].proc
.links
.next
= TwoPhaseState
->freeGXacts
;
199 TwoPhaseState
->freeGXacts
= MAKE_OFFSET(&gxacts
[i
]);
209 * Reserve the GID for the given transaction.
211 * Internally, this creates a gxact struct and puts it into the active array.
212 * NOTE: this is also used when reloading a gxact after a crash; so avoid
213 * assuming that we can use very much backend context.
216 MarkAsPreparing(TransactionId xid
, const char *gid
,
217 TimestampTz prepared_at
, Oid owner
, Oid databaseid
)
219 GlobalTransaction gxact
;
222 if (strlen(gid
) >= GIDSIZE
)
224 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
225 errmsg("transaction identifier \"%s\" is too long",
228 LWLockAcquire(TwoPhaseStateLock
, LW_EXCLUSIVE
);
231 * First, find and recycle any gxacts that failed during prepare. We do
232 * this partly to ensure we don't mistakenly say their GIDs are still
233 * reserved, and partly so we don't fail on out-of-slots unnecessarily.
235 for (i
= 0; i
< TwoPhaseState
->numPrepXacts
; i
++)
237 gxact
= TwoPhaseState
->prepXacts
[i
];
238 if (!gxact
->valid
&& !TransactionIdIsActive(gxact
->locking_xid
))
240 /* It's dead Jim ... remove from the active array */
241 TwoPhaseState
->numPrepXacts
--;
242 TwoPhaseState
->prepXacts
[i
] = TwoPhaseState
->prepXacts
[TwoPhaseState
->numPrepXacts
];
243 /* and put it back in the freelist */
244 gxact
->proc
.links
.next
= TwoPhaseState
->freeGXacts
;
245 TwoPhaseState
->freeGXacts
= MAKE_OFFSET(gxact
);
246 /* Back up index count too, so we don't miss scanning one */
251 /* Check for conflicting GID */
252 for (i
= 0; i
< TwoPhaseState
->numPrepXacts
; i
++)
254 gxact
= TwoPhaseState
->prepXacts
[i
];
255 if (strcmp(gxact
->gid
, gid
) == 0)
258 (errcode(ERRCODE_DUPLICATE_OBJECT
),
259 errmsg("transaction identifier \"%s\" is already in use",
264 /* Get a free gxact from the freelist */
265 if (TwoPhaseState
->freeGXacts
== INVALID_OFFSET
)
267 (errcode(ERRCODE_OUT_OF_MEMORY
),
268 errmsg("maximum number of prepared transactions reached"),
269 errhint("Increase max_prepared_transactions (currently %d).",
270 max_prepared_xacts
)));
271 gxact
= (GlobalTransaction
) MAKE_PTR(TwoPhaseState
->freeGXacts
);
272 TwoPhaseState
->freeGXacts
= gxact
->proc
.links
.next
;
275 MemSet(&gxact
->proc
, 0, sizeof(PGPROC
));
276 SHMQueueElemInit(&(gxact
->proc
.links
));
277 gxact
->proc
.waitStatus
= STATUS_OK
;
278 /* We set up the gxact's VXID as InvalidBackendId/XID */
279 gxact
->proc
.lxid
= (LocalTransactionId
) xid
;
280 gxact
->proc
.xid
= xid
;
281 gxact
->proc
.xmin
= InvalidTransactionId
;
283 gxact
->proc
.backendId
= InvalidBackendId
;
284 gxact
->proc
.databaseId
= databaseid
;
285 gxact
->proc
.roleId
= owner
;
286 gxact
->proc
.inCommit
= false;
287 gxact
->proc
.vacuumFlags
= 0;
288 gxact
->proc
.lwWaiting
= false;
289 gxact
->proc
.lwExclusive
= false;
290 gxact
->proc
.lwWaitLink
= NULL
;
291 gxact
->proc
.waitLock
= NULL
;
292 gxact
->proc
.waitProcLock
= NULL
;
293 for (i
= 0; i
< NUM_LOCK_PARTITIONS
; i
++)
294 SHMQueueInit(&(gxact
->proc
.myProcLocks
[i
]));
295 /* subxid data must be filled later by GXactLoadSubxactData */
296 gxact
->proc
.subxids
.overflowed
= false;
297 gxact
->proc
.subxids
.nxids
= 0;
299 gxact
->prepared_at
= prepared_at
;
300 /* initialize LSN to 0 (start of WAL) */
301 gxact
->prepare_lsn
.xlogid
= 0;
302 gxact
->prepare_lsn
.xrecoff
= 0;
303 gxact
->owner
= owner
;
304 gxact
->locking_xid
= xid
;
305 gxact
->valid
= false;
306 strcpy(gxact
->gid
, gid
);
308 /* And insert it into the active array */
309 Assert(TwoPhaseState
->numPrepXacts
< max_prepared_xacts
);
310 TwoPhaseState
->prepXacts
[TwoPhaseState
->numPrepXacts
++] = gxact
;
312 LWLockRelease(TwoPhaseStateLock
);
318 * GXactLoadSubxactData
320 * If the transaction being persisted had any subtransactions, this must
321 * be called before MarkAsPrepared() to load information into the dummy
325 GXactLoadSubxactData(GlobalTransaction gxact
, int nsubxacts
,
326 TransactionId
*children
)
328 /* We need no extra lock since the GXACT isn't valid yet */
329 if (nsubxacts
> PGPROC_MAX_CACHED_SUBXIDS
)
331 gxact
->proc
.subxids
.overflowed
= true;
332 nsubxacts
= PGPROC_MAX_CACHED_SUBXIDS
;
336 memcpy(gxact
->proc
.subxids
.xids
, children
,
337 nsubxacts
* sizeof(TransactionId
));
338 gxact
->proc
.subxids
.nxids
= nsubxacts
;
344 * Mark the GXACT as fully valid, and enter it into the global ProcArray.
347 MarkAsPrepared(GlobalTransaction gxact
)
349 /* Lock here may be overkill, but I'm not convinced of that ... */
350 LWLockAcquire(TwoPhaseStateLock
, LW_EXCLUSIVE
);
351 Assert(!gxact
->valid
);
353 LWLockRelease(TwoPhaseStateLock
);
356 * Put it into the global ProcArray so TransactionIdIsInProgress considers
357 * the XID as still running.
359 ProcArrayAdd(&gxact
->proc
);
364 * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
366 static GlobalTransaction
367 LockGXact(const char *gid
, Oid user
)
371 LWLockAcquire(TwoPhaseStateLock
, LW_EXCLUSIVE
);
373 for (i
= 0; i
< TwoPhaseState
->numPrepXacts
; i
++)
375 GlobalTransaction gxact
= TwoPhaseState
->prepXacts
[i
];
377 /* Ignore not-yet-valid GIDs */
380 if (strcmp(gxact
->gid
, gid
) != 0)
383 /* Found it, but has someone else got it locked? */
384 if (TransactionIdIsValid(gxact
->locking_xid
))
386 if (TransactionIdIsActive(gxact
->locking_xid
))
388 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
389 errmsg("prepared transaction with identifier \"%s\" is busy",
391 gxact
->locking_xid
= InvalidTransactionId
;
394 if (user
!= gxact
->owner
&& !superuser_arg(user
))
396 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
397 errmsg("permission denied to finish prepared transaction"),
398 errhint("Must be superuser or the user that prepared the transaction.")));
401 * Note: it probably would be possible to allow committing from
402 * another database; but at the moment NOTIFY is known not to work and
403 * there may be some other issues as well. Hence disallow until
404 * someone gets motivated to make it work.
406 if (MyDatabaseId
!= gxact
->proc
.databaseId
)
408 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
409 errmsg("prepared transaction belongs to another database"),
410 errhint("Connect to the database where the transaction was prepared to finish it.")));
412 /* OK for me to lock it */
413 gxact
->locking_xid
= GetTopTransactionId();
415 LWLockRelease(TwoPhaseStateLock
);
420 LWLockRelease(TwoPhaseStateLock
);
423 (errcode(ERRCODE_UNDEFINED_OBJECT
),
424 errmsg("prepared transaction with identifier \"%s\" does not exist",
433 * Remove the prepared transaction from the shared memory array.
435 * NB: caller should have already removed it from ProcArray
438 RemoveGXact(GlobalTransaction gxact
)
442 LWLockAcquire(TwoPhaseStateLock
, LW_EXCLUSIVE
);
444 for (i
= 0; i
< TwoPhaseState
->numPrepXacts
; i
++)
446 if (gxact
== TwoPhaseState
->prepXacts
[i
])
448 /* remove from the active array */
449 TwoPhaseState
->numPrepXacts
--;
450 TwoPhaseState
->prepXacts
[i
] = TwoPhaseState
->prepXacts
[TwoPhaseState
->numPrepXacts
];
452 /* and put it back in the freelist */
453 gxact
->proc
.links
.next
= TwoPhaseState
->freeGXacts
;
454 TwoPhaseState
->freeGXacts
= MAKE_OFFSET(gxact
);
456 LWLockRelease(TwoPhaseStateLock
);
462 LWLockRelease(TwoPhaseStateLock
);
464 elog(ERROR
, "failed to find %p in GlobalTransaction array", gxact
);
468 * TransactionIdIsPrepared
469 * True iff transaction associated with the identifier is prepared
470 * for two-phase commit
472 * Note: only gxacts marked "valid" are considered; but notice we do not
473 * check the locking status.
475 * This is not currently exported, because it is only needed internally.
478 TransactionIdIsPrepared(TransactionId xid
)
483 LWLockAcquire(TwoPhaseStateLock
, LW_SHARED
);
485 for (i
= 0; i
< TwoPhaseState
->numPrepXacts
; i
++)
487 GlobalTransaction gxact
= TwoPhaseState
->prepXacts
[i
];
489 if (gxact
->valid
&& gxact
->proc
.xid
== xid
)
496 LWLockRelease(TwoPhaseStateLock
);
502 * Returns an array of all prepared transactions for the user-level
503 * function pg_prepared_xact.
505 * The returned array and all its elements are copies of internal data
506 * structures, to minimize the time we need to hold the TwoPhaseStateLock.
508 * WARNING -- we return even those transactions that are not fully prepared
509 * yet. The caller should filter them out if he doesn't want them.
511 * The returned array is palloc'd.
514 GetPreparedTransactionList(GlobalTransaction
*gxacts
)
516 GlobalTransaction array
;
520 LWLockAcquire(TwoPhaseStateLock
, LW_SHARED
);
522 if (TwoPhaseState
->numPrepXacts
== 0)
524 LWLockRelease(TwoPhaseStateLock
);
530 num
= TwoPhaseState
->numPrepXacts
;
531 array
= (GlobalTransaction
) palloc(sizeof(GlobalTransactionData
) * num
);
533 for (i
= 0; i
< num
; i
++)
534 memcpy(array
+ i
, TwoPhaseState
->prepXacts
[i
],
535 sizeof(GlobalTransactionData
));
537 LWLockRelease(TwoPhaseStateLock
);
543 /* Working status for pg_prepared_xact */
546 GlobalTransaction array
;
553 * Produce a view with one row per prepared transaction.
555 * This function is here so we don't have to export the
556 * GlobalTransactionData struct definition.
559 pg_prepared_xact(PG_FUNCTION_ARGS
)
561 FuncCallContext
*funcctx
;
562 Working_State
*status
;
564 if (SRF_IS_FIRSTCALL())
567 MemoryContext oldcontext
;
569 /* create a function context for cross-call persistence */
570 funcctx
= SRF_FIRSTCALL_INIT();
573 * Switch to memory context appropriate for multiple function calls
575 oldcontext
= MemoryContextSwitchTo(funcctx
->multi_call_memory_ctx
);
577 /* build tupdesc for result tuples */
578 /* this had better match pg_prepared_xacts view in system_views.sql */
579 tupdesc
= CreateTemplateTupleDesc(5, false);
580 TupleDescInitEntry(tupdesc
, (AttrNumber
) 1, "transaction",
582 TupleDescInitEntry(tupdesc
, (AttrNumber
) 2, "gid",
584 TupleDescInitEntry(tupdesc
, (AttrNumber
) 3, "prepared",
585 TIMESTAMPTZOID
, -1, 0);
586 TupleDescInitEntry(tupdesc
, (AttrNumber
) 4, "ownerid",
588 TupleDescInitEntry(tupdesc
, (AttrNumber
) 5, "dbid",
591 funcctx
->tuple_desc
= BlessTupleDesc(tupdesc
);
594 * Collect all the 2PC status information that we will format and send
595 * out as a result set.
597 status
= (Working_State
*) palloc(sizeof(Working_State
));
598 funcctx
->user_fctx
= (void *) status
;
600 status
->ngxacts
= GetPreparedTransactionList(&status
->array
);
603 MemoryContextSwitchTo(oldcontext
);
606 funcctx
= SRF_PERCALL_SETUP();
607 status
= (Working_State
*) funcctx
->user_fctx
;
609 while (status
->array
!= NULL
&& status
->currIdx
< status
->ngxacts
)
611 GlobalTransaction gxact
= &status
->array
[status
->currIdx
++];
621 * Form tuple with appropriate data.
623 MemSet(values
, 0, sizeof(values
));
624 MemSet(nulls
, 0, sizeof(nulls
));
626 values
[0] = TransactionIdGetDatum(gxact
->proc
.xid
);
627 values
[1] = CStringGetTextDatum(gxact
->gid
);
628 values
[2] = TimestampTzGetDatum(gxact
->prepared_at
);
629 values
[3] = ObjectIdGetDatum(gxact
->owner
);
630 values
[4] = ObjectIdGetDatum(gxact
->proc
.databaseId
);
632 tuple
= heap_form_tuple(funcctx
->tuple_desc
, values
, nulls
);
633 result
= HeapTupleGetDatum(tuple
);
634 SRF_RETURN_NEXT(funcctx
, result
);
637 SRF_RETURN_DONE(funcctx
);
641 * TwoPhaseGetDummyProc
642 * Get the PGPROC that represents a prepared transaction specified by XID
645 TwoPhaseGetDummyProc(TransactionId xid
)
647 PGPROC
*result
= NULL
;
650 static TransactionId cached_xid
= InvalidTransactionId
;
651 static PGPROC
*cached_proc
= NULL
;
654 * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
655 * repeatedly for the same XID. We can save work with a simple cache.
657 if (xid
== cached_xid
)
660 LWLockAcquire(TwoPhaseStateLock
, LW_SHARED
);
662 for (i
= 0; i
< TwoPhaseState
->numPrepXacts
; i
++)
664 GlobalTransaction gxact
= TwoPhaseState
->prepXacts
[i
];
666 if (gxact
->proc
.xid
== xid
)
668 result
= &gxact
->proc
;
673 LWLockRelease(TwoPhaseStateLock
);
675 if (result
== NULL
) /* should not happen */
676 elog(ERROR
, "failed to find dummy PGPROC for xid %u", xid
);
679 cached_proc
= result
;
684 /************************************************************************/
685 /* State file support */
686 /************************************************************************/
688 #define TwoPhaseFilePath(path, xid) \
689 snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
692 * 2PC state file format:
694 * 1. TwoPhaseFileHeader
695 * 2. TransactionId[] (subtransactions)
696 * 3. RelFileNode[] (files to be deleted at commit)
697 * 4. RelFileNode[] (files to be deleted at abort)
698 * 5. TwoPhaseRecordOnDisk
700 * 7. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
703 * Each segment except the final CRC32 is MAXALIGN'd.
707 * Header for a 2PC state file
709 #define TWOPHASE_MAGIC 0x57F94531 /* format identifier */
711 typedef struct TwoPhaseFileHeader
713 uint32 magic
; /* format identifier */
714 uint32 total_len
; /* actual file length */
715 TransactionId xid
; /* original transaction XID */
716 Oid database
; /* OID of database it was in */
717 TimestampTz prepared_at
; /* time of preparation */
718 Oid owner
; /* user running the transaction */
719 int32 nsubxacts
; /* number of following subxact XIDs */
720 int32 ncommitrels
; /* number of delete-on-commit rels */
721 int32 nabortrels
; /* number of delete-on-abort rels */
722 char gid
[GIDSIZE
]; /* GID for transaction */
723 } TwoPhaseFileHeader
;
726 * Header for each record in a state file
728 * NOTE: len counts only the rmgr data, not the TwoPhaseRecordOnDisk header.
729 * The rmgr data will be stored starting on a MAXALIGN boundary.
731 typedef struct TwoPhaseRecordOnDisk
733 uint32 len
; /* length of rmgr data */
734 TwoPhaseRmgrId rmid
; /* resource manager for this record */
735 uint16 info
; /* flag bits for use by rmgr */
736 } TwoPhaseRecordOnDisk
;
739 * During prepare, the state file is assembled in memory before writing it
740 * to WAL and the actual state file. We use a chain of XLogRecData blocks
741 * so that we will be able to pass the state file contents directly to
746 XLogRecData
*head
; /* first data block in the chain */
747 XLogRecData
*tail
; /* last block in chain */
748 uint32 bytes_free
; /* free bytes left in tail block */
749 uint32 total_len
; /* total data bytes in chain */
754 * Append a block of data to records data structure.
756 * NB: each block is padded to a MAXALIGN multiple. This must be
757 * accounted for when the file is later read!
759 * The data is copied, so the caller is free to modify it afterwards.
762 save_state_data(const void *data
, uint32 len
)
764 uint32 padlen
= MAXALIGN(len
);
766 if (padlen
> records
.bytes_free
)
768 records
.tail
->next
= palloc0(sizeof(XLogRecData
));
769 records
.tail
= records
.tail
->next
;
770 records
.tail
->buffer
= InvalidBuffer
;
771 records
.tail
->len
= 0;
772 records
.tail
->next
= NULL
;
774 records
.bytes_free
= Max(padlen
, 512);
775 records
.tail
->data
= palloc(records
.bytes_free
);
778 memcpy(((char *) records
.tail
->data
) + records
.tail
->len
, data
, len
);
779 records
.tail
->len
+= padlen
;
780 records
.bytes_free
-= padlen
;
781 records
.total_len
+= padlen
;
785 * Start preparing a state file.
787 * Initializes data structure and inserts the 2PC file header record.
790 StartPrepare(GlobalTransaction gxact
)
792 TransactionId xid
= gxact
->proc
.xid
;
793 TwoPhaseFileHeader hdr
;
794 TransactionId
*children
;
795 RelFileNode
*commitrels
;
796 RelFileNode
*abortrels
;
798 /* Initialize linked list */
799 records
.head
= palloc0(sizeof(XLogRecData
));
800 records
.head
->buffer
= InvalidBuffer
;
801 records
.head
->len
= 0;
802 records
.head
->next
= NULL
;
804 records
.bytes_free
= Max(sizeof(TwoPhaseFileHeader
), 512);
805 records
.head
->data
= palloc(records
.bytes_free
);
807 records
.tail
= records
.head
;
809 records
.total_len
= 0;
812 hdr
.magic
= TWOPHASE_MAGIC
;
813 hdr
.total_len
= 0; /* EndPrepare will fill this in */
815 hdr
.database
= gxact
->proc
.databaseId
;
816 hdr
.prepared_at
= gxact
->prepared_at
;
817 hdr
.owner
= gxact
->owner
;
818 hdr
.nsubxacts
= xactGetCommittedChildren(&children
);
819 hdr
.ncommitrels
= smgrGetPendingDeletes(true, &commitrels
, NULL
);
820 hdr
.nabortrels
= smgrGetPendingDeletes(false, &abortrels
, NULL
);
821 StrNCpy(hdr
.gid
, gxact
->gid
, GIDSIZE
);
823 save_state_data(&hdr
, sizeof(TwoPhaseFileHeader
));
825 /* Add the additional info about subxacts and deletable files */
826 if (hdr
.nsubxacts
> 0)
828 save_state_data(children
, hdr
.nsubxacts
* sizeof(TransactionId
));
829 /* While we have the child-xact data, stuff it in the gxact too */
830 GXactLoadSubxactData(gxact
, hdr
.nsubxacts
, children
);
832 if (hdr
.ncommitrels
> 0)
834 save_state_data(commitrels
, hdr
.ncommitrels
* sizeof(RelFileNode
));
837 if (hdr
.nabortrels
> 0)
839 save_state_data(abortrels
, hdr
.nabortrels
* sizeof(RelFileNode
));
845 * Finish preparing state file.
847 * Calculates CRC and writes state file to WAL and in pg_twophase directory.
850 EndPrepare(GlobalTransaction gxact
)
852 TransactionId xid
= gxact
->proc
.xid
;
853 TwoPhaseFileHeader
*hdr
;
854 char path
[MAXPGPATH
];
856 pg_crc32 statefile_crc
;
860 /* Add the end sentinel to the list of 2PC records */
861 RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID
, 0,
864 /* Go back and fill in total_len in the file header record */
865 hdr
= (TwoPhaseFileHeader
*) records
.head
->data
;
866 Assert(hdr
->magic
== TWOPHASE_MAGIC
);
867 hdr
->total_len
= records
.total_len
+ sizeof(pg_crc32
);
870 * If the file size exceeds MaxAllocSize, we won't be able to read it in
871 * ReadTwoPhaseFile. Check for that now, rather than fail at commit time.
873 if (hdr
->total_len
> MaxAllocSize
)
875 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED
),
876 errmsg("two-phase state file maximum length exceeded")));
879 * Create the 2PC state file.
881 * Note: because we use BasicOpenFile(), we are responsible for ensuring
882 * the FD gets closed in any error exit path. Once we get into the
883 * critical section, though, it doesn't matter since any failure causes
886 TwoPhaseFilePath(path
, xid
);
888 fd
= BasicOpenFile(path
,
889 O_CREAT
| O_EXCL
| O_WRONLY
| PG_BINARY
,
893 (errcode_for_file_access(),
894 errmsg("could not create two-phase state file \"%s\": %m",
897 /* Write data to file, and calculate CRC as we pass over it */
898 INIT_CRC32(statefile_crc
);
900 for (record
= records
.head
; record
!= NULL
; record
= record
->next
)
902 COMP_CRC32(statefile_crc
, record
->data
, record
->len
);
903 if ((write(fd
, record
->data
, record
->len
)) != record
->len
)
907 (errcode_for_file_access(),
908 errmsg("could not write two-phase state file: %m")));
912 FIN_CRC32(statefile_crc
);
915 * Write a deliberately bogus CRC to the state file; this is just paranoia
916 * to catch the case where four more bytes will run us out of disk space.
918 bogus_crc
= ~statefile_crc
;
920 if ((write(fd
, &bogus_crc
, sizeof(pg_crc32
))) != sizeof(pg_crc32
))
924 (errcode_for_file_access(),
925 errmsg("could not write two-phase state file: %m")));
928 /* Back up to prepare for rewriting the CRC */
929 if (lseek(fd
, -((off_t
) sizeof(pg_crc32
)), SEEK_CUR
) < 0)
933 (errcode_for_file_access(),
934 errmsg("could not seek in two-phase state file: %m")));
938 * The state file isn't valid yet, because we haven't written the correct
939 * CRC yet. Before we do that, insert entry in WAL and flush it to disk.
941 * Between the time we have written the WAL entry and the time we write
942 * out the correct state file CRC, we have an inconsistency: the xact is
943 * prepared according to WAL but not according to our on-disk state. We
944 * use a critical section to force a PANIC if we are unable to complete
945 * the write --- then, WAL replay should repair the inconsistency. The
946 * odds of a PANIC actually occurring should be very tiny given that we
947 * were able to write the bogus CRC above.
949 * We have to set inCommit here, too; otherwise a checkpoint starting
950 * immediately after the WAL record is inserted could complete without
951 * fsync'ing our state file. (This is essentially the same kind of race
952 * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
953 * uses inCommit for; see notes there.)
955 * We save the PREPARE record's location in the gxact for later use by
956 * CheckPointTwoPhase.
958 START_CRIT_SECTION();
960 MyProc
->inCommit
= true;
962 gxact
->prepare_lsn
= XLogInsert(RM_XACT_ID
, XLOG_XACT_PREPARE
,
964 XLogFlush(gxact
->prepare_lsn
);
966 /* If we crash now, we have prepared: WAL replay will fix things */
968 /* write correct CRC and close file */
969 if ((write(fd
, &statefile_crc
, sizeof(pg_crc32
))) != sizeof(pg_crc32
))
973 (errcode_for_file_access(),
974 errmsg("could not write two-phase state file: %m")));
979 (errcode_for_file_access(),
980 errmsg("could not close two-phase state file: %m")));
983 * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
984 * as not running our XID (which it will do immediately after this
985 * function returns), others can commit/rollback the xact.
987 * NB: a side effect of this is to make a dummy ProcArray entry for the
988 * prepared XID. This must happen before we clear the XID from MyProc,
989 * else there is a window where the XID is not running according to
990 * TransactionIdIsInProgress, and onlookers would be entitled to assume
991 * the xact crashed. Instead we have a window where the same XID appears
992 * twice in ProcArray, which is OK.
994 MarkAsPrepared(gxact
);
997 * Now we can mark ourselves as out of the commit critical section: a
998 * checkpoint starting after this will certainly see the gxact as a
999 * candidate for fsyncing.
1001 MyProc
->inCommit
= false;
1005 records
.tail
= records
.head
= NULL
;
1009 * Register a 2PC record to be written to state file.
1012 RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid
, uint16 info
,
1013 const void *data
, uint32 len
)
1015 TwoPhaseRecordOnDisk record
;
1020 save_state_data(&record
, sizeof(TwoPhaseRecordOnDisk
));
1022 save_state_data(data
, len
);
1027 * Read and validate the state file for xid.
1029 * If it looks OK (has a valid magic number and CRC), return the palloc'd
1030 * contents of the file. Otherwise return NULL.
1033 ReadTwoPhaseFile(TransactionId xid
)
1035 char path
[MAXPGPATH
];
1037 TwoPhaseFileHeader
*hdr
;
1044 TwoPhaseFilePath(path
, xid
);
1046 fd
= BasicOpenFile(path
, O_RDONLY
| PG_BINARY
, 0);
1050 (errcode_for_file_access(),
1051 errmsg("could not open two-phase state file \"%s\": %m",
1057 * Check file length. We can determine a lower bound pretty easily. We
1058 * set an upper bound to avoid palloc() failure on a corrupt file, though
1059 * we can't guarantee that we won't get an out of memory error anyway,
1060 * even on a valid file.
1062 if (fstat(fd
, &stat
))
1066 (errcode_for_file_access(),
1067 errmsg("could not stat two-phase state file \"%s\": %m",
1072 if (stat
.st_size
< (MAXALIGN(sizeof(TwoPhaseFileHeader
)) +
1073 MAXALIGN(sizeof(TwoPhaseRecordOnDisk
)) +
1074 sizeof(pg_crc32
)) ||
1075 stat
.st_size
> MaxAllocSize
)
1081 crc_offset
= stat
.st_size
- sizeof(pg_crc32
);
1082 if (crc_offset
!= MAXALIGN(crc_offset
))
1089 * OK, slurp in the file.
1091 buf
= (char *) palloc(stat
.st_size
);
1093 if (read(fd
, buf
, stat
.st_size
) != stat
.st_size
)
1097 (errcode_for_file_access(),
1098 errmsg("could not read two-phase state file \"%s\": %m",
1106 hdr
= (TwoPhaseFileHeader
*) buf
;
1107 if (hdr
->magic
!= TWOPHASE_MAGIC
|| hdr
->total_len
!= stat
.st_size
)
1113 INIT_CRC32(calc_crc
);
1114 COMP_CRC32(calc_crc
, buf
, crc_offset
);
1115 FIN_CRC32(calc_crc
);
1117 file_crc
= *((pg_crc32
*) (buf
+ crc_offset
));
1119 if (!EQ_CRC32(calc_crc
, file_crc
))
1130 * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1133 FinishPreparedTransaction(const char *gid
, bool isCommit
)
1135 GlobalTransaction gxact
;
1139 TwoPhaseFileHeader
*hdr
;
1140 TransactionId latestXid
;
1141 TransactionId
*children
;
1142 RelFileNode
*commitrels
;
1143 RelFileNode
*abortrels
;
1147 * Validate the GID, and lock the GXACT to ensure that two backends do not
1148 * try to commit the same GID at once.
1150 gxact
= LockGXact(gid
, GetUserId());
1151 xid
= gxact
->proc
.xid
;
1154 * Read and validate the state file
1156 buf
= ReadTwoPhaseFile(xid
);
1159 (errcode(ERRCODE_DATA_CORRUPTED
),
1160 errmsg("two-phase state file for transaction %u is corrupt",
1164 * Disassemble the header area
1166 hdr
= (TwoPhaseFileHeader
*) buf
;
1167 Assert(TransactionIdEquals(hdr
->xid
, xid
));
1168 bufptr
= buf
+ MAXALIGN(sizeof(TwoPhaseFileHeader
));
1169 children
= (TransactionId
*) bufptr
;
1170 bufptr
+= MAXALIGN(hdr
->nsubxacts
* sizeof(TransactionId
));
1171 commitrels
= (RelFileNode
*) bufptr
;
1172 bufptr
+= MAXALIGN(hdr
->ncommitrels
* sizeof(RelFileNode
));
1173 abortrels
= (RelFileNode
*) bufptr
;
1174 bufptr
+= MAXALIGN(hdr
->nabortrels
* sizeof(RelFileNode
));
1176 /* compute latestXid among all children */
1177 latestXid
= TransactionIdLatest(xid
, hdr
->nsubxacts
, children
);
1180 * The order of operations here is critical: make the XLOG entry for
1181 * commit or abort, then mark the transaction committed or aborted in
1182 * pg_clog, then remove its PGPROC from the global ProcArray (which means
1183 * TransactionIdIsInProgress will stop saying the prepared xact is in
1184 * progress), then run the post-commit or post-abort callbacks. The
1185 * callbacks will release the locks the transaction held.
1188 RecordTransactionCommitPrepared(xid
,
1189 hdr
->nsubxacts
, children
,
1190 hdr
->ncommitrels
, commitrels
);
1192 RecordTransactionAbortPrepared(xid
,
1193 hdr
->nsubxacts
, children
,
1194 hdr
->nabortrels
, abortrels
);
1196 ProcArrayRemove(&gxact
->proc
, latestXid
);
1199 * In case we fail while running the callbacks, mark the gxact invalid so
1200 * no one else will try to commit/rollback, and so it can be recycled
1201 * properly later. It is still locked by our XID so it won't go away yet.
1203 * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1205 gxact
->valid
= false;
1208 * We have to remove any files that were supposed to be dropped. For
1209 * consistency with the regular xact.c code paths, must do this before
1210 * releasing locks, so do it before running the callbacks.
1212 * NB: this code knows that we couldn't be dropping any temp rels ...
1216 for (i
= 0; i
< hdr
->ncommitrels
; i
++)
1217 smgrdounlink(smgropen(commitrels
[i
]), false, false);
1221 for (i
= 0; i
< hdr
->nabortrels
; i
++)
1222 smgrdounlink(smgropen(abortrels
[i
]), false, false);
1225 /* And now do the callbacks */
1227 ProcessRecords(bufptr
, xid
, twophase_postcommit_callbacks
);
1229 ProcessRecords(bufptr
, xid
, twophase_postabort_callbacks
);
1231 /* Count the prepared xact as committed or aborted */
1232 AtEOXact_PgStat(isCommit
);
1235 * And now we can clean up our mess.
1237 RemoveTwoPhaseFile(xid
, true);
1245 * Scan a 2PC state file (already read into memory by ReadTwoPhaseFile)
1246 * and call the indicated callbacks for each 2PC record.
1249 ProcessRecords(char *bufptr
, TransactionId xid
,
1250 const TwoPhaseCallback callbacks
[])
1254 TwoPhaseRecordOnDisk
*record
= (TwoPhaseRecordOnDisk
*) bufptr
;
1256 Assert(record
->rmid
<= TWOPHASE_RM_MAX_ID
);
1257 if (record
->rmid
== TWOPHASE_RM_END_ID
)
1260 bufptr
+= MAXALIGN(sizeof(TwoPhaseRecordOnDisk
));
1262 if (callbacks
[record
->rmid
] != NULL
)
1263 callbacks
[record
->rmid
] (xid
, record
->info
,
1264 (void *) bufptr
, record
->len
);
1266 bufptr
+= MAXALIGN(record
->len
);
1271 * Remove the 2PC file for the specified XID.
1273 * If giveWarning is false, do not complain about file-not-present;
1274 * this is an expected case during WAL replay.
1277 RemoveTwoPhaseFile(TransactionId xid
, bool giveWarning
)
1279 char path
[MAXPGPATH
];
1281 TwoPhaseFilePath(path
, xid
);
1283 if (errno
!= ENOENT
|| giveWarning
)
1285 (errcode_for_file_access(),
1286 errmsg("could not remove two-phase state file \"%s\": %m",
1291 * Recreates a state file. This is used in WAL replay.
1293 * Note: content and len don't include CRC.
1296 RecreateTwoPhaseFile(TransactionId xid
, void *content
, int len
)
1298 char path
[MAXPGPATH
];
1299 pg_crc32 statefile_crc
;
1303 INIT_CRC32(statefile_crc
);
1304 COMP_CRC32(statefile_crc
, content
, len
);
1305 FIN_CRC32(statefile_crc
);
1307 TwoPhaseFilePath(path
, xid
);
1309 fd
= BasicOpenFile(path
,
1310 O_CREAT
| O_TRUNC
| O_WRONLY
| PG_BINARY
,
1314 (errcode_for_file_access(),
1315 errmsg("could not recreate two-phase state file \"%s\": %m",
1318 /* Write content and CRC */
1319 if (write(fd
, content
, len
) != len
)
1323 (errcode_for_file_access(),
1324 errmsg("could not write two-phase state file: %m")));
1326 if (write(fd
, &statefile_crc
, sizeof(pg_crc32
)) != sizeof(pg_crc32
))
1330 (errcode_for_file_access(),
1331 errmsg("could not write two-phase state file: %m")));
1335 * We must fsync the file because the end-of-replay checkpoint will not do
1336 * so, there being no GXACT in shared memory yet to tell it to.
1338 if (pg_fsync(fd
) != 0)
1342 (errcode_for_file_access(),
1343 errmsg("could not fsync two-phase state file: %m")));
1348 (errcode_for_file_access(),
1349 errmsg("could not close two-phase state file: %m")));
1353 * CheckPointTwoPhase -- handle 2PC component of checkpointing.
1355 * We must fsync the state file of any GXACT that is valid and has a PREPARE
1356 * LSN <= the checkpoint's redo horizon. (If the gxact isn't valid yet or
1357 * has a later LSN, this checkpoint is not responsible for fsyncing it.)
1359 * This is deliberately run as late as possible in the checkpoint sequence,
1360 * because GXACTs ordinarily have short lifespans, and so it is quite
1361 * possible that GXACTs that were valid at checkpoint start will no longer
1362 * exist if we wait a little bit.
1364 * If a GXACT remains valid across multiple checkpoints, it'll be fsynced
1365 * each time. This is considered unusual enough that we don't bother to
1366 * expend any extra code to avoid the redundant fsyncs. (They should be
1367 * reasonably cheap anyway, since they won't cause I/O.)
1370 CheckPointTwoPhase(XLogRecPtr redo_horizon
)
1372 TransactionId
*xids
;
1374 char path
[MAXPGPATH
];
1378 * We don't want to hold the TwoPhaseStateLock while doing I/O, so we grab
1379 * it just long enough to make a list of the XIDs that require fsyncing,
1380 * and then do the I/O afterwards.
1382 * This approach creates a race condition: someone else could delete a
1383 * GXACT between the time we release TwoPhaseStateLock and the time we try
1384 * to open its state file. We handle this by special-casing ENOENT
1385 * failures: if we see that, we verify that the GXACT is no longer valid,
1386 * and if so ignore the failure.
1388 if (max_prepared_xacts
<= 0)
1389 return; /* nothing to do */
1390 xids
= (TransactionId
*) palloc(max_prepared_xacts
* sizeof(TransactionId
));
1393 LWLockAcquire(TwoPhaseStateLock
, LW_SHARED
);
1395 for (i
= 0; i
< TwoPhaseState
->numPrepXacts
; i
++)
1397 GlobalTransaction gxact
= TwoPhaseState
->prepXacts
[i
];
1400 XLByteLE(gxact
->prepare_lsn
, redo_horizon
))
1401 xids
[nxids
++] = gxact
->proc
.xid
;
1404 LWLockRelease(TwoPhaseStateLock
);
1406 for (i
= 0; i
< nxids
; i
++)
1408 TransactionId xid
= xids
[i
];
1411 TwoPhaseFilePath(path
, xid
);
1413 fd
= BasicOpenFile(path
, O_RDWR
| PG_BINARY
, 0);
1416 if (errno
== ENOENT
)
1418 /* OK if gxact is no longer valid */
1419 if (!TransactionIdIsPrepared(xid
))
1421 /* Restore errno in case it was changed */
1425 (errcode_for_file_access(),
1426 errmsg("could not open two-phase state file \"%s\": %m",
1430 if (pg_fsync(fd
) != 0)
1434 (errcode_for_file_access(),
1435 errmsg("could not fsync two-phase state file \"%s\": %m",
1441 (errcode_for_file_access(),
1442 errmsg("could not close two-phase state file \"%s\": %m",
1450 * PrescanPreparedTransactions
1452 * Scan the pg_twophase directory and determine the range of valid XIDs
1453 * present. This is run during database startup, after we have completed
1454 * reading WAL. ShmemVariableCache->nextXid has been set to one more than
1455 * the highest XID for which evidence exists in WAL.
1457 * We throw away any prepared xacts with main XID beyond nextXid --- if any
1458 * are present, it suggests that the DBA has done a PITR recovery to an
1459 * earlier point in time without cleaning out pg_twophase. We dare not
1460 * try to recover such prepared xacts since they likely depend on database
1461 * state that doesn't exist now.
1463 * However, we will advance nextXid beyond any subxact XIDs belonging to
1464 * valid prepared xacts. We need to do this since subxact commit doesn't
1465 * write a WAL entry, and so there might be no evidence in WAL of those
1468 * Our other responsibility is to determine and return the oldest valid XID
1469 * among the prepared xacts (if none, return ShmemVariableCache->nextXid).
1470 * This is needed to synchronize pg_subtrans startup properly.
1473 PrescanPreparedTransactions(void)
1475 TransactionId origNextXid
= ShmemVariableCache
->nextXid
;
1476 TransactionId result
= origNextXid
;
1478 struct dirent
*clde
;
1480 cldir
= AllocateDir(TWOPHASE_DIR
);
1481 while ((clde
= ReadDir(cldir
, TWOPHASE_DIR
)) != NULL
)
1483 if (strlen(clde
->d_name
) == 8 &&
1484 strspn(clde
->d_name
, "0123456789ABCDEF") == 8)
1488 TwoPhaseFileHeader
*hdr
;
1489 TransactionId
*subxids
;
1492 xid
= (TransactionId
) strtoul(clde
->d_name
, NULL
, 16);
1494 /* Reject XID if too new */
1495 if (TransactionIdFollowsOrEquals(xid
, origNextXid
))
1498 (errmsg("removing future two-phase state file \"%s\"",
1500 RemoveTwoPhaseFile(xid
, true);
1505 * Note: we can't check if already processed because clog
1506 * subsystem isn't up yet.
1509 /* Read and validate file */
1510 buf
= ReadTwoPhaseFile(xid
);
1514 (errmsg("removing corrupt two-phase state file \"%s\"",
1516 RemoveTwoPhaseFile(xid
, true);
1520 /* Deconstruct header */
1521 hdr
= (TwoPhaseFileHeader
*) buf
;
1522 if (!TransactionIdEquals(hdr
->xid
, xid
))
1525 (errmsg("removing corrupt two-phase state file \"%s\"",
1527 RemoveTwoPhaseFile(xid
, true);
1533 * OK, we think this file is valid. Incorporate xid into the
1534 * running-minimum result.
1536 if (TransactionIdPrecedes(xid
, result
))
1540 * Examine subtransaction XIDs ... they should all follow main
1541 * XID, and they may force us to advance nextXid.
1543 subxids
= (TransactionId
*)
1544 (buf
+ MAXALIGN(sizeof(TwoPhaseFileHeader
)));
1545 for (i
= 0; i
< hdr
->nsubxacts
; i
++)
1547 TransactionId subxid
= subxids
[i
];
1549 Assert(TransactionIdFollows(subxid
, xid
));
1550 if (TransactionIdFollowsOrEquals(subxid
,
1551 ShmemVariableCache
->nextXid
))
1553 ShmemVariableCache
->nextXid
= subxid
;
1554 TransactionIdAdvance(ShmemVariableCache
->nextXid
);
1567 * RecoverPreparedTransactions
1569 * Scan the pg_twophase directory and reload shared-memory state for each
1570 * prepared transaction (reacquire locks, etc). This is run during database
1574 RecoverPreparedTransactions(void)
1576 char dir
[MAXPGPATH
];
1578 struct dirent
*clde
;
1580 snprintf(dir
, MAXPGPATH
, "%s", TWOPHASE_DIR
);
1582 cldir
= AllocateDir(dir
);
1583 while ((clde
= ReadDir(cldir
, dir
)) != NULL
)
1585 if (strlen(clde
->d_name
) == 8 &&
1586 strspn(clde
->d_name
, "0123456789ABCDEF") == 8)
1591 TwoPhaseFileHeader
*hdr
;
1592 TransactionId
*subxids
;
1593 GlobalTransaction gxact
;
1596 xid
= (TransactionId
) strtoul(clde
->d_name
, NULL
, 16);
1598 /* Already processed? */
1599 if (TransactionIdDidCommit(xid
) || TransactionIdDidAbort(xid
))
1602 (errmsg("removing stale two-phase state file \"%s\"",
1604 RemoveTwoPhaseFile(xid
, true);
1608 /* Read and validate file */
1609 buf
= ReadTwoPhaseFile(xid
);
1613 (errmsg("removing corrupt two-phase state file \"%s\"",
1615 RemoveTwoPhaseFile(xid
, true);
1620 (errmsg("recovering prepared transaction %u", xid
)));
1622 /* Deconstruct header */
1623 hdr
= (TwoPhaseFileHeader
*) buf
;
1624 Assert(TransactionIdEquals(hdr
->xid
, xid
));
1625 bufptr
= buf
+ MAXALIGN(sizeof(TwoPhaseFileHeader
));
1626 subxids
= (TransactionId
*) bufptr
;
1627 bufptr
+= MAXALIGN(hdr
->nsubxacts
* sizeof(TransactionId
));
1628 bufptr
+= MAXALIGN(hdr
->ncommitrels
* sizeof(RelFileNode
));
1629 bufptr
+= MAXALIGN(hdr
->nabortrels
* sizeof(RelFileNode
));
1632 * Reconstruct subtrans state for the transaction --- needed
1633 * because pg_subtrans is not preserved over a restart. Note that
1634 * we are linking all the subtransactions directly to the
1635 * top-level XID; there may originally have been a more complex
1636 * hierarchy, but there's no need to restore that exactly.
1638 for (i
= 0; i
< hdr
->nsubxacts
; i
++)
1639 SubTransSetParent(subxids
[i
], xid
);
1642 * Recreate its GXACT and dummy PGPROC
1644 * Note: since we don't have the PREPARE record's WAL location at
1645 * hand, we leave prepare_lsn zeroes. This means the GXACT will
1646 * be fsync'd on every future checkpoint. We assume this
1647 * situation is infrequent enough that the performance cost is
1648 * negligible (especially since we know the state file has already
1651 gxact
= MarkAsPreparing(xid
, hdr
->gid
,
1653 hdr
->owner
, hdr
->database
);
1654 GXactLoadSubxactData(gxact
, hdr
->nsubxacts
, subxids
);
1655 MarkAsPrepared(gxact
);
1658 * Recover other state (notably locks) using resource managers
1660 ProcessRecords(bufptr
, xid
, twophase_recover_callbacks
);
1669 * RecordTransactionCommitPrepared
1671 * This is basically the same as RecordTransactionCommit: in particular,
1672 * we must set the inCommit flag to avoid a race condition.
1674 * We know the transaction made at least one XLOG entry (its PREPARE),
1675 * so it is never possible to optimize out the commit record.
1678 RecordTransactionCommitPrepared(TransactionId xid
,
1680 TransactionId
*children
,
1684 XLogRecData rdata
[3];
1686 xl_xact_commit_prepared xlrec
;
1689 START_CRIT_SECTION();
1691 /* See notes in RecordTransactionCommit */
1692 MyProc
->inCommit
= true;
1694 /* Emit the XLOG commit record */
1696 xlrec
.crec
.xact_time
= GetCurrentTimestamp();
1697 xlrec
.crec
.nrels
= nrels
;
1698 xlrec
.crec
.nsubxacts
= nchildren
;
1699 rdata
[0].data
= (char *) (&xlrec
);
1700 rdata
[0].len
= MinSizeOfXactCommitPrepared
;
1701 rdata
[0].buffer
= InvalidBuffer
;
1702 /* dump rels to delete */
1705 rdata
[0].next
= &(rdata
[1]);
1706 rdata
[1].data
= (char *) rels
;
1707 rdata
[1].len
= nrels
* sizeof(RelFileNode
);
1708 rdata
[1].buffer
= InvalidBuffer
;
1711 /* dump committed child Xids */
1714 rdata
[lastrdata
].next
= &(rdata
[2]);
1715 rdata
[2].data
= (char *) children
;
1716 rdata
[2].len
= nchildren
* sizeof(TransactionId
);
1717 rdata
[2].buffer
= InvalidBuffer
;
1720 rdata
[lastrdata
].next
= NULL
;
1722 recptr
= XLogInsert(RM_XACT_ID
, XLOG_XACT_COMMIT_PREPARED
, rdata
);
1725 * We don't currently try to sleep before flush here ... nor is there any
1726 * support for async commit of a prepared xact (the very idea is probably
1730 /* Flush XLOG to disk */
1733 /* Mark the transaction committed in pg_clog */
1734 TransactionIdCommit(xid
);
1735 /* to avoid race conditions, the parent must commit first */
1736 TransactionIdCommitTree(nchildren
, children
);
1738 /* Checkpoint can proceed now */
1739 MyProc
->inCommit
= false;
1745 * RecordTransactionAbortPrepared
1747 * This is basically the same as RecordTransactionAbort.
1749 * We know the transaction made at least one XLOG entry (its PREPARE),
1750 * so it is never possible to optimize out the abort record.
1753 RecordTransactionAbortPrepared(TransactionId xid
,
1755 TransactionId
*children
,
1759 XLogRecData rdata
[3];
1761 xl_xact_abort_prepared xlrec
;
1765 * Catch the scenario where we aborted partway through
1766 * RecordTransactionCommitPrepared ...
1768 if (TransactionIdDidCommit(xid
))
1769 elog(PANIC
, "cannot abort transaction %u, it was already committed",
1772 START_CRIT_SECTION();
1774 /* Emit the XLOG abort record */
1776 xlrec
.arec
.xact_time
= GetCurrentTimestamp();
1777 xlrec
.arec
.nrels
= nrels
;
1778 xlrec
.arec
.nsubxacts
= nchildren
;
1779 rdata
[0].data
= (char *) (&xlrec
);
1780 rdata
[0].len
= MinSizeOfXactAbortPrepared
;
1781 rdata
[0].buffer
= InvalidBuffer
;
1782 /* dump rels to delete */
1785 rdata
[0].next
= &(rdata
[1]);
1786 rdata
[1].data
= (char *) rels
;
1787 rdata
[1].len
= nrels
* sizeof(RelFileNode
);
1788 rdata
[1].buffer
= InvalidBuffer
;
1791 /* dump committed child Xids */
1794 rdata
[lastrdata
].next
= &(rdata
[2]);
1795 rdata
[2].data
= (char *) children
;
1796 rdata
[2].len
= nchildren
* sizeof(TransactionId
);
1797 rdata
[2].buffer
= InvalidBuffer
;
1800 rdata
[lastrdata
].next
= NULL
;
1802 recptr
= XLogInsert(RM_XACT_ID
, XLOG_XACT_ABORT_PREPARED
, rdata
);
1804 /* Always flush, since we're about to remove the 2PC state file */
1808 * Mark the transaction aborted in clog. This is not absolutely necessary
1809 * but we may as well do it while we are here.
1811 TransactionIdAbort(xid
);
1812 TransactionIdAbortTree(nchildren
, children
);