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/xlogutils.h"
#include "access/xlogreader.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  TwoPhaseFileHeader
 
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 struct TwoPhaseFileHeader 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)
 
void ParsePrepareRecord (uint8 info, char *xlrec, xl_xact_parsed_prepare *parsed)
 
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 115 of file twophase.c.

Referenced by CheckPointTwoPhase(), and restoreTwoPhaseData().

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */

Definition at line 912 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 890 of file twophase.c.

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

Typedef Documentation

◆ GlobalTransactionData

◆ StateFileChunk

◆ TwoPhaseFileHeader

◆ TwoPhaseRecordOnDisk

◆ TwoPhaseStateData

Function Documentation

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 318 of file twophase.c.

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

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

◆ AtProcExit_Twophase()

static void AtProcExit_Twophase ( int  code,
Datum  arg 
)
static

Definition at line 308 of file twophase.c.

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

309 {
310  /* same logic as abort */
312 }
void AtAbort_Twophase(void)
Definition: twophase.c:318

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1750 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().

1751 {
1752  int i;
1753  int serialized_xacts = 0;
1754 
1755  if (max_prepared_xacts <= 0)
1756  return; /* nothing to do */
1757 
1758  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1759 
1760  /*
1761  * We are expecting there to be zero GXACTs that need to be copied to
1762  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1763  * simplicity. This prevents any new xacts from preparing while this
1764  * occurs, which shouldn't be a problem since the presence of long-lived
1765  * prepared xacts indicates the transaction manager isn't active.
1766  *
1767  * It's also possible to move I/O out of the lock, but on every error we
1768  * should check whether somebody committed our transaction in different
1769  * backend. Let's leave this optimization for future, if somebody will
1770  * spot that this place cause bottleneck.
1771  *
1772  * Note that it isn't possible for there to be a GXACT with a
1773  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1774  * because of the efforts with delayChkpt.
1775  */
1776  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1777  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1778  {
1779  /*
1780  * Note that we are using gxact not pgxact so this works in recovery
1781  * also
1782  */
1784 
1785  if ((gxact->valid || gxact->inredo) &&
1786  !gxact->ondisk &&
1787  gxact->prepare_end_lsn <= redo_horizon)
1788  {
1789  char *buf;
1790  int len;
1791 
1792  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1793  RecreateTwoPhaseFile(gxact->xid, buf, len);
1794  gxact->ondisk = true;
1797  pfree(buf);
1798  serialized_xacts++;
1799  }
1800  }
1801  LWLockRelease(TwoPhaseStateLock);
1802 
1803  /*
1804  * Flush unconditionally the parent directory to make any information
1805  * durable on disk. Two-phase files could have been removed and those
1806  * removals need to be made persistent as well as any files newly created
1807  * previously since the last checkpoint.
1808  */
1809  fsync_fname(TWOPHASE_DIR, true);
1810 
1811  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1812 
1813  if (log_checkpoints && serialized_xacts > 0)
1814  ereport(LOG,
1815  (errmsg_plural("%u two-phase state file was written "
1816  "for a long-running prepared transaction",
1817  "%u two-phase state files were written "
1818  "for long-running prepared transactions",
1819  serialized_xacts,
1820  serialized_xacts)));
1821 }
bool log_checkpoints
Definition: xlog.c:101
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:837
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:580
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:164
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
int max_prepared_xacts
Definition: twophase.c:118
static char * buf
Definition: pg_test_fsync.c:68
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:189
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1670
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define TWOPHASE_DIR
Definition: twophase.c:115
TransactionId xid
Definition: twophase.c:166
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1382
int i
XLogRecPtr prepare_end_lsn
Definition: twophase.c:165

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1077 of file twophase.c.

References Assert, StateFileChunk::data, PGXACT::delayChkpt, DoNotReplicateId, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xllist::head, InvalidRepOriginId, InvalidXLogRecPtr, StateFileChunk::len, TwoPhaseFileHeader::magic, MarkAsPrepared(), MaxAllocSize, MyPgXact, StateFileChunk::next, xllist::num_chunks, TwoPhaseFileHeader::origin_lsn, TwoPhaseFileHeader::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, TwoPhaseFileHeader::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().

1078 {
1079  TwoPhaseFileHeader *hdr;
1080  StateFileChunk *record;
1081  bool replorigin;
1082 
1083  /* Add the end sentinel to the list of 2PC records */
1085  NULL, 0);
1086 
1087  /* Go back and fill in total_len in the file header record */
1088  hdr = (TwoPhaseFileHeader *) records.head->data;
1089  Assert(hdr->magic == TWOPHASE_MAGIC);
1090  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1091 
1092  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1094 
1095  if (replorigin)
1096  {
1100  }
1101  else
1102  {
1104  hdr->origin_timestamp = 0;
1105  }
1106 
1107  /*
1108  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1109  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1110  * where we write data to file and then re-read at commit time.
1111  */
1112  if (hdr->total_len > MaxAllocSize)
1113  ereport(ERROR,
1114  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1115  errmsg("two-phase state file maximum length exceeded")));
1116 
1117  /*
1118  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1119  * cover us, so no need to calculate a separate CRC.
1120  *
1121  * We have to set delayChkpt here, too; otherwise a checkpoint starting
1122  * immediately after the WAL record is inserted could complete without
1123  * fsync'ing our state file. (This is essentially the same kind of race
1124  * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1125  * uses delayChkpt for; see notes there.)
1126  *
1127  * We save the PREPARE record's location in the gxact for later use by
1128  * CheckPointTwoPhase.
1129  */
1131 
1133 
1134  MyPgXact->delayChkpt = true;
1135 
1136  XLogBeginInsert();
1137  for (record = records.head; record != NULL; record = record->next)
1138  XLogRegisterData(record->data, record->len);
1139 
1141 
1142  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1143 
1144  if (replorigin)
1145  {
1146  /* Move LSNs forward for this replication origin */
1148  gxact->prepare_end_lsn);
1149  }
1150 
1151  XLogFlush(gxact->prepare_end_lsn);
1152 
1153  /* If we crash now, we have prepared: WAL replay will fix things */
1154 
1155  /* Store record's start location to read that later on Commit */
1157 
1158  /*
1159  * Mark the prepared transaction as valid. As soon as xact.c marks
1160  * MyPgXact as not running our XID (which it will do immediately after
1161  * this function returns), others can commit/rollback the xact.
1162  *
1163  * NB: a side effect of this is to make a dummy ProcArray entry for the
1164  * prepared XID. This must happen before we clear the XID from MyPgXact,
1165  * else there is a window where the XID is not running according to
1166  * TransactionIdIsInProgress, and onlookers would be entitled to assume
1167  * the xact crashed. Instead we have a window where the same XID appears
1168  * twice in ProcArray, which is OK.
1169  */
1170  MarkAsPrepared(gxact, false);
1171 
1172  /*
1173  * Now we can mark ourselves as out of the commit critical section: a
1174  * checkpoint starting after this will certainly see the gxact as a
1175  * candidate for fsyncing.
1176  */
1177  MyPgXact->delayChkpt = false;
1178 
1179  /*
1180  * Remember that we have this GlobalTransaction entry locked for us. If
1181  * we crash after this point, it's too late to abort, but we must unlock
1182  * it so that the prepared transaction can be committed or rolled back.
1183  */
1184  MyLockedGxact = gxact;
1185 
1186  END_CRIT_SECTION();
1187 
1188  /*
1189  * Wait for synchronous replication, if required.
1190  *
1191  * Note that at this stage we have marked the prepare, but still show as
1192  * running in the procarray (twice!) and continue to hold locks.
1193  */
1194  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1195 
1196  records.tail = records.head = NULL;
1197  records.num_chunks = 0;
1198 }
#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:960
uint32 pg_crc32c
Definition: pg_crc32c.h:38
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:351
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:570
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:228
uint32 num_chunks
Definition: twophase.c:961
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2798
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1204
PGXACT * MyPgXact
Definition: proc.c:69
XLogRecPtr prepare_start_lsn
Definition: twophase.c:164
char * data
Definition: twophase.c:952
#define ERROR
Definition: elog.h:43
TimestampTz origin_timestamp
Definition: twophase.c:929
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:157
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:158
uint32 len
Definition: twophase.c:953
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:963
#define MaxAllocSize
Definition: memutils.h:40
struct StateFileChunk * next
Definition: twophase.c:954
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:912
StateFileChunk * head
Definition: twophase.c:959
#define Assert(condition)
Definition: c.h:732
RepOriginId replorigin_session_origin
Definition: origin.c:156
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:1174
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:537
#define InvalidRepOriginId
Definition: origin.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:784
static GlobalTransaction MyLockedGxact
Definition: twophase.c:200
XLogRecPtr origin_lsn
Definition: twophase.c:928
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr prepare_end_lsn
Definition: twophase.c:165

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1454 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Assert, AtEOXact_PgStat(), buf, DropRelationFiles(), GetUserId(), TwoPhaseFileHeader::gidlen, HOLD_INTERRUPTS, TwoPhaseFileHeader::initfileinval, LockGXact(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, TwoPhaseFileHeader::nabortrels, TwoPhaseFileHeader::ncommitrels, TwoPhaseFileHeader::ninvalmsgs, TwoPhaseFileHeader::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, TwoPhaseFileHeader::xid, and XlogReadTwoPhaseData().

Referenced by standard_ProcessUtility().

1455 {
1456  GlobalTransaction gxact;
1457  PGPROC *proc;
1458  PGXACT *pgxact;
1459  TransactionId xid;
1460  char *buf;
1461  char *bufptr;
1462  TwoPhaseFileHeader *hdr;
1463  TransactionId latestXid;
1464  TransactionId *children;
1465  RelFileNode *commitrels;
1466  RelFileNode *abortrels;
1467  RelFileNode *delrels;
1468  int ndelrels;
1469  SharedInvalidationMessage *invalmsgs;
1470 
1471  /*
1472  * Validate the GID, and lock the GXACT to ensure that two backends do not
1473  * try to commit the same GID at once.
1474  */
1475  gxact = LockGXact(gid, GetUserId());
1476  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1477  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1478  xid = pgxact->xid;
1479 
1480  /*
1481  * Read and validate 2PC state data. State data will typically be stored
1482  * in WAL files if the LSN is after the last checkpoint record, or moved
1483  * to disk if for some reason they have lived for a long time.
1484  */
1485  if (gxact->ondisk)
1486  buf = ReadTwoPhaseFile(xid, false);
1487  else
1488  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1489 
1490 
1491  /*
1492  * Disassemble the header area
1493  */
1494  hdr = (TwoPhaseFileHeader *) buf;
1495  Assert(TransactionIdEquals(hdr->xid, xid));
1496  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1497  bufptr += MAXALIGN(hdr->gidlen);
1498  children = (TransactionId *) bufptr;
1499  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1500  commitrels = (RelFileNode *) bufptr;
1501  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1502  abortrels = (RelFileNode *) bufptr;
1503  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1504  invalmsgs = (SharedInvalidationMessage *) bufptr;
1505  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1506 
1507  /* compute latestXid among all children */
1508  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1509 
1510  /* Prevent cancel/die interrupt while cleaning up */
1511  HOLD_INTERRUPTS();
1512 
1513  /*
1514  * The order of operations here is critical: make the XLOG entry for
1515  * commit or abort, then mark the transaction committed or aborted in
1516  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1517  * TransactionIdIsInProgress will stop saying the prepared xact is in
1518  * progress), then run the post-commit or post-abort callbacks. The
1519  * callbacks will release the locks the transaction held.
1520  */
1521  if (isCommit)
1523  hdr->nsubxacts, children,
1524  hdr->ncommitrels, commitrels,
1525  hdr->ninvalmsgs, invalmsgs,
1526  hdr->initfileinval, gid);
1527  else
1529  hdr->nsubxacts, children,
1530  hdr->nabortrels, abortrels,
1531  gid);
1532 
1533  ProcArrayRemove(proc, latestXid);
1534 
1535  /*
1536  * In case we fail while running the callbacks, mark the gxact invalid so
1537  * no one else will try to commit/rollback, and so it will be recycled if
1538  * we fail after this point. It is still locked by our backend so it
1539  * won't go away yet.
1540  *
1541  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1542  */
1543  gxact->valid = false;
1544 
1545  /*
1546  * We have to remove any files that were supposed to be dropped. For
1547  * consistency with the regular xact.c code paths, must do this before
1548  * releasing locks, so do it before running the callbacks.
1549  *
1550  * NB: this code knows that we couldn't be dropping any temp rels ...
1551  */
1552  if (isCommit)
1553  {
1554  delrels = commitrels;
1555  ndelrels = hdr->ncommitrels;
1556  }
1557  else
1558  {
1559  delrels = abortrels;
1560  ndelrels = hdr->nabortrels;
1561  }
1562 
1563  /* Make sure files supposed to be dropped are dropped */
1564  DropRelationFiles(delrels, ndelrels, false);
1565 
1566  /*
1567  * Handle cache invalidation messages.
1568  *
1569  * Relcache init file invalidation requires processing both before and
1570  * after we send the SI messages. See AtEOXact_Inval()
1571  */
1572  if (hdr->initfileinval)
1574  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1575  if (hdr->initfileinval)
1577 
1578  /*
1579  * Acquire the two-phase lock. We want to work on the two-phase callbacks
1580  * while holding it to avoid potential conflicts with other transactions
1581  * attempting to use the same GID, so the lock is released once the shared
1582  * memory state is cleared.
1583  */
1584  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1585 
1586  /* And now do the callbacks */
1587  if (isCommit)
1589  else
1591 
1592  PredicateLockTwoPhaseFinish(xid, isCommit);
1593 
1594  /* Clear shared memory state */
1595  RemoveGXact(gxact);
1596 
1597  /*
1598  * Release the lock as all callbacks are called and shared memory cleanup
1599  * is done.
1600  */
1601  LWLockRelease(TwoPhaseStateLock);
1602 
1603  /* Count the prepared xact as committed or aborted */
1604  AtEOXact_PgStat(isCommit, false);
1605 
1606  /*
1607  * And now we can clean up any files we may have left.
1608  */
1609  if (gxact->ondisk)
1610  RemoveTwoPhaseFile(xid, true);
1611 
1612  MyLockedGxact = NULL;
1613 
1615 
1616  pfree(buf);
1617 }
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, const char *gid)
Definition: twophase.c:2331
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:507
Definition: proc.h:222
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:1623
const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:33
PROC_HDR * ProcGlobal
Definition: proc.c:81
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1227
TransactionId xid
Definition: twophase.c:918
XLogRecPtr prepare_start_lsn
Definition: twophase.c:164
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:559
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:333
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:635
void DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
Definition: md.c:1001
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat.c:2094
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:5020
static char * buf
Definition: pg_test_fsync.c:68
const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:42
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:5964
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1651
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:5939
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define MAXALIGN(LEN)
Definition: c.h:685
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1382
static GlobalTransaction MyLockedGxact
Definition: twophase.c:200
#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:2237

◆ GetPreparedTransactionList()

static int GetPreparedTransactionList ( GlobalTransaction gxacts)
static

Definition at line 673 of file twophase.c.

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

Referenced by pg_prepared_xact().

674 {
675  GlobalTransaction array;
676  int num;
677  int i;
678 
679  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
680 
681  if (TwoPhaseState->numPrepXacts == 0)
682  {
683  LWLockRelease(TwoPhaseStateLock);
684 
685  *gxacts = NULL;
686  return 0;
687  }
688 
690  array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
691  *gxacts = array;
692  for (i = 0; i < num; i++)
693  memcpy(array + i, TwoPhaseState->prepXacts[i],
694  sizeof(GlobalTransactionData));
695 
696  LWLockRelease(TwoPhaseStateLock);
697 
698  return num;
699 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:26
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:189
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 510 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().

512 {
513  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
514  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
515 
516  /* We need no extra lock since the GXACT isn't valid yet */
517  if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
518  {
519  pgxact->overflowed = true;
520  nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
521  }
522  if (nsubxacts > 0)
523  {
524  memcpy(proc->subxids.xids, children,
525  nsubxacts * sizeof(TransactionId));
526  pgxact->nxids = nsubxacts;
527  }
528 }
uint32 TransactionId
Definition: c.h:507
Definition: proc.h:222
PGXACT * allPgXact
Definition: proc.h:249
PROC_HDR * ProcGlobal
Definition: proc.c:81
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 559 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().

560 {
561  int i;
562 
563  /* on first call, register the exit hook */
565  {
567  twophaseExitRegistered = true;
568  }
569 
570  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
571 
572  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
573  {
575  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
576 
577  /* Ignore not-yet-valid GIDs */
578  if (!gxact->valid)
579  continue;
580  if (strcmp(gxact->gid, gid) != 0)
581  continue;
582 
583  /* Found it, but has someone else got it locked? */
584  if (gxact->locking_backend != InvalidBackendId)
585  ereport(ERROR,
586  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
587  errmsg("prepared transaction with identifier \"%s\" is busy",
588  gid)));
589 
590  if (user != gxact->owner && !superuser_arg(user))
591  ereport(ERROR,
592  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
593  errmsg("permission denied to finish prepared transaction"),
594  errhint("Must be superuser or the user that prepared the transaction.")));
595 
596  /*
597  * Note: it probably would be possible to allow committing from
598  * another database; but at the moment NOTIFY is known not to work and
599  * there may be some other issues as well. Hence disallow until
600  * someone gets motivated to make it work.
601  */
602  if (MyDatabaseId != proc->databaseId)
603  ereport(ERROR,
604  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
605  errmsg("prepared transaction belongs to another database"),
606  errhint("Connect to the database where the transaction was prepared to finish it.")));
607 
608  /* OK for me to lock it */
609  gxact->locking_backend = MyBackendId;
610  MyLockedGxact = gxact;
611 
612  LWLockRelease(TwoPhaseStateLock);
613 
614  return gxact;
615  }
616 
617  LWLockRelease(TwoPhaseStateLock);
618 
619  ereport(ERROR,
620  (errcode(ERRCODE_UNDEFINED_OBJECT),
621  errmsg("prepared transaction with identifier \"%s\" does not exist",
622  gid)));
623 
624  /* NOTREACHED */
625  return NULL;
626 }
int errhint(const char *fmt,...)
Definition: elog.c:974
BackendId MyBackendId
Definition: globals.c:81
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
int errcode(int sqlerrcode)
Definition: elog.c:570
PROC_HDR * ProcGlobal
Definition: proc.c:81
static bool twophaseExitRegistered
Definition: twophase.c:202
char gid[GIDSIZE]
Definition: twophase.c:173
BackendId locking_backend
Definition: twophase.c:169
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:189
bool superuser_arg(Oid roleid)
Definition: superuser.c:57
#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:95
int errmsg(const char *fmt,...)
Definition: elog.c:784
static GlobalTransaction MyLockedGxact
Definition: twophase.c:200
int i
PGPROC * allProcs
Definition: proc.h:247
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:308
Definition: proc.h:95

◆ MarkAsPrepared()

static void MarkAsPrepared ( GlobalTransaction  gxact,
bool  lock_held 
)
static

Definition at line 537 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().

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

◆ MarkAsPreparing()

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

Definition at line 373 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().

375 {
376  GlobalTransaction gxact;
377  int i;
378 
379  if (strlen(gid) >= GIDSIZE)
380  ereport(ERROR,
381  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
382  errmsg("transaction identifier \"%s\" is too long",
383  gid)));
384 
385  /* fail immediately if feature is disabled */
386  if (max_prepared_xacts == 0)
387  ereport(ERROR,
388  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
389  errmsg("prepared transactions are disabled"),
390  errhint("Set max_prepared_transactions to a nonzero value.")));
391 
392  /* on first call, register the exit hook */
394  {
396  twophaseExitRegistered = true;
397  }
398 
399  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
400 
401  /* Check for conflicting GID */
402  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
403  {
404  gxact = TwoPhaseState->prepXacts[i];
405  if (strcmp(gxact->gid, gid) == 0)
406  {
407  ereport(ERROR,
409  errmsg("transaction identifier \"%s\" is already in use",
410  gid)));
411  }
412  }
413 
414  /* Get a free gxact from the freelist */
415  if (TwoPhaseState->freeGXacts == NULL)
416  ereport(ERROR,
417  (errcode(ERRCODE_OUT_OF_MEMORY),
418  errmsg("maximum number of prepared transactions reached"),
419  errhint("Increase max_prepared_transactions (currently %d).",
421  gxact = TwoPhaseState->freeGXacts;
422  TwoPhaseState->freeGXacts = gxact->next;
423 
424  MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
425 
426  gxact->ondisk = false;
427 
428  /* And insert it into the active array */
431 
432  LWLockRelease(TwoPhaseStateLock);
433 
434  return gxact;
435 }
int errhint(const char *fmt,...)
Definition: elog.c:974
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
GlobalTransaction freeGXacts
Definition: twophase.c:183
int errcode(int sqlerrcode)
Definition: elog.c:570
static bool twophaseExitRegistered
Definition: twophase.c:202
GlobalTransaction next
Definition: twophase.c:152
char gid[GIDSIZE]
Definition: twophase.c:173
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:447
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:118
#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:189
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:308
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:33

◆ MarkAsPreparingGuts()

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

Definition at line 447 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().

449 {
450  PGPROC *proc;
451  PGXACT *pgxact;
452  int i;
453 
454  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
455 
456  Assert(gxact != NULL);
457  proc = &ProcGlobal->allProcs[gxact->pgprocno];
458  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
459 
460  /* Initialize the PGPROC entry */
461  MemSet(proc, 0, sizeof(PGPROC));
462  proc->pgprocno = gxact->pgprocno;
463  SHMQueueElemInit(&(proc->links));
464  proc->waitStatus = STATUS_OK;
465  /* We set up the gxact's VXID as InvalidBackendId/XID */
466  proc->lxid = (LocalTransactionId) xid;
467  pgxact->xid = xid;
468  pgxact->xmin = InvalidTransactionId;
469  pgxact->delayChkpt = false;
470  pgxact->vacuumFlags = 0;
471  proc->pid = 0;
472  proc->backendId = InvalidBackendId;
473  proc->databaseId = databaseid;
474  proc->roleId = owner;
475  proc->tempNamespaceId = InvalidOid;
476  proc->isBackgroundWorker = false;
477  proc->lwWaiting = false;
478  proc->lwWaitMode = 0;
479  proc->waitLock = NULL;
480  proc->waitProcLock = NULL;
481  for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
482  SHMQueueInit(&(proc->myProcLocks[i]));
483  /* subxid data must be filled later by GXactLoadSubxactData */
484  pgxact->overflowed = false;
485  pgxact->nxids = 0;
486 
487  gxact->prepared_at = prepared_at;
488  gxact->xid = xid;
489  gxact->owner = owner;
490  gxact->locking_backend = MyBackendId;
491  gxact->valid = false;
492  gxact->inredo = false;
493  strcpy(gxact->gid, gid);
494 
495  /*
496  * Remember that we have this GlobalTransaction entry locked for us. If we
497  * abort after this, we must release it.
498  */
499  MyLockedGxact = gxact;
500 }
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:81
#define MemSet(start, val, len)
Definition: c.h:955
uint8 lwWaitMode
Definition: proc.h:131
char gid[GIDSIZE]
Definition: twophase.c:173
uint8 vacuumFlags
Definition: proc.h:233
BackendId locking_backend
Definition: twophase.c:169
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:509
LOCK * waitLock
Definition: proc.h:139
#define STATUS_OK
Definition: c.h:1089
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:732
TransactionId xid
Definition: twophase.c:166
TimestampTz prepared_at
Definition: twophase.c:155
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:200
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

◆ ParsePrepareRecord()

void ParsePrepareRecord ( uint8  info,
char *  xlrec,
xl_xact_parsed_prepare parsed 
)

Definition at line 1339 of file twophase.c.

References xl_xact_parsed_commit::abortnodes, TwoPhaseFileHeader::database, xl_xact_parsed_commit::dbId, TwoPhaseFileHeader::gidlen, MAXALIGN, xl_xact_parsed_commit::msgs, xl_xact_parsed_commit::nabortrels, TwoPhaseFileHeader::nabortrels, TwoPhaseFileHeader::ncommitrels, TwoPhaseFileHeader::ninvalmsgs, xl_xact_parsed_commit::nmsgs, xl_xact_parsed_commit::nrels, xl_xact_parsed_commit::nsubxacts, TwoPhaseFileHeader::nsubxacts, xl_xact_parsed_commit::origin_lsn, TwoPhaseFileHeader::origin_lsn, xl_xact_parsed_commit::origin_timestamp, TwoPhaseFileHeader::origin_timestamp, xl_xact_parsed_commit::subxacts, xl_xact_parsed_commit::twophase_gid, xl_xact_parsed_commit::twophase_xid, TwoPhaseFileHeader::xid, and xl_xact_parsed_commit::xnodes.

1340 {
1341  TwoPhaseFileHeader *hdr;
1342  char *bufptr;
1343 
1344  hdr = (TwoPhaseFileHeader *) xlrec;
1345  bufptr = xlrec + MAXALIGN(sizeof(TwoPhaseFileHeader));
1346 
1347  parsed->origin_lsn = hdr->origin_lsn;
1348  parsed->origin_timestamp = hdr->origin_timestamp;
1349  parsed->twophase_xid = hdr->xid;
1350  parsed->dbId = hdr->database;
1351  parsed->nsubxacts = hdr->nsubxacts;
1352  parsed->nrels = hdr->ncommitrels;
1353  parsed->nabortrels = hdr->nabortrels;
1354  parsed->nmsgs = hdr->ninvalmsgs;
1355 
1356  strncpy(parsed->twophase_gid, bufptr, hdr->gidlen);
1357  bufptr += MAXALIGN(hdr->gidlen);
1358 
1359  parsed->subxacts = (TransactionId *) bufptr;
1360  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1361 
1362  parsed->xnodes = (RelFileNode *) bufptr;
1363  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1364 
1365  parsed->abortnodes = (RelFileNode *) bufptr;
1366  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1367 
1368  parsed->msgs = (SharedInvalidationMessage *) bufptr;
1369  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1370 }
RelFileNode * xnodes
Definition: xact.h:312
uint32 TransactionId
Definition: c.h:507
TimestampTz origin_timestamp
Definition: xact.h:323
TransactionId twophase_xid
Definition: xact.h:317
TransactionId * subxacts
Definition: xact.h:309
SharedInvalidationMessage * msgs
Definition: xact.h:315
XLogRecPtr origin_lsn
Definition: xact.h:322
TransactionId xid
Definition: twophase.c:918
TimestampTz origin_timestamp
Definition: twophase.c:929
RelFileNode * abortnodes
Definition: xact.h:320
#define MAXALIGN(LEN)
Definition: c.h:685
XLogRecPtr origin_lsn
Definition: twophase.c:928
char twophase_gid[GIDSIZE]
Definition: xact.h:318

◆ pg_prepared_xact()

Datum pg_prepared_xact ( PG_FUNCTION_ARGS  )

Definition at line 718 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.

719 {
720  FuncCallContext *funcctx;
722 
723  if (SRF_IS_FIRSTCALL())
724  {
725  TupleDesc tupdesc;
726  MemoryContext oldcontext;
727 
728  /* create a function context for cross-call persistence */
729  funcctx = SRF_FIRSTCALL_INIT();
730 
731  /*
732  * Switch to memory context appropriate for multiple function calls
733  */
734  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
735 
736  /* build tupdesc for result tuples */
737  /* this had better match pg_prepared_xacts view in system_views.sql */
738  tupdesc = CreateTemplateTupleDesc(5);
739  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
740  XIDOID, -1, 0);
741  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
742  TEXTOID, -1, 0);
743  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
744  TIMESTAMPTZOID, -1, 0);
745  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
746  OIDOID, -1, 0);
747  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
748  OIDOID, -1, 0);
749 
750  funcctx->tuple_desc = BlessTupleDesc(tupdesc);
751 
752  /*
753  * Collect all the 2PC status information that we will format and send
754  * out as a result set.
755  */
756  status = (Working_State *) palloc(sizeof(Working_State));
757  funcctx->user_fctx = (void *) status;
758 
759  status->ngxacts = GetPreparedTransactionList(&status->array);
760  status->currIdx = 0;
761 
762  MemoryContextSwitchTo(oldcontext);
763  }
764 
765  funcctx = SRF_PERCALL_SETUP();
766  status = (Working_State *) funcctx->user_fctx;
767 
768  while (status->array != NULL && status->currIdx < status->ngxacts)
769  {
770  GlobalTransaction gxact = &status->array[status->currIdx++];
771  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
772  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
773  Datum values[5];
774  bool nulls[5];
775  HeapTuple tuple;
776  Datum result;
777 
778  if (!gxact->valid)
779  continue;
780 
781  /*
782  * Form tuple with appropriate data.
783  */
784  MemSet(values, 0, sizeof(values));
785  MemSet(nulls, 0, sizeof(nulls));
786 
787  values[0] = TransactionIdGetDatum(pgxact->xid);
788  values[1] = CStringGetTextDatum(gxact->gid);
789  values[2] = TimestampTzGetDatum(gxact->prepared_at);
790  values[3] = ObjectIdGetDatum(gxact->owner);
791  values[4] = ObjectIdGetDatum(proc->databaseId);
792 
793  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
794  result = HeapTupleGetDatum(tuple);
795  SRF_RETURN_NEXT(funcctx, result);
796  }
797 
798  SRF_RETURN_DONE(funcctx);
799 }
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:283
TransactionId xid
Definition: proc.h:224
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition: twophase.c:673
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PROC_HDR * ProcGlobal
Definition: proc.c:81
#define MemSet(start, val, len)
Definition: c.h:955
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:287
char gid[GIDSIZE]
Definition: twophase.c:173
TupleDesc tuple_desc
Definition: funcapi.h:113
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:289
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2048
Oid databaseId
Definition: proc.h:114
GlobalTransaction array
Definition: twophase.c:705
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:102
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
static Datum values[MAXATTR]
Definition: bootstrap.c:167
TimestampTz prepared_at
Definition: twophase.c:155
void * user_fctx
Definition: funcapi.h:83
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:227
Definition: proc.h:95
int16 AttrNumber
Definition: attnum.h:21
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:307
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:285

◆ PostPrepare_Twophase()

void PostPrepare_Twophase ( void  )

Definition at line 358 of file twophase.c.

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

359 {
360  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
362  LWLockRelease(TwoPhaseStateLock);
363 
364  MyLockedGxact = NULL;
365 }
BackendId locking_backend
Definition: twophase.c:169
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:200

◆ PrepareRedoAdd()

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

Definition at line 2390 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, TwoPhaseFileHeader::origin_lsn, GlobalTransactionData::owner, TwoPhaseFileHeader::owner, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, GlobalTransactionData::prepared_at, TwoPhaseFileHeader::prepared_at, TwoPhaseStateData::prepXacts, RecoveryInProgress(), replorigin_advance(), GlobalTransactionData::valid, GlobalTransactionData::xid, TwoPhaseFileHeader::xid, and XLogRecPtrIsInvalid.

Referenced by restoreTwoPhaseData(), and xact_redo().

2392 {
2394  char *bufptr;
2395  const char *gid;
2396  GlobalTransaction gxact;
2397 
2398  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2400 
2401  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2402  gid = (const char *) bufptr;
2403 
2404  /*
2405  * Reserve the GID for the given transaction in the redo code path.
2406  *
2407  * This creates a gxact struct and puts it into the active array.
2408  *
2409  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2410  * shared memory. Hence, we only fill up the bare minimum contents here.
2411  * The gxact also gets marked with gxact->inredo set to true to indicate
2412  * that it got added in the redo phase
2413  */
2414 
2415  /* Get a free gxact from the freelist */
2416  if (TwoPhaseState->freeGXacts == NULL)
2417  ereport(ERROR,
2418  (errcode(ERRCODE_OUT_OF_MEMORY),
2419  errmsg("maximum number of prepared transactions reached"),
2420  errhint("Increase max_prepared_transactions (currently %d).",
2421  max_prepared_xacts)));
2422  gxact = TwoPhaseState->freeGXacts;
2423  TwoPhaseState->freeGXacts = gxact->next;
2424 
2425  gxact->prepared_at = hdr->prepared_at;
2426  gxact->prepare_start_lsn = start_lsn;
2427  gxact->prepare_end_lsn = end_lsn;
2428  gxact->xid = hdr->xid;
2429  gxact->owner = hdr->owner;
2431  gxact->valid = false;
2432  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2433  gxact->inredo = true; /* yes, added in redo */
2434  strcpy(gxact->gid, gid);
2435 
2436  /* And insert it into the active array */
2439 
2440  if (origin_id != InvalidRepOriginId)
2441  {
2442  /* recover apply progress */
2443  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2444  false /* backward */ , false /* WAL */ );
2445  }
2446 
2447  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2448 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
int errhint(const char *fmt,...)
Definition: elog.c:974
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
GlobalTransaction freeGXacts
Definition: twophase.c:183
int errcode(int sqlerrcode)
Definition: elog.c:570
TransactionId xid
Definition: twophase.c:918
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:861
GlobalTransaction next
Definition: twophase.c:152
bool RecoveryInProgress(void)
Definition: xlog.c:7917
char gid[GIDSIZE]
Definition: twophase.c:173
BackendId locking_backend
Definition: twophase.c:169
XLogRecPtr prepare_start_lsn
Definition: twophase.c:164
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:118
#define DEBUG2
Definition: elog.h:24
static char * buf
Definition: pg_test_fsync.c:68
#define ereport(elevel, rest)
Definition: elog.h:141
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:189
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define InvalidBackendId
Definition: backendid.h:23
#define Assert(condition)
Definition: c.h:732
#define MAXALIGN(LEN)
Definition: c.h:685
#define InvalidRepOriginId
Definition: origin.h:33
TransactionId xid
Definition: twophase.c:166
TimestampTz prepared_at
Definition: twophase.c:155
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
XLogRecPtr origin_lsn
Definition: twophase.c:928
TimestampTz prepared_at
Definition: twophase.c:920
XLogRecPtr prepare_end_lsn
Definition: twophase.c:165

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2460 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().

2461 {
2462  GlobalTransaction gxact = NULL;
2463  int i;
2464  bool found = false;
2465 
2466  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2468 
2469  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2470  {
2471  gxact = TwoPhaseState->prepXacts[i];
2472 
2473  if (gxact->xid == xid)
2474  {
2475  Assert(gxact->inredo);
2476  found = true;
2477  break;
2478  }
2479  }
2480 
2481  /*
2482  * Just leave if there is nothing, this is expected during WAL replay.
2483  */
2484  if (!found)
2485  return;
2486 
2487  /*
2488  * And now we can clean up any files we may have left.
2489  */
2490  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2491  if (gxact->ondisk)
2492  RemoveTwoPhaseFile(xid, giveWarning);
2493  RemoveGXact(gxact);
2494 
2495  return;
2496 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
bool RecoveryInProgress(void)
Definition: xlog.c:7917
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:635
#define DEBUG2
Definition: elog.h:24
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:189
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1651
#define Assert(condition)
Definition: c.h:732
TransactionId xid
Definition: twophase.c:166
#define elog(elevel,...)
Definition: elog.h:226
int i

◆ PrescanPreparedTransactions()

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

Definition at line 1894 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().

1895 {
1897  TransactionId origNextXid = XidFromFullTransactionId(nextFullXid);
1898  TransactionId result = origNextXid;
1899  TransactionId *xids = NULL;
1900  int nxids = 0;
1901  int allocsize = 0;
1902  int i;
1903 
1904  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1905  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1906  {
1907  TransactionId xid;
1908  char *buf;
1910 
1911  Assert(gxact->inredo);
1912 
1913  xid = gxact->xid;
1914 
1915  buf = ProcessTwoPhaseBuffer(xid,
1916  gxact->prepare_start_lsn,
1917  gxact->ondisk, false, true);
1918 
1919  if (buf == NULL)
1920  continue;
1921 
1922  /*
1923  * OK, we think this file is valid. Incorporate xid into the
1924  * running-minimum result.
1925  */
1926  if (TransactionIdPrecedes(xid, result))
1927  result = xid;
1928 
1929  if (xids_p)
1930  {
1931  if (nxids == allocsize)
1932  {
1933  if (nxids == 0)
1934  {
1935  allocsize = 10;
1936  xids = palloc(allocsize * sizeof(TransactionId));
1937  }
1938  else
1939  {
1940  allocsize = allocsize * 2;
1941  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1942  }
1943  }
1944  xids[nxids++] = xid;
1945  }
1946 
1947  pfree(buf);
1948  }
1949  LWLockRelease(TwoPhaseStateLock);
1950 
1951  if (xids_p)
1952  {
1953  *xids_p = xids;
1954  *nxids_p = nxids;
1955  }
1956 
1957  return result;
1958 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
uint32 TransactionId
Definition: c.h:507
FullTransactionId nextFullXid
Definition: transam.h:164
XLogRecPtr prepare_start_lsn
Definition: twophase.c:164
#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:68
VariableCache ShmemVariableCache
Definition: varsup.c:34
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:189
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:2117
#define Assert(condition)
Definition: c.h:732
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:166
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 1623 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().

1625 {
1626  for (;;)
1627  {
1628  TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1629 
1630  Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1631  if (record->rmid == TWOPHASE_RM_END_ID)
1632  break;
1633 
1634  bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1635 
1636  if (callbacks[record->rmid] != NULL)
1637  callbacks[record->rmid] (xid, record->info,
1638  (void *) bufptr, record->len);
1639 
1640  bufptr += MAXALIGN(record->len);
1641  }
1642 }
#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:732
#define MAXALIGN(LEN)
Definition: c.h:685
TwoPhaseRmgrId rmid
Definition: twophase.c:941

◆ ProcessTwoPhaseBuffer()

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

Definition at line 2117 of file twophase.c.

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

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

2121 {
2123  TransactionId origNextXid = XidFromFullTransactionId(nextFullXid);
2124  TransactionId *subxids;
2125  char *buf;
2126  TwoPhaseFileHeader *hdr;
2127  int i;
2128 
2129  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2130 
2131  if (!fromdisk)
2132  Assert(prepare_start_lsn != InvalidXLogRecPtr);
2133 
2134  /* Already processed? */
2136  {
2137  if (fromdisk)
2138  {
2139  ereport(WARNING,
2140  (errmsg("removing stale two-phase state file for transaction %u",
2141  xid)));
2142  RemoveTwoPhaseFile(xid, true);
2143  }
2144  else
2145  {
2146  ereport(WARNING,
2147  (errmsg("removing stale two-phase state from memory for transaction %u",
2148  xid)));
2149  PrepareRedoRemove(xid, true);
2150  }
2151  return NULL;
2152  }
2153 
2154  /* Reject XID if too new */
2155  if (TransactionIdFollowsOrEquals(xid, origNextXid))
2156  {
2157  if (fromdisk)
2158  {
2159  ereport(WARNING,
2160  (errmsg("removing future two-phase state file for transaction %u",
2161  xid)));
2162  RemoveTwoPhaseFile(xid, true);
2163  }
2164  else
2165  {
2166  ereport(WARNING,
2167  (errmsg("removing future two-phase state from memory for transaction %u",
2168  xid)));
2169  PrepareRedoRemove(xid, true);
2170  }
2171  return NULL;
2172  }
2173 
2174  if (fromdisk)
2175  {
2176  /* Read and validate file */
2177  buf = ReadTwoPhaseFile(xid, false);
2178  }
2179  else
2180  {
2181  /* Read xlog data */
2182  XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2183  }
2184 
2185  /* Deconstruct header */
2186  hdr = (TwoPhaseFileHeader *) buf;
2187  if (!TransactionIdEquals(hdr->xid, xid))
2188  {
2189  if (fromdisk)
2190  ereport(ERROR,
2192  errmsg("corrupted two-phase state file for transaction %u",
2193  xid)));
2194  else
2195  ereport(ERROR,
2197  errmsg("corrupted two-phase state in memory for transaction %u",
2198  xid)));
2199  }
2200 
2201  /*
2202  * Examine subtransaction XIDs ... they should all follow main XID, and
2203  * they may force us to advance nextFullXid.
2204  */
2205  subxids = (TransactionId *) (buf +
2206  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2207  MAXALIGN(hdr->gidlen));
2208  for (i = 0; i < hdr->nsubxacts; i++)
2209  {
2210  TransactionId subxid = subxids[i];
2211 
2212  Assert(TransactionIdFollows(subxid, xid));
2213 
2214  /* update nextFullXid if needed */
2215  if (setNextXid)
2217 
2218  if (setParent)
2219  SubTransSetParent(subxid, xid);
2220  }
2221 
2222  return buf;
2223 }
#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:2460
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:507
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:570
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1227
TransactionId xid
Definition: twophase.c:918
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:68
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:1651
#define Assert(condition)
Definition: c.h:732
#define MAXALIGN(LEN)
Definition: c.h:685
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1382
int errmsg(const char *fmt,...)
Definition: elog.c:784
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 1227 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, TwoPhaseFileHeader::magic, MAXALIGN, MaxAllocSize, MAXPGPATH, OpenTransientFile(), palloc(), PG_BINARY, pgstat_report_wait_end(), pgstat_report_wait_start(), read, stat, TwoPhaseFileHeader::total_len, TWOPHASE_MAGIC, TwoPhaseFilePath, and WAIT_EVENT_TWOPHASE_FILE_READ.

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

1228 {
1229  char path[MAXPGPATH];
1230  char *buf;
1231  TwoPhaseFileHeader *hdr;
1232  int fd;
1233  struct stat stat;
1234  uint32 crc_offset;
1235  pg_crc32c calc_crc,
1236  file_crc;
1237  int r;
1238 
1239  TwoPhaseFilePath(path, xid);
1240 
1241  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
1242  if (fd < 0)
1243  {
1244  if (missing_ok && errno == ENOENT)
1245  return NULL;
1246 
1247  ereport(ERROR,
1249  errmsg("could not open file \"%s\": %m", path)));
1250  }
1251 
1252  /*
1253  * Check file length. We can determine a lower bound pretty easily. We
1254  * set an upper bound to avoid palloc() failure on a corrupt file, though
1255  * we can't guarantee that we won't get an out of memory error anyway,
1256  * even on a valid file.
1257  */
1258  if (fstat(fd, &stat))
1259  ereport(ERROR,
1261  errmsg("could not stat file \"%s\": %m", path)));
1262 
1263  if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1264  MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1265  sizeof(pg_crc32c)) ||
1266  stat.st_size > MaxAllocSize)
1267  ereport(ERROR,
1269  errmsg_plural("incorrect size of file \"%s\": %zu byte",
1270  "incorrect size of file \"%s\": %zu bytes",
1271  (Size) stat.st_size, path,
1272  (Size) stat.st_size)));
1273 
1274  crc_offset = stat.st_size - sizeof(pg_crc32c);
1275  if (crc_offset != MAXALIGN(crc_offset))
1276  ereport(ERROR,
1278  errmsg("incorrect alignment of CRC offset for file \"%s\"",
1279  path)));
1280 
1281  /*
1282  * OK, slurp in the file.
1283  */
1284  buf = (char *) palloc(stat.st_size);
1285 
1287  r = read(fd, buf, stat.st_size);
1288  if (r != stat.st_size)
1289  {
1290  if (r < 0)
1291  ereport(ERROR,
1293  errmsg("could not read file \"%s\": %m", path)));
1294  else
1295  ereport(ERROR,
1296  (errmsg("could not read file \"%s\": read %d of %zu",
1297  path, r, (Size) stat.st_size)));
1298  }
1299 
1301 
1302  if (CloseTransientFile(fd) != 0)
1303  ereport(ERROR,
1305  errmsg("could not close file \"%s\": %m", path)));
1306 
1307  hdr = (TwoPhaseFileHeader *) buf;
1308  if (hdr->magic != TWOPHASE_MAGIC)
1309  ereport(ERROR,
1311  errmsg("invalid magic number stored in file \"%s\"",
1312  path)));
1313 
1314  if (hdr->total_len != stat.st_size)
1315  ereport(ERROR,
1317  errmsg("invalid size stored in file \"%s\"",
1318  path)));
1319 
1320  INIT_CRC32C(calc_crc);
1321  COMP_CRC32C(calc_crc, buf, crc_offset);
1322  FIN_CRC32C(calc_crc);
1323 
1324  file_crc = *((pg_crc32c *) (buf + crc_offset));
1325 
1326  if (!EQ_CRC32C(calc_crc, file_crc))
1327  ereport(ERROR,
1329  errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
1330  path)));
1331 
1332  return buf;
1333 }
#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:837
uint32 pg_crc32c
Definition: pg_crc32c.h:38
int errcode(int sqlerrcode)
Definition: elog.c:570
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1191
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:890
#define ERROR
Definition: elog.h:43
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2255
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:68
int errcode_for_file_access(void)
Definition: elog.c:593
unsigned int uint32
Definition: c.h:358
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1342
#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:2432
#define stat(a, b)
Definition: win32_port.h:255
#define TWOPHASE_MAGIC
Definition: twophase.c:912
size_t Size
Definition: c.h:466
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1318
#define MAXALIGN(LEN)
Definition: c.h:685
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:784
#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 2331 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().

2337 {
2338  XLogRecPtr recptr;
2339 
2340  /*
2341  * Catch the scenario where we aborted partway through
2342  * RecordTransactionCommitPrepared ...
2343  */
2344  if (TransactionIdDidCommit(xid))
2345  elog(PANIC, "cannot abort transaction %u, it was already committed",
2346  xid);
2347 
2349 
2350  /*
2351  * Emit the XLOG commit record. Note that we mark 2PC aborts as
2352  * potentially having AccessExclusiveLocks since we don't know whether or
2353  * not they do.
2354  */
2356  nchildren, children,
2357  nrels, rels,
2359  xid, gid);
2360 
2361  /* Always flush, since we're about to remove the 2PC state file */
2362  XLogFlush(recptr);
2363 
2364  /*
2365  * Mark the transaction aborted in clog. This is not absolutely necessary
2366  * but we may as well do it while we are here.
2367  */
2368  TransactionIdAbortTree(xid, nchildren, children);
2369 
2370  END_CRIT_SECTION();
2371 
2372  /*
2373  * Wait for synchronous replication, if required.
2374  *
2375  * Note that at this stage we have marked clog, but still show as running
2376  * in the procarray and continue to hold locks.
2377  */
2378  SyncRepWaitForLSN(recptr, false);
2379 }
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:5598
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:2798
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:103
int MyXactFlags
Definition: xact.c:119
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define elog(elevel,...)
Definition: elog.h:226

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

2246 {
2247  XLogRecPtr recptr;
2248  TimestampTz committs = GetCurrentTimestamp();
2249  bool replorigin;
2250 
2251  /*
2252  * Are we using the replication origins feature? Or, in other words, are
2253  * we replaying remote actions?
2254  */
2255  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2257 
2259 
2260  /* See notes in RecordTransactionCommit */
2261  MyPgXact->delayChkpt = true;
2262 
2263  /*
2264  * Emit the XLOG commit record. Note that we mark 2PC commits as
2265  * potentially having AccessExclusiveLocks since we don't know whether or
2266  * not they do.
2267  */
2268  recptr = XactLogCommitRecord(committs,
2269  nchildren, children, nrels, rels,
2270  ninvalmsgs, invalmsgs,
2271  initfileinval, false,
2273  xid, gid);
2274 
2275 
2276  if (replorigin)
2277  /* Move LSNs forward for this replication origin */
2279  XactLastRecEnd);
2280 
2281  /*
2282  * Record commit timestamp. The value comes from plain commit timestamp
2283  * if replorigin is not enabled, or replorigin already set a value for us
2284  * in replorigin_session_origin_timestamp otherwise.
2285  *
2286  * We don't need to WAL-log anything here, as the commit record written
2287  * above already contains the data.
2288  */
2289  if (!replorigin || replorigin_session_origin_timestamp == 0)
2291 
2292  TransactionTreeSetCommitTsData(xid, nchildren, children,
2294  replorigin_session_origin, false);
2295 
2296  /*
2297  * We don't currently try to sleep before flush here ... nor is there any
2298  * support for async commit of a prepared xact (the very idea is probably
2299  * a contradiction)
2300  */
2301 
2302  /* Flush XLOG to disk */
2303  XLogFlush(recptr);
2304 
2305  /* Mark the transaction committed in pg_xact */
2306  TransactionIdCommitTree(xid, nchildren, children);
2307 
2308  /* Checkpoint can proceed now */
2309  MyPgXact->delayChkpt = false;
2310 
2311  END_CRIT_SECTION();
2312 
2313  /*
2314  * Wait for synchronous replication, if required.
2315  *
2316  * Note that at this stage we have marked clog, but still show as running
2317  * in the procarray and continue to hold locks.
2318  */
2319  SyncRepWaitForLSN(recptr, true);
2320 }
#define DoNotReplicateId
Definition: origin.h:34
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
XLogRecPtr XactLastRecEnd
Definition: xlog.c:352
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:2798
PGXACT * MyPgXact
Definition: proc.c:69
#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:157
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:158
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:5443
int MyXactFlags
Definition: xact.c:119
uint64 XLogRecPtr
Definition: xlogdefs.h:21
RepOriginId replorigin_session_origin
Definition: origin.c:156
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1174
#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 2016 of file twophase.c.

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

Referenced by StartupXLOG().

2017 {
2018  int i;
2019 
2020  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2021  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2022  {
2023  TransactionId xid;
2024  char *buf;
2026  char *bufptr;
2027  TwoPhaseFileHeader *hdr;
2028  TransactionId *subxids;
2029  const char *gid;
2030 
2031  xid = gxact->xid;
2032 
2033  /*
2034  * Reconstruct subtrans state for the transaction --- needed because
2035  * pg_subtrans is not preserved over a restart. Note that we are
2036  * linking all the subtransactions directly to the top-level XID;
2037  * there may originally have been a more complex hierarchy, but
2038  * there's no need to restore that exactly. It's possible that
2039  * SubTransSetParent has been set before, if the prepared transaction
2040  * generated xid assignment records.
2041  */
2042  buf = ProcessTwoPhaseBuffer(xid,
2043  gxact->prepare_start_lsn,
2044  gxact->ondisk, true, false);
2045  if (buf == NULL)
2046  continue;
2047 
2048  ereport(LOG,
2049  (errmsg("recovering prepared transaction %u from shared memory", xid)));
2050 
2051  hdr = (TwoPhaseFileHeader *) buf;
2052  Assert(TransactionIdEquals(hdr->xid, xid));
2053  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2054  gid = (const char *) bufptr;
2055  bufptr += MAXALIGN(hdr->gidlen);
2056  subxids = (TransactionId *) bufptr;
2057  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
2058  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
2059  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
2060  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
2061 
2062  /*
2063  * Recreate its GXACT and dummy PGPROC. But, check whether it was
2064  * added in redo and already has a shmem entry for it.
2065  */
2066  MarkAsPreparingGuts(gxact, xid, gid,
2067  hdr->prepared_at,
2068  hdr->owner, hdr->database);
2069 
2070  /* recovered, so reset the flag for entries generated by redo */
2071  gxact->inredo = false;
2072 
2073  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
2074  MarkAsPrepared(gxact, true);
2075 
2076  LWLockRelease(TwoPhaseStateLock);
2077 
2078  /*
2079  * Recover other state (notably locks) using resource managers.
2080  */
2082 
2083  /*
2084  * Release locks held by the standby process after we process each
2085  * prepared transaction. As a result, we don't need too many
2086  * additional locks at any one time.
2087  */
2088  if (InHotStandby)
2089  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2090 
2091  /*
2092  * We're done with recovering this transaction. Clear MyLockedGxact,
2093  * like we do in PrepareTransaction() during normal operation.
2094  */
2096 
2097  pfree(buf);
2098 
2099  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2100  }
2101 
2102  LWLockRelease(TwoPhaseStateLock);
2103 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:507
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1623
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlog.h:74
TransactionId xid
Definition: twophase.c:918
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:164
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:447
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:510
static char * buf
Definition: pg_test_fsync.c:68
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:189
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2117
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define MAXALIGN(LEN)
Definition: c.h:685
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:537
TransactionId xid
Definition: twophase.c:166
int errmsg(const char *fmt,...)
Definition: elog.c:784
void PostPrepare_Twophase(void)
Definition: twophase.c:358
int i
TimestampTz prepared_at
Definition: twophase.c:920

◆ RecreateTwoPhaseFile()

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

Definition at line 1670 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().

1671 {
1672  char path[MAXPGPATH];
1673  pg_crc32c statefile_crc;
1674  int fd;
1675 
1676  /* Recompute CRC */
1677  INIT_CRC32C(statefile_crc);
1678  COMP_CRC32C(statefile_crc, content, len);
1679  FIN_CRC32C(statefile_crc);
1680 
1681  TwoPhaseFilePath(path, xid);
1682 
1683  fd = OpenTransientFile(path,
1684  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY);
1685  if (fd < 0)
1686  ereport(ERROR,
1688  errmsg("could not recreate file \"%s\": %m", path)));
1689 
1690  /* Write content and CRC */
1691  errno = 0;
1693  if (write(fd, content, len) != len)
1694  {
1695  /* if write didn't set errno, assume problem is no disk space */
1696  if (errno == 0)
1697  errno = ENOSPC;
1698  ereport(ERROR,
1700  errmsg("could not write file \"%s\": %m", path)));
1701  }
1702  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1703  {
1704  /* if write didn't set errno, assume problem is no disk space */
1705  if (errno == 0)
1706  errno = ENOSPC;
1707  ereport(ERROR,
1709  errmsg("could not write file \"%s\": %m", path)));
1710  }
1712 
1713  /*
1714  * We must fsync the file because the end-of-replay checkpoint will not do
1715  * so, there being no GXACT in shared memory yet to tell it to.
1716  */
1718  if (pg_fsync(fd) != 0)
1719  ereport(ERROR,
1721  errmsg("could not fsync file \"%s\": %m", path)));
1723 
1724  if (CloseTransientFile(fd) != 0)
1725  ereport(ERROR,
1727  errmsg("could not close file \"%s\": %m", path)));
1728 }
#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:1191
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:890
#define ERROR
Definition: elog.h:43
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2255
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:593
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1342
#define ereport(elevel, rest)
Definition: elog.h:141
int CloseTransientFile(int fd)
Definition: fd.c:2432
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1318
int errmsg(const char *fmt,...)
Definition: elog.c:784
int pg_fsync(int fd)
Definition: fd.c:331
#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 1204 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().

1206 {
1207  TwoPhaseRecordOnDisk record;
1208 
1209  record.rmid = rmid;
1210  record.info = info;
1211  record.len = len;
1212  save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1213  if (len > 0)
1214  save_state_data(data, len);
1215 }
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:976
TwoPhaseRmgrId rmid
Definition: twophase.c:941

◆ RemoveGXact()

static void RemoveGXact ( GlobalTransaction  gxact)
static

Definition at line 635 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().

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

◆ RemoveTwoPhaseFile()

static void RemoveTwoPhaseFile ( TransactionId  xid,
bool  giveWarning 
)
static

Definition at line 1651 of file twophase.c.

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

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

1652 {
1653  char path[MAXPGPATH];
1654 
1655  TwoPhaseFilePath(path, xid);
1656  if (unlink(path))
1657  if (errno != ENOENT || giveWarning)
1658  ereport(WARNING,
1660  errmsg("could not remove file \"%s\": %m", path)));
1661 }
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:890
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:593
#define ereport(elevel, rest)
Definition: elog.h:141
#define WARNING
Definition: elog.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1832 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().

1833 {
1834  DIR *cldir;
1835  struct dirent *clde;
1836 
1837  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1838  cldir = AllocateDir(TWOPHASE_DIR);
1839  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1840  {
1841  if (strlen(clde->d_name) == 8 &&
1842  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1843  {
1844  TransactionId xid;
1845  char *buf;
1846 
1847  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1848 
1850  true, false, false);
1851  if (buf == NULL)
1852  continue;
1853 
1856  }
1857  }
1858  LWLockRelease(TwoPhaseStateLock);
1859  FreeDir(cldir);
1860 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TransactionId
Definition: c.h:507
Definition: dirent.h:9
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
Definition: dirent.c:25
static char * buf
Definition: pg_test_fsync.c:68
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2466
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2117
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2390
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2532
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define InvalidRepOriginId
Definition: origin.h:33
#define TWOPHASE_DIR
Definition: twophase.c:115
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2584

◆ save_state_data()

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

Definition at line 976 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().

977 {
978  uint32 padlen = MAXALIGN(len);
979 
980  if (padlen > records.bytes_free)
981  {
982  records.tail->next = palloc0(sizeof(StateFileChunk));
984  records.tail->len = 0;
985  records.tail->next = NULL;
987 
988  records.bytes_free = Max(padlen, 512);
990  }
991 
992  memcpy(((char *) records.tail->data) + records.tail->len, data, len);
993  records.tail->len += padlen;
994  records.bytes_free -= padlen;
995  records.total_len += padlen;
996 }
StateFileChunk * tail
Definition: twophase.c:960
uint32 num_chunks
Definition: twophase.c:961
char * data
Definition: twophase.c:952
uint32 bytes_free
Definition: twophase.c:962
uint32 len
Definition: twophase.c:953
unsigned int uint32
Definition: c.h:358
static struct xllist records
uint32 total_len
Definition: twophase.c:963
struct StateFileChunk * next
Definition: twophase.c:954
void * palloc0(Size size)
Definition: mcxt.c:980
#define Max(x, y)
Definition: c.h:898
#define MAXALIGN(LEN)
Definition: c.h:685
void * palloc(Size size)
Definition: mcxt.c:949

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 1975 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().

1976 {
1977  int i;
1978 
1979  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1980  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1981  {
1982  TransactionId xid;
1983  char *buf;
1985 
1986  Assert(gxact->inredo);
1987 
1988  xid = gxact->xid;
1989 
1990  buf = ProcessTwoPhaseBuffer(xid,
1991  gxact->prepare_start_lsn,
1992  gxact->ondisk, false, false);
1993  if (buf != NULL)
1994  pfree(buf);
1995  }
1996  LWLockRelease(TwoPhaseStateLock);
1997 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:192
uint32 TransactionId
Definition: c.h:507
XLogRecPtr prepare_start_lsn
Definition: twophase.c:164
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void pfree(void *pointer)
Definition: mcxt.c:1056
static char * buf
Definition: pg_test_fsync.c:68
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:189
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2117
#define Assert(condition)
Definition: c.h:732
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
TransactionId xid
Definition: twophase.c:166
int i

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1426 of file twophase.c.

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

1427 {
1428  char *buf;
1429  TwoPhaseFileHeader *hdr;
1430  bool result;
1431 
1433 
1434  if (max_prepared_xacts <= 0)
1435  return false; /* nothing to do */
1436 
1437  /* Read and validate file */
1438  buf = ReadTwoPhaseFile(xid, true);
1439  if (buf == NULL)
1440  return false;
1441 
1442  /* Check header also */
1443  hdr = (TwoPhaseFileHeader *) buf;
1444  result = TransactionIdEquals(hdr->xid, xid);
1445  pfree(buf);
1446 
1447  return result;
1448 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1227
TransactionId xid
Definition: twophase.c:918
void pfree(void *pointer)
Definition: mcxt.c:1056
int max_prepared_xacts
Definition: twophase.c:118
static char * buf
Definition: pg_test_fsync.c:68
#define Assert(condition)
Definition: c.h:732
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 1004 of file twophase.c.

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

Referenced by PrepareTransaction().

1005 {
1006  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
1007  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1008  TransactionId xid = pgxact->xid;
1009  TwoPhaseFileHeader hdr;
1010  TransactionId *children;
1011  RelFileNode *commitrels;
1012  RelFileNode *abortrels;
1013  SharedInvalidationMessage *invalmsgs;
1014 
1015  /* Initialize linked list */
1016  records.head = palloc0(sizeof(StateFileChunk));
1017  records.head->len = 0;
1018  records.head->next = NULL;
1019 
1020  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1022 
1024  records.num_chunks = 1;
1025 
1026  records.total_len = 0;
1027 
1028  /* Create header */
1029  hdr.magic = TWOPHASE_MAGIC;
1030  hdr.total_len = 0; /* EndPrepare will fill this in */
1031  hdr.xid = xid;
1032  hdr.database = proc->databaseId;
1033  hdr.prepared_at = gxact->prepared_at;
1034  hdr.owner = gxact->owner;
1035  hdr.nsubxacts = xactGetCommittedChildren(&children);
1036  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1037  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1039  &hdr.initfileinval);
1040  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1041 
1042  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1043  save_state_data(gxact->gid, hdr.gidlen);
1044 
1045  /*
1046  * Add the additional info about subxacts, deletable files and cache
1047  * invalidation messages.
1048  */
1049  if (hdr.nsubxacts > 0)
1050  {
1051  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1052  /* While we have the child-xact data, stuff it in the gxact too */
1053  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1054  }
1055  if (hdr.ncommitrels > 0)
1056  {
1057  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1058  pfree(commitrels);
1059  }
1060  if (hdr.nabortrels > 0)
1061  {
1062  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1063  pfree(abortrels);
1064  }
1065  if (hdr.ninvalmsgs > 0)
1066  {
1067  save_state_data(invalmsgs,
1068  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1069  pfree(invalmsgs);
1070  }
1071 }
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5419
uint32 TransactionId
Definition: c.h:507
Definition: proc.h:222
PGXACT * allPgXact
Definition: proc.h:249
TransactionId xid
Definition: proc.h:224
StateFileChunk * tail
Definition: twophase.c:960
PROC_HDR * ProcGlobal
Definition: proc.c:81
TransactionId xid
Definition: twophase.c:918
uint32 num_chunks
Definition: twophase.c:961
char gid[GIDSIZE]
Definition: twophase.c:173
char * data
Definition: twophase.c:952
void pfree(void *pointer)
Definition: mcxt.c:1056
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:510
uint32 bytes_free
Definition: twophase.c:962
int smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
Definition: storage.c:514
uint32 len
Definition: twophase.c:953
Oid databaseId
Definition: proc.h:114
static struct xllist records
uint32 total_len
Definition: twophase.c:963
struct StateFileChunk * next
Definition: twophase.c:954
void * palloc0(Size size)
Definition: mcxt.c:980
#define TWOPHASE_MAGIC
Definition: twophase.c:912
#define Max(x, y)
Definition: c.h:898
StateFileChunk * head
Definition: twophase.c:959
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:976
TimestampTz prepared_at
Definition: twophase.c:155
void * palloc(Size size)
Definition: mcxt.c:949
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:828
PGPROC * allProcs
Definition: proc.h:247
TimestampTz prepared_at
Definition: twophase.c:920
Definition: proc.h:95

◆ TwoPhaseGetDummyBackendId()

BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid,
bool  lock_held 
)

Definition at line 864 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

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

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid,
bool  lock_held 
)

Definition at line 879 of file twophase.c.

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

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

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

◆ TwoPhaseGetGXact()

static GlobalTransaction TwoPhaseGetGXact ( TransactionId  xid,
bool  lock_held 
)
static

Definition at line 810 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().

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

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 253 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().

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

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 237 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores(), and TwoPhaseShmemInit().

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

◆ XlogReadTwoPhaseData()

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

Definition at line 1382 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, XLogReaderAllocate(), XLogReaderFree(), XLogReadRecord(), XLogRecGetData, XLogRecGetDataLen, XLogRecGetInfo, and XLogRecGetRmid.

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

1383 {
1384  XLogRecord *record;
1385  XLogReaderState *xlogreader;
1386  char *errormsg;
1387 
1388  xlogreader = XLogReaderAllocate(wal_segment_size, NULL,
1389  &read_local_xlog_page, NULL);
1390  if (!xlogreader)
1391  ereport(ERROR,
1392  (errcode(ERRCODE_OUT_OF_MEMORY),
1393  errmsg("out of memory"),
1394  errdetail("Failed while allocating a WAL reading processor.")));
1395 
1396  record = XLogReadRecord(xlogreader, lsn, &errormsg);
1397  if (record == NULL)
1398  ereport(ERROR,
1400  errmsg("could not read two-phase state from WAL at %X/%X",
1401  (uint32) (lsn >> 32),
1402  (uint32) lsn)));
1403 
1404  if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1406  ereport(ERROR,
1408  errmsg("expected two-phase state data is not present in WAL at %X/%X",
1409  (uint32) (lsn >> 32),
1410  (uint32) lsn)));
1411 
1412  if (len != NULL)
1413  *len = XLogRecGetDataLen(xlogreader);
1414 
1415  *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1416  memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1417 
1418  XLogReaderFree(xlogreader);
1419 }
#define XLOG_XACT_PREPARE
Definition: xact.h:144
int wal_segment_size
Definition: xlog.c:112
int errcode(int sqlerrcode)
Definition: elog.c:570
XLogRecord * XLogReadRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
Definition: xlogreader.c:237
#define XLogRecGetData(decoder)
Definition: xlogreader.h:246
#define ERROR
Definition: elog.h:43
#define XLogRecGetDataLen(decoder)
Definition: xlogreader.h:247
static char * buf
Definition: pg_test_fsync.c:68
int errdetail(const char *fmt,...)
Definition: elog.c:860
int errcode_for_file_access(void)
Definition: elog.c:593
unsigned int uint32
Definition: c.h:358
#define ereport(elevel, rest)
Definition: elog.h:141
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:242
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:133
#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:71
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:784
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:911
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:243

Variable Documentation

◆ max_prepared_xacts

◆ MyLockedGxact

GlobalTransaction MyLockedGxact = NULL
static

Definition at line 200 of file twophase.c.

◆ records

struct xllist records
static

◆ twophaseExitRegistered

bool twophaseExitRegistered = false
static

Definition at line 202 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseState

TwoPhaseStateData* TwoPhaseState
static

Definition at line 192 of file twophase.c.