PostgreSQL Source Code git master
Loading...
Searching...
No Matches
twophase.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "access/commit_ts.h"
#include "access/htup_details.h"
#include "access/subtrans.h"
#include "access/transam.h"
#include "access/twophase.h"
#include "access/twophase_rmgr.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "access/xlogreader.h"
#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "catalog/pg_type.h"
#include "catalog/storage.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "pgstat.h"
#include "replication/origin.h"
#include "replication/syncrep.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/md.h"
#include "storage/predicate.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/builtins.h"
#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/timestamp.h"
#include "utils/wait_event.h"
Include dependency graph for twophase.c:

Go to the source code of this file.

Data Structures

struct  GlobalTransactionData
 
struct  TwoPhaseStateData
 
struct  Working_State
 
struct  TwoPhaseRecordOnDisk
 
struct  StateFileChunk
 
struct  xllist
 

Macros

#define TWOPHASE_DIR   "pg_twophase"
 
#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */
 

Typedefs

typedef struct GlobalTransactionData GlobalTransactionData
 
typedef struct TwoPhaseStateData TwoPhaseStateData
 
typedef xl_xact_prepare TwoPhaseFileHeader
 
typedef struct TwoPhaseRecordOnDisk TwoPhaseRecordOnDisk
 
typedef struct StateFileChunk StateFileChunk
 

Functions

static void PrepareRedoRemoveFull (FullTransactionId fxid, bool giveWarning)
 
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)
 
static void RecordTransactionAbortPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileLocator *rels, int nstats, xl_xact_stats_item *stats, const char *gid)
 
static void ProcessRecords (char *bufptr, FullTransactionId fxid, const TwoPhaseCallback callbacks[])
 
static void RemoveGXact (GlobalTransaction gxact)
 
static void XlogReadTwoPhaseData (XLogRecPtr lsn, char **buf, int *len)
 
static charProcessTwoPhaseBuffer (FullTransactionId fxid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
 
static void MarkAsPreparingGuts (GlobalTransaction gxact, FullTransactionId fxid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
static void RemoveTwoPhaseFile (FullTransactionId fxid, bool giveWarning)
 
static void RecreateTwoPhaseFile (FullTransactionId fxid, void *content, int len)
 
Size TwoPhaseShmemSize (void)
 
void TwoPhaseShmemInit (void)
 
static void AtProcExit_Twophase (int code, Datum arg)
 
void AtAbort_Twophase (void)
 
void PostPrepare_Twophase (void)
 
GlobalTransaction MarkAsPreparing (FullTransactionId fxid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
static void GXactLoadSubxactData (GlobalTransaction gxact, int nsubxacts, TransactionId *children)
 
static void MarkAsPrepared (GlobalTransaction gxact, bool lock_held)
 
static GlobalTransaction LockGXact (const char *gid, Oid user)
 
static int GetPreparedTransactionList (GlobalTransaction *gxacts)
 
Datum pg_prepared_xact (PG_FUNCTION_ARGS)
 
static GlobalTransaction TwoPhaseGetGXact (FullTransactionId fxid, bool lock_held)
 
TransactionId TwoPhaseGetXidByVirtualXID (VirtualTransactionId vxid, bool *have_more)
 
ProcNumber TwoPhaseGetDummyProcNumber (FullTransactionId fxid, bool lock_held)
 
PGPROCTwoPhaseGetDummyProc (FullTransactionId fxid, bool lock_held)
 
static FullTransactionId AdjustToFullTransactionId (TransactionId xid)
 
static int TwoPhaseFilePath (char *path, FullTransactionId fxid)
 
static void save_state_data (const void *data, uint32 len)
 
void StartPrepare (GlobalTransaction gxact)
 
void EndPrepare (GlobalTransaction gxact)
 
void RegisterTwoPhaseRecord (TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
 
static charReadTwoPhaseFile (FullTransactionId fxid, bool missing_ok)
 
bool StandbyTransactionIdIsPrepared (TransactionId xid)
 
void FinishPreparedTransaction (const char *gid, bool isCommit)
 
void CheckPointTwoPhase (XLogRecPtr redo_horizon)
 
void restoreTwoPhaseData (void)
 
TransactionId PrescanPreparedTransactions (TransactionId **xids_p, int *nxids_p)
 
void StandbyRecoverPreparedTransactions (void)
 
void RecoverPreparedTransactions (void)
 
void PrepareRedoAdd (FullTransactionId fxid, char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, ReplOriginId origin_id)
 
void PrepareRedoRemove (TransactionId xid, bool giveWarning)
 
bool LookupGXact (const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
 
void TwoPhaseTransactionGid (Oid subid, TransactionId xid, char *gid_res, int szgid)
 
static bool IsTwoPhaseTransactionGidForSubid (Oid subid, char *gid)
 
bool LookupGXactBySubid (Oid subid)
 
TransactionId TwoPhaseGetOldestXidInCommit (void)
 

Variables

int max_prepared_xacts = 0
 
static TwoPhaseStateDataTwoPhaseState
 
static GlobalTransaction MyLockedGxact = NULL
 
static bool twophaseExitRegistered = false
 
static struct xllist records
 

Macro Definition Documentation

◆ TWOPHASE_DIR

#define TWOPHASE_DIR   "pg_twophase"

Definition at line 114 of file twophase.c.

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */

Definition at line 979 of file twophase.c.

Typedef Documentation

◆ GlobalTransactionData

◆ StateFileChunk

◆ TwoPhaseFileHeader

◆ TwoPhaseRecordOnDisk

◆ TwoPhaseStateData

Function Documentation

◆ AdjustToFullTransactionId()

static FullTransactionId AdjustToFullTransactionId ( TransactionId  xid)
inlinestatic

Definition at line 946 of file twophase.c.

947{
950}
#define Assert(condition)
Definition c.h:945
static FullTransactionId FullTransactionIdFromAllowableAt(FullTransactionId nextFullXid, TransactionId xid)
Definition transam.h:443
#define TransactionIdIsValid(xid)
Definition transam.h:41
FullTransactionId ReadNextFullTransactionId(void)
Definition varsup.c:292

References Assert, FullTransactionIdFromAllowableAt(), ReadNextFullTransactionId(), and TransactionIdIsValid.

Referenced by StandbyTransactionIdIsPrepared().

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

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:1153
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1770
@ LW_EXCLUSIVE
Definition lwlock.h:104
static int fb(int x)
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
ProcNumber locking_backend
Definition twophase.c: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().

◆ AtProcExit_Twophase()

static void AtProcExit_Twophase ( int  code,
Datum  arg 
)
static

Definition at line 297 of file twophase.c.

298{
299 /* same logic as abort */
301}
void AtAbort_Twophase(void)
Definition twophase.c:307

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1825 of file twophase.c.

1826{
1827 int i;
1828 int serialized_xacts = 0;
1829
1830 if (max_prepared_xacts <= 0)
1831 return; /* nothing to do */
1832
1834
1835 /*
1836 * We are expecting there to be zero GXACTs that need to be copied to
1837 * disk, so we perform all I/O while holding TwoPhaseStateLock for
1838 * simplicity. This prevents any new xacts from preparing while this
1839 * occurs, which shouldn't be a problem since the presence of long-lived
1840 * prepared xacts indicates the transaction manager isn't active.
1841 *
1842 * It's also possible to move I/O out of the lock, but on every error we
1843 * should check whether somebody committed our transaction in different
1844 * backend. Let's leave this optimization for future, if somebody will
1845 * spot that this place cause bottleneck.
1846 *
1847 * Note that it isn't possible for there to be a GXACT with a
1848 * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1849 * because of the efforts with delayChkptFlags.
1850 */
1852 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1853 {
1854 /*
1855 * Note that we are using gxact not PGPROC so this works in recovery
1856 * also
1857 */
1859
1860 if ((gxact->valid || gxact->inredo) &&
1861 !gxact->ondisk &&
1862 gxact->prepare_end_lsn <= redo_horizon)
1863 {
1864 char *buf;
1865 int len;
1866
1867 XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1869 gxact->ondisk = true;
1870 gxact->prepare_start_lsn = InvalidXLogRecPtr;
1871 gxact->prepare_end_lsn = InvalidXLogRecPtr;
1872 pfree(buf);
1874 }
1875 }
1877
1878 /*
1879 * Flush unconditionally the parent directory to make any information
1880 * durable on disk. Two-phase files could have been removed and those
1881 * removals need to be made persistent as well as any files newly created
1882 * previously since the last checkpoint.
1883 */
1885
1887
1889 ereport(LOG,
1890 (errmsg_plural("%u two-phase state file was written "
1891 "for a long-running prepared transaction",
1892 "%u two-phase state files were written "
1893 "for long-running prepared transactions",
1896}
#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:105
void pfree(void *pointer)
Definition mcxt.c:1616
const void size_t len
static char buf[DEFAULT_XLOG_SEG_SIZE]
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition twophase.c:187
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition twophase.c:1415
#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:1745
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)

Definition at line 1148 of file twophase.c.

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

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

Referenced by PrepareTransaction().

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char gid,
bool  isCommit 
)

Definition at line 1500 of file twophase.c.

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

◆ GetPreparedTransactionList()

static int GetPreparedTransactionList ( GlobalTransaction gxacts)
static

Definition at line 671 of file twophase.c.

672{
673 GlobalTransaction array;
674 int num;
675 int i;
676
678
679 if (TwoPhaseState->numPrepXacts == 0)
680 {
682
683 *gxacts = NULL;
684 return 0;
685 }
686
689 *gxacts = array;
690 for (i = 0; i < num; i++)
691 memcpy(array + i, TwoPhaseState->prepXacts[i],
692 sizeof(GlobalTransactionData));
693
695
696 return num;
697}
#define palloc_array(type, count)
Definition fe_memutils.h:76

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

Referenced by pg_prepared_xact().

◆ GXactLoadSubxactData()

static void GXactLoadSubxactData ( GlobalTransaction  gxact,
int  nsubxacts,
TransactionId children 
)
static

Definition at line 509 of file twophase.c.

511{
512 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
513
514 /* We need no extra lock since the GXACT isn't valid yet */
515 if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
516 {
517 proc->subxidStatus.overflowed = true;
518 nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
519 }
520 if (nsubxacts > 0)
521 {
522 memcpy(proc->subxids.xids, children,
523 nsubxacts * sizeof(TransactionId));
524 proc->subxidStatus.count = nsubxacts;
525 }
526}
#define PGPROC_MAX_CACHED_SUBXIDS
Definition proc.h:42
XidCacheStatus subxidStatus
Definition proc.h:246
struct XidCache subxids
Definition proc.h:248
bool overflowed
Definition proc.h:49
uint8 count
Definition proc.h:47
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition proc.h:54

References XidCacheStatus::count, fb(), GetPGProcByNumber, XidCacheStatus::overflowed, PGPROC_MAX_CACHED_SUBXIDS, PGPROC::subxids, PGPROC::subxidStatus, and XidCache::xids.

Referenced by RecoverPreparedTransactions(), and StartPrepare().

◆ IsTwoPhaseTransactionGidForSubid()

static bool IsTwoPhaseTransactionGidForSubid ( Oid  subid,
char gid 
)
static

Definition at line 2768 of file twophase.c.

2769{
2770 int ret;
2773 char gid_tmp[GIDSIZE];
2774
2775 /* Extract the subid and xid from the given GID */
2776 ret = sscanf(gid, "pg_gid_%u_%u", &subid_from_gid, &xid_from_gid);
2777
2778 /*
2779 * Check that the given GID has expected format, and at least the subid
2780 * matches.
2781 */
2782 if (ret != 2 || subid != subid_from_gid)
2783 return false;
2784
2785 /*
2786 * Reconstruct a temporary GID based on the subid and xid extracted from
2787 * the given GID and check whether the temporary GID and the given GID
2788 * match.
2789 */
2791
2792 return strcmp(gid, gid_tmp) == 0;
2793}
unsigned int Oid
void TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid_res, int szgid)
Definition twophase.c:2750
#define GIDSIZE
Definition xact.h:31

References fb(), GIDSIZE, and TwoPhaseTransactionGid().

Referenced by LookupGXactBySubid().

◆ LockGXact()

static GlobalTransaction LockGXact ( const char gid,
Oid  user 
)
static

Definition at line 557 of file twophase.c.

558{
559 int i;
560
561 /* on first call, register the exit hook */
563 {
566 }
567
569
570 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
571 {
573 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
574
575 /* Ignore not-yet-valid GIDs */
576 if (!gxact->valid)
577 continue;
578 if (strcmp(gxact->gid, gid) != 0)
579 continue;
580
581 /* Found it, but has someone else got it locked? */
582 if (gxact->locking_backend != INVALID_PROC_NUMBER)
585 errmsg("prepared transaction with identifier \"%s\" is busy",
586 gid)));
587
588 if (user != gxact->owner && !superuser_arg(user))
591 errmsg("permission denied to finish prepared transaction"),
592 errhint("Must be superuser or the user that prepared the transaction.")));
593
594 /*
595 * Note: it probably would be possible to allow committing from
596 * another database; but at the moment NOTIFY is known not to work and
597 * there may be some other issues as well. Hence disallow until
598 * someone gets motivated to make it work.
599 */
600 if (MyDatabaseId != proc->databaseId)
603 errmsg("prepared transaction belongs to another database"),
604 errhint("Connect to the database where the transaction was prepared to finish it.")));
605
606 /* OK for me to lock it */
607 gxact->locking_backend = MyProcNumber;
609
611
612 return gxact;
613 }
614
616
619 errmsg("prepared transaction with identifier \"%s\" does not exist",
620 gid)));
621
622 /* NOTREACHED */
623 return NULL;
624}
int errhint(const char *fmt,...) pg_attribute_printf(1
ProcNumber MyProcNumber
Definition globals.c:90
Oid MyDatabaseId
Definition globals.c:94
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344
static char * user
Definition pg_regress.c:119
Oid databaseId
Definition proc.h:200
bool superuser_arg(Oid roleid)
Definition superuser.c:57
static bool twophaseExitRegistered
Definition twophase.c:200
static void AtProcExit_Twophase(int code, Datum arg)
Definition twophase.c:297

References AtProcExit_Twophase(), before_shmem_exit(), PGPROC::databaseId, ereport, errcode(), errhint(), errmsg, ERROR, fb(), GetPGProcByNumber, i, INVALID_PROC_NUMBER, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyDatabaseId, MyLockedGxact, MyProcNumber, TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, superuser_arg(), twophaseExitRegistered, TwoPhaseState, and user.

Referenced by FinishPreparedTransaction().

◆ LookupGXact()

bool LookupGXact ( const char gid,
XLogRecPtr  prepare_end_lsn,
TimestampTz  origin_prepare_timestamp 
)

Definition at line 2691 of file twophase.c.

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

Definition at line 2800 of file twophase.c.

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

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

Referenced by AlterSubscription().

◆ MarkAsPrepared()

static void MarkAsPrepared ( GlobalTransaction  gxact,
bool  lock_held 
)
static

Definition at line 535 of file twophase.c.

536{
537 /* Lock here may be overkill, but I'm not convinced of that ... */
538 if (!lock_held)
540 Assert(!gxact->valid);
541 gxact->valid = true;
542 if (!lock_held)
544
545 /*
546 * Put it into the global ProcArray so TransactionIdIsInProgress considers
547 * the XID as still running.
548 */
550}
void ProcArrayAdd(PGPROC *proc)
Definition procarray.c:472

References Assert, fb(), GetPGProcByNumber, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), and ProcArrayAdd().

Referenced by EndPrepare(), and RecoverPreparedTransactions().

◆ MarkAsPreparing()

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

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}
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
GlobalTransaction next
Definition twophase.c:151
GlobalTransaction freeGXacts
Definition twophase.c:181
static void MarkAsPreparingGuts(GlobalTransaction gxact, FullTransactionId fxid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition twophase.c:436

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().

◆ MarkAsPreparingGuts()

static void MarkAsPreparingGuts ( GlobalTransaction  gxact,
FullTransactionId  fxid,
const char gid,
TimestampTz  prepared_at,
Oid  owner,
Oid  databaseid 
)
static

Definition at line 436 of file twophase.c.

439{
440 PGPROC *proc;
441 int i;
443
445
446 Assert(gxact != NULL);
447 proc = GetPGProcByNumber(gxact->pgprocno);
448
449 /* Initialize the PGPROC entry */
450 MemSet(proc, 0, sizeof(PGPROC));
453 {
454 /* clone VXID, for TwoPhaseGetXidByVirtualXID() to find */
455 proc->vxid.lxid = MyProc->vxid.lxid;
457 }
458 else
459 {
461 /* GetLockConflicts() uses this to specify a wait on the XID */
462 proc->vxid.lxid = xid;
464 }
465 proc->xid = xid;
467 proc->delayChkptFlags = 0;
468 proc->statusFlags = 0;
469 proc->pid = 0;
470 proc->databaseId = databaseid;
471 proc->roleId = owner;
473 proc->backendType = B_INVALID;
475 proc->lwWaitMode = 0;
476 proc->waitLock = NULL;
478 proc->waitProcLock = NULL;
479 pg_atomic_init_u64(&proc->waitStart, 0);
480 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
481 dlist_init(&proc->myProcLocks[i]);
482 /* subxid data must be filled later by GXactLoadSubxactData */
483 proc->subxidStatus.overflowed = false;
484 proc->subxidStatus.count = 0;
485
486 gxact->prepared_at = prepared_at;
487 gxact->fxid = fxid;
488 gxact->owner = owner;
489 gxact->locking_backend = MyProcNumber;
490 gxact->valid = false;
491 gxact->inredo = false;
492 strcpy(gxact->gid, gid);
493
494 /*
495 * Remember that we have this GlobalTransaction entry locked for us. If we
496 * abort after this, we must release it.
497 */
499}
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition atomics.h:453
#define MemSet(start, val, len)
Definition c.h:1109
bool IsPostmasterEnvironment
Definition globals.c:119
static void dlist_init(dlist_head *head)
Definition ilist.h:314
static void dlist_node_init(dlist_node *node)
Definition ilist.h:325
#define LocalTransactionIdIsValid(lxid)
Definition lock.h:69
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1932
@ LW_WS_NOT_WAITING
Definition lwlock.h:30
#define NUM_LOCK_PARTITIONS
Definition lwlock.h:87
#define AmStartupProcess()
Definition miscadmin.h:390
@ B_INVALID
Definition miscadmin.h:339
#define InvalidOid
@ PROC_WAIT_STATUS_OK
Definition proc.h:144
TransactionId xmin
Definition proc.h:241
LocalTransactionId lxid
Definition proc.h:230
PROCLOCK * waitProcLock
Definition proc.h:305
uint8 lwWaitMode
Definition proc.h:283
BackendType backendType
Definition proc.h:197
uint8 statusFlags
Definition proc.h:209
pg_atomic_uint64 waitStart
Definition proc.h:310
ProcNumber procNumber
Definition proc.h:225
int pid
Definition proc.h:196
LOCK * waitLock
Definition proc.h:303
TransactionId xid
Definition proc.h:236
dlist_node waitLink
Definition proc.h:304
struct PGPROC::@134 vxid
dlist_head myProcLocks[NUM_LOCK_PARTITIONS]
Definition proc.h:320
Oid roleId
Definition proc.h:201
ProcWaitStatus waitStatus
Definition proc.h:313
Oid tempNamespaceId
Definition proc.h:203
uint8 lwWaiting
Definition proc.h:282
#define InvalidTransactionId
Definition transam.h:31

References AmStartupProcess, Assert, B_INVALID, PGPROC::backendType, XidCacheStatus::count, PGPROC::databaseId, PGPROC::delayChkptFlags, dlist_init(), dlist_node_init(), fb(), GetPGProcByNumber, i, INVALID_PROC_NUMBER, InvalidOid, InvalidTransactionId, IsPostmasterEnvironment, LocalTransactionIdIsValid, LW_EXCLUSIVE, LW_WS_NOT_WAITING, LWLockHeldByMeInMode(), PGPROC::lwWaiting, PGPROC::lwWaitMode, PGPROC::lxid, MemSet, MyLockedGxact, MyProc, PGPROC::myProcLocks, MyProcNumber, NUM_LOCK_PARTITIONS, XidCacheStatus::overflowed, pg_atomic_init_u64(), PGPROC::pid, PROC_WAIT_STATUS_OK, PGPROC::procNumber, PGPROC::roleId, PGPROC::statusFlags, PGPROC::subxidStatus, PGPROC::tempNamespaceId, PGPROC::vxid, PGPROC::waitLink, PGPROC::waitLock, PGPROC::waitProcLock, PGPROC::waitStart, PGPROC::waitStatus, PGPROC::xid, XidFromFullTransactionId, and PGPROC::xmin.

Referenced by MarkAsPreparing(), and RecoverPreparedTransactions().

◆ pg_prepared_xact()

Datum pg_prepared_xact ( PG_FUNCTION_ARGS  )

Definition at line 716 of file twophase.c.

717{
719 Working_State *status;
720
721 if (SRF_IS_FIRSTCALL())
722 {
723 TupleDesc tupdesc;
724 MemoryContext oldcontext;
725
726 /* create a function context for cross-call persistence */
728
729 /*
730 * Switch to memory context appropriate for multiple function calls
731 */
732 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
733
734 /* build tupdesc for result tuples */
735 /* this had better match pg_prepared_xacts view in system_views.sql */
736 tupdesc = CreateTemplateTupleDesc(5);
737 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
738 XIDOID, -1, 0);
739 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
740 TEXTOID, -1, 0);
741 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
742 TIMESTAMPTZOID, -1, 0);
743 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
744 OIDOID, -1, 0);
745 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
746 OIDOID, -1, 0);
747
748 TupleDescFinalize(tupdesc);
749 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
750
751 /*
752 * Collect all the 2PC status information that we will format and send
753 * out as a result set.
754 */
756 funcctx->user_fctx = status;
757
758 status->ngxacts = GetPreparedTransactionList(&status->array);
759 status->currIdx = 0;
760
761 MemoryContextSwitchTo(oldcontext);
762 }
763
765 status = (Working_State *) funcctx->user_fctx;
766
767 while (status->array != NULL && status->currIdx < status->ngxacts)
768 {
769 GlobalTransaction gxact = &status->array[status->currIdx++];
770 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
771 Datum values[5] = {0};
772 bool nulls[5] = {0};
773 HeapTuple tuple;
774 Datum result;
775
776 if (!gxact->valid)
777 continue;
778
779 /*
780 * Form tuple with appropriate data.
781 */
782
783 values[0] = TransactionIdGetDatum(proc->xid);
785 values[2] = TimestampTzGetDatum(gxact->prepared_at);
786 values[3] = ObjectIdGetDatum(gxact->owner);
788
789 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
790 result = HeapTupleGetDatum(tuple);
791 SRF_RETURN_NEXT(funcctx, result);
792 }
793
795}
int16 AttrNumber
Definition attnum.h:21
static Datum values[MAXATTR]
Definition bootstrap.c:188
#define CStringGetTextDatum(s)
Definition builtins.h:98
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
#define palloc_object(type)
Definition fe_memutils.h:74
#define SRF_IS_FIRSTCALL()
Definition funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition funcapi.h:308
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition funcapi.h:306
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition funcapi.h:230
#define SRF_RETURN_DONE(_funcctx)
Definition funcapi.h:328
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition heaptuple.c:1037
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
static Datum TransactionIdGetDatum(TransactionId X)
Definition postgres.h:292
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
GlobalTransaction array
Definition twophase.c:703
TupleDesc CreateTemplateTupleDesc(int natts)
Definition tupdesc.c:165
void TupleDescFinalize(TupleDesc tupdesc)
Definition tupdesc.c:511
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition tupdesc.c:900
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition twophase.c:671
static Datum TimestampTzGetDatum(TimestampTz X)
Definition timestamp.h:52

References Working_State::array, BlessTupleDesc(), CreateTemplateTupleDesc(), CStringGetTextDatum, Working_State::currIdx, PGPROC::databaseId, fb(), GetPGProcByNumber, GetPreparedTransactionList(), heap_form_tuple(), HeapTupleGetDatum(), MemoryContextSwitchTo(), Working_State::ngxacts, ObjectIdGetDatum(), palloc_object, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TimestampTzGetDatum(), TransactionIdGetDatum(), TupleDescFinalize(), TupleDescInitEntry(), values, and PGPROC::xid.

◆ PostPrepare_Twophase()

◆ PrepareRedoAdd()

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

Definition at line 2510 of file twophase.c.

2513{
2515 char *bufptr;
2516 const char *gid;
2518
2521
2522 if (!FullTransactionIdIsValid(fxid))
2523 {
2526 hdr->xid);
2527 }
2528
2529 bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2530 gid = (const char *) bufptr;
2531
2532 /*
2533 * Reserve the GID for the given transaction in the redo code path.
2534 *
2535 * This creates a gxact struct and puts it into the active array.
2536 *
2537 * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2538 * shared memory. Hence, we only fill up the bare minimum contents here.
2539 * The gxact also gets marked with gxact->inredo set to true to indicate
2540 * that it got added in the redo phase
2541 */
2542
2543 /*
2544 * In the event of a crash while a checkpoint was running, it may be
2545 * possible that some two-phase data found its way to disk while its
2546 * corresponding record needs to be replayed in the follow-up recovery. As
2547 * the 2PC data was on disk, it has already been restored at the beginning
2548 * of recovery with restoreTwoPhaseData(), so skip this record to avoid
2549 * duplicates in TwoPhaseState. If a consistent state has been reached,
2550 * the record is added to TwoPhaseState and it should have no
2551 * corresponding file in pg_twophase.
2552 */
2553 if (XLogRecPtrIsValid(start_lsn))
2554 {
2555 char path[MAXPGPATH];
2556
2558 TwoPhaseFilePath(path, fxid);
2559
2560 if (access(path, F_OK) == 0)
2561 {
2563 (errmsg("could not recover two-phase state file for transaction %u",
2564 hdr->xid),
2565 errdetail("Two-phase state file has been found in WAL record %X/%08X, but this transaction has already been restored from disk.",
2566 LSN_FORMAT_ARGS(start_lsn))));
2567 return;
2568 }
2569
2570 if (errno != ENOENT)
2571 ereport(ERROR,
2573 errmsg("could not access file \"%s\": %m", path)));
2574 }
2575
2576 /* Get a free gxact from the freelist */
2578 ereport(ERROR,
2580 errmsg("maximum number of prepared transactions reached"),
2581 errhint("Increase \"max_prepared_transactions\" (currently %d).",
2585
2587 gxact->prepare_start_lsn = start_lsn;
2588 gxact->prepare_end_lsn = end_lsn;
2589 gxact->fxid = fxid;
2590 gxact->owner = hdr->owner;
2591 gxact->locking_backend = INVALID_PROC_NUMBER;
2592 gxact->valid = false;
2593 gxact->ondisk = !XLogRecPtrIsValid(start_lsn);
2594 gxact->inredo = true; /* yes, added in redo */
2595 strcpy(gxact->gid, gid);
2596
2597 /* And insert it into the active array */
2600
2601 if (origin_id != InvalidReplOriginId)
2602 {
2603 /* recover apply progress */
2604 replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2605 false /* backward */ , false /* WAL */ );
2606 }
2607
2608 elog(DEBUG2, "added 2PC data in shared memory for transaction %u of epoch %u",
2611}
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
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
#define EpochFromFullTransactionId(x)
Definition transam.h:47
#define FullTransactionIdIsValid(x)
Definition transam.h:55
static int TwoPhaseFilePath(char *path, FullTransactionId fxid)
Definition twophase.c:953
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 
)

Definition at line 2667 of file twophase.c.

2668{
2669 FullTransactionId fxid =
2671
2673}
static void PrepareRedoRemoveFull(FullTransactionId fxid, bool giveWarning)
Definition twophase.c:2623

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

Referenced by xact_redo().

◆ PrepareRedoRemoveFull()

static void PrepareRedoRemoveFull ( FullTransactionId  fxid,
bool  giveWarning 
)
static

Definition at line 2623 of file twophase.c.

2624{
2626 int i;
2627 bool found = false;
2628
2631
2632 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2633 {
2635
2636 if (FullTransactionIdEquals(gxact->fxid, fxid))
2637 {
2638 Assert(gxact->inredo);
2639 found = true;
2640 break;
2641 }
2642 }
2643
2644 /*
2645 * Just leave if there is nothing, this is expected during WAL replay.
2646 */
2647 if (!found)
2648 return;
2649
2650 /*
2651 * And now we can clean up any files we may have left.
2652 */
2653 elog(DEBUG2, "removing 2PC data for transaction %u of epoch %u ",
2656
2657 if (gxact->ondisk)
2659
2661}
#define FullTransactionIdEquals(a, b)
Definition transam.h:50

References Assert, DEBUG2, elog, EpochFromFullTransactionId, fb(), FullTransactionIdEquals, i, LW_EXCLUSIVE, LWLockHeldByMeInMode(), TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, RecoveryInProgress(), RemoveGXact(), RemoveTwoPhaseFile(), TwoPhaseState, and XidFromFullTransactionId.

Referenced by PrepareRedoRemove(), and ProcessTwoPhaseBuffer().

◆ PrescanPreparedTransactions()

TransactionId PrescanPreparedTransactions ( TransactionId **  xids_p,
int nxids_p 
)

Definition at line 1969 of file twophase.c.

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

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().

◆ ProcessRecords()

static void ProcessRecords ( char bufptr,
FullTransactionId  fxid,
const TwoPhaseCallback  callbacks[] 
)
static

Definition at line 1695 of file twophase.c.

1697{
1698 for (;;)
1699 {
1700 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1701
1702 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1703 if (record->rmid == TWOPHASE_RM_END_ID)
1704 break;
1705
1706 bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1707
1708 if (callbacks[record->rmid] != NULL)
1709 callbacks[record->rmid] (fxid, record->info, bufptr, record->len);
1710
1711 bufptr += MAXALIGN(record->len);
1712 }
1713}
TwoPhaseRmgrId rmid
Definition twophase.c:992
#define TWOPHASE_RM_MAX_ID

References Assert, fb(), TwoPhaseRecordOnDisk::info, TwoPhaseRecordOnDisk::len, MAXALIGN, TwoPhaseRecordOnDisk::rmid, TWOPHASE_RM_END_ID, and TWOPHASE_RM_MAX_ID.

Referenced by FinishPreparedTransaction(), and RecoverPreparedTransactions().

◆ ProcessTwoPhaseBuffer()

static char * ProcessTwoPhaseBuffer ( FullTransactionId  fxid,
XLogRecPtr  prepare_start_lsn,
bool  fromdisk,
bool  setParent,
bool  setNextXid 
)
static

Definition at line 2190 of file twophase.c.

2194{
2196 TransactionId *subxids;
2197 char *buf;
2198 TwoPhaseFileHeader *hdr;
2199 int i;
2200
2202
2203 if (!fromdisk)
2204 Assert(XLogRecPtrIsValid(prepare_start_lsn));
2205
2206 /* Already processed? */
2209 {
2210 if (fromdisk)
2211 {
2213 (errmsg("removing stale two-phase state file for transaction %u of epoch %u",
2216 RemoveTwoPhaseFile(fxid, true);
2217 }
2218 else
2219 {
2221 (errmsg("removing stale two-phase state from memory for transaction %u of epoch %u",
2224 PrepareRedoRemoveFull(fxid, true);
2225 }
2226 return NULL;
2227 }
2228
2229 /* Reject XID if too new */
2230 if (FullTransactionIdFollowsOrEquals(fxid, nextXid))
2231 {
2232 if (fromdisk)
2233 {
2235 (errmsg("removing future two-phase state file for transaction %u of epoch %u",
2238 RemoveTwoPhaseFile(fxid, true);
2239 }
2240 else
2241 {
2243 (errmsg("removing future two-phase state from memory for transaction %u of epoch %u",
2246 PrepareRedoRemoveFull(fxid, true);
2247 }
2248 return NULL;
2249 }
2250
2251 if (fromdisk)
2252 {
2253 /* Read and validate file */
2254 buf = ReadTwoPhaseFile(fxid, false);
2255 }
2256 else
2257 {
2258 /* Read xlog data */
2259 XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2260 }
2261
2262 /* Deconstruct header */
2263 hdr = (TwoPhaseFileHeader *) buf;
2265 {
2266 if (fromdisk)
2267 ereport(ERROR,
2269 errmsg("corrupted two-phase state file for transaction %u of epoch %u",
2272 else
2273 ereport(ERROR,
2275 errmsg("corrupted two-phase state in memory for transaction %u of epoch %u",
2278 }
2279
2280 /*
2281 * Examine subtransaction XIDs ... they should all follow main XID, and
2282 * they may force us to advance nextXid.
2283 */
2284 subxids = (TransactionId *) (buf +
2285 MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2286 MAXALIGN(hdr->gidlen));
2287 for (i = 0; i < hdr->nsubxacts; i++)
2288 {
2289 TransactionId subxid = subxids[i];
2290
2292
2293 /* update nextXid if needed */
2294 if (setNextXid)
2296
2297 if (setParent)
2299 }
2300
2301 return buf;
2302}
#define ERRCODE_DATA_CORRUPTED
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition subtrans.c:85
bool TransactionIdDidCommit(TransactionId transactionId)
Definition transam.c:126
bool TransactionIdDidAbort(TransactionId transactionId)
Definition transam.c:188
static bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition transam.h:297
#define FullTransactionIdFollowsOrEquals(a, b)
Definition transam.h:54
void AdvanceNextFullTransactionIdPastXid(TransactionId xid)
Definition varsup.c:308

References AdvanceNextFullTransactionIdPastXid(), Assert, buf, EpochFromFullTransactionId, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg, ERROR, fb(), FullTransactionIdFollowsOrEquals, xl_xact_prepare::gidlen, i, LW_EXCLUSIVE, LWLockHeldByMeInMode(), MAXALIGN, TransamVariablesData::nextXid, xl_xact_prepare::nsubxacts, PrepareRedoRemoveFull(), ReadTwoPhaseFile(), RemoveTwoPhaseFile(), SubTransSetParent(), TransactionIdDidAbort(), TransactionIdDidCommit(), TransactionIdEquals, TransactionIdFollows(), TransamVariables, WARNING, xl_xact_prepare::xid, XidFromFullTransactionId, XlogReadTwoPhaseData(), and XLogRecPtrIsValid.

Referenced by PrescanPreparedTransactions(), RecoverPreparedTransactions(), restoreTwoPhaseData(), and StandbyRecoverPreparedTransactions().

◆ ReadTwoPhaseFile()

static char * ReadTwoPhaseFile ( FullTransactionId  fxid,
bool  missing_ok 
)
static

Definition at line 1298 of file twophase.c.

1299{
1300 char path[MAXPGPATH];
1301 char *buf;
1302 TwoPhaseFileHeader *hdr;
1303 int fd;
1304 struct stat stat;
1307 file_crc;
1308 int r;
1309
1310 TwoPhaseFilePath(path, fxid);
1311
1313 if (fd < 0)
1314 {
1315 if (missing_ok && errno == ENOENT)
1316 return NULL;
1317
1318 ereport(ERROR,
1320 errmsg("could not open file \"%s\": %m", path)));
1321 }
1322
1323 /*
1324 * Check file length. We can determine a lower bound pretty easily. We
1325 * set an upper bound to avoid palloc() failure on a corrupt file, though
1326 * we can't guarantee that we won't get an out of memory error anyway,
1327 * even on a valid file.
1328 */
1329 if (fstat(fd, &stat))
1330 ereport(ERROR,
1332 errmsg("could not stat file \"%s\": %m", path)));
1333
1334 if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1336 sizeof(pg_crc32c)) ||
1338 ereport(ERROR,
1340 errmsg_plural("incorrect size of file \"%s\": %lld byte",
1341 "incorrect size of file \"%s\": %lld bytes",
1342 (long long int) stat.st_size, path,
1343 (long long int) stat.st_size)));
1344
1345 crc_offset = stat.st_size - sizeof(pg_crc32c);
1347 ereport(ERROR,
1349 errmsg("incorrect alignment of CRC offset for file \"%s\"",
1350 path)));
1351
1352 /*
1353 * OK, slurp in the file.
1354 */
1355 buf = (char *) palloc(stat.st_size);
1356
1358 r = read(fd, buf, stat.st_size);
1359 if (r != stat.st_size)
1360 {
1361 if (r < 0)
1362 ereport(ERROR,
1364 errmsg("could not read file \"%s\": %m", path)));
1365 else
1366 ereport(ERROR,
1367 (errmsg("could not read file \"%s\": read %d of %lld",
1368 path, r, (long long int) stat.st_size)));
1369 }
1370
1372
1373 if (CloseTransientFile(fd) != 0)
1374 ereport(ERROR,
1376 errmsg("could not close file \"%s\": %m", path)));
1377
1378 hdr = (TwoPhaseFileHeader *) buf;
1379 if (hdr->magic != TWOPHASE_MAGIC)
1380 ereport(ERROR,
1382 errmsg("invalid magic number stored in file \"%s\"",
1383 path)));
1384
1385 if (hdr->total_len != stat.st_size)
1386 ereport(ERROR,
1388 errmsg("invalid size stored in file \"%s\"",
1389 path)));
1390
1394
1395 file_crc = *((pg_crc32c *) (buf + crc_offset));
1396
1398 ereport(ERROR,
1400 errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
1401 path)));
1402
1403 return buf;
1404}
#define PG_BINARY
Definition c.h:1376
uint32_t uint32
Definition c.h:618
int CloseTransientFile(int fd)
Definition fd.c:2855
int OpenTransientFile(const char *fileName, int fileFlags)
Definition fd.c:2678
#define read(a, b, c)
Definition win32.h:13
#define COMP_CRC32C(crc, data, len)
Definition pg_crc32c.h:153
#define EQ_CRC32C(c1, c2)
Definition pg_crc32c.h:42
#define INIT_CRC32C(crc)
Definition pg_crc32c.h:41
#define FIN_CRC32C(crc)
Definition pg_crc32c.h:158
static int fd(const char *x, int i)
__int64 st_size
Definition win32_port.h:263
uint32 total_len
Definition xact.h:356
uint32 magic
Definition xact.h:355
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition wait_event.h:69
static void pgstat_report_wait_end(void)
Definition wait_event.h:85
#define fstat
Definition win32_port.h:73

References buf, CloseTransientFile(), COMP_CRC32C, EQ_CRC32C, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errcode_for_file_access(), errmsg, errmsg_plural(), ERROR, fb(), fd(), FIN_CRC32C, fstat, INIT_CRC32C, xl_xact_prepare::magic, MAXALIGN, MaxAllocSize, MAXPGPATH, OpenTransientFile(), palloc(), PG_BINARY, pgstat_report_wait_end(), pgstat_report_wait_start(), read, stat::st_size, xl_xact_prepare::total_len, TWOPHASE_MAGIC, and TwoPhaseFilePath().

Referenced by FinishPreparedTransaction(), LookupGXact(), ProcessTwoPhaseBuffer(), and StandbyTransactionIdIsPrepared().

◆ RecordTransactionAbortPrepared()

static void RecordTransactionAbortPrepared ( TransactionId  xid,
int  nchildren,
TransactionId children,
int  nrels,
RelFileLocator rels,
int  nstats,
xl_xact_stats_item stats,
const char gid 
)
static

Definition at line 2435 of file twophase.c.

2443{
2445 bool replorigin;
2446
2447 /*
2448 * Are we using the replication origins feature? Or, in other words, are
2449 * we replaying remote actions?
2450 */
2453
2454 /*
2455 * Catch the scenario where we aborted partway through
2456 * RecordTransactionCommitPrepared ...
2457 */
2458 if (TransactionIdDidCommit(xid))
2459 elog(PANIC, "cannot abort transaction %u, it was already committed",
2460 xid);
2461
2463
2464 /*
2465 * Emit the XLOG commit record. Note that we mark 2PC aborts as
2466 * potentially having AccessExclusiveLocks since we don't know whether or
2467 * not they do.
2468 */
2470 nchildren, children,
2471 nrels, rels,
2472 nstats, stats,
2474 xid, gid);
2475
2476 if (replorigin)
2477 /* Move LSNs forward for this replication origin */
2480
2481 /* Always flush, since we're about to remove the 2PC state file */
2483
2484 /*
2485 * Mark the transaction aborted in clog. This is not absolutely necessary
2486 * but we may as well do it while we are here.
2487 */
2488 TransactionIdAbortTree(xid, nchildren, children);
2489
2491
2492 /*
2493 * Wait for synchronous replication, if required.
2494 *
2495 * Note that at this stage we have marked clog, but still show as running
2496 * in the procarray and continue to hold locks.
2497 */
2498 SyncRepWaitForLSN(recptr, false);
2499}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
#define PANIC
Definition elog.h:42
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition transam.c:270
int MyXactFlags
Definition xact.c:138
XLogRecPtr XactLogAbortRecord(TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileLocator *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition xact.c:6009
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition xact.h:109
XLogRecPtr XactLastRecEnd
Definition xlog.c:258
uint64 XLogRecPtr
Definition xlogdefs.h:21

References DoNotReplicateId, elog, END_CRIT_SECTION, fb(), GetCurrentTimestamp(), InvalidReplOriginId, MyXactFlags, ReplOriginXactState::origin, ReplOriginXactState::origin_lsn, PANIC, replorigin_session_advance(), replorigin_xact_state, START_CRIT_SECTION, SyncRepWaitForLSN(), TransactionIdAbortTree(), TransactionIdDidCommit(), XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK, XactLastRecEnd, XactLogAbortRecord(), and XLogFlush().

Referenced by FinishPreparedTransaction().

◆ RecordTransactionCommitPrepared()

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 
)
static

Definition at line 2316 of file twophase.c.

2327{
2330 bool replorigin;
2331
2332 /*
2333 * Are we using the replication origins feature? Or, in other words, are
2334 * we replaying remote actions?
2335 */
2338
2339 /* Load the injection point before entering the critical section */
2340 INJECTION_POINT_LOAD("commit-after-delay-checkpoint");
2341
2343
2344 /* See notes in RecordTransactionCommit */
2347
2348 INJECTION_POINT_CACHED("commit-after-delay-checkpoint", NULL);
2349
2350 /*
2351 * Ensures the DELAY_CHKPT_IN_COMMIT flag write is globally visible before
2352 * commit time is written.
2353 */
2355
2356 /*
2357 * Note it is important to set committs value after marking ourselves as
2358 * in the commit critical section (DELAY_CHKPT_IN_COMMIT). This is because
2359 * we want to ensure all transactions that have acquired commit timestamp
2360 * are finished before we allow the logical replication client to advance
2361 * its xid which is used to hold back dead rows for conflict detection.
2362 * See comments atop worker.c.
2363 */
2365
2366 /*
2367 * Emit the XLOG commit record. Note that we mark 2PC commits as
2368 * potentially having AccessExclusiveLocks since we don't know whether or
2369 * not they do.
2370 */
2372 nchildren, children, nrels, rels,
2373 nstats, stats,
2374 ninvalmsgs, invalmsgs,
2375 initfileinval,
2377 xid, gid);
2378
2379
2380 if (replorigin)
2381 /* Move LSNs forward for this replication origin */
2384
2385 /*
2386 * Record commit timestamp. The value comes from plain commit timestamp
2387 * if replorigin is not enabled, or replorigin already set a value for us
2388 * in replorigin_xact_state.origin_timestamp otherwise.
2389 *
2390 * We don't need to WAL-log anything here, as the commit record written
2391 * above already contains the data.
2392 */
2395
2399
2400 /*
2401 * We don't currently try to sleep before flush here ... nor is there any
2402 * support for async commit of a prepared xact (the very idea is probably
2403 * a contradiction)
2404 */
2405
2406 /* Flush XLOG to disk */
2408
2409 /* Mark the transaction committed in pg_xact */
2410 TransactionIdCommitTree(xid, nchildren, children);
2411
2412 /* Checkpoint can proceed now */
2414
2416
2417 /*
2418 * Wait for synchronous replication, if required.
2419 *
2420 * Note that at this stage we have marked clog, but still show as running
2421 * in the procarray and continue to hold locks.
2422 */
2424}
#define pg_write_barrier()
Definition atomics.h:155
void TransactionTreeSetCommitTsData(TransactionId xid, int nsubxids, TransactionId *subxids, TimestampTz timestamp, ReplOriginId nodeid)
Definition commit_ts.c:140
int64 TimestampTz
Definition timestamp.h:39
#define INJECTION_POINT_CACHED(name, arg)
#define INJECTION_POINT_LOAD(name)
#define DELAY_CHKPT_IN_COMMIT
Definition proc.h:140
void TransactionIdCommitTree(TransactionId xid, int nxids, TransactionId *xids)
Definition transam.c:240
XLogRecPtr XactLogCommitRecord(TimestampTz commit_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileLocator *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, int nmsgs, SharedInvalidationMessage *msgs, bool relcacheInval, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition xact.c:5837

References Assert, DELAY_CHKPT_IN_COMMIT, PGPROC::delayChkptFlags, DoNotReplicateId, END_CRIT_SECTION, fb(), GetCurrentTimestamp(), INJECTION_POINT_CACHED, INJECTION_POINT_LOAD, InvalidReplOriginId, MyProc, MyXactFlags, ReplOriginXactState::origin, ReplOriginXactState::origin_lsn, ReplOriginXactState::origin_timestamp, pg_write_barrier, replorigin_session_advance(), replorigin_xact_state, START_CRIT_SECTION, SyncRepWaitForLSN(), TransactionIdCommitTree(), TransactionTreeSetCommitTsData(), XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK, XactLastRecEnd, XactLogCommitRecord(), and XLogFlush().

Referenced by FinishPreparedTransaction().

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 2086 of file twophase.c.

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

◆ RecreateTwoPhaseFile()

static void RecreateTwoPhaseFile ( FullTransactionId  fxid,
void content,
int  len 
)
static

Definition at line 1745 of file twophase.c.

1746{
1747 char path[MAXPGPATH];
1749 int fd;
1750
1751 /* Recompute CRC */
1753 COMP_CRC32C(statefile_crc, content, len);
1755
1756 TwoPhaseFilePath(path, fxid);
1757
1758 fd = OpenTransientFile(path,
1760 if (fd < 0)
1761 ereport(ERROR,
1763 errmsg("could not recreate file \"%s\": %m", path)));
1764
1765 /* Write content and CRC */
1766 errno = 0;
1768 if (write(fd, content, len) != len)
1769 {
1770 /* if write didn't set errno, assume problem is no disk space */
1771 if (errno == 0)
1772 errno = ENOSPC;
1773 ereport(ERROR,
1775 errmsg("could not write file \"%s\": %m", path)));
1776 }
1777 if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1778 {
1779 /* if write didn't set errno, assume problem is no disk space */
1780 if (errno == 0)
1781 errno = ENOSPC;
1782 ereport(ERROR,
1784 errmsg("could not write file \"%s\": %m", path)));
1785 }
1787
1788 /*
1789 * We must fsync the file because the end-of-replay checkpoint will not do
1790 * so, there being no GXACT in shared memory yet to tell it to.
1791 */
1793 if (pg_fsync(fd) != 0)
1794 ereport(ERROR,
1796 errmsg("could not fsync file \"%s\": %m", path)));
1798
1799 if (CloseTransientFile(fd) != 0)
1800 ereport(ERROR,
1802 errmsg("could not close file \"%s\": %m", path)));
1803}
int pg_fsync(int fd)
Definition fd.c:390
#define write(a, b, c)
Definition win32.h:14

References CloseTransientFile(), COMP_CRC32C, ereport, errcode_for_file_access(), errmsg, ERROR, fb(), fd(), FIN_CRC32C, INIT_CRC32C, len, MAXPGPATH, OpenTransientFile(), PG_BINARY, pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), TwoPhaseFilePath(), and write.

Referenced by CheckPointTwoPhase().

◆ RegisterTwoPhaseRecord()

void RegisterTwoPhaseRecord ( TwoPhaseRmgrId  rmid,
uint16  info,
const void data,
uint32  len 
)

Definition at line 1274 of file twophase.c.

1276{
1277 TwoPhaseRecordOnDisk record;
1278
1279 record.rmid = rmid;
1280 record.info = info;
1281 record.len = len;
1282 save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1283 if (len > 0)
1285}
const void * data
static void save_state_data(const void *data, uint32 len)
Definition twophase.c:1027

References data, TwoPhaseRecordOnDisk::info, TwoPhaseRecordOnDisk::len, len, TwoPhaseRecordOnDisk::rmid, and save_state_data().

Referenced by AtPrepare_Locks(), AtPrepare_MultiXact(), AtPrepare_PgStat_Relations(), AtPrepare_PredicateLocks(), and EndPrepare().

◆ RemoveGXact()

static void RemoveGXact ( GlobalTransaction  gxact)
static

Definition at line 633 of file twophase.c.

634{
635 int i;
636
638
639 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
640 {
642 {
643 /* remove from the active array */
646
647 /* and put it back in the freelist */
650
651 return;
652 }
653 }
654
655 elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
656}

References Assert, elog, ERROR, fb(), TwoPhaseStateData::freeGXacts, i, LW_EXCLUSIVE, LWLockHeldByMeInMode(), GlobalTransactionData::next, TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, and TwoPhaseState.

Referenced by AtAbort_Twophase(), FinishPreparedTransaction(), and PrepareRedoRemoveFull().

◆ RemoveTwoPhaseFile()

static void RemoveTwoPhaseFile ( FullTransactionId  fxid,
bool  giveWarning 
)
static

Definition at line 1726 of file twophase.c.

1727{
1728 char path[MAXPGPATH];
1729
1730 TwoPhaseFilePath(path, fxid);
1731 if (unlink(path))
1732 if (errno != ENOENT || giveWarning)
1735 errmsg("could not remove file \"%s\": %m", path)));
1736}

References ereport, errcode_for_file_access(), errmsg, fb(), MAXPGPATH, TwoPhaseFilePath(), and WARNING.

Referenced by FinishPreparedTransaction(), PrepareRedoRemoveFull(), and ProcessTwoPhaseBuffer().

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1907 of file twophase.c.

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

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

Referenced by StartupXLOG().

◆ save_state_data()

static void save_state_data ( const void data,
uint32  len 
)
static

Definition at line 1027 of file twophase.c.

1028{
1030
1032 {
1035 records.tail->len = 0;
1036 records.tail->next = NULL;
1038
1039 records.bytes_free = Max(padlen, 512);
1041 }
1042
1044 records.tail->len += padlen;
1047}
#define Max(x, y)
Definition c.h:1087
#define palloc0_object(type)
Definition fe_memutils.h:75
struct StateFileChunk * next
Definition twophase.c:1005
uint32 bytes_free
Definition twophase.c:1013

References xllist::bytes_free, StateFileChunk::data, data, fb(), StateFileChunk::len, len, Max, MAXALIGN, StateFileChunk::next, xllist::num_chunks, palloc(), palloc0_object, records, xllist::tail, and xllist::total_len.

Referenced by RegisterTwoPhaseRecord(), and StartPrepare().

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 2048 of file twophase.c.

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

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)

Definition at line 1470 of file twophase.c.

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

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)

Definition at line 1055 of file twophase.c.

1056{
1057 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
1060 TransactionId *children;
1063 xl_xact_stats_item *abortstats = NULL;
1066
1067 /* Initialize linked list */
1069 records.head->len = 0;
1070 records.head->next = NULL;
1071
1072 records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1074
1076 records.num_chunks = 1;
1077
1078 records.total_len = 0;
1079
1080 /* Create header */
1081 hdr.magic = TWOPHASE_MAGIC;
1082 hdr.total_len = 0; /* EndPrepare will fill this in */
1083 hdr.xid = xid;
1084 hdr.database = proc->databaseId;
1085 hdr.prepared_at = gxact->prepared_at;
1086 hdr.owner = gxact->owner;
1087 hdr.nsubxacts = xactGetCommittedChildren(&children);
1090 hdr.ncommitstats =
1092 hdr.nabortstats =
1093 pgstat_get_transactional_drops(false, &abortstats);
1095 &hdr.initfileinval);
1096 hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1097 /* EndPrepare will fill the origin data, if necessary */
1099 hdr.origin_timestamp = 0;
1100
1101 save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1102 save_state_data(gxact->gid, hdr.gidlen);
1103
1104 /*
1105 * Add the additional info about subxacts, deletable files and cache
1106 * invalidation messages.
1107 */
1108 if (hdr.nsubxacts > 0)
1109 {
1110 save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1111 /* While we have the child-xact data, stuff it in the gxact too */
1112 GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1113 }
1114 if (hdr.ncommitrels > 0)
1115 {
1118 }
1119 if (hdr.nabortrels > 0)
1120 {
1123 }
1124 if (hdr.ncommitstats > 0)
1125 {
1127 hdr.ncommitstats * sizeof(xl_xact_stats_item));
1129 }
1130 if (hdr.nabortstats > 0)
1131 {
1132 save_state_data(abortstats,
1133 hdr.nabortstats * sizeof(xl_xact_stats_item));
1134 pfree(abortstats);
1135 }
1136 if (hdr.ninvalmsgs > 0)
1137 {
1141 }
1142}
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
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().

◆ TwoPhaseFilePath()

static int TwoPhaseFilePath ( char path,
FullTransactionId  fxid 
)
inlinestatic

Definition at line 953 of file twophase.c.

954{
955 return snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X%08X",
958}
#define snprintf
Definition port.h:260

References EpochFromFullTransactionId, MAXPGPATH, snprintf, TWOPHASE_DIR, and XidFromFullTransactionId.

Referenced by PrepareRedoAdd(), ReadTwoPhaseFile(), RecreateTwoPhaseFile(), and RemoveTwoPhaseFile().

◆ TwoPhaseGetDummyProc()

PGPROC * TwoPhaseGetDummyProc ( FullTransactionId  fxid,
bool  lock_held 
)

Definition at line 926 of file twophase.c.

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

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

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

◆ TwoPhaseGetDummyProcNumber()

ProcNumber TwoPhaseGetDummyProcNumber ( FullTransactionId  fxid,
bool  lock_held 
)

Definition at line 911 of file twophase.c.

912{
914
915 return gxact->pgprocno;
916}

References fb(), and TwoPhaseGetGXact().

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

◆ TwoPhaseGetGXact()

static GlobalTransaction TwoPhaseGetGXact ( FullTransactionId  fxid,
bool  lock_held 
)
static

Definition at line 806 of file twophase.c.

807{
808 GlobalTransaction result = NULL;
809 int i;
810
813
815
816 /*
817 * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
818 * repeatedly for the same XID. We can save work with a simple cache.
819 */
821 return cached_gxact;
822
823 if (!lock_held)
825
826 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
827 {
829
830 if (FullTransactionIdEquals(gxact->fxid, fxid))
831 {
832 result = gxact;
833 break;
834 }
835 }
836
837 if (!lock_held)
839
840 if (result == NULL) /* should not happen */
841 elog(ERROR, "failed to find GlobalTransaction for xid %u",
843
844 cached_fxid = fxid;
845 cached_gxact = result;
846
847 return result;
848}
bool LWLockHeldByMe(LWLock *lock)
Definition lwlock.c:1888

References Assert, elog, ERROR, fb(), FullTransactionIdEquals, i, InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockHeldByMe(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, TwoPhaseState, and XidFromFullTransactionId.

Referenced by TwoPhaseGetDummyProc(), and TwoPhaseGetDummyProcNumber().

◆ TwoPhaseGetOldestXidInCommit()

TransactionId TwoPhaseGetOldestXidInCommit ( void  )

Definition at line 2832 of file twophase.c.

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

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 
)

Definition at line 859 of file twophase.c.

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

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

Referenced by XactLockForVirtualXact().

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 256 of file twophase.c.

257{
258 bool found;
259
260 TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
262 &found);
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:504
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:380
PGPROC * PreparedXactProcs
Definition proc.c:74
Size TwoPhaseShmemSize(void)
Definition twophase.c:240
struct GlobalTransactionData * GlobalTransaction
Definition twophase.h:31

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  )

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:691
Size add_size(Size s1, Size s2)
Definition shmem.c:455
Size mul_size(Size s1, Size s2)
Definition shmem.c:470

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 
)

Definition at line 2750 of file twophase.c.

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

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().

◆ XlogReadTwoPhaseData()

static void XlogReadTwoPhaseData ( XLogRecPtr  lsn,
char **  buf,
int len 
)
static

Definition at line 1415 of file twophase.c.

1416{
1417 XLogRecord *record;
1419 char *errormsg;
1420
1422 XL_ROUTINE(.page_read = &read_local_xlog_page,
1423 .segment_open = &wal_segment_open,
1424 .segment_close = &wal_segment_close),
1425 NULL);
1426 if (!xlogreader)
1427 ereport(ERROR,
1429 errmsg("out of memory"),
1430 errdetail("Failed while allocating a WAL reading processor.")));
1431
1433 record = XLogReadRecord(xlogreader, &errormsg);
1434
1435 if (record == NULL)
1436 {
1437 if (errormsg)
1438 ereport(ERROR,
1440 errmsg("could not read two-phase state from WAL at %X/%08X: %s",
1441 LSN_FORMAT_ARGS(lsn), errormsg)));
1442 else
1443 ereport(ERROR,
1445 errmsg("could not read two-phase state from WAL at %X/%08X",
1446 LSN_FORMAT_ARGS(lsn))));
1447 }
1448
1451 ereport(ERROR,
1453 errmsg("expected two-phase state data is not present in WAL at %X/%08X",
1454 LSN_FORMAT_ARGS(lsn))));
1455
1456 if (len != NULL)
1458
1461
1463}
#define XLOG_XACT_OPMASK
Definition xact.h:180
int wal_segment_size
Definition xlog.c:147
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition xlogreader.c:108
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition xlogreader.c:391
void XLogReaderFree(XLogReaderState *state)
Definition xlogreader.c:163
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition xlogreader.c:233
#define XLogRecGetDataLen(decoder)
Definition xlogreader.h:416
#define XLogRecGetInfo(decoder)
Definition xlogreader.h:410
#define XLogRecGetRmid(decoder)
Definition xlogreader.h:411
#define XLogRecGetData(decoder)
Definition xlogreader.h:415
#define XL_ROUTINE(...)
Definition xlogreader.h:117
static XLogReaderState * xlogreader
void wal_segment_close(XLogReaderState *state)
Definition xlogutils.c:831
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition xlogutils.c:806
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition xlogutils.c:845

References buf, ereport, errcode(), errcode_for_file_access(), errdetail(), errmsg, ERROR, fb(), len, LSN_FORMAT_ARGS, palloc_array, read_local_xlog_page(), wal_segment_close(), wal_segment_open(), wal_segment_size, XL_ROUTINE, XLOG_XACT_OPMASK, XLOG_XACT_PREPARE, XLogBeginRead(), xlogreader, XLogReaderAllocate(), XLogReaderFree(), XLogReadRecord(), XLogRecGetData, XLogRecGetDataLen, XLogRecGetInfo, and XLogRecGetRmid.

Referenced by CheckPointTwoPhase(), FinishPreparedTransaction(), LookupGXact(), and ProcessTwoPhaseBuffer().

Variable Documentation

◆ max_prepared_xacts

◆ MyLockedGxact

◆ records

struct xllist records
static

◆ twophaseExitRegistered

bool twophaseExitRegistered = false
static

Definition at line 200 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseState