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 "storage/subsystems.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 TwoPhaseShmemRequest (void *arg)
 
static void TwoPhaseShmemInit (void *arg)
 
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, size_t *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, const void *content, size_t len)
 
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
 
const ShmemCallbacks TwoPhaseShmemCallbacks
 
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 115 of file twophase.c.

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */

Definition at line 982 of file twophase.c.

Typedef Documentation

◆ GlobalTransactionData

◆ StateFileChunk

◆ TwoPhaseFileHeader

◆ TwoPhaseRecordOnDisk

◆ TwoPhaseStateData

Function Documentation

◆ AdjustToFullTransactionId()

static FullTransactionId AdjustToFullTransactionId ( TransactionId  xid)
inlinestatic

Definition at line 949 of file twophase.c.

950{
953}
#define Assert(condition)
Definition c.h:1002
static FullTransactionId FullTransactionIdFromAllowableAt(FullTransactionId nextFullXid, TransactionId xid)
Definition transam.h:441
#define TransactionIdIsValid(xid)
Definition transam.h:41
FullTransactionId ReadNextFullTransactionId(void)
Definition varsup.c:283

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

Referenced by StandbyTransactionIdIsPrepared().

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 310 of file twophase.c.

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

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

◆ AtProcExit_Twophase()

static void AtProcExit_Twophase ( int  code,
Datum  arg 
)
static

Definition at line 300 of file twophase.c.

301{
302 /* same logic as abort */
304}
void AtAbort_Twophase(void)
Definition twophase.c:310

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1830 of file twophase.c.

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

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

Referenced by CheckPointGuts().

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1151 of file twophase.c.

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

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

Referenced by PrepareTransaction().

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char gid,
bool  isCommit 
)

Definition at line 1505 of file twophase.c.

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

References Assert, AtEOXact_PgStat(), buf, DropRelationFiles(), fb(), GetPGProcByNumber, GetUserId(), xl_xact_prepare::gidlen, HOLD_INTERRUPTS, xl_xact_prepare::initfileinval, LockGXact(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, MyLockedGxact, xl_xact_prepare::nabortrels, xl_xact_prepare::nabortstats, xl_xact_prepare::ncommitrels, xl_xact_prepare::ncommitstats, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, pfree(), pgstat_execute_transactional_drops(), PredicateLockTwoPhaseFinish(), ProcArrayRemove(), ProcessRecords(), ReadTwoPhaseFile(), RecordTransactionAbortPrepared(), RecordTransactionCommitPrepared(), RelationCacheInitFilePostInvalidate(), RelationCacheInitFilePreInvalidate(), RemoveGXact(), RemoveTwoPhaseFile(), RESUME_INTERRUPTS, SendSharedInvalidMessages(), TransactionIdEquals, TransactionIdLatest(), twophase_postabort_callbacks, twophase_postcommit_callbacks, xl_xact_prepare::xid, XidFromFullTransactionId, and XlogReadTwoPhaseData().

Referenced by apply_handle_commit_prepared(), apply_handle_rollback_prepared(), and standard_ProcessUtility().

◆ GetPreparedTransactionList()

static int GetPreparedTransactionList ( GlobalTransaction gxacts)
static

Definition at line 674 of file twophase.c.

675{
676 GlobalTransaction array;
677 int num;
678 int i;
679
681
682 if (TwoPhaseState->numPrepXacts == 0)
683 {
685
686 *gxacts = NULL;
687 return 0;
688 }
689
692 *gxacts = array;
693 for (i = 0; i < num; i++)
694 memcpy(array + i, TwoPhaseState->prepXacts[i],
695 sizeof(GlobalTransactionData));
696
698
699 return num;
700}
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define palloc_array(type, count)
Definition fe_memutils.h:91

References fb(), i, LW_SHARED, LWLockAcquire(), LWLockRelease(), memcpy(), 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 512 of file twophase.c.

514{
515 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
516
517 /* We need no extra lock since the GXACT isn't valid yet */
518 if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
519 {
520 proc->subxidStatus.overflowed = true;
521 nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
522 }
523 if (nsubxacts > 0)
524 {
525 memcpy(proc->subxids.xids, children,
526 nsubxacts * sizeof(TransactionId));
527 proc->subxidStatus.count = nsubxacts;
528 }
529}
#define PGPROC_MAX_CACHED_SUBXIDS
Definition proc.h:43
XidCacheStatus subxidStatus
Definition proc.h:247
struct XidCache subxids
Definition proc.h:249
bool overflowed
Definition proc.h:50
uint8 count
Definition proc.h:48
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition proc.h:55

References XidCacheStatus::count, fb(), GetPGProcByNumber, memcpy(), 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 2773 of file twophase.c.

2774{
2775 int ret;
2778 char gid_tmp[GIDSIZE];
2779
2780 /* Extract the subid and xid from the given GID */
2781 ret = sscanf(gid, "pg_gid_%u_%u", &subid_from_gid, &xid_from_gid);
2782
2783 /*
2784 * Check that the given GID has expected format, and at least the subid
2785 * matches.
2786 */
2787 if (ret != 2 || subid != subid_from_gid)
2788 return false;
2789
2790 /*
2791 * Reconstruct a temporary GID based on the subid and xid extracted from
2792 * the given GID and check whether the temporary GID and the given GID
2793 * match.
2794 */
2796
2797 return strcmp(gid, gid_tmp) == 0;
2798}
unsigned int Oid
void TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid_res, int szgid)
Definition twophase.c:2755
#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 560 of file twophase.c.

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

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

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

2806{
2807 bool found = false;
2808
2810 for (int i = 0; i < TwoPhaseState->numPrepXacts; i++)
2811 {
2813
2814 /* Ignore not-yet-valid GIDs. */
2815 if (gxact->valid &&
2817 {
2818 found = true;
2819 break;
2820 }
2821 }
2823
2824 return found;
2825}
static bool IsTwoPhaseTransactionGidForSubid(Oid subid, char *gid)
Definition twophase.c:2773

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

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

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

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

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

442{
443 PGPROC *proc;
444 int i;
446
448
449 Assert(gxact != NULL);
450 proc = GetPGProcByNumber(gxact->pgprocno);
451
452 /* Initialize the PGPROC entry */
453 MemSet(proc, 0, sizeof(PGPROC));
456 {
457 /* clone VXID, for TwoPhaseGetXidByVirtualXID() to find */
458 proc->vxid.lxid = MyProc->vxid.lxid;
460 }
461 else
462 {
464 /* GetLockConflicts() uses this to specify a wait on the XID */
465 proc->vxid.lxid = xid;
467 }
468 proc->xid = xid;
470 proc->delayChkptFlags = 0;
471 proc->statusFlags = 0;
472 proc->pid = 0;
473 proc->databaseId = databaseid;
474 proc->roleId = owner;
476 proc->backendType = B_INVALID;
478 proc->lwWaitMode = 0;
479 proc->waitLock = NULL;
481 proc->waitProcLock = NULL;
482 pg_atomic_init_u64(&proc->waitStart, 0);
483 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
484 dlist_init(&proc->myProcLocks[i]);
485 /* subxid data must be filled later by GXactLoadSubxactData */
486 proc->subxidStatus.overflowed = false;
487 proc->subxidStatus.count = 0;
488
489 gxact->prepared_at = prepared_at;
490 gxact->fxid = fxid;
491 gxact->owner = owner;
492 gxact->locking_backend = MyProcNumber;
493 gxact->valid = false;
494 gxact->inredo = false;
495 strcpy(gxact->gid, gid);
496
497 /*
498 * Remember that we have this GlobalTransaction entry locked for us. If we
499 * abort after this, we must release it.
500 */
502}
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition atomics.h:448
#define MemSet(start, val, len)
Definition c.h:1147
bool IsPostmasterEnvironment
Definition globals.c:121
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:1929
@ LW_WS_NOT_WAITING
Definition lwlock.h:30
#define NUM_LOCK_PARTITIONS
Definition lwlock.h:87
#define AmStartupProcess()
Definition miscadmin.h:396
@ B_INVALID
Definition miscadmin.h:342
#define InvalidOid
@ PROC_WAIT_STATUS_OK
Definition proc.h:145
TransactionId xmin
Definition proc.h:242
LocalTransactionId lxid
Definition proc.h:231
PROCLOCK * waitProcLock
Definition proc.h:306
uint8 lwWaitMode
Definition proc.h:284
BackendType backendType
Definition proc.h:198
uint8 statusFlags
Definition proc.h:210
pg_atomic_uint64 waitStart
Definition proc.h:311
ProcNumber procNumber
Definition proc.h:226
int pid
Definition proc.h:197
LOCK * waitLock
Definition proc.h:304
TransactionId xid
Definition proc.h:237
dlist_node waitLink
Definition proc.h:305
struct PGPROC::@134 vxid
dlist_head myProcLocks[NUM_LOCK_PARTITIONS]
Definition proc.h:321
Oid roleId
Definition proc.h:202
ProcWaitStatus waitStatus
Definition proc.h:314
Oid tempNamespaceId
Definition proc.h:204
uint8 lwWaiting
Definition proc.h:283
#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 719 of file twophase.c.

720{
722 Working_State *status;
723
724 if (SRF_IS_FIRSTCALL())
725 {
726 TupleDesc tupdesc;
727 MemoryContext oldcontext;
728
729 /* create a function context for cross-call persistence */
731
732 /*
733 * Switch to memory context appropriate for multiple function calls
734 */
735 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
736
737 /* build tupdesc for result tuples */
738 /* this had better match pg_prepared_xacts view in system_views.sql */
739 tupdesc = CreateTemplateTupleDesc(5);
740 TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
741 XIDOID, -1, 0);
742 TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
743 TEXTOID, -1, 0);
744 TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
745 TIMESTAMPTZOID, -1, 0);
746 TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
747 OIDOID, -1, 0);
748 TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
749 OIDOID, -1, 0);
750
751 TupleDescFinalize(tupdesc);
752 funcctx->tuple_desc = BlessTupleDesc(tupdesc);
753
754 /*
755 * Collect all the 2PC status information that we will format and send
756 * out as a result set.
757 */
759 funcctx->user_fctx = status;
760
761 status->ngxacts = GetPreparedTransactionList(&status->array);
762 status->currIdx = 0;
763
764 MemoryContextSwitchTo(oldcontext);
765 }
766
768 status = (Working_State *) funcctx->user_fctx;
769
770 while (status->array != NULL && status->currIdx < status->ngxacts)
771 {
772 GlobalTransaction gxact = &status->array[status->currIdx++];
773 PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
774 Datum values[5] = {0};
775 bool nulls[5] = {0};
776 HeapTuple tuple;
778
779 if (!gxact->valid)
780 continue;
781
782 /*
783 * Form tuple with appropriate data.
784 */
785
786 values[0] = TransactionIdGetDatum(proc->xid);
788 values[2] = TimestampTzGetDatum(gxact->prepared_at);
789 values[3] = ObjectIdGetDatum(gxact->owner);
791
792 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
793 result = HeapTupleGetDatum(tuple);
795 }
796
798}
int16 AttrNumber
Definition attnum.h:21
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define CStringGetTextDatum(s)
Definition builtins.h:98
uint32 result
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
#define palloc_object(type)
Definition fe_memutils.h:89
#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:1025
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
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:706
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:909
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition twophase.c:674
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, result, 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 2515 of file twophase.c.

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

2673{
2674 FullTransactionId fxid =
2676
2678}
static void PrepareRedoRemoveFull(FullTransactionId fxid, bool giveWarning)
Definition twophase.c:2628

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

Referenced by xact_redo().

◆ PrepareRedoRemoveFull()

static void PrepareRedoRemoveFull ( FullTransactionId  fxid,
bool  giveWarning 
)
static

Definition at line 2628 of file twophase.c.

2629{
2631 int i;
2632 bool found = false;
2633
2636
2637 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2638 {
2640
2641 if (FullTransactionIdEquals(gxact->fxid, fxid))
2642 {
2643 Assert(gxact->inredo);
2644 found = true;
2645 break;
2646 }
2647 }
2648
2649 /*
2650 * Just leave if there is nothing, this is expected during WAL replay.
2651 */
2652 if (!found)
2653 return;
2654
2655 /*
2656 * And now we can clean up any files we may have left.
2657 */
2658 elog(DEBUG2, "removing 2PC data for transaction %u of epoch %u ",
2661
2662 if (gxact->ondisk)
2664
2666}
#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 1974 of file twophase.c.

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

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

Referenced by StartupXLOG(), and xlog_redo().

◆ ProcessRecords()

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

Definition at line 1700 of file twophase.c.

1702{
1703 for (;;)
1704 {
1705 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1706
1707 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1708 if (record->rmid == TWOPHASE_RM_END_ID)
1709 break;
1710
1711 bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1712
1713 if (callbacks[record->rmid] != NULL)
1714 callbacks[record->rmid] (fxid, record->info, bufptr, record->len);
1715
1716 bufptr += MAXALIGN(record->len);
1717 }
1718}
TwoPhaseRmgrId rmid
Definition twophase.c:995
#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 2195 of file twophase.c.

2199{
2201 TransactionId *subxids;
2202 char *buf;
2203 TwoPhaseFileHeader *hdr;
2204 int i;
2205
2207
2208 if (!fromdisk)
2209 Assert(XLogRecPtrIsValid(prepare_start_lsn));
2210
2211 /* Already processed? */
2214 {
2215 if (fromdisk)
2216 {
2218 (errmsg("removing stale two-phase state file for transaction %u of epoch %u",
2221 RemoveTwoPhaseFile(fxid, true);
2222 }
2223 else
2224 {
2226 (errmsg("removing stale two-phase state from memory for transaction %u of epoch %u",
2229 PrepareRedoRemoveFull(fxid, true);
2230 }
2231 return NULL;
2232 }
2233
2234 /* Reject XID if too new */
2235 if (FullTransactionIdFollowsOrEquals(fxid, nextXid))
2236 {
2237 if (fromdisk)
2238 {
2240 (errmsg("removing future two-phase state file for transaction %u of epoch %u",
2243 RemoveTwoPhaseFile(fxid, true);
2244 }
2245 else
2246 {
2248 (errmsg("removing future two-phase state from memory for transaction %u of epoch %u",
2251 PrepareRedoRemoveFull(fxid, true);
2252 }
2253 return NULL;
2254 }
2255
2256 if (fromdisk)
2257 {
2258 /* Read and validate file */
2259 buf = ReadTwoPhaseFile(fxid, false);
2260 }
2261 else
2262 {
2263 /* Read xlog data */
2264 XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2265 }
2266
2267 /* Deconstruct header */
2268 hdr = (TwoPhaseFileHeader *) buf;
2270 {
2271 if (fromdisk)
2272 ereport(ERROR,
2274 errmsg("corrupted two-phase state file for transaction %u of epoch %u",
2277 else
2278 ereport(ERROR,
2280 errmsg("corrupted two-phase state in memory for transaction %u of epoch %u",
2283 }
2284
2285 /*
2286 * Examine subtransaction XIDs ... they should all follow main XID, and
2287 * they may force us to advance nextXid.
2288 */
2289 subxids = (TransactionId *) (buf +
2290 MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2291 MAXALIGN(hdr->gidlen));
2292 for (i = 0; i < hdr->nsubxacts; i++)
2293 {
2294 TransactionId subxid = subxids[i];
2295
2297
2298 /* update nextXid if needed */
2299 if (setNextXid)
2301
2302 if (setParent)
2304 }
2305
2306 return buf;
2307}
#define ERRCODE_DATA_CORRUPTED
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition subtrans.c:92
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:299

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

1302{
1303 char path[MAXPGPATH];
1304 size_t buflen;
1305 char *buf;
1306 TwoPhaseFileHeader *hdr;
1307 int fd;
1308 struct stat stat;
1311 file_crc;
1312 ssize_t r;
1313
1314 TwoPhaseFilePath(path, fxid);
1315
1317 if (fd < 0)
1318 {
1319 if (missing_ok && errno == ENOENT)
1320 return NULL;
1321
1322 ereport(ERROR,
1324 errmsg("could not open file \"%s\": %m", path)));
1325 }
1326
1327 /*
1328 * Check file length. We can determine a lower bound pretty easily. We
1329 * set an upper bound to avoid palloc() failure on a corrupt file, though
1330 * we can't guarantee that we won't get an out of memory error anyway,
1331 * even on a valid file.
1332 */
1333 if (fstat(fd, &stat))
1334 ereport(ERROR,
1336 errmsg("could not stat file \"%s\": %m", path)));
1337
1338 if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1340 sizeof(pg_crc32c)) ||
1342 ereport(ERROR,
1344 errmsg_plural("incorrect size of file \"%s\": %lld byte",
1345 "incorrect size of file \"%s\": %lld bytes",
1346 (long long int) stat.st_size, path,
1347 (long long int) stat.st_size)));
1348
1349 crc_offset = stat.st_size - sizeof(pg_crc32c);
1351 ereport(ERROR,
1353 errmsg("incorrect alignment of CRC offset for file \"%s\"",
1354 path)));
1355
1356 /*
1357 * OK, slurp in the file.
1358 */
1359 buflen = stat.st_size;
1360 buf = (char *) palloc(buflen);
1361
1363 r = read(fd, buf, buflen);
1364 if (r != buflen)
1365 {
1366 if (r < 0)
1367 ereport(ERROR,
1369 errmsg("could not read file \"%s\": %m", path)));
1370 else
1371 ereport(ERROR,
1372 (errmsg("could not read file \"%s\": read %zd of %zu",
1373 path, r, buflen)));
1374 }
1375
1377
1378 if (CloseTransientFile(fd) != 0)
1379 ereport(ERROR,
1381 errmsg("could not close file \"%s\": %m", path)));
1382
1383 hdr = (TwoPhaseFileHeader *) buf;
1384 if (hdr->magic != TWOPHASE_MAGIC)
1385 ereport(ERROR,
1387 errmsg("invalid magic number stored in file \"%s\"",
1388 path)));
1389
1390 if (hdr->total_len != stat.st_size)
1391 ereport(ERROR,
1393 errmsg("invalid size stored in file \"%s\"",
1394 path)));
1395
1399
1400 file_crc = *((pg_crc32c *) (buf + crc_offset));
1401
1403 ereport(ERROR,
1405 errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
1406 path)));
1407
1408 return buf;
1409}
#define PG_BINARY
Definition c.h:1431
uint32_t uint32
Definition c.h:683
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:177
#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:182
static int fd(const char *x, int i)
__int64 st_size
Definition win32_port.h:280
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:67
static void pgstat_report_wait_end(void)
Definition wait_event.h:83
#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 2440 of file twophase.c.

2448{
2450 bool replorigin;
2451
2452 /*
2453 * Are we using the replication origins feature? Or, in other words, are
2454 * we replaying remote actions?
2455 */
2458
2459 /*
2460 * Catch the scenario where we aborted partway through
2461 * RecordTransactionCommitPrepared ...
2462 */
2463 if (TransactionIdDidCommit(xid))
2464 elog(PANIC, "cannot abort transaction %u, it was already committed",
2465 xid);
2466
2468
2469 /*
2470 * Emit the XLOG commit record. Note that we mark 2PC aborts as
2471 * potentially having AccessExclusiveLocks since we don't know whether or
2472 * not they do.
2473 */
2475 nchildren, children,
2476 nrels, rels,
2477 nstats, stats,
2479 xid, gid);
2480
2481 if (replorigin)
2482 /* Move LSNs forward for this replication origin */
2485
2486 /* Always flush, since we're about to remove the 2PC state file */
2488
2489 /*
2490 * Mark the transaction aborted in clog. This is not absolutely necessary
2491 * but we may as well do it while we are here.
2492 */
2493 TransactionIdAbortTree(xid, nchildren, children);
2494
2496
2497 /*
2498 * Wait for synchronous replication, if required.
2499 *
2500 * Note that at this stage we have marked clog, but still show as running
2501 * in the procarray and continue to hold locks.
2502 */
2503 SyncRepWaitForLSN(recptr, false);
2504}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1649
#define PANIC
Definition elog.h:44
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:6045
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition xact.h:109
XLogRecPtr XactLastRecEnd
Definition xlog.c:261
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 2321 of file twophase.c.

2332{
2335 bool replorigin;
2336
2337 /*
2338 * Are we using the replication origins feature? Or, in other words, are
2339 * we replaying remote actions?
2340 */
2343
2344 /* Load the injection point before entering the critical section */
2345 INJECTION_POINT_LOAD("commit-after-delay-checkpoint");
2346
2348
2349 /* See notes in RecordTransactionCommit */
2352
2353 INJECTION_POINT_CACHED("commit-after-delay-checkpoint", NULL);
2354
2355 /*
2356 * Ensures the DELAY_CHKPT_IN_COMMIT flag write is globally visible before
2357 * commit time is written.
2358 */
2360
2361 /*
2362 * Note it is important to set committs value after marking ourselves as
2363 * in the commit critical section (DELAY_CHKPT_IN_COMMIT). This is because
2364 * we want to ensure all transactions that have acquired commit timestamp
2365 * are finished before we allow the logical replication client to advance
2366 * its xid which is used to hold back dead rows for conflict detection.
2367 * See comments atop worker.c.
2368 */
2370
2371 /*
2372 * Emit the XLOG commit record. Note that we mark 2PC commits as
2373 * potentially having AccessExclusiveLocks since we don't know whether or
2374 * not they do.
2375 */
2377 nchildren, children, nrels, rels,
2378 nstats, stats,
2379 ninvalmsgs, invalmsgs,
2380 initfileinval,
2382 xid, gid);
2383
2384
2385 if (replorigin)
2386 /* Move LSNs forward for this replication origin */
2389
2390 /*
2391 * Record commit timestamp. The value comes from plain commit timestamp
2392 * if replorigin is not enabled, or replorigin already set a value for us
2393 * in replorigin_xact_state.origin_timestamp otherwise.
2394 *
2395 * We don't need to WAL-log anything here, as the commit record written
2396 * above already contains the data.
2397 */
2400
2404
2405 /*
2406 * We don't currently try to sleep before flush here ... nor is there any
2407 * support for async commit of a prepared xact (the very idea is probably
2408 * a contradiction)
2409 */
2410
2411 /* Flush XLOG to disk */
2413
2414 /* Mark the transaction committed in pg_xact */
2415 TransactionIdCommitTree(xid, nchildren, children);
2416
2417 /* Checkpoint can proceed now */
2419
2421
2422 /*
2423 * Wait for synchronous replication, if required.
2424 *
2425 * Note that at this stage we have marked clog, but still show as running
2426 * in the procarray and continue to hold locks.
2427 */
2429}
#define pg_write_barrier()
Definition atomics.h:155
void TransactionTreeSetCommitTsData(TransactionId xid, int nsubxids, TransactionId *subxids, TimestampTz timestamp, ReplOriginId nodeid)
Definition commit_ts.c:150
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:141
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:5873

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

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

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

Referenced by StartupXLOG().

◆ RecreateTwoPhaseFile()

static void RecreateTwoPhaseFile ( FullTransactionId  fxid,
const void content,
size_t  len 
)
static

Definition at line 1750 of file twophase.c.

1751{
1752 char path[MAXPGPATH];
1754 int fd;
1755
1756 /* Recompute CRC */
1758 COMP_CRC32C(statefile_crc, content, len);
1760
1761 TwoPhaseFilePath(path, fxid);
1762
1763 fd = OpenTransientFile(path,
1765 if (fd < 0)
1766 ereport(ERROR,
1768 errmsg("could not recreate file \"%s\": %m", path)));
1769
1770 /* Write content and CRC */
1771 errno = 0;
1773 if (write(fd, content, len) != len)
1774 {
1775 /* if write didn't set errno, assume problem is no disk space */
1776 if (errno == 0)
1777 errno = ENOSPC;
1778 ereport(ERROR,
1780 errmsg("could not write file \"%s\": %m", path)));
1781 }
1782 if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1783 {
1784 /* if write didn't set errno, assume problem is no disk space */
1785 if (errno == 0)
1786 errno = ENOSPC;
1787 ereport(ERROR,
1789 errmsg("could not write file \"%s\": %m", path)));
1790 }
1792
1793 /*
1794 * We must fsync the file because the end-of-replay checkpoint will not do
1795 * so, there being no GXACT in shared memory yet to tell it to.
1796 */
1798 if (pg_fsync(fd) != 0)
1799 ereport(ERROR,
1801 errmsg("could not fsync file \"%s\": %m", path)));
1803
1804 if (CloseTransientFile(fd) != 0)
1805 ereport(ERROR,
1807 errmsg("could not close file \"%s\": %m", path)));
1808}
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 1277 of file twophase.c.

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

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

637{
638 int i;
639
641
642 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
643 {
645 {
646 /* remove from the active array */
649
650 /* and put it back in the freelist */
653
654 return;
655 }
656 }
657
658 elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
659}

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

1732{
1733 char path[MAXPGPATH];
1734
1735 TwoPhaseFilePath(path, fxid);
1736 if (unlink(path))
1737 if (errno != ENOENT || giveWarning)
1740 errmsg("could not remove file \"%s\": %m", path)));
1741}

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

1913{
1914 DIR *cldir;
1915 struct dirent *clde;
1916
1919 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1920 {
1921 if (strlen(clde->d_name) == 16 &&
1922 strspn(clde->d_name, "0123456789ABCDEF") == 16)
1923 {
1924 FullTransactionId fxid;
1925 char *buf;
1926
1927 fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
1928
1930 true, false, false);
1931 if (buf == NULL)
1932 continue;
1933
1936 }
1937 }
1939 FreeDir(cldir);
1940}
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:2515

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

1031{
1033
1035 {
1038 records.tail->len = 0;
1039 records.tail->next = NULL;
1041
1042 records.bytes_free = Max(padlen, 512);
1044 }
1045
1047 records.tail->len += padlen;
1050}
#define Max(x, y)
Definition c.h:1125
#define palloc0_object(type)
Definition fe_memutils.h:90
struct StateFileChunk * next
Definition twophase.c:1008
uint32 bytes_free
Definition twophase.c:1016

References xllist::bytes_free, StateFileChunk::data, data, fb(), StateFileChunk::len, len, Max, MAXALIGN, memcpy(), 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 2053 of file twophase.c.

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

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

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

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 1058 of file twophase.c.

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

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

957{
958 return snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X%08X",
961}
#define snprintf
Definition port.h:261

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

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

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

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

◆ TwoPhaseGetDummyProcNumber()

ProcNumber TwoPhaseGetDummyProcNumber ( FullTransactionId  fxid,
bool  lock_held 
)

Definition at line 914 of file twophase.c.

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

References fb(), and TwoPhaseGetGXact().

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

◆ TwoPhaseGetGXact()

static GlobalTransaction TwoPhaseGetGXact ( FullTransactionId  fxid,
bool  lock_held 
)
static

Definition at line 809 of file twophase.c.

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

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

Referenced by TwoPhaseGetDummyProc(), and TwoPhaseGetDummyProcNumber().

◆ TwoPhaseGetOldestXidInCommit()

TransactionId TwoPhaseGetOldestXidInCommit ( void  )

Definition at line 2837 of file twophase.c.

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

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

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

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

Referenced by XactLockForVirtualXact().

◆ TwoPhaseShmemInit()

static void TwoPhaseShmemInit ( void arg)
static

Definition at line 270 of file twophase.c.

271{
273 int i;
274
277
278 /*
279 * Initialize the linked list of free GlobalTransactionData structs
280 */
282 ((char *) TwoPhaseState +
285 for (i = 0; i < max_prepared_xacts; i++)
286 {
287 /* insert into linked list */
290
291 /* associate it with a PGPROC assigned by ProcGlobalShmemInit */
293 }
294}
#define GetNumberFromPGProc(proc)
Definition proc.h:507
PGPROC * PreparedXactProcs
Definition proc.c:78
struct GlobalTransactionData * GlobalTransaction
Definition twophase.h:31

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

◆ TwoPhaseShmemRequest()

static void TwoPhaseShmemRequest ( void arg)
static

Definition at line 249 of file twophase.c.

250{
251 Size size;
252
253 /* Need the fixed struct, the array of pointers, and the GTD structs */
254 size = offsetof(TwoPhaseStateData, prepXacts);
256 sizeof(GlobalTransaction)));
257 size = MAXALIGN(size);
259 sizeof(GlobalTransactionData)));
260 ShmemRequestStruct(.name = "Prepared Transaction Table",
261 .size = size,
262 .ptr = (void **) &TwoPhaseState,
263 );
264}
size_t Size
Definition c.h:748
Size add_size(Size s1, Size s2)
Definition mcxt.c:1733
Size mul_size(Size s1, Size s2)
Definition mcxt.c:1752
#define ShmemRequestStruct(...)
Definition shmem.h:176
const char * name

References add_size(), fb(), max_prepared_xacts, MAXALIGN, mul_size(), name, ShmemRequestStruct, and TwoPhaseState.

◆ TwoPhaseTransactionGid()

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

Definition at line 2755 of file twophase.c.

2756{
2757 Assert(OidIsValid(subid));
2758
2759 if (!TransactionIdIsValid(xid))
2760 ereport(ERROR,
2762 errmsg_internal("invalid two-phase transaction ID")));
2763
2764 snprintf(gid_res, szgid, "pg_gid_%u_%u", subid, xid);
2765}
#define OidIsValid(objectId)
Definition c.h:917
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,
size_t len 
)
static

Definition at line 1420 of file twophase.c.

1421{
1422 XLogRecord *record;
1424 char *errormsg;
1425
1427 XL_ROUTINE(.page_read = &read_local_xlog_page,
1428 .segment_open = &wal_segment_open,
1429 .segment_close = &wal_segment_close),
1430 NULL);
1431 if (!xlogreader)
1432 ereport(ERROR,
1434 errmsg("out of memory"),
1435 errdetail("Failed while allocating a WAL reading processor.")));
1436
1438 record = XLogReadRecord(xlogreader, &errormsg);
1439
1440 if (record == NULL)
1441 {
1442 if (errormsg)
1443 ereport(ERROR,
1445 errmsg("could not read two-phase state from WAL at %X/%08X: %s",
1446 LSN_FORMAT_ARGS(lsn), errormsg)));
1447 else
1448 ereport(ERROR,
1450 errmsg("could not read two-phase state from WAL at %X/%08X",
1451 LSN_FORMAT_ARGS(lsn))));
1452 }
1453
1456 ereport(ERROR,
1458 errmsg("expected two-phase state data is not present in WAL at %X/%08X",
1459 LSN_FORMAT_ARGS(lsn))));
1460
1461 if (len != NULL)
1463
1466
1468}
#define XLOG_XACT_OPMASK
Definition xact.h:180
int wal_segment_size
Definition xlog.c:150
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:855
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition xlogutils.c:830
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition xlogutils.c:869

References buf, ereport, errcode(), errcode_for_file_access(), errdetail(), errmsg, ERROR, fb(), len, LSN_FORMAT_ARGS, memcpy(), 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 209 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseShmemCallbacks

const ShmemCallbacks TwoPhaseShmemCallbacks
Initial value:
= {
.request_fn = TwoPhaseShmemRequest,
.init_fn = TwoPhaseShmemInit,
}
static void TwoPhaseShmemInit(void *arg)
Definition twophase.c:270
static void TwoPhaseShmemRequest(void *arg)
Definition twophase.c:249

Definition at line 196 of file twophase.c.

196 {
197 .request_fn = TwoPhaseShmemRequest,
198 .init_fn = TwoPhaseShmemInit,
199};

◆ TwoPhaseState