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)
 
TransactionId TwoPhaseGetXidByVirtualXID (VirtualTransactionId vxid, bool *have_more)
 
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)
 
bool LookupGXact (const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
 

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 321 of file twophase.c.

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

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1793 of file twophase.c.

1794 {
1795  int i;
1796  int serialized_xacts = 0;
1797 
1798  if (max_prepared_xacts <= 0)
1799  return; /* nothing to do */
1800 
1801  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1802 
1803  /*
1804  * We are expecting there to be zero GXACTs that need to be copied to
1805  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1806  * simplicity. This prevents any new xacts from preparing while this
1807  * occurs, which shouldn't be a problem since the presence of long-lived
1808  * prepared xacts indicates the transaction manager isn't active.
1809  *
1810  * It's also possible to move I/O out of the lock, but on every error we
1811  * should check whether somebody committed our transaction in different
1812  * backend. Let's leave this optimization for future, if somebody will
1813  * spot that this place cause bottleneck.
1814  *
1815  * Note that it isn't possible for there to be a GXACT with a
1816  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1817  * because of the efforts with delayChkptFlags.
1818  */
1819  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1820  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1821  {
1822  /*
1823  * Note that we are using gxact not PGPROC so this works in recovery
1824  * also
1825  */
1827 
1828  if ((gxact->valid || gxact->inredo) &&
1829  !gxact->ondisk &&
1830  gxact->prepare_end_lsn <= redo_horizon)
1831  {
1832  char *buf;
1833  int len;
1834 
1836  RecreateTwoPhaseFile(gxact->xid, buf, len);
1837  gxact->ondisk = true;
1840  pfree(buf);
1841  serialized_xacts++;
1842  }
1843  }
1844  LWLockRelease(TwoPhaseStateLock);
1845 
1846  /*
1847  * Flush unconditionally the parent directory to make any information
1848  * durable on disk. Two-phase files could have been removed and those
1849  * removals need to be made persistent as well as any files newly created
1850  * previously since the last checkpoint.
1851  */
1852  fsync_fname(TWOPHASE_DIR, true);
1853 
1854  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1855 
1856  if (log_checkpoints && serialized_xacts > 0)
1857  ereport(LOG,
1858  (errmsg_plural("%u two-phase state file was written "
1859  "for a long-running prepared transaction",
1860  "%u two-phase state files were written "
1861  "for long-running prepared transactions",
1862  serialized_xacts,
1863  serialized_xacts)));
1864 }
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1179
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:667
int i
Definition: isn.c:73
@ LW_SHARED
Definition: lwlock.h:117
void pfree(void *pointer)
Definition: mcxt.c:1456
const void size_t len
static char * buf
Definition: pg_test_fsync.c:67
TransactionId xid
Definition: twophase.c:165
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1397
#define TWOPHASE_DIR
Definition: twophase.c:114
int max_prepared_xacts
Definition: twophase.c:117
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1713
bool log_checkpoints
Definition: xlog.c:132
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References buf, ereport, errmsg_plural(), fsync_fname(), i, GlobalTransactionData::inredo, InvalidXLogRecPtr, len, 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, TwoPhaseState, GlobalTransactionData::valid, GlobalTransactionData::xid, and XlogReadTwoPhaseData().

Referenced by CheckPointGuts().

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1135 of file twophase.c.

1136 {
1137  TwoPhaseFileHeader *hdr;
1138  StateFileChunk *record;
1139  bool replorigin;
1140 
1141  /* Add the end sentinel to the list of 2PC records */
1143  NULL, 0);
1144 
1145  /* Go back and fill in total_len in the file header record */
1146  hdr = (TwoPhaseFileHeader *) records.head->data;
1147  Assert(hdr->magic == TWOPHASE_MAGIC);
1148  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1149 
1150  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1152 
1153  if (replorigin)
1154  {
1157  }
1158 
1159  /*
1160  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1161  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1162  * where we write data to file and then re-read at commit time.
1163  */
1164  if (hdr->total_len > MaxAllocSize)
1165  ereport(ERROR,
1166  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1167  errmsg("two-phase state file maximum length exceeded")));
1168 
1169  /*
1170  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1171  * cover us, so no need to calculate a separate CRC.
1172  *
1173  * We have to set DELAY_CHKPT_START here, too; otherwise a checkpoint
1174  * starting immediately after the WAL record is inserted could complete
1175  * without fsync'ing our state file. (This is essentially the same kind
1176  * of race condition as the COMMIT-to-clog-write case that
1177  * RecordTransactionCommit uses DELAY_CHKPT_START for; see notes there.)
1178  *
1179  * We save the PREPARE record's location in the gxact for later use by
1180  * CheckPointTwoPhase.
1181  */
1183 
1185 
1188 
1189  XLogBeginInsert();
1190  for (record = records.head; record != NULL; record = record->next)
1191  XLogRegisterData(record->data, record->len);
1192 
1194 
1195  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1196 
1197  if (replorigin)
1198  {
1199  /* Move LSNs forward for this replication origin */
1201  gxact->prepare_end_lsn);
1202  }
1203 
1204  XLogFlush(gxact->prepare_end_lsn);
1205 
1206  /* If we crash now, we have prepared: WAL replay will fix things */
1207 
1208  /* Store record's start location to read that later on Commit */
1210 
1211  /*
1212  * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
1213  * as not running our XID (which it will do immediately after this
1214  * function returns), others can commit/rollback the xact.
1215  *
1216  * NB: a side effect of this is to make a dummy ProcArray entry for the
1217  * prepared XID. This must happen before we clear the XID from MyProc /
1218  * ProcGlobal->xids[], else there is a window where the XID is not running
1219  * according to TransactionIdIsInProgress, and onlookers would be entitled
1220  * to assume the xact crashed. Instead we have a window where the same
1221  * XID appears twice in ProcArray, which is OK.
1222  */
1223  MarkAsPrepared(gxact, false);
1224 
1225  /*
1226  * Now we can mark ourselves as out of the commit critical section: a
1227  * checkpoint starting after this will certainly see the gxact as a
1228  * candidate for fsyncing.
1229  */
1231 
1232  /*
1233  * Remember that we have this GlobalTransaction entry locked for us. If
1234  * we crash after this point, it's too late to abort, but we must unlock
1235  * it so that the prepared transaction can be committed or rolled back.
1236  */
1237  MyLockedGxact = gxact;
1238 
1239  END_CRIT_SECTION();
1240 
1241  /*
1242  * Wait for synchronous replication, if required.
1243  *
1244  * Note that at this stage we have marked the prepare, but still show as
1245  * running in the procarray (twice!) and continue to hold locks.
1246  */
1247  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1248 
1249  records.tail = records.head = NULL;
1250  records.num_chunks = 0;
1251 }
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
Assert(fmt[strlen(fmt) - 1] !='\n')
#define MaxAllocSize
Definition: memutils.h:40
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:158
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1216
RepOriginId replorigin_session_origin
Definition: origin.c:156
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:157
#define DoNotReplicateId
Definition: origin.h:34
#define InvalidRepOriginId
Definition: origin.h:33
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define DELAY_CHKPT_START
Definition: proc.h:119
PGPROC * MyProc
Definition: proc.c:66
int delayChkptFlags
Definition: proc.h:231
struct StateFileChunk * next
Definition: twophase.c:992
uint32 len
Definition: twophase.c:991
char * data
Definition: twophase.c:990
TimestampTz origin_timestamp
Definition: xact.h:363
uint32 total_len
Definition: xact.h:349
XLogRecPtr origin_lsn
Definition: xact.h:362
uint32 magic
Definition: xact.h:348
uint32 total_len
Definition: twophase.c:1001
uint32 num_chunks
Definition: twophase.c:999
StateFileChunk * head
Definition: twophase.c:997
StateFileChunk * tail
Definition: twophase.c:998
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:149
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1257
#define TWOPHASE_MAGIC
Definition: twophase.c:966
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:548
static struct xllist records
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
#define XLOG_XACT_PREPARE
Definition: xact.h:170
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:256
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2513
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:149
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:351
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:461
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:443
void XLogBeginInsert(void)
Definition: xloginsert.c:150
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition: xloginsert.c:176

References Assert(), StateFileChunk::data, DELAY_CHKPT_START, PGPROC::delayChkptFlags, DoNotReplicateId, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xllist::head, InvalidRepOriginId, StateFileChunk::len, xl_xact_prepare::magic, MarkAsPrepared(), MaxAllocSize, MyLockedGxact, MyProc, 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, xllist::total_len, xl_xact_prepare::total_len, TWOPHASE_MAGIC, TWOPHASE_RM_END_ID, XLOG_INCLUDE_ORIGIN, XLOG_XACT_PREPARE, XLogBeginInsert(), XLogEnsureRecordSpace(), XLogFlush(), XLogInsert(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by PrepareTransaction().

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1480 of file twophase.c.

1481 {
1482  GlobalTransaction gxact;
1483  PGPROC *proc;
1484  TransactionId xid;
1485  char *buf;
1486  char *bufptr;
1487  TwoPhaseFileHeader *hdr;
1488  TransactionId latestXid;
1489  TransactionId *children;
1490  RelFileLocator *commitrels;
1491  RelFileLocator *abortrels;
1492  RelFileLocator *delrels;
1493  int ndelrels;
1494  xl_xact_stats_item *commitstats;
1495  xl_xact_stats_item *abortstats;
1496  SharedInvalidationMessage *invalmsgs;
1497 
1498  /*
1499  * Validate the GID, and lock the GXACT to ensure that two backends do not
1500  * try to commit the same GID at once.
1501  */
1502  gxact = LockGXact(gid, GetUserId());
1503  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1504  xid = gxact->xid;
1505 
1506  /*
1507  * Read and validate 2PC state data. State data will typically be stored
1508  * in WAL files if the LSN is after the last checkpoint record, or moved
1509  * to disk if for some reason they have lived for a long time.
1510  */
1511  if (gxact->ondisk)
1512  buf = ReadTwoPhaseFile(xid, false);
1513  else
1514  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1515 
1516 
1517  /*
1518  * Disassemble the header area
1519  */
1520  hdr = (TwoPhaseFileHeader *) buf;
1521  Assert(TransactionIdEquals(hdr->xid, xid));
1522  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1523  bufptr += MAXALIGN(hdr->gidlen);
1524  children = (TransactionId *) bufptr;
1525  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1526  commitrels = (RelFileLocator *) bufptr;
1527  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
1528  abortrels = (RelFileLocator *) bufptr;
1529  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
1530  commitstats = (xl_xact_stats_item *) bufptr;
1531  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
1532  abortstats = (xl_xact_stats_item *) bufptr;
1533  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
1534  invalmsgs = (SharedInvalidationMessage *) bufptr;
1535  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1536 
1537  /* compute latestXid among all children */
1538  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1539 
1540  /* Prevent cancel/die interrupt while cleaning up */
1541  HOLD_INTERRUPTS();
1542 
1543  /*
1544  * The order of operations here is critical: make the XLOG entry for
1545  * commit or abort, then mark the transaction committed or aborted in
1546  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1547  * TransactionIdIsInProgress will stop saying the prepared xact is in
1548  * progress), then run the post-commit or post-abort callbacks. The
1549  * callbacks will release the locks the transaction held.
1550  */
1551  if (isCommit)
1553  hdr->nsubxacts, children,
1554  hdr->ncommitrels, commitrels,
1555  hdr->ncommitstats,
1556  commitstats,
1557  hdr->ninvalmsgs, invalmsgs,
1558  hdr->initfileinval, gid);
1559  else
1561  hdr->nsubxacts, children,
1562  hdr->nabortrels, abortrels,
1563  hdr->nabortstats,
1564  abortstats,
1565  gid);
1566 
1567  ProcArrayRemove(proc, latestXid);
1568 
1569  /*
1570  * In case we fail while running the callbacks, mark the gxact invalid so
1571  * no one else will try to commit/rollback, and so it will be recycled if
1572  * we fail after this point. It is still locked by our backend so it
1573  * won't go away yet.
1574  *
1575  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1576  */
1577  gxact->valid = false;
1578 
1579  /*
1580  * We have to remove any files that were supposed to be dropped. For
1581  * consistency with the regular xact.c code paths, must do this before
1582  * releasing locks, so do it before running the callbacks.
1583  *
1584  * NB: this code knows that we couldn't be dropping any temp rels ...
1585  */
1586  if (isCommit)
1587  {
1588  delrels = commitrels;
1589  ndelrels = hdr->ncommitrels;
1590  }
1591  else
1592  {
1593  delrels = abortrels;
1594  ndelrels = hdr->nabortrels;
1595  }
1596 
1597  /* Make sure files supposed to be dropped are dropped */
1598  DropRelationFiles(delrels, ndelrels, false);
1599 
1600  if (isCommit)
1601  pgstat_execute_transactional_drops(hdr->ncommitstats, commitstats, false);
1602  else
1603  pgstat_execute_transactional_drops(hdr->nabortstats, abortstats, false);
1604 
1605  /*
1606  * Handle cache invalidation messages.
1607  *
1608  * Relcache init file invalidation requires processing both before and
1609  * after we send the SI messages, only when committing. See
1610  * AtEOXact_Inval().
1611  */
1612  if (isCommit)
1613  {
1614  if (hdr->initfileinval)
1616  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1617  if (hdr->initfileinval)
1619  }
1620 
1621  /*
1622  * Acquire the two-phase lock. We want to work on the two-phase callbacks
1623  * while holding it to avoid potential conflicts with other transactions
1624  * attempting to use the same GID, so the lock is released once the shared
1625  * memory state is cleared.
1626  */
1627  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1628 
1629  /* And now do the callbacks */
1630  if (isCommit)
1632  else
1634 
1635  PredicateLockTwoPhaseFinish(xid, isCommit);
1636 
1637  /* Clear shared memory state */
1638  RemoveGXact(gxact);
1639 
1640  /*
1641  * Release the lock as all callbacks are called and shared memory cleanup
1642  * is done.
1643  */
1644  LWLockRelease(TwoPhaseStateLock);
1645 
1646  /* Count the prepared xact as committed or aborted */
1647  AtEOXact_PgStat(isCommit, false);
1648 
1649  /*
1650  * And now we can clean up any files we may have left.
1651  */
1652  if (gxact->ondisk)
1653  RemoveTwoPhaseFile(xid, true);
1654 
1655  MyLockedGxact = NULL;
1656 
1658 
1659  pfree(buf);
1660 }
#define MAXALIGN(LEN)
Definition: c.h:795
uint32 TransactionId
Definition: c.h:636
void DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo)
Definition: md.c:1249
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
Oid GetUserId(void)
Definition: miscinit.c:510
void pgstat_execute_transactional_drops(int ndrops, struct xl_xact_stats_item *items, bool is_redo)
Definition: pgstat_xact.c:313
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat_xact.c:41
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:4816
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:568
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:6732
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:6707
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
PROC_HDR * ProcGlobal
Definition: proc.c:78
Definition: proc.h:162
PGPROC * allProcs
Definition: proc.h:362
int32 nabortrels
Definition: xact.h:356
int32 ninvalmsgs
Definition: xact.h:359
bool initfileinval
Definition: xact.h:360
int32 ncommitstats
Definition: xact.h:357
uint16 gidlen
Definition: xact.h:361
int32 nabortstats
Definition: xact.h:358
int32 ncommitrels
Definition: xact.h:355
TransactionId xid
Definition: xact.h:350
int32 nsubxacts
Definition: xact.h:354
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:345
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileLocator *rels, int nstats, xl_xact_stats_item *stats, const char *gid)
Definition: twophase.c:2380
static void RecordTransactionCommitPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileLocator *rels, int nstats, xl_xact_stats_item *stats, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval, const char *gid)
Definition: twophase.c:2282
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1666
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1694
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1280
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:570
const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:33
const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:42

References 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, MyLockedGxact, xl_xact_prepare::nabortrels, xl_xact_prepare::nabortstats, xl_xact_prepare::ncommitrels, xl_xact_prepare::ncommitstats, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::pgprocno, pgstat_execute_transactional_drops(), 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, xl_xact_prepare::xid, and XlogReadTwoPhaseData().

Referenced by apply_handle_commit_prepared(), apply_handle_rollback_prepared(), and standard_ProcessUtility().

◆ LookupGXact()

bool LookupGXact ( const char *  gid,
XLogRecPtr  prepare_end_lsn,
TimestampTz  origin_prepare_timestamp 
)

Definition at line 2577 of file twophase.c.

2579 {
2580  int i;
2581  bool found = false;
2582 
2583  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
2584  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2585  {
2587 
2588  /* Ignore not-yet-valid GIDs. */
2589  if (gxact->valid && strcmp(gxact->gid, gid) == 0)
2590  {
2591  char *buf;
2592  TwoPhaseFileHeader *hdr;
2593 
2594  /*
2595  * We are not expecting collisions of GXACTs (same gid) between
2596  * publisher and subscribers, so we perform all I/O while holding
2597  * TwoPhaseStateLock for simplicity.
2598  *
2599  * To move the I/O out of the lock, we need to ensure that no
2600  * other backend commits the prepared xact in the meantime. We can
2601  * do this optimization if we encounter many collisions in GID
2602  * between publisher and subscriber.
2603  */
2604  if (gxact->ondisk)
2605  buf = ReadTwoPhaseFile(gxact->xid, false);
2606  else
2607  {
2608  Assert(gxact->prepare_start_lsn);
2609  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
2610  }
2611 
2612  hdr = (TwoPhaseFileHeader *) buf;
2613 
2614  if (hdr->origin_lsn == prepare_end_lsn &&
2615  hdr->origin_timestamp == origin_prepare_timestamp)
2616  {
2617  found = true;
2618  pfree(buf);
2619  break;
2620  }
2621 
2622  pfree(buf);
2623  }
2624  }
2625  LWLockRelease(TwoPhaseStateLock);
2626  return found;
2627 }
char gid[GIDSIZE]
Definition: twophase.c:172

References Assert(), buf, GlobalTransactionData::gid, i, LW_SHARED, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, xl_xact_prepare::origin_lsn, xl_xact_prepare::origin_timestamp, pfree(), GlobalTransactionData::prepare_start_lsn, TwoPhaseStateData::prepXacts, ReadTwoPhaseFile(), TwoPhaseState, GlobalTransactionData::valid, GlobalTransactionData::xid, and XlogReadTwoPhaseData().

Referenced by apply_handle_rollback_prepared().

◆ MarkAsPreparing()

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

Definition at line 376 of file twophase.c.

378 {
379  GlobalTransaction gxact;
380  int i;
381 
382  if (strlen(gid) >= GIDSIZE)
383  ereport(ERROR,
384  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
385  errmsg("transaction identifier \"%s\" is too long",
386  gid)));
387 
388  /* fail immediately if feature is disabled */
389  if (max_prepared_xacts == 0)
390  ereport(ERROR,
391  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
392  errmsg("prepared transactions are disabled"),
393  errhint("Set max_prepared_transactions to a nonzero value.")));
394 
395  /* on first call, register the exit hook */
397  {
399  twophaseExitRegistered = true;
400  }
401 
402  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
403 
404  /* Check for conflicting GID */
405  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
406  {
407  gxact = TwoPhaseState->prepXacts[i];
408  if (strcmp(gxact->gid, gid) == 0)
409  {
410  ereport(ERROR,
412  errmsg("transaction identifier \"%s\" is already in use",
413  gid)));
414  }
415  }
416 
417  /* Get a free gxact from the freelist */
418  if (TwoPhaseState->freeGXacts == NULL)
419  ereport(ERROR,
420  (errcode(ERRCODE_OUT_OF_MEMORY),
421  errmsg("maximum number of prepared transactions reached"),
422  errhint("Increase max_prepared_transactions (currently %d).",
424  gxact = TwoPhaseState->freeGXacts;
425  TwoPhaseState->freeGXacts = gxact->next;
426 
427  MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
428 
429  gxact->ondisk = false;
430 
431  /* And insert it into the active array */
434 
435  LWLockRelease(TwoPhaseStateLock);
436 
437  return gxact;
438 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
GlobalTransaction next
Definition: twophase.c:151
GlobalTransaction freeGXacts
Definition: twophase.c:182
static bool twophaseExitRegistered
Definition: twophase.c:201
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:450
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:311
#define GIDSIZE
Definition: xact.h:31

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, twophaseExitRegistered, and TwoPhaseState.

Referenced by PrepareTransaction().

◆ PostPrepare_Twophase()

void PostPrepare_Twophase ( void  )

Definition at line 361 of file twophase.c.

362 {
363  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
365  LWLockRelease(TwoPhaseStateLock);
366 
367  MyLockedGxact = NULL;
368 }

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

◆ PrepareRedoAdd()

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

Definition at line 2455 of file twophase.c.

2457 {
2459  char *bufptr;
2460  const char *gid;
2461  GlobalTransaction gxact;
2462 
2463  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2465 
2466  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2467  gid = (const char *) bufptr;
2468 
2469  /*
2470  * Reserve the GID for the given transaction in the redo code path.
2471  *
2472  * This creates a gxact struct and puts it into the active array.
2473  *
2474  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2475  * shared memory. Hence, we only fill up the bare minimum contents here.
2476  * The gxact also gets marked with gxact->inredo set to true to indicate
2477  * that it got added in the redo phase
2478  */
2479 
2480  /* Get a free gxact from the freelist */
2481  if (TwoPhaseState->freeGXacts == NULL)
2482  ereport(ERROR,
2483  (errcode(ERRCODE_OUT_OF_MEMORY),
2484  errmsg("maximum number of prepared transactions reached"),
2485  errhint("Increase max_prepared_transactions (currently %d).",
2486  max_prepared_xacts)));
2487  gxact = TwoPhaseState->freeGXacts;
2488  TwoPhaseState->freeGXacts = gxact->next;
2489 
2490  gxact->prepared_at = hdr->prepared_at;
2491  gxact->prepare_start_lsn = start_lsn;
2492  gxact->prepare_end_lsn = end_lsn;
2493  gxact->xid = hdr->xid;
2494  gxact->owner = hdr->owner;
2496  gxact->valid = false;
2497  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2498  gxact->inredo = true; /* yes, added in redo */
2499  strcpy(gxact->gid, gid);
2500 
2501  /* And insert it into the active array */
2504 
2505  if (origin_id != InvalidRepOriginId)
2506  {
2507  /* recover apply progress */
2508  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2509  false /* backward */ , false /* WAL */ );
2510  }
2511 
2512  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2513 }
#define DEBUG2
Definition: elog.h:29
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1963
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:888
TimestampTz prepared_at
Definition: twophase.c:154
TimestampTz prepared_at
Definition: xact.h:352
bool RecoveryInProgress(void)
Definition: xlog.c:5921
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29

References Assert(), buf, 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(), TwoPhaseState, GlobalTransactionData::valid, GlobalTransactionData::xid, xl_xact_prepare::xid, and XLogRecPtrIsInvalid.

Referenced by restoreTwoPhaseData(), and xact_redo().

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2525 of file twophase.c.

2526 {
2527  GlobalTransaction gxact = NULL;
2528  int i;
2529  bool found = false;
2530 
2531  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2533 
2534  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2535  {
2536  gxact = TwoPhaseState->prepXacts[i];
2537 
2538  if (gxact->xid == xid)
2539  {
2540  Assert(gxact->inredo);
2541  found = true;
2542  break;
2543  }
2544  }
2545 
2546  /*
2547  * Just leave if there is nothing, this is expected during WAL replay.
2548  */
2549  if (!found)
2550  return;
2551 
2552  /*
2553  * And now we can clean up any files we may have left.
2554  */
2555  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2556  if (gxact->ondisk)
2557  RemoveTwoPhaseFile(xid, giveWarning);
2558  RemoveGXact(gxact);
2559 }

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

Referenced by ProcessTwoPhaseBuffer(), and xact_redo().

◆ PrescanPreparedTransactions()

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

Definition at line 1937 of file twophase.c.

1938 {
1940  TransactionId origNextXid = XidFromFullTransactionId(nextXid);
1941  TransactionId result = origNextXid;
1942  TransactionId *xids = NULL;
1943  int nxids = 0;
1944  int allocsize = 0;
1945  int i;
1946 
1947  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1948  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1949  {
1950  TransactionId xid;
1951  char *buf;
1953 
1954  Assert(gxact->inredo);
1955 
1956  xid = gxact->xid;
1957 
1958  buf = ProcessTwoPhaseBuffer(xid,
1959  gxact->prepare_start_lsn,
1960  gxact->ondisk, false, true);
1961 
1962  if (buf == NULL)
1963  continue;
1964 
1965  /*
1966  * OK, we think this file is valid. Incorporate xid into the
1967  * running-minimum result.
1968  */
1969  if (TransactionIdPrecedes(xid, result))
1970  result = xid;
1971 
1972  if (xids_p)
1973  {
1974  if (nxids == allocsize)
1975  {
1976  if (nxids == 0)
1977  {
1978  allocsize = 10;
1979  xids = palloc(allocsize * sizeof(TransactionId));
1980  }
1981  else
1982  {
1983  allocsize = allocsize * 2;
1984  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1985  }
1986  }
1987  xids[nxids++] = xid;
1988  }
1989 
1990  pfree(buf);
1991  }
1992  LWLockRelease(TwoPhaseStateLock);
1993 
1994  if (xids_p)
1995  {
1996  *xids_p = xids;
1997  *nxids_p = nxids;
1998  }
1999 
2000  return result;
2001 }
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1476
void * palloc(Size size)
Definition: mcxt.c:1226
FullTransactionId nextXid
Definition: transam.h:220
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define XidFromFullTransactionId(x)
Definition: transam.h:48
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2162
VariableCache ShmemVariableCache
Definition: varsup.c:34

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(), TwoPhaseState, GlobalTransactionData::xid, and XidFromFullTransactionId.

Referenced by StartupXLOG(), and xlog_redo().

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 2059 of file twophase.c.

2060 {
2061  int i;
2062 
2063  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2064  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2065  {
2066  TransactionId xid;
2067  char *buf;
2069  char *bufptr;
2070  TwoPhaseFileHeader *hdr;
2071  TransactionId *subxids;
2072  const char *gid;
2073 
2074  xid = gxact->xid;
2075 
2076  /*
2077  * Reconstruct subtrans state for the transaction --- needed because
2078  * pg_subtrans is not preserved over a restart. Note that we are
2079  * linking all the subtransactions directly to the top-level XID;
2080  * there may originally have been a more complex hierarchy, but
2081  * there's no need to restore that exactly. It's possible that
2082  * SubTransSetParent has been set before, if the prepared transaction
2083  * generated xid assignment records.
2084  */
2085  buf = ProcessTwoPhaseBuffer(xid,
2086  gxact->prepare_start_lsn,
2087  gxact->ondisk, true, false);
2088  if (buf == NULL)
2089  continue;
2090 
2091  ereport(LOG,
2092  (errmsg("recovering prepared transaction %u from shared memory", xid)));
2093 
2094  hdr = (TwoPhaseFileHeader *) buf;
2095  Assert(TransactionIdEquals(hdr->xid, xid));
2096  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2097  gid = (const char *) bufptr;
2098  bufptr += MAXALIGN(hdr->gidlen);
2099  subxids = (TransactionId *) bufptr;
2100  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
2101  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
2102  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
2103  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
2104  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
2105  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
2106 
2107  /*
2108  * Recreate its GXACT and dummy PGPROC. But, check whether it was
2109  * added in redo and already has a shmem entry for it.
2110  */
2111  MarkAsPreparingGuts(gxact, xid, gid,
2112  hdr->prepared_at,
2113  hdr->owner, hdr->database);
2114 
2115  /* recovered, so reset the flag for entries generated by redo */
2116  gxact->inredo = false;
2117 
2118  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
2119  MarkAsPrepared(gxact, true);
2120 
2121  LWLockRelease(TwoPhaseStateLock);
2122 
2123  /*
2124  * Recover other state (notably locks) using resource managers.
2125  */
2127 
2128  /*
2129  * Release locks held by the standby process after we process each
2130  * prepared transaction. As a result, we don't need too many
2131  * additional locks at any one time.
2132  */
2133  if (InHotStandby)
2134  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2135 
2136  /*
2137  * We're done with recovering this transaction. Clear MyLockedGxact,
2138  * like we do in PrepareTransaction() during normal operation.
2139  */
2141 
2142  pfree(buf);
2143 
2144  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2145  }
2146 
2147  LWLockRelease(TwoPhaseStateLock);
2148 }
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:1093
Oid database
Definition: xact.h:351
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:522
void PostPrepare_Twophase(void)
Definition: twophase.c:361
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlogutils.h:57

References Assert(), buf, xl_xact_prepare::database, ereport, errmsg(), xl_xact_prepare::gidlen, GXactLoadSubxactData(), i, InHotStandby, GlobalTransactionData::inredo, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MarkAsPrepared(), MarkAsPreparingGuts(), MAXALIGN, xl_xact_prepare::nabortrels, xl_xact_prepare::nabortstats, xl_xact_prepare::ncommitrels, xl_xact_prepare::ncommitstats, 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, TwoPhaseState, GlobalTransactionData::xid, and xl_xact_prepare::xid.

Referenced by StartupXLOG().

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1875 of file twophase.c.

1876 {
1877  DIR *cldir;
1878  struct dirent *clde;
1879 
1880  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1881  cldir = AllocateDir(TWOPHASE_DIR);
1882  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1883  {
1884  if (strlen(clde->d_name) == 8 &&
1885  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1886  {
1887  TransactionId xid;
1888  char *buf;
1889 
1890  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1891 
1893  true, false, false);
1894  if (buf == NULL)
1895  continue;
1896 
1899  }
1900  }
1901  LWLockRelease(TwoPhaseStateLock);
1902  FreeDir(cldir);
1903 }
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2806
int FreeDir(DIR *dir)
Definition: fd.c:2858
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2740
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2455

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

Referenced by StartupXLOG().

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 2018 of file twophase.c.

2019 {
2020  int i;
2021 
2022  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2023  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2024  {
2025  TransactionId xid;
2026  char *buf;
2028 
2029  Assert(gxact->inredo);
2030 
2031  xid = gxact->xid;
2032 
2033  buf = ProcessTwoPhaseBuffer(xid,
2034  gxact->prepare_start_lsn,
2035  gxact->ondisk, false, false);
2036  if (buf != NULL)
2037  pfree(buf);
2038  }
2039  LWLockRelease(TwoPhaseStateLock);
2040 }

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

Referenced by StartupXLOG(), and xlog_redo().

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1452 of file twophase.c.

1453 {
1454  char *buf;
1455  TwoPhaseFileHeader *hdr;
1456  bool result;
1457 
1459 
1460  if (max_prepared_xacts <= 0)
1461  return false; /* nothing to do */
1462 
1463  /* Read and validate file */
1464  buf = ReadTwoPhaseFile(xid, true);
1465  if (buf == NULL)
1466  return false;
1467 
1468  /* Check header also */
1469  hdr = (TwoPhaseFileHeader *) buf;
1470  result = TransactionIdEquals(hdr->xid, xid);
1471  pfree(buf);
1472 
1473  return result;
1474 }
#define TransactionIdIsValid(xid)
Definition: transam.h:41

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 1042 of file twophase.c.

1043 {
1044  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
1045  TransactionId xid = gxact->xid;
1046  TwoPhaseFileHeader hdr;
1047  TransactionId *children;
1048  RelFileLocator *commitrels;
1049  RelFileLocator *abortrels;
1050  xl_xact_stats_item *abortstats = NULL;
1051  xl_xact_stats_item *commitstats = NULL;
1052  SharedInvalidationMessage *invalmsgs;
1053 
1054  /* Initialize linked list */
1055  records.head = palloc0(sizeof(StateFileChunk));
1056  records.head->len = 0;
1057  records.head->next = NULL;
1058 
1059  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1061 
1063  records.num_chunks = 1;
1064 
1065  records.total_len = 0;
1066 
1067  /* Create header */
1068  hdr.magic = TWOPHASE_MAGIC;
1069  hdr.total_len = 0; /* EndPrepare will fill this in */
1070  hdr.xid = xid;
1071  hdr.database = proc->databaseId;
1072  hdr.prepared_at = gxact->prepared_at;
1073  hdr.owner = gxact->owner;
1074  hdr.nsubxacts = xactGetCommittedChildren(&children);
1075  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1076  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1077  hdr.ncommitstats =
1078  pgstat_get_transactional_drops(true, &commitstats);
1079  hdr.nabortstats =
1080  pgstat_get_transactional_drops(false, &abortstats);
1082  &hdr.initfileinval);
1083  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1084  /* EndPrepare will fill the origin data, if necessary */
1086  hdr.origin_timestamp = 0;
1087 
1088  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1089  save_state_data(gxact->gid, hdr.gidlen);
1090 
1091  /*
1092  * Add the additional info about subxacts, deletable files and cache
1093  * invalidation messages.
1094  */
1095  if (hdr.nsubxacts > 0)
1096  {
1097  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1098  /* While we have the child-xact data, stuff it in the gxact too */
1099  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1100  }
1101  if (hdr.ncommitrels > 0)
1102  {
1103  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileLocator));
1104  pfree(commitrels);
1105  }
1106  if (hdr.nabortrels > 0)
1107  {
1108  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileLocator));
1109  pfree(abortrels);
1110  }
1111  if (hdr.ncommitstats > 0)
1112  {
1113  save_state_data(commitstats,
1114  hdr.ncommitstats * sizeof(xl_xact_stats_item));
1115  pfree(commitstats);
1116  }
1117  if (hdr.nabortstats > 0)
1118  {
1119  save_state_data(abortstats,
1120  hdr.nabortstats * sizeof(xl_xact_stats_item));
1121  pfree(abortstats);
1122  }
1123  if (hdr.ninvalmsgs > 0)
1124  {
1125  save_state_data(invalmsgs,
1126  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1127  pfree(invalmsgs);
1128  }
1129 }
#define Max(x, y)
Definition: c.h:982
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:884
void * palloc0(Size size)
Definition: mcxt.c:1257
int pgstat_get_transactional_drops(bool isCommit, xl_xact_stats_item **items)
Definition: pgstat_xact.c:271
int smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
Definition: storage.c:870
Oid databaseId
Definition: proc.h:198
uint32 bytes_free
Definition: twophase.c:1000
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:1014
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5611

References 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, InvalidXLogRecPtr, StateFileChunk::len, xl_xact_prepare::magic, Max, xl_xact_prepare::nabortrels, xl_xact_prepare::nabortstats, xl_xact_prepare::ncommitrels, xl_xact_prepare::ncommitstats, StateFileChunk::next, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, xllist::num_chunks, xl_xact_prepare::origin_lsn, xl_xact_prepare::origin_timestamp, GlobalTransactionData::owner, xl_xact_prepare::owner, palloc(), palloc0(), pfree(), GlobalTransactionData::pgprocno, pgstat_get_transactional_drops(), GlobalTransactionData::prepared_at, xl_xact_prepare::prepared_at, ProcGlobal, records, save_state_data(), smgrGetPendingDeletes(), xllist::tail, xllist::total_len, xl_xact_prepare::total_len, TWOPHASE_MAGIC, xactGetCommittedChildren(), xactGetCommittedInvalidationMessages(), GlobalTransactionData::xid, and xl_xact_prepare::xid.

Referenced by PrepareTransaction().

◆ TwoPhaseGetDummyBackendId()

BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid,
bool  lock_held 
)

Definition at line 918 of file twophase.c.

919 {
920  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
921 
922  return gxact->dummyBackendId;
923 }
BackendId dummyBackendId
Definition: twophase.c:153
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:818

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid,
bool  lock_held 
)

Definition at line 933 of file twophase.c.

934 {
935  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
936 
937  return &ProcGlobal->allProcs[gxact->pgprocno];
938 }

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

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

◆ TwoPhaseGetXidByVirtualXID()

TransactionId TwoPhaseGetXidByVirtualXID ( VirtualTransactionId  vxid,
bool have_more 
)

Definition at line 870 of file twophase.c.

872 {
873  int i;
875 
877  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
878 
879  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
880  {
882  PGPROC *proc;
883  VirtualTransactionId proc_vxid;
884 
885  if (!gxact->valid)
886  continue;
887  proc = &ProcGlobal->allProcs[gxact->pgprocno];
888  GET_VXID_FROM_PGPROC(proc_vxid, *proc);
889  if (VirtualTransactionIdEquals(vxid, proc_vxid))
890  {
891  /* Startup process sets proc->backendId to InvalidBackendId. */
892  Assert(!gxact->inredo);
893 
894  if (result != InvalidTransactionId)
895  {
896  *have_more = true;
897  break;
898  }
899  result = gxact->xid;
900  }
901  }
902 
903  LWLockRelease(TwoPhaseStateLock);
904 
905  return result;
906 }
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:67
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:71
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:77
#define InvalidTransactionId
Definition: transam.h:31

References PROC_HDR::allProcs, Assert(), GET_VXID_FROM_PGPROC, i, GlobalTransactionData::inredo, InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, GlobalTransactionData::pgprocno, TwoPhaseStateData::prepXacts, ProcGlobal, TwoPhaseState, GlobalTransactionData::valid, VirtualTransactionIdEquals, VirtualTransactionIdIsValid, and GlobalTransactionData::xid.

Referenced by XactLockForVirtualXact().

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 256 of file twophase.c.

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

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

Referenced by CreateSharedMemoryAndSemaphores().

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 240 of file twophase.c.

241 {
242  Size size;
243 
244  /* Need the fixed struct, the array of pointers, and the GTD structs */
245  size = offsetof(TwoPhaseStateData, prepXacts);
246  size = add_size(size, mul_size(max_prepared_xacts,
247  sizeof(GlobalTransaction)));
248  size = MAXALIGN(size);
249  size = add_size(size, mul_size(max_prepared_xacts,
250  sizeof(GlobalTransactionData)));
251 
252  return size;
253 }
size_t Size
Definition: c.h:589
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

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

Referenced by CalculateShmemSize(), and TwoPhaseShmemInit().

Variable Documentation

◆ max_prepared_xacts