PostgreSQL Source Code git master
Typedefs | Functions | Variables
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

 

Functions

 
void  TwoPhaseShmemInit (void)
 
void  AtAbort_Twophase (void)
 
void  PostPrepare_Twophase (void)
 
 
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  CheckPointTwoPhase (XLogRecPtr redo_horizon)
 
void  FinishPreparedTransaction (const char *gid, bool isCommit)
 
void  PrepareRedoAdd (FullTransactionId fxid, char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
 
void  PrepareRedoRemove (TransactionId xid, bool giveWarning)
 
void  restoreTwoPhaseData (void)
 
bool  LookupGXact (const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
 
void  TwoPhaseTransactionGid (Oid subid, TransactionId xid, char *gid_res, int szgid)
 
bool  LookupGXactBySubid (Oid subid)
 
 

Variables

 

Typedef Documentation

GlobalTransaction

Definition at line 26 of file twophase.h.

Function Documentation

AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 306 of file twophase.c.

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

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon )

Definition at line 1822 of file twophase.c.

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

References buf, ereport, errmsg_plural(), fsync_fname(), GlobalTransactionData::fxid, i, GlobalTransactionData::inredo, InvalidXLogRecPtr, len, LOG, log_checkpoints, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_prepared_xacts, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, TwoPhaseStateData::prepXacts, RecreateTwoPhaseFile(), TWOPHASE_DIR, TwoPhaseState, GlobalTransactionData::valid, and XlogReadTwoPhaseData().

Referenced by CheckPointGuts().

EndPrepare()

void EndPrepare ( GlobalTransaction  gxact )

Definition at line 1145 of file twophase.c.

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

References Assert(), StateFileChunk::data, DELAY_CHKPT_START, PGPROC::delayChkptFlags, DoNotReplicateId, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xllist::head, InvalidRepOriginId, StateFileChunk::len, xl_xact_prepare::magic, MarkAsPrepared(), MaxAllocSize, MyLockedGxact, MyProc, StateFileChunk::next, xllist::num_chunks, xl_xact_prepare::origin_lsn, xl_xact_prepare::origin_timestamp, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, ProcLastRecPtr, records, RegisterTwoPhaseRecord(), replorigin_session_advance(), replorigin_session_origin, replorigin_session_origin_lsn, replorigin_session_origin_timestamp, START_CRIT_SECTION, SyncRepWaitForLSN(), xllist::tail, xllist::total_len, xl_xact_prepare::total_len, TWOPHASE_MAGIC, TWOPHASE_RM_END_ID, XLOG_INCLUDE_ORIGIN, XLOG_XACT_PREPARE, XLogBeginInsert(), XLogEnsureRecordSpace(), XLogFlush(), XLogInsert(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by PrepareTransaction().

FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1497 of file twophase.c.

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

References Assert(), AtEOXact_PgStat(), buf, DropRelationFiles(), GlobalTransactionData::fxid, GetPGProcByNumber, GetUserId(), xl_xact_prepare::gidlen, HOLD_INTERRUPTS, xl_xact_prepare::initfileinval, LockGXact(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, MyLockedGxact, xl_xact_prepare::nabortrels, xl_xact_prepare::nabortstats, xl_xact_prepare::ncommitrels, xl_xact_prepare::ncommitstats, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::pgprocno, pgstat_execute_transactional_drops(), PredicateLockTwoPhaseFinish(), GlobalTransactionData::prepare_start_lsn, ProcArrayRemove(), ProcessRecords(), ReadTwoPhaseFile(), RecordTransactionAbortPrepared(), RecordTransactionCommitPrepared(), RelationCacheInitFilePostInvalidate(), RelationCacheInitFilePreInvalidate(), RemoveGXact(), RemoveTwoPhaseFile(), RESUME_INTERRUPTS, SendSharedInvalidMessages(), TransactionIdEquals, TransactionIdLatest(), twophase_postabort_callbacks, twophase_postcommit_callbacks, GlobalTransactionData::valid, 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 
)

Definition at line 2688 of file twophase.c.

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

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

Referenced by apply_handle_rollback_prepared().

LookupGXactBySubid()

bool LookupGXactBySubid ( Oid  subid )

Definition at line 2797 of file twophase.c.

2798{
2799 bool found = false;
2800
2801 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
2802 for (int i = 0; i < TwoPhaseState->numPrepXacts; i++)
2803 {
2805
2806 /* Ignore not-yet-valid GIDs. */
2807 if (gxact->valid &&
2809 {
2810 found = true;
2811 break;
2812 }
2813 }
2814 LWLockRelease(TwoPhaseStateLock);
2815
2816 return found;
2817}
static bool IsTwoPhaseTransactionGidForSubid(Oid subid, char *gid)
Definition: twophase.c:2765

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

Referenced by AlterSubscription().

MarkAsPreparing()

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

Definition at line 361 of file twophase.c.

363{
364 GlobalTransaction gxact;
365 int i;
366
367 if (strlen(gid) >= GIDSIZE)
369 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
370 errmsg("transaction identifier \"%s\" is too long",
371 gid)));
372
373 /* fail immediately if feature is disabled */
374 if (max_prepared_xacts == 0)
376 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
377 errmsg("prepared transactions are disabled"),
378 errhint("Set \"max_prepared_transactions\" to a nonzero value.")));
379
380 /* on first call, register the exit hook */
382 {
385 }
386
387 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
388
389 /* Check for conflicting GID */
390 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
391 {
392 gxact = TwoPhaseState->prepXacts[i];
393 if (strcmp(gxact->gid, gid) == 0)
394 {
397 errmsg("transaction identifier \"%s\" is already in use",
398 gid)));
399 }
400 }
401
402 /* Get a free gxact from the freelist */
403 if (TwoPhaseState->freeGXacts == NULL)
405 (errcode(ERRCODE_OUT_OF_MEMORY),
406 errmsg("maximum number of prepared transactions reached"),
407 errhint("Increase \"max_prepared_transactions\" (currently %d).",
409 gxact = TwoPhaseState->freeGXacts;
410 TwoPhaseState->freeGXacts = gxact->next;
411
412 MarkAsPreparingGuts(gxact, fxid, gid, prepared_at, owner, databaseid);
413
414 gxact->ondisk = false;
415
416 /* And insert it into the active array */
419
420 LWLockRelease(TwoPhaseStateLock);
421
422 return gxact;
423}
int errhint(const char *fmt,...)
Definition: elog.c:1321
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:30
GlobalTransaction next
Definition: twophase.c:150
GlobalTransaction freeGXacts
Definition: twophase.c:180
static bool twophaseExitRegistered
Definition: twophase.c:199
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:296
static void MarkAsPreparingGuts(GlobalTransaction gxact, FullTransactionId fxid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:435
#define GIDSIZE
Definition: xact.h:31

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

Referenced by PrepareTransaction().

PostPrepare_Twophase()

void PostPrepare_Twophase ( void  )

Definition at line 346 of file twophase.c.

347{
348 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
350 LWLockRelease(TwoPhaseStateLock);
351
352 MyLockedGxact = NULL;
353}

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

PrepareRedoAdd()

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

Definition at line 2507 of file twophase.c.

2510{
2512 char *bufptr;
2513 const char *gid;
2514 GlobalTransaction gxact;
2515
2516 Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2518
2519 if (!FullTransactionIdIsValid(fxid))
2520 {
2523 hdr->xid);
2524 }
2525
2526 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2527 gid = (const char *) bufptr;
2528
2529 /*
2530 * Reserve the GID for the given transaction in the redo code path.
2531 *
2532 * This creates a gxact struct and puts it into the active array.
2533 *
2534 * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2535 * shared memory. Hence, we only fill up the bare minimum contents here.
2536 * The gxact also gets marked with gxact->inredo set to true to indicate
2537 * that it got added in the redo phase
2538 */
2539
2540 /*
2541 * In the event of a crash while a checkpoint was running, it may be
2542 * possible that some two-phase data found its way to disk while its
2543 * corresponding record needs to be replayed in the follow-up recovery. As
2544 * the 2PC data was on disk, it has already been restored at the beginning
2545 * of recovery with restoreTwoPhaseData(), so skip this record to avoid
2546 * duplicates in TwoPhaseState. If a consistent state has been reached,
2547 * the record is added to TwoPhaseState and it should have no
2548 * corresponding file in pg_twophase.
2549 */
2550 if (!XLogRecPtrIsInvalid(start_lsn))
2551 {
2552 char path[MAXPGPATH];
2553
2555 TwoPhaseFilePath(path, fxid);
2556
2557 if (access(path, F_OK) == 0)
2558 {
2560 (errmsg("could not recover two-phase state file for transaction %u",
2561 hdr->xid),
2562 errdetail("Two-phase state file has been found in WAL record %X/%08X, but this transaction has already been restored from disk.",
2563 LSN_FORMAT_ARGS(start_lsn))));
2564 return;
2565 }
2566
2567 if (errno != ENOENT)
2568 ereport(ERROR,
2570 errmsg("could not access file \"%s\": %m", path)));
2571 }
2572
2573 /* Get a free gxact from the freelist */
2574 if (TwoPhaseState->freeGXacts == NULL)
2575 ereport(ERROR,
2576 (errcode(ERRCODE_OUT_OF_MEMORY),
2577 errmsg("maximum number of prepared transactions reached"),
2578 errhint("Increase \"max_prepared_transactions\" (currently %d).",
2580 gxact = TwoPhaseState->freeGXacts;
2581 TwoPhaseState->freeGXacts = gxact->next;
2582
2583 gxact->prepared_at = hdr->prepared_at;
2584 gxact->prepare_start_lsn = start_lsn;
2585 gxact->prepare_end_lsn = end_lsn;
2586 gxact->fxid = fxid;
2587 gxact->owner = hdr->owner;
2589 gxact->valid = false;
2590 gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2591 gxact->inredo = true; /* yes, added in redo */
2592 strcpy(gxact->gid, gid);
2593
2594 /* And insert it into the active array */
2597
2598 if (origin_id != InvalidRepOriginId)
2599 {
2600 /* recover apply progress */
2601 replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2602 false /* backward */ , false /* WAL */ );
2603 }
2604
2605 elog(DEBUG2, "added 2PC data in shared memory for transaction %u of epoch %u",
2608}
int errcode_for_file_access(void)
Definition: elog.c:877
int errdetail(const char *fmt,...)
Definition: elog.c:1207
#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:2021
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:911
#define MAXPGPATH
short access
Definition: preproc-type.c:36
TimestampTz prepared_at
Definition: twophase.c:152
FullTransactionId nextXid
Definition: transam.h:220
Oid owner
Definition: xact.h:360
TimestampTz prepared_at
Definition: xact.h:359
static FullTransactionId FullTransactionIdFromAllowableAt(FullTransactionId nextFullXid, TransactionId xid)
Definition: transam.h:381
#define EpochFromFullTransactionId(x)
Definition: transam.h:47
#define FullTransactionIdIsValid(x)
Definition: transam.h:55
static int TwoPhaseFilePath(char *path, FullTransactionId fxid)
Definition: twophase.c:950
TransamVariablesData * TransamVariables
Definition: varsup.c:34
bool RecoveryInProgress(void)
Definition: xlog.c:6386
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:46
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
bool reachedConsistency
Definition: xlogrecovery.c:301
bool InRecovery
Definition: xlogutils.c:50

References Assert(), buf, DEBUG2, elog, EpochFromFullTransactionId, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), ERROR, TwoPhaseStateData::freeGXacts, FullTransactionIdFromAllowableAt(), FullTransactionIdIsValid, GlobalTransactionData::fxid, GlobalTransactionData::gid, InRecovery, GlobalTransactionData::inredo, INVALID_PROC_NUMBER, InvalidRepOriginId, GlobalTransactionData::locking_backend, LSN_FORMAT_ARGS, LW_EXCLUSIVE, LWLockHeldByMeInMode(), max_prepared_xacts, MAXALIGN, MAXPGPATH, GlobalTransactionData::next, TransamVariablesData::nextXid, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, xl_xact_prepare::origin_lsn, GlobalTransactionData::owner, xl_xact_prepare::owner, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, GlobalTransactionData::prepared_at, xl_xact_prepare::prepared_at, TwoPhaseStateData::prepXacts, reachedConsistency, RecoveryInProgress(), replorigin_advance(), TransamVariables, TwoPhaseFilePath(), TwoPhaseState, GlobalTransactionData::valid, WARNING, xl_xact_prepare::xid, XidFromFullTransactionId, and XLogRecPtrIsInvalid.

Referenced by restoreTwoPhaseData(), and xact_redo().

PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2664 of file twophase.c.

2665{
2666 FullTransactionId fxid =
2668
2669 PrepareRedoRemoveFull(fxid, giveWarning);
2670}
static void PrepareRedoRemoveFull(FullTransactionId fxid, bool giveWarning)
Definition: twophase.c:2620

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

Referenced by xact_redo().

PrescanPreparedTransactions()

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

Definition at line 1966 of file twophase.c.

1967{
1969 TransactionId origNextXid = XidFromFullTransactionId(nextXid);
1970 TransactionId result = origNextXid;
1971 TransactionId *xids = NULL;
1972 int nxids = 0;
1973 int allocsize = 0;
1974 int i;
1975
1976 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1977 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1978 {
1979 TransactionId xid;
1980 char *buf;
1982
1983 Assert(gxact->inredo);
1984
1986 gxact->prepare_start_lsn,
1987 gxact->ondisk, false, true);
1988
1989 if (buf == NULL)
1990 continue;
1991
1992 /*
1993 * OK, we think this file is valid. Incorporate xid into the
1994 * running-minimum result.
1995 */
1996 xid = XidFromFullTransactionId(gxact->fxid);
1997 if (TransactionIdPrecedes(xid, result))
1998 result = xid;
1999
2000 if (xids_p)
2001 {
2002 if (nxids == allocsize)
2003 {
2004 if (nxids == 0)
2005 {
2006 allocsize = 10;
2007 xids = palloc(allocsize * sizeof(TransactionId));
2008 }
2009 else
2010 {
2011 allocsize = allocsize * 2;
2012 xids = repalloc(xids, allocsize * sizeof(TransactionId));
2013 }
2014 }
2015 xids[nxids++] = xid;
2016 }
2017
2018 pfree(buf);
2019 }
2020 LWLockRelease(TwoPhaseStateLock);
2021
2022 if (xids_p)
2023 {
2024 *xids_p = xids;
2025 *nxids_p = nxids;
2026 }
2027
2028 return result;
2029}
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1610
void * palloc(Size size)
Definition: mcxt.c:1365
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
static char * ProcessTwoPhaseBuffer(FullTransactionId fxid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2187

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

Referenced by StartupXLOG(), and xlog_redo().

RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 2083 of file twophase.c.

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

References Assert(), buf, xl_xact_prepare::database, EpochFromFullTransactionId, ereport, errmsg(), GlobalTransactionData::fxid, xl_xact_prepare::gidlen, GXactLoadSubxactData(), i, InHotStandby, GlobalTransactionData::inredo, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MarkAsPrepared(), MarkAsPreparingGuts(), MAXALIGN, xl_xact_prepare::nabortrels, xl_xact_prepare::nabortstats, xl_xact_prepare::ncommitrels, xl_xact_prepare::ncommitstats, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, xl_xact_prepare::owner, pfree(), PostPrepare_Twophase(), GlobalTransactionData::prepare_start_lsn, xl_xact_prepare::prepared_at, TwoPhaseStateData::prepXacts, ProcessRecords(), ProcessTwoPhaseBuffer(), StandbyReleaseLockTree(), TransactionIdEquals, twophase_recover_callbacks, TwoPhaseState, xl_xact_prepare::xid, and XidFromFullTransactionId.

Referenced by StartupXLOG().

restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1904 of file twophase.c.

1905{
1906 DIR *cldir;
1907 struct dirent *clde;
1908
1909 LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1910 cldir = AllocateDir(TWOPHASE_DIR);
1911 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1912 {
1913 if (strlen(clde->d_name) == 16 &&
1914 strspn(clde->d_name, "0123456789ABCDEF") == 16)
1915 {
1916 FullTransactionId fxid;
1917 char *buf;
1918
1919 fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
1920
1922 true, false, false);
1923 if (buf == NULL)
1924 continue;
1925
1928 }
1929 }
1930 LWLockRelease(TwoPhaseStateLock);
1931 FreeDir(cldir);
1932}
int FreeDir(DIR *dir)
Definition: fd.c:3022
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2904
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2970
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
static FullTransactionId FullTransactionIdFromU64(uint64 value)
Definition: transam.h:81
void PrepareRedoAdd(FullTransactionId fxid, char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2507

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

Referenced by StartupXLOG().

StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 2045 of file twophase.c.

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

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

Referenced by StartupXLOG(), and xlog_redo().

StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid )

Definition at line 1467 of file twophase.c.

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

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

StartPrepare()

void StartPrepare ( GlobalTransaction  gxact )

Definition at line 1052 of file twophase.c.

1053{
1054 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
1057 TransactionId *children;
1058 RelFileLocator *commitrels;
1059 RelFileLocator *abortrels;
1060 xl_xact_stats_item *abortstats = NULL;
1061 xl_xact_stats_item *commitstats = NULL;
1062 SharedInvalidationMessage *invalmsgs;
1063
1064 /* Initialize linked list */
1066 records.head->len = 0;
1067 records.head->next = NULL;
1068
1069 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1071
1073 records.num_chunks = 1;
1074
1075 records.total_len = 0;
1076
1077 /* Create header */
1078 hdr.magic = TWOPHASE_MAGIC;
1079 hdr.total_len = 0; /* EndPrepare will fill this in */
1080 hdr.xid = xid;
1081 hdr.database = proc->databaseId;
1082 hdr.prepared_at = gxact->prepared_at;
1083 hdr.owner = gxact->owner;
1084 hdr.nsubxacts = xactGetCommittedChildren(&children);
1085 hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1086 hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1087 hdr.ncommitstats =
1088 pgstat_get_transactional_drops(true, &commitstats);
1089 hdr.nabortstats =
1090 pgstat_get_transactional_drops(false, &abortstats);
1092 &hdr.initfileinval);
1093 hdr.gidlen = strlen(gxact->gid) + 1; /* Include '0円' */
1094 /* EndPrepare will fill the origin data, if necessary */
1096 hdr.origin_timestamp = 0;
1097
1098 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1099 save_state_data(gxact->gid, hdr.gidlen);
1100
1101 /*
1102 * Add the additional info about subxacts, deletable files and cache
1103 * invalidation messages.
1104 */
1105 if (hdr.nsubxacts > 0)
1106 {
1107 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1108 /* While we have the child-xact data, stuff it in the gxact too */
1109 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1110 }
1111 if (hdr.ncommitrels > 0)
1112 {
1113 save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileLocator));
1114 pfree(commitrels);
1115 }
1116 if (hdr.nabortrels > 0)
1117 {
1118 save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileLocator));
1119 pfree(abortrels);
1120 }
1121 if (hdr.ncommitstats > 0)
1122 {
1123 save_state_data(commitstats,
1124 hdr.ncommitstats * sizeof(xl_xact_stats_item));
1125 pfree(commitstats);
1126 }
1127 if (hdr.nabortstats > 0)
1128 {
1129 save_state_data(abortstats,
1130 hdr.nabortstats * sizeof(xl_xact_stats_item));
1131 pfree(abortstats);
1132 }
1133 if (hdr.ninvalmsgs > 0)
1134 {
1135 save_state_data(invalmsgs,
1137 pfree(invalmsgs);
1138 }
1139}
#define Max(x, y)
Definition: c.h:997
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:1012
void * palloc0(Size size)
Definition: mcxt.c:1395
int pgstat_get_transactional_drops(bool isCommit, xl_xact_stats_item **items)
Definition: pgstat_xact.c:272
int smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
Definition: storage.c:893
Oid databaseId
Definition: proc.h:224
uint32 bytes_free
Definition: twophase.c:1010
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:1024
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5802

References xllist::bytes_free, StateFileChunk::data, xl_xact_prepare::database, PGPROC::databaseId, GlobalTransactionData::fxid, GetPGProcByNumber, GlobalTransactionData::gid, xl_xact_prepare::gidlen, GXactLoadSubxactData(), xllist::head, xl_xact_prepare::initfileinval, InvalidXLogRecPtr, StateFileChunk::len, xl_xact_prepare::magic, Max, xl_xact_prepare::nabortrels, xl_xact_prepare::nabortstats, xl_xact_prepare::ncommitrels, xl_xact_prepare::ncommitstats, StateFileChunk::next, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, xllist::num_chunks, xl_xact_prepare::origin_lsn, xl_xact_prepare::origin_timestamp, GlobalTransactionData::owner, xl_xact_prepare::owner, palloc(), palloc0(), pfree(), GlobalTransactionData::pgprocno, pgstat_get_transactional_drops(), GlobalTransactionData::prepared_at, xl_xact_prepare::prepared_at, records, save_state_data(), smgrGetPendingDeletes(), xllist::tail, xllist::total_len, xl_xact_prepare::total_len, TWOPHASE_MAGIC, xactGetCommittedChildren(), xactGetCommittedInvalidationMessages(), xl_xact_prepare::xid, and XidFromFullTransactionId.

Referenced by PrepareTransaction().

TwoPhaseGetDummyProc()

PGPROC * TwoPhaseGetDummyProc ( FullTransactionId  fxid,
bool  lock_held 
)

Definition at line 923 of file twophase.c.

924{
925 GlobalTransaction gxact = TwoPhaseGetGXact(fxid, lock_held);
926
927 return GetPGProcByNumber(gxact->pgprocno);
928}
static GlobalTransaction TwoPhaseGetGXact(FullTransactionId fxid, bool lock_held)
Definition: twophase.c:804

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

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

TwoPhaseGetDummyProcNumber()

int TwoPhaseGetDummyProcNumber ( FullTransactionId  fxid,
bool  lock_held 
)

Definition at line 908 of file twophase.c.

909{
910 GlobalTransaction gxact = TwoPhaseGetGXact(fxid, lock_held);
911
912 return gxact->pgprocno;
913}

References GlobalTransactionData::pgprocno, and TwoPhaseGetGXact().

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

TwoPhaseGetOldestXidInCommit()

TransactionId TwoPhaseGetOldestXidInCommit ( void  )

Definition at line 2829 of file twophase.c.

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

References PGPROC::databaseId, DELAY_CHKPT_IN_COMMIT, PGPROC::delayChkptFlags, GlobalTransactionData::fxid, GetPGProcByNumber, i, INVALID_PROC_NUMBER, InvalidTransactionId, GlobalTransactionData::locking_backend, LW_SHARED, LWLockAcquire(), LWLockRelease(), MyDatabaseId, TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, TransactionIdIsValid, TransactionIdPrecedes(), TwoPhaseState, GlobalTransactionData::valid, and XidFromFullTransactionId.

Referenced by ProcessStandbyPSRequestMessage().

TwoPhaseGetXidByVirtualXID()

TransactionId TwoPhaseGetXidByVirtualXID ( VirtualTransactionId  vxid,
bool *  have_more 
)

Definition at line 857 of file twophase.c.

859{
860 int i;
862
864 LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
865
866 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
867 {
869 PGPROC *proc;
870 VirtualTransactionId proc_vxid;
871
872 if (!gxact->valid)
873 continue;
874 proc = GetPGProcByNumber(gxact->pgprocno);
875 GET_VXID_FROM_PGPROC(proc_vxid, *proc);
876 if (VirtualTransactionIdEquals(vxid, proc_vxid))
877 {
878 /*
879 * Startup process sets proc->vxid.procNumber to
880 * INVALID_PROC_NUMBER.
881 */
882 Assert(!gxact->inredo);
883
884 if (result != InvalidTransactionId)
885 {
886 *have_more = true;
887 break;
888 }
889 result = XidFromFullTransactionId(gxact->fxid);
890 }
891 }
892
893 LWLockRelease(TwoPhaseStateLock);
894
895 return result;
896}
#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(), GlobalTransactionData::fxid, GET_VXID_FROM_PGPROC, GetPGProcByNumber, i, GlobalTransactionData::inredo, InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, GlobalTransactionData::pgprocno, TwoPhaseStateData::prepXacts, TwoPhaseState, GlobalTransactionData::valid, VirtualTransactionIdEquals, VirtualTransactionIdIsValid, and XidFromFullTransactionId.

Referenced by XactLockForVirtualXact().

TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 255 of file twophase.c.

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

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

Referenced by CreateOrAttachShmemStructs().

TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 239 of file twophase.c.

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

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

Referenced by CalculateShmemSize(), and TwoPhaseShmemInit().

TwoPhaseTransactionGid()

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

Definition at line 2747 of file twophase.c.

2748{
2749 Assert(OidIsValid(subid));
2750
2751 if (!TransactionIdIsValid(xid))
2752 ereport(ERROR,
2753 (errcode(ERRCODE_PROTOCOL_VIOLATION),
2754 errmsg_internal("invalid two-phase transaction ID")));
2755
2756 snprintf(gid_res, szgid, "pg_gid_%u_%u", subid, xid);
2757}
#define OidIsValid(objectId)
Definition: c.h:774
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1161
#define snprintf
Definition: port.h:239

References Assert(), ereport, errcode(), errmsg_internal(), ERROR, 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

PGDLLIMPORT int max_prepared_xacts
extern

Definition at line 116 of file twophase.c.

Referenced by CheckPointTwoPhase(), CheckRequiredParameterValues(), FastPathLockShmemSize(), GetLockConflicts(), GetSerializableTransactionSnapshotInt(), InitControlFile(), InitProcGlobal(), MarkAsPreparing(), PGProcShmemSize(), predicatelock_twophase_recover(), PredicateLockShmemInit(), PredicateLockShmemSize(), PrepareRedoAdd(), StandbyTransactionIdIsPrepared(), TwoPhaseShmemInit(), TwoPhaseShmemSize(), XactLockForVirtualXact(), and XLogReportParameters().

AltStyle によって変換されたページ (->オリジナル) /