PostgreSQL Source Code  git master
twophase.h File Reference
#include "access/xact.h"
#include "access/xlogdefs.h"
#include "datatype/timestamp.h"
#include "storage/lock.h"
Include dependency graph for twophase.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef struct GlobalTransactionDataGlobalTransaction
 

Functions

Size TwoPhaseShmemSize (void)
 
void TwoPhaseShmemInit (void)
 
void AtAbort_Twophase (void)
 
void PostPrepare_Twophase (void)
 
PGPROCTwoPhaseGetDummyProc (TransactionId xid, bool lock_held)
 
BackendId TwoPhaseGetDummyBackendId (TransactionId xid, bool lock_held)
 
GlobalTransaction MarkAsPreparing (TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
void StartPrepare (GlobalTransaction gxact)
 
void EndPrepare (GlobalTransaction gxact)
 
bool StandbyTransactionIdIsPrepared (TransactionId xid)
 
TransactionId PrescanPreparedTransactions (TransactionId **xids_p, int *nxids_p)
 
void StandbyRecoverPreparedTransactions (void)
 
void RecoverPreparedTransactions (void)
 
void CheckPointTwoPhase (XLogRecPtr redo_horizon)
 
void FinishPreparedTransaction (const char *gid, bool isCommit)
 
void PrepareRedoAdd (char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
 
void PrepareRedoRemove (TransactionId xid, bool giveWarning)
 
void restoreTwoPhaseData (void)
 

Variables

PGDLLIMPORT int max_prepared_xacts
 

Typedef Documentation

◆ GlobalTransaction

Definition at line 26 of file twophase.h.

Function Documentation

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 317 of file twophase.c.

References InvalidBackendId, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), RemoveGXact(), and GlobalTransactionData::valid.

Referenced by AbortTransaction(), and AtProcExit_Twophase().

318 {
319  if (MyLockedGxact == NULL)
320  return;
321 
322  /*
323  * What to do with the locked global transaction entry? If we were in the
324  * process of preparing the transaction, but haven't written the WAL
325  * record and state file yet, the transaction must not be considered as
326  * prepared. Likewise, if we are in the process of finishing an
327  * already-prepared transaction, and fail after having already written the
328  * 2nd phase commit or rollback record to the WAL, the transaction should
329  * not be considered as prepared anymore. In those cases, just remove the
330  * entry from shared memory.
331  *
332  * Otherwise, the entry must be left in place so that the transaction can
333  * be finished later, so just unlock it.
334  *
335  * If we abort during prepare, after having written the WAL record, we
336  * might not have transferred all locks and other state to the prepared
337  * transaction yet. Likewise, if we abort during commit or rollback,
338  * after having written the WAL record, we might not have released all the
339  * resources held by the transaction yet. In those cases, the in-memory
340  * state can be wrong, but it's too late to back out.
341  */
342  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
343  if (!MyLockedGxact->valid)
345  else
347  LWLockRelease(TwoPhaseStateLock);
348 
349  MyLockedGxact = NULL;
350 }
BackendId locking_backend
Definition: twophase.c:168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:634
#define InvalidBackendId
Definition: backendid.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1695 of file twophase.c.

References buf, ereport, errmsg_plural(), fsync_fname(), i, GlobalTransactionData::inredo, InvalidXLogRecPtr, LOG, log_checkpoints, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_prepared_xacts, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, TwoPhaseStateData::prepXacts, RecreateTwoPhaseFile(), TWOPHASE_DIR, GlobalTransactionData::valid, GlobalTransactionData::xid, and XlogReadTwoPhaseData().

Referenced by CheckPointGuts().

1696 {
1697  int i;
1698  int serialized_xacts = 0;
1699 
1700  if (max_prepared_xacts <= 0)
1701  return; /* nothing to do */
1702 
1703  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1704 
1705  /*
1706  * We are expecting there to be zero GXACTs that need to be copied to
1707  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1708  * simplicity. This prevents any new xacts from preparing while this
1709  * occurs, which shouldn't be a problem since the presence of long-lived
1710  * prepared xacts indicates the transaction manager isn't active.
1711  *
1712  * It's also possible to move I/O out of the lock, but on every error we
1713  * should check whether somebody committed our transaction in different
1714  * backend. Let's leave this optimization for future, if somebody will
1715  * spot that this place cause bottleneck.
1716  *
1717  * Note that it isn't possible for there to be a GXACT with a
1718  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1719  * because of the efforts with delayChkpt.
1720  */
1721  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1722  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1723  {
1724  /*
1725  * Note that we are using gxact not pgxact so this works in recovery
1726  * also
1727  */
1729 
1730  if ((gxact->valid || gxact->inredo) &&
1731  !gxact->ondisk &&
1732  gxact->prepare_end_lsn <= redo_horizon)
1733  {
1734  char *buf;
1735  int len;
1736 
1737  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1738  RecreateTwoPhaseFile(gxact->xid, buf, len);
1739  gxact->ondisk = true;
1742  pfree(buf);
1743  serialized_xacts++;
1744  }
1745  }
1746  LWLockRelease(TwoPhaseStateLock);
1747 
1748  /*
1749  * Flush unconditionally the parent directory to make any information
1750  * durable on disk. Two-phase files could have been removed and those
1751  * removals need to be made persistent as well as any files newly created
1752  * previously since the last checkpoint.
1753  */
1754  fsync_fname(TWOPHASE_DIR, true);
1755 
1756  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1757 
1758  if (log_checkpoints && serialized_xacts > 0)
1759  ereport(LOG,
1760  (errmsg_plural("%u two-phase state file was written "
1761  "for a long-running prepared transaction",
1762  "%u two-phase state files were written "
1763  "for long-running prepared transactions",
1764  serialized_xacts,
1765  serialized_xacts)));
1766 }
bool log_checkpoints
Definition: xlog.c:101
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:617
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
int max_prepared_xacts
Definition: twophase.c:117
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1615
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define TWOPHASE_DIR
Definition: twophase.c:114
TransactionId xid
Definition: twophase.c:165
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1327
int i
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1060 of file twophase.c.

References Assert, StateFileChunk::data, PGXACT::delayChkpt, DoNotReplicateId, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xllist::head, InvalidRepOriginId, InvalidXLogRecPtr, StateFileChunk::len, xl_xact_prepare::magic, MarkAsPrepared(), MaxAllocSize, MyPgXact, StateFileChunk::next, xllist::num_chunks, xl_xact_prepare::origin_lsn, xl_xact_prepare::origin_timestamp, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, ProcLastRecPtr, records, RegisterTwoPhaseRecord(), replorigin_session_advance(), replorigin_session_origin, replorigin_session_origin_lsn, replorigin_session_origin_timestamp, START_CRIT_SECTION, SyncRepWaitForLSN(), xllist::tail, xl_xact_prepare::total_len, xllist::total_len, TWOPHASE_MAGIC, TWOPHASE_RM_END_ID, XLOG_INCLUDE_ORIGIN, XLOG_XACT_PREPARE, XLogBeginInsert(), XLogEnsureRecordSpace(), XLogFlush(), XLogInsert(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by PrepareTransaction().

1061 {
1062  TwoPhaseFileHeader *hdr;
1063  StateFileChunk *record;
1064  bool replorigin;
1065 
1066  /* Add the end sentinel to the list of 2PC records */
1068  NULL, 0);
1069 
1070  /* Go back and fill in total_len in the file header record */
1071  hdr = (TwoPhaseFileHeader *) records.head->data;
1072  Assert(hdr->magic == TWOPHASE_MAGIC);
1073  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1074 
1075  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1077 
1078  if (replorigin)
1079  {
1083  }
1084  else
1085  {
1087  hdr->origin_timestamp = 0;
1088  }
1089 
1090  /*
1091  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1092  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1093  * where we write data to file and then re-read at commit time.
1094  */
1095  if (hdr->total_len > MaxAllocSize)
1096  ereport(ERROR,
1097  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1098  errmsg("two-phase state file maximum length exceeded")));
1099 
1100  /*
1101  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1102  * cover us, so no need to calculate a separate CRC.
1103  *
1104  * We have to set delayChkpt here, too; otherwise a checkpoint starting
1105  * immediately after the WAL record is inserted could complete without
1106  * fsync'ing our state file. (This is essentially the same kind of race
1107  * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1108  * uses delayChkpt for; see notes there.)
1109  *
1110  * We save the PREPARE record's location in the gxact for later use by
1111  * CheckPointTwoPhase.
1112  */
1114 
1116 
1117  MyPgXact->delayChkpt = true;
1118 
1119  XLogBeginInsert();
1120  for (record = records.head; record != NULL; record = record->next)
1121  XLogRegisterData(record->data, record->len);
1122 
1124 
1125  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1126 
1127  if (replorigin)
1128  {
1129  /* Move LSNs forward for this replication origin */
1131  gxact->prepare_end_lsn);
1132  }
1133 
1134  XLogFlush(gxact->prepare_end_lsn);
1135 
1136  /* If we crash now, we have prepared: WAL replay will fix things */
1137 
1138  /* Store record's start location to read that later on Commit */
1140 
1141  /*
1142  * Mark the prepared transaction as valid. As soon as xact.c marks
1143  * MyPgXact as not running our XID (which it will do immediately after
1144  * this function returns), others can commit/rollback the xact.
1145  *
1146  * NB: a side effect of this is to make a dummy ProcArray entry for the
1147  * prepared XID. This must happen before we clear the XID from MyPgXact,
1148  * else there is a window where the XID is not running according to
1149  * TransactionIdIsInProgress, and onlookers would be entitled to assume
1150  * the xact crashed. Instead we have a window where the same XID appears
1151  * twice in ProcArray, which is OK.
1152  */
1153  MarkAsPrepared(gxact, false);
1154 
1155  /*
1156  * Now we can mark ourselves as out of the commit critical section: a
1157  * checkpoint starting after this will certainly see the gxact as a
1158  * candidate for fsyncing.
1159  */
1160  MyPgXact->delayChkpt = false;
1161 
1162  /*
1163  * Remember that we have this GlobalTransaction entry locked for us. If
1164  * we crash after this point, it's too late to abort, but we must unlock
1165  * it so that the prepared transaction can be committed or rolled back.
1166  */
1167  MyLockedGxact = gxact;
1168 
1169  END_CRIT_SECTION();
1170 
1171  /*
1172  * Wait for synchronous replication, if required.
1173  *
1174  * Note that at this stage we have marked the prepare, but still show as
1175  * running in the procarray (twice!) and continue to hold locks.
1176  */
1177  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1178 
1179  records.tail = records.head = NULL;
1180  records.num_chunks = 0;
1181 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define XLOG_XACT_PREPARE
Definition: xact.h:144
#define DoNotReplicateId
Definition: origin.h:34
StateFileChunk * tail
Definition: twophase.c:943
uint32 pg_crc32c
Definition: pg_crc32c.h:38
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:351
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:146
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
int errcode(int sqlerrcode)
Definition: elog.c:608
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:228
uint32 num_chunks
Definition: twophase.c:944
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2805
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1187
PGXACT * MyPgXact
Definition: proc.c:68
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
char * data
Definition: twophase.c:935
#define ERROR
Definition: elog.h:43
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:153
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:154
XLogRecPtr origin_lsn
Definition: xact.h:309
uint32 total_len
Definition: xact.h:298
uint32 len
Definition: twophase.c:936
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:397
#define ereport(elevel, rest)
Definition: elog.h:141
bool delayChkpt
Definition: proc.h:235
static struct xllist records
uint32 total_len
Definition: twophase.c:946
#define MaxAllocSize
Definition: memutils.h:40
struct StateFileChunk * next
Definition: twophase.c:937
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define TWOPHASE_MAGIC
Definition: twophase.c:911
StateFileChunk * head
Definition: twophase.c:942
#define Assert(condition)
Definition: c.h:739
RepOriginId replorigin_session_origin
Definition: origin.c:152
TimestampTz origin_timestamp
Definition: xact.h:310
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition: xloginsert.c:146
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1170
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:536
#define InvalidRepOriginId
Definition: origin.h:33
uint32 magic
Definition: xact.h:297
int errmsg(const char *fmt,...)
Definition: elog.c:822
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1399 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Assert, AtEOXact_PgStat(), buf, DropRelationFiles(), GetUserId(), xl_xact_prepare::gidlen, HOLD_INTERRUPTS, xl_xact_prepare::initfileinval, LockGXact(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, xl_xact_prepare::nabortrels, xl_xact_prepare::ncommitrels, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::pgprocno, PredicateLockTwoPhaseFinish(), GlobalTransactionData::prepare_start_lsn, ProcArrayRemove(), ProcessRecords(), ProcGlobal, ReadTwoPhaseFile(), RecordTransactionAbortPrepared(), RecordTransactionCommitPrepared(), RelationCacheInitFilePostInvalidate(), RelationCacheInitFilePreInvalidate(), RemoveGXact(), RemoveTwoPhaseFile(), RESUME_INTERRUPTS, SendSharedInvalidMessages(), TransactionIdEquals, TransactionIdLatest(), twophase_postabort_callbacks, twophase_postcommit_callbacks, GlobalTransactionData::valid, GlobalTransactionData::xid, PGXACT::xid, xl_xact_prepare::xid, and XlogReadTwoPhaseData().

Referenced by standard_ProcessUtility().

1400 {
1401  GlobalTransaction gxact;
1402  PGPROC *proc;
1403  PGXACT *pgxact;
1404  TransactionId xid;
1405  char *buf;
1406  char *bufptr;
1407  TwoPhaseFileHeader *hdr;
1408  TransactionId latestXid;
1409  TransactionId *children;
1410  RelFileNode *commitrels;
1411  RelFileNode *abortrels;
1412  RelFileNode *delrels;
1413  int ndelrels;
1414  SharedInvalidationMessage *invalmsgs;
1415 
1416  /*
1417  * Validate the GID, and lock the GXACT to ensure that two backends do not
1418  * try to commit the same GID at once.
1419  */
1420  gxact = LockGXact(gid, GetUserId());
1421  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1422  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1423  xid = pgxact->xid;
1424 
1425  /*
1426  * Read and validate 2PC state data. State data will typically be stored
1427  * in WAL files if the LSN is after the last checkpoint record, or moved
1428  * to disk if for some reason they have lived for a long time.
1429  */
1430  if (gxact->ondisk)
1431  buf = ReadTwoPhaseFile(xid, false);
1432  else
1433  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1434 
1435 
1436  /*
1437  * Disassemble the header area
1438  */
1439  hdr = (TwoPhaseFileHeader *) buf;
1440  Assert(TransactionIdEquals(hdr->xid, xid));
1441  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1442  bufptr += MAXALIGN(hdr->gidlen);
1443  children = (TransactionId *) bufptr;
1444  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1445  commitrels = (RelFileNode *) bufptr;
1446  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1447  abortrels = (RelFileNode *) bufptr;
1448  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1449  invalmsgs = (SharedInvalidationMessage *) bufptr;
1450  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1451 
1452  /* compute latestXid among all children */
1453  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1454 
1455  /* Prevent cancel/die interrupt while cleaning up */
1456  HOLD_INTERRUPTS();
1457 
1458  /*
1459  * The order of operations here is critical: make the XLOG entry for
1460  * commit or abort, then mark the transaction committed or aborted in
1461  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1462  * TransactionIdIsInProgress will stop saying the prepared xact is in
1463  * progress), then run the post-commit or post-abort callbacks. The
1464  * callbacks will release the locks the transaction held.
1465  */
1466  if (isCommit)
1468  hdr->nsubxacts, children,
1469  hdr->ncommitrels, commitrels,
1470  hdr->ninvalmsgs, invalmsgs,
1471  hdr->initfileinval, gid);
1472  else
1474  hdr->nsubxacts, children,
1475  hdr->nabortrels, abortrels,
1476  gid);
1477 
1478  ProcArrayRemove(proc, latestXid);
1479 
1480  /*
1481  * In case we fail while running the callbacks, mark the gxact invalid so
1482  * no one else will try to commit/rollback, and so it will be recycled if
1483  * we fail after this point. It is still locked by our backend so it
1484  * won't go away yet.
1485  *
1486  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1487  */
1488  gxact->valid = false;
1489 
1490  /*
1491  * We have to remove any files that were supposed to be dropped. For
1492  * consistency with the regular xact.c code paths, must do this before
1493  * releasing locks, so do it before running the callbacks.
1494  *
1495  * NB: this code knows that we couldn't be dropping any temp rels ...
1496  */
1497  if (isCommit)
1498  {
1499  delrels = commitrels;
1500  ndelrels = hdr->ncommitrels;
1501  }
1502  else
1503  {
1504  delrels = abortrels;
1505  ndelrels = hdr->nabortrels;
1506  }
1507 
1508  /* Make sure files supposed to be dropped are dropped */
1509  DropRelationFiles(delrels, ndelrels, false);
1510 
1511  /*
1512  * Handle cache invalidation messages.
1513  *
1514  * Relcache init file invalidation requires processing both before and
1515  * after we send the SI messages. See AtEOXact_Inval()
1516  */
1517  if (hdr->initfileinval)
1519  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1520  if (hdr->initfileinval)
1522 
1523  /*
1524  * Acquire the two-phase lock. We want to work on the two-phase callbacks
1525  * while holding it to avoid potential conflicts with other transactions
1526  * attempting to use the same GID, so the lock is released once the shared
1527  * memory state is cleared.
1528  */
1529  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1530 
1531  /* And now do the callbacks */
1532  if (isCommit)
1534  else
1536 
1537  PredicateLockTwoPhaseFinish(xid, isCommit);
1538 
1539  /* Clear shared memory state */
1540  RemoveGXact(gxact);
1541 
1542  /*
1543  * Release the lock as all callbacks are called and shared memory cleanup
1544  * is done.
1545  */
1546  LWLockRelease(TwoPhaseStateLock);
1547 
1548  /* Count the prepared xact as committed or aborted */
1549  AtEOXact_PgStat(isCommit, false);
1550 
1551  /*
1552  * And now we can clean up any files we may have left.
1553  */
1554  if (gxact->ondisk)
1555  RemoveTwoPhaseFile(xid, true);
1556 
1557  MyLockedGxact = NULL;
1558 
1560 
1561  pfree(buf);
1562 }
int32 ninvalmsgs
Definition: xact.h:306
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, const char *gid)
Definition: twophase.c:2276
int32 nsubxacts
Definition: xact.h:303
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
int32 ncommitrels
Definition: xact.h:304
Oid GetUserId(void)
Definition: miscinit.c:380
PGXACT * allPgXact
Definition: proc.h:249
TransactionId xid
Definition: proc.h:224
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:365
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1568
const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:33
PROC_HDR * ProcGlobal
Definition: proc.c:80
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1210
uint16 gidlen
Definition: xact.h:308
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
int32 nabortrels
Definition: xact.h:305
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
void pfree(void *pointer)
Definition: mcxt.c:1056
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:558
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:335
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:634
void DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
Definition: md.c:1001
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat.c:2092
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:5004
static char * buf
Definition: pg_test_fsync.c:67
const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:42
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:6014
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1596
bool initfileinval
Definition: xact.h:307
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:5989
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define MAXALIGN(LEN)
Definition: c.h:692
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
TransactionId xid
Definition: xact.h:299
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1327
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
PGPROC * allProcs
Definition: proc.h:247
Definition: proc.h:95
static void RecordTransactionCommitPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval, const char *gid)
Definition: twophase.c:2182

◆ MarkAsPreparing()

GlobalTransaction MarkAsPreparing ( TransactionId  xid,
const char *  gid,
TimestampTz  prepared_at,
Oid  owner,
Oid  databaseid 
)

Definition at line 372 of file twophase.c.

References Assert, AtProcExit_Twophase(), before_shmem_exit(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, TwoPhaseStateData::freeGXacts, GlobalTransactionData::gid, GIDSIZE, i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MarkAsPreparingGuts(), max_prepared_xacts, GlobalTransactionData::next, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, TwoPhaseStateData::prepXacts, and twophaseExitRegistered.

Referenced by PrepareTransaction().

374 {
375  GlobalTransaction gxact;
376  int i;
377 
378  if (strlen(gid) >= GIDSIZE)
379  ereport(ERROR,
380  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
381  errmsg("transaction identifier \"%s\" is too long",
382  gid)));
383 
384  /* fail immediately if feature is disabled */
385  if (max_prepared_xacts == 0)
386  ereport(ERROR,
387  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
388  errmsg("prepared transactions are disabled"),
389  errhint("Set max_prepared_transactions to a nonzero value.")));
390 
391  /* on first call, register the exit hook */
393  {
395  twophaseExitRegistered = true;
396  }
397 
398  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
399 
400  /* Check for conflicting GID */
401  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
402  {
403  gxact = TwoPhaseState->prepXacts[i];
404  if (strcmp(gxact->gid, gid) == 0)
405  {
406  ereport(ERROR,
408  errmsg("transaction identifier \"%s\" is already in use",
409  gid)));
410  }
411  }
412 
413  /* Get a free gxact from the freelist */
414  if (TwoPhaseState->freeGXacts == NULL)
415  ereport(ERROR,
416  (errcode(ERRCODE_OUT_OF_MEMORY),
417  errmsg("maximum number of prepared transactions reached"),
418  errhint("Increase max_prepared_transactions (currently %d).",
420  gxact = TwoPhaseState->freeGXacts;
421  TwoPhaseState->freeGXacts = gxact->next;
422 
423  MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
424 
425  gxact->ondisk = false;
426 
427  /* And insert it into the active array */
430 
431  LWLockRelease(TwoPhaseStateLock);
432 
433  return gxact;
434 }
int errhint(const char *fmt,...)
Definition: elog.c:1069
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
int errcode(int sqlerrcode)
Definition: elog.c:608
static bool twophaseExitRegistered
Definition: twophase.c:201
GlobalTransaction next
Definition: twophase.c:151
char gid[GIDSIZE]
Definition: twophase.c:172
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:446
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:117
#define GIDSIZE
Definition: xact.h:31
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:307
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31

◆ PostPrepare_Twophase()

void PostPrepare_Twophase ( void  )

Definition at line 357 of file twophase.c.

References InvalidBackendId, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockAcquire(), and LWLockRelease().

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

358 {
359  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
361  LWLockRelease(TwoPhaseStateLock);
362 
363  MyLockedGxact = NULL;
364 }
BackendId locking_backend
Definition: twophase.c:168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define InvalidBackendId
Definition: backendid.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199

◆ PrepareRedoAdd()

void PrepareRedoAdd ( char *  buf,
XLogRecPtr  start_lsn,
XLogRecPtr  end_lsn,
RepOriginId  origin_id 
)

Definition at line 2335 of file twophase.c.

References Assert, DEBUG2, elog, ereport, errcode(), errhint(), errmsg(), ERROR, TwoPhaseStateData::freeGXacts, GlobalTransactionData::gid, GlobalTransactionData::inredo, InvalidBackendId, InvalidRepOriginId, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockHeldByMeInMode(), max_prepared_xacts, MAXALIGN, GlobalTransactionData::next, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, xl_xact_prepare::origin_lsn, GlobalTransactionData::owner, xl_xact_prepare::owner, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, GlobalTransactionData::prepared_at, xl_xact_prepare::prepared_at, TwoPhaseStateData::prepXacts, RecoveryInProgress(), replorigin_advance(), GlobalTransactionData::valid, GlobalTransactionData::xid, xl_xact_prepare::xid, and XLogRecPtrIsInvalid.

Referenced by restoreTwoPhaseData(), and xact_redo().

2337 {
2339  char *bufptr;
2340  const char *gid;
2341  GlobalTransaction gxact;
2342 
2343  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2345 
2346  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2347  gid = (const char *) bufptr;
2348 
2349  /*
2350  * Reserve the GID for the given transaction in the redo code path.
2351  *
2352  * This creates a gxact struct and puts it into the active array.
2353  *
2354  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2355  * shared memory. Hence, we only fill up the bare minimum contents here.
2356  * The gxact also gets marked with gxact->inredo set to true to indicate
2357  * that it got added in the redo phase
2358  */
2359 
2360  /* Get a free gxact from the freelist */
2361  if (TwoPhaseState->freeGXacts == NULL)
2362  ereport(ERROR,
2363  (errcode(ERRCODE_OUT_OF_MEMORY),
2364  errmsg("maximum number of prepared transactions reached"),
2365  errhint("Increase max_prepared_transactions (currently %d).",
2366  max_prepared_xacts)));
2367  gxact = TwoPhaseState->freeGXacts;
2368  TwoPhaseState->freeGXacts = gxact->next;
2369 
2370  gxact->prepared_at = hdr->prepared_at;
2371  gxact->prepare_start_lsn = start_lsn;
2372  gxact->prepare_end_lsn = end_lsn;
2373  gxact->xid = hdr->xid;
2374  gxact->owner = hdr->owner;
2376  gxact->valid = false;
2377  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2378  gxact->inredo = true; /* yes, added in redo */
2379  strcpy(gxact->gid, gid);
2380 
2381  /* And insert it into the active array */
2384 
2385  if (origin_id != InvalidRepOriginId)
2386  {
2387  /* recover apply progress */
2388  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2389  false /* backward */ , false /* WAL */ );
2390  }
2391 
2392  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2393 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
int errhint(const char *fmt,...)
Definition: elog.c:1069
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
int errcode(int sqlerrcode)
Definition: elog.c:608
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:857
GlobalTransaction next
Definition: twophase.c:151
bool RecoveryInProgress(void)
Definition: xlog.c:7935
char gid[GIDSIZE]
Definition: twophase.c:172
BackendId locking_backend
Definition: twophase.c:168
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:117
#define DEBUG2
Definition: elog.h:24
static char * buf
Definition: pg_test_fsync.c:67
XLogRecPtr origin_lsn
Definition: xact.h:309
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define InvalidBackendId
Definition: backendid.h:23
#define Assert(condition)
Definition: c.h:739
#define MAXALIGN(LEN)
Definition: c.h:692
TransactionId xid
Definition: xact.h:299
#define InvalidRepOriginId
Definition: origin.h:33
TransactionId xid
Definition: twophase.c:165
TimestampTz prepared_at
Definition: twophase.c:154
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
TimestampTz prepared_at
Definition: xact.h:301
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2405 of file twophase.c.

References Assert, DEBUG2, elog, i, GlobalTransactionData::inredo, LW_EXCLUSIVE, LWLockHeldByMeInMode(), TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, TwoPhaseStateData::prepXacts, RecoveryInProgress(), RemoveGXact(), RemoveTwoPhaseFile(), and GlobalTransactionData::xid.

Referenced by ProcessTwoPhaseBuffer(), and xact_redo().

2406 {
2407  GlobalTransaction gxact = NULL;
2408  int i;
2409  bool found = false;
2410 
2411  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2413 
2414  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2415  {
2416  gxact = TwoPhaseState->prepXacts[i];
2417 
2418  if (gxact->xid == xid)
2419  {
2420  Assert(gxact->inredo);
2421  found = true;
2422  break;
2423  }
2424  }
2425 
2426  /*
2427  * Just leave if there is nothing, this is expected during WAL replay.
2428  */
2429  if (!found)
2430  return;
2431 
2432  /*
2433  * And now we can clean up any files we may have left.
2434  */
2435  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2436  if (gxact->ondisk)
2437  RemoveTwoPhaseFile(xid, giveWarning);
2438  RemoveGXact(gxact);
2439 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
bool RecoveryInProgress(void)
Definition: xlog.c:7935
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:634
#define DEBUG2
Definition: elog.h:24
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1596
#define Assert(condition)
Definition: c.h:739
TransactionId xid
Definition: twophase.c:165
#define elog(elevel,...)
Definition: elog.h:228
int i

◆ PrescanPreparedTransactions()

TransactionId PrescanPreparedTransactions ( TransactionId **  xids_p,
int *  nxids_p 
)

Definition at line 1839 of file twophase.c.

References Assert, buf, i, GlobalTransactionData::inredo, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), VariableCacheData::nextFullXid, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, palloc(), pfree(), GlobalTransactionData::prepare_start_lsn, TwoPhaseStateData::prepXacts, ProcessTwoPhaseBuffer(), repalloc(), ShmemVariableCache, TransactionIdPrecedes(), GlobalTransactionData::xid, and XidFromFullTransactionId.

Referenced by StartupXLOG(), and xlog_redo().

1840 {
1842  TransactionId origNextXid = XidFromFullTransactionId(nextFullXid);
1843  TransactionId result = origNextXid;
1844  TransactionId *xids = NULL;
1845  int nxids = 0;
1846  int allocsize = 0;
1847  int i;
1848 
1849  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1850  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1851  {
1852  TransactionId xid;
1853  char *buf;
1855 
1856  Assert(gxact->inredo);
1857 
1858  xid = gxact->xid;
1859 
1860  buf = ProcessTwoPhaseBuffer(xid,
1861  gxact->prepare_start_lsn,
1862  gxact->ondisk, false, true);
1863 
1864  if (buf == NULL)
1865  continue;
1866 
1867  /*
1868  * OK, we think this file is valid. Incorporate xid into the
1869  * running-minimum result.
1870  */
1871  if (TransactionIdPrecedes(xid, result))
1872  result = xid;
1873 
1874  if (xids_p)
1875  {
1876  if (nxids == allocsize)
1877  {
1878  if (nxids == 0)
1879  {
1880  allocsize = 10;
1881  xids = palloc(allocsize * sizeof(TransactionId));
1882  }
1883  else
1884  {
1885  allocsize = allocsize * 2;
1886  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1887  }
1888  }
1889  xids[nxids++] = xid;
1890  }
1891 
1892  pfree(buf);
1893  }
1894  LWLockRelease(TwoPhaseStateLock);
1895 
1896  if (xids_p)
1897  {
1898  *xids_p = xids;
1899  *nxids_p = nxids;
1900  }
1901 
1902  return result;
1903 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:514
FullTransactionId nextFullXid
Definition: transam.h:164
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
#define XidFromFullTransactionId(x)
Definition: transam.h:48
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
static char * buf
Definition: pg_test_fsync.c:67
VariableCache ShmemVariableCache
Definition: varsup.c:34
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2062
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
TransactionId xid
Definition: twophase.c:165
void * palloc(Size size)
Definition: mcxt.c:949
int i

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 1961 of file twophase.c.

References Assert, buf, xl_xact_prepare::database, ereport, errmsg(), GlobalTransactionData::gid, xl_xact_prepare::gidlen, GXactLoadSubxactData(), i, InHotStandby, GlobalTransactionData::inredo, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MarkAsPrepared(), MarkAsPreparingGuts(), MAXALIGN, xl_xact_prepare::nabortrels, xl_xact_prepare::ncommitrels, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, xl_xact_prepare::owner, pfree(), PostPrepare_Twophase(), GlobalTransactionData::prepare_start_lsn, xl_xact_prepare::prepared_at, TwoPhaseStateData::prepXacts, ProcessRecords(), ProcessTwoPhaseBuffer(), StandbyReleaseLockTree(), TransactionIdEquals, twophase_recover_callbacks, GlobalTransactionData::xid, and xl_xact_prepare::xid.

Referenced by StartupXLOG().

1962 {
1963  int i;
1964 
1965  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1966  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1967  {
1968  TransactionId xid;
1969  char *buf;
1971  char *bufptr;
1972  TwoPhaseFileHeader *hdr;
1973  TransactionId *subxids;
1974  const char *gid;
1975 
1976  xid = gxact->xid;
1977 
1978  /*
1979  * Reconstruct subtrans state for the transaction --- needed because
1980  * pg_subtrans is not preserved over a restart. Note that we are
1981  * linking all the subtransactions directly to the top-level XID;
1982  * there may originally have been a more complex hierarchy, but
1983  * there's no need to restore that exactly. It's possible that
1984  * SubTransSetParent has been set before, if the prepared transaction
1985  * generated xid assignment records.
1986  */
1987  buf = ProcessTwoPhaseBuffer(xid,
1988  gxact->prepare_start_lsn,
1989  gxact->ondisk, true, false);
1990  if (buf == NULL)
1991  continue;
1992 
1993  ereport(LOG,
1994  (errmsg("recovering prepared transaction %u from shared memory", xid)));
1995 
1996  hdr = (TwoPhaseFileHeader *) buf;
1997  Assert(TransactionIdEquals(hdr->xid, xid));
1998  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1999  gid = (const char *) bufptr;
2000  bufptr += MAXALIGN(hdr->gidlen);
2001  subxids = (TransactionId *) bufptr;
2002  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
2003  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
2004  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
2005  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
2006 
2007  /*
2008  * Recreate its GXACT and dummy PGPROC. But, check whether it was
2009  * added in redo and already has a shmem entry for it.
2010  */
2011  MarkAsPreparingGuts(gxact, xid, gid,
2012  hdr->prepared_at,
2013  hdr->owner, hdr->database);
2014 
2015  /* recovered, so reset the flag for entries generated by redo */
2016  gxact->inredo = false;
2017 
2018  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
2019  MarkAsPrepared(gxact, true);
2020 
2021  LWLockRelease(TwoPhaseStateLock);
2022 
2023  /*
2024  * Recover other state (notably locks) using resource managers.
2025  */
2027 
2028  /*
2029  * Release locks held by the standby process after we process each
2030  * prepared transaction. As a result, we don't need too many
2031  * additional locks at any one time.
2032  */
2033  if (InHotStandby)
2034  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2035 
2036  /*
2037  * We're done with recovering this transaction. Clear MyLockedGxact,
2038  * like we do in PrepareTransaction() during normal operation.
2039  */
2041 
2042  pfree(buf);
2043 
2044  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2045  }
2046 
2047  LWLockRelease(TwoPhaseStateLock);
2048 }
int32 ninvalmsgs
Definition: xact.h:306
int32 nsubxacts
Definition: xact.h:303
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:514
int32 ncommitrels
Definition: xact.h:304
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1568
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlog.h:74
uint16 gidlen
Definition: xact.h:308
#define LOG
Definition: elog.h:26
Oid database
Definition: xact.h:300
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
int32 nabortrels
Definition: xact.h:305
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:446
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:509
static char * buf
Definition: pg_test_fsync.c:67
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:716
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2062
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define MAXALIGN(LEN)
Definition: c.h:692
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:536
TransactionId xid
Definition: xact.h:299
TransactionId xid
Definition: twophase.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:822
void PostPrepare_Twophase(void)
Definition: twophase.c:357
int i
TimestampTz prepared_at
Definition: xact.h:301

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1777 of file twophase.c.

References AllocateDir(), buf, dirent::d_name, FreeDir(), InvalidRepOriginId, InvalidXLogRecPtr, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), PrepareRedoAdd(), ProcessTwoPhaseBuffer(), ReadDir(), TWOPHASE_DIR, and GlobalTransactionData::xid.

Referenced by StartupXLOG().

1778 {
1779  DIR *cldir;
1780  struct dirent *clde;
1781 
1782  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1783  cldir = AllocateDir(TWOPHASE_DIR);
1784  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1785  {
1786  if (strlen(clde->d_name) == 8 &&
1787  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1788  {
1789  TransactionId xid;
1790  char *buf;
1791 
1792  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1793 
1795  true, false, false);
1796  if (buf == NULL)
1797  continue;
1798 
1801  }
1802  }
1803  LWLockRelease(TwoPhaseStateLock);
1804  FreeDir(cldir);
1805 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TransactionId
Definition: c.h:514
Definition: dirent.h:9
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
Definition: dirent.c:25
static char * buf
Definition: pg_test_fsync.c:67
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2503
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2062
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2335
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2569
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define InvalidRepOriginId
Definition: origin.h:33
#define TWOPHASE_DIR
Definition: twophase.c:114
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2621

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 1920 of file twophase.c.

References Assert, buf, i, GlobalTransactionData::inredo, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::prepare_start_lsn, TwoPhaseStateData::prepXacts, ProcessTwoPhaseBuffer(), and GlobalTransactionData::xid.

Referenced by StartupXLOG(), and xlog_redo().

1921 {
1922  int i;
1923 
1924  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1925  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1926  {
1927  TransactionId xid;
1928  char *buf;
1930 
1931  Assert(gxact->inredo);
1932 
1933  xid = gxact->xid;
1934 
1935  buf = ProcessTwoPhaseBuffer(xid,
1936  gxact->prepare_start_lsn,
1937  gxact->ondisk, false, false);
1938  if (buf != NULL)
1939  pfree(buf);
1940  }
1941  LWLockRelease(TwoPhaseStateLock);
1942 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:514
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
static char * buf
Definition: pg_test_fsync.c:67
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2062
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
TransactionId xid
Definition: twophase.c:165
int i

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1371 of file twophase.c.

References Assert, buf, max_prepared_xacts, pfree(), ReadTwoPhaseFile(), TransactionIdEquals, TransactionIdIsValid, and xl_xact_prepare::xid.

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

1372 {
1373  char *buf;
1374  TwoPhaseFileHeader *hdr;
1375  bool result;
1376 
1378 
1379  if (max_prepared_xacts <= 0)
1380  return false; /* nothing to do */
1381 
1382  /* Read and validate file */
1383  buf = ReadTwoPhaseFile(xid, true);
1384  if (buf == NULL)
1385  return false;
1386 
1387  /* Check header also */
1388  hdr = (TwoPhaseFileHeader *) buf;
1389  result = TransactionIdEquals(hdr->xid, xid);
1390  pfree(buf);
1391 
1392  return result;
1393 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1210
void pfree(void *pointer)
Definition: mcxt.c:1056
int max_prepared_xacts
Definition: twophase.c:117
static char * buf
Definition: pg_test_fsync.c:67
#define Assert(condition)
Definition: c.h:739
TransactionId xid
Definition: xact.h:299
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 987 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, xllist::bytes_free, StateFileChunk::data, xl_xact_prepare::database, PGPROC::databaseId, GlobalTransactionData::gid, xl_xact_prepare::gidlen, GXactLoadSubxactData(), xllist::head, xl_xact_prepare::initfileinval, StateFileChunk::len, xl_xact_prepare::magic, Max, xl_xact_prepare::nabortrels, xl_xact_prepare::ncommitrels, StateFileChunk::next, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, xllist::num_chunks, GlobalTransactionData::owner, xl_xact_prepare::owner, palloc(), palloc0(), pfree(), GlobalTransactionData::pgprocno, GlobalTransactionData::prepared_at, xl_xact_prepare::prepared_at, ProcGlobal, records, save_state_data(), smgrGetPendingDeletes(), xllist::tail, xl_xact_prepare::total_len, xllist::total_len, TWOPHASE_MAGIC, xactGetCommittedChildren(), xactGetCommittedInvalidationMessages(), GlobalTransactionData::xid, PGXACT::xid, and xl_xact_prepare::xid.

Referenced by PrepareTransaction().

988 {
989  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
990  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
991  TransactionId xid = pgxact->xid;
992  TwoPhaseFileHeader hdr;
993  TransactionId *children;
994  RelFileNode *commitrels;
995  RelFileNode *abortrels;
996  SharedInvalidationMessage *invalmsgs;
997 
998  /* Initialize linked list */
999  records.head = palloc0(sizeof(StateFileChunk));
1000  records.head->len = 0;
1001  records.head->next = NULL;
1002 
1003  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1005 
1007  records.num_chunks = 1;
1008 
1009  records.total_len = 0;
1010 
1011  /* Create header */
1012  hdr.magic = TWOPHASE_MAGIC;
1013  hdr.total_len = 0; /* EndPrepare will fill this in */
1014  hdr.xid = xid;
1015  hdr.database = proc->databaseId;
1016  hdr.prepared_at = gxact->prepared_at;
1017  hdr.owner = gxact->owner;
1018  hdr.nsubxacts = xactGetCommittedChildren(&children);
1019  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1020  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1022  &hdr.initfileinval);
1023  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1024 
1025  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1026  save_state_data(gxact->gid, hdr.gidlen);
1027 
1028  /*
1029  * Add the additional info about subxacts, deletable files and cache
1030  * invalidation messages.
1031  */
1032  if (hdr.nsubxacts > 0)
1033  {
1034  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1035  /* While we have the child-xact data, stuff it in the gxact too */
1036  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1037  }
1038  if (hdr.ncommitrels > 0)
1039  {
1040  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1041  pfree(commitrels);
1042  }
1043  if (hdr.nabortrels > 0)
1044  {
1045  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1046  pfree(abortrels);
1047  }
1048  if (hdr.ninvalmsgs > 0)
1049  {
1050  save_state_data(invalmsgs,
1051  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1052  pfree(invalmsgs);
1053  }
1054 }
int32 ninvalmsgs
Definition: xact.h:306
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5421
int32 nsubxacts
Definition: xact.h:303
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
int32 ncommitrels
Definition: xact.h:304
PGXACT * allPgXact
Definition: proc.h:249
TransactionId xid
Definition: proc.h:224
StateFileChunk * tail
Definition: twophase.c:943
PROC_HDR * ProcGlobal
Definition: proc.c:80
uint16 gidlen
Definition: xact.h:308
uint32 num_chunks
Definition: twophase.c:944
char gid[GIDSIZE]
Definition: twophase.c:172
Oid database
Definition: xact.h:300
char * data
Definition: twophase.c:935
int32 nabortrels
Definition: xact.h:305
void pfree(void *pointer)
Definition: mcxt.c:1056
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:509
uint32 bytes_free
Definition: twophase.c:945
int smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
Definition: storage.c:513
uint32 total_len
Definition: xact.h:298
uint32 len
Definition: twophase.c:936
Oid databaseId
Definition: proc.h:114
static struct xllist records
uint32 total_len
Definition: twophase.c:946
struct StateFileChunk * next
Definition: twophase.c:937
void * palloc0(Size size)
Definition: mcxt.c:980
#define TWOPHASE_MAGIC
Definition: twophase.c:911
bool initfileinval
Definition: xact.h:307
#define Max(x, y)
Definition: c.h:905
StateFileChunk * head
Definition: twophase.c:942
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:959
TransactionId xid
Definition: xact.h:299
TimestampTz prepared_at
Definition: twophase.c:154
uint32 magic
Definition: xact.h:297
void * palloc(Size size)
Definition: mcxt.c:949
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:828
TimestampTz prepared_at
Definition: xact.h:301
PGPROC * allProcs
Definition: proc.h:247
Definition: proc.h:95

◆ TwoPhaseGetDummyBackendId()

BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid,
bool  lock_held 
)

Definition at line 863 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

Referenced by multixact_twophase_postcommit(), multixact_twophase_recover(), and PostPrepare_MultiXact().

864 {
865  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
866 
867  return gxact->dummyBackendId;
868 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:809
BackendId dummyBackendId
Definition: twophase.c:153

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid,
bool  lock_held 
)

Definition at line 878 of file twophase.c.

References PROC_HDR::allProcs, GlobalTransactionData::pgprocno, ProcGlobal, and TwoPhaseGetGXact().

Referenced by lock_twophase_postcommit(), lock_twophase_recover(), and PostPrepare_Locks().

879 {
880  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
881 
882  return &ProcGlobal->allProcs[gxact->pgprocno];
883 }
PROC_HDR * ProcGlobal
Definition: proc.c:80
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:809
PGPROC * allProcs
Definition: proc.h:247

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 252 of file twophase.c.

References Assert, GlobalTransactionData::dummyBackendId, TwoPhaseStateData::freeGXacts, i, IsUnderPostmaster, max_prepared_xacts, MAXALIGN, MaxBackends, GlobalTransactionData::next, TwoPhaseStateData::numPrepXacts, offsetof, PGPROC::pgprocno, GlobalTransactionData::pgprocno, PreparedXactProcs, ShmemInitStruct(), and TwoPhaseShmemSize().

Referenced by CreateSharedMemoryAndSemaphores().

253 {
254  bool found;
255 
256  TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
258  &found);
259  if (!IsUnderPostmaster)
260  {
261  GlobalTransaction gxacts;
262  int i;
263 
264  Assert(!found);
265  TwoPhaseState->freeGXacts = NULL;
267 
268  /*
269  * Initialize the linked list of free GlobalTransactionData structs
270  */
271  gxacts = (GlobalTransaction)
272  ((char *) TwoPhaseState +
273  MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
275  for (i = 0; i < max_prepared_xacts; i++)
276  {
277  /* insert into linked list */
278  gxacts[i].next = TwoPhaseState->freeGXacts;
279  TwoPhaseState->freeGXacts = &gxacts[i];
280 
281  /* associate it with a PGPROC assigned by InitProcGlobal */
283 
284  /*
285  * Assign a unique ID for each dummy proc, so that the range of
286  * dummy backend IDs immediately follows the range of normal
287  * backend IDs. We don't dare to assign a real backend ID to dummy
288  * procs, because prepared transactions don't take part in cache
289  * invalidation like a real backend ID would imply, but having a
290  * unique ID for them is nevertheless handy. This arrangement
291  * allows you to allocate an array of size (MaxBackends +
292  * max_prepared_xacts + 1), and have a slot for every backend and
293  * prepared transaction. Currently multixact.c uses that
294  * technique.
295  */
296  gxacts[i].dummyBackendId = MaxBackends + 1 + i;
297  }
298  }
299  else
300  Assert(found);
301 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
PGPROC * PreparedXactProcs
Definition: proc.c:82
Size TwoPhaseShmemSize(void)
Definition: twophase.c:236
GlobalTransaction next
Definition: twophase.c:151
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:26
int max_prepared_xacts
Definition: twophase.c:117
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
int MaxBackends
Definition: globals.c:135
bool IsUnderPostmaster
Definition: globals.c:109
#define Assert(condition)
Definition: c.h:739
#define MAXALIGN(LEN)
Definition: c.h:692
int pgprocno
Definition: proc.h:110
int i
#define offsetof(type, field)
Definition: c.h:662
BackendId dummyBackendId
Definition: twophase.c:153

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 236 of file twophase.c.

References add_size(), max_prepared_xacts, MAXALIGN, mul_size(), and offsetof.

Referenced by CreateSharedMemoryAndSemaphores(), and TwoPhaseShmemInit().

237 {
238  Size size;
239 
240  /* Need the fixed struct, the array of pointers, and the GTD structs */
241  size = offsetof(TwoPhaseStateData, prepXacts);
242  size = add_size(size, mul_size(max_prepared_xacts,
243  sizeof(GlobalTransaction)));
244  size = MAXALIGN(size);
245  size = add_size(size, mul_size(max_prepared_xacts,
246  sizeof(GlobalTransactionData)));
247 
248  return size;
249 }
int max_prepared_xacts
Definition: twophase.c:117
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
size_t Size
Definition: c.h:467
#define MAXALIGN(LEN)
Definition: c.h:692
#define offsetof(type, field)
Definition: c.h:662

Variable Documentation

◆ max_prepared_xacts