PostgreSQL Source Code git master
Loading...
Searching...
No Matches
twophase.h File Reference
#include "access/xact.h"
#include "access/xlogdefs.h"
#include "datatype/timestamp.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 PGPROC PGPROC
 
typedef struct VirtualTransactionId VirtualTransactionId
 
typedef struct GlobalTransactionDataGlobalTransaction
 

Functions

void AtAbort_Twophase (void)
 
void PostPrepare_Twophase (void)
 
TransactionId TwoPhaseGetXidByVirtualXID (VirtualTransactionId vxid, bool *have_more)
 
PGPROCTwoPhaseGetDummyProc (FullTransactionId fxid, bool lock_held)
 
int TwoPhaseGetDummyProcNumber (FullTransactionId fxid, bool lock_held)
 
GlobalTransaction MarkAsPreparing (FullTransactionId fxid, 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 (FullTransactionId fxid, char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, ReplOriginId origin_id)
 
void PrepareRedoRemove (TransactionId xid, bool giveWarning)
 
void restoreTwoPhaseData (void)
 
bool LookupGXact (const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
 
void TwoPhaseTransactionGid (Oid subid, TransactionId xid, char *gid_res, int szgid)
 
bool LookupGXactBySubid (Oid subid)
 
TransactionId TwoPhaseGetOldestXidInCommit (void)
 

Variables

PGDLLIMPORT int max_prepared_xacts
 

Typedef Documentation

◆ GlobalTransaction

Definition at line 31 of file twophase.h.

◆ PGPROC

Definition at line 24 of file twophase.h.

◆ VirtualTransactionId

Definition at line 25 of file twophase.h.

Function Documentation

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )
extern

Definition at line 310 of file twophase.c.

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

References fb(), 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)
extern

Definition at line 1828 of file twophase.c.

1829{
1830 int i;
1831 int serialized_xacts = 0;
1832
1833 if (max_prepared_xacts <= 0)
1834 return; /* nothing to do */
1835
1837
1838 /*
1839 * We are expecting there to be zero GXACTs that need to be copied to
1840 * disk, so we perform all I/O while holding TwoPhaseStateLock for
1841 * simplicity. This prevents any new xacts from preparing while this
1842 * occurs, which shouldn't be a problem since the presence of long-lived
1843 * prepared xacts indicates the transaction manager isn't active.
1844 *
1845 * It's also possible to move I/O out of the lock, but on every error we
1846 * should check whether somebody committed our transaction in different
1847 * backend. Let's leave this optimization for future, if somebody will
1848 * spot that this place cause bottleneck.
1849 *
1850 * Note that it isn't possible for there to be a GXACT with a
1851 * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1852 * because of the efforts with delayChkptFlags.
1853 */
1855 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1856 {
1857 /*
1858 * Note that we are using gxact not PGPROC so this works in recovery
1859 * also
1860 */
1862
1863 if ((gxact->valid || gxact->inredo) &&
1864 !gxact->ondisk &&
1865 gxact->prepare_end_lsn <= redo_horizon)
1866 {
1867 char *buf;
1868 int len;
1869
1870 XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1872 gxact->ondisk = true;
1873 gxact->prepare_start_lsn = InvalidXLogRecPtr;
1874 gxact->prepare_end_lsn = InvalidXLogRecPtr;
1875 pfree(buf);
1877 }
1878 }
1880
1881 /*
1882 * Flush unconditionally the parent directory to make any information
1883 * durable on disk. Two-phase files could have been removed and those
1884 * removals need to be made persistent as well as any files newly created
1885 * previously since the last checkpoint.
1886 */
1888
1890
1892 ereport(LOG,
1893 (errmsg_plural("%u two-phase state file was written "
1894 "for a long-running prepared transaction",
1895 "%u two-phase state files were written "
1896 "for long-running prepared transactions",
1899}
#define LOG
Definition elog.h:32
int int int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
#define ereport(elevel,...)
Definition elog.h:152
void fsync_fname(const char *fname, bool isdir)
Definition fd.c:757
int i
Definition isn.c:77
@ LW_SHARED
Definition lwlock.h:105
void pfree(void *pointer)
Definition mcxt.c:1616
const void size_t len
static char buf[DEFAULT_XLOG_SEG_SIZE]
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition twophase.c:188
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition twophase.c:1418
#define TWOPHASE_DIR
Definition twophase.c:115
int max_prepared_xacts
Definition twophase.c:118
static TwoPhaseStateData * TwoPhaseState
Definition twophase.c:191
static void RecreateTwoPhaseFile(FullTransactionId fxid, void *content, int len)
Definition twophase.c:1748
bool log_checkpoints
Definition xlog.c:136
#define InvalidXLogRecPtr
Definition xlogdefs.h:28

References buf, ereport, errmsg_plural(), fb(), fsync_fname(), i, InvalidXLogRecPtr, len, LOG, log_checkpoints, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_prepared_xacts, TwoPhaseStateData::numPrepXacts, pfree(), TwoPhaseStateData::prepXacts, RecreateTwoPhaseFile(), TWOPHASE_DIR, TwoPhaseState, and XlogReadTwoPhaseData().

Referenced by CheckPointGuts().

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)
extern

Definition at line 1151 of file twophase.c.

1152{
1153 TwoPhaseFileHeader *hdr;
1154 StateFileChunk *record;
1155 bool replorigin;
1156
1157 /* Add the end sentinel to the list of 2PC records */
1159 NULL, 0);
1160
1161 /* Go back and fill in total_len in the file header record */
1163 Assert(hdr->magic == TWOPHASE_MAGIC);
1164 hdr->total_len = records.total_len + sizeof(pg_crc32c);
1165
1168
1169 if (replorigin)
1170 {
1171 hdr->origin_lsn = replorigin_xact_state.origin_lsn;
1172 hdr->origin_timestamp = replorigin_xact_state.origin_timestamp;
1173 }
1174
1175 /*
1176 * If the data size exceeds MaxAllocSize, we won't be able to read it in
1177 * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1178 * where we write data to file and then re-read at commit time.
1179 */
1180 if (hdr->total_len > MaxAllocSize)
1181 ereport(ERROR,
1183 errmsg("two-phase state file maximum length exceeded")));
1184
1185 /*
1186 * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1187 * cover us, so no need to calculate a separate CRC.
1188 *
1189 * We have to set DELAY_CHKPT_START here, too; otherwise a checkpoint
1190 * starting immediately after the WAL record is inserted could complete
1191 * without fsync'ing our state file. (This is essentially the same kind
1192 * of race condition as the COMMIT-to-clog-write case that
1193 * RecordTransactionCommit uses DELAY_CHKPT_IN_COMMIT for; see notes
1194 * there.) Note that DELAY_CHKPT_IN_COMMIT is used to find transactions in
1195 * the critical commit section. We need to know about such transactions
1196 * for conflict detection in logical replication. See
1197 * GetOldestActiveTransactionId(true, false) and its use.
1198 *
1199 * We save the PREPARE record's location in the gxact for later use by
1200 * CheckPointTwoPhase.
1201 */
1203
1205
1208
1210 for (record = records.head; record != NULL; record = record->next)
1211 XLogRegisterData(record->data, record->len);
1212
1214
1215 gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1216
1217 if (replorigin)
1218 {
1219 /* Move LSNs forward for this replication origin */
1221 gxact->prepare_end_lsn);
1222 }
1223
1224 XLogFlush(gxact->prepare_end_lsn);
1225
1226 /* If we crash now, we have prepared: WAL replay will fix things */
1227
1228 /* Store record's start location to read that later on Commit */
1229 gxact->prepare_start_lsn = ProcLastRecPtr;
1230
1231 /*
1232 * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
1233 * as not running our XID (which it will do immediately after this
1234 * function returns), others can commit/rollback the xact.
1235 *
1236 * NB: a side effect of this is to make a dummy ProcArray entry for the
1237 * prepared XID. This must happen before we clear the XID from MyProc /
1238 * ProcGlobal->xids[], else there is a window where the XID is not running
1239 * according to TransactionIdIsInProgress, and onlookers would be entitled
1240 * to assume the xact crashed. Instead we have a window where the same
1241 * XID appears twice in ProcArray, which is OK.
1242 */
1243 MarkAsPrepared(gxact, false);
1244
1245 /*
1246 * Now we can mark ourselves as out of the commit critical section: a
1247 * checkpoint starting after this will certainly see the gxact as a
1248 * candidate for fsyncing.
1249 */
1251
1252 /*
1253 * Remember that we have this GlobalTransaction entry locked for us. If
1254 * we crash after this point, it's too late to abort, but we must unlock
1255 * it so that the prepared transaction can be committed or rolled back.
1256 */
1258
1260
1261 /*
1262 * Wait for synchronous replication, if required.
1263 *
1264 * Note that at this stage we have marked the prepare, but still show as
1265 * running in the procarray (twice!) and continue to hold locks.
1266 */
1267 SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1268
1270 records.num_chunks = 0;
1271}
#define Assert(condition)
Definition c.h:943
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
#define MaxAllocSize
Definition fe_memutils.h:22
#define START_CRIT_SECTION()
Definition miscadmin.h:152
#define END_CRIT_SECTION()
Definition miscadmin.h:154
static char * errmsg
ReplOriginXactState replorigin_xact_state
Definition origin.c:168
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition origin.c:1335
#define DoNotReplicateId
Definition origin.h:34
#define InvalidReplOriginId
Definition origin.h:33
uint32 pg_crc32c
Definition pg_crc32c.h:38
#define DELAY_CHKPT_START
Definition proc.h:139
PGPROC * MyProc
Definition proc.c:71
int delayChkptFlags
Definition proc.h:260
ReplOriginId origin
Definition origin.h:45
XLogRecPtr origin_lsn
Definition origin.h:46
TimestampTz origin_timestamp
Definition origin.h:47
uint32 total_len
Definition twophase.c:1017
uint32 num_chunks
Definition twophase.c:1015
StateFileChunk * head
Definition twophase.c:1013
StateFileChunk * tail
Definition twophase.c:1014
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition syncrep.c:149
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition twophase.c:1277
#define TWOPHASE_MAGIC
Definition twophase.c:982
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition twophase.c:538
static struct xllist records
#define TWOPHASE_RM_END_ID
#define XLOG_XACT_PREPARE
Definition xact.h:171
XLogRecPtr ProcLastRecPtr
Definition xlog.c:260
void XLogFlush(XLogRecPtr record)
Definition xlog.c:2801
#define XLOG_INCLUDE_ORIGIN
Definition xlog.h:166
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:482
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:372
void XLogSetRecordFlags(uint8 flags)
Definition xloginsert.c:464
void XLogBeginInsert(void)
Definition xloginsert.c:153
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition xloginsert.c:179

References Assert, StateFileChunk::data, DELAY_CHKPT_START, PGPROC::delayChkptFlags, DoNotReplicateId, END_CRIT_SECTION, ereport, errcode(), errmsg, ERROR, fb(), xllist::head, InvalidReplOriginId, StateFileChunk::len, xl_xact_prepare::magic, MarkAsPrepared(), MaxAllocSize, MyLockedGxact, MyProc, StateFileChunk::next, xllist::num_chunks, ReplOriginXactState::origin, xl_xact_prepare::origin_lsn, ReplOriginXactState::origin_lsn, xl_xact_prepare::origin_timestamp, ReplOriginXactState::origin_timestamp, ProcLastRecPtr, records, RegisterTwoPhaseRecord(), replorigin_session_advance(), replorigin_xact_state, 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 
)
extern

Definition at line 1503 of file twophase.c.

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

References Assert, AtEOXact_PgStat(), buf, DropRelationFiles(), fb(), 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, pfree(), pgstat_execute_transactional_drops(), PredicateLockTwoPhaseFinish(), ProcArrayRemove(), ProcessRecords(), ReadTwoPhaseFile(), RecordTransactionAbortPrepared(), RecordTransactionCommitPrepared(), RelationCacheInitFilePostInvalidate(), RelationCacheInitFilePreInvalidate(), RemoveGXact(), RemoveTwoPhaseFile(), RESUME_INTERRUPTS, SendSharedInvalidMessages(), TransactionIdEquals, TransactionIdLatest(), twophase_postabort_callbacks, twophase_postcommit_callbacks, xl_xact_prepare::xid, XidFromFullTransactionId, 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 
)
extern

Definition at line 2694 of file twophase.c.

2696{
2697 int i;
2698 bool found = false;
2699
2701 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2702 {
2704
2705 /* Ignore not-yet-valid GIDs. */
2706 if (gxact->valid && strcmp(gxact->gid, gid) == 0)
2707 {
2708 char *buf;
2709 TwoPhaseFileHeader *hdr;
2710
2711 /*
2712 * We are not expecting collisions of GXACTs (same gid) between
2713 * publisher and subscribers, so we perform all I/O while holding
2714 * TwoPhaseStateLock for simplicity.
2715 *
2716 * To move the I/O out of the lock, we need to ensure that no
2717 * other backend commits the prepared xact in the meantime. We can
2718 * do this optimization if we encounter many collisions in GID
2719 * between publisher and subscriber.
2720 */
2721 if (gxact->ondisk)
2722 buf = ReadTwoPhaseFile(gxact->fxid, false);
2723 else
2724 {
2725 Assert(gxact->prepare_start_lsn);
2726 XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
2727 }
2728
2729 hdr = (TwoPhaseFileHeader *) buf;
2730
2731 if (hdr->origin_lsn == prepare_end_lsn &&
2733 {
2734 found = true;
2735 pfree(buf);
2736 break;
2737 }
2738
2739 pfree(buf);
2740 }
2741 }
2743 return found;
2744}
TimestampTz origin_timestamp
Definition xact.h:370
XLogRecPtr origin_lsn
Definition xact.h:369

References Assert, buf, fb(), i, LW_SHARED, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, xl_xact_prepare::origin_lsn, xl_xact_prepare::origin_timestamp, pfree(), TwoPhaseStateData::prepXacts, ReadTwoPhaseFile(), TwoPhaseState, and XlogReadTwoPhaseData().

Referenced by apply_handle_rollback_prepared().

◆ LookupGXactBySubid()

bool LookupGXactBySubid ( Oid  subid)
extern

Definition at line 2803 of file twophase.c.

2804{
2805 bool found = false;
2806
2808 for (int i = 0; i < TwoPhaseState->numPrepXacts; i++)
2809 {
2811
2812 /* Ignore not-yet-valid GIDs. */
2813 if (gxact->valid &&
2815 {
2816 found = true;
2817 break;
2818 }
2819 }
2821
2822 return found;
2823}
static bool IsTwoPhaseTransactionGidForSubid(Oid subid, char *gid)
Definition twophase.c:2771

References fb(), i, IsTwoPhaseTransactionGidForSubid(), LW_SHARED, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, and TwoPhaseState.

Referenced by AlterSubscription().

◆ MarkAsPreparing()

GlobalTransaction MarkAsPreparing ( FullTransactionId  fxid,
const char gid,
TimestampTz  prepared_at,
Oid  owner,
Oid  databaseid 
)
extern

Definition at line 365 of file twophase.c.

367{
369 int i;
370
371 if (strlen(gid) >= GIDSIZE)
374 errmsg("transaction identifier \"%s\" is too long",
375 gid)));
376
377 /* fail immediately if feature is disabled */
378 if (max_prepared_xacts == 0)
381 errmsg("prepared transactions are disabled"),
382 errhint("Set \"max_prepared_transactions\" to a nonzero value.")));
383
384 /* on first call, register the exit hook */
386 {
389 }
390
392
393 /* Check for conflicting GID */
394 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
395 {
397 if (strcmp(gxact->gid, gid) == 0)
398 {
401 errmsg("transaction identifier \"%s\" is already in use",
402 gid)));
403 }
404 }
405
406 /* Get a free gxact from the freelist */
410 errmsg("maximum number of prepared transactions reached"),
411 errhint("Increase \"max_prepared_transactions\" (currently %d).",
415
416 MarkAsPreparingGuts(gxact, fxid, gid, prepared_at, owner, databaseid);
417
418 gxact->ondisk = false;
419
420 /* And insert it into the active array */
423
425
426 return gxact;
427}
int errhint(const char *fmt,...) pg_attribute_printf(1
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
GlobalTransaction next
Definition twophase.c:152
GlobalTransaction freeGXacts
Definition twophase.c:182
static bool twophaseExitRegistered
Definition twophase.c:209
static void AtProcExit_Twophase(int code, Datum arg)
Definition twophase.c:300
static void MarkAsPreparingGuts(GlobalTransaction gxact, FullTransactionId fxid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition twophase.c:439
#define GIDSIZE
Definition xact.h:31

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

Referenced by PrepareTransaction().

◆ PostPrepare_Twophase()

◆ PrepareRedoAdd()

void PrepareRedoAdd ( FullTransactionId  fxid,
char buf,
XLogRecPtr  start_lsn,
XLogRecPtr  end_lsn,
ReplOriginId  origin_id 
)
extern

Definition at line 2513 of file twophase.c.

2516{
2518 char *bufptr;
2519 const char *gid;
2521
2524
2525 if (!FullTransactionIdIsValid(fxid))
2526 {
2529 hdr->xid);
2530 }
2531
2532 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2533 gid = (const char *) bufptr;
2534
2535 /*
2536 * Reserve the GID for the given transaction in the redo code path.
2537 *
2538 * This creates a gxact struct and puts it into the active array.
2539 *
2540 * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2541 * shared memory. Hence, we only fill up the bare minimum contents here.
2542 * The gxact also gets marked with gxact->inredo set to true to indicate
2543 * that it got added in the redo phase
2544 */
2545
2546 /*
2547 * In the event of a crash while a checkpoint was running, it may be
2548 * possible that some two-phase data found its way to disk while its
2549 * corresponding record needs to be replayed in the follow-up recovery. As
2550 * the 2PC data was on disk, it has already been restored at the beginning
2551 * of recovery with restoreTwoPhaseData(), so skip this record to avoid
2552 * duplicates in TwoPhaseState. If a consistent state has been reached,
2553 * the record is added to TwoPhaseState and it should have no
2554 * corresponding file in pg_twophase.
2555 */
2556 if (XLogRecPtrIsValid(start_lsn))
2557 {
2558 char path[MAXPGPATH];
2559
2561 TwoPhaseFilePath(path, fxid);
2562
2563 if (access(path, F_OK) == 0)
2564 {
2566 (errmsg("could not recover two-phase state file for transaction %u",
2567 hdr->xid),
2568 errdetail("Two-phase state file has been found in WAL record %X/%08X, but this transaction has already been restored from disk.",
2569 LSN_FORMAT_ARGS(start_lsn))));
2570 return;
2571 }
2572
2573 if (errno != ENOENT)
2574 ereport(ERROR,
2576 errmsg("could not access file \"%s\": %m", path)));
2577 }
2578
2579 /* Get a free gxact from the freelist */
2581 ereport(ERROR,
2583 errmsg("maximum number of prepared transactions reached"),
2584 errhint("Increase \"max_prepared_transactions\" (currently %d).",
2588
2590 gxact->prepare_start_lsn = start_lsn;
2591 gxact->prepare_end_lsn = end_lsn;
2592 gxact->fxid = fxid;
2593 gxact->owner = hdr->owner;
2594 gxact->locking_backend = INVALID_PROC_NUMBER;
2595 gxact->valid = false;
2596 gxact->ondisk = !XLogRecPtrIsValid(start_lsn);
2597 gxact->inredo = true; /* yes, added in redo */
2598 strcpy(gxact->gid, gid);
2599
2600 /* And insert it into the active array */
2603
2604 if (origin_id != InvalidReplOriginId)
2605 {
2606 /* recover apply progress */
2607 replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2608 false /* backward */ , false /* WAL */ );
2609 }
2610
2611 elog(DEBUG2, "added 2PC data in shared memory for transaction %u of epoch %u",
2614}
int errcode_for_file_access(void)
Definition elog.c:898
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:37
#define DEBUG2
Definition elog.h:30
#define elog(elevel,...)
Definition elog.h:228
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1929
void replorigin_advance(ReplOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition origin.c:928
#define MAXPGPATH
short access
TimestampTz prepared_at
Definition twophase.c:154
FullTransactionId nextXid
Definition transam.h:220
TimestampTz prepared_at
Definition xact.h:359
static FullTransactionId FullTransactionIdFromAllowableAt(FullTransactionId nextFullXid, TransactionId xid)
Definition transam.h:441
#define EpochFromFullTransactionId(x)
Definition transam.h:47
#define FullTransactionIdIsValid(x)
Definition transam.h:55
static int TwoPhaseFilePath(char *path, FullTransactionId fxid)
Definition twophase.c:956
TransamVariablesData * TransamVariables
Definition varsup.c:37
bool RecoveryInProgress(void)
Definition xlog.c:6830
#define XLogRecPtrIsValid(r)
Definition xlogdefs.h:29
#define LSN_FORMAT_ARGS(lsn)
Definition xlogdefs.h:47
bool reachedConsistency
bool InRecovery
Definition xlogutils.c:50

References Assert, buf, DEBUG2, elog, EpochFromFullTransactionId, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg, ERROR, fb(), TwoPhaseStateData::freeGXacts, FullTransactionIdFromAllowableAt(), FullTransactionIdIsValid, InRecovery, INVALID_PROC_NUMBER, InvalidReplOriginId, LSN_FORMAT_ARGS, LW_EXCLUSIVE, LWLockHeldByMeInMode(), max_prepared_xacts, MAXALIGN, MAXPGPATH, GlobalTransactionData::next, TransamVariablesData::nextXid, TwoPhaseStateData::numPrepXacts, xl_xact_prepare::origin_lsn, xl_xact_prepare::owner, GlobalTransactionData::prepared_at, xl_xact_prepare::prepared_at, TwoPhaseStateData::prepXacts, reachedConsistency, RecoveryInProgress(), replorigin_advance(), TransamVariables, TwoPhaseFilePath(), TwoPhaseState, WARNING, xl_xact_prepare::xid, XidFromFullTransactionId, and XLogRecPtrIsValid.

Referenced by restoreTwoPhaseData(), and xact_redo().

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)
extern

Definition at line 2670 of file twophase.c.

2671{
2672 FullTransactionId fxid =
2674
2676}
static void PrepareRedoRemoveFull(FullTransactionId fxid, bool giveWarning)
Definition twophase.c:2626

References fb(), FullTransactionIdFromAllowableAt(), TransamVariablesData::nextXid, PrepareRedoRemoveFull(), and TransamVariables.

Referenced by xact_redo().

◆ PrescanPreparedTransactions()

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

Definition at line 1972 of file twophase.c.

1973{
1977 TransactionId *xids = NULL;
1978 int nxids = 0;
1979 int allocsize = 0;
1980 int i;
1981
1983 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1984 {
1985 TransactionId xid;
1986 char *buf;
1988
1989 Assert(gxact->inredo);
1990
1992 gxact->prepare_start_lsn,
1993 gxact->ondisk, false, true);
1994
1995 if (buf == NULL)
1996 continue;
1997
1998 /*
1999 * OK, we think this file is valid. Incorporate xid into the
2000 * running-minimum result.
2001 */
2002 xid = XidFromFullTransactionId(gxact->fxid);
2003 if (TransactionIdPrecedes(xid, result))
2004 result = xid;
2005
2006 if (xids_p)
2007 {
2008 if (nxids == allocsize)
2009 {
2010 if (nxids == 0)
2011 {
2012 allocsize = 10;
2013 xids = palloc(allocsize * sizeof(TransactionId));
2014 }
2015 else
2016 {
2017 allocsize = allocsize * 2;
2018 xids = repalloc(xids, allocsize * sizeof(TransactionId));
2019 }
2020 }
2021 xids[nxids++] = xid;
2022 }
2023
2024 pfree(buf);
2025 }
2027
2028 if (xids_p)
2029 {
2030 *xids_p = xids;
2031 *nxids_p = nxids;
2032 }
2033
2034 return result;
2035}
uint32 result
void * repalloc(void *pointer, Size size)
Definition mcxt.c:1632
void * palloc(Size size)
Definition mcxt.c:1387
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
static char * ProcessTwoPhaseBuffer(FullTransactionId fxid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition twophase.c:2193

References Assert, buf, fb(), i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), TransamVariablesData::nextXid, TwoPhaseStateData::numPrepXacts, palloc(), pfree(), TwoPhaseStateData::prepXacts, ProcessTwoPhaseBuffer(), repalloc(), result, TransactionIdPrecedes(), TransamVariables, TwoPhaseState, and XidFromFullTransactionId.

Referenced by StartupXLOG(), and xlog_redo().

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )
extern

Definition at line 2089 of file twophase.c.

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

References Assert, buf, xl_xact_prepare::database, EpochFromFullTransactionId, ereport, errmsg, fb(), xl_xact_prepare::gidlen, GXactLoadSubxactData(), i, InHotStandby, 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, xl_xact_prepare::owner, pfree(), PostPrepare_Twophase(), xl_xact_prepare::prepared_at, TwoPhaseStateData::prepXacts, ProcessRecords(), ProcessTwoPhaseBuffer(), StandbyReleaseLockTree(), TransactionIdEquals, twophase_recover_callbacks, TwoPhaseState, xl_xact_prepare::xid, and XidFromFullTransactionId.

Referenced by StartupXLOG().

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )
extern

Definition at line 1910 of file twophase.c.

1911{
1912 DIR *cldir;
1913 struct dirent *clde;
1914
1917 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1918 {
1919 if (strlen(clde->d_name) == 16 &&
1920 strspn(clde->d_name, "0123456789ABCDEF") == 16)
1921 {
1922 FullTransactionId fxid;
1923 char *buf;
1924
1925 fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
1926
1928 true, false, false);
1929 if (buf == NULL)
1930 continue;
1931
1934 }
1935 }
1937 FreeDir(cldir);
1938}
int FreeDir(DIR *dir)
Definition fd.c:3009
DIR * AllocateDir(const char *dirname)
Definition fd.c:2891
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition fd.c:2957
Definition dirent.c:26
static FullTransactionId FullTransactionIdFromU64(uint64 value)
Definition transam.h:81
void PrepareRedoAdd(FullTransactionId fxid, char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, ReplOriginId origin_id)
Definition twophase.c:2513

References AllocateDir(), buf, fb(), FreeDir(), FullTransactionIdFromU64(), InvalidReplOriginId, InvalidXLogRecPtr, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), PrepareRedoAdd(), ProcessTwoPhaseBuffer(), ReadDir(), and TWOPHASE_DIR.

Referenced by StartupXLOG().

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )
extern

Definition at line 2051 of file twophase.c.

2052{
2053 int i;
2054
2056 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2057 {
2058 char *buf;
2060
2061 Assert(gxact->inredo);
2062
2064 gxact->prepare_start_lsn,
2065 gxact->ondisk, true, false);
2066 if (buf != NULL)
2067 pfree(buf);
2068 }
2070}

References Assert, buf, fb(), i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, pfree(), TwoPhaseStateData::prepXacts, ProcessTwoPhaseBuffer(), and TwoPhaseState.

Referenced by StartupXLOG(), and xlog_redo().

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)
extern

Definition at line 1473 of file twophase.c.

1474{
1475 char *buf;
1476 TwoPhaseFileHeader *hdr;
1477 bool result;
1478 FullTransactionId fxid;
1479
1481
1482 if (max_prepared_xacts <= 0)
1483 return false; /* nothing to do */
1484
1485 /* Read and validate file */
1486 fxid = AdjustToFullTransactionId(xid);
1487 buf = ReadTwoPhaseFile(fxid, 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
static FullTransactionId AdjustToFullTransactionId(TransactionId xid)
Definition twophase.c:949

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)
extern

Definition at line 1058 of file twophase.c.

1059{
1060 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
1063 TransactionId *children;
1066 xl_xact_stats_item *abortstats = NULL;
1069
1070 /* Initialize linked list */
1072 records.head->len = 0;
1073 records.head->next = NULL;
1074
1075 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1077
1079 records.num_chunks = 1;
1080
1081 records.total_len = 0;
1082
1083 /* Create header */
1084 hdr.magic = TWOPHASE_MAGIC;
1085 hdr.total_len = 0; /* EndPrepare will fill this in */
1086 hdr.xid = xid;
1087 hdr.database = proc->databaseId;
1088 hdr.prepared_at = gxact->prepared_at;
1089 hdr.owner = gxact->owner;
1090 hdr.nsubxacts = xactGetCommittedChildren(&children);
1093 hdr.ncommitstats =
1095 hdr.nabortstats =
1096 pgstat_get_transactional_drops(false, &abortstats);
1098 &hdr.initfileinval);
1099 hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1100 /* EndPrepare will fill the origin data, if necessary */
1102 hdr.origin_timestamp = 0;
1103
1104 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1105 save_state_data(gxact->gid, hdr.gidlen);
1106
1107 /*
1108 * Add the additional info about subxacts, deletable files and cache
1109 * invalidation messages.
1110 */
1111 if (hdr.nsubxacts > 0)
1112 {
1113 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1114 /* While we have the child-xact data, stuff it in the gxact too */
1115 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1116 }
1117 if (hdr.ncommitrels > 0)
1118 {
1121 }
1122 if (hdr.nabortrels > 0)
1123 {
1126 }
1127 if (hdr.ncommitstats > 0)
1128 {
1130 hdr.ncommitstats * sizeof(xl_xact_stats_item));
1132 }
1133 if (hdr.nabortstats > 0)
1134 {
1135 save_state_data(abortstats,
1136 hdr.nabortstats * sizeof(xl_xact_stats_item));
1137 pfree(abortstats);
1138 }
1139 if (hdr.ninvalmsgs > 0)
1140 {
1144 }
1145}
#define Max(x, y)
Definition c.h:1085
#define palloc0_object(type)
Definition fe_memutils.h:75
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition inval.c:1012
int pgstat_get_transactional_drops(bool isCommit, xl_xact_stats_item **items)
int smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
Definition storage.c:893
Oid databaseId
Definition proc.h:201
struct StateFileChunk * next
Definition twophase.c:1008
uint32 total_len
Definition xact.h:356
uint32 magic
Definition xact.h:355
uint32 bytes_free
Definition twophase.c:1016
static void save_state_data(const void *data, uint32 len)
Definition twophase.c:1030
int xactGetCommittedChildren(TransactionId **ptr)
Definition xact.c:5841

References xllist::bytes_free, StateFileChunk::data, xl_xact_prepare::database, PGPROC::databaseId, fb(), GetPGProcByNumber, 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, xl_xact_prepare::owner, palloc(), palloc0_object, pfree(), pgstat_get_transactional_drops(), xl_xact_prepare::prepared_at, records, save_state_data(), smgrGetPendingDeletes(), xllist::tail, xllist::total_len, xl_xact_prepare::total_len, TWOPHASE_MAGIC, xactGetCommittedChildren(), xactGetCommittedInvalidationMessages(), xl_xact_prepare::xid, and XidFromFullTransactionId.

Referenced by PrepareTransaction().

◆ TwoPhaseGetDummyProc()

PGPROC * TwoPhaseGetDummyProc ( FullTransactionId  fxid,
bool  lock_held 
)
extern

Definition at line 929 of file twophase.c.

930{
932
933 return GetPGProcByNumber(gxact->pgprocno);
934}
static GlobalTransaction TwoPhaseGetGXact(FullTransactionId fxid, bool lock_held)
Definition twophase.c:809

References fb(), GetPGProcByNumber, and TwoPhaseGetGXact().

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

◆ TwoPhaseGetDummyProcNumber()

int TwoPhaseGetDummyProcNumber ( FullTransactionId  fxid,
bool  lock_held 
)
extern

Definition at line 914 of file twophase.c.

915{
917
918 return gxact->pgprocno;
919}

References fb(), and TwoPhaseGetGXact().

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

◆ TwoPhaseGetOldestXidInCommit()

TransactionId TwoPhaseGetOldestXidInCommit ( void  )
extern

Definition at line 2835 of file twophase.c.

2836{
2837 TransactionId oldestRunningXid = InvalidTransactionId;
2838
2840
2841 for (int i = 0; i < TwoPhaseState->numPrepXacts; i++)
2842 {
2845 TransactionId xid;
2846
2847 if (!gxact->valid)
2848 continue;
2849
2850 if (gxact->locking_backend == INVALID_PROC_NUMBER)
2851 continue;
2852
2853 /*
2854 * Get the backend that is handling the transaction. It's safe to
2855 * access this backend while holding TwoPhaseStateLock, as the backend
2856 * can only be destroyed after either removing or unlocking the
2857 * current global transaction, both of which require an exclusive
2858 * TwoPhaseStateLock.
2859 */
2860 commitproc = GetPGProcByNumber(gxact->locking_backend);
2861
2862 if (MyDatabaseId != commitproc->databaseId)
2863 continue;
2864
2865 if ((commitproc->delayChkptFlags & DELAY_CHKPT_IN_COMMIT) == 0)
2866 continue;
2867
2868 xid = XidFromFullTransactionId(gxact->fxid);
2869
2870 if (!TransactionIdIsValid(oldestRunningXid) ||
2871 TransactionIdPrecedes(xid, oldestRunningXid))
2872 oldestRunningXid = xid;
2873 }
2874
2876
2877 return oldestRunningXid;
2878}
Oid MyDatabaseId
Definition globals.c:96
#define DELAY_CHKPT_IN_COMMIT
Definition proc.h:141
#define InvalidTransactionId
Definition transam.h:31

References DELAY_CHKPT_IN_COMMIT, fb(), GetPGProcByNumber, i, INVALID_PROC_NUMBER, InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), MyDatabaseId, TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, TransactionIdIsValid, TransactionIdPrecedes(), TwoPhaseState, and XidFromFullTransactionId.

Referenced by ProcessStandbyPSRequestMessage().

◆ TwoPhaseGetXidByVirtualXID()

TransactionId TwoPhaseGetXidByVirtualXID ( VirtualTransactionId  vxid,
bool have_more 
)
extern

Definition at line 862 of file twophase.c.

864{
865 int i;
867
870
871 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
872 {
874 PGPROC *proc;
876
877 if (!gxact->valid)
878 continue;
879 proc = GetPGProcByNumber(gxact->pgprocno);
882 {
883 /*
884 * Startup process sets proc->vxid.procNumber to
885 * INVALID_PROC_NUMBER.
886 */
887 Assert(!gxact->inredo);
888
890 {
891 *have_more = true;
892 break;
893 }
895 }
896 }
897
899
900 return result;
901}
#define VirtualTransactionIdIsValid(vxid)
Definition lock.h:70
#define GET_VXID_FROM_PGPROC(vxid_dst, proc)
Definition lock.h:80
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition lock.h:74

References Assert, fb(), GET_VXID_FROM_PGPROC, GetPGProcByNumber, i, InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, result, TwoPhaseState, VirtualTransactionIdEquals, VirtualTransactionIdIsValid, and XidFromFullTransactionId.

Referenced by XactLockForVirtualXact().

◆ TwoPhaseTransactionGid()

void TwoPhaseTransactionGid ( Oid  subid,
TransactionId  xid,
char gid_res,
int  szgid 
)
extern

Definition at line 2753 of file twophase.c.

2754{
2755 Assert(OidIsValid(subid));
2756
2757 if (!TransactionIdIsValid(xid))
2758 ereport(ERROR,
2760 errmsg_internal("invalid two-phase transaction ID")));
2761
2762 snprintf(gid_res, szgid, "pg_gid_%u_%u", subid, xid);
2763}
#define OidIsValid(objectId)
Definition c.h:858
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define ERRCODE_PROTOCOL_VIOLATION
Definition fe-connect.c:96
#define snprintf
Definition port.h:260

References Assert, ereport, errcode(), ERRCODE_PROTOCOL_VIOLATION, errmsg_internal(), ERROR, fb(), OidIsValid, snprintf, and TransactionIdIsValid.

Referenced by apply_handle_commit_prepared(), apply_handle_prepare_internal(), apply_handle_rollback_prepared(), and IsTwoPhaseTransactionGidForSubid().

Variable Documentation

◆ max_prepared_xacts