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 "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 (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 26 of file twophase.h.

Function Documentation

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )
extern

Definition at line 307 of file twophase.c.

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

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

1825{
1826 int i;
1827 int serialized_xacts = 0;
1828
1829 if (max_prepared_xacts <= 0)
1830 return; /* nothing to do */
1831
1833
1834 /*
1835 * We are expecting there to be zero GXACTs that need to be copied to
1836 * disk, so we perform all I/O while holding TwoPhaseStateLock for
1837 * simplicity. This prevents any new xacts from preparing while this
1838 * occurs, which shouldn't be a problem since the presence of long-lived
1839 * prepared xacts indicates the transaction manager isn't active.
1840 *
1841 * It's also possible to move I/O out of the lock, but on every error we
1842 * should check whether somebody committed our transaction in different
1843 * backend. Let's leave this optimization for future, if somebody will
1844 * spot that this place cause bottleneck.
1845 *
1846 * Note that it isn't possible for there to be a GXACT with a
1847 * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1848 * because of the efforts with delayChkptFlags.
1849 */
1851 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1852 {
1853 /*
1854 * Note that we are using gxact not PGPROC so this works in recovery
1855 * also
1856 */
1858
1859 if ((gxact->valid || gxact->inredo) &&
1860 !gxact->ondisk &&
1861 gxact->prepare_end_lsn <= redo_horizon)
1862 {
1863 char *buf;
1864 int len;
1865
1866 XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1868 gxact->ondisk = true;
1869 gxact->prepare_start_lsn = InvalidXLogRecPtr;
1870 gxact->prepare_end_lsn = InvalidXLogRecPtr;
1871 pfree(buf);
1873 }
1874 }
1876
1877 /*
1878 * Flush unconditionally the parent directory to make any information
1879 * durable on disk. Two-phase files could have been removed and those
1880 * removals need to be made persistent as well as any files newly created
1881 * previously since the last checkpoint.
1882 */
1884
1886
1888 ereport(LOG,
1889 (errmsg_plural("%u two-phase state file was written "
1890 "for a long-running prepared transaction",
1891 "%u two-phase state files were written "
1892 "for long-running prepared transactions",
1895}
#define LOG
Definition elog.h:31
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:150
void fsync_fname(const char *fname, bool isdir)
Definition fd.c:757
int i
Definition isn.c:77
@ LW_SHARED
Definition lwlock.h:113
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:187
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition twophase.c:1414
#define TWOPHASE_DIR
Definition twophase.c:114
int max_prepared_xacts
Definition twophase.c:117
static TwoPhaseStateData * TwoPhaseState
Definition twophase.c:190
static void RecreateTwoPhaseFile(FullTransactionId fxid, void *content, int len)
Definition twophase.c:1744
bool log_checkpoints
Definition xlog.c:133
#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 1147 of file twophase.c.

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

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

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

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

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

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

364{
366 int i;
367
368 if (strlen(gid) >= GIDSIZE)
371 errmsg("transaction identifier \"%s\" is too long",
372 gid)));
373
374 /* fail immediately if feature is disabled */
375 if (max_prepared_xacts == 0)
378 errmsg("prepared transactions are disabled"),
379 errhint("Set \"max_prepared_transactions\" to a nonzero value.")));
380
381 /* on first call, register the exit hook */
383 {
386 }
387
389
390 /* Check for conflicting GID */
391 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
392 {
394 if (strcmp(gxact->gid, gid) == 0)
395 {
398 errmsg("transaction identifier \"%s\" is already in use",
399 gid)));
400 }
401 }
402
403 /* Get a free gxact from the freelist */
407 errmsg("maximum number of prepared transactions reached"),
408 errhint("Increase \"max_prepared_transactions\" (currently %d).",
412
413 MarkAsPreparingGuts(gxact, fxid, gid, prepared_at, owner, databaseid);
414
415 gxact->ondisk = false;
416
417 /* And insert it into the active array */
420
422
423 return gxact;
424}
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:151
GlobalTransaction freeGXacts
Definition twophase.c:181
static bool twophaseExitRegistered
Definition twophase.c:200
static void AtProcExit_Twophase(int code, Datum arg)
Definition twophase.c:297
static void MarkAsPreparingGuts(GlobalTransaction gxact, FullTransactionId fxid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition twophase.c:436
#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 2509 of file twophase.c.

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

2667{
2668 FullTransactionId fxid =
2670
2672}
static void PrepareRedoRemoveFull(FullTransactionId fxid, bool giveWarning)
Definition twophase.c:2622

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

1969{
1972 TransactionId result = origNextXid;
1973 TransactionId *xids = NULL;
1974 int nxids = 0;
1975 int allocsize = 0;
1976 int i;
1977
1979 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1980 {
1981 TransactionId xid;
1982 char *buf;
1984
1985 Assert(gxact->inredo);
1986
1988 gxact->prepare_start_lsn,
1989 gxact->ondisk, false, true);
1990
1991 if (buf == NULL)
1992 continue;
1993
1994 /*
1995 * OK, we think this file is valid. Incorporate xid into the
1996 * running-minimum result.
1997 */
1998 xid = XidFromFullTransactionId(gxact->fxid);
1999 if (TransactionIdPrecedes(xid, result))
2000 result = xid;
2001
2002 if (xids_p)
2003 {
2004 if (nxids == allocsize)
2005 {
2006 if (nxids == 0)
2007 {
2008 allocsize = 10;
2009 xids = palloc(allocsize * sizeof(TransactionId));
2010 }
2011 else
2012 {
2013 allocsize = allocsize * 2;
2014 xids = repalloc(xids, allocsize * sizeof(TransactionId));
2015 }
2016 }
2017 xids[nxids++] = xid;
2018 }
2019
2020 pfree(buf);
2021 }
2023
2024 if (xids_p)
2025 {
2026 *xids_p = xids;
2027 *nxids_p = nxids;
2028 }
2029
2030 return result;
2031}
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:2189

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

Referenced by StartupXLOG(), and xlog_redo().

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )
extern

Definition at line 2085 of file twophase.c.

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

1907{
1908 DIR *cldir;
1909 struct dirent *clde;
1910
1913 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1914 {
1915 if (strlen(clde->d_name) == 16 &&
1916 strspn(clde->d_name, "0123456789ABCDEF") == 16)
1917 {
1918 FullTransactionId fxid;
1919 char *buf;
1920
1921 fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
1922
1924 true, false, false);
1925 if (buf == NULL)
1926 continue;
1927
1930 }
1931 }
1933 FreeDir(cldir);
1934}
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:2509

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

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

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

1470{
1471 char *buf;
1472 TwoPhaseFileHeader *hdr;
1473 bool result;
1474 FullTransactionId fxid;
1475
1477
1478 if (max_prepared_xacts <= 0)
1479 return false; /* nothing to do */
1480
1481 /* Read and validate file */
1482 fxid = AdjustToFullTransactionId(xid);
1483 buf = ReadTwoPhaseFile(fxid, true);
1484 if (buf == NULL)
1485 return false;
1486
1487 /* Check header also */
1488 hdr = (TwoPhaseFileHeader *) buf;
1489 result = TransactionIdEquals(hdr->xid, xid);
1490 pfree(buf);
1491
1492 return result;
1493}
#define TransactionIdIsValid(xid)
Definition transam.h:41
static FullTransactionId AdjustToFullTransactionId(TransactionId xid)
Definition twophase.c:945

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)
extern

Definition at line 1054 of file twophase.c.

1055{
1056 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
1059 TransactionId *children;
1062 xl_xact_stats_item *abortstats = NULL;
1065
1066 /* Initialize linked list */
1068 records.head->len = 0;
1069 records.head->next = NULL;
1070
1071 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1073
1075 records.num_chunks = 1;
1076
1077 records.total_len = 0;
1078
1079 /* Create header */
1080 hdr.magic = TWOPHASE_MAGIC;
1081 hdr.total_len = 0; /* EndPrepare will fill this in */
1082 hdr.xid = xid;
1083 hdr.database = proc->databaseId;
1084 hdr.prepared_at = gxact->prepared_at;
1085 hdr.owner = gxact->owner;
1086 hdr.nsubxacts = xactGetCommittedChildren(&children);
1089 hdr.ncommitstats =
1091 hdr.nabortstats =
1092 pgstat_get_transactional_drops(false, &abortstats);
1094 &hdr.initfileinval);
1095 hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1096 /* EndPrepare will fill the origin data, if necessary */
1098 hdr.origin_timestamp = 0;
1099
1100 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1101 save_state_data(gxact->gid, hdr.gidlen);
1102
1103 /*
1104 * Add the additional info about subxacts, deletable files and cache
1105 * invalidation messages.
1106 */
1107 if (hdr.nsubxacts > 0)
1108 {
1109 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1110 /* While we have the child-xact data, stuff it in the gxact too */
1111 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1112 }
1113 if (hdr.ncommitrels > 0)
1114 {
1117 }
1118 if (hdr.nabortrels > 0)
1119 {
1122 }
1123 if (hdr.ncommitstats > 0)
1124 {
1126 hdr.ncommitstats * sizeof(xl_xact_stats_item));
1128 }
1129 if (hdr.nabortstats > 0)
1130 {
1131 save_state_data(abortstats,
1132 hdr.nabortstats * sizeof(xl_xact_stats_item));
1133 pfree(abortstats);
1134 }
1135 if (hdr.ninvalmsgs > 0)
1136 {
1140 }
1141}
#define Max(x, y)
Definition c.h:1048
#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:193
struct StateFileChunk * next
Definition twophase.c:1004
uint32 total_len
Definition xact.h:356
uint32 magic
Definition xact.h:355
uint32 bytes_free
Definition twophase.c:1012
static void save_state_data(const void *data, uint32 len)
Definition twophase.c:1026
int xactGetCommittedChildren(TransactionId **ptr)
Definition xact.c:5813

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

926{
928
929 return GetPGProcByNumber(gxact->pgprocno);
930}
static GlobalTransaction TwoPhaseGetGXact(FullTransactionId fxid, bool lock_held)
Definition twophase.c:805

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

911{
913
914 return gxact->pgprocno;
915}

References fb(), and TwoPhaseGetGXact().

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

◆ TwoPhaseGetOldestXidInCommit()

TransactionId TwoPhaseGetOldestXidInCommit ( void  )
extern

Definition at line 2831 of file twophase.c.

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

860{
861 int i;
863
866
867 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
868 {
870 PGPROC *proc;
872
873 if (!gxact->valid)
874 continue;
875 proc = GetPGProcByNumber(gxact->pgprocno);
878 {
879 /*
880 * Startup process sets proc->vxid.procNumber to
881 * INVALID_PROC_NUMBER.
882 */
883 Assert(!gxact->inredo);
884
885 if (result != InvalidTransactionId)
886 {
887 *have_more = true;
888 break;
889 }
890 result = XidFromFullTransactionId(gxact->fxid);
891 }
892 }
893
895
896 return result;
897}
#define VirtualTransactionIdIsValid(vxid)
Definition lock.h:69
#define GET_VXID_FROM_PGPROC(vxid_dst, proc)
Definition lock.h:79
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition lock.h:73

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

Referenced by XactLockForVirtualXact().

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )
extern

Definition at line 256 of file twophase.c.

257{
258 bool found;
259
260 TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
262 &found);
264 {
266 int i;
267
268 Assert(!found);
271
272 /*
273 * Initialize the linked list of free GlobalTransactionData structs
274 */
276 ((char *) TwoPhaseState +
279 for (i = 0; i < max_prepared_xacts; i++)
280 {
281 /* insert into linked list */
284
285 /* associate it with a PGPROC assigned by InitProcGlobal */
287 }
288 }
289 else
290 Assert(found);
291}
bool IsUnderPostmaster
Definition globals.c:120
#define GetNumberFromPGProc(proc)
Definition proc.h:505
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:378
PGPROC * PreparedXactProcs
Definition proc.c:73
Size TwoPhaseShmemSize(void)
Definition twophase.c:240
struct GlobalTransactionData * GlobalTransaction
Definition twophase.h:26

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

Referenced by CreateOrAttachShmemStructs().

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )
extern

Definition at line 240 of file twophase.c.

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

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

Referenced by CalculateShmemSize(), and TwoPhaseShmemInit().

◆ TwoPhaseTransactionGid()

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

Definition at line 2749 of file twophase.c.

2750{
2751 Assert(OidIsValid(subid));
2752
2753 if (!TransactionIdIsValid(xid))
2754 ereport(ERROR,
2756 errmsg_internal("invalid two-phase transaction ID")));
2757
2758 snprintf(gid_res, szgid, "pg_gid_%u_%u", subid, xid);
2759}
#define OidIsValid(objectId)
Definition c.h:821
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