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_at_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:1196
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1800
@ LW_EXCLUSIVE
Definition: lwlock.h:104
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 1795 of file twophase.c.

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

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

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

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

Definition at line 2579 of file twophase.c.

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

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

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

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

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

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

1878 {
1879  DIR *cldir;
1880  struct dirent *clde;
1881 
1882  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1883  cldir = AllocateDir(TWOPHASE_DIR);
1884  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1885  {
1886  if (strlen(clde->d_name) == 8 &&
1887  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1888  {
1889  TransactionId xid;
1890  char *buf;
1891 
1892  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1893 
1895  true, false, false);
1896  if (buf == NULL)
1897  continue;
1898 
1901  }
1902  }
1903  LWLockRelease(TwoPhaseStateLock);
1904  FreeDir(cldir);
1905 }
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2788
int FreeDir(DIR *dir)
Definition: fd.c:2840
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2722
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:2457

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

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

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

1455 {
1456  char *buf;
1457  TwoPhaseFileHeader *hdr;
1458  bool result;
1459 
1461 
1462  if (max_prepared_xacts <= 0)
1463  return false; /* nothing to do */
1464 
1465  /* Read and validate file */
1466  buf = ReadTwoPhaseFile(xid, true);
1467  if (buf == NULL)
1468  return false;
1469 
1470  /* Check header also */
1471  hdr = (TwoPhaseFileHeader *) buf;
1472  result = TransactionIdEquals(hdr->xid, xid);
1473  pfree(buf);
1474 
1475  return result;
1476 }
#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 1044 of file twophase.c.

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

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

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

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

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

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

874 {
875  int i;
877 
879  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
880 
881  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
882  {
884  PGPROC *proc;
885  VirtualTransactionId proc_vxid;
886 
887  if (!gxact->valid)
888  continue;
889  proc = &ProcGlobal->allProcs[gxact->pgprocno];
890  GET_VXID_FROM_PGPROC(proc_vxid, *proc);
891  if (VirtualTransactionIdEquals(vxid, proc_vxid))
892  {
893  /* Startup process sets proc->backendId to InvalidBackendId. */
894  Assert(!gxact->inredo);
895 
896  if (result != InvalidTransactionId)
897  {
898  *have_more = true;
899  break;
900  }
901  result = gxact->xid;
902  }
903  }
904 
905  LWLockRelease(TwoPhaseStateLock);
906 
907  return result;
908 }
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:72
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:76
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:82
#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 }
#define offsetof(type, field)
Definition: c.h:727
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:82
int pgprocno
Definition: proc.h:188
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, offsetof, 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:540
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, mul_size(), and offsetof.

Referenced by CalculateShmemSize(), and TwoPhaseShmemInit().

Variable Documentation

◆ max_prepared_xacts