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

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Functions

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

Variables

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

Macro Definition Documentation

◆ TWOPHASE_DIR

#define TWOPHASE_DIR   "pg_twophase"

Definition at line 113 of file twophase.c.

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */

Definition at line 977 of file twophase.c.

Typedef Documentation

◆ GlobalTransactionData

◆ StateFileChunk

◆ TwoPhaseFileHeader

◆ TwoPhaseRecordOnDisk

◆ TwoPhaseStateData

Function Documentation

◆ AdjustToFullTransactionId()

static FullTransactionId AdjustToFullTransactionId ( TransactionId  xid)
inlinestatic

Definition at line 944 of file twophase.c.

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

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

Referenced by StandbyTransactionIdIsPrepared().

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 306 of file twophase.c.

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

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

297{
298 /* same logic as abort */
300}
void AtAbort_Twophase(void)
Definition twophase.c:306

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1823 of file twophase.c.

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

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

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

Referenced by PrepareTransaction().

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char gid,
bool  isCommit 
)

Definition at line 1498 of file twophase.c.

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

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

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

Referenced by pg_prepared_xact().

◆ GXactLoadSubxactData()

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

Definition at line 508 of file twophase.c.

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

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

Referenced by RecoverPreparedTransactions(), and StartPrepare().

◆ IsTwoPhaseTransactionGidForSubid()

static bool IsTwoPhaseTransactionGidForSubid ( Oid  subid,
char gid 
)
static

Definition at line 2766 of file twophase.c.

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

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

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

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

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

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

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

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

363{
365 int i;
366
367 if (strlen(gid) >= GIDSIZE)
370 errmsg("transaction identifier \"%s\" is too long",
371 gid)));
372
373 /* fail immediately if feature is disabled */
374 if (max_prepared_xacts == 0)
377 errmsg("prepared transactions are disabled"),
378 errhint("Set \"max_prepared_transactions\" to a nonzero value.")));
379
380 /* on first call, register the exit hook */
382 {
385 }
386
388
389 /* Check for conflicting GID */
390 for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
391 {
393 if (strcmp(gxact->gid, gid) == 0)
394 {
397 errmsg("transaction identifier \"%s\" is already in use",
398 gid)));
399 }
400 }
401
402 /* Get a free gxact from the freelist */
406 errmsg("maximum number of prepared transactions reached"),
407 errhint("Increase \"max_prepared_transactions\" (currently %d).",
411
412 MarkAsPreparingGuts(gxact, fxid, gid, prepared_at, owner, databaseid);
413
414 gxact->ondisk = false;
415
416 /* And insert it into the active array */
419
421
422 return gxact;
423}
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
GlobalTransaction next
Definition twophase.c:150
GlobalTransaction freeGXacts
Definition twophase.c:180
static void MarkAsPreparingGuts(GlobalTransaction gxact, FullTransactionId fxid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition twophase.c:435

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

438{
439 PGPROC *proc;
440 int i;
442
444
445 Assert(gxact != NULL);
446 proc = GetPGProcByNumber(gxact->pgprocno);
447
448 /* Initialize the PGPROC entry */
449 MemSet(proc, 0, sizeof(PGPROC));
452 {
453 /* clone VXID, for TwoPhaseGetXidByVirtualXID() to find */
454 proc->vxid.lxid = MyProc->vxid.lxid;
456 }
457 else
458 {
460 /* GetLockConflicts() uses this to specify a wait on the XID */
461 proc->vxid.lxid = xid;
463 }
464 proc->xid = xid;
466 proc->delayChkptFlags = 0;
467 proc->statusFlags = 0;
468 proc->pid = 0;
469 proc->databaseId = databaseid;
470 proc->roleId = owner;
472 proc->backendType = B_INVALID;
474 proc->lwWaitMode = 0;
475 proc->waitLock = NULL;
477 proc->waitProcLock = NULL;
478 pg_atomic_init_u64(&proc->waitStart, 0);
479 for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
480 dlist_init(&proc->myProcLocks[i]);
481 /* subxid data must be filled later by GXactLoadSubxactData */
482 proc->subxidStatus.overflowed = false;
483 proc->subxidStatus.count = 0;
484
485 gxact->prepared_at = prepared_at;
486 gxact->fxid = fxid;
487 gxact->owner = owner;
488 gxact->locking_backend = MyProcNumber;
489 gxact->valid = false;
490 gxact->inredo = false;
491 strcpy(gxact->gid, gid);
492
493 /*
494 * Remember that we have this GlobalTransaction entry locked for us. If we
495 * abort after this, we must release it.
496 */
498}
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition atomics.h:453
#define MemSet(start, val, len)
Definition c.h:1056
bool IsPostmasterEnvironment
Definition globals.c:119
static void dlist_init(dlist_head *head)
Definition ilist.h:314
static void dlist_node_init(dlist_node *node)
Definition ilist.h:325
#define LocalTransactionIdIsValid(lxid)
Definition lock.h:68
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1955
@ LW_WS_NOT_WAITING
Definition lwlock.h:30
#define NUM_LOCK_PARTITIONS
Definition lwlock.h:95
#define AmStartupProcess()
Definition miscadmin.h:390
@ B_INVALID
Definition miscadmin.h:339
#define InvalidOid
@ PROC_WAIT_STATUS_OK
Definition proc.h:142
TransactionId xmin
Definition proc.h:234
LocalTransactionId lxid
Definition proc.h:223
PROCLOCK * waitProcLock
Definition proc.h:298
uint8 lwWaitMode
Definition proc.h:276
BackendType backendType
Definition proc.h:190
uint8 statusFlags
Definition proc.h:202
struct PGPROC::@133 vxid
pg_atomic_uint64 waitStart
Definition proc.h:303
ProcNumber procNumber
Definition proc.h:218
int pid
Definition proc.h:189
LOCK * waitLock
Definition proc.h:296
TransactionId xid
Definition proc.h:229
dlist_node waitLink
Definition proc.h:297
dlist_head myProcLocks[NUM_LOCK_PARTITIONS]
Definition proc.h:313
Oid roleId
Definition proc.h:194
ProcWaitStatus waitStatus
Definition proc.h:306
Oid tempNamespaceId
Definition proc.h:196
uint8 lwWaiting
Definition proc.h:275
#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 715 of file twophase.c.

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

References Working_State::array, BlessTupleDesc(), CreateTemplateTupleDesc(), CStringGetTextDatum, Working_State::currIdx, PGPROC::databaseId, fb(), GetPGProcByNumber, GetPreparedTransactionList(), heap_form_tuple(), HeapTupleGetDatum(), MemoryContextSwitchTo(), Working_State::ngxacts, ObjectIdGetDatum(), palloc_object, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TimestampTzGetDatum(), TransactionIdGetDatum(), 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 2508 of file twophase.c.

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

2666{
2667 FullTransactionId fxid =
2669
2671}
static void PrepareRedoRemoveFull(FullTransactionId fxid, bool giveWarning)
Definition twophase.c:2621

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

Referenced by xact_redo().

◆ PrepareRedoRemoveFull()

static void PrepareRedoRemoveFull ( FullTransactionId  fxid,
bool  giveWarning 
)
static

Definition at line 2621 of file twophase.c.

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

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

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

Referenced by StartupXLOG(), and xlog_redo().

◆ ProcessRecords()

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

Definition at line 1693 of file twophase.c.

1695{
1696 for (;;)
1697 {
1698 TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1699
1700 Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1701 if (record->rmid == TWOPHASE_RM_END_ID)
1702 break;
1703
1704 bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1705
1706 if (callbacks[record->rmid] != NULL)
1707 callbacks[record->rmid] (fxid, record->info, bufptr, record->len);
1708
1709 bufptr += MAXALIGN(record->len);
1710 }
1711}
TwoPhaseRmgrId rmid
Definition twophase.c:990
#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 2188 of file twophase.c.

2192{
2194 TransactionId *subxids;
2195 char *buf;
2196 TwoPhaseFileHeader *hdr;
2197 int i;
2198
2200
2201 if (!fromdisk)
2202 Assert(XLogRecPtrIsValid(prepare_start_lsn));
2203
2204 /* Already processed? */
2207 {
2208 if (fromdisk)
2209 {
2211 (errmsg("removing stale two-phase state file for transaction %u of epoch %u",
2214 RemoveTwoPhaseFile(fxid, true);
2215 }
2216 else
2217 {
2219 (errmsg("removing stale two-phase state from memory for transaction %u of epoch %u",
2222 PrepareRedoRemoveFull(fxid, true);
2223 }
2224 return NULL;
2225 }
2226
2227 /* Reject XID if too new */
2228 if (FullTransactionIdFollowsOrEquals(fxid, nextXid))
2229 {
2230 if (fromdisk)
2231 {
2233 (errmsg("removing future two-phase state file for transaction %u of epoch %u",
2236 RemoveTwoPhaseFile(fxid, true);
2237 }
2238 else
2239 {
2241 (errmsg("removing future two-phase state from memory for transaction %u of epoch %u",
2244 PrepareRedoRemoveFull(fxid, true);
2245 }
2246 return NULL;
2247 }
2248
2249 if (fromdisk)
2250 {
2251 /* Read and validate file */
2252 buf = ReadTwoPhaseFile(fxid, false);
2253 }
2254 else
2255 {
2256 /* Read xlog data */
2257 XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2258 }
2259
2260 /* Deconstruct header */
2261 hdr = (TwoPhaseFileHeader *) buf;
2263 {
2264 if (fromdisk)
2265 ereport(ERROR,
2267 errmsg("corrupted two-phase state file for transaction %u of epoch %u",
2270 else
2271 ereport(ERROR,
2273 errmsg("corrupted two-phase state in memory for transaction %u of epoch %u",
2276 }
2277
2278 /*
2279 * Examine subtransaction XIDs ... they should all follow main XID, and
2280 * they may force us to advance nextXid.
2281 */
2282 subxids = (TransactionId *) (buf +
2283 MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2284 MAXALIGN(hdr->gidlen));
2285 for (i = 0; i < hdr->nsubxacts; i++)
2286 {
2287 TransactionId subxid = subxids[i];
2288
2290
2291 /* update nextXid if needed */
2292 if (setNextXid)
2294
2295 if (setParent)
2297 }
2298
2299 return buf;
2300}
#define ERRCODE_DATA_CORRUPTED
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition subtrans.c:84
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:304

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

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

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

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

◆ RecordTransactionAbortPrepared()

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

Definition at line 2433 of file twophase.c.

2441{
2443 bool replorigin;
2444
2445 /*
2446 * Are we using the replication origins feature? Or, in other words, are
2447 * we replaying remote actions?
2448 */
2451
2452 /*
2453 * Catch the scenario where we aborted partway through
2454 * RecordTransactionCommitPrepared ...
2455 */
2456 if (TransactionIdDidCommit(xid))
2457 elog(PANIC, "cannot abort transaction %u, it was already committed",
2458 xid);
2459
2461
2462 /*
2463 * Emit the XLOG commit record. Note that we mark 2PC aborts as
2464 * potentially having AccessExclusiveLocks since we don't know whether or
2465 * not they do.
2466 */
2468 nchildren, children,
2469 nrels, rels,
2470 nstats, stats,
2472 xid, gid);
2473
2474 if (replorigin)
2475 /* Move LSNs forward for this replication origin */
2478
2479 /* Always flush, since we're about to remove the 2PC state file */
2481
2482 /*
2483 * Mark the transaction aborted in clog. This is not absolutely necessary
2484 * but we may as well do it while we are here.
2485 */
2486 TransactionIdAbortTree(xid, nchildren, children);
2487
2489
2490 /*
2491 * Wait for synchronous replication, if required.
2492 *
2493 * Note that at this stage we have marked clog, but still show as running
2494 * in the procarray and continue to hold locks.
2495 */
2496 SyncRepWaitForLSN(recptr, false);
2497}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1643
#define PANIC
Definition elog.h:42
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition transam.c:270
int MyXactFlags
Definition xact.c:137
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:6008
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition xact.h:109
XLogRecPtr XactLastRecEnd
Definition xlog.c:257
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 2314 of file twophase.c.

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

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

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

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

Referenced by StartupXLOG().

◆ RecreateTwoPhaseFile()

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

Definition at line 1743 of file twophase.c.

1744{
1745 char path[MAXPGPATH];
1747 int fd;
1748
1749 /* Recompute CRC */
1751 COMP_CRC32C(statefile_crc, content, len);
1753
1754 TwoPhaseFilePath(path, fxid);
1755
1756 fd = OpenTransientFile(path,
1758 if (fd < 0)
1759 ereport(ERROR,
1761 errmsg("could not recreate file \"%s\": %m", path)));
1762
1763 /* Write content and CRC */
1764 errno = 0;
1766 if (write(fd, content, len) != len)
1767 {
1768 /* if write didn't set errno, assume problem is no disk space */
1769 if (errno == 0)
1770 errno = ENOSPC;
1771 ereport(ERROR,
1773 errmsg("could not write file \"%s\": %m", path)));
1774 }
1775 if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1776 {
1777 /* if write didn't set errno, assume problem is no disk space */
1778 if (errno == 0)
1779 errno = ENOSPC;
1780 ereport(ERROR,
1782 errmsg("could not write file \"%s\": %m", path)));
1783 }
1785
1786 /*
1787 * We must fsync the file because the end-of-replay checkpoint will not do
1788 * so, there being no GXACT in shared memory yet to tell it to.
1789 */
1791 if (pg_fsync(fd) != 0)
1792 ereport(ERROR,
1794 errmsg("could not fsync file \"%s\": %m", path)));
1796
1797 if (CloseTransientFile(fd) != 0)
1798 ereport(ERROR,
1800 errmsg("could not close file \"%s\": %m", path)));
1801}
int pg_fsync(int fd)
Definition fd.c:389
#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 1272 of file twophase.c.

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

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

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

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

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

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

1906{
1907 DIR *cldir;
1908 struct dirent *clde;
1909
1912 while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1913 {
1914 if (strlen(clde->d_name) == 16 &&
1915 strspn(clde->d_name, "0123456789ABCDEF") == 16)
1916 {
1917 FullTransactionId fxid;
1918 char *buf;
1919
1920 fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
1921
1923 true, false, false);
1924 if (buf == NULL)
1925 continue;
1926
1929 }
1930 }
1932 FreeDir(cldir);
1933}
int FreeDir(DIR *dir)
Definition fd.c:3008
DIR * AllocateDir(const char *dirname)
Definition fd.c:2890
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition fd.c:2956
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:2508

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

1026{
1028
1030 {
1033 records.tail->len = 0;
1034 records.tail->next = NULL;
1036
1037 records.bytes_free = Max(padlen, 512);
1039 }
1040
1042 records.tail->len += padlen;
1045}
#define Max(x, y)
Definition c.h:1034
#define palloc0_object(type)
Definition fe_memutils.h:75
struct StateFileChunk * next
Definition twophase.c:1003
uint32 bytes_free
Definition twophase.c:1011

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

Referenced by RegisterTwoPhaseRecord(), and StartPrepare().

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 2046 of file twophase.c.

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

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

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

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 1053 of file twophase.c.

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

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

952{
953 return snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X%08X",
956}
#define snprintf
Definition port.h:260

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

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

◆ TwoPhaseGetDummyProc()

PGPROC * TwoPhaseGetDummyProc ( FullTransactionId  fxid,
bool  lock_held 
)

Definition at line 924 of file twophase.c.

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

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

910{
912
913 return gxact->pgprocno;
914}

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

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

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

Referenced by TwoPhaseGetDummyProc(), and TwoPhaseGetDummyProcNumber().

◆ TwoPhaseGetOldestXidInCommit()

TransactionId TwoPhaseGetOldestXidInCommit ( void  )

Definition at line 2830 of file twophase.c.

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

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

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

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

Referenced by XactLockForVirtualXact().

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 255 of file twophase.c.

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

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

Referenced by CreateOrAttachShmemStructs().

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 239 of file twophase.c.

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

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

Referenced by CalculateShmemSize(), and TwoPhaseShmemInit().

◆ TwoPhaseTransactionGid()

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

Definition at line 2748 of file twophase.c.

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

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

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

◆ XlogReadTwoPhaseData()

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

Definition at line 1413 of file twophase.c.

1414{
1415 XLogRecord *record;
1417 char *errormsg;
1418
1420 XL_ROUTINE(.page_read = &read_local_xlog_page,
1421 .segment_open = &wal_segment_open,
1422 .segment_close = &wal_segment_close),
1423 NULL);
1424 if (!xlogreader)
1425 ereport(ERROR,
1427 errmsg("out of memory"),
1428 errdetail("Failed while allocating a WAL reading processor.")));
1429
1431 record = XLogReadRecord(xlogreader, &errormsg);
1432
1433 if (record == NULL)
1434 {
1435 if (errormsg)
1436 ereport(ERROR,
1438 errmsg("could not read two-phase state from WAL at %X/%08X: %s",
1439 LSN_FORMAT_ARGS(lsn), errormsg)));
1440 else
1441 ereport(ERROR,
1443 errmsg("could not read two-phase state from WAL at %X/%08X",
1444 LSN_FORMAT_ARGS(lsn))));
1445 }
1446
1449 ereport(ERROR,
1451 errmsg("expected two-phase state data is not present in WAL at %X/%08X",
1452 LSN_FORMAT_ARGS(lsn))));
1453
1454 if (len != NULL)
1456
1459
1461}
#define XLOG_XACT_OPMASK
Definition xact.h:180
int wal_segment_size
Definition xlog.c:146
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition xlogreader.c:107
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition xlogreader.c:390
void XLogReaderFree(XLogReaderState *state)
Definition xlogreader.c:162
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition xlogreader.c:232
#define XLogRecGetDataLen(decoder)
Definition xlogreader.h:415
#define XLogRecGetInfo(decoder)
Definition xlogreader.h:409
#define XLogRecGetRmid(decoder)
Definition xlogreader.h:410
#define XLogRecGetData(decoder)
Definition xlogreader.h:414
#define XL_ROUTINE(...)
Definition xlogreader.h:117
static XLogReaderState * xlogreader
void wal_segment_close(XLogReaderState *state)
Definition xlogutils.c:831
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition xlogutils.c:806
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition xlogutils.c:845

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

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

Variable Documentation

◆ max_prepared_xacts

◆ MyLockedGxact

◆ records

struct xllist records
static

◆ twophaseExitRegistered

bool twophaseExitRegistered = false
static

Definition at line 199 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseState