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/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, RelFileNode *rels, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval, const char *gid)
 
static void RecordTransactionAbortPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, 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)
 
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)
 

Variables

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

Macro Definition Documentation

◆ TWOPHASE_DIR

#define TWOPHASE_DIR   "pg_twophase"

Definition at line 114 of file twophase.c.

Referenced by CheckPointTwoPhase(), and restoreTwoPhaseData().

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */

Definition at line 911 of file twophase.c.

Referenced by EndPrepare(), ReadTwoPhaseFile(), and StartPrepare().

◆ TwoPhaseFilePath

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

Definition at line 889 of file twophase.c.

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

Typedef Documentation

◆ GlobalTransactionData

◆ StateFileChunk

◆ TwoPhaseFileHeader

Definition at line 913 of file twophase.c.

◆ TwoPhaseRecordOnDisk

◆ TwoPhaseStateData

Function Documentation

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 317 of file twophase.c.

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

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

◆ AtProcExit_Twophase()

static void AtProcExit_Twophase ( int  code,
Datum  arg 
)
static

Definition at line 307 of file twophase.c.

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

308 {
309  /* same logic as abort */
311 }
void AtAbort_Twophase(void)
Definition: twophase.c:317

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1696 of file twophase.c.

References buf, ereport, errmsg_plural(), fsync_fname(), i, GlobalTransactionData::inredo, InvalidXLogRecPtr, 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, GlobalTransactionData::valid, GlobalTransactionData::xid, and XlogReadTwoPhaseData().

Referenced by CheckPointGuts().

1697 {
1698  int i;
1699  int serialized_xacts = 0;
1700 
1701  if (max_prepared_xacts <= 0)
1702  return; /* nothing to do */
1703 
1704  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1705 
1706  /*
1707  * We are expecting there to be zero GXACTs that need to be copied to
1708  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1709  * simplicity. This prevents any new xacts from preparing while this
1710  * occurs, which shouldn't be a problem since the presence of long-lived
1711  * prepared xacts indicates the transaction manager isn't active.
1712  *
1713  * It's also possible to move I/O out of the lock, but on every error we
1714  * should check whether somebody committed our transaction in different
1715  * backend. Let's leave this optimization for future, if somebody will
1716  * spot that this place cause bottleneck.
1717  *
1718  * Note that it isn't possible for there to be a GXACT with a
1719  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1720  * because of the efforts with delayChkpt.
1721  */
1722  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1723  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1724  {
1725  /*
1726  * Note that we are using gxact not pgxact so this works in recovery
1727  * also
1728  */
1730 
1731  if ((gxact->valid || gxact->inredo) &&
1732  !gxact->ondisk &&
1733  gxact->prepare_end_lsn <= redo_horizon)
1734  {
1735  char *buf;
1736  int len;
1737 
1738  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1739  RecreateTwoPhaseFile(gxact->xid, buf, len);
1740  gxact->ondisk = true;
1743  pfree(buf);
1744  serialized_xacts++;
1745  }
1746  }
1747  LWLockRelease(TwoPhaseStateLock);
1748 
1749  /*
1750  * Flush unconditionally the parent directory to make any information
1751  * durable on disk. Two-phase files could have been removed and those
1752  * removals need to be made persistent as well as any files newly created
1753  * previously since the last checkpoint.
1754  */
1755  fsync_fname(TWOPHASE_DIR, true);
1756 
1757  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1758 
1759  if (log_checkpoints && serialized_xacts > 0)
1760  ereport(LOG,
1761  (errmsg_plural("%u two-phase state file was written "
1762  "for a long-running prepared transaction",
1763  "%u two-phase state files were written "
1764  "for long-running prepared transactions",
1765  serialized_xacts,
1766  serialized_xacts)));
1767 }
bool log_checkpoints
Definition: xlog.c:101
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:616
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
int max_prepared_xacts
Definition: twophase.c:117
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1616
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define TWOPHASE_DIR
Definition: twophase.c:114
TransactionId xid
Definition: twophase.c:165
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1327
int i
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1060 of file twophase.c.

References Assert, StateFileChunk::data, PGXACT::delayChkpt, DoNotReplicateId, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xllist::head, InvalidRepOriginId, InvalidXLogRecPtr, StateFileChunk::len, xl_xact_prepare::magic, MarkAsPrepared(), MaxAllocSize, MyPgXact, 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, xl_xact_prepare::total_len, xllist::total_len, TWOPHASE_MAGIC, TWOPHASE_RM_END_ID, XLOG_INCLUDE_ORIGIN, XLOG_XACT_PREPARE, XLogBeginInsert(), XLogEnsureRecordSpace(), XLogFlush(), XLogInsert(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by PrepareTransaction().

1061 {
1062  TwoPhaseFileHeader *hdr;
1063  StateFileChunk *record;
1064  bool replorigin;
1065 
1066  /* Add the end sentinel to the list of 2PC records */
1068  NULL, 0);
1069 
1070  /* Go back and fill in total_len in the file header record */
1071  hdr = (TwoPhaseFileHeader *) records.head->data;
1072  Assert(hdr->magic == TWOPHASE_MAGIC);
1073  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1074 
1075  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1077 
1078  if (replorigin)
1079  {
1083  }
1084  else
1085  {
1087  hdr->origin_timestamp = 0;
1088  }
1089 
1090  /*
1091  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1092  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1093  * where we write data to file and then re-read at commit time.
1094  */
1095  if (hdr->total_len > MaxAllocSize)
1096  ereport(ERROR,
1097  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1098  errmsg("two-phase state file maximum length exceeded")));
1099 
1100  /*
1101  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1102  * cover us, so no need to calculate a separate CRC.
1103  *
1104  * We have to set delayChkpt here, too; otherwise a checkpoint starting
1105  * immediately after the WAL record is inserted could complete without
1106  * fsync'ing our state file. (This is essentially the same kind of race
1107  * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1108  * uses delayChkpt for; see notes there.)
1109  *
1110  * We save the PREPARE record's location in the gxact for later use by
1111  * CheckPointTwoPhase.
1112  */
1114 
1116 
1117  MyPgXact->delayChkpt = true;
1118 
1119  XLogBeginInsert();
1120  for (record = records.head; record != NULL; record = record->next)
1121  XLogRegisterData(record->data, record->len);
1122 
1124 
1125  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1126 
1127  if (replorigin)
1128  {
1129  /* Move LSNs forward for this replication origin */
1131  gxact->prepare_end_lsn);
1132  }
1133 
1134  XLogFlush(gxact->prepare_end_lsn);
1135 
1136  /* If we crash now, we have prepared: WAL replay will fix things */
1137 
1138  /* Store record's start location to read that later on Commit */
1140 
1141  /*
1142  * Mark the prepared transaction as valid. As soon as xact.c marks
1143  * MyPgXact as not running our XID (which it will do immediately after
1144  * this function returns), others can commit/rollback the xact.
1145  *
1146  * NB: a side effect of this is to make a dummy ProcArray entry for the
1147  * prepared XID. This must happen before we clear the XID from MyPgXact,
1148  * else there is a window where the XID is not running according to
1149  * TransactionIdIsInProgress, and onlookers would be entitled to assume
1150  * the xact crashed. Instead we have a window where the same XID appears
1151  * twice in ProcArray, which is OK.
1152  */
1153  MarkAsPrepared(gxact, false);
1154 
1155  /*
1156  * Now we can mark ourselves as out of the commit critical section: a
1157  * checkpoint starting after this will certainly see the gxact as a
1158  * candidate for fsyncing.
1159  */
1160  MyPgXact->delayChkpt = false;
1161 
1162  /*
1163  * Remember that we have this GlobalTransaction entry locked for us. If
1164  * we crash after this point, it's too late to abort, but we must unlock
1165  * it so that the prepared transaction can be committed or rolled back.
1166  */
1167  MyLockedGxact = gxact;
1168 
1169  END_CRIT_SECTION();
1170 
1171  /*
1172  * Wait for synchronous replication, if required.
1173  *
1174  * Note that at this stage we have marked the prepare, but still show as
1175  * running in the procarray (twice!) and continue to hold locks.
1176  */
1177  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1178 
1179  records.tail = records.head = NULL;
1180  records.num_chunks = 0;
1181 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define XLOG_XACT_PREPARE
Definition: xact.h:144
#define DoNotReplicateId
Definition: origin.h:34
StateFileChunk * tail
Definition: twophase.c:943
uint32 pg_crc32c
Definition: pg_crc32c.h:38
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:350
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:146
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
int errcode(int sqlerrcode)
Definition: elog.c:608
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:228
uint32 num_chunks
Definition: twophase.c:944
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2804
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1187
PGXACT * MyPgXact
Definition: proc.c:68
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
char * data
Definition: twophase.c:935
#define ERROR
Definition: elog.h:43
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:153
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:154
XLogRecPtr origin_lsn
Definition: xact.h:309
uint32 total_len
Definition: xact.h:298
uint32 len
Definition: twophase.c:936
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:397
#define ereport(elevel, rest)
Definition: elog.h:141
bool delayChkpt
Definition: proc.h:235
static struct xllist records
uint32 total_len
Definition: twophase.c:946
#define MaxAllocSize
Definition: memutils.h:40
struct StateFileChunk * next
Definition: twophase.c:937
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define TWOPHASE_MAGIC
Definition: twophase.c:911
StateFileChunk * head
Definition: twophase.c:942
#define Assert(condition)
Definition: c.h:739
RepOriginId replorigin_session_origin
Definition: origin.c:152
TimestampTz origin_timestamp
Definition: xact.h:310
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition: xloginsert.c:146
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1170
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:536
#define InvalidRepOriginId
Definition: origin.h:33
uint32 magic
Definition: xact.h:297
int errmsg(const char *fmt,...)
Definition: elog.c:822
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1400 of file twophase.c.

References PROC_HDR::allPgXact, 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, xl_xact_prepare::nabortrels, xl_xact_prepare::ncommitrels, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::pgprocno, 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, PGXACT::xid, xl_xact_prepare::xid, and XlogReadTwoPhaseData().

Referenced by standard_ProcessUtility().

1401 {
1402  GlobalTransaction gxact;
1403  PGPROC *proc;
1404  PGXACT *pgxact;
1405  TransactionId xid;
1406  char *buf;
1407  char *bufptr;
1408  TwoPhaseFileHeader *hdr;
1409  TransactionId latestXid;
1410  TransactionId *children;
1411  RelFileNode *commitrels;
1412  RelFileNode *abortrels;
1413  RelFileNode *delrels;
1414  int ndelrels;
1415  SharedInvalidationMessage *invalmsgs;
1416 
1417  /*
1418  * Validate the GID, and lock the GXACT to ensure that two backends do not
1419  * try to commit the same GID at once.
1420  */
1421  gxact = LockGXact(gid, GetUserId());
1422  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1423  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1424  xid = pgxact->xid;
1425 
1426  /*
1427  * Read and validate 2PC state data. State data will typically be stored
1428  * in WAL files if the LSN is after the last checkpoint record, or moved
1429  * to disk if for some reason they have lived for a long time.
1430  */
1431  if (gxact->ondisk)
1432  buf = ReadTwoPhaseFile(xid, false);
1433  else
1434  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1435 
1436 
1437  /*
1438  * Disassemble the header area
1439  */
1440  hdr = (TwoPhaseFileHeader *) buf;
1441  Assert(TransactionIdEquals(hdr->xid, xid));
1442  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1443  bufptr += MAXALIGN(hdr->gidlen);
1444  children = (TransactionId *) bufptr;
1445  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1446  commitrels = (RelFileNode *) bufptr;
1447  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1448  abortrels = (RelFileNode *) bufptr;
1449  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1450  invalmsgs = (SharedInvalidationMessage *) bufptr;
1451  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1452 
1453  /* compute latestXid among all children */
1454  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1455 
1456  /* Prevent cancel/die interrupt while cleaning up */
1457  HOLD_INTERRUPTS();
1458 
1459  /*
1460  * The order of operations here is critical: make the XLOG entry for
1461  * commit or abort, then mark the transaction committed or aborted in
1462  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1463  * TransactionIdIsInProgress will stop saying the prepared xact is in
1464  * progress), then run the post-commit or post-abort callbacks. The
1465  * callbacks will release the locks the transaction held.
1466  */
1467  if (isCommit)
1469  hdr->nsubxacts, children,
1470  hdr->ncommitrels, commitrels,
1471  hdr->ninvalmsgs, invalmsgs,
1472  hdr->initfileinval, gid);
1473  else
1475  hdr->nsubxacts, children,
1476  hdr->nabortrels, abortrels,
1477  gid);
1478 
1479  ProcArrayRemove(proc, latestXid);
1480 
1481  /*
1482  * In case we fail while running the callbacks, mark the gxact invalid so
1483  * no one else will try to commit/rollback, and so it will be recycled if
1484  * we fail after this point. It is still locked by our backend so it
1485  * won't go away yet.
1486  *
1487  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1488  */
1489  gxact->valid = false;
1490 
1491  /*
1492  * We have to remove any files that were supposed to be dropped. For
1493  * consistency with the regular xact.c code paths, must do this before
1494  * releasing locks, so do it before running the callbacks.
1495  *
1496  * NB: this code knows that we couldn't be dropping any temp rels ...
1497  */
1498  if (isCommit)
1499  {
1500  delrels = commitrels;
1501  ndelrels = hdr->ncommitrels;
1502  }
1503  else
1504  {
1505  delrels = abortrels;
1506  ndelrels = hdr->nabortrels;
1507  }
1508 
1509  /* Make sure files supposed to be dropped are dropped */
1510  DropRelationFiles(delrels, ndelrels, false);
1511 
1512  /*
1513  * Handle cache invalidation messages.
1514  *
1515  * Relcache init file invalidation requires processing both before and
1516  * after we send the SI messages. See AtEOXact_Inval()
1517  */
1518  if (hdr->initfileinval)
1520  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1521  if (hdr->initfileinval)
1523 
1524  /*
1525  * Acquire the two-phase lock. We want to work on the two-phase callbacks
1526  * while holding it to avoid potential conflicts with other transactions
1527  * attempting to use the same GID, so the lock is released once the shared
1528  * memory state is cleared.
1529  */
1530  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1531 
1532  /* And now do the callbacks */
1533  if (isCommit)
1535  else
1537 
1538  PredicateLockTwoPhaseFinish(xid, isCommit);
1539 
1540  /* Clear shared memory state */
1541  RemoveGXact(gxact);
1542 
1543  /*
1544  * Release the lock as all callbacks are called and shared memory cleanup
1545  * is done.
1546  */
1547  LWLockRelease(TwoPhaseStateLock);
1548 
1549  /* Count the prepared xact as committed or aborted */
1550  AtEOXact_PgStat(isCommit, false);
1551 
1552  /*
1553  * And now we can clean up any files we may have left.
1554  */
1555  if (gxact->ondisk)
1556  RemoveTwoPhaseFile(xid, true);
1557 
1558  MyLockedGxact = NULL;
1559 
1561 
1562  pfree(buf);
1563 }
int32 ninvalmsgs
Definition: xact.h:306
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, const char *gid)
Definition: twophase.c:2277
int32 nsubxacts
Definition: xact.h:303
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
int32 ncommitrels
Definition: xact.h:304
Oid GetUserId(void)
Definition: miscinit.c:380
PGXACT * allPgXact
Definition: proc.h:249
TransactionId xid
Definition: proc.h:224
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:365
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1569
const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:33
PROC_HDR * ProcGlobal
Definition: proc.c:80
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1210
uint16 gidlen
Definition: xact.h:308
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
int32 nabortrels
Definition: xact.h:305
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:118
void pfree(void *pointer)
Definition: mcxt.c:1056
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:558
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:335
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:634
void DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
Definition: md.c:993
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat.c:2087
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:5004
static char * buf
Definition: pg_test_fsync.c:67
const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:42
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:5997
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1597
bool initfileinval
Definition: xact.h:307
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:5972
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define MAXALIGN(LEN)
Definition: c.h:692
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
TransactionId xid
Definition: xact.h:299
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1327
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:116
PGPROC * allProcs
Definition: proc.h:247
Definition: proc.h:95
static void RecordTransactionCommitPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval, const char *gid)
Definition: twophase.c:2183

◆ GetPreparedTransactionList()

static int GetPreparedTransactionList ( GlobalTransaction gxacts)
static

Definition at line 672 of file twophase.c.

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

Referenced by pg_prepared_xact().

673 {
674  GlobalTransaction array;
675  int num;
676  int i;
677 
678  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
679 
680  if (TwoPhaseState->numPrepXacts == 0)
681  {
682  LWLockRelease(TwoPhaseStateLock);
683 
684  *gxacts = NULL;
685  return 0;
686  }
687 
689  array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
690  *gxacts = array;
691  for (i = 0; i < num; i++)
692  memcpy(array + i, TwoPhaseState->prepXacts[i],
693  sizeof(GlobalTransactionData));
694 
695  LWLockRelease(TwoPhaseStateLock);
696 
697  return num;
698 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:26
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
void * palloc(Size size)
Definition: mcxt.c:949
int i

◆ GXactLoadSubxactData()

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

Definition at line 509 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, PGXACT::nxids, PGXACT::overflowed, PGPROC_MAX_CACHED_SUBXIDS, GlobalTransactionData::pgprocno, ProcGlobal, PGPROC::subxids, and XidCache::xids.

Referenced by RecoverPreparedTransactions(), and StartPrepare().

511 {
512  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
513  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
514 
515  /* We need no extra lock since the GXACT isn't valid yet */
516  if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
517  {
518  pgxact->overflowed = true;
519  nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
520  }
521  if (nsubxacts > 0)
522  {
523  memcpy(proc->subxids.xids, children,
524  nsubxacts * sizeof(TransactionId));
525  pgxact->nxids = nsubxacts;
526  }
527 }
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
PGXACT * allPgXact
Definition: proc.h:249
PROC_HDR * ProcGlobal
Definition: proc.c:80
uint8 nxids
Definition: proc.h:238
struct XidCache subxids
Definition: proc.h:162
bool overflowed
Definition: proc.h:234
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:36
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:40
PGPROC * allProcs
Definition: proc.h:247
Definition: proc.h:95

◆ LockGXact()

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

Definition at line 558 of file twophase.c.

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, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::owner, GlobalTransactionData::pgprocno, TwoPhaseStateData::prepXacts, ProcGlobal, superuser_arg(), twophaseExitRegistered, and GlobalTransactionData::valid.

Referenced by FinishPreparedTransaction().

559 {
560  int i;
561 
562  /* on first call, register the exit hook */
564  {
566  twophaseExitRegistered = true;
567  }
568 
569  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
570 
571  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
572  {
574  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
575 
576  /* Ignore not-yet-valid GIDs */
577  if (!gxact->valid)
578  continue;
579  if (strcmp(gxact->gid, gid) != 0)
580  continue;
581 
582  /* Found it, but has someone else got it locked? */
583  if (gxact->locking_backend != InvalidBackendId)
584  ereport(ERROR,
585  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
586  errmsg("prepared transaction with identifier \"%s\" is busy",
587  gid)));
588 
589  if (user != gxact->owner && !superuser_arg(user))
590  ereport(ERROR,
591  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
592  errmsg("permission denied to finish prepared transaction"),
593  errhint("Must be superuser or the user that prepared the transaction.")));
594 
595  /*
596  * Note: it probably would be possible to allow committing from
597  * another database; but at the moment NOTIFY is known not to work and
598  * there may be some other issues as well. Hence disallow until
599  * someone gets motivated to make it work.
600  */
601  if (MyDatabaseId != proc->databaseId)
602  ereport(ERROR,
603  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
604  errmsg("prepared transaction belongs to another database"),
605  errhint("Connect to the database where the transaction was prepared to finish it.")));
606 
607  /* OK for me to lock it */
608  gxact->locking_backend = MyBackendId;
609  MyLockedGxact = gxact;
610 
611  LWLockRelease(TwoPhaseStateLock);
612 
613  return gxact;
614  }
615 
616  LWLockRelease(TwoPhaseStateLock);
617 
618  ereport(ERROR,
619  (errcode(ERRCODE_UNDEFINED_OBJECT),
620  errmsg("prepared transaction with identifier \"%s\" does not exist",
621  gid)));
622 
623  /* NOTREACHED */
624  return NULL;
625 }
int errhint(const char *fmt,...)
Definition: elog.c:1069
BackendId MyBackendId
Definition: globals.c:81
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
int errcode(int sqlerrcode)
Definition: elog.c:608
PROC_HDR * ProcGlobal
Definition: proc.c:80
static bool twophaseExitRegistered
Definition: twophase.c:201
char gid[GIDSIZE]
Definition: twophase.c:172
BackendId locking_backend
Definition: twophase.c:168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define ERROR
Definition: elog.h:43
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
Oid databaseId
Definition: proc.h:114
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
#define InvalidBackendId
Definition: backendid.h:23
Oid MyDatabaseId
Definition: globals.c:85
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
static char * user
Definition: pg_regress.c:94
int errmsg(const char *fmt,...)
Definition: elog.c:822
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
int i
PGPROC * allProcs
Definition: proc.h:247
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:307
Definition: proc.h:95

◆ MarkAsPrepared()

static void MarkAsPrepared ( GlobalTransaction  gxact,
bool  lock_held 
)
static

Definition at line 536 of file twophase.c.

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

Referenced by EndPrepare(), and RecoverPreparedTransactions().

537 {
538  /* Lock here may be overkill, but I'm not convinced of that ... */
539  if (!lock_held)
540  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
541  Assert(!gxact->valid);
542  gxact->valid = true;
543  if (!lock_held)
544  LWLockRelease(TwoPhaseStateLock);
545 
546  /*
547  * Put it into the global ProcArray so TransactionIdIsInProgress considers
548  * the XID as still running.
549  */
551 }
PROC_HDR * ProcGlobal
Definition: proc.c:80
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
PGPROC * allProcs
Definition: proc.h:247
void ProcArrayAdd(PGPROC *proc)
Definition: procarray.c:277

◆ MarkAsPreparing()

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

Definition at line 372 of file twophase.c.

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, and twophaseExitRegistered.

Referenced by PrepareTransaction().

374 {
375  GlobalTransaction gxact;
376  int i;
377 
378  if (strlen(gid) >= GIDSIZE)
379  ereport(ERROR,
380  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
381  errmsg("transaction identifier \"%s\" is too long",
382  gid)));
383 
384  /* fail immediately if feature is disabled */
385  if (max_prepared_xacts == 0)
386  ereport(ERROR,
387  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
388  errmsg("prepared transactions are disabled"),
389  errhint("Set max_prepared_transactions to a nonzero value.")));
390 
391  /* on first call, register the exit hook */
393  {
395  twophaseExitRegistered = true;
396  }
397 
398  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
399 
400  /* Check for conflicting GID */
401  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
402  {
403  gxact = TwoPhaseState->prepXacts[i];
404  if (strcmp(gxact->gid, gid) == 0)
405  {
406  ereport(ERROR,
408  errmsg("transaction identifier \"%s\" is already in use",
409  gid)));
410  }
411  }
412 
413  /* Get a free gxact from the freelist */
414  if (TwoPhaseState->freeGXacts == NULL)
415  ereport(ERROR,
416  (errcode(ERRCODE_OUT_OF_MEMORY),
417  errmsg("maximum number of prepared transactions reached"),
418  errhint("Increase max_prepared_transactions (currently %d).",
420  gxact = TwoPhaseState->freeGXacts;
421  TwoPhaseState->freeGXacts = gxact->next;
422 
423  MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
424 
425  gxact->ondisk = false;
426 
427  /* And insert it into the active array */
430 
431  LWLockRelease(TwoPhaseStateLock);
432 
433  return gxact;
434 }
int errhint(const char *fmt,...)
Definition: elog.c:1069
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
int errcode(int sqlerrcode)
Definition: elog.c:608
static bool twophaseExitRegistered
Definition: twophase.c:201
GlobalTransaction next
Definition: twophase.c:151
char gid[GIDSIZE]
Definition: twophase.c:172
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:446
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:117
#define GIDSIZE
Definition: xact.h:31
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:307
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31

◆ MarkAsPreparingGuts()

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

Definition at line 446 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Assert, PGPROC::backendId, PGPROC::databaseId, PGXACT::delayChkpt, GlobalTransactionData::gid, i, GlobalTransactionData::inredo, InvalidBackendId, InvalidOid, InvalidTransactionId, PGPROC::isBackgroundWorker, PGPROC::links, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockHeldByMeInMode(), PGPROC::lwWaiting, PGPROC::lwWaitMode, PGPROC::lxid, MemSet, MyBackendId, PGPROC::myProcLocks, NUM_LOCK_PARTITIONS, PGXACT::nxids, PGXACT::overflowed, GlobalTransactionData::owner, PGPROC::pgprocno, GlobalTransactionData::pgprocno, PGPROC::pid, GlobalTransactionData::prepared_at, ProcGlobal, PGPROC::roleId, SHMQueueElemInit(), SHMQueueInit(), STATUS_OK, PGPROC::tempNamespaceId, PGXACT::vacuumFlags, GlobalTransactionData::valid, PGPROC::waitLock, PGPROC::waitProcLock, PGPROC::waitStatus, GlobalTransactionData::xid, PGXACT::xid, and PGXACT::xmin.

Referenced by MarkAsPreparing(), and RecoverPreparedTransactions().

448 {
449  PGPROC *proc;
450  PGXACT *pgxact;
451  int i;
452 
453  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
454 
455  Assert(gxact != NULL);
456  proc = &ProcGlobal->allProcs[gxact->pgprocno];
457  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
458 
459  /* Initialize the PGPROC entry */
460  MemSet(proc, 0, sizeof(PGPROC));
461  proc->pgprocno = gxact->pgprocno;
462  SHMQueueElemInit(&(proc->links));
463  proc->waitStatus = STATUS_OK;
464  /* We set up the gxact's VXID as InvalidBackendId/XID */
465  proc->lxid = (LocalTransactionId) xid;
466  pgxact->xid = xid;
467  pgxact->xmin = InvalidTransactionId;
468  pgxact->delayChkpt = false;
469  pgxact->vacuumFlags = 0;
470  proc->pid = 0;
471  proc->backendId = InvalidBackendId;
472  proc->databaseId = databaseid;
473  proc->roleId = owner;
474  proc->tempNamespaceId = InvalidOid;
475  proc->isBackgroundWorker = false;
476  proc->lwWaiting = false;
477  proc->lwWaitMode = 0;
478  proc->waitLock = NULL;
479  proc->waitProcLock = NULL;
480  for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
481  SHMQueueInit(&(proc->myProcLocks[i]));
482  /* subxid data must be filled later by GXactLoadSubxactData */
483  pgxact->overflowed = false;
484  pgxact->nxids = 0;
485 
486  gxact->prepared_at = prepared_at;
487  gxact->xid = xid;
488  gxact->owner = owner;
489  gxact->locking_backend = MyBackendId;
490  gxact->valid = false;
491  gxact->inredo = false;
492  strcpy(gxact->gid, gid);
493 
494  /*
495  * Remember that we have this GlobalTransaction entry locked for us. If we
496  * abort after this, we must release it.
497  */
498  MyLockedGxact = gxact;
499 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
BackendId MyBackendId
Definition: globals.c:81
BackendId backendId
Definition: proc.h:113
Definition: proc.h:222
Oid tempNamespaceId
Definition: proc.h:117
TransactionId xmin
Definition: proc.h:228
PGXACT * allPgXact
Definition: proc.h:249
TransactionId xid
Definition: proc.h:224
SHM_QUEUE links
Definition: proc.h:98
bool lwWaiting
Definition: proc.h:130
Oid roleId
Definition: proc.h:115
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:962
uint8 lwWaitMode
Definition: proc.h:131
char gid[GIDSIZE]
Definition: twophase.c:172
uint8 vacuumFlags
Definition: proc.h:233
BackendId locking_backend
Definition: twophase.c:168
bool isBackgroundWorker
Definition: proc.h:120
PROCLOCK * waitProcLock
Definition: proc.h:140
uint8 nxids
Definition: proc.h:238
#define InvalidTransactionId
Definition: transam.h:31
Oid databaseId
Definition: proc.h:114
uint32 LocalTransactionId
Definition: c.h:516
LOCK * waitLock
Definition: proc.h:139
#define STATUS_OK
Definition: c.h:1120
bool delayChkpt
Definition: proc.h:235
#define InvalidBackendId
Definition: backendid.h:23
bool overflowed
Definition: proc.h:234
int waitStatus
Definition: proc.h:102
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:739
TransactionId xid
Definition: twophase.c:165
TimestampTz prepared_at
Definition: twophase.c:154
void SHMQueueElemInit(SHM_QUEUE *queue)
Definition: shmqueue.c:57
int pgprocno
Definition: proc.h:110
void SHMQueueInit(SHM_QUEUE *queue)
Definition: shmqueue.c:36
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
int i
PGPROC * allProcs
Definition: proc.h:247
SHM_QUEUE myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:160
Definition: proc.h:95
int pid
Definition: proc.h:109
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:117
LocalTransactionId lxid
Definition: proc.h:106

◆ pg_prepared_xact()

Datum pg_prepared_xact ( PG_FUNCTION_ARGS  )

Definition at line 717 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Working_State::array, BlessTupleDesc(), CreateTemplateTupleDesc(), CStringGetTextDatum, Working_State::currIdx, PGPROC::databaseId, GetPreparedTransactionList(), GlobalTransactionData::gid, heap_form_tuple(), HeapTupleGetDatum, MemoryContextSwitchTo(), MemSet, 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, status(), TimestampTzGetDatum, TransactionIdGetDatum, FuncCallContext::tuple_desc, TupleDescInitEntry(), FuncCallContext::user_fctx, GlobalTransactionData::valid, values, and PGXACT::xid.

718 {
719  FuncCallContext *funcctx;
721 
722  if (SRF_IS_FIRSTCALL())
723  {
724  TupleDesc tupdesc;
725  MemoryContext oldcontext;
726 
727  /* create a function context for cross-call persistence */
728  funcctx = SRF_FIRSTCALL_INIT();
729 
730  /*
731  * Switch to memory context appropriate for multiple function calls
732  */
733  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
734 
735  /* build tupdesc for result tuples */
736  /* this had better match pg_prepared_xacts view in system_views.sql */
737  tupdesc = CreateTemplateTupleDesc(5);
738  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
739  XIDOID, -1, 0);
740  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
741  TEXTOID, -1, 0);
742  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
743  TIMESTAMPTZOID, -1, 0);
744  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
745  OIDOID, -1, 0);
746  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
747  OIDOID, -1, 0);
748 
749  funcctx->tuple_desc = BlessTupleDesc(tupdesc);
750 
751  /*
752  * Collect all the 2PC status information that we will format and send
753  * out as a result set.
754  */
755  status = (Working_State *) palloc(sizeof(Working_State));
756  funcctx->user_fctx = (void *) status;
757 
758  status->ngxacts = GetPreparedTransactionList(&status->array);
759  status->currIdx = 0;
760 
761  MemoryContextSwitchTo(oldcontext);
762  }
763 
764  funcctx = SRF_PERCALL_SETUP();
765  status = (Working_State *) funcctx->user_fctx;
766 
767  while (status->array != NULL && status->currIdx < status->ngxacts)
768  {
769  GlobalTransaction gxact = &status->array[status->currIdx++];
770  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
771  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
772  Datum values[5];
773  bool nulls[5];
774  HeapTuple tuple;
775  Datum result;
776 
777  if (!gxact->valid)
778  continue;
779 
780  /*
781  * Form tuple with appropriate data.
782  */
783  MemSet(values, 0, sizeof(values));
784  MemSet(nulls, 0, sizeof(nulls));
785 
786  values[0] = TransactionIdGetDatum(pgxact->xid);
787  values[1] = CStringGetTextDatum(gxact->gid);
788  values[2] = TimestampTzGetDatum(gxact->prepared_at);
789  values[3] = ObjectIdGetDatum(gxact->owner);
790  values[4] = ObjectIdGetDatum(proc->databaseId);
791 
792  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
793  result = HeapTupleGetDatum(tuple);
794  SRF_RETURN_NEXT(funcctx, result);
795  }
796 
797  SRF_RETURN_DONE(funcctx);
798 }
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:44
Definition: proc.h:222
PGXACT * allPgXact
Definition: proc.h:249
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:282
TransactionId xid
Definition: proc.h:224
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition: twophase.c:672
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:962
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:286
char gid[GIDSIZE]
Definition: twophase.c:172
TupleDesc tuple_desc
Definition: funcapi.h:112
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:288
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2052
Oid databaseId
Definition: proc.h:114
GlobalTransaction array
Definition: twophase.c:704
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:603
#define TransactionIdGetDatum(X)
Definition: postgres.h:521
uintptr_t Datum
Definition: postgres.h:367
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:220
static Datum values[MAXATTR]
Definition: bootstrap.c:167
TimestampTz prepared_at
Definition: twophase.c:154
void * user_fctx
Definition: funcapi.h:82
void * palloc(Size size)
Definition: mcxt.c:949
#define CStringGetTextDatum(s)
Definition: builtins.h:83
PGPROC * allProcs
Definition: proc.h:247
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:226
Definition: proc.h:95
int16 AttrNumber
Definition: attnum.h:21
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:306
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:284

◆ PostPrepare_Twophase()

void PostPrepare_Twophase ( void  )

Definition at line 357 of file twophase.c.

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

358 {
359  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
361  LWLockRelease(TwoPhaseStateLock);
362 
363  MyLockedGxact = NULL;
364 }
BackendId locking_backend
Definition: twophase.c:168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define InvalidBackendId
Definition: backendid.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199

◆ PrepareRedoAdd()

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

Definition at line 2336 of file twophase.c.

References Assert, DEBUG2, elog, ereport, errcode(), errhint(), errmsg(), ERROR, TwoPhaseStateData::freeGXacts, GlobalTransactionData::gid, GlobalTransactionData::inredo, InvalidBackendId, InvalidRepOriginId, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockHeldByMeInMode(), max_prepared_xacts, MAXALIGN, 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, RecoveryInProgress(), replorigin_advance(), GlobalTransactionData::valid, GlobalTransactionData::xid, xl_xact_prepare::xid, and XLogRecPtrIsInvalid.

Referenced by restoreTwoPhaseData(), and xact_redo().

2338 {
2340  char *bufptr;
2341  const char *gid;
2342  GlobalTransaction gxact;
2343 
2344  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2346 
2347  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2348  gid = (const char *) bufptr;
2349 
2350  /*
2351  * Reserve the GID for the given transaction in the redo code path.
2352  *
2353  * This creates a gxact struct and puts it into the active array.
2354  *
2355  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2356  * shared memory. Hence, we only fill up the bare minimum contents here.
2357  * The gxact also gets marked with gxact->inredo set to true to indicate
2358  * that it got added in the redo phase
2359  */
2360 
2361  /* Get a free gxact from the freelist */
2362  if (TwoPhaseState->freeGXacts == NULL)
2363  ereport(ERROR,
2364  (errcode(ERRCODE_OUT_OF_MEMORY),
2365  errmsg("maximum number of prepared transactions reached"),
2366  errhint("Increase max_prepared_transactions (currently %d).",
2367  max_prepared_xacts)));
2368  gxact = TwoPhaseState->freeGXacts;
2369  TwoPhaseState->freeGXacts = gxact->next;
2370 
2371  gxact->prepared_at = hdr->prepared_at;
2372  gxact->prepare_start_lsn = start_lsn;
2373  gxact->prepare_end_lsn = end_lsn;
2374  gxact->xid = hdr->xid;
2375  gxact->owner = hdr->owner;
2377  gxact->valid = false;
2378  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2379  gxact->inredo = true; /* yes, added in redo */
2380  strcpy(gxact->gid, gid);
2381 
2382  /* And insert it into the active array */
2385 
2386  if (origin_id != InvalidRepOriginId)
2387  {
2388  /* recover apply progress */
2389  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2390  false /* backward */ , false /* WAL */ );
2391  }
2392 
2393  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2394 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
int errhint(const char *fmt,...)
Definition: elog.c:1069
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
int errcode(int sqlerrcode)
Definition: elog.c:608
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:857
GlobalTransaction next
Definition: twophase.c:151
bool RecoveryInProgress(void)
Definition: xlog.c:7931
char gid[GIDSIZE]
Definition: twophase.c:172
BackendId locking_backend
Definition: twophase.c:168
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:117
#define DEBUG2
Definition: elog.h:24
static char * buf
Definition: pg_test_fsync.c:67
XLogRecPtr origin_lsn
Definition: xact.h:309
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define InvalidBackendId
Definition: backendid.h:23
#define Assert(condition)
Definition: c.h:739
#define MAXALIGN(LEN)
Definition: c.h:692
TransactionId xid
Definition: xact.h:299
#define InvalidRepOriginId
Definition: origin.h:33
TransactionId xid
Definition: twophase.c:165
TimestampTz prepared_at
Definition: twophase.c:154
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
TimestampTz prepared_at
Definition: xact.h:301
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2406 of file twophase.c.

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

Referenced by ProcessTwoPhaseBuffer(), and xact_redo().

2407 {
2408  GlobalTransaction gxact = NULL;
2409  int i;
2410  bool found = false;
2411 
2412  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2414 
2415  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2416  {
2417  gxact = TwoPhaseState->prepXacts[i];
2418 
2419  if (gxact->xid == xid)
2420  {
2421  Assert(gxact->inredo);
2422  found = true;
2423  break;
2424  }
2425  }
2426 
2427  /*
2428  * Just leave if there is nothing, this is expected during WAL replay.
2429  */
2430  if (!found)
2431  return;
2432 
2433  /*
2434  * And now we can clean up any files we may have left.
2435  */
2436  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2437  if (gxact->ondisk)
2438  RemoveTwoPhaseFile(xid, giveWarning);
2439  RemoveGXact(gxact);
2440 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
bool RecoveryInProgress(void)
Definition: xlog.c:7931
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:634
#define DEBUG2
Definition: elog.h:24
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1597
#define Assert(condition)
Definition: c.h:739
TransactionId xid
Definition: twophase.c:165
#define elog(elevel,...)
Definition: elog.h:228
int i

◆ PrescanPreparedTransactions()

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

Definition at line 1840 of file twophase.c.

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

Referenced by StartupXLOG(), and xlog_redo().

1841 {
1843  TransactionId origNextXid = XidFromFullTransactionId(nextFullXid);
1844  TransactionId result = origNextXid;
1845  TransactionId *xids = NULL;
1846  int nxids = 0;
1847  int allocsize = 0;
1848  int i;
1849 
1850  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1851  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1852  {
1853  TransactionId xid;
1854  char *buf;
1856 
1857  Assert(gxact->inredo);
1858 
1859  xid = gxact->xid;
1860 
1861  buf = ProcessTwoPhaseBuffer(xid,
1862  gxact->prepare_start_lsn,
1863  gxact->ondisk, false, true);
1864 
1865  if (buf == NULL)
1866  continue;
1867 
1868  /*
1869  * OK, we think this file is valid. Incorporate xid into the
1870  * running-minimum result.
1871  */
1872  if (TransactionIdPrecedes(xid, result))
1873  result = xid;
1874 
1875  if (xids_p)
1876  {
1877  if (nxids == allocsize)
1878  {
1879  if (nxids == 0)
1880  {
1881  allocsize = 10;
1882  xids = palloc(allocsize * sizeof(TransactionId));
1883  }
1884  else
1885  {
1886  allocsize = allocsize * 2;
1887  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1888  }
1889  }
1890  xids[nxids++] = xid;
1891  }
1892 
1893  pfree(buf);
1894  }
1895  LWLockRelease(TwoPhaseStateLock);
1896 
1897  if (xids_p)
1898  {
1899  *xids_p = xids;
1900  *nxids_p = nxids;
1901  }
1902 
1903  return result;
1904 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:514
FullTransactionId nextFullXid
Definition: transam.h:164
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
#define XidFromFullTransactionId(x)
Definition: transam.h:48
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
static char * buf
Definition: pg_test_fsync.c:67
VariableCache ShmemVariableCache
Definition: varsup.c:34
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2063
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1069
TransactionId xid
Definition: twophase.c:165
void * palloc(Size size)
Definition: mcxt.c:949
int i

◆ ProcessRecords()

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

Definition at line 1569 of file twophase.c.

References Assert, TwoPhaseRecordOnDisk::info, TwoPhaseRecordOnDisk::len, MAXALIGN, TwoPhaseRecordOnDisk::rmid, TWOPHASE_RM_END_ID, TWOPHASE_RM_MAX_ID, and GlobalTransactionData::xid.

Referenced by FinishPreparedTransaction(), and RecoverPreparedTransactions().

1571 {
1572  for (;;)
1573  {
1574  TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1575 
1576  Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1577  if (record->rmid == TWOPHASE_RM_END_ID)
1578  break;
1579 
1580  bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1581 
1582  if (callbacks[record->rmid] != NULL)
1583  callbacks[record->rmid] (xid, record->info,
1584  (void *) bufptr, record->len);
1585 
1586  bufptr += MAXALIGN(record->len);
1587  }
1588 }
#define TWOPHASE_RM_MAX_ID
Definition: twophase_rmgr.h:29
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
#define Assert(condition)
Definition: c.h:739
#define MAXALIGN(LEN)
Definition: c.h:692
TwoPhaseRmgrId rmid
Definition: twophase.c:924

◆ ProcessTwoPhaseBuffer()

static char * ProcessTwoPhaseBuffer ( TransactionId  xid,
XLogRecPtr  prepare_start_lsn,
bool  fromdisk,
bool  setParent,
bool  setNextXid 
)
static

Definition at line 2063 of file twophase.c.

References AdvanceNextFullTransactionIdPastXid(), Assert, buf, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errmsg(), ERROR, xl_xact_prepare::gidlen, i, InvalidXLogRecPtr, LW_EXCLUSIVE, LWLockHeldByMeInMode(), MAXALIGN, VariableCacheData::nextFullXid, 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().

2067 {
2069  TransactionId origNextXid = XidFromFullTransactionId(nextFullXid);
2070  TransactionId *subxids;
2071  char *buf;
2072  TwoPhaseFileHeader *hdr;
2073  int i;
2074 
2075  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2076 
2077  if (!fromdisk)
2078  Assert(prepare_start_lsn != InvalidXLogRecPtr);
2079 
2080  /* Already processed? */
2082  {
2083  if (fromdisk)
2084  {
2085  ereport(WARNING,
2086  (errmsg("removing stale two-phase state file for transaction %u",
2087  xid)));
2088  RemoveTwoPhaseFile(xid, true);
2089  }
2090  else
2091  {
2092  ereport(WARNING,
2093  (errmsg("removing stale two-phase state from memory for transaction %u",
2094  xid)));
2095  PrepareRedoRemove(xid, true);
2096  }
2097  return NULL;
2098  }
2099 
2100  /* Reject XID if too new */
2101  if (TransactionIdFollowsOrEquals(xid, origNextXid))
2102  {
2103  if (fromdisk)
2104  {
2105  ereport(WARNING,
2106  (errmsg("removing future two-phase state file for transaction %u",
2107  xid)));
2108  RemoveTwoPhaseFile(xid, true);
2109  }
2110  else
2111  {
2112  ereport(WARNING,
2113  (errmsg("removing future two-phase state from memory for transaction %u",
2114  xid)));
2115  PrepareRedoRemove(xid, true);
2116  }
2117  return NULL;
2118  }
2119 
2120  if (fromdisk)
2121  {
2122  /* Read and validate file */
2123  buf = ReadTwoPhaseFile(xid, false);
2124  }
2125  else
2126  {
2127  /* Read xlog data */
2128  XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2129  }
2130 
2131  /* Deconstruct header */
2132  hdr = (TwoPhaseFileHeader *) buf;
2133  if (!TransactionIdEquals(hdr->xid, xid))
2134  {
2135  if (fromdisk)
2136  ereport(ERROR,
2138  errmsg("corrupted two-phase state file for transaction %u",
2139  xid)));
2140  else
2141  ereport(ERROR,
2143  errmsg("corrupted two-phase state in memory for transaction %u",
2144  xid)));
2145  }
2146 
2147  /*
2148  * Examine subtransaction XIDs ... they should all follow main XID, and
2149  * they may force us to advance nextFullXid.
2150  */
2151  subxids = (TransactionId *) (buf +
2152  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2153  MAXALIGN(hdr->gidlen));
2154  for (i = 0; i < hdr->nsubxacts; i++)
2155  {
2156  TransactionId subxid = subxids[i];
2157 
2158  Assert(TransactionIdFollows(subxid, xid));
2159 
2160  /* update nextFullXid if needed */
2161  if (setNextXid)
2163 
2164  if (setParent)
2165  SubTransSetParent(subxid, xid);
2166  }
2167 
2168  return buf;
2169 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
void PrepareRedoRemove(TransactionId xid, bool giveWarning)
Definition: twophase.c:2406
int32 nsubxacts
Definition: xact.h:303
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:514
void AdvanceNextFullTransactionIdPastXid(TransactionId xid)
Definition: varsup.c:262
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:349
int errcode(int sqlerrcode)
Definition: elog.c:608
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1210
uint16 gidlen
Definition: xact.h:308
FullTransactionId nextFullXid
Definition: transam.h:164
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define XidFromFullTransactionId(x)
Definition: transam.h:48
#define ERROR
Definition: elog.h:43
static char * buf
Definition: pg_test_fsync.c:67
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define ereport(elevel, rest)
Definition: elog.h:141
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:45
#define WARNING
Definition: elog.h:40
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1597
#define Assert(condition)
Definition: c.h:739
#define MAXALIGN(LEN)
Definition: c.h:692
TransactionId xid
Definition: xact.h:299
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1327
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition: subtrans.c:74

◆ ReadTwoPhaseFile()

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

Definition at line 1210 of file twophase.c.

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

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

1211 {
1212  char path[MAXPGPATH];
1213  char *buf;
1214  TwoPhaseFileHeader *hdr;
1215  int fd;
1216  struct stat stat;
1217  uint32 crc_offset;
1218  pg_crc32c calc_crc,
1219  file_crc;
1220  int r;
1221 
1222  TwoPhaseFilePath(path, xid);
1223 
1224  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
1225  if (fd < 0)
1226  {
1227  if (missing_ok && errno == ENOENT)
1228  return NULL;
1229 
1230  ereport(ERROR,
1232  errmsg("could not open file \"%s\": %m", path)));
1233  }
1234 
1235  /*
1236  * Check file length. We can determine a lower bound pretty easily. We
1237  * set an upper bound to avoid palloc() failure on a corrupt file, though
1238  * we can't guarantee that we won't get an out of memory error anyway,
1239  * even on a valid file.
1240  */
1241  if (fstat(fd, &stat))
1242  ereport(ERROR,
1244  errmsg("could not stat file \"%s\": %m", path)));
1245 
1246  if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1247  MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1248  sizeof(pg_crc32c)) ||
1249  stat.st_size > MaxAllocSize)
1250  ereport(ERROR,
1252  errmsg_plural("incorrect size of file \"%s\": %zu byte",
1253  "incorrect size of file \"%s\": %zu bytes",
1254  (Size) stat.st_size, path,
1255  (Size) stat.st_size)));
1256 
1257  crc_offset = stat.st_size - sizeof(pg_crc32c);
1258  if (crc_offset != MAXALIGN(crc_offset))
1259  ereport(ERROR,
1261  errmsg("incorrect alignment of CRC offset for file \"%s\"",
1262  path)));
1263 
1264  /*
1265  * OK, slurp in the file.
1266  */
1267  buf = (char *) palloc(stat.st_size);
1268 
1270  r = read(fd, buf, stat.st_size);
1271  if (r != stat.st_size)
1272  {
1273  if (r < 0)
1274  ereport(ERROR,
1276  errmsg("could not read file \"%s\": %m", path)));
1277  else
1278  ereport(ERROR,
1279  (errmsg("could not read file \"%s\": read %d of %zu",
1280  path, r, (Size) stat.st_size)));
1281  }
1282 
1284 
1285  if (CloseTransientFile(fd) != 0)
1286  ereport(ERROR,
1288  errmsg("could not close file \"%s\": %m", path)));
1289 
1290  hdr = (TwoPhaseFileHeader *) buf;
1291  if (hdr->magic != TWOPHASE_MAGIC)
1292  ereport(ERROR,
1294  errmsg("invalid magic number stored in file \"%s\"",
1295  path)));
1296 
1297  if (hdr->total_len != stat.st_size)
1298  ereport(ERROR,
1300  errmsg("invalid size stored in file \"%s\"",
1301  path)));
1302 
1303  INIT_CRC32C(calc_crc);
1304  COMP_CRC32C(calc_crc, buf, crc_offset);
1305  FIN_CRC32C(calc_crc);
1306 
1307  file_crc = *((pg_crc32c *) (buf + crc_offset));
1308 
1309  if (!EQ_CRC32C(calc_crc, file_crc))
1310  ereport(ERROR,
1312  errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
1313  path)));
1314 
1315  return buf;
1316 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:932
uint32 pg_crc32c
Definition: pg_crc32c.h:38
int errcode(int sqlerrcode)
Definition: elog.c:608
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1221
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:889
#define ERROR
Definition: elog.h:43
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2291
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:67
int errcode_for_file_access(void)
Definition: elog.c:631
uint32 total_len
Definition: xact.h:298
unsigned int uint32
Definition: c.h:359
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1344
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
#define ereport(elevel, rest)
Definition: elog.h:141
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:45
#define MaxAllocSize
Definition: memutils.h:40
int CloseTransientFile(int fd)
Definition: fd.c:2468
#define stat(a, b)
Definition: win32_port.h:255
#define TWOPHASE_MAGIC
Definition: twophase.c:911
size_t Size
Definition: c.h:467
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1320
#define MAXALIGN(LEN)
Definition: c.h:692
uint32 magic
Definition: xact.h:297
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
#define read(a, b, c)
Definition: win32.h:13

◆ RecordTransactionAbortPrepared()

static void RecordTransactionAbortPrepared ( TransactionId  xid,
int  nchildren,
TransactionId children,
int  nrels,
RelFileNode rels,
const char *  gid 
)
static

Definition at line 2277 of file twophase.c.

References elog, END_CRIT_SECTION, GetCurrentTimestamp(), MyXactFlags, PANIC, START_CRIT_SECTION, SyncRepWaitForLSN(), TransactionIdAbortTree(), TransactionIdDidCommit(), XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK, XactLogAbortRecord(), and XLogFlush().

Referenced by FinishPreparedTransaction().

2283 {
2284  XLogRecPtr recptr;
2285 
2286  /*
2287  * Catch the scenario where we aborted partway through
2288  * RecordTransactionCommitPrepared ...
2289  */
2290  if (TransactionIdDidCommit(xid))
2291  elog(PANIC, "cannot abort transaction %u, it was already committed",
2292  xid);
2293 
2295 
2296  /*
2297  * Emit the XLOG commit record. Note that we mark 2PC aborts as
2298  * potentially having AccessExclusiveLocks since we don't know whether or
2299  * not they do.
2300  */
2302  nchildren, children,
2303  nrels, rels,
2305  xid, gid);
2306 
2307  /* Always flush, since we're about to remove the 2PC state file */
2308  XLogFlush(recptr);
2309 
2310  /*
2311  * Mark the transaction aborted in clog. This is not absolutely necessary
2312  * but we may as well do it while we are here.
2313  */
2314  TransactionIdAbortTree(xid, nchildren, children);
2315 
2316  END_CRIT_SECTION();
2317 
2318  /*
2319  * Wait for synchronous replication, if required.
2320  *
2321  * Note that at this stage we have marked clog, but still show as running
2322  * in the procarray and continue to hold locks.
2323  */
2324  SyncRepWaitForLSN(recptr, false);
2325 }
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:290
XLogRecPtr XactLogAbortRecord(TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileNode *rels, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition: xact.c:5600
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:146
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define PANIC
Definition: elog.h:53
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2804
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:103
int MyXactFlags
Definition: xact.c:118
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define elog(elevel,...)
Definition: elog.h:228

◆ RecordTransactionCommitPrepared()

static void RecordTransactionCommitPrepared ( TransactionId  xid,
int  nchildren,
TransactionId children,
int  nrels,
RelFileNode rels,
int  ninvalmsgs,
SharedInvalidationMessage invalmsgs,
bool  initfileinval,
const char *  gid 
)
static

Definition at line 2183 of file twophase.c.

References PGXACT::delayChkpt, DoNotReplicateId, END_CRIT_SECTION, GetCurrentTimestamp(), InvalidRepOriginId, MyPgXact, 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().

2192 {
2193  XLogRecPtr recptr;
2194  TimestampTz committs = GetCurrentTimestamp();
2195  bool replorigin;
2196 
2197  /*
2198  * Are we using the replication origins feature? Or, in other words, are
2199  * we replaying remote actions?
2200  */
2201  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2203 
2205 
2206  /* See notes in RecordTransactionCommit */
2207  MyPgXact->delayChkpt = true;
2208 
2209  /*
2210  * Emit the XLOG commit record. Note that we mark 2PC commits as
2211  * potentially having AccessExclusiveLocks since we don't know whether or
2212  * not they do.
2213  */
2214  recptr = XactLogCommitRecord(committs,
2215  nchildren, children, nrels, rels,
2216  ninvalmsgs, invalmsgs,
2217  initfileinval, false,
2219  xid, gid);
2220 
2221 
2222  if (replorigin)
2223  /* Move LSNs forward for this replication origin */
2225  XactLastRecEnd);
2226 
2227  /*
2228  * Record commit timestamp. The value comes from plain commit timestamp
2229  * if replorigin is not enabled, or replorigin already set a value for us
2230  * in replorigin_session_origin_timestamp otherwise.
2231  *
2232  * We don't need to WAL-log anything here, as the commit record written
2233  * above already contains the data.
2234  */
2235  if (!replorigin || replorigin_session_origin_timestamp == 0)
2237 
2238  TransactionTreeSetCommitTsData(xid, nchildren, children,
2240  replorigin_session_origin, false);
2241 
2242  /*
2243  * We don't currently try to sleep before flush here ... nor is there any
2244  * support for async commit of a prepared xact (the very idea is probably
2245  * a contradiction)
2246  */
2247 
2248  /* Flush XLOG to disk */
2249  XLogFlush(recptr);
2250 
2251  /* Mark the transaction committed in pg_xact */
2252  TransactionIdCommitTree(xid, nchildren, children);
2253 
2254  /* Checkpoint can proceed now */
2255  MyPgXact->delayChkpt = false;
2256 
2257  END_CRIT_SECTION();
2258 
2259  /*
2260  * Wait for synchronous replication, if required.
2261  *
2262  * Note that at this stage we have marked clog, but still show as running
2263  * in the procarray and continue to hold locks.
2264  */
2265  SyncRepWaitForLSN(recptr, true);
2266 }
#define DoNotReplicateId
Definition: origin.h:34
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
XLogRecPtr XactLastRecEnd
Definition: xlog.c:351
int64 TimestampTz
Definition: timestamp.h:39
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:146
#define END_CRIT_SECTION()
Definition: miscadmin.h:134
#define START_CRIT_SECTION()
Definition: miscadmin.h:132
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2804
PGXACT * MyPgXact
Definition: proc.c:68
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:103
void TransactionIdCommitTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:260
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:153
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:154
bool delayChkpt
Definition: proc.h:235
XLogRecPtr XactLogCommitRecord(TimestampTz commit_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileNode *rels, int nmsgs, SharedInvalidationMessage *msgs, bool relcacheInval, bool forceSync, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition: xact.c:5445
int MyXactFlags
Definition: xact.c:118
uint64 XLogRecPtr
Definition: xlogdefs.h:21
RepOriginId replorigin_session_origin
Definition: origin.c:152
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1170
#define InvalidRepOriginId
Definition: origin.h:33
void TransactionTreeSetCommitTsData(TransactionId xid, int nsubxids, TransactionId *subxids, TimestampTz timestamp, RepOriginId nodeid, bool write_xlog)
Definition: commit_ts.c:145

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 1962 of file twophase.c.

References Assert, buf, xl_xact_prepare::database, ereport, errmsg(), GlobalTransactionData::gid, xl_xact_prepare::gidlen, GXactLoadSubxactData(), i, InHotStandby, GlobalTransactionData::inredo, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MarkAsPrepared(), MarkAsPreparingGuts(), MAXALIGN, xl_xact_prepare::nabortrels, xl_xact_prepare::ncommitrels, 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, GlobalTransactionData::xid, and xl_xact_prepare::xid.

Referenced by StartupXLOG().

1963 {
1964  int i;
1965 
1966  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1967  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1968  {
1969  TransactionId xid;
1970  char *buf;
1972  char *bufptr;
1973  TwoPhaseFileHeader *hdr;
1974  TransactionId *subxids;
1975  const char *gid;
1976 
1977  xid = gxact->xid;
1978 
1979  /*
1980  * Reconstruct subtrans state for the transaction --- needed because
1981  * pg_subtrans is not preserved over a restart. Note that we are
1982  * linking all the subtransactions directly to the top-level XID;
1983  * there may originally have been a more complex hierarchy, but
1984  * there's no need to restore that exactly. It's possible that
1985  * SubTransSetParent has been set before, if the prepared transaction
1986  * generated xid assignment records.
1987  */
1988  buf = ProcessTwoPhaseBuffer(xid,
1989  gxact->prepare_start_lsn,
1990  gxact->ondisk, true, false);
1991  if (buf == NULL)
1992  continue;
1993 
1994  ereport(LOG,
1995  (errmsg("recovering prepared transaction %u from shared memory", xid)));
1996 
1997  hdr = (TwoPhaseFileHeader *) buf;
1998  Assert(TransactionIdEquals(hdr->xid, xid));
1999  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2000  gid = (const char *) bufptr;
2001  bufptr += MAXALIGN(hdr->gidlen);
2002  subxids = (TransactionId *) bufptr;
2003  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
2004  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
2005  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
2006  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
2007 
2008  /*
2009  * Recreate its GXACT and dummy PGPROC. But, check whether it was
2010  * added in redo and already has a shmem entry for it.
2011  */
2012  MarkAsPreparingGuts(gxact, xid, gid,
2013  hdr->prepared_at,
2014  hdr->owner, hdr->database);
2015 
2016  /* recovered, so reset the flag for entries generated by redo */
2017  gxact->inredo = false;
2018 
2019  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
2020  MarkAsPrepared(gxact, true);
2021 
2022  LWLockRelease(TwoPhaseStateLock);
2023 
2024  /*
2025  * Recover other state (notably locks) using resource managers.
2026  */
2028 
2029  /*
2030  * Release locks held by the standby process after we process each
2031  * prepared transaction. As a result, we don't need too many
2032  * additional locks at any one time.
2033  */
2034  if (InHotStandby)
2035  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2036 
2037  /*
2038  * We're done with recovering this transaction. Clear MyLockedGxact,
2039  * like we do in PrepareTransaction() during normal operation.
2040  */
2042 
2043  pfree(buf);
2044 
2045  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2046  }
2047 
2048  LWLockRelease(TwoPhaseStateLock);
2049 }
int32 ninvalmsgs
Definition: xact.h:306
int32 nsubxacts
Definition: xact.h:303
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:514
int32 ncommitrels
Definition: xact.h:304
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1569
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlog.h:74
uint16 gidlen
Definition: xact.h:308
#define LOG
Definition: elog.h:26
Oid database
Definition: xact.h:300
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
int32 nabortrels
Definition: xact.h:305
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:446
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:509
static char * buf
Definition: pg_test_fsync.c:67
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:716
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2063
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define MAXALIGN(LEN)
Definition: c.h:692
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:536
TransactionId xid
Definition: xact.h:299
TransactionId xid
Definition: twophase.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:822
void PostPrepare_Twophase(void)
Definition: twophase.c:357
int i
TimestampTz prepared_at
Definition: xact.h:301

◆ RecreateTwoPhaseFile()

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

Definition at line 1616 of file twophase.c.

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

Referenced by CheckPointTwoPhase().

1617 {
1618  char path[MAXPGPATH];
1619  pg_crc32c statefile_crc;
1620  int fd;
1621 
1622  /* Recompute CRC */
1623  INIT_CRC32C(statefile_crc);
1624  COMP_CRC32C(statefile_crc, content, len);
1625  FIN_CRC32C(statefile_crc);
1626 
1627  TwoPhaseFilePath(path, xid);
1628 
1629  fd = OpenTransientFile(path,
1630  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY);
1631  if (fd < 0)
1632  ereport(ERROR,
1634  errmsg("could not recreate file \"%s\": %m", path)));
1635 
1636  /* Write content and CRC */
1637  errno = 0;
1639  if (write(fd, content, len) != len)
1640  {
1641  /* if write didn't set errno, assume problem is no disk space */
1642  if (errno == 0)
1643  errno = ENOSPC;
1644  ereport(ERROR,
1646  errmsg("could not write file \"%s\": %m", path)));
1647  }
1648  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1649  {
1650  /* if write didn't set errno, assume problem is no disk space */
1651  if (errno == 0)
1652  errno = ENOSPC;
1653  ereport(ERROR,
1655  errmsg("could not write file \"%s\": %m", path)));
1656  }
1658 
1659  /*
1660  * We must fsync the file because the end-of-replay checkpoint will not do
1661  * so, there being no GXACT in shared memory yet to tell it to.
1662  */
1664  if (pg_fsync(fd) != 0)
1665  ereport(ERROR,
1667  errmsg("could not fsync file \"%s\": %m", path)));
1669 
1670  if (CloseTransientFile(fd) != 0)
1671  ereport(ERROR,
1673  errmsg("could not close file \"%s\": %m", path)));
1674 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define write(a, b, c)
Definition: win32.h:14
uint32 pg_crc32c
Definition: pg_crc32c.h:38
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1221
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:889
#define ERROR
Definition: elog.h:43
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2291
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:631
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1344
#define ereport(elevel, rest)
Definition: elog.h:141
int CloseTransientFile(int fd)
Definition: fd.c:2468
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1320
int errmsg(const char *fmt,...)
Definition: elog.c:822
int pg_fsync(int fd)
Definition: fd.c:329
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94

◆ RegisterTwoPhaseRecord()

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

Definition at line 1187 of file twophase.c.

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

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

1189 {
1190  TwoPhaseRecordOnDisk record;
1191 
1192  record.rmid = rmid;
1193  record.info = info;
1194  record.len = len;
1195  save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1196  if (len > 0)
1197  save_state_data(data, len);
1198 }
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:959
TwoPhaseRmgrId rmid
Definition: twophase.c:924

◆ RemoveGXact()

static void RemoveGXact ( GlobalTransaction  gxact)
static

Definition at line 634 of file twophase.c.

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

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

635 {
636  int i;
637 
638  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
639 
640  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
641  {
642  if (gxact == TwoPhaseState->prepXacts[i])
643  {
644  /* remove from the active array */
647 
648  /* and put it back in the freelist */
649  gxact->next = TwoPhaseState->freeGXacts;
650  TwoPhaseState->freeGXacts = gxact;
651 
652  return;
653  }
654  }
655 
656  elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
657 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
GlobalTransaction next
Definition: twophase.c:151
#define ERROR
Definition: elog.h:43
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define Assert(condition)
Definition: c.h:739
#define elog(elevel,...)
Definition: elog.h:228
int i

◆ RemoveTwoPhaseFile()

static void RemoveTwoPhaseFile ( TransactionId  xid,
bool  giveWarning 
)
static

Definition at line 1597 of file twophase.c.

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

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

1598 {
1599  char path[MAXPGPATH];
1600 
1601  TwoPhaseFilePath(path, xid);
1602  if (unlink(path))
1603  if (errno != ENOENT || giveWarning)
1604  ereport(WARNING,
1606  errmsg("could not remove file \"%s\": %m", path)));
1607 }
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:889
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:631
#define ereport(elevel, rest)
Definition: elog.h:141
#define WARNING
Definition: elog.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1778 of file twophase.c.

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

Referenced by StartupXLOG().

1779 {
1780  DIR *cldir;
1781  struct dirent *clde;
1782 
1783  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1784  cldir = AllocateDir(TWOPHASE_DIR);
1785  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1786  {
1787  if (strlen(clde->d_name) == 8 &&
1788  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1789  {
1790  TransactionId xid;
1791  char *buf;
1792 
1793  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1794 
1796  true, false, false);
1797  if (buf == NULL)
1798  continue;
1799 
1802  }
1803  }
1804  LWLockRelease(TwoPhaseStateLock);
1805  FreeDir(cldir);
1806 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TransactionId
Definition: c.h:514
Definition: dirent.h:9
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
Definition: dirent.c:25
static char * buf
Definition: pg_test_fsync.c:67
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2502
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2063
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2336
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2568
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define InvalidRepOriginId
Definition: origin.h:33
#define TWOPHASE_DIR
Definition: twophase.c:114
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2620

◆ save_state_data()

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

Definition at line 959 of file twophase.c.

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

Referenced by RegisterTwoPhaseRecord(), and StartPrepare().

960 {
961  uint32 padlen = MAXALIGN(len);
962 
963  if (padlen > records.bytes_free)
964  {
965  records.tail->next = palloc0(sizeof(StateFileChunk));
967  records.tail->len = 0;
968  records.tail->next = NULL;
970 
971  records.bytes_free = Max(padlen, 512);
973  }
974 
975  memcpy(((char *) records.tail->data) + records.tail->len, data, len);
976  records.tail->len += padlen;
977  records.bytes_free -= padlen;
978  records.total_len += padlen;
979 }
StateFileChunk * tail
Definition: twophase.c:943
uint32 num_chunks
Definition: twophase.c:944
char * data
Definition: twophase.c:935
uint32 bytes_free
Definition: twophase.c:945
uint32 len
Definition: twophase.c:936
unsigned int uint32
Definition: c.h:359
static struct xllist records
uint32 total_len
Definition: twophase.c:946
struct StateFileChunk * next
Definition: twophase.c:937
void * palloc0(Size size)
Definition: mcxt.c:980
#define Max(x, y)
Definition: c.h:905
#define MAXALIGN(LEN)
Definition: c.h:692
void * palloc(Size size)
Definition: mcxt.c:949

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 1921 of file twophase.c.

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

Referenced by StartupXLOG(), and xlog_redo().

1922 {
1923  int i;
1924 
1925  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1926  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1927  {
1928  TransactionId xid;
1929  char *buf;
1931 
1932  Assert(gxact->inredo);
1933 
1934  xid = gxact->xid;
1935 
1936  buf = ProcessTwoPhaseBuffer(xid,
1937  gxact->prepare_start_lsn,
1938  gxact->ondisk, false, false);
1939  if (buf != NULL)
1940  pfree(buf);
1941  }
1942  LWLockRelease(TwoPhaseStateLock);
1943 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:514
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
static char * buf
Definition: pg_test_fsync.c:67
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2063
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
TransactionId xid
Definition: twophase.c:165
int i

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1372 of file twophase.c.

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

1373 {
1374  char *buf;
1375  TwoPhaseFileHeader *hdr;
1376  bool result;
1377 
1379 
1380  if (max_prepared_xacts <= 0)
1381  return false; /* nothing to do */
1382 
1383  /* Read and validate file */
1384  buf = ReadTwoPhaseFile(xid, true);
1385  if (buf == NULL)
1386  return false;
1387 
1388  /* Check header also */
1389  hdr = (TwoPhaseFileHeader *) buf;
1390  result = TransactionIdEquals(hdr->xid, xid);
1391  pfree(buf);
1392 
1393  return result;
1394 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1210
void pfree(void *pointer)
Definition: mcxt.c:1056
int max_prepared_xacts
Definition: twophase.c:117
static char * buf
Definition: pg_test_fsync.c:67
#define Assert(condition)
Definition: c.h:739
TransactionId xid
Definition: xact.h:299
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 987 of file twophase.c.

References PROC_HDR::allPgXact, 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, StateFileChunk::len, xl_xact_prepare::magic, Max, xl_xact_prepare::nabortrels, xl_xact_prepare::ncommitrels, StateFileChunk::next, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, xllist::num_chunks, GlobalTransactionData::owner, xl_xact_prepare::owner, palloc(), palloc0(), pfree(), GlobalTransactionData::pgprocno, GlobalTransactionData::prepared_at, xl_xact_prepare::prepared_at, ProcGlobal, records, save_state_data(), smgrGetPendingDeletes(), xllist::tail, xl_xact_prepare::total_len, xllist::total_len, TWOPHASE_MAGIC, xactGetCommittedChildren(), xactGetCommittedInvalidationMessages(), GlobalTransactionData::xid, PGXACT::xid, and xl_xact_prepare::xid.

Referenced by PrepareTransaction().

988 {
989  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
990  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
991  TransactionId xid = pgxact->xid;
992  TwoPhaseFileHeader hdr;
993  TransactionId *children;
994  RelFileNode *commitrels;
995  RelFileNode *abortrels;
996  SharedInvalidationMessage *invalmsgs;
997 
998  /* Initialize linked list */
999  records.head = palloc0(sizeof(StateFileChunk));
1000  records.head->len = 0;
1001  records.head->next = NULL;
1002 
1003  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1005 
1007  records.num_chunks = 1;
1008 
1009  records.total_len = 0;
1010 
1011  /* Create header */
1012  hdr.magic = TWOPHASE_MAGIC;
1013  hdr.total_len = 0; /* EndPrepare will fill this in */
1014  hdr.xid = xid;
1015  hdr.database = proc->databaseId;
1016  hdr.prepared_at = gxact->prepared_at;
1017  hdr.owner = gxact->owner;
1018  hdr.nsubxacts = xactGetCommittedChildren(&children);
1019  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1020  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1022  &hdr.initfileinval);
1023  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1024 
1025  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1026  save_state_data(gxact->gid, hdr.gidlen);
1027 
1028  /*
1029  * Add the additional info about subxacts, deletable files and cache
1030  * invalidation messages.
1031  */
1032  if (hdr.nsubxacts > 0)
1033  {
1034  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1035  /* While we have the child-xact data, stuff it in the gxact too */
1036  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1037  }
1038  if (hdr.ncommitrels > 0)
1039  {
1040  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1041  pfree(commitrels);
1042  }
1043  if (hdr.nabortrels > 0)
1044  {
1045  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1046  pfree(abortrels);
1047  }
1048  if (hdr.ninvalmsgs > 0)
1049  {
1050  save_state_data(invalmsgs,
1051  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1052  pfree(invalmsgs);
1053  }
1054 }
int32 ninvalmsgs
Definition: xact.h:306
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5421
int32 nsubxacts
Definition: xact.h:303
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
int32 ncommitrels
Definition: xact.h:304
PGXACT * allPgXact
Definition: proc.h:249
TransactionId xid
Definition: proc.h:224
StateFileChunk * tail
Definition: twophase.c:943
PROC_HDR * ProcGlobal
Definition: proc.c:80
uint16 gidlen
Definition: xact.h:308
uint32 num_chunks
Definition: twophase.c:944
char gid[GIDSIZE]
Definition: twophase.c:172
Oid database
Definition: xact.h:300
char * data
Definition: twophase.c:935
int32 nabortrels
Definition: xact.h:305
void pfree(void *pointer)
Definition: mcxt.c:1056
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:509
uint32 bytes_free
Definition: twophase.c:945
int smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
Definition: storage.c:513
uint32 total_len
Definition: xact.h:298
uint32 len
Definition: twophase.c:936
Oid databaseId
Definition: proc.h:114
static struct xllist records
uint32 total_len
Definition: twophase.c:946
struct StateFileChunk * next
Definition: twophase.c:937
void * palloc0(Size size)
Definition: mcxt.c:980
#define TWOPHASE_MAGIC
Definition: twophase.c:911
bool initfileinval
Definition: xact.h:307
#define Max(x, y)
Definition: c.h:905
StateFileChunk * head
Definition: twophase.c:942
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:959
TransactionId xid
Definition: xact.h:299
TimestampTz prepared_at
Definition: twophase.c:154
uint32 magic
Definition: xact.h:297
void * palloc(Size size)
Definition: mcxt.c:949
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:828
TimestampTz prepared_at
Definition: xact.h:301
PGPROC * allProcs
Definition: proc.h:247
Definition: proc.h:95

◆ TwoPhaseGetDummyBackendId()

BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid,
bool  lock_held 
)

Definition at line 863 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

864 {
865  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
866 
867  return gxact->dummyBackendId;
868 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:809
BackendId dummyBackendId
Definition: twophase.c:153

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid,
bool  lock_held 
)

Definition at line 878 of file twophase.c.

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

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

879 {
880  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
881 
882  return &ProcGlobal->allProcs[gxact->pgprocno];
883 }
PROC_HDR * ProcGlobal
Definition: proc.c:80
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:809
PGPROC * allProcs
Definition: proc.h:247

◆ TwoPhaseGetGXact()

static GlobalTransaction TwoPhaseGetGXact ( TransactionId  xid,
bool  lock_held 
)
static

Definition at line 809 of file twophase.c.

References PROC_HDR::allPgXact, Assert, elog, ERROR, i, InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockHeldByMe(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, GlobalTransactionData::pgprocno, TwoPhaseStateData::prepXacts, ProcGlobal, GlobalTransactionData::xid, and PGXACT::xid.

Referenced by TwoPhaseGetDummyBackendId(), and TwoPhaseGetDummyProc().

810 {
811  GlobalTransaction result = NULL;
812  int i;
813 
814  static TransactionId cached_xid = InvalidTransactionId;
815  static GlobalTransaction cached_gxact = NULL;
816 
817  Assert(!lock_held || LWLockHeldByMe(TwoPhaseStateLock));
818 
819  /*
820  * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
821  * repeatedly for the same XID. We can save work with a simple cache.
822  */
823  if (xid == cached_xid)
824  return cached_gxact;
825 
826  if (!lock_held)
827  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
828 
829  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
830  {
832  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
833 
834  if (pgxact->xid == xid)
835  {
836  result = gxact;
837  break;
838  }
839  }
840 
841  if (!lock_held)
842  LWLockRelease(TwoPhaseStateLock);
843 
844  if (result == NULL) /* should not happen */
845  elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
846 
847  cached_xid = xid;
848  cached_gxact = result;
849 
850  return result;
851 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:514
Definition: proc.h:222
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
PGXACT * allPgXact
Definition: proc.h:249
TransactionId xid
Definition: proc.h:224
PROC_HDR * ProcGlobal
Definition: proc.c:80
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define ERROR
Definition: elog.h:43
#define InvalidTransactionId
Definition: transam.h:31
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define Assert(condition)
Definition: c.h:739
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define elog(elevel,...)
Definition: elog.h:228
int i

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 252 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

253 {
254  bool found;
255 
256  TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
258  &found);
259  if (!IsUnderPostmaster)
260  {
261  GlobalTransaction gxacts;
262  int i;
263 
264  Assert(!found);
265  TwoPhaseState->freeGXacts = NULL;
267 
268  /*
269  * Initialize the linked list of free GlobalTransactionData structs
270  */
271  gxacts = (GlobalTransaction)
272  ((char *) TwoPhaseState +
273  MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
275  for (i = 0; i < max_prepared_xacts; i++)
276  {
277  /* insert into linked list */
278  gxacts[i].next = TwoPhaseState->freeGXacts;
279  TwoPhaseState->freeGXacts = &gxacts[i];
280 
281  /* associate it with a PGPROC assigned by InitProcGlobal */
283 
284  /*
285  * Assign a unique ID for each dummy proc, so that the range of
286  * dummy backend IDs immediately follows the range of normal
287  * backend IDs. We don't dare to assign a real backend ID to dummy
288  * procs, because prepared transactions don't take part in cache
289  * invalidation like a real backend ID would imply, but having a
290  * unique ID for them is nevertheless handy. This arrangement
291  * allows you to allocate an array of size (MaxBackends +
292  * max_prepared_xacts + 1), and have a slot for every backend and
293  * prepared transaction. Currently multixact.c uses that
294  * technique.
295  */
296  gxacts[i].dummyBackendId = MaxBackends + 1 + i;
297  }
298  }
299  else
300  Assert(found);
301 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
PGPROC * PreparedXactProcs
Definition: proc.c:82
Size TwoPhaseShmemSize(void)
Definition: twophase.c:236
GlobalTransaction next
Definition: twophase.c:151
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:26
int max_prepared_xacts
Definition: twophase.c:117
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:392
int MaxBackends
Definition: globals.c:135
bool IsUnderPostmaster
Definition: globals.c:109
#define Assert(condition)
Definition: c.h:739
#define MAXALIGN(LEN)
Definition: c.h:692
int pgprocno
Definition: proc.h:110
int i
#define offsetof(type, field)
Definition: c.h:662
BackendId dummyBackendId
Definition: twophase.c:153

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 236 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores(), and TwoPhaseShmemInit().

237 {
238  Size size;
239 
240  /* Need the fixed struct, the array of pointers, and the GTD structs */
241  size = offsetof(TwoPhaseStateData, prepXacts);
242  size = add_size(size, mul_size(max_prepared_xacts,
243  sizeof(GlobalTransaction)));
244  size = MAXALIGN(size);
245  size = add_size(size, mul_size(max_prepared_xacts,
246  sizeof(GlobalTransactionData)));
247 
248  return size;
249 }
int max_prepared_xacts
Definition: twophase.c:117
Size mul_size(Size s1, Size s2)
Definition: shmem.c:515
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
size_t Size
Definition: c.h:467
#define MAXALIGN(LEN)
Definition: c.h:692
#define offsetof(type, field)
Definition: c.h:662

◆ XlogReadTwoPhaseData()

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

Definition at line 1327 of file twophase.c.

References ereport, errcode(), errcode_for_file_access(), errdetail(), errmsg(), ERROR, palloc(), read_local_xlog_page(), wal_segment_size, XLOG_XACT_OPMASK, XLOG_XACT_PREPARE, XLogBeginRead(), XLogReaderAllocate(), XLogReaderFree(), XLogReadRecord(), XLogRecGetData, XLogRecGetDataLen, XLogRecGetInfo, and XLogRecGetRmid.

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

1328 {
1329  XLogRecord *record;
1330  XLogReaderState *xlogreader;
1331  char *errormsg;
1332 
1333  xlogreader = XLogReaderAllocate(wal_segment_size, NULL,
1334  &read_local_xlog_page, NULL);
1335  if (!xlogreader)
1336  ereport(ERROR,
1337  (errcode(ERRCODE_OUT_OF_MEMORY),
1338  errmsg("out of memory"),
1339  errdetail("Failed while allocating a WAL reading processor.")));
1340 
1341  XLogBeginRead(xlogreader, lsn);
1342  record = XLogReadRecord(xlogreader, &errormsg);
1343  if (record == NULL)
1344  ereport(ERROR,
1346  errmsg("could not read two-phase state from WAL at %X/%X",
1347  (uint32) (lsn >> 32),
1348  (uint32) lsn)));
1349 
1350  if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1352  ereport(ERROR,
1354  errmsg("expected two-phase state data is not present in WAL at %X/%X",
1355  (uint32) (lsn >> 32),
1356  (uint32) lsn)));
1357 
1358  if (len != NULL)
1359  *len = XLogRecGetDataLen(xlogreader);
1360 
1361  *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1362  memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1363 
1364  XLogReaderFree(xlogreader);
1365 }
#define XLOG_XACT_PREPARE
Definition: xact.h:144
int wal_segment_size
Definition: xlog.c:112
int errcode(int sqlerrcode)
Definition: elog.c:608
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:261
#define XLogRecGetData(decoder)
Definition: xlogreader.h:288
#define ERROR
Definition: elog.h:43
#define XLogRecGetDataLen(decoder)
Definition: xlogreader.h:289
static char * buf
Definition: pg_test_fsync.c:67
int errdetail(const char *fmt,...)
Definition: elog.c:955
int errcode_for_file_access(void)
Definition: elog.c:631
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:233
unsigned int uint32
Definition: c.h:359
#define ereport(elevel, rest)
Definition: elog.h:141
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:284
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:135
#define XLOG_XACT_OPMASK
Definition: xact.h:153
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogPageReadCB pagereadfunc, void *private_data)
Definition: xlogreader.c:73
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:822
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:285

Variable Documentation

◆ max_prepared_xacts

◆ MyLockedGxact

GlobalTransaction MyLockedGxact = NULL
static

Definition at line 199 of file twophase.c.

◆ records

struct xllist records
static

◆ twophaseExitRegistered

bool twophaseExitRegistered = false
static

Definition at line 201 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseState

TwoPhaseStateData* TwoPhaseState
static

Definition at line 191 of file twophase.c.