PostgreSQL Source Code  git master
twophase.h File Reference
#include "access/xlogdefs.h"
#include "access/xact.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)
 
BackendId TwoPhaseGetDummyBackendId (TransactionId xid)
 
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 ParsePrepareRecord (uint8 info, char *xlrec, xl_xact_parsed_prepare *parsed)
 
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:1725
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:634
#define InvalidBackendId
Definition: backendid.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1735 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().

1736 {
1737  int i;
1738  int serialized_xacts = 0;
1739 
1740  if (max_prepared_xacts <= 0)
1741  return; /* nothing to do */
1742 
1743  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1744 
1745  /*
1746  * We are expecting there to be zero GXACTs that need to be copied to
1747  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1748  * simplicity. This prevents any new xacts from preparing while this
1749  * occurs, which shouldn't be a problem since the presence of long-lived
1750  * prepared xacts indicates the transaction manager isn't active.
1751  *
1752  * It's also possible to move I/O out of the lock, but on every error we
1753  * should check whether somebody committed our transaction in different
1754  * backend. Let's leave this optimization for future, if somebody will
1755  * spot that this place cause bottleneck.
1756  *
1757  * Note that it isn't possible for there to be a GXACT with a
1758  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1759  * because of the efforts with delayChkpt.
1760  */
1761  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1762  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1763  {
1764  /*
1765  * Note that we are using gxact not pgxact so this works in recovery
1766  * also
1767  */
1769 
1770  if ((gxact->valid || gxact->inredo) &&
1771  !gxact->ondisk &&
1772  gxact->prepare_end_lsn <= redo_horizon)
1773  {
1774  char *buf;
1775  int len;
1776 
1777  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1778  RecreateTwoPhaseFile(gxact->xid, buf, len);
1779  gxact->ondisk = true;
1782  pfree(buf);
1783  serialized_xacts++;
1784  }
1785  }
1786  LWLockRelease(TwoPhaseStateLock);
1787 
1788  /*
1789  * Flush unconditionally the parent directory to make any information
1790  * durable on disk. Two-phase files could have been removed and those
1791  * removals need to be made persistent as well as any files newly created
1792  * previously since the last checkpoint.
1793  */
1794  fsync_fname(TWOPHASE_DIR, true);
1795 
1796  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1797 
1798  if (log_checkpoints && serialized_xacts > 0)
1799  ereport(LOG,
1800  (errmsg_plural("%u two-phase state file was written "
1801  "for a long-running prepared transaction",
1802  "%u two-phase state files were written "
1803  "for long-running prepared transactions",
1804  serialized_xacts,
1805  serialized_xacts)));
1806 }
bool log_checkpoints
Definition: xlog.c:102
#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:850
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:575
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
void pfree(void *pointer)
Definition: mcxt.c:1031
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:1641
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
#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:1367
int i
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1065 of file twophase.c.

References Assert, StateFileChunk::data, PGXACT::delayChkpt, DoNotReplicateId, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xllist::head, InvalidRepOriginId, InvalidXLogRecPtr, StateFileChunk::len, TwoPhaseFileHeader::magic, MarkAsPrepared(), MaxAllocSize, MyPgXact, StateFileChunk::next, xllist::num_chunks, TwoPhaseFileHeader::origin_lsn, TwoPhaseFileHeader::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, TwoPhaseFileHeader::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().

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

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Assert, AtEOXact_PgStat(), buf, DropRelationFiles(), GetUserId(), TwoPhaseFileHeader::gidlen, HOLD_INTERRUPTS, TwoPhaseFileHeader::initfileinval, LockGXact(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, TwoPhaseFileHeader::nabortrels, TwoPhaseFileHeader::ncommitrels, TwoPhaseFileHeader::ninvalmsgs, TwoPhaseFileHeader::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, TwoPhaseFileHeader::xid, and XlogReadTwoPhaseData().

Referenced by standard_ProcessUtility().

1440 {
1441  GlobalTransaction gxact;
1442  PGPROC *proc;
1443  PGXACT *pgxact;
1444  TransactionId xid;
1445  char *buf;
1446  char *bufptr;
1447  TwoPhaseFileHeader *hdr;
1448  TransactionId latestXid;
1449  TransactionId *children;
1450  RelFileNode *commitrels;
1451  RelFileNode *abortrels;
1452  RelFileNode *delrels;
1453  int ndelrels;
1454  SharedInvalidationMessage *invalmsgs;
1455 
1456  /*
1457  * Validate the GID, and lock the GXACT to ensure that two backends do not
1458  * try to commit the same GID at once.
1459  */
1460  gxact = LockGXact(gid, GetUserId());
1461  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1462  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1463  xid = pgxact->xid;
1464 
1465  /*
1466  * Read and validate 2PC state data. State data will typically be stored
1467  * in WAL files if the LSN is after the last checkpoint record, or moved
1468  * to disk if for some reason they have lived for a long time.
1469  */
1470  if (gxact->ondisk)
1471  buf = ReadTwoPhaseFile(xid, false);
1472  else
1473  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1474 
1475 
1476  /*
1477  * Disassemble the header area
1478  */
1479  hdr = (TwoPhaseFileHeader *) buf;
1480  Assert(TransactionIdEquals(hdr->xid, xid));
1481  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1482  bufptr += MAXALIGN(hdr->gidlen);
1483  children = (TransactionId *) bufptr;
1484  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1485  commitrels = (RelFileNode *) bufptr;
1486  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1487  abortrels = (RelFileNode *) bufptr;
1488  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1489  invalmsgs = (SharedInvalidationMessage *) bufptr;
1490  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1491 
1492  /* compute latestXid among all children */
1493  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1494 
1495  /* Prevent cancel/die interrupt while cleaning up */
1496  HOLD_INTERRUPTS();
1497 
1498  /*
1499  * The order of operations here is critical: make the XLOG entry for
1500  * commit or abort, then mark the transaction committed or aborted in
1501  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1502  * TransactionIdIsInProgress will stop saying the prepared xact is in
1503  * progress), then run the post-commit or post-abort callbacks. The
1504  * callbacks will release the locks the transaction held.
1505  */
1506  if (isCommit)
1508  hdr->nsubxacts, children,
1509  hdr->ncommitrels, commitrels,
1510  hdr->ninvalmsgs, invalmsgs,
1511  hdr->initfileinval, gid);
1512  else
1514  hdr->nsubxacts, children,
1515  hdr->nabortrels, abortrels,
1516  gid);
1517 
1518  ProcArrayRemove(proc, latestXid);
1519 
1520  /*
1521  * In case we fail while running the callbacks, mark the gxact invalid so
1522  * no one else will try to commit/rollback, and so it will be recycled if
1523  * we fail after this point. It is still locked by our backend so it
1524  * won't go away yet.
1525  *
1526  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1527  */
1528  gxact->valid = false;
1529 
1530  /*
1531  * We have to remove any files that were supposed to be dropped. For
1532  * consistency with the regular xact.c code paths, must do this before
1533  * releasing locks, so do it before running the callbacks.
1534  *
1535  * NB: this code knows that we couldn't be dropping any temp rels ...
1536  */
1537  if (isCommit)
1538  {
1539  delrels = commitrels;
1540  ndelrels = hdr->ncommitrels;
1541  }
1542  else
1543  {
1544  delrels = abortrels;
1545  ndelrels = hdr->nabortrels;
1546  }
1547 
1548  /* Make sure files supposed to be dropped are dropped */
1549  DropRelationFiles(delrels, ndelrels, false);
1550 
1551  /*
1552  * Handle cache invalidation messages.
1553  *
1554  * Relcache init file invalidation requires processing both before and
1555  * after we send the SI messages. See AtEOXact_Inval()
1556  */
1557  if (hdr->initfileinval)
1559  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1560  if (hdr->initfileinval)
1562 
1563  /* And now do the callbacks */
1564  if (isCommit)
1566  else
1568 
1569  PredicateLockTwoPhaseFinish(xid, isCommit);
1570 
1571  /* Count the prepared xact as committed or aborted */
1572  AtEOXact_PgStat(isCommit);
1573 
1574  /*
1575  * And now we can clean up any files we may have left.
1576  */
1577  if (gxact->ondisk)
1578  RemoveTwoPhaseFile(xid, true);
1579 
1580  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1581  RemoveGXact(gxact);
1582  LWLockRelease(TwoPhaseStateLock);
1583  MyLockedGxact = NULL;
1584 
1586 
1587  pfree(buf);
1588 }
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, const char *gid)
Definition: twophase.c:2330
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:507
Definition: proc.h:222
Oid GetUserId(void)
Definition: miscinit.c:392
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:1594
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:1215
TransactionId xid
Definition: twophase.c:906
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
void pfree(void *pointer)
Definition: mcxt.c:1031
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:558
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:333
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:634
void DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
Definition: md.c:1711
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:4850
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:6100
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1622
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:6075
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
#define MAXALIGN(LEN)
Definition: c.h:685
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1367
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
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:2236
void AtEOXact_PgStat(bool isCommit)
Definition: pgstat.c:2053

◆ 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:987
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
int errcode(int sqlerrcode)
Definition: elog.c:575
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:1725
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:30
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:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:307
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32

◆ ParsePrepareRecord()

void ParsePrepareRecord ( uint8  info,
char *  xlrec,
xl_xact_parsed_prepare parsed 
)

Definition at line 1323 of file twophase.c.

References xl_xact_parsed_commit::abortnodes, TwoPhaseFileHeader::database, xl_xact_parsed_commit::dbId, TwoPhaseFileHeader::gidlen, MAXALIGN, xl_xact_parsed_commit::msgs, xl_xact_parsed_commit::nabortrels, TwoPhaseFileHeader::nabortrels, TwoPhaseFileHeader::ncommitrels, TwoPhaseFileHeader::ninvalmsgs, xl_xact_parsed_commit::nmsgs, xl_xact_parsed_commit::nrels, xl_xact_parsed_commit::nsubxacts, TwoPhaseFileHeader::nsubxacts, xl_xact_parsed_commit::origin_lsn, TwoPhaseFileHeader::origin_lsn, xl_xact_parsed_commit::origin_timestamp, TwoPhaseFileHeader::origin_timestamp, xl_xact_parsed_commit::subxacts, xl_xact_parsed_commit::twophase_gid, xl_xact_parsed_commit::twophase_xid, TwoPhaseFileHeader::xid, and xl_xact_parsed_commit::xnodes.

1324 {
1325  TwoPhaseFileHeader *hdr;
1326  char *bufptr;
1327 
1328  hdr = (TwoPhaseFileHeader *) xlrec;
1329  bufptr = xlrec + MAXALIGN(sizeof(TwoPhaseFileHeader));
1330 
1331  parsed->origin_lsn = hdr->origin_lsn;
1332  parsed->origin_timestamp = hdr->origin_timestamp;
1333  parsed->twophase_xid = hdr->xid;
1334  parsed->dbId = hdr->database;
1335  parsed->nsubxacts = hdr->nsubxacts;
1336  parsed->nrels = hdr->ncommitrels;
1337  parsed->nabortrels = hdr->nabortrels;
1338  parsed->nmsgs = hdr->ninvalmsgs;
1339 
1340  strncpy(parsed->twophase_gid, bufptr, hdr->gidlen);
1341  bufptr += MAXALIGN(hdr->gidlen);
1342 
1343  parsed->subxacts = (TransactionId *) bufptr;
1344  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1345 
1346  parsed->xnodes = (RelFileNode *) bufptr;
1347  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1348 
1349  parsed->abortnodes = (RelFileNode *) bufptr;
1350  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1351 
1352  parsed->msgs = (SharedInvalidationMessage *) bufptr;
1353  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1354 }
RelFileNode * xnodes
Definition: xact.h:309
uint32 TransactionId
Definition: c.h:507
TimestampTz origin_timestamp
Definition: xact.h:320
TransactionId twophase_xid
Definition: xact.h:314
TransactionId * subxacts
Definition: xact.h:306
SharedInvalidationMessage * msgs
Definition: xact.h:312
XLogRecPtr origin_lsn
Definition: xact.h:319
TransactionId xid
Definition: twophase.c:906
TimestampTz origin_timestamp
Definition: twophase.c:917
RelFileNode * abortnodes
Definition: xact.h:317
#define MAXALIGN(LEN)
Definition: c.h:685
XLogRecPtr origin_lsn
Definition: twophase.c:916
char twophase_gid[GIDSIZE]
Definition: xact.h:315

◆ 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:1725
#define InvalidBackendId
Definition: backendid.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199

◆ PrepareRedoAdd()

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

Definition at line 2389 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, TwoPhaseFileHeader::origin_lsn, GlobalTransactionData::owner, TwoPhaseFileHeader::owner, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, GlobalTransactionData::prepared_at, TwoPhaseFileHeader::prepared_at, TwoPhaseStateData::prepXacts, RecoveryInProgress(), replorigin_advance(), GlobalTransactionData::valid, GlobalTransactionData::xid, TwoPhaseFileHeader::xid, and XLogRecPtrIsInvalid.

Referenced by restoreTwoPhaseData(), and xact_redo().

2391 {
2393  char *bufptr;
2394  const char *gid;
2395  GlobalTransaction gxact;
2396 
2397  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2399 
2400  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2401  gid = (const char *) bufptr;
2402 
2403  /*
2404  * Reserve the GID for the given transaction in the redo code path.
2405  *
2406  * This creates a gxact struct and puts it into the active array.
2407  *
2408  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2409  * shared memory. Hence, we only fill up the bare minimum contents here.
2410  * The gxact also gets marked with gxact->inredo set to true to indicate
2411  * that it got added in the redo phase
2412  */
2413 
2414  /* Get a free gxact from the freelist */
2415  if (TwoPhaseState->freeGXacts == NULL)
2416  ereport(ERROR,
2417  (errcode(ERRCODE_OUT_OF_MEMORY),
2418  errmsg("maximum number of prepared transactions reached"),
2419  errhint("Increase max_prepared_transactions (currently %d).",
2420  max_prepared_xacts)));
2421  gxact = TwoPhaseState->freeGXacts;
2422  TwoPhaseState->freeGXacts = gxact->next;
2423 
2424  gxact->prepared_at = hdr->prepared_at;
2425  gxact->prepare_start_lsn = start_lsn;
2426  gxact->prepare_end_lsn = end_lsn;
2427  gxact->xid = hdr->xid;
2428  gxact->owner = hdr->owner;
2430  gxact->valid = false;
2431  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2432  gxact->inredo = true; /* yes, added in redo */
2433  strcpy(gxact->gid, gid);
2434 
2435  /* And insert it into the active array */
2438 
2439  if (origin_id != InvalidRepOriginId)
2440  {
2441  /* recover apply progress */
2442  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2443  false /* backward */ , false /* WAL */ );
2444  }
2445 
2446  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2447 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1859
int errhint(const char *fmt,...)
Definition: elog.c:987
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
int errcode(int sqlerrcode)
Definition: elog.c:575
TransactionId xid
Definition: twophase.c:906
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:861
GlobalTransaction next
Definition: twophase.c:151
bool RecoveryInProgress(void)
Definition: xlog.c:8082
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
#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:732
#define MAXALIGN(LEN)
Definition: c.h:685
#define InvalidRepOriginId
Definition: origin.h:34
TransactionId xid
Definition: twophase.c:165
TimestampTz prepared_at
Definition: twophase.c:154
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog(elevel,...)
Definition: elog.h:226
XLogRecPtr origin_lsn
Definition: twophase.c:916
TimestampTz prepared_at
Definition: twophase.c:908
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2459 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().

2460 {
2461  GlobalTransaction gxact = NULL;
2462  int i;
2463  bool found = false;
2464 
2465  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2467 
2468  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2469  {
2470  gxact = TwoPhaseState->prepXacts[i];
2471 
2472  if (gxact->xid == xid)
2473  {
2474  Assert(gxact->inredo);
2475  found = true;
2476  break;
2477  }
2478  }
2479 
2480  /*
2481  * Just leave if there is nothing, this is expected during WAL replay.
2482  */
2483  if (!found)
2484  return;
2485 
2486  /*
2487  * And now we can clean up any files we may have left.
2488  */
2489  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2490  if (gxact->ondisk)
2491  RemoveTwoPhaseFile(xid, giveWarning);
2492  RemoveGXact(gxact);
2493 
2494  return;
2495 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1859
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
bool RecoveryInProgress(void)
Definition: xlog.c:8082
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:1622
#define Assert(condition)
Definition: c.h:732
TransactionId xid
Definition: twophase.c:165
#define elog(elevel,...)
Definition: elog.h:226
int i

◆ PrescanPreparedTransactions()

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

Definition at line 1879 of file twophase.c.

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

Referenced by StartupXLOG(), and xlog_redo().

1880 {
1881  TransactionId origNextXid = ShmemVariableCache->nextXid;
1882  TransactionId result = origNextXid;
1883  TransactionId *xids = NULL;
1884  int nxids = 0;
1885  int allocsize = 0;
1886  int i;
1887 
1888  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1889  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1890  {
1891  TransactionId xid;
1892  char *buf;
1894 
1895  Assert(gxact->inredo);
1896 
1897  xid = gxact->xid;
1898 
1899  buf = ProcessTwoPhaseBuffer(xid,
1900  gxact->prepare_start_lsn,
1901  gxact->ondisk, false, true);
1902 
1903  if (buf == NULL)
1904  continue;
1905 
1906  /*
1907  * OK, we think this file is valid. Incorporate xid into the
1908  * running-minimum result.
1909  */
1910  if (TransactionIdPrecedes(xid, result))
1911  result = xid;
1912 
1913  if (xids_p)
1914  {
1915  if (nxids == allocsize)
1916  {
1917  if (nxids == 0)
1918  {
1919  allocsize = 10;
1920  xids = palloc(allocsize * sizeof(TransactionId));
1921  }
1922  else
1923  {
1924  allocsize = allocsize * 2;
1925  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1926  }
1927  }
1928  xids[nxids++] = xid;
1929  }
1930 
1931  pfree(buf);
1932  }
1933  LWLockRelease(TwoPhaseStateLock);
1934 
1935  if (xids_p)
1936  {
1937  *xids_p = xids;
1938  *nxids_p = nxids;
1939  }
1940 
1941  return result;
1942 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:507
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
void pfree(void *pointer)
Definition: mcxt.c:1031
TransactionId nextXid
Definition: transam.h:117
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:2101
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
TransactionId xid
Definition: twophase.c:165
void * palloc(Size size)
Definition: mcxt.c:924
int i

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 2000 of file twophase.c.

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

Referenced by StartupXLOG().

2001 {
2002  int i;
2003 
2004  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2005  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2006  {
2007  TransactionId xid;
2008  char *buf;
2010  char *bufptr;
2011  TwoPhaseFileHeader *hdr;
2012  TransactionId *subxids;
2013  const char *gid;
2014 
2015  xid = gxact->xid;
2016 
2017  /*
2018  * Reconstruct subtrans state for the transaction --- needed because
2019  * pg_subtrans is not preserved over a restart. Note that we are
2020  * linking all the subtransactions directly to the top-level XID;
2021  * there may originally have been a more complex hierarchy, but
2022  * there's no need to restore that exactly. It's possible that
2023  * SubTransSetParent has been set before, if the prepared transaction
2024  * generated xid assignment records.
2025  */
2026  buf = ProcessTwoPhaseBuffer(xid,
2027  gxact->prepare_start_lsn,
2028  gxact->ondisk, true, false);
2029  if (buf == NULL)
2030  continue;
2031 
2032  ereport(LOG,
2033  (errmsg("recovering prepared transaction %u from shared memory", xid)));
2034 
2035  hdr = (TwoPhaseFileHeader *) buf;
2036  Assert(TransactionIdEquals(hdr->xid, xid));
2037  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2038  gid = (const char *) bufptr;
2039  bufptr += MAXALIGN(hdr->gidlen);
2040  subxids = (TransactionId *) bufptr;
2041  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
2042  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
2043  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
2044  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
2045 
2046  /*
2047  * Recreate its GXACT and dummy PGPROC. But, check whether it was
2048  * added in redo and already has a shmem entry for it.
2049  */
2050  MarkAsPreparingGuts(gxact, xid, gid,
2051  hdr->prepared_at,
2052  hdr->owner, hdr->database);
2053 
2054  /* recovered, so reset the flag for entries generated by redo */
2055  gxact->inredo = false;
2056 
2057  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
2058  MarkAsPrepared(gxact, true);
2059 
2060  LWLockRelease(TwoPhaseStateLock);
2061 
2062  /*
2063  * Recover other state (notably locks) using resource managers.
2064  */
2066 
2067  /*
2068  * Release locks held by the standby process after we process each
2069  * prepared transaction. As a result, we don't need too many
2070  * additional locks at any one time.
2071  */
2072  if (InHotStandby)
2073  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2074 
2075  /*
2076  * We're done with recovering this transaction. Clear MyLockedGxact,
2077  * like we do in PrepareTransaction() during normal operation.
2078  */
2080 
2081  pfree(buf);
2082 
2083  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2084  }
2085 
2086  LWLockRelease(TwoPhaseStateLock);
2087 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:507
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1594
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlog.h:74
TransactionId xid
Definition: twophase.c:906
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
void pfree(void *pointer)
Definition: mcxt.c:1031
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:2101
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
#define MAXALIGN(LEN)
Definition: c.h:685
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:536
TransactionId xid
Definition: twophase.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PostPrepare_Twophase(void)
Definition: twophase.c:357
int i
TimestampTz prepared_at
Definition: twophase.c:908

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1817 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().

1818 {
1819  DIR *cldir;
1820  struct dirent *clde;
1821 
1822  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1823  cldir = AllocateDir(TWOPHASE_DIR);
1824  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1825  {
1826  if (strlen(clde->d_name) == 8 &&
1827  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1828  {
1829  TransactionId xid;
1830  char *buf;
1831 
1832  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1833 
1835  true, false, false);
1836  if (buf == NULL)
1837  continue;
1838 
1841  }
1842  }
1843  LWLockRelease(TwoPhaseStateLock);
1844  FreeDir(cldir);
1845 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TransactionId
Definition: c.h:507
Definition: dirent.h:9
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
Definition: dirent.c:25
static char * buf
Definition: pg_test_fsync.c:67
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2590
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2101
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2389
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2656
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
#define InvalidRepOriginId
Definition: origin.h:34
#define TWOPHASE_DIR
Definition: twophase.c:114
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2708

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 1959 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().

1960 {
1961  int i;
1962 
1963  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1964  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1965  {
1966  TransactionId xid;
1967  char *buf;
1969 
1970  Assert(gxact->inredo);
1971 
1972  xid = gxact->xid;
1973 
1974  buf = ProcessTwoPhaseBuffer(xid,
1975  gxact->prepare_start_lsn,
1976  gxact->ondisk, false, false);
1977  if (buf != NULL)
1978  pfree(buf);
1979  }
1980  LWLockRelease(TwoPhaseStateLock);
1981 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:507
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
void pfree(void *pointer)
Definition: mcxt.c:1031
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:2101
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
TransactionId xid
Definition: twophase.c:165
int i

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1411 of file twophase.c.

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

1412 {
1413  char *buf;
1414  TwoPhaseFileHeader *hdr;
1415  bool result;
1416 
1418 
1419  if (max_prepared_xacts <= 0)
1420  return false; /* nothing to do */
1421 
1422  /* Read and validate file */
1423  buf = ReadTwoPhaseFile(xid, true);
1424  if (buf == NULL)
1425  return false;
1426 
1427  /* Check header also */
1428  hdr = (TwoPhaseFileHeader *) buf;
1429  result = TransactionIdEquals(hdr->xid, xid);
1430  pfree(buf);
1431 
1432  return result;
1433 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1215
TransactionId xid
Definition: twophase.c:906
void pfree(void *pointer)
Definition: mcxt.c:1031
int max_prepared_xacts
Definition: twophase.c:117
static char * buf
Definition: pg_test_fsync.c:67
#define Assert(condition)
Definition: c.h:732
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 992 of file twophase.c.

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

Referenced by PrepareTransaction().

993 {
994  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
995  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
996  TransactionId xid = pgxact->xid;
997  TwoPhaseFileHeader hdr;
998  TransactionId *children;
999  RelFileNode *commitrels;
1000  RelFileNode *abortrels;
1001  SharedInvalidationMessage *invalmsgs;
1002 
1003  /* Initialize linked list */
1004  records.head = palloc0(sizeof(StateFileChunk));
1005  records.head->len = 0;
1006  records.head->next = NULL;
1007 
1008  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1010 
1012  records.num_chunks = 1;
1013 
1014  records.total_len = 0;
1015 
1016  /* Create header */
1017  hdr.magic = TWOPHASE_MAGIC;
1018  hdr.total_len = 0; /* EndPrepare will fill this in */
1019  hdr.xid = xid;
1020  hdr.database = proc->databaseId;
1021  hdr.prepared_at = gxact->prepared_at;
1022  hdr.owner = gxact->owner;
1023  hdr.nsubxacts = xactGetCommittedChildren(&children);
1024  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1025  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1027  &hdr.initfileinval);
1028  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1029 
1030  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1031  save_state_data(gxact->gid, hdr.gidlen);
1032 
1033  /*
1034  * Add the additional info about subxacts, deletable files and cache
1035  * invalidation messages.
1036  */
1037  if (hdr.nsubxacts > 0)
1038  {
1039  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1040  /* While we have the child-xact data, stuff it in the gxact too */
1041  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1042  }
1043  if (hdr.ncommitrels > 0)
1044  {
1045  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1046  pfree(commitrels);
1047  }
1048  if (hdr.nabortrels > 0)
1049  {
1050  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1051  pfree(abortrels);
1052  }
1053  if (hdr.ninvalmsgs > 0)
1054  {
1055  save_state_data(invalmsgs,
1056  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1057  pfree(invalmsgs);
1058  }
1059 }
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5191
uint32 TransactionId
Definition: c.h:507
Definition: proc.h:222
PGXACT * allPgXact
Definition: proc.h:249
TransactionId xid
Definition: proc.h:224
StateFileChunk * tail
Definition: twophase.c:948
PROC_HDR * ProcGlobal
Definition: proc.c:80
TransactionId xid
Definition: twophase.c:906
uint32 num_chunks
Definition: twophase.c:949
char gid[GIDSIZE]
Definition: twophase.c:172
char * data
Definition: twophase.c:940
void pfree(void *pointer)
Definition: mcxt.c:1031
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:509
uint32 bytes_free
Definition: twophase.c:950
int smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
Definition: storage.c:388
uint32 len
Definition: twophase.c:941
Oid databaseId
Definition: proc.h:114
static struct xllist records
uint32 total_len
Definition: twophase.c:951
struct StateFileChunk * next
Definition: twophase.c:942
void * palloc0(Size size)
Definition: mcxt.c:955
#define TWOPHASE_MAGIC
Definition: twophase.c:900
#define Max(x, y)
Definition: c.h:884
StateFileChunk * head
Definition: twophase.c:947
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:964
TimestampTz prepared_at
Definition: twophase.c:154
void * palloc(Size size)
Definition: mcxt.c:924
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:826
PGPROC * allProcs
Definition: proc.h:247
TimestampTz prepared_at
Definition: twophase.c:908
Definition: proc.h:95

◆ TwoPhaseGetDummyBackendId()

BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid)

Definition at line 855 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

856 {
857  GlobalTransaction gxact = TwoPhaseGetGXact(xid);
858 
859  return gxact->dummyBackendId;
860 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid)
Definition: twophase.c:806
BackendId dummyBackendId
Definition: twophase.c:153

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid)

Definition at line 867 of file twophase.c.

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

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

868 {
869  GlobalTransaction gxact = TwoPhaseGetGXact(xid);
870 
871  return &ProcGlobal->allProcs[gxact->pgprocno];
872 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid)
Definition: twophase.c:806
PROC_HDR * ProcGlobal
Definition: proc.c:80
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:134
bool IsUnderPostmaster
Definition: globals.c:108
#define Assert(condition)
Definition: c.h:732
#define MAXALIGN(LEN)
Definition: c.h:685
int pgprocno
Definition: proc.h:110
int i
#define offsetof(type, field)
Definition: c.h:655
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:466
#define MAXALIGN(LEN)
Definition: c.h:685
#define offsetof(type, field)
Definition: c.h:655

Variable Documentation

◆ max_prepared_xacts