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)
 
int TwoPhaseGetDummyProcNumber (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 304 of file twophase.c.

305 {
306  if (MyLockedGxact == NULL)
307  return;
308 
309  /*
310  * What to do with the locked global transaction entry? If we were in the
311  * process of preparing the transaction, but haven't written the WAL
312  * record and state file yet, the transaction must not be considered as
313  * prepared. Likewise, if we are in the process of finishing an
314  * already-prepared transaction, and fail after having already written the
315  * 2nd phase commit or rollback record to the WAL, the transaction should
316  * not be considered as prepared anymore. In those cases, just remove the
317  * entry from shared memory.
318  *
319  * Otherwise, the entry must be left in place so that the transaction can
320  * be finished later, so just unlock it.
321  *
322  * If we abort during prepare, after having written the WAL record, we
323  * might not have transferred all locks and other state to the prepared
324  * transaction yet. Likewise, if we abort during commit or rollback,
325  * after having written the WAL record, we might not have released all the
326  * resources held by the transaction yet. In those cases, the in-memory
327  * state can be wrong, but it's too late to back out.
328  */
329  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
330  if (!MyLockedGxact->valid)
332  else
334  LWLockRelease(TwoPhaseStateLock);
335 
336  MyLockedGxact = NULL;
337 }
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1170
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783
@ LW_EXCLUSIVE
Definition: lwlock.h:114
#define INVALID_PROC_NUMBER
Definition: procnumber.h:26
ProcNumber locking_backend
Definition: twophase.c:165
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:628
static GlobalTransaction MyLockedGxact
Definition: twophase.c:196

References INVALID_PROC_NUMBER, 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 1816 of file twophase.c.

1817 {
1818  int i;
1819  int serialized_xacts = 0;
1820 
1821  if (max_prepared_xacts <= 0)
1822  return; /* nothing to do */
1823 
1824  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1825 
1826  /*
1827  * We are expecting there to be zero GXACTs that need to be copied to
1828  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1829  * simplicity. This prevents any new xacts from preparing while this
1830  * occurs, which shouldn't be a problem since the presence of long-lived
1831  * prepared xacts indicates the transaction manager isn't active.
1832  *
1833  * It's also possible to move I/O out of the lock, but on every error we
1834  * should check whether somebody committed our transaction in different
1835  * backend. Let's leave this optimization for future, if somebody will
1836  * spot that this place cause bottleneck.
1837  *
1838  * Note that it isn't possible for there to be a GXACT with a
1839  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1840  * because of the efforts with delayChkptFlags.
1841  */
1842  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1843  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1844  {
1845  /*
1846  * Note that we are using gxact not PGPROC so this works in recovery
1847  * also
1848  */
1850 
1851  if ((gxact->valid || gxact->inredo) &&
1852  !gxact->ondisk &&
1853  gxact->prepare_end_lsn <= redo_horizon)
1854  {
1855  char *buf;
1856  int len;
1857 
1859  RecreateTwoPhaseFile(gxact->xid, buf, len);
1860  gxact->ondisk = true;
1863  pfree(buf);
1864  serialized_xacts++;
1865  }
1866  }
1867  LWLockRelease(TwoPhaseStateLock);
1868 
1869  /*
1870  * Flush unconditionally the parent directory to make any information
1871  * durable on disk. Two-phase files could have been removed and those
1872  * removals need to be made persistent as well as any files newly created
1873  * previously since the last checkpoint.
1874  */
1875  fsync_fname(TWOPHASE_DIR, true);
1876 
1877  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1878 
1879  if (log_checkpoints && serialized_xacts > 0)
1880  ereport(LOG,
1881  (errmsg_plural("%u two-phase state file was written "
1882  "for a long-running prepared transaction",
1883  "%u two-phase state files were written "
1884  "for long-running prepared transactions",
1885  serialized_xacts,
1886  serialized_xacts)));
1887 }
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1182
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:756
int i
Definition: isn.c:73
@ LW_SHARED
Definition: lwlock.h:115
void pfree(void *pointer)
Definition: mcxt.c:1520
const void size_t len
static char * buf
Definition: pg_test_fsync.c:73
TransactionId xid
Definition: twophase.c:162
XLogRecPtr prepare_start_lsn
Definition: twophase.c:160
XLogRecPtr prepare_end_lsn
Definition: twophase.c:161
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:185
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1420
#define TWOPHASE_DIR
Definition: twophase.c:112
int max_prepared_xacts
Definition: twophase.c:115
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:188
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1736
bool log_checkpoints
Definition: xlog.c:129
#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 1158 of file twophase.c.

1159 {
1160  TwoPhaseFileHeader *hdr;
1161  StateFileChunk *record;
1162  bool replorigin;
1163 
1164  /* Add the end sentinel to the list of 2PC records */
1166  NULL, 0);
1167 
1168  /* Go back and fill in total_len in the file header record */
1169  hdr = (TwoPhaseFileHeader *) records.head->data;
1170  Assert(hdr->magic == TWOPHASE_MAGIC);
1171  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1172 
1173  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1175 
1176  if (replorigin)
1177  {
1180  }
1181 
1182  /*
1183  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1184  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1185  * where we write data to file and then re-read at commit time.
1186  */
1187  if (hdr->total_len > MaxAllocSize)
1188  ereport(ERROR,
1189  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1190  errmsg("two-phase state file maximum length exceeded")));
1191 
1192  /*
1193  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1194  * cover us, so no need to calculate a separate CRC.
1195  *
1196  * We have to set DELAY_CHKPT_START here, too; otherwise a checkpoint
1197  * starting immediately after the WAL record is inserted could complete
1198  * without fsync'ing our state file. (This is essentially the same kind
1199  * of race condition as the COMMIT-to-clog-write case that
1200  * RecordTransactionCommit uses DELAY_CHKPT_START for; see notes there.)
1201  *
1202  * We save the PREPARE record's location in the gxact for later use by
1203  * CheckPointTwoPhase.
1204  */
1206 
1208 
1211 
1212  XLogBeginInsert();
1213  for (record = records.head; record != NULL; record = record->next)
1214  XLogRegisterData(record->data, record->len);
1215 
1217 
1218  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1219 
1220  if (replorigin)
1221  {
1222  /* Move LSNs forward for this replication origin */
1224  gxact->prepare_end_lsn);
1225  }
1226 
1227  XLogFlush(gxact->prepare_end_lsn);
1228 
1229  /* If we crash now, we have prepared: WAL replay will fix things */
1230 
1231  /* Store record's start location to read that later on Commit */
1233 
1234  /*
1235  * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
1236  * as not running our XID (which it will do immediately after this
1237  * function returns), others can commit/rollback the xact.
1238  *
1239  * NB: a side effect of this is to make a dummy ProcArray entry for the
1240  * prepared XID. This must happen before we clear the XID from MyProc /
1241  * ProcGlobal->xids[], else there is a window where the XID is not running
1242  * according to TransactionIdIsInProgress, and onlookers would be entitled
1243  * to assume the xact crashed. Instead we have a window where the same
1244  * XID appears twice in ProcArray, which is OK.
1245  */
1246  MarkAsPrepared(gxact, false);
1247 
1248  /*
1249  * Now we can mark ourselves as out of the commit critical section: a
1250  * checkpoint starting after this will certainly see the gxact as a
1251  * candidate for fsyncing.
1252  */
1254 
1255  /*
1256  * Remember that we have this GlobalTransaction entry locked for us. If
1257  * we crash after this point, it's too late to abort, but we must unlock
1258  * it so that the prepared transaction can be committed or rolled back.
1259  */
1260  MyLockedGxact = gxact;
1261 
1262  END_CRIT_SECTION();
1263 
1264  /*
1265  * Wait for synchronous replication, if required.
1266  *
1267  * Note that at this stage we have marked the prepare, but still show as
1268  * running in the procarray (twice!) and continue to hold locks.
1269  */
1270  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1271 
1272  records.tail = records.head = NULL;
1273  records.num_chunks = 0;
1274 }
#define Assert(condition)
Definition: c.h:858
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ERROR
Definition: elog.h:39
#define MaxAllocSize
Definition: memutils.h:40
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:157
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1219
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:114
PGPROC * MyProc
Definition: proc.c:66
int delayChkptFlags
Definition: proc.h:236
struct StateFileChunk * next
Definition: twophase.c:1015
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:1024
uint32 num_chunks
Definition: twophase.c:1022
StateFileChunk * head
Definition: twophase.c:1020
StateFileChunk * tail
Definition: twophase.c:1021
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:148
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1280
#define TWOPHASE_MAGIC
Definition: twophase.c:989
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:530
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:253
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2791
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:152
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:364
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:456
void XLogBeginInsert(void)
Definition: xloginsert.c:149
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition: xloginsert.c:175

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

1504 {
1505  GlobalTransaction gxact;
1506  PGPROC *proc;
1507  TransactionId xid;
1508  char *buf;
1509  char *bufptr;
1510  TwoPhaseFileHeader *hdr;
1511  TransactionId latestXid;
1512  TransactionId *children;
1513  RelFileLocator *commitrels;
1514  RelFileLocator *abortrels;
1515  RelFileLocator *delrels;
1516  int ndelrels;
1517  xl_xact_stats_item *commitstats;
1518  xl_xact_stats_item *abortstats;
1519  SharedInvalidationMessage *invalmsgs;
1520 
1521  /*
1522  * Validate the GID, and lock the GXACT to ensure that two backends do not
1523  * try to commit the same GID at once.
1524  */
1525  gxact = LockGXact(gid, GetUserId());
1526  proc = GetPGProcByNumber(gxact->pgprocno);
1527  xid = gxact->xid;
1528 
1529  /*
1530  * Read and validate 2PC state data. State data will typically be stored
1531  * in WAL files if the LSN is after the last checkpoint record, or moved
1532  * to disk if for some reason they have lived for a long time.
1533  */
1534  if (gxact->ondisk)
1535  buf = ReadTwoPhaseFile(xid, false);
1536  else
1537  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1538 
1539 
1540  /*
1541  * Disassemble the header area
1542  */
1543  hdr = (TwoPhaseFileHeader *) buf;
1544  Assert(TransactionIdEquals(hdr->xid, xid));
1545  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1546  bufptr += MAXALIGN(hdr->gidlen);
1547  children = (TransactionId *) bufptr;
1548  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1549  commitrels = (RelFileLocator *) bufptr;
1550  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
1551  abortrels = (RelFileLocator *) bufptr;
1552  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
1553  commitstats = (xl_xact_stats_item *) bufptr;
1554  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
1555  abortstats = (xl_xact_stats_item *) bufptr;
1556  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
1557  invalmsgs = (SharedInvalidationMessage *) bufptr;
1558  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1559 
1560  /* compute latestXid among all children */
1561  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1562 
1563  /* Prevent cancel/die interrupt while cleaning up */
1564  HOLD_INTERRUPTS();
1565 
1566  /*
1567  * The order of operations here is critical: make the XLOG entry for
1568  * commit or abort, then mark the transaction committed or aborted in
1569  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1570  * TransactionIdIsInProgress will stop saying the prepared xact is in
1571  * progress), then run the post-commit or post-abort callbacks. The
1572  * callbacks will release the locks the transaction held.
1573  */
1574  if (isCommit)
1576  hdr->nsubxacts, children,
1577  hdr->ncommitrels, commitrels,
1578  hdr->ncommitstats,
1579  commitstats,
1580  hdr->ninvalmsgs, invalmsgs,
1581  hdr->initfileinval, gid);
1582  else
1584  hdr->nsubxacts, children,
1585  hdr->nabortrels, abortrels,
1586  hdr->nabortstats,
1587  abortstats,
1588  gid);
1589 
1590  ProcArrayRemove(proc, latestXid);
1591 
1592  /*
1593  * In case we fail while running the callbacks, mark the gxact invalid so
1594  * no one else will try to commit/rollback, and so it will be recycled if
1595  * we fail after this point. It is still locked by our backend so it
1596  * won't go away yet.
1597  *
1598  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1599  */
1600  gxact->valid = false;
1601 
1602  /*
1603  * We have to remove any files that were supposed to be dropped. For
1604  * consistency with the regular xact.c code paths, must do this before
1605  * releasing locks, so do it before running the callbacks.
1606  *
1607  * NB: this code knows that we couldn't be dropping any temp rels ...
1608  */
1609  if (isCommit)
1610  {
1611  delrels = commitrels;
1612  ndelrels = hdr->ncommitrels;
1613  }
1614  else
1615  {
1616  delrels = abortrels;
1617  ndelrels = hdr->nabortrels;
1618  }
1619 
1620  /* Make sure files supposed to be dropped are dropped */
1621  DropRelationFiles(delrels, ndelrels, false);
1622 
1623  if (isCommit)
1624  pgstat_execute_transactional_drops(hdr->ncommitstats, commitstats, false);
1625  else
1626  pgstat_execute_transactional_drops(hdr->nabortstats, abortstats, false);
1627 
1628  /*
1629  * Handle cache invalidation messages.
1630  *
1631  * Relcache init file invalidation requires processing both before and
1632  * after we send the SI messages, only when committing. See
1633  * AtEOXact_Inval().
1634  */
1635  if (isCommit)
1636  {
1637  if (hdr->initfileinval)
1639  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1640  if (hdr->initfileinval)
1642  }
1643 
1644  /*
1645  * Acquire the two-phase lock. We want to work on the two-phase callbacks
1646  * while holding it to avoid potential conflicts with other transactions
1647  * attempting to use the same GID, so the lock is released once the shared
1648  * memory state is cleared.
1649  */
1650  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1651 
1652  /* And now do the callbacks */
1653  if (isCommit)
1655  else
1657 
1658  PredicateLockTwoPhaseFinish(xid, isCommit);
1659 
1660  /* Clear shared memory state */
1661  RemoveGXact(gxact);
1662 
1663  /*
1664  * Release the lock as all callbacks are called and shared memory cleanup
1665  * is done.
1666  */
1667  LWLockRelease(TwoPhaseStateLock);
1668 
1669  /* Count the prepared xact as committed or aborted */
1670  AtEOXact_PgStat(isCommit, false);
1671 
1672  /*
1673  * And now we can clean up any files we may have left.
1674  */
1675  if (gxact->ondisk)
1676  RemoveTwoPhaseFile(xid, true);
1677 
1678  MyLockedGxact = NULL;
1679 
1681 
1682  pfree(buf);
1683 }
#define MAXALIGN(LEN)
Definition: c.h:811
uint32 TransactionId
Definition: c.h:652
void DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo)
Definition: md.c:1446
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
Oid GetUserId(void)
Definition: miscinit.c:514
void pgstat_execute_transactional_drops(int ndrops, struct xl_xact_stats_item *items, bool is_redo)
Definition: pgstat_xact.c:312
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat_xact.c:40
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:4867
#define GetPGProcByNumber(n)
Definition: proc.h:428
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:565
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:6779
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:6754
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:47
Definition: proc.h:157
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:2405
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:2307
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1689
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1717
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1303
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:552
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 Assert, AtEOXact_PgStat(), buf, DropRelationFiles(), GetPGProcByNumber, 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(), 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 2634 of file twophase.c.

2636 {
2637  int i;
2638  bool found = false;
2639 
2640  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
2641  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2642  {
2644 
2645  /* Ignore not-yet-valid GIDs. */
2646  if (gxact->valid && strcmp(gxact->gid, gid) == 0)
2647  {
2648  char *buf;
2649  TwoPhaseFileHeader *hdr;
2650 
2651  /*
2652  * We are not expecting collisions of GXACTs (same gid) between
2653  * publisher and subscribers, so we perform all I/O while holding
2654  * TwoPhaseStateLock for simplicity.
2655  *
2656  * To move the I/O out of the lock, we need to ensure that no
2657  * other backend commits the prepared xact in the meantime. We can
2658  * do this optimization if we encounter many collisions in GID
2659  * between publisher and subscriber.
2660  */
2661  if (gxact->ondisk)
2662  buf = ReadTwoPhaseFile(gxact->xid, false);
2663  else
2664  {
2665  Assert(gxact->prepare_start_lsn);
2666  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
2667  }
2668 
2669  hdr = (TwoPhaseFileHeader *) buf;
2670 
2671  if (hdr->origin_lsn == prepare_end_lsn &&
2672  hdr->origin_timestamp == origin_prepare_timestamp)
2673  {
2674  found = true;
2675  pfree(buf);
2676  break;
2677  }
2678 
2679  pfree(buf);
2680  }
2681  }
2682  LWLockRelease(TwoPhaseStateLock);
2683  return found;
2684 }
char gid[GIDSIZE]
Definition: twophase.c:169

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

361 {
362  GlobalTransaction gxact;
363  int i;
364 
365  if (strlen(gid) >= GIDSIZE)
366  ereport(ERROR,
367  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
368  errmsg("transaction identifier \"%s\" is too long",
369  gid)));
370 
371  /* fail immediately if feature is disabled */
372  if (max_prepared_xacts == 0)
373  ereport(ERROR,
374  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
375  errmsg("prepared transactions are disabled"),
376  errhint("Set max_prepared_transactions to a nonzero value.")));
377 
378  /* on first call, register the exit hook */
380  {
382  twophaseExitRegistered = true;
383  }
384 
385  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
386 
387  /* Check for conflicting GID */
388  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
389  {
390  gxact = TwoPhaseState->prepXacts[i];
391  if (strcmp(gxact->gid, gid) == 0)
392  {
393  ereport(ERROR,
395  errmsg("transaction identifier \"%s\" is already in use",
396  gid)));
397  }
398  }
399 
400  /* Get a free gxact from the freelist */
401  if (TwoPhaseState->freeGXacts == NULL)
402  ereport(ERROR,
403  (errcode(ERRCODE_OUT_OF_MEMORY),
404  errmsg("maximum number of prepared transactions reached"),
405  errhint("Increase max_prepared_transactions (currently %d).",
407  gxact = TwoPhaseState->freeGXacts;
408  TwoPhaseState->freeGXacts = gxact->next;
409 
410  MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
411 
412  gxact->ondisk = false;
413 
414  /* And insert it into the active array */
417 
418  LWLockRelease(TwoPhaseStateLock);
419 
420  return gxact;
421 }
int errhint(const char *fmt,...)
Definition: elog.c:1319
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
GlobalTransaction next
Definition: twophase.c:149
GlobalTransaction freeGXacts
Definition: twophase.c:179
static bool twophaseExitRegistered
Definition: twophase.c:198
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:433
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:294
#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 344 of file twophase.c.

345 {
346  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
348  LWLockRelease(TwoPhaseStateLock);
349 
350  MyLockedGxact = NULL;
351 }

References INVALID_PROC_NUMBER, 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 2480 of file twophase.c.

2482 {
2484  char *bufptr;
2485  const char *gid;
2486  GlobalTransaction gxact;
2487 
2488  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2490 
2491  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2492  gid = (const char *) bufptr;
2493 
2494  /*
2495  * Reserve the GID for the given transaction in the redo code path.
2496  *
2497  * This creates a gxact struct and puts it into the active array.
2498  *
2499  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2500  * shared memory. Hence, we only fill up the bare minimum contents here.
2501  * The gxact also gets marked with gxact->inredo set to true to indicate
2502  * that it got added in the redo phase
2503  */
2504 
2505  /*
2506  * In the event of a crash while a checkpoint was running, it may be
2507  * possible that some two-phase data found its way to disk while its
2508  * corresponding record needs to be replayed in the follow-up recovery. As
2509  * the 2PC data was on disk, it has already been restored at the beginning
2510  * of recovery with restoreTwoPhaseData(), so skip this record to avoid
2511  * duplicates in TwoPhaseState. If a consistent state has been reached,
2512  * the record is added to TwoPhaseState and it should have no
2513  * corresponding file in pg_twophase.
2514  */
2515  if (!XLogRecPtrIsInvalid(start_lsn))
2516  {
2517  char path[MAXPGPATH];
2518 
2519  TwoPhaseFilePath(path, hdr->xid);
2520 
2521  if (access(path, F_OK) == 0)
2522  {
2524  (errmsg("could not recover two-phase state file for transaction %u",
2525  hdr->xid),
2526  errdetail("Two-phase state file has been found in WAL record %X/%X, but this transaction has already been restored from disk.",
2527  LSN_FORMAT_ARGS(start_lsn))));
2528  return;
2529  }
2530 
2531  if (errno != ENOENT)
2532  ereport(ERROR,
2534  errmsg("could not access file \"%s\": %m", path)));
2535  }
2536 
2537  /* Get a free gxact from the freelist */
2538  if (TwoPhaseState->freeGXacts == NULL)
2539  ereport(ERROR,
2540  (errcode(ERRCODE_OUT_OF_MEMORY),
2541  errmsg("maximum number of prepared transactions reached"),
2542  errhint("Increase max_prepared_transactions (currently %d).",
2543  max_prepared_xacts)));
2544  gxact = TwoPhaseState->freeGXacts;
2545  TwoPhaseState->freeGXacts = gxact->next;
2546 
2547  gxact->prepared_at = hdr->prepared_at;
2548  gxact->prepare_start_lsn = start_lsn;
2549  gxact->prepare_end_lsn = end_lsn;
2550  gxact->xid = hdr->xid;
2551  gxact->owner = hdr->owner;
2553  gxact->valid = false;
2554  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2555  gxact->inredo = true; /* yes, added in redo */
2556  strcpy(gxact->gid, gid);
2557 
2558  /* And insert it into the active array */
2561 
2562  if (origin_id != InvalidRepOriginId)
2563  {
2564  /* recover apply progress */
2565  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2566  false /* backward */ , false /* WAL */ );
2567  }
2568 
2569  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2570 }
int errcode_for_file_access(void)
Definition: elog.c:882
int errdetail(const char *fmt,...)
Definition: elog.c:1205
#define WARNING
Definition: elog.h:36
#define DEBUG2
Definition: elog.h:29
#define elog(elevel,...)
Definition: elog.h:224
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1939
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:888
#define MAXPGPATH
short access
Definition: preproc-type.c:36
TimestampTz prepared_at
Definition: twophase.c:151
TimestampTz prepared_at
Definition: xact.h:352
static int TwoPhaseFilePath(char *path, TransactionId xid)
Definition: twophase.c:961
bool RecoveryInProgress(void)
Definition: xlog.c:6290
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
bool reachedConsistency
Definition: xlogrecovery.c:294

References Assert, buf, DEBUG2, elog, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), ERROR, TwoPhaseStateData::freeGXacts, GlobalTransactionData::gid, GlobalTransactionData::inredo, INVALID_PROC_NUMBER, InvalidRepOriginId, GlobalTransactionData::locking_backend, LSN_FORMAT_ARGS, LW_EXCLUSIVE, LWLockHeldByMeInMode(), max_prepared_xacts, MAXALIGN, MAXPGPATH, 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, reachedConsistency, RecoveryInProgress(), replorigin_advance(), TwoPhaseFilePath(), TwoPhaseState, GlobalTransactionData::valid, WARNING, GlobalTransactionData::xid, xl_xact_prepare::xid, and XLogRecPtrIsInvalid.

Referenced by restoreTwoPhaseData(), and xact_redo().

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2582 of file twophase.c.

2583 {
2584  GlobalTransaction gxact = NULL;
2585  int i;
2586  bool found = false;
2587 
2588  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2590 
2591  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2592  {
2593  gxact = TwoPhaseState->prepXacts[i];
2594 
2595  if (gxact->xid == xid)
2596  {
2597  Assert(gxact->inredo);
2598  found = true;
2599  break;
2600  }
2601  }
2602 
2603  /*
2604  * Just leave if there is nothing, this is expected during WAL replay.
2605  */
2606  if (!found)
2607  return;
2608 
2609  /*
2610  * And now we can clean up any files we may have left.
2611  */
2612  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2613  if (gxact->ondisk)
2614  RemoveTwoPhaseFile(xid, giveWarning);
2615  RemoveGXact(gxact);
2616 }

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

1963 {
1965  TransactionId origNextXid = XidFromFullTransactionId(nextXid);
1966  TransactionId result = origNextXid;
1967  TransactionId *xids = NULL;
1968  int nxids = 0;
1969  int allocsize = 0;
1970  int i;
1971 
1972  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1973  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1974  {
1975  TransactionId xid;
1976  char *buf;
1978 
1979  Assert(gxact->inredo);
1980 
1981  xid = gxact->xid;
1982 
1983  buf = ProcessTwoPhaseBuffer(xid,
1984  gxact->prepare_start_lsn,
1985  gxact->ondisk, false, true);
1986 
1987  if (buf == NULL)
1988  continue;
1989 
1990  /*
1991  * OK, we think this file is valid. Incorporate xid into the
1992  * running-minimum result.
1993  */
1994  if (TransactionIdPrecedes(xid, result))
1995  result = xid;
1996 
1997  if (xids_p)
1998  {
1999  if (nxids == allocsize)
2000  {
2001  if (nxids == 0)
2002  {
2003  allocsize = 10;
2004  xids = palloc(allocsize * sizeof(TransactionId));
2005  }
2006  else
2007  {
2008  allocsize = allocsize * 2;
2009  xids = repalloc(xids, allocsize * sizeof(TransactionId));
2010  }
2011  }
2012  xids[nxids++] = xid;
2013  }
2014 
2015  pfree(buf);
2016  }
2017  LWLockRelease(TwoPhaseStateLock);
2018 
2019  if (xids_p)
2020  {
2021  *xids_p = xids;
2022  *nxids_p = nxids;
2023  }
2024 
2025  return result;
2026 }
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1540
void * palloc(Size size)
Definition: mcxt.c:1316
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:2187
TransamVariablesData * TransamVariables
Definition: varsup.c:34

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

Referenced by StartupXLOG(), and xlog_redo().

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 2084 of file twophase.c.

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

1899 {
1900  DIR *cldir;
1901  struct dirent *clde;
1902 
1903  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1904  cldir = AllocateDir(TWOPHASE_DIR);
1905  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1906  {
1907  if (strlen(clde->d_name) == 16 &&
1908  strspn(clde->d_name, "0123456789ABCDEF") == 16)
1909  {
1910  TransactionId xid;
1911  FullTransactionId fxid;
1912  char *buf;
1913 
1914  fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
1915  xid = XidFromFullTransactionId(fxid);
1916 
1918  true, false, false);
1919  if (buf == NULL)
1920  continue;
1921 
1924  }
1925  }
1926  LWLockRelease(TwoPhaseStateLock);
1927  FreeDir(cldir);
1928 }
#define strtou64(str, endptr, base)
Definition: c.h:1298
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2909
int FreeDir(DIR *dir)
Definition: fd.c:2961
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2843
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
static FullTransactionId FullTransactionIdFromU64(uint64 value)
Definition: transam.h:81
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2480

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

Referenced by StartupXLOG().

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 2043 of file twophase.c.

2044 {
2045  int i;
2046 
2047  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2048  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2049  {
2050  TransactionId xid;
2051  char *buf;
2053 
2054  Assert(gxact->inredo);
2055 
2056  xid = gxact->xid;
2057 
2058  buf = ProcessTwoPhaseBuffer(xid,
2059  gxact->prepare_start_lsn,
2060  gxact->ondisk, false, false);
2061  if (buf != NULL)
2062  pfree(buf);
2063  }
2064  LWLockRelease(TwoPhaseStateLock);
2065 }

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

1476 {
1477  char *buf;
1478  TwoPhaseFileHeader *hdr;
1479  bool result;
1480 
1482 
1483  if (max_prepared_xacts <= 0)
1484  return false; /* nothing to do */
1485 
1486  /* Read and validate file */
1487  buf = ReadTwoPhaseFile(xid, true);
1488  if (buf == NULL)
1489  return false;
1490 
1491  /* Check header also */
1492  hdr = (TwoPhaseFileHeader *) buf;
1493  result = TransactionIdEquals(hdr->xid, xid);
1494  pfree(buf);
1495 
1496  return result;
1497 }
#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 1065 of file twophase.c.

1066 {
1067  PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
1068  TransactionId xid = gxact->xid;
1069  TwoPhaseFileHeader hdr;
1070  TransactionId *children;
1071  RelFileLocator *commitrels;
1072  RelFileLocator *abortrels;
1073  xl_xact_stats_item *abortstats = NULL;
1074  xl_xact_stats_item *commitstats = NULL;
1075  SharedInvalidationMessage *invalmsgs;
1076 
1077  /* Initialize linked list */
1078  records.head = palloc0(sizeof(StateFileChunk));
1079  records.head->len = 0;
1080  records.head->next = NULL;
1081 
1082  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1084 
1086  records.num_chunks = 1;
1087 
1088  records.total_len = 0;
1089 
1090  /* Create header */
1091  hdr.magic = TWOPHASE_MAGIC;
1092  hdr.total_len = 0; /* EndPrepare will fill this in */
1093  hdr.xid = xid;
1094  hdr.database = proc->databaseId;
1095  hdr.prepared_at = gxact->prepared_at;
1096  hdr.owner = gxact->owner;
1097  hdr.nsubxacts = xactGetCommittedChildren(&children);
1098  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1099  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1100  hdr.ncommitstats =
1101  pgstat_get_transactional_drops(true, &commitstats);
1102  hdr.nabortstats =
1103  pgstat_get_transactional_drops(false, &abortstats);
1105  &hdr.initfileinval);
1106  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1107  /* EndPrepare will fill the origin data, if necessary */
1109  hdr.origin_timestamp = 0;
1110 
1111  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1112  save_state_data(gxact->gid, hdr.gidlen);
1113 
1114  /*
1115  * Add the additional info about subxacts, deletable files and cache
1116  * invalidation messages.
1117  */
1118  if (hdr.nsubxacts > 0)
1119  {
1120  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1121  /* While we have the child-xact data, stuff it in the gxact too */
1122  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1123  }
1124  if (hdr.ncommitrels > 0)
1125  {
1126  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileLocator));
1127  pfree(commitrels);
1128  }
1129  if (hdr.nabortrels > 0)
1130  {
1131  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileLocator));
1132  pfree(abortrels);
1133  }
1134  if (hdr.ncommitstats > 0)
1135  {
1136  save_state_data(commitstats,
1137  hdr.ncommitstats * sizeof(xl_xact_stats_item));
1138  pfree(commitstats);
1139  }
1140  if (hdr.nabortstats > 0)
1141  {
1142  save_state_data(abortstats,
1143  hdr.nabortstats * sizeof(xl_xact_stats_item));
1144  pfree(abortstats);
1145  }
1146  if (hdr.ninvalmsgs > 0)
1147  {
1148  save_state_data(invalmsgs,
1149  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1150  pfree(invalmsgs);
1151  }
1152 }
#define Max(x, y)
Definition: c.h:998
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:882
void * palloc0(Size size)
Definition: mcxt.c:1346
int pgstat_get_transactional_drops(bool isCommit, xl_xact_stats_item **items)
Definition: pgstat_xact.c:270
int smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
Definition: storage.c:852
Oid databaseId
Definition: proc.h:203
uint32 bytes_free
Definition: twophase.c:1023
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:1037
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5741

References xllist::bytes_free, StateFileChunk::data, xl_xact_prepare::database, PGPROC::databaseId, GetPGProcByNumber, 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, 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().

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid,
bool  lock_held 
)

Definition at line 918 of file twophase.c.

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

References GetPGProcByNumber, GlobalTransactionData::pgprocno, and TwoPhaseGetGXact().

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

◆ TwoPhaseGetDummyProcNumber()

int TwoPhaseGetDummyProcNumber ( TransactionId  xid,
bool  lock_held 
)

Definition at line 903 of file twophase.c.

904 {
905  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
906 
907  return gxact->pgprocno;
908 }

References GlobalTransactionData::pgprocno, and TwoPhaseGetGXact().

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

◆ TwoPhaseGetXidByVirtualXID()

TransactionId TwoPhaseGetXidByVirtualXID ( VirtualTransactionId  vxid,
bool have_more 
)

Definition at line 852 of file twophase.c.

854 {
855  int i;
857 
859  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
860 
861  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
862  {
864  PGPROC *proc;
865  VirtualTransactionId proc_vxid;
866 
867  if (!gxact->valid)
868  continue;
869  proc = GetPGProcByNumber(gxact->pgprocno);
870  GET_VXID_FROM_PGPROC(proc_vxid, *proc);
871  if (VirtualTransactionIdEquals(vxid, proc_vxid))
872  {
873  /*
874  * Startup process sets proc->vxid.procNumber to
875  * INVALID_PROC_NUMBER.
876  */
877  Assert(!gxact->inredo);
878 
879  if (result != InvalidTransactionId)
880  {
881  *have_more = true;
882  break;
883  }
884  result = gxact->xid;
885  }
886  }
887 
888  LWLockRelease(TwoPhaseStateLock);
889 
890  return result;
891 }
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:67
#define GET_VXID_FROM_PGPROC(vxid_dst, proc)
Definition: lock.h:77
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:71
#define InvalidTransactionId
Definition: transam.h:31

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

Referenced by XactLockForVirtualXact().

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 253 of file twophase.c.

254 {
255  bool found;
256 
257  TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
259  &found);
260  if (!IsUnderPostmaster)
261  {
262  GlobalTransaction gxacts;
263  int i;
264 
265  Assert(!found);
266  TwoPhaseState->freeGXacts = NULL;
268 
269  /*
270  * Initialize the linked list of free GlobalTransactionData structs
271  */
272  gxacts = (GlobalTransaction)
273  ((char *) TwoPhaseState +
274  MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
276  for (i = 0; i < max_prepared_xacts; i++)
277  {
278  /* insert into linked list */
279  gxacts[i].next = TwoPhaseState->freeGXacts;
280  TwoPhaseState->freeGXacts = &gxacts[i];
281 
282  /* associate it with a PGPROC assigned by InitProcGlobal */
284  }
285  }
286  else
287  Assert(found);
288 }
bool IsUnderPostmaster
Definition: globals.c:117
#define GetNumberFromPGProc(proc)
Definition: proc.h:429
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387
PGPROC * PreparedXactProcs
Definition: proc.c:80
Size TwoPhaseShmemSize(void)
Definition: twophase.c:237
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:26

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

Referenced by CreateOrAttachShmemStructs().

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 237 of file twophase.c.

238 {
239  Size size;
240 
241  /* Need the fixed struct, the array of pointers, and the GTD structs */
242  size = offsetof(TwoPhaseStateData, prepXacts);
244  sizeof(GlobalTransaction)));
245  size = MAXALIGN(size);
247  sizeof(GlobalTransactionData)));
248 
249  return size;
250 }
size_t Size
Definition: c.h:605
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
static pg_noinline void Size size
Definition: slab.c:607

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

Referenced by CalculateShmemSize(), and TwoPhaseShmemInit().

Variable Documentation

◆ max_prepared_xacts