Remove arbitrary 10MB limit on two-phase state file size. It's not that hard
[PostgreSQL.git] / src / backend / access / transam / twophase.c
blobb15ff5d5ecc9133d14a611e36eb05ae20fa6fb4d
1 /*-------------------------------------------------------------------------
3 * twophase.c
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
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 "catalog/pg_type.h"
52 #include "funcapi.h"
53 #include "miscadmin.h"
54 #include "pgstat.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
95 * the freelist.
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
102 * twophase.h
104 #define GIDSIZE 200
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. */
127 int numPrepXacts;
130 * There are max_prepared_xacts items in this array, but C wants a
131 * fixed-size array.
133 GlobalTransaction prepXacts[1]; /* VARIABLE LENGTH ARRAY */
134 } TwoPhaseStateData; /* VARIABLE LENGTH STRUCT */
136 static TwoPhaseStateData *TwoPhaseState;
139 static void RecordTransactionCommitPrepared(TransactionId xid,
140 int nchildren,
141 TransactionId *children,
142 int nrels,
143 RelFileNode *rels);
144 static void RecordTransactionAbortPrepared(TransactionId xid,
145 int nchildren,
146 TransactionId *children,
147 int nrels,
148 RelFileNode *rels);
149 static void ProcessRecords(char *bufptr, TransactionId xid,
150 const TwoPhaseCallback callbacks[]);
154 * Initialization of shared memory
156 Size
157 TwoPhaseShmemSize(void)
159 Size size;
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)));
169 return size;
172 void
173 TwoPhaseShmemInit(void)
175 bool found;
177 TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
178 TwoPhaseShmemSize(),
179 &found);
180 if (!IsUnderPostmaster)
182 GlobalTransaction gxacts;
183 int i;
185 Assert(!found);
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]);
202 else
203 Assert(found);
208 * MarkAsPreparing
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.
215 GlobalTransaction
216 MarkAsPreparing(TransactionId xid, const char *gid,
217 TimestampTz prepared_at, Oid owner, Oid databaseid)
219 GlobalTransaction gxact;
220 int i;
222 if (strlen(gid) >= GIDSIZE)
223 ereport(ERROR,
224 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
225 errmsg("transaction identifier \"%s\" is too long",
226 gid)));
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 */
247 i--;
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)
257 ereport(ERROR,
258 (errcode(ERRCODE_DUPLICATE_OBJECT),
259 errmsg("transaction identifier \"%s\" is already in use",
260 gid)));
264 /* Get a free gxact from the freelist */
265 if (TwoPhaseState->freeGXacts == INVALID_OFFSET)
266 ereport(ERROR,
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;
274 /* Initialize it */
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;
282 gxact->proc.pid = 0;
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);
314 return gxact;
318 * GXactLoadSubxactData
320 * If the transaction being persisted had any subtransactions, this must
321 * be called before MarkAsPrepared() to load information into the dummy
322 * PGPROC.
324 static void
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;
334 if (nsubxacts > 0)
336 memcpy(gxact->proc.subxids.xids, children,
337 nsubxacts * sizeof(TransactionId));
338 gxact->proc.subxids.nxids = nsubxacts;
343 * MarkAsPrepared
344 * Mark the GXACT as fully valid, and enter it into the global ProcArray.
346 static void
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);
352 gxact->valid = true;
353 LWLockRelease(TwoPhaseStateLock);
356 * Put it into the global ProcArray so TransactionIdIsInProgress considers
357 * the XID as still running.
359 ProcArrayAdd(&gxact->proc);
363 * LockGXact
364 * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
366 static GlobalTransaction
367 LockGXact(const char *gid, Oid user)
369 int i;
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 */
378 if (!gxact->valid)
379 continue;
380 if (strcmp(gxact->gid, gid) != 0)
381 continue;
383 /* Found it, but has someone else got it locked? */
384 if (TransactionIdIsValid(gxact->locking_xid))
386 if (TransactionIdIsActive(gxact->locking_xid))
387 ereport(ERROR,
388 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
389 errmsg("prepared transaction with identifier \"%s\" is busy",
390 gid)));
391 gxact->locking_xid = InvalidTransactionId;
394 if (user != gxact->owner && !superuser_arg(user))
395 ereport(ERROR,
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)
407 ereport(ERROR,
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);
417 return gxact;
420 LWLockRelease(TwoPhaseStateLock);
422 ereport(ERROR,
423 (errcode(ERRCODE_UNDEFINED_OBJECT),
424 errmsg("prepared transaction with identifier \"%s\" does not exist",
425 gid)));
427 /* NOTREACHED */
428 return NULL;
432 * RemoveGXact
433 * Remove the prepared transaction from the shared memory array.
435 * NB: caller should have already removed it from ProcArray
437 static void
438 RemoveGXact(GlobalTransaction gxact)
440 int i;
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);
458 return;
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.
477 static bool
478 TransactionIdIsPrepared(TransactionId xid)
480 bool result = false;
481 int i;
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)
491 result = true;
492 break;
496 LWLockRelease(TwoPhaseStateLock);
498 return result;
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.
513 static int
514 GetPreparedTransactionList(GlobalTransaction *gxacts)
516 GlobalTransaction array;
517 int num;
518 int i;
520 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
522 if (TwoPhaseState->numPrepXacts == 0)
524 LWLockRelease(TwoPhaseStateLock);
526 *gxacts = NULL;
527 return 0;
530 num = TwoPhaseState->numPrepXacts;
531 array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
532 *gxacts = array;
533 for (i = 0; i < num; i++)
534 memcpy(array + i, TwoPhaseState->prepXacts[i],
535 sizeof(GlobalTransactionData));
537 LWLockRelease(TwoPhaseStateLock);
539 return num;
543 /* Working status for pg_prepared_xact */
544 typedef struct
546 GlobalTransaction array;
547 int ngxacts;
548 int currIdx;
549 } Working_State;
552 * pg_prepared_xact
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.
558 Datum
559 pg_prepared_xact(PG_FUNCTION_ARGS)
561 FuncCallContext *funcctx;
562 Working_State *status;
564 if (SRF_IS_FIRSTCALL())
566 TupleDesc tupdesc;
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",
581 XIDOID, -1, 0);
582 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
583 TEXTOID, -1, 0);
584 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
585 TIMESTAMPTZOID, -1, 0);
586 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
587 OIDOID, -1, 0);
588 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
589 OIDOID, -1, 0);
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);
601 status->currIdx = 0;
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++];
612 Datum values[5];
613 bool nulls[5];
614 HeapTuple tuple;
615 Datum result;
617 if (!gxact->valid)
618 continue;
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
644 PGPROC *
645 TwoPhaseGetDummyProc(TransactionId xid)
647 PGPROC *result = NULL;
648 int i;
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)
658 return cached_proc;
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;
669 break;
673 LWLockRelease(TwoPhaseStateLock);
675 if (result == NULL) /* should not happen */
676 elog(ERROR, "failed to find dummy PGPROC for xid %u", xid);
678 cached_xid = xid;
679 cached_proc = result;
681 return 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
699 * 6. ...
700 * 7. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
701 * 8. CRC32
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
742 * XLogInsert.
744 static struct xllist
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 */
750 } records;
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.
761 static void
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.
789 void
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;
811 /* Create header */
812 hdr.magic = TWOPHASE_MAGIC;
813 hdr.total_len = 0; /* EndPrepare will fill this in */
814 hdr.xid = xid;
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));
835 pfree(commitrels);
837 if (hdr.nabortrels > 0)
839 save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
840 pfree(abortrels);
845 * Finish preparing state file.
847 * Calculates CRC and writes state file to WAL and in pg_twophase directory.
849 void
850 EndPrepare(GlobalTransaction gxact)
852 TransactionId xid = gxact->proc.xid;
853 TwoPhaseFileHeader *hdr;
854 char path[MAXPGPATH];
855 XLogRecData *record;
856 pg_crc32 statefile_crc;
857 pg_crc32 bogus_crc;
858 int fd;
860 /* Add the end sentinel to the list of 2PC records */
861 RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID, 0,
862 NULL, 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)
874 ereport(ERROR,
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
884 * PANIC anyway.
886 TwoPhaseFilePath(path, xid);
888 fd = BasicOpenFile(path,
889 O_CREAT | O_EXCL | O_WRONLY | PG_BINARY,
890 S_IRUSR | S_IWUSR);
891 if (fd < 0)
892 ereport(ERROR,
893 (errcode_for_file_access(),
894 errmsg("could not create two-phase state file \"%s\": %m",
895 path)));
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)
905 close(fd);
906 ereport(ERROR,
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))
922 close(fd);
923 ereport(ERROR,
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)
931 close(fd);
932 ereport(ERROR,
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,
963 records.head);
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))
971 close(fd);
972 ereport(ERROR,
973 (errcode_for_file_access(),
974 errmsg("could not write two-phase state file: %m")));
977 if (close(fd) != 0)
978 ereport(ERROR,
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;
1003 END_CRIT_SECTION();
1005 records.tail = records.head = NULL;
1009 * Register a 2PC record to be written to state file.
1011 void
1012 RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info,
1013 const void *data, uint32 len)
1015 TwoPhaseRecordOnDisk record;
1017 record.rmid = rmid;
1018 record.info = info;
1019 record.len = len;
1020 save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1021 if (len > 0)
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.
1032 static char *
1033 ReadTwoPhaseFile(TransactionId xid)
1035 char path[MAXPGPATH];
1036 char *buf;
1037 TwoPhaseFileHeader *hdr;
1038 int fd;
1039 struct stat stat;
1040 uint32 crc_offset;
1041 pg_crc32 calc_crc,
1042 file_crc;
1044 TwoPhaseFilePath(path, xid);
1046 fd = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1047 if (fd < 0)
1049 ereport(WARNING,
1050 (errcode_for_file_access(),
1051 errmsg("could not open two-phase state file \"%s\": %m",
1052 path)));
1053 return NULL;
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))
1064 close(fd);
1065 ereport(WARNING,
1066 (errcode_for_file_access(),
1067 errmsg("could not stat two-phase state file \"%s\": %m",
1068 path)));
1069 return NULL;
1072 if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1073 MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1074 sizeof(pg_crc32)) ||
1075 stat.st_size > MaxAllocSize)
1077 close(fd);
1078 return NULL;
1081 crc_offset = stat.st_size - sizeof(pg_crc32);
1082 if (crc_offset != MAXALIGN(crc_offset))
1084 close(fd);
1085 return NULL;
1089 * OK, slurp in the file.
1091 buf = (char *) palloc(stat.st_size);
1093 if (read(fd, buf, stat.st_size) != stat.st_size)
1095 close(fd);
1096 ereport(WARNING,
1097 (errcode_for_file_access(),
1098 errmsg("could not read two-phase state file \"%s\": %m",
1099 path)));
1100 pfree(buf);
1101 return NULL;
1104 close(fd);
1106 hdr = (TwoPhaseFileHeader *) buf;
1107 if (hdr->magic != TWOPHASE_MAGIC || hdr->total_len != stat.st_size)
1109 pfree(buf);
1110 return NULL;
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))
1121 pfree(buf);
1122 return NULL;
1125 return buf;
1130 * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1132 void
1133 FinishPreparedTransaction(const char *gid, bool isCommit)
1135 GlobalTransaction gxact;
1136 TransactionId xid;
1137 char *buf;
1138 char *bufptr;
1139 TwoPhaseFileHeader *hdr;
1140 TransactionId latestXid;
1141 TransactionId *children;
1142 RelFileNode *commitrels;
1143 RelFileNode *abortrels;
1144 int i;
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);
1157 if (buf == NULL)
1158 ereport(ERROR,
1159 (errcode(ERRCODE_DATA_CORRUPTED),
1160 errmsg("two-phase state file for transaction %u is corrupt",
1161 xid)));
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.
1187 if (isCommit)
1188 RecordTransactionCommitPrepared(xid,
1189 hdr->nsubxacts, children,
1190 hdr->ncommitrels, commitrels);
1191 else
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 ...
1214 if (isCommit)
1216 for (i = 0; i < hdr->ncommitrels; i++)
1217 smgrdounlink(smgropen(commitrels[i]), false, false);
1219 else
1221 for (i = 0; i < hdr->nabortrels; i++)
1222 smgrdounlink(smgropen(abortrels[i]), false, false);
1225 /* And now do the callbacks */
1226 if (isCommit)
1227 ProcessRecords(bufptr, xid, twophase_postcommit_callbacks);
1228 else
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);
1239 RemoveGXact(gxact);
1241 pfree(buf);
1245 * Scan a 2PC state file (already read into memory by ReadTwoPhaseFile)
1246 * and call the indicated callbacks for each 2PC record.
1248 static void
1249 ProcessRecords(char *bufptr, TransactionId xid,
1250 const TwoPhaseCallback callbacks[])
1252 for (;;)
1254 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1256 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1257 if (record->rmid == TWOPHASE_RM_END_ID)
1258 break;
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.
1276 void
1277 RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
1279 char path[MAXPGPATH];
1281 TwoPhaseFilePath(path, xid);
1282 if (unlink(path))
1283 if (errno != ENOENT || giveWarning)
1284 ereport(WARNING,
1285 (errcode_for_file_access(),
1286 errmsg("could not remove two-phase state file \"%s\": %m",
1287 path)));
1291 * Recreates a state file. This is used in WAL replay.
1293 * Note: content and len don't include CRC.
1295 void
1296 RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
1298 char path[MAXPGPATH];
1299 pg_crc32 statefile_crc;
1300 int fd;
1302 /* Recompute 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,
1311 S_IRUSR | S_IWUSR);
1312 if (fd < 0)
1313 ereport(ERROR,
1314 (errcode_for_file_access(),
1315 errmsg("could not recreate two-phase state file \"%s\": %m",
1316 path)));
1318 /* Write content and CRC */
1319 if (write(fd, content, len) != len)
1321 close(fd);
1322 ereport(ERROR,
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))
1328 close(fd);
1329 ereport(ERROR,
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)
1340 close(fd);
1341 ereport(ERROR,
1342 (errcode_for_file_access(),
1343 errmsg("could not fsync two-phase state file: %m")));
1346 if (close(fd) != 0)
1347 ereport(ERROR,
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.)
1369 void
1370 CheckPointTwoPhase(XLogRecPtr redo_horizon)
1372 TransactionId *xids;
1373 int nxids;
1374 char path[MAXPGPATH];
1375 int i;
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));
1391 nxids = 0;
1393 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1395 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1397 GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1399 if (gxact->valid &&
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];
1409 int fd;
1411 TwoPhaseFilePath(path, xid);
1413 fd = BasicOpenFile(path, O_RDWR | PG_BINARY, 0);
1414 if (fd < 0)
1416 if (errno == ENOENT)
1418 /* OK if gxact is no longer valid */
1419 if (!TransactionIdIsPrepared(xid))
1420 continue;
1421 /* Restore errno in case it was changed */
1422 errno = ENOENT;
1424 ereport(ERROR,
1425 (errcode_for_file_access(),
1426 errmsg("could not open two-phase state file \"%s\": %m",
1427 path)));
1430 if (pg_fsync(fd) != 0)
1432 close(fd);
1433 ereport(ERROR,
1434 (errcode_for_file_access(),
1435 errmsg("could not fsync two-phase state file \"%s\": %m",
1436 path)));
1439 if (close(fd) != 0)
1440 ereport(ERROR,
1441 (errcode_for_file_access(),
1442 errmsg("could not close two-phase state file \"%s\": %m",
1443 path)));
1446 pfree(xids);
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
1466 * subxact XIDs.
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.
1472 TransactionId
1473 PrescanPreparedTransactions(void)
1475 TransactionId origNextXid = ShmemVariableCache->nextXid;
1476 TransactionId result = origNextXid;
1477 DIR *cldir;
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)
1486 TransactionId xid;
1487 char *buf;
1488 TwoPhaseFileHeader *hdr;
1489 TransactionId *subxids;
1490 int i;
1492 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1494 /* Reject XID if too new */
1495 if (TransactionIdFollowsOrEquals(xid, origNextXid))
1497 ereport(WARNING,
1498 (errmsg("removing future two-phase state file \"%s\"",
1499 clde->d_name)));
1500 RemoveTwoPhaseFile(xid, true);
1501 continue;
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);
1511 if (buf == NULL)
1513 ereport(WARNING,
1514 (errmsg("removing corrupt two-phase state file \"%s\"",
1515 clde->d_name)));
1516 RemoveTwoPhaseFile(xid, true);
1517 continue;
1520 /* Deconstruct header */
1521 hdr = (TwoPhaseFileHeader *) buf;
1522 if (!TransactionIdEquals(hdr->xid, xid))
1524 ereport(WARNING,
1525 (errmsg("removing corrupt two-phase state file \"%s\"",
1526 clde->d_name)));
1527 RemoveTwoPhaseFile(xid, true);
1528 pfree(buf);
1529 continue;
1533 * OK, we think this file is valid. Incorporate xid into the
1534 * running-minimum result.
1536 if (TransactionIdPrecedes(xid, result))
1537 result = xid;
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);
1558 pfree(buf);
1561 FreeDir(cldir);
1563 return result;
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
1571 * startup.
1573 void
1574 RecoverPreparedTransactions(void)
1576 char dir[MAXPGPATH];
1577 DIR *cldir;
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)
1588 TransactionId xid;
1589 char *buf;
1590 char *bufptr;
1591 TwoPhaseFileHeader *hdr;
1592 TransactionId *subxids;
1593 GlobalTransaction gxact;
1594 int i;
1596 xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1598 /* Already processed? */
1599 if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
1601 ereport(WARNING,
1602 (errmsg("removing stale two-phase state file \"%s\"",
1603 clde->d_name)));
1604 RemoveTwoPhaseFile(xid, true);
1605 continue;
1608 /* Read and validate file */
1609 buf = ReadTwoPhaseFile(xid);
1610 if (buf == NULL)
1612 ereport(WARNING,
1613 (errmsg("removing corrupt two-phase state file \"%s\"",
1614 clde->d_name)));
1615 RemoveTwoPhaseFile(xid, true);
1616 continue;
1619 ereport(LOG,
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
1649 * been fsynced).
1651 gxact = MarkAsPreparing(xid, hdr->gid,
1652 hdr->prepared_at,
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);
1662 pfree(buf);
1665 FreeDir(cldir);
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.
1677 static void
1678 RecordTransactionCommitPrepared(TransactionId xid,
1679 int nchildren,
1680 TransactionId *children,
1681 int nrels,
1682 RelFileNode *rels)
1684 XLogRecData rdata[3];
1685 int lastrdata = 0;
1686 xl_xact_commit_prepared xlrec;
1687 XLogRecPtr recptr;
1689 START_CRIT_SECTION();
1691 /* See notes in RecordTransactionCommit */
1692 MyProc->inCommit = true;
1694 /* Emit the XLOG commit record */
1695 xlrec.xid = xid;
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 */
1703 if (nrels > 0)
1705 rdata[0].next = &(rdata[1]);
1706 rdata[1].data = (char *) rels;
1707 rdata[1].len = nrels * sizeof(RelFileNode);
1708 rdata[1].buffer = InvalidBuffer;
1709 lastrdata = 1;
1711 /* dump committed child Xids */
1712 if (nchildren > 0)
1714 rdata[lastrdata].next = &(rdata[2]);
1715 rdata[2].data = (char *) children;
1716 rdata[2].len = nchildren * sizeof(TransactionId);
1717 rdata[2].buffer = InvalidBuffer;
1718 lastrdata = 2;
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
1727 * a contradiction)
1730 /* Flush XLOG to disk */
1731 XLogFlush(recptr);
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;
1741 END_CRIT_SECTION();
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.
1752 static void
1753 RecordTransactionAbortPrepared(TransactionId xid,
1754 int nchildren,
1755 TransactionId *children,
1756 int nrels,
1757 RelFileNode *rels)
1759 XLogRecData rdata[3];
1760 int lastrdata = 0;
1761 xl_xact_abort_prepared xlrec;
1762 XLogRecPtr recptr;
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",
1770 xid);
1772 START_CRIT_SECTION();
1774 /* Emit the XLOG abort record */
1775 xlrec.xid = xid;
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 */
1783 if (nrels > 0)
1785 rdata[0].next = &(rdata[1]);
1786 rdata[1].data = (char *) rels;
1787 rdata[1].len = nrels * sizeof(RelFileNode);
1788 rdata[1].buffer = InvalidBuffer;
1789 lastrdata = 1;
1791 /* dump committed child Xids */
1792 if (nchildren > 0)
1794 rdata[lastrdata].next = &(rdata[2]);
1795 rdata[2].data = (char *) children;
1796 rdata[2].len = nchildren * sizeof(TransactionId);
1797 rdata[2].buffer = InvalidBuffer;
1798 lastrdata = 2;
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 */
1805 XLogFlush(recptr);
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);
1814 END_CRIT_SECTION();