PostgreSQL Source Code  git master
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 "replication/walsender.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/md.h"
#include "storage/predicate.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/sinvaladt.h"
#include "storage/smgr.h"
#include "utils/builtins.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 TwoPhaseFilePath(path, xid)    snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
 
#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 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, TransactionId xid, const TwoPhaseCallback callbacks[])
 
static void RemoveGXact (GlobalTransaction gxact)
 
static void XlogReadTwoPhaseData (XLogRecPtr lsn, char **buf, int *len)
 
static char * ProcessTwoPhaseBuffer (TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
 
static void MarkAsPreparingGuts (GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
static void RemoveTwoPhaseFile (TransactionId xid, bool giveWarning)
 
static void RecreateTwoPhaseFile (TransactionId xid, 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 (TransactionId xid, 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 (TransactionId xid, bool lock_held)
 
TransactionId TwoPhaseGetXidByVirtualXID (VirtualTransactionId vxid, bool *have_more)
 
BackendId TwoPhaseGetDummyBackendId (TransactionId xid, bool lock_held)
 
PGPROCTwoPhaseGetDummyProc (TransactionId xid, bool lock_held)
 
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 char * ReadTwoPhaseFile (TransactionId xid, 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 (char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
 
void PrepareRedoRemove (TransactionId xid, bool giveWarning)
 
bool LookupGXact (const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
 

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

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */

Definition at line 967 of file twophase.c.

◆ TwoPhaseFilePath

#define TwoPhaseFilePath (   path,
  xid 
)     snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)

Definition at line 945 of file twophase.c.

Typedef Documentation

◆ GlobalTransactionData

◆ StateFileChunk

◆ TwoPhaseFileHeader

Definition at line 969 of file twophase.c.

◆ TwoPhaseRecordOnDisk

◆ TwoPhaseStateData

Function Documentation

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 322 of file twophase.c.

323 {
324  if (MyLockedGxact == NULL)
325  return;
326 
327  /*
328  * What to do with the locked global transaction entry? If we were in the
329  * process of preparing the transaction, but haven't written the WAL
330  * record and state file yet, the transaction must not be considered as
331  * prepared. Likewise, if we are in the process of finishing an
332  * already-prepared transaction, and fail after having already written the
333  * 2nd phase commit or rollback record to the WAL, the transaction should
334  * not be considered as prepared anymore. In those cases, just remove the
335  * entry from shared memory.
336  *
337  * Otherwise, the entry must be left in place so that the transaction can
338  * be finished later, so just unlock it.
339  *
340  * If we abort during prepare, after having written the WAL record, we
341  * might not have transferred all locks and other state to the prepared
342  * transaction yet. Likewise, if we abort during commit or rollback,
343  * after having written the WAL record, we might not have released all the
344  * resources held by the transaction yet. In those cases, the in-memory
345  * state can be wrong, but it's too late to back out.
346  */
347  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
348  if (!MyLockedGxact->valid)
350  else
352  LWLockRelease(TwoPhaseStateLock);
353 
354  MyLockedGxact = NULL;
355 }
#define InvalidBackendId
Definition: backendid.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
@ LW_EXCLUSIVE
Definition: lwlock.h:116
BackendId locking_backend
Definition: twophase.c:169
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:647
static GlobalTransaction MyLockedGxact
Definition: twophase.c:200

References InvalidBackendId, 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 312 of file twophase.c.

313 {
314  /* same logic as abort */
316 }
void AtAbort_Twophase(void)
Definition: twophase.c:322

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1794 of file twophase.c.

1795 {
1796  int i;
1797  int serialized_xacts = 0;
1798 
1799  if (max_prepared_xacts <= 0)
1800  return; /* nothing to do */
1801 
1802  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1803 
1804  /*
1805  * We are expecting there to be zero GXACTs that need to be copied to
1806  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1807  * simplicity. This prevents any new xacts from preparing while this
1808  * occurs, which shouldn't be a problem since the presence of long-lived
1809  * prepared xacts indicates the transaction manager isn't active.
1810  *
1811  * It's also possible to move I/O out of the lock, but on every error we
1812  * should check whether somebody committed our transaction in different
1813  * backend. Let's leave this optimization for future, if somebody will
1814  * spot that this place cause bottleneck.
1815  *
1816  * Note that it isn't possible for there to be a GXACT with a
1817  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1818  * because of the efforts with delayChkptFlags.
1819  */
1820  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1821  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1822  {
1823  /*
1824  * Note that we are using gxact not PGPROC so this works in recovery
1825  * also
1826  */
1828 
1829  if ((gxact->valid || gxact->inredo) &&
1830  !gxact->ondisk &&
1831  gxact->prepare_end_lsn <= redo_horizon)
1832  {
1833  char *buf;
1834  int len;
1835 
1837  RecreateTwoPhaseFile(gxact->xid, buf, len);
1838  gxact->ondisk = true;
1841  pfree(buf);
1842  serialized_xacts++;
1843  }
1844  }
1845  LWLockRelease(TwoPhaseStateLock);
1846 
1847  /*
1848  * Flush unconditionally the parent directory to make any information
1849  * durable on disk. Two-phase files could have been removed and those
1850  * removals need to be made persistent as well as any files newly created
1851  * previously since the last checkpoint.
1852  */
1853  fsync_fname(TWOPHASE_DIR, true);
1854 
1855  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1856 
1857  if (log_checkpoints && serialized_xacts > 0)
1858  ereport(LOG,
1859  (errmsg_plural("%u two-phase state file was written "
1860  "for a long-running prepared transaction",
1861  "%u two-phase state files were written "
1862  "for long-running prepared transactions",
1863  serialized_xacts,
1864  serialized_xacts)));
1865 }
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1179
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:708
int i
Definition: isn.c:73
@ LW_SHARED
Definition: lwlock.h:117
void pfree(void *pointer)
Definition: mcxt.c:1456
const void size_t len
static char * buf
Definition: pg_test_fsync.c:67
TransactionId xid
Definition: twophase.c:166
XLogRecPtr prepare_start_lsn
Definition: twophase.c:164
XLogRecPtr prepare_end_lsn
Definition: twophase.c:165
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:189
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1398
#define TWOPHASE_DIR
Definition: twophase.c:115
int max_prepared_xacts
Definition: twophase.c:118
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1714
bool log_checkpoints
Definition: xlog.c:132
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

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

Referenced by CheckPointGuts().

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1136 of file twophase.c.

1137 {
1138  TwoPhaseFileHeader *hdr;
1139  StateFileChunk *record;
1140  bool replorigin;
1141 
1142  /* Add the end sentinel to the list of 2PC records */
1144  NULL, 0);
1145 
1146  /* Go back and fill in total_len in the file header record */
1147  hdr = (TwoPhaseFileHeader *) records.head->data;
1148  Assert(hdr->magic == TWOPHASE_MAGIC);
1149  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1150 
1151  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1153 
1154  if (replorigin)
1155  {
1158  }
1159 
1160  /*
1161  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1162  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1163  * where we write data to file and then re-read at commit time.
1164  */
1165  if (hdr->total_len > MaxAllocSize)
1166  ereport(ERROR,
1167  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1168  errmsg("two-phase state file maximum length exceeded")));
1169 
1170  /*
1171  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1172  * cover us, so no need to calculate a separate CRC.
1173  *
1174  * We have to set DELAY_CHKPT_START here, too; otherwise a checkpoint
1175  * starting immediately after the WAL record is inserted could complete
1176  * without fsync'ing our state file. (This is essentially the same kind
1177  * of race condition as the COMMIT-to-clog-write case that
1178  * RecordTransactionCommit uses DELAY_CHKPT_START for; see notes there.)
1179  *
1180  * We save the PREPARE record's location in the gxact for later use by
1181  * CheckPointTwoPhase.
1182  */
1184 
1186 
1189 
1190  XLogBeginInsert();
1191  for (record = records.head; record != NULL; record = record->next)
1192  XLogRegisterData(record->data, record->len);
1193 
1195 
1196  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1197 
1198  if (replorigin)
1199  {
1200  /* Move LSNs forward for this replication origin */
1202  gxact->prepare_end_lsn);
1203  }
1204 
1205  XLogFlush(gxact->prepare_end_lsn);
1206 
1207  /* If we crash now, we have prepared: WAL replay will fix things */
1208 
1209  /* Store record's start location to read that later on Commit */
1211 
1212  /*
1213  * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
1214  * as not running our XID (which it will do immediately after this
1215  * function returns), others can commit/rollback the xact.
1216  *
1217  * NB: a side effect of this is to make a dummy ProcArray entry for the
1218  * prepared XID. This must happen before we clear the XID from MyProc /
1219  * ProcGlobal->xids[], else there is a window where the XID is not running
1220  * according to TransactionIdIsInProgress, and onlookers would be entitled
1221  * to assume the xact crashed. Instead we have a window where the same
1222  * XID appears twice in ProcArray, which is OK.
1223  */
1224  MarkAsPrepared(gxact, false);
1225 
1226  /*
1227  * Now we can mark ourselves as out of the commit critical section: a
1228  * checkpoint starting after this will certainly see the gxact as a
1229  * candidate for fsyncing.
1230  */
1232 
1233  /*
1234  * Remember that we have this GlobalTransaction entry locked for us. If
1235  * we crash after this point, it's too late to abort, but we must unlock
1236  * it so that the prepared transaction can be committed or rolled back.
1237  */
1238  MyLockedGxact = gxact;
1239 
1240  END_CRIT_SECTION();
1241 
1242  /*
1243  * Wait for synchronous replication, if required.
1244  *
1245  * Note that at this stage we have marked the prepare, but still show as
1246  * running in the procarray (twice!) and continue to hold locks.
1247  */
1248  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1249 
1250  records.tail = records.head = NULL;
1251  records.num_chunks = 0;
1252 }
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
Assert(fmt[strlen(fmt) - 1] !='\n')
#define MaxAllocSize
Definition: memutils.h:40
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:158
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1216
RepOriginId replorigin_session_origin
Definition: origin.c:156
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:157
#define DoNotReplicateId
Definition: origin.h:34
#define InvalidRepOriginId
Definition: origin.h:33
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define DELAY_CHKPT_START
Definition: proc.h:119
PGPROC * MyProc
Definition: proc.c:66
int delayChkptFlags
Definition: proc.h:231
struct StateFileChunk * next
Definition: twophase.c:993
uint32 len
Definition: twophase.c:992
char * data
Definition: twophase.c:991
TimestampTz origin_timestamp
Definition: xact.h:363
uint32 total_len
Definition: xact.h:349
XLogRecPtr origin_lsn
Definition: xact.h:362
uint32 magic
Definition: xact.h:348
uint32 total_len
Definition: twophase.c:1002
uint32 num_chunks
Definition: twophase.c:1000
StateFileChunk * head
Definition: twophase.c:998
StateFileChunk * tail
Definition: twophase.c:999
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:149
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1258
#define TWOPHASE_MAGIC
Definition: twophase.c:967
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:549
static struct xllist records
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
#define XLOG_XACT_PREPARE
Definition: xact.h:170
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:256
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2535
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:149
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:351
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:461
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:443
void XLogBeginInsert(void)
Definition: xloginsert.c:150
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition: xloginsert.c:176

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

Referenced by PrepareTransaction().

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1481 of file twophase.c.

1482 {
1483  GlobalTransaction gxact;
1484  PGPROC *proc;
1485  TransactionId xid;
1486  char *buf;
1487  char *bufptr;
1488  TwoPhaseFileHeader *hdr;
1489  TransactionId latestXid;
1490  TransactionId *children;
1491  RelFileLocator *commitrels;
1492  RelFileLocator *abortrels;
1493  RelFileLocator *delrels;
1494  int ndelrels;
1495  xl_xact_stats_item *commitstats;
1496  xl_xact_stats_item *abortstats;
1497  SharedInvalidationMessage *invalmsgs;
1498 
1499  /*
1500  * Validate the GID, and lock the GXACT to ensure that two backends do not
1501  * try to commit the same GID at once.
1502  */
1503  gxact = LockGXact(gid, GetUserId());
1504  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1505  xid = gxact->xid;
1506 
1507  /*
1508  * Read and validate 2PC state data. State data will typically be stored
1509  * in WAL files if the LSN is after the last checkpoint record, or moved
1510  * to disk if for some reason they have lived for a long time.
1511  */
1512  if (gxact->ondisk)
1513  buf = ReadTwoPhaseFile(xid, false);
1514  else
1515  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1516 
1517 
1518  /*
1519  * Disassemble the header area
1520  */
1521  hdr = (TwoPhaseFileHeader *) buf;
1522  Assert(TransactionIdEquals(hdr->xid, xid));
1523  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1524  bufptr += MAXALIGN(hdr->gidlen);
1525  children = (TransactionId *) bufptr;
1526  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1527  commitrels = (RelFileLocator *) bufptr;
1528  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
1529  abortrels = (RelFileLocator *) bufptr;
1530  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
1531  commitstats = (xl_xact_stats_item *) bufptr;
1532  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
1533  abortstats = (xl_xact_stats_item *) bufptr;
1534  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
1535  invalmsgs = (SharedInvalidationMessage *) bufptr;
1536  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1537 
1538  /* compute latestXid among all children */
1539  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1540 
1541  /* Prevent cancel/die interrupt while cleaning up */
1542  HOLD_INTERRUPTS();
1543 
1544  /*
1545  * The order of operations here is critical: make the XLOG entry for
1546  * commit or abort, then mark the transaction committed or aborted in
1547  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1548  * TransactionIdIsInProgress will stop saying the prepared xact is in
1549  * progress), then run the post-commit or post-abort callbacks. The
1550  * callbacks will release the locks the transaction held.
1551  */
1552  if (isCommit)
1554  hdr->nsubxacts, children,
1555  hdr->ncommitrels, commitrels,
1556  hdr->ncommitstats,
1557  commitstats,
1558  hdr->ninvalmsgs, invalmsgs,
1559  hdr->initfileinval, gid);
1560  else
1562  hdr->nsubxacts, children,
1563  hdr->nabortrels, abortrels,
1564  hdr->nabortstats,
1565  abortstats,
1566  gid);
1567 
1568  ProcArrayRemove(proc, latestXid);
1569 
1570  /*
1571  * In case we fail while running the callbacks, mark the gxact invalid so
1572  * no one else will try to commit/rollback, and so it will be recycled if
1573  * we fail after this point. It is still locked by our backend so it
1574  * won't go away yet.
1575  *
1576  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1577  */
1578  gxact->valid = false;
1579 
1580  /*
1581  * We have to remove any files that were supposed to be dropped. For
1582  * consistency with the regular xact.c code paths, must do this before
1583  * releasing locks, so do it before running the callbacks.
1584  *
1585  * NB: this code knows that we couldn't be dropping any temp rels ...
1586  */
1587  if (isCommit)
1588  {
1589  delrels = commitrels;
1590  ndelrels = hdr->ncommitrels;
1591  }
1592  else
1593  {
1594  delrels = abortrels;
1595  ndelrels = hdr->nabortrels;
1596  }
1597 
1598  /* Make sure files supposed to be dropped are dropped */
1599  DropRelationFiles(delrels, ndelrels, false);
1600 
1601  if (isCommit)
1602  pgstat_execute_transactional_drops(hdr->ncommitstats, commitstats, false);
1603  else
1604  pgstat_execute_transactional_drops(hdr->nabortstats, abortstats, false);
1605 
1606  /*
1607  * Handle cache invalidation messages.
1608  *
1609  * Relcache init file invalidation requires processing both before and
1610  * after we send the SI messages, only when committing. See
1611  * AtEOXact_Inval().
1612  */
1613  if (isCommit)
1614  {
1615  if (hdr->initfileinval)
1617  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1618  if (hdr->initfileinval)
1620  }
1621 
1622  /*
1623  * Acquire the two-phase lock. We want to work on the two-phase callbacks
1624  * while holding it to avoid potential conflicts with other transactions
1625  * attempting to use the same GID, so the lock is released once the shared
1626  * memory state is cleared.
1627  */
1628  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1629 
1630  /* And now do the callbacks */
1631  if (isCommit)
1633  else
1635 
1636  PredicateLockTwoPhaseFinish(xid, isCommit);
1637 
1638  /* Clear shared memory state */
1639  RemoveGXact(gxact);
1640 
1641  /*
1642  * Release the lock as all callbacks are called and shared memory cleanup
1643  * is done.
1644  */
1645  LWLockRelease(TwoPhaseStateLock);
1646 
1647  /* Count the prepared xact as committed or aborted */
1648  AtEOXact_PgStat(isCommit, false);
1649 
1650  /*
1651  * And now we can clean up any files we may have left.
1652  */
1653  if (gxact->ondisk)
1654  RemoveTwoPhaseFile(xid, true);
1655 
1656  MyLockedGxact = NULL;
1657 
1659 
1660  pfree(buf);
1661 }
#define MAXALIGN(LEN)
Definition: c.h:800
uint32 TransactionId
Definition: c.h:641
void DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo)
Definition: md.c:1252
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
Oid GetUserId(void)
Definition: miscinit.c:509
void pgstat_execute_transactional_drops(int ndrops, struct xl_xact_stats_item *items, bool is_redo)
Definition: pgstat_xact.c:313
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat_xact.c:41
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:4816
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:565
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:6761
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:6736
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
PROC_HDR * ProcGlobal
Definition: proc.c:78
Definition: proc.h:162
PGPROC * allProcs
Definition: proc.h:362
int32 nabortrels
Definition: xact.h:356
int32 ninvalmsgs
Definition: xact.h:359
bool initfileinval
Definition: xact.h:360
int32 ncommitstats
Definition: xact.h:357
uint16 gidlen
Definition: xact.h:361
int32 nabortstats
Definition: xact.h:358
int32 ncommitrels
Definition: xact.h:355
TransactionId xid
Definition: xact.h:350
int32 nsubxacts
Definition: xact.h:354
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:345
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
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:2381
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:2283
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1667
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1695
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1281
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:571
const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:33
const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:42

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

686 {
687  GlobalTransaction array;
688  int num;
689  int i;
690 
691  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
692 
693  if (TwoPhaseState->numPrepXacts == 0)
694  {
695  LWLockRelease(TwoPhaseStateLock);
696 
697  *gxacts = NULL;
698  return 0;
699  }
700 
702  array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
703  *gxacts = array;
704  for (i = 0; i < num; i++)
705  memcpy(array + i, TwoPhaseState->prepXacts[i],
706  sizeof(GlobalTransactionData));
707 
708  LWLockRelease(TwoPhaseStateLock);
709 
710  return num;
711 }
void * palloc(Size size)
Definition: mcxt.c:1226
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:26

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

Referenced by pg_prepared_xact().

◆ GXactLoadSubxactData()

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

Definition at line 523 of file twophase.c.

525 {
526  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
527 
528  /* We need no extra lock since the GXACT isn't valid yet */
529  if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
530  {
531  proc->subxidStatus.overflowed = true;
532  nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
533  }
534  if (nsubxacts > 0)
535  {
536  memcpy(proc->subxids.xids, children,
537  nsubxacts * sizeof(TransactionId));
538  proc->subxidStatus.count = nsubxacts;
539  }
540 }
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:38
XidCacheStatus subxidStatus
Definition: proc.h:254
struct XidCache subxids
Definition: proc.h:256
bool overflowed
Definition: proc.h:45
uint8 count
Definition: proc.h:43
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:50

References PROC_HDR::allProcs, XidCacheStatus::count, XidCacheStatus::overflowed, PGPROC_MAX_CACHED_SUBXIDS, GlobalTransactionData::pgprocno, ProcGlobal, PGPROC::subxids, PGPROC::subxidStatus, and XidCache::xids.

Referenced by RecoverPreparedTransactions(), and StartPrepare().

◆ LockGXact()

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

Definition at line 571 of file twophase.c.

572 {
573  int i;
574 
575  /* on first call, register the exit hook */
577  {
579  twophaseExitRegistered = true;
580  }
581 
582  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
583 
584  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
585  {
587  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
588 
589  /* Ignore not-yet-valid GIDs */
590  if (!gxact->valid)
591  continue;
592  if (strcmp(gxact->gid, gid) != 0)
593  continue;
594 
595  /* Found it, but has someone else got it locked? */
596  if (gxact->locking_backend != InvalidBackendId)
597  ereport(ERROR,
598  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
599  errmsg("prepared transaction with identifier \"%s\" is busy",
600  gid)));
601 
602  if (user != gxact->owner && !superuser_arg(user))
603  ereport(ERROR,
604  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
605  errmsg("permission denied to finish prepared transaction"),
606  errhint("Must be superuser or the user that prepared the transaction.")));
607 
608  /*
609  * Note: it probably would be possible to allow committing from
610  * another database; but at the moment NOTIFY is known not to work and
611  * there may be some other issues as well. Hence disallow until
612  * someone gets motivated to make it work.
613  */
614  if (MyDatabaseId != proc->databaseId)
615  ereport(ERROR,
616  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
617  errmsg("prepared transaction belongs to another database"),
618  errhint("Connect to the database where the transaction was prepared to finish it.")));
619 
620  /* OK for me to lock it */
621  gxact->locking_backend = MyBackendId;
622  MyLockedGxact = gxact;
623 
624  LWLockRelease(TwoPhaseStateLock);
625 
626  return gxact;
627  }
628 
629  LWLockRelease(TwoPhaseStateLock);
630 
631  ereport(ERROR,
632  (errcode(ERRCODE_UNDEFINED_OBJECT),
633  errmsg("prepared transaction with identifier \"%s\" does not exist",
634  gid)));
635 
636  /* NOTREACHED */
637  return NULL;
638 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
BackendId MyBackendId
Definition: globals.c:85
Oid MyDatabaseId
Definition: globals.c:89
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
static char * user
Definition: pg_regress.c:112
char gid[GIDSIZE]
Definition: twophase.c:173
Oid databaseId
Definition: proc.h:198
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
static bool twophaseExitRegistered
Definition: twophase.c:202
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:312

References PROC_HDR::allProcs, AtProcExit_Twophase(), before_shmem_exit(), PGPROC::databaseId, ereport, errcode(), errhint(), errmsg(), ERROR, GlobalTransactionData::gid, i, InvalidBackendId, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyBackendId, MyDatabaseId, MyLockedGxact, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::owner, GlobalTransactionData::pgprocno, TwoPhaseStateData::prepXacts, ProcGlobal, superuser_arg(), twophaseExitRegistered, TwoPhaseState, user, and GlobalTransactionData::valid.

Referenced by FinishPreparedTransaction().

◆ LookupGXact()

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

Definition at line 2610 of file twophase.c.

2612 {
2613  int i;
2614  bool found = false;
2615 
2616  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
2617  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2618  {
2620 
2621  /* Ignore not-yet-valid GIDs. */
2622  if (gxact->valid && strcmp(gxact->gid, gid) == 0)
2623  {
2624  char *buf;
2625  TwoPhaseFileHeader *hdr;
2626 
2627  /*
2628  * We are not expecting collisions of GXACTs (same gid) between
2629  * publisher and subscribers, so we perform all I/O while holding
2630  * TwoPhaseStateLock for simplicity.
2631  *
2632  * To move the I/O out of the lock, we need to ensure that no
2633  * other backend commits the prepared xact in the meantime. We can
2634  * do this optimization if we encounter many collisions in GID
2635  * between publisher and subscriber.
2636  */
2637  if (gxact->ondisk)
2638  buf = ReadTwoPhaseFile(gxact->xid, false);
2639  else
2640  {
2641  Assert(gxact->prepare_start_lsn);
2642  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
2643  }
2644 
2645  hdr = (TwoPhaseFileHeader *) buf;
2646 
2647  if (hdr->origin_lsn == prepare_end_lsn &&
2648  hdr->origin_timestamp == origin_prepare_timestamp)
2649  {
2650  found = true;
2651  pfree(buf);
2652  break;
2653  }
2654 
2655  pfree(buf);
2656  }
2657  }
2658  LWLockRelease(TwoPhaseStateLock);
2659  return found;
2660 }

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

Referenced by apply_handle_rollback_prepared().

◆ MarkAsPrepared()

static void MarkAsPrepared ( GlobalTransaction  gxact,
bool  lock_held 
)
static

Definition at line 549 of file twophase.c.

550 {
551  /* Lock here may be overkill, but I'm not convinced of that ... */
552  if (!lock_held)
553  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
554  Assert(!gxact->valid);
555  gxact->valid = true;
556  if (!lock_held)
557  LWLockRelease(TwoPhaseStateLock);
558 
559  /*
560  * Put it into the global ProcArray so TransactionIdIsInProgress considers
561  * the XID as still running.
562  */
564 }
void ProcArrayAdd(PGPROC *proc)
Definition: procarray.c:469

References PROC_HDR::allProcs, Assert(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), GlobalTransactionData::pgprocno, ProcArrayAdd(), ProcGlobal, and GlobalTransactionData::valid.

Referenced by EndPrepare(), and RecoverPreparedTransactions().

◆ MarkAsPreparing()

GlobalTransaction MarkAsPreparing ( TransactionId  xid,
const char *  gid,
TimestampTz  prepared_at,
Oid  owner,
Oid  databaseid 
)

Definition at line 377 of file twophase.c.

379 {
380  GlobalTransaction gxact;
381  int i;
382 
383  if (strlen(gid) >= GIDSIZE)
384  ereport(ERROR,
385  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
386  errmsg("transaction identifier \"%s\" is too long",
387  gid)));
388 
389  /* fail immediately if feature is disabled */
390  if (max_prepared_xacts == 0)
391  ereport(ERROR,
392  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
393  errmsg("prepared transactions are disabled"),
394  errhint("Set max_prepared_transactions to a nonzero value.")));
395 
396  /* on first call, register the exit hook */
398  {
400  twophaseExitRegistered = true;
401  }
402 
403  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
404 
405  /* Check for conflicting GID */
406  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
407  {
408  gxact = TwoPhaseState->prepXacts[i];
409  if (strcmp(gxact->gid, gid) == 0)
410  {
411  ereport(ERROR,
413  errmsg("transaction identifier \"%s\" is already in use",
414  gid)));
415  }
416  }
417 
418  /* Get a free gxact from the freelist */
419  if (TwoPhaseState->freeGXacts == NULL)
420  ereport(ERROR,
421  (errcode(ERRCODE_OUT_OF_MEMORY),
422  errmsg("maximum number of prepared transactions reached"),
423  errhint("Increase max_prepared_transactions (currently %d).",
425  gxact = TwoPhaseState->freeGXacts;
426  TwoPhaseState->freeGXacts = gxact->next;
427 
428  MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
429 
430  gxact->ondisk = false;
431 
432  /* And insert it into the active array */
435 
436  LWLockRelease(TwoPhaseStateLock);
437 
438  return gxact;
439 }
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
GlobalTransaction next
Definition: twophase.c:152
GlobalTransaction freeGXacts
Definition: twophase.c:183
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:451
#define GIDSIZE
Definition: xact.h:31

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

Referenced by PrepareTransaction().

◆ MarkAsPreparingGuts()

static void MarkAsPreparingGuts ( GlobalTransaction  gxact,
TransactionId  xid,
const char *  gid,
TimestampTz  prepared_at,
Oid  owner,
Oid  databaseid 
)
static

Definition at line 451 of file twophase.c.

453 {
454  PGPROC *proc;
455  int i;
456 
457  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
458 
459  Assert(gxact != NULL);
460  proc = &ProcGlobal->allProcs[gxact->pgprocno];
461 
462  /* Initialize the PGPROC entry */
463  MemSet(proc, 0, sizeof(PGPROC));
464  proc->pgprocno = gxact->pgprocno;
465  dlist_node_init(&proc->links);
468  {
469  /* clone VXID, for TwoPhaseGetXidByVirtualXID() to find */
470  proc->lxid = MyProc->lxid;
471  proc->backendId = MyBackendId;
472  }
473  else
474  {
476  /* GetLockConflicts() uses this to specify a wait on the XID */
477  proc->lxid = xid;
478  proc->backendId = InvalidBackendId;
479  }
480  proc->xid = xid;
481  Assert(proc->xmin == InvalidTransactionId);
482  proc->delayChkptFlags = 0;
483  proc->statusFlags = 0;
484  proc->pid = 0;
485  proc->databaseId = databaseid;
486  proc->roleId = owner;
487  proc->tempNamespaceId = InvalidOid;
488  proc->isBackgroundWorker = false;
490  proc->lwWaitMode = 0;
491  proc->waitLock = NULL;
492  proc->waitProcLock = NULL;
493  pg_atomic_init_u64(&proc->waitStart, 0);
494  for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
495  dlist_init(&proc->myProcLocks[i]);
496  /* subxid data must be filled later by GXactLoadSubxactData */
497  proc->subxidStatus.overflowed = false;
498  proc->subxidStatus.count = 0;
499 
500  gxact->prepared_at = prepared_at;
501  gxact->xid = xid;
502  gxact->owner = owner;
503  gxact->locking_backend = MyBackendId;
504  gxact->valid = false;
505  gxact->inredo = false;
506  strcpy(gxact->gid, gid);
507 
508  /*
509  * Remember that we have this GlobalTransaction entry locked for us. If we
510  * abort after this, we must release it.
511  */
512  MyLockedGxact = gxact;
513 }
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:410
#define MemSet(start, val, len)
Definition: c.h:1009
bool IsPostmasterEnvironment
Definition: globals.c:112
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:66
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1964
@ LW_WS_NOT_WAITING
Definition: lwlock.h:29
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:99
#define AmStartupProcess()
Definition: miscadmin.h:452
#define InvalidOid
Definition: postgres_ext.h:36
@ PROC_WAIT_STATUS_OK
Definition: proc.h:124
TimestampTz prepared_at
Definition: twophase.c:155
TransactionId xmin
Definition: proc.h:178
LocalTransactionId lxid
Definition: proc.h:183
PROCLOCK * waitProcLock
Definition: proc.h:224
uint8 lwWaitMode
Definition: proc.h:215
uint8 statusFlags
Definition: proc.h:233
pg_atomic_uint64 waitStart
Definition: proc.h:228
BackendId backendId
Definition: proc.h:197
int pid
Definition: proc.h:186
bool isBackgroundWorker
Definition: proc.h:204
LOCK * waitLock
Definition: proc.h:223
TransactionId xid
Definition: proc.h:173
int pgprocno
Definition: proc.h:191
dlist_head myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:252
Oid roleId
Definition: proc.h:199
ProcWaitStatus waitStatus
Definition: proc.h:168
Oid tempNamespaceId
Definition: proc.h:201
dlist_node links
Definition: proc.h:164
uint8 lwWaiting
Definition: proc.h:214
#define InvalidTransactionId
Definition: transam.h:31

References PROC_HDR::allProcs, AmStartupProcess, Assert(), PGPROC::backendId, XidCacheStatus::count, PGPROC::databaseId, PGPROC::delayChkptFlags, dlist_init(), dlist_node_init(), GlobalTransactionData::gid, i, GlobalTransactionData::inredo, InvalidBackendId, InvalidOid, InvalidTransactionId, PGPROC::isBackgroundWorker, IsPostmasterEnvironment, PGPROC::links, LocalTransactionIdIsValid, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LW_WS_NOT_WAITING, LWLockHeldByMeInMode(), PGPROC::lwWaiting, PGPROC::lwWaitMode, PGPROC::lxid, MemSet, MyBackendId, MyLockedGxact, MyProc, PGPROC::myProcLocks, NUM_LOCK_PARTITIONS, XidCacheStatus::overflowed, GlobalTransactionData::owner, pg_atomic_init_u64(), GlobalTransactionData::pgprocno, PGPROC::pgprocno, PGPROC::pid, GlobalTransactionData::prepared_at, PROC_WAIT_STATUS_OK, ProcGlobal, PGPROC::roleId, PGPROC::statusFlags, PGPROC::subxidStatus, PGPROC::tempNamespaceId, GlobalTransactionData::valid, PGPROC::waitLock, PGPROC::waitProcLock, PGPROC::waitStart, PGPROC::waitStatus, GlobalTransactionData::xid, PGPROC::xid, and PGPROC::xmin.

Referenced by MarkAsPreparing(), and RecoverPreparedTransactions().

◆ pg_prepared_xact()

Datum pg_prepared_xact ( PG_FUNCTION_ARGS  )

Definition at line 730 of file twophase.c.

731 {
732  FuncCallContext *funcctx;
733  Working_State *status;
734 
735  if (SRF_IS_FIRSTCALL())
736  {
737  TupleDesc tupdesc;
738  MemoryContext oldcontext;
739 
740  /* create a function context for cross-call persistence */
741  funcctx = SRF_FIRSTCALL_INIT();
742 
743  /*
744  * Switch to memory context appropriate for multiple function calls
745  */
746  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
747 
748  /* build tupdesc for result tuples */
749  /* this had better match pg_prepared_xacts view in system_views.sql */
750  tupdesc = CreateTemplateTupleDesc(5);
751  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
752  XIDOID, -1, 0);
753  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
754  TEXTOID, -1, 0);
755  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
756  TIMESTAMPTZOID, -1, 0);
757  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
758  OIDOID, -1, 0);
759  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
760  OIDOID, -1, 0);
761 
762  funcctx->tuple_desc = BlessTupleDesc(tupdesc);
763 
764  /*
765  * Collect all the 2PC status information that we will format and send
766  * out as a result set.
767  */
768  status = (Working_State *) palloc(sizeof(Working_State));
769  funcctx->user_fctx = (void *) status;
770 
771  status->ngxacts = GetPreparedTransactionList(&status->array);
772  status->currIdx = 0;
773 
774  MemoryContextSwitchTo(oldcontext);
775  }
776 
777  funcctx = SRF_PERCALL_SETUP();
778  status = (Working_State *) funcctx->user_fctx;
779 
780  while (status->array != NULL && status->currIdx < status->ngxacts)
781  {
782  GlobalTransaction gxact = &status->array[status->currIdx++];
783  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
784  Datum values[5] = {0};
785  bool nulls[5] = {0};
786  HeapTuple tuple;
787  Datum result;
788 
789  if (!gxact->valid)
790  continue;
791 
792  /*
793  * Form tuple with appropriate data.
794  */
795 
796  values[0] = TransactionIdGetDatum(proc->xid);
797  values[1] = CStringGetTextDatum(gxact->gid);
799  values[3] = ObjectIdGetDatum(gxact->owner);
800  values[4] = ObjectIdGetDatum(proc->databaseId);
801 
802  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
803  result = HeapTupleGetDatum(tuple);
804  SRF_RETURN_NEXT(funcctx, result);
805  }
806 
807  SRF_RETURN_DONE(funcctx);
808 }
int16 AttrNumber
Definition: attnum.h:21
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:94
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2072
#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, Datum *values, bool *isnull)
Definition: heaptuple.c:1108
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
while(p+4<=pend)
static Datum TransactionIdGetDatum(TransactionId X)
Definition: postgres.h:272
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
TupleDesc tuple_desc
Definition: funcapi.h:112
GlobalTransaction array
Definition: twophase.c:717
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:583
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition: twophase.c:685
static Datum TimestampTzGetDatum(TimestampTz X)
Definition: timestamp.h:52

References PROC_HDR::allProcs, Working_State::array, BlessTupleDesc(), CreateTemplateTupleDesc(), CStringGetTextDatum, Working_State::currIdx, PGPROC::databaseId, GetPreparedTransactionList(), GlobalTransactionData::gid, heap_form_tuple(), HeapTupleGetDatum(), MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, Working_State::ngxacts, ObjectIdGetDatum(), GlobalTransactionData::owner, palloc(), GlobalTransactionData::pgprocno, GlobalTransactionData::prepared_at, ProcGlobal, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, TimestampTzGetDatum(), TransactionIdGetDatum(), FuncCallContext::tuple_desc, TupleDescInitEntry(), FuncCallContext::user_fctx, GlobalTransactionData::valid, values, while(), and PGPROC::xid.

◆ PostPrepare_Twophase()

void PostPrepare_Twophase ( void  )

Definition at line 362 of file twophase.c.

363 {
364  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
366  LWLockRelease(TwoPhaseStateLock);
367 
368  MyLockedGxact = NULL;
369 }

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

◆ PrepareRedoAdd()

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

Definition at line 2456 of file twophase.c.

2458 {
2460  char *bufptr;
2461  const char *gid;
2462  GlobalTransaction gxact;
2463 
2464  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2466 
2467  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2468  gid = (const char *) bufptr;
2469 
2470  /*
2471  * Reserve the GID for the given transaction in the redo code path.
2472  *
2473  * This creates a gxact struct and puts it into the active array.
2474  *
2475  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2476  * shared memory. Hence, we only fill up the bare minimum contents here.
2477  * The gxact also gets marked with gxact->inredo set to true to indicate
2478  * that it got added in the redo phase
2479  */
2480 
2481  /*
2482  * In the event of a crash while a checkpoint was running, it may be
2483  * possible that some two-phase data found its way to disk while its
2484  * corresponding record needs to be replayed in the follow-up recovery. As
2485  * the 2PC data was on disk, it has already been restored at the beginning
2486  * of recovery with restoreTwoPhaseData(), so skip this record to avoid
2487  * duplicates in TwoPhaseState. If a consistent state has been reached,
2488  * the record is added to TwoPhaseState and it should have no
2489  * corresponding file in pg_twophase.
2490  */
2491  if (!XLogRecPtrIsInvalid(start_lsn))
2492  {
2493  char path[MAXPGPATH];
2494 
2495  TwoPhaseFilePath(path, hdr->xid);
2496 
2497  if (access(path, F_OK) == 0)
2498  {
2500  (errmsg("could not recover two-phase state file for transaction %u",
2501  hdr->xid),
2502  errdetail("Two-phase state file has been found in WAL record %X/%X, but this transaction has already been restored from disk.",
2503  LSN_FORMAT_ARGS(start_lsn))));
2504  return;
2505  }
2506 
2507  if (errno != ENOENT)
2508  ereport(ERROR,
2510  errmsg("could not access file \"%s\": %m", path)));
2511  }
2512 
2513  /* Get a free gxact from the freelist */
2514  if (TwoPhaseState->freeGXacts == NULL)
2515  ereport(ERROR,
2516  (errcode(ERRCODE_OUT_OF_MEMORY),
2517  errmsg("maximum number of prepared transactions reached"),
2518  errhint("Increase max_prepared_transactions (currently %d).",
2519  max_prepared_xacts)));
2520  gxact = TwoPhaseState->freeGXacts;
2521  TwoPhaseState->freeGXacts = gxact->next;
2522 
2523  gxact->prepared_at = hdr->prepared_at;
2524  gxact->prepare_start_lsn = start_lsn;
2525  gxact->prepare_end_lsn = end_lsn;
2526  gxact->xid = hdr->xid;
2527  gxact->owner = hdr->owner;
2529  gxact->valid = false;
2530  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2531  gxact->inredo = true; /* yes, added in redo */
2532  strcpy(gxact->gid, gid);
2533 
2534  /* And insert it into the active array */
2537 
2538  if (origin_id != InvalidRepOriginId)
2539  {
2540  /* recover apply progress */
2541  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2542  false /* backward */ , false /* WAL */ );
2543  }
2544 
2545  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2546 }
int errcode_for_file_access(void)
Definition: elog.c:881
int errdetail(const char *fmt,...)
Definition: elog.c:1202
#define WARNING
Definition: elog.h:36
#define DEBUG2
Definition: elog.h:29
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:888
#define MAXPGPATH
short access
Definition: preproc-type.c:36
TimestampTz prepared_at
Definition: xact.h:352
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:945
bool RecoveryInProgress(void)
Definition: xlog.c:5948
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
bool reachedConsistency
Definition: xlogrecovery.c:294

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

Referenced by restoreTwoPhaseData(), and xact_redo().

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2558 of file twophase.c.

2559 {
2560  GlobalTransaction gxact = NULL;
2561  int i;
2562  bool found = false;
2563 
2564  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2566 
2567  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2568  {
2569  gxact = TwoPhaseState->prepXacts[i];
2570 
2571  if (gxact->xid == xid)
2572  {
2573  Assert(gxact->inredo);
2574  found = true;
2575  break;
2576  }
2577  }
2578 
2579  /*
2580  * Just leave if there is nothing, this is expected during WAL replay.
2581  */
2582  if (!found)
2583  return;
2584 
2585  /*
2586  * And now we can clean up any files we may have left.
2587  */
2588  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2589  if (gxact->ondisk)
2590  RemoveTwoPhaseFile(xid, giveWarning);
2591  RemoveGXact(gxact);
2592 }

References Assert(), DEBUG2, elog(), i, GlobalTransactionData::inredo, LW_EXCLUSIVE, LWLockHeldByMeInMode(), TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, TwoPhaseStateData::prepXacts, RecoveryInProgress(), RemoveGXact(), RemoveTwoPhaseFile(), TwoPhaseState, and GlobalTransactionData::xid.

Referenced by ProcessTwoPhaseBuffer(), and xact_redo().

◆ PrescanPreparedTransactions()

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

Definition at line 1938 of file twophase.c.

1939 {
1941  TransactionId origNextXid = XidFromFullTransactionId(nextXid);
1942  TransactionId result = origNextXid;
1943  TransactionId *xids = NULL;
1944  int nxids = 0;
1945  int allocsize = 0;
1946  int i;
1947 
1948  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1949  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1950  {
1951  TransactionId xid;
1952  char *buf;
1954 
1955  Assert(gxact->inredo);
1956 
1957  xid = gxact->xid;
1958 
1959  buf = ProcessTwoPhaseBuffer(xid,
1960  gxact->prepare_start_lsn,
1961  gxact->ondisk, false, true);
1962 
1963  if (buf == NULL)
1964  continue;
1965 
1966  /*
1967  * OK, we think this file is valid. Incorporate xid into the
1968  * running-minimum result.
1969  */
1970  if (TransactionIdPrecedes(xid, result))
1971  result = xid;
1972 
1973  if (xids_p)
1974  {
1975  if (nxids == allocsize)
1976  {
1977  if (nxids == 0)
1978  {
1979  allocsize = 10;
1980  xids = palloc(allocsize * sizeof(TransactionId));
1981  }
1982  else
1983  {
1984  allocsize = allocsize * 2;
1985  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1986  }
1987  }
1988  xids[nxids++] = xid;
1989  }
1990 
1991  pfree(buf);
1992  }
1993  LWLockRelease(TwoPhaseStateLock);
1994 
1995  if (xids_p)
1996  {
1997  *xids_p = xids;
1998  *nxids_p = nxids;
1999  }
2000 
2001  return result;
2002 }
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1476
FullTransactionId nextXid
Definition: transam.h:220
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
#define XidFromFullTransactionId(x)
Definition: transam.h:48
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2163
VariableCache ShmemVariableCache
Definition: varsup.c:34

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

Referenced by StartupXLOG(), and xlog_redo().

◆ ProcessRecords()

static void ProcessRecords ( char *  bufptr,
TransactionId  xid,
const TwoPhaseCallback  callbacks[] 
)
static

Definition at line 1667 of file twophase.c.

1669 {
1670  for (;;)
1671  {
1672  TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1673 
1674  Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1675  if (record->rmid == TWOPHASE_RM_END_ID)
1676  break;
1677 
1678  bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1679 
1680  if (callbacks[record->rmid] != NULL)
1681  callbacks[record->rmid] (xid, record->info,
1682  (void *) bufptr, record->len);
1683 
1684  bufptr += MAXALIGN(record->len);
1685  }
1686 }
TwoPhaseRmgrId rmid
Definition: twophase.c:980
#define TWOPHASE_RM_MAX_ID
Definition: twophase_rmgr.h:29

References Assert(), 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 ( TransactionId  xid,
XLogRecPtr  prepare_start_lsn,
bool  fromdisk,
bool  setParent,
bool  setNextXid 
)
static

Definition at line 2163 of file twophase.c.

2167 {
2169  TransactionId origNextXid = XidFromFullTransactionId(nextXid);
2170  TransactionId *subxids;
2171  char *buf;
2172  TwoPhaseFileHeader *hdr;
2173  int i;
2174 
2175  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2176 
2177  if (!fromdisk)
2178  Assert(prepare_start_lsn != InvalidXLogRecPtr);
2179 
2180  /* Already processed? */
2182  {
2183  if (fromdisk)
2184  {
2185  ereport(WARNING,
2186  (errmsg("removing stale two-phase state file for transaction %u",
2187  xid)));
2188  RemoveTwoPhaseFile(xid, true);
2189  }
2190  else
2191  {
2192  ereport(WARNING,
2193  (errmsg("removing stale two-phase state from memory for transaction %u",
2194  xid)));
2195  PrepareRedoRemove(xid, true);
2196  }
2197  return NULL;
2198  }
2199 
2200  /* Reject XID if too new */
2201  if (TransactionIdFollowsOrEquals(xid, origNextXid))
2202  {
2203  if (fromdisk)
2204  {
2205  ereport(WARNING,
2206  (errmsg("removing future two-phase state file for transaction %u",
2207  xid)));
2208  RemoveTwoPhaseFile(xid, true);
2209  }
2210  else
2211  {
2212  ereport(WARNING,
2213  (errmsg("removing future two-phase state from memory for transaction %u",
2214  xid)));
2215  PrepareRedoRemove(xid, true);
2216  }
2217  return NULL;
2218  }
2219 
2220  if (fromdisk)
2221  {
2222  /* Read and validate file */
2223  buf = ReadTwoPhaseFile(xid, false);
2224  }
2225  else
2226  {
2227  /* Read xlog data */
2228  XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2229  }
2230 
2231  /* Deconstruct header */
2232  hdr = (TwoPhaseFileHeader *) buf;
2233  if (!TransactionIdEquals(hdr->xid, xid))
2234  {
2235  if (fromdisk)
2236  ereport(ERROR,
2238  errmsg("corrupted two-phase state file for transaction %u",
2239  xid)));
2240  else
2241  ereport(ERROR,
2243  errmsg("corrupted two-phase state in memory for transaction %u",
2244  xid)));
2245  }
2246 
2247  /*
2248  * Examine subtransaction XIDs ... they should all follow main XID, and
2249  * they may force us to advance nextXid.
2250  */
2251  subxids = (TransactionId *) (buf +
2252  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2253  MAXALIGN(hdr->gidlen));
2254  for (i = 0; i < hdr->nsubxacts; i++)
2255  {
2256  TransactionId subxid = subxids[i];
2257 
2258  Assert(TransactionIdFollows(subxid, xid));
2259 
2260  /* update nextXid if needed */
2261  if (setNextXid)
2263 
2264  if (setParent)
2265  SubTransSetParent(subxid, xid);
2266  }
2267 
2268  return buf;
2269 }
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition: subtrans.c:74
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:188
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:314
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:329
void PrepareRedoRemove(TransactionId xid, bool giveWarning)
Definition: twophase.c:2558
void AdvanceNextFullTransactionIdPastXid(TransactionId xid)
Definition: varsup.c:277

References AdvanceNextFullTransactionIdPastXid(), Assert(), buf, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg(), ERROR, xl_xact_prepare::gidlen, i, InvalidXLogRecPtr, LW_EXCLUSIVE, LWLockHeldByMeInMode(), MAXALIGN, VariableCacheData::nextXid, xl_xact_prepare::nsubxacts, PrepareRedoRemove(), ReadTwoPhaseFile(), RemoveTwoPhaseFile(), ShmemVariableCache, SubTransSetParent(), TransactionIdDidAbort(), TransactionIdDidCommit(), TransactionIdEquals, TransactionIdFollows(), TransactionIdFollowsOrEquals(), WARNING, xl_xact_prepare::xid, XidFromFullTransactionId, and XlogReadTwoPhaseData().

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

◆ ReadTwoPhaseFile()

static char* ReadTwoPhaseFile ( TransactionId  xid,
bool  missing_ok 
)
static

Definition at line 1281 of file twophase.c.

1282 {
1283  char path[MAXPGPATH];
1284  char *buf;
1285  TwoPhaseFileHeader *hdr;
1286  int fd;
1287  struct stat stat;
1288  uint32 crc_offset;
1289  pg_crc32c calc_crc,
1290  file_crc;
1291  int r;
1292 
1293  TwoPhaseFilePath(path, xid);
1294 
1295  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
1296  if (fd < 0)
1297  {
1298  if (missing_ok && errno == ENOENT)
1299  return NULL;
1300 
1301  ereport(ERROR,
1303  errmsg("could not open file \"%s\": %m", path)));
1304  }
1305 
1306  /*
1307  * Check file length. We can determine a lower bound pretty easily. We
1308  * set an upper bound to avoid palloc() failure on a corrupt file, though
1309  * we can't guarantee that we won't get an out of memory error anyway,
1310  * even on a valid file.
1311  */
1312  if (fstat(fd, &stat))
1313  ereport(ERROR,
1315  errmsg("could not stat file \"%s\": %m", path)));
1316 
1317  if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1318  MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1319  sizeof(pg_crc32c)) ||
1321  ereport(ERROR,
1323  errmsg_plural("incorrect size of file \"%s\": %lld byte",
1324  "incorrect size of file \"%s\": %lld bytes",
1325  (long long int) stat.st_size, path,
1326  (long long int) stat.st_size)));
1327 
1328  crc_offset = stat.st_size - sizeof(pg_crc32c);
1329  if (crc_offset != MAXALIGN(crc_offset))
1330  ereport(ERROR,
1332  errmsg("incorrect alignment of CRC offset for file \"%s\"",
1333  path)));
1334 
1335  /*
1336  * OK, slurp in the file.
1337  */
1338  buf = (char *) palloc(stat.st_size);
1339 
1340  pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_READ);
1341  r = read(fd, buf, stat.st_size);
1342  if (r != stat.st_size)
1343  {
1344  if (r < 0)
1345  ereport(ERROR,
1347  errmsg("could not read file \"%s\": %m", path)));
1348  else
1349  ereport(ERROR,
1350  (errmsg("could not read file \"%s\": read %d of %lld",
1351  path, r, (long long int) stat.st_size)));
1352  }
1353 
1355 
1356  if (CloseTransientFile(fd) != 0)
1357  ereport(ERROR,
1359  errmsg("could not close file \"%s\": %m", path)));
1360 
1361  hdr = (TwoPhaseFileHeader *) buf;
1362  if (hdr->magic != TWOPHASE_MAGIC)
1363  ereport(ERROR,
1365  errmsg("invalid magic number stored in file \"%s\"",
1366  path)));
1367 
1368  if (hdr->total_len != stat.st_size)
1369  ereport(ERROR,
1371  errmsg("invalid size stored in file \"%s\"",
1372  path)));
1373 
1374  INIT_CRC32C(calc_crc);
1375  COMP_CRC32C(calc_crc, buf, crc_offset);
1376  FIN_CRC32C(calc_crc);
1377 
1378  file_crc = *((pg_crc32c *) (buf + crc_offset));
1379 
1380  if (!EQ_CRC32C(calc_crc, file_crc))
1381  ereport(ERROR,
1383  errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
1384  path)));
1385 
1386  return buf;
1387 }
unsigned int uint32
Definition: c.h:495
#define PG_BINARY
Definition: c.h:1283
int CloseTransientFile(int fd)
Definition: fd.c:2754
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2578
#define read(a, b, c)
Definition: win32.h:13
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:98
#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:103
static int fd(const char *x, int i)
Definition: preproc-init.c:105
__int64 st_size
Definition: win32_port.h:273
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
#define fstat
Definition: win32_port.h:283

References buf, CloseTransientFile(), COMP_CRC32C, EQ_CRC32C, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errcode_for_file_access(), errmsg(), errmsg_plural(), ERROR, 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 2381 of file twophase.c.

2389 {
2390  XLogRecPtr recptr;
2391  bool replorigin;
2392 
2393  /*
2394  * Are we using the replication origins feature? Or, in other words, are
2395  * we replaying remote actions?
2396  */
2397  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2399 
2400  /*
2401  * Catch the scenario where we aborted partway through
2402  * RecordTransactionCommitPrepared ...
2403  */
2404  if (TransactionIdDidCommit(xid))
2405  elog(PANIC, "cannot abort transaction %u, it was already committed",
2406  xid);
2407 
2409 
2410  /*
2411  * Emit the XLOG commit record. Note that we mark 2PC aborts as
2412  * potentially having AccessExclusiveLocks since we don't know whether or
2413  * not they do.
2414  */
2416  nchildren, children,
2417  nrels, rels,
2418  nstats, stats,
2420  xid, gid);
2421 
2422  if (replorigin)
2423  /* Move LSNs forward for this replication origin */
2425  XactLastRecEnd);
2426 
2427  /* Always flush, since we're about to remove the 2PC state file */
2428  XLogFlush(recptr);
2429 
2430  /*
2431  * Mark the transaction aborted in clog. This is not absolutely necessary
2432  * but we may as well do it while we are here.
2433  */
2434  TransactionIdAbortTree(xid, nchildren, children);
2435 
2436  END_CRIT_SECTION();
2437 
2438  /*
2439  * Wait for synchronous replication, if required.
2440  *
2441  * Note that at this stage we have marked clog, but still show as running
2442  * in the procarray and continue to hold locks.
2443  */
2444  SyncRepWaitForLSN(recptr, false);
2445 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
#define PANIC
Definition: elog.h:42
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:270
int MyXactFlags
Definition: xact.c:136
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:5808
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:108
XLogRecPtr XactLastRecEnd
Definition: xlog.c:257
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References DoNotReplicateId, elog(), END_CRIT_SECTION, GetCurrentTimestamp(), InvalidRepOriginId, MyXactFlags, PANIC, replorigin_session_advance(), replorigin_session_origin, replorigin_session_origin_lsn, 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 2283 of file twophase.c.

2294 {
2295  XLogRecPtr recptr;
2296  TimestampTz committs = GetCurrentTimestamp();
2297  bool replorigin;
2298 
2299  /*
2300  * Are we using the replication origins feature? Or, in other words, are
2301  * we replaying remote actions?
2302  */
2303  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2305 
2307 
2308  /* See notes in RecordTransactionCommit */
2311 
2312  /*
2313  * Emit the XLOG commit record. Note that we mark 2PC commits as
2314  * potentially having AccessExclusiveLocks since we don't know whether or
2315  * not they do.
2316  */
2317  recptr = XactLogCommitRecord(committs,
2318  nchildren, children, nrels, rels,
2319  nstats, stats,
2320  ninvalmsgs, invalmsgs,
2321  initfileinval,
2323  xid, gid);
2324 
2325 
2326  if (replorigin)
2327  /* Move LSNs forward for this replication origin */
2329  XactLastRecEnd);
2330 
2331  /*
2332  * Record commit timestamp. The value comes from plain commit timestamp
2333  * if replorigin is not enabled, or replorigin already set a value for us
2334  * in replorigin_session_origin_timestamp otherwise.
2335  *
2336  * We don't need to WAL-log anything here, as the commit record written
2337  * above already contains the data.
2338  */
2339  if (!replorigin || replorigin_session_origin_timestamp == 0)
2341 
2342  TransactionTreeSetCommitTsData(xid, nchildren, children,
2345 
2346  /*
2347  * We don't currently try to sleep before flush here ... nor is there any
2348  * support for async commit of a prepared xact (the very idea is probably
2349  * a contradiction)
2350  */
2351 
2352  /* Flush XLOG to disk */
2353  XLogFlush(recptr);
2354 
2355  /* Mark the transaction committed in pg_xact */
2356  TransactionIdCommitTree(xid, nchildren, children);
2357 
2358  /* Checkpoint can proceed now */
2360 
2361  END_CRIT_SECTION();
2362 
2363  /*
2364  * Wait for synchronous replication, if required.
2365  *
2366  * Note that at this stage we have marked clog, but still show as running
2367  * in the procarray and continue to hold locks.
2368  */
2369  SyncRepWaitForLSN(recptr, true);
2370 }
void TransactionTreeSetCommitTsData(TransactionId xid, int nsubxids, TransactionId *subxids, TimestampTz timestamp, RepOriginId nodeid)
Definition: commit_ts.c:134
int64 TimestampTz
Definition: timestamp.h:39
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:5636

References Assert(), DELAY_CHKPT_START, PGPROC::delayChkptFlags, DoNotReplicateId, END_CRIT_SECTION, GetCurrentTimestamp(), InvalidRepOriginId, MyProc, MyXactFlags, replorigin_session_advance(), replorigin_session_origin, replorigin_session_origin_lsn, replorigin_session_origin_timestamp, START_CRIT_SECTION, SyncRepWaitForLSN(), TransactionIdCommitTree(), TransactionTreeSetCommitTsData(), XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK, XactLastRecEnd, XactLogCommitRecord(), and XLogFlush().

Referenced by FinishPreparedTransaction().

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 2060 of file twophase.c.

2061 {
2062  int i;
2063 
2064  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2065  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2066  {
2067  TransactionId xid;
2068  char *buf;
2070  char *bufptr;
2071  TwoPhaseFileHeader *hdr;
2072  TransactionId *subxids;
2073  const char *gid;
2074 
2075  xid = gxact->xid;
2076 
2077  /*
2078  * Reconstruct subtrans state for the transaction --- needed because
2079  * pg_subtrans is not preserved over a restart. Note that we are
2080  * linking all the subtransactions directly to the top-level XID;
2081  * there may originally have been a more complex hierarchy, but
2082  * there's no need to restore that exactly. It's possible that
2083  * SubTransSetParent has been set before, if the prepared transaction
2084  * generated xid assignment records.
2085  */
2086  buf = ProcessTwoPhaseBuffer(xid,
2087  gxact->prepare_start_lsn,
2088  gxact->ondisk, true, false);
2089  if (buf == NULL)
2090  continue;
2091 
2092  ereport(LOG,
2093  (errmsg("recovering prepared transaction %u from shared memory", xid)));
2094 
2095  hdr = (TwoPhaseFileHeader *) buf;
2096  Assert(TransactionIdEquals(hdr->xid, xid));
2097  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2098  gid = (const char *) bufptr;
2099  bufptr += MAXALIGN(hdr->gidlen);
2100  subxids = (TransactionId *) bufptr;
2101  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
2102  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
2103  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
2104  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
2105  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
2106  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
2107 
2108  /*
2109  * Recreate its GXACT and dummy PGPROC. But, check whether it was
2110  * added in redo and already has a shmem entry for it.
2111  */
2112  MarkAsPreparingGuts(gxact, xid, gid,
2113  hdr->prepared_at,
2114  hdr->owner, hdr->database);
2115 
2116  /* recovered, so reset the flag for entries generated by redo */
2117  gxact->inredo = false;
2118 
2119  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
2120  MarkAsPrepared(gxact, true);
2121 
2122  LWLockRelease(TwoPhaseStateLock);
2123 
2124  /*
2125  * Recover other state (notably locks) using resource managers.
2126  */
2128 
2129  /*
2130  * Release locks held by the standby process after we process each
2131  * prepared transaction. As a result, we don't need too many
2132  * additional locks at any one time.
2133  */
2134  if (InHotStandby)
2135  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2136 
2137  /*
2138  * We're done with recovering this transaction. Clear MyLockedGxact,
2139  * like we do in PrepareTransaction() during normal operation.
2140  */
2142 
2143  pfree(buf);
2144 
2145  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2146  }
2147 
2148  LWLockRelease(TwoPhaseStateLock);
2149 }
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:1093
Oid database
Definition: xact.h:351
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:523
void PostPrepare_Twophase(void)
Definition: twophase.c:362
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlogutils.h:57

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

Referenced by StartupXLOG().

◆ RecreateTwoPhaseFile()

static void RecreateTwoPhaseFile ( TransactionId  xid,
void *  content,
int  len 
)
static

Definition at line 1714 of file twophase.c.

1715 {
1716  char path[MAXPGPATH];
1717  pg_crc32c statefile_crc;
1718  int fd;
1719 
1720  /* Recompute CRC */
1721  INIT_CRC32C(statefile_crc);
1722  COMP_CRC32C(statefile_crc, content, len);
1723  FIN_CRC32C(statefile_crc);
1724 
1725  TwoPhaseFilePath(path, xid);
1726 
1727  fd = OpenTransientFile(path,
1728  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY);
1729  if (fd < 0)
1730  ereport(ERROR,
1732  errmsg("could not recreate file \"%s\": %m", path)));
1733 
1734  /* Write content and CRC */
1735  errno = 0;
1736  pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_WRITE);
1737  if (write(fd, content, len) != len)
1738  {
1739  /* if write didn't set errno, assume problem is no disk space */
1740  if (errno == 0)
1741  errno = ENOSPC;
1742  ereport(ERROR,
1744  errmsg("could not write file \"%s\": %m", path)));
1745  }
1746  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1747  {
1748  /* if write didn't set errno, assume problem is no disk space */
1749  if (errno == 0)
1750  errno = ENOSPC;
1751  ereport(ERROR,
1753  errmsg("could not write file \"%s\": %m", path)));
1754  }
1756 
1757  /*
1758  * We must fsync the file because the end-of-replay checkpoint will not do
1759  * so, there being no GXACT in shared memory yet to tell it to.
1760  */
1761  pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_SYNC);
1762  if (pg_fsync(fd) != 0)
1763  ereport(ERROR,
1765  errmsg("could not fsync file \"%s\": %m", path)));
1767 
1768  if (CloseTransientFile(fd) != 0)
1769  ereport(ERROR,
1771  errmsg("could not close file \"%s\": %m", path)));
1772 }
int pg_fsync(int fd)
Definition: fd.c:361
#define write(a, b, c)
Definition: win32.h:14

References CloseTransientFile(), COMP_CRC32C, ereport, errcode_for_file_access(), errmsg(), ERROR, 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 1258 of file twophase.c.

1260 {
1261  TwoPhaseRecordOnDisk record;
1262 
1263  record.rmid = rmid;
1264  record.info = info;
1265  record.len = len;
1266  save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1267  if (len > 0)
1269 }
const void * data
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:1015

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

648 {
649  int i;
650 
651  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
652 
653  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
654  {
655  if (gxact == TwoPhaseState->prepXacts[i])
656  {
657  /* remove from the active array */
660 
661  /* and put it back in the freelist */
662  gxact->next = TwoPhaseState->freeGXacts;
663  TwoPhaseState->freeGXacts = gxact;
664 
665  return;
666  }
667  }
668 
669  elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
670 }

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

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

◆ RemoveTwoPhaseFile()

static void RemoveTwoPhaseFile ( TransactionId  xid,
bool  giveWarning 
)
static

Definition at line 1695 of file twophase.c.

1696 {
1697  char path[MAXPGPATH];
1698 
1699  TwoPhaseFilePath(path, xid);
1700  if (unlink(path))
1701  if (errno != ENOENT || giveWarning)
1702  ereport(WARNING,
1704  errmsg("could not remove file \"%s\": %m", path)));
1705 }

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

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

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1876 of file twophase.c.

1877 {
1878  DIR *cldir;
1879  struct dirent *clde;
1880 
1881  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1882  cldir = AllocateDir(TWOPHASE_DIR);
1883  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1884  {
1885  if (strlen(clde->d_name) == 8 &&
1886  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1887  {
1888  TransactionId xid;
1889  char *buf;
1890 
1891  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1892 
1894  true, false, false);
1895  if (buf == NULL)
1896  continue;
1897 
1900  }
1901  }
1902  LWLockRelease(TwoPhaseStateLock);
1903  FreeDir(cldir);
1904 }
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2854
int FreeDir(DIR *dir)
Definition: fd.c:2906
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2788
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2456

References AllocateDir(), buf, dirent::d_name, FreeDir(), InvalidRepOriginId, 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 1015 of file twophase.c.

1016 {
1017  uint32 padlen = MAXALIGN(len);
1018 
1019  if (padlen > records.bytes_free)
1020  {
1021  records.tail->next = palloc0(sizeof(StateFileChunk));
1023  records.tail->len = 0;
1024  records.tail->next = NULL;
1025  records.num_chunks++;
1026 
1027  records.bytes_free = Max(padlen, 512);
1029  }
1030 
1031  memcpy(((char *) records.tail->data) + records.tail->len, data, len);
1032  records.tail->len += padlen;
1033  records.bytes_free -= padlen;
1034  records.total_len += padlen;
1035 }
#define Max(x, y)
Definition: c.h:987
void * palloc0(Size size)
Definition: mcxt.c:1257
uint32 bytes_free
Definition: twophase.c:1001

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

Referenced by RegisterTwoPhaseRecord(), and StartPrepare().

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 2019 of file twophase.c.

2020 {
2021  int i;
2022 
2023  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2024  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2025  {
2026  TransactionId xid;
2027  char *buf;
2029 
2030  Assert(gxact->inredo);
2031 
2032  xid = gxact->xid;
2033 
2034  buf = ProcessTwoPhaseBuffer(xid,
2035  gxact->prepare_start_lsn,
2036  gxact->ondisk, false, false);
2037  if (buf != NULL)
2038  pfree(buf);
2039  }
2040  LWLockRelease(TwoPhaseStateLock);
2041 }

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

Referenced by StartupXLOG(), and xlog_redo().

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1453 of file twophase.c.

1454 {
1455  char *buf;
1456  TwoPhaseFileHeader *hdr;
1457  bool result;
1458 
1460 
1461  if (max_prepared_xacts <= 0)
1462  return false; /* nothing to do */
1463 
1464  /* Read and validate file */
1465  buf = ReadTwoPhaseFile(xid, true);
1466  if (buf == NULL)
1467  return false;
1468 
1469  /* Check header also */
1470  hdr = (TwoPhaseFileHeader *) buf;
1471  result = TransactionIdEquals(hdr->xid, xid);
1472  pfree(buf);
1473 
1474  return result;
1475 }
#define TransactionIdIsValid(xid)
Definition: transam.h:41

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 1043 of file twophase.c.

1044 {
1045  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
1046  TransactionId xid = gxact->xid;
1047  TwoPhaseFileHeader hdr;
1048  TransactionId *children;
1049  RelFileLocator *commitrels;
1050  RelFileLocator *abortrels;
1051  xl_xact_stats_item *abortstats = NULL;
1052  xl_xact_stats_item *commitstats = NULL;
1053  SharedInvalidationMessage *invalmsgs;
1054 
1055  /* Initialize linked list */
1056  records.head = palloc0(sizeof(StateFileChunk));
1057  records.head->len = 0;
1058  records.head->next = NULL;
1059 
1060  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1062 
1064  records.num_chunks = 1;
1065 
1066  records.total_len = 0;
1067 
1068  /* Create header */
1069  hdr.magic = TWOPHASE_MAGIC;
1070  hdr.total_len = 0; /* EndPrepare will fill this in */
1071  hdr.xid = xid;
1072  hdr.database = proc->databaseId;
1073  hdr.prepared_at = gxact->prepared_at;
1074  hdr.owner = gxact->owner;
1075  hdr.nsubxacts = xactGetCommittedChildren(&children);
1076  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1077  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1078  hdr.ncommitstats =
1079  pgstat_get_transactional_drops(true, &commitstats);
1080  hdr.nabortstats =
1081  pgstat_get_transactional_drops(false, &abortstats);
1083  &hdr.initfileinval);
1084  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1085  /* EndPrepare will fill the origin data, if necessary */
1087  hdr.origin_timestamp = 0;
1088 
1089  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1090  save_state_data(gxact->gid, hdr.gidlen);
1091 
1092  /*
1093  * Add the additional info about subxacts, deletable files and cache
1094  * invalidation messages.
1095  */
1096  if (hdr.nsubxacts > 0)
1097  {
1098  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1099  /* While we have the child-xact data, stuff it in the gxact too */
1100  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1101  }
1102  if (hdr.ncommitrels > 0)
1103  {
1104  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileLocator));
1105  pfree(commitrels);
1106  }
1107  if (hdr.nabortrels > 0)
1108  {
1109  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileLocator));
1110  pfree(abortrels);
1111  }
1112  if (hdr.ncommitstats > 0)
1113  {
1114  save_state_data(commitstats,
1115  hdr.ncommitstats * sizeof(xl_xact_stats_item));
1116  pfree(commitstats);
1117  }
1118  if (hdr.nabortstats > 0)
1119  {
1120  save_state_data(abortstats,
1121  hdr.nabortstats * sizeof(xl_xact_stats_item));
1122  pfree(abortstats);
1123  }
1124  if (hdr.ninvalmsgs > 0)
1125  {
1126  save_state_data(invalmsgs,
1127  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1128  pfree(invalmsgs);
1129  }
1130 }
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:884
int pgstat_get_transactional_drops(bool isCommit, xl_xact_stats_item **items)
Definition: pgstat_xact.c:271
int smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
Definition: storage.c:870
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5612

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

Referenced by PrepareTransaction().

◆ TwoPhaseGetDummyBackendId()

BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid,
bool  lock_held 
)

Definition at line 919 of file twophase.c.

920 {
921  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
922 
923  return gxact->dummyBackendId;
924 }
BackendId dummyBackendId
Definition: twophase.c:154
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:819

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid,
bool  lock_held 
)

Definition at line 934 of file twophase.c.

935 {
936  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
937 
938  return &ProcGlobal->allProcs[gxact->pgprocno];
939 }

References PROC_HDR::allProcs, GlobalTransactionData::pgprocno, ProcGlobal, and TwoPhaseGetGXact().

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

◆ TwoPhaseGetGXact()

static GlobalTransaction TwoPhaseGetGXact ( TransactionId  xid,
bool  lock_held 
)
static

Definition at line 819 of file twophase.c.

820 {
821  GlobalTransaction result = NULL;
822  int i;
823 
824  static TransactionId cached_xid = InvalidTransactionId;
825  static GlobalTransaction cached_gxact = NULL;
826 
827  Assert(!lock_held || LWLockHeldByMe(TwoPhaseStateLock));
828 
829  /*
830  * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
831  * repeatedly for the same XID. We can save work with a simple cache.
832  */
833  if (xid == cached_xid)
834  return cached_gxact;
835 
836  if (!lock_held)
837  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
838 
839  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
840  {
842 
843  if (gxact->xid == xid)
844  {
845  result = gxact;
846  break;
847  }
848  }
849 
850  if (!lock_held)
851  LWLockRelease(TwoPhaseStateLock);
852 
853  if (result == NULL) /* should not happen */
854  elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
855 
856  cached_xid = xid;
857  cached_gxact = result;
858 
859  return result;
860 }
bool LWLockHeldByMe(LWLock *lock)
Definition: lwlock.c:1920

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

Referenced by TwoPhaseGetDummyBackendId(), and TwoPhaseGetDummyProc().

◆ TwoPhaseGetXidByVirtualXID()

TransactionId TwoPhaseGetXidByVirtualXID ( VirtualTransactionId  vxid,
bool have_more 
)

Definition at line 871 of file twophase.c.

873 {
874  int i;
876 
878  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
879 
880  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
881  {
883  PGPROC *proc;
884  VirtualTransactionId proc_vxid;
885 
886  if (!gxact->valid)
887  continue;
888  proc = &ProcGlobal->allProcs[gxact->pgprocno];
889  GET_VXID_FROM_PGPROC(proc_vxid, *proc);
890  if (VirtualTransactionIdEquals(vxid, proc_vxid))
891  {
892  /* Startup process sets proc->backendId to InvalidBackendId. */
893  Assert(!gxact->inredo);
894 
895  if (result != InvalidTransactionId)
896  {
897  *have_more = true;
898  break;
899  }
900  result = gxact->xid;
901  }
902  }
903 
904  LWLockRelease(TwoPhaseStateLock);
905 
906  return result;
907 }
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:67
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:71
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:77

References PROC_HDR::allProcs, Assert(), GET_VXID_FROM_PGPROC, i, GlobalTransactionData::inredo, InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, GlobalTransactionData::pgprocno, TwoPhaseStateData::prepXacts, ProcGlobal, TwoPhaseState, GlobalTransactionData::valid, VirtualTransactionIdEquals, VirtualTransactionIdIsValid, and GlobalTransactionData::xid.

Referenced by XactLockForVirtualXact().

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 257 of file twophase.c.

258 {
259  bool found;
260 
261  TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
263  &found);
264  if (!IsUnderPostmaster)
265  {
266  GlobalTransaction gxacts;
267  int i;
268 
269  Assert(!found);
270  TwoPhaseState->freeGXacts = NULL;
272 
273  /*
274  * Initialize the linked list of free GlobalTransactionData structs
275  */
276  gxacts = (GlobalTransaction)
277  ((char *) TwoPhaseState +
278  MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
280  for (i = 0; i < max_prepared_xacts; i++)
281  {
282  /* insert into linked list */
283  gxacts[i].next = TwoPhaseState->freeGXacts;
284  TwoPhaseState->freeGXacts = &gxacts[i];
285 
286  /* associate it with a PGPROC assigned by InitProcGlobal */
288 
289  /*
290  * Assign a unique ID for each dummy proc, so that the range of
291  * dummy backend IDs immediately follows the range of normal
292  * backend IDs. We don't dare to assign a real backend ID to dummy
293  * procs, because prepared transactions don't take part in cache
294  * invalidation like a real backend ID would imply, but having a
295  * unique ID for them is nevertheless handy. This arrangement
296  * allows you to allocate an array of size (MaxBackends +
297  * max_prepared_xacts + 1), and have a slot for every backend and
298  * prepared transaction. Currently multixact.c uses that
299  * technique.
300  */
301  gxacts[i].dummyBackendId = MaxBackends + 1 + i;
302  }
303  }
304  else
305  Assert(found);
306 }
bool IsUnderPostmaster
Definition: globals.c:113
int MaxBackends
Definition: globals.c:140
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
PGPROC * PreparedXactProcs
Definition: proc.c:80
Size TwoPhaseShmemSize(void)
Definition: twophase.c:241

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

Referenced by CreateSharedMemoryAndSemaphores().

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 241 of file twophase.c.

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

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

Referenced by CalculateShmemSize(), and TwoPhaseShmemInit().

◆ XlogReadTwoPhaseData()

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

Definition at line 1398 of file twophase.c.

1399 {
1400  XLogRecord *record;
1402  char *errormsg;
1403 
1405  XL_ROUTINE(.page_read = &read_local_xlog_page,
1406  .segment_open = &wal_segment_open,
1407  .segment_close = &wal_segment_close),
1408  NULL);
1409  if (!xlogreader)
1410  ereport(ERROR,
1411  (errcode(ERRCODE_OUT_OF_MEMORY),
1412  errmsg("out of memory"),
1413  errdetail("Failed while allocating a WAL reading processor.")));
1414 
1415  XLogBeginRead(xlogreader, lsn);
1416  record = XLogReadRecord(xlogreader, &errormsg);
1417 
1418  if (record == NULL)
1419  {
1420  if (errormsg)
1421  ereport(ERROR,
1423  errmsg("could not read two-phase state from WAL at %X/%X: %s",
1424  LSN_FORMAT_ARGS(lsn), errormsg)));
1425  else
1426  ereport(ERROR,
1428  errmsg("could not read two-phase state from WAL at %X/%X",
1429  LSN_FORMAT_ARGS(lsn))));
1430  }
1431 
1432  if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1434  ereport(ERROR,
1436  errmsg("expected two-phase state data is not present in WAL at %X/%X",
1437  LSN_FORMAT_ARGS(lsn))));
1438 
1439  if (len != NULL)
1441 
1442  *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1443  memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1444 
1446 }
#define XLOG_XACT_OPMASK
Definition: xact.h:179
int wal_segment_size
Definition: xlog.c:146
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:406
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:170
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:108
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:248
#define XLogRecGetDataLen(decoder)
Definition: xlogreader.h:416
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:411
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
static XLogReaderState * xlogreader
Definition: xlogrecovery.c:188
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:844
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:819
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:863

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

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseState