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/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 GIDSIZE   200
 
#define TwoPhaseFilePath(path, xid)   snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
 
#define TWOPHASE_MAGIC   0x57F94533 /* 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)
 
static void RecordTransactionAbortPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels)
 
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)
 
BackendId TwoPhaseGetDummyBackendId (TransactionId xid)
 
PGPROCTwoPhaseGetDummyProc (TransactionId xid)
 
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 give_warnings)
 
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)
 
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

◆ GIDSIZE

#define GIDSIZE   200

Definition at line 151 of file twophase.c.

Referenced by MarkAsPreparing().

◆ TWOPHASE_DIR

#define TWOPHASE_DIR   "pg_twophase"

Definition at line 114 of file twophase.c.

Referenced by CheckPointTwoPhase(), and restoreTwoPhaseData().

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94533 /* format identifier */

Definition at line 901 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 879 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 319 of file twophase.c.

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

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

◆ AtProcExit_Twophase()

static void AtProcExit_Twophase ( int  code,
Datum  arg 
)
static

Definition at line 309 of file twophase.c.

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

310 {
311  /* same logic as abort */
313 }
void AtAbort_Twophase(void)
Definition: twophase.c:319

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

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

1652 {
1653  int i;
1654  int serialized_xacts = 0;
1655 
1656  if (max_prepared_xacts <= 0)
1657  return; /* nothing to do */
1658 
1659  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1660 
1661  /*
1662  * We are expecting there to be zero GXACTs that need to be copied to
1663  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1664  * simplicity. This prevents any new xacts from preparing while this
1665  * occurs, which shouldn't be a problem since the presence of long-lived
1666  * prepared xacts indicates the transaction manager isn't active.
1667  *
1668  * It's also possible to move I/O out of the lock, but on every error we
1669  * should check whether somebody committed our transaction in different
1670  * backend. Let's leave this optimization for future, if somebody will
1671  * spot that this place cause bottleneck.
1672  *
1673  * Note that it isn't possible for there to be a GXACT with a
1674  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1675  * because of the efforts with delayChkpt.
1676  */
1677  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1678  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1679  {
1680  /*
1681  * Note that we are using gxact not pgxact so this works in recovery
1682  * also
1683  */
1685 
1686  if ((gxact->valid || gxact->inredo) &&
1687  !gxact->ondisk &&
1688  gxact->prepare_end_lsn <= redo_horizon)
1689  {
1690  char *buf;
1691  int len;
1692 
1693  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1694  RecreateTwoPhaseFile(gxact->xid, buf, len);
1695  gxact->ondisk = true;
1698  pfree(buf);
1699  serialized_xacts++;
1700  }
1701  }
1702  LWLockRelease(TwoPhaseStateLock);
1703 
1704  /*
1705  * Flush unconditionally the parent directory to make any information
1706  * durable on disk. Two-phase files could have been removed and those
1707  * removals need to be made persistent as well as any files newly created
1708  * previously since the last checkpoint.
1709  */
1710  fsync_fname(TWOPHASE_DIR, true);
1711 
1712  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1713 
1714  if (log_checkpoints && serialized_xacts > 0)
1715  ereport(LOG,
1716  (errmsg_plural("%u two-phase state file was written "
1717  "for a long-running prepared transaction",
1718  "%u two-phase state files were written "
1719  "for long-running prepared transactions",
1720  serialized_xacts,
1721  serialized_xacts)));
1722 }
bool log_checkpoints
Definition: xlog.c:102
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:572
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void pfree(void *pointer)
Definition: mcxt.c:949
int max_prepared_xacts
Definition: twophase.c:117
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:122
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1570
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
#define TWOPHASE_DIR
Definition: twophase.c:114
TransactionId xid
Definition: twophase.c:169
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1296
int i
XLogRecPtr prepare_end_lsn
Definition: twophase.c:168

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1064 of file twophase.c.

References Assert, StateFileChunk::data, PGXACT::delayChkpt, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xllist::head, StateFileChunk::len, TwoPhaseFileHeader::magic, MarkAsPrepared(), MaxAllocSize, MyPgXact, StateFileChunk::next, xllist::num_chunks, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, ProcLastRecPtr, records, RegisterTwoPhaseRecord(), START_CRIT_SECTION, SyncRepWaitForLSN(), xllist::tail, TwoPhaseFileHeader::total_len, xllist::total_len, TWOPHASE_MAGIC, TWOPHASE_RM_END_ID, XLOG_XACT_PREPARE, XLogBeginInsert(), XLogEnsureRecordSpace(), XLogFlush(), XLogInsert(), and XLogRegisterData().

Referenced by PrepareTransaction().

1065 {
1066  TwoPhaseFileHeader *hdr;
1067  StateFileChunk *record;
1068 
1069  /* Add the end sentinel to the list of 2PC records */
1071  NULL, 0);
1072 
1073  /* Go back and fill in total_len in the file header record */
1074  hdr = (TwoPhaseFileHeader *) records.head->data;
1075  Assert(hdr->magic == TWOPHASE_MAGIC);
1076  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1077 
1078  /*
1079  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1080  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1081  * where we write data to file and then re-read at commit time.
1082  */
1083  if (hdr->total_len > MaxAllocSize)
1084  ereport(ERROR,
1085  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1086  errmsg("two-phase state file maximum length exceeded")));
1087 
1088  /*
1089  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1090  * cover us, so no need to calculate a separate CRC.
1091  *
1092  * We have to set delayChkpt here, too; otherwise a checkpoint starting
1093  * immediately after the WAL record is inserted could complete without
1094  * fsync'ing our state file. (This is essentially the same kind of race
1095  * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1096  * uses delayChkpt for; see notes there.)
1097  *
1098  * We save the PREPARE record's location in the gxact for later use by
1099  * CheckPointTwoPhase.
1100  */
1102 
1104 
1105  MyPgXact->delayChkpt = true;
1106 
1107  XLogBeginInsert();
1108  for (record = records.head; record != NULL; record = record->next)
1109  XLogRegisterData(record->data, record->len);
1110  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1111  XLogFlush(gxact->prepare_end_lsn);
1112 
1113  /* If we crash now, we have prepared: WAL replay will fix things */
1114 
1115  /* Store record's start location to read that later on Commit */
1117 
1118  /*
1119  * Mark the prepared transaction as valid. As soon as xact.c marks
1120  * MyPgXact as not running our XID (which it will do immediately after
1121  * this function returns), others can commit/rollback the xact.
1122  *
1123  * NB: a side effect of this is to make a dummy ProcArray entry for the
1124  * prepared XID. This must happen before we clear the XID from MyPgXact,
1125  * else there is a window where the XID is not running according to
1126  * TransactionIdIsInProgress, and onlookers would be entitled to assume
1127  * the xact crashed. Instead we have a window where the same XID appears
1128  * twice in ProcArray, which is OK.
1129  */
1130  MarkAsPrepared(gxact, false);
1131 
1132  /*
1133  * Now we can mark ourselves as out of the commit critical section: a
1134  * checkpoint starting after this will certainly see the gxact as a
1135  * candidate for fsyncing.
1136  */
1137  MyPgXact->delayChkpt = false;
1138 
1139  /*
1140  * Remember that we have this GlobalTransaction entry locked for us. If
1141  * we crash after this point, it's too late to abort, but we must unlock
1142  * it so that the prepared transaction can be committed or rolled back.
1143  */
1144  MyLockedGxact = gxact;
1145 
1146  END_CRIT_SECTION();
1147 
1148  /*
1149  * Wait for synchronous replication, if required.
1150  *
1151  * Note that at this stage we have marked the prepare, but still show as
1152  * running in the procarray (twice!) and continue to hold locks.
1153  */
1154  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1155 
1156  records.tail = records.head = NULL;
1157  records.num_chunks = 0;
1158 }
#define XLOG_XACT_PREPARE
Definition: xact.h:134
StateFileChunk * tail
Definition: twophase.c:947
uint32 pg_crc32c
Definition: pg_crc32c.h:38
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:338
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:146
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
#define START_CRIT_SECTION()
Definition: miscadmin.h:131
int errcode(int sqlerrcode)
Definition: elog.c:575
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
uint32 num_chunks
Definition: twophase.c:948
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2763
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1164
PGXACT * MyPgXact
Definition: proc.c:68
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
char * data
Definition: twophase.c:939
#define ERROR
Definition: elog.h:43
uint32 len
Definition: twophase.c:940
#define ereport(elevel, rest)
Definition: elog.h:122
bool delayChkpt
Definition: proc.h:232
static struct xllist records
uint32 total_len
Definition: twophase.c:950
#define MaxAllocSize
Definition: memutils.h:40
struct StateFileChunk * next
Definition: twophase.c:941
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:901
StateFileChunk * head
Definition: twophase.c:946
#define Assert(condition)
Definition: c.h:670
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition: xloginsert.c:146
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:537
int errmsg(const char *fmt,...)
Definition: elog.c:797
static GlobalTransaction MyLockedGxact
Definition: twophase.c:203
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr prepare_end_lsn
Definition: twophase.c:168

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1368 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Assert, AtEOXact_PgStat(), buf, GetUserId(), TwoPhaseFileHeader::gidlen, i, TwoPhaseFileHeader::initfileinval, InvalidBackendId, 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(), SendSharedInvalidMessages(), smgrclose(), smgrdounlink(), smgropen(), TransactionIdEquals, TransactionIdLatest(), twophase_postabort_callbacks, twophase_postcommit_callbacks, GlobalTransactionData::valid, GlobalTransactionData::xid, PGXACT::xid, TwoPhaseFileHeader::xid, and XlogReadTwoPhaseData().

Referenced by standard_ProcessUtility().

1369 {
1370  GlobalTransaction gxact;
1371  PGPROC *proc;
1372  PGXACT *pgxact;
1373  TransactionId xid;
1374  char *buf;
1375  char *bufptr;
1376  TwoPhaseFileHeader *hdr;
1377  TransactionId latestXid;
1378  TransactionId *children;
1379  RelFileNode *commitrels;
1380  RelFileNode *abortrels;
1381  RelFileNode *delrels;
1382  int ndelrels;
1383  SharedInvalidationMessage *invalmsgs;
1384  int i;
1385 
1386  /*
1387  * Validate the GID, and lock the GXACT to ensure that two backends do not
1388  * try to commit the same GID at once.
1389  */
1390  gxact = LockGXact(gid, GetUserId());
1391  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1392  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1393  xid = pgxact->xid;
1394 
1395  /*
1396  * Read and validate 2PC state data. State data will typically be stored
1397  * in WAL files if the LSN is after the last checkpoint record, or moved
1398  * to disk if for some reason they have lived for a long time.
1399  */
1400  if (gxact->ondisk)
1401  buf = ReadTwoPhaseFile(xid, true);
1402  else
1403  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1404 
1405 
1406  /*
1407  * Disassemble the header area
1408  */
1409  hdr = (TwoPhaseFileHeader *) buf;
1410  Assert(TransactionIdEquals(hdr->xid, xid));
1411  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1412  bufptr += MAXALIGN(hdr->gidlen);
1413  children = (TransactionId *) bufptr;
1414  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1415  commitrels = (RelFileNode *) bufptr;
1416  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1417  abortrels = (RelFileNode *) bufptr;
1418  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1419  invalmsgs = (SharedInvalidationMessage *) bufptr;
1420  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1421 
1422  /* compute latestXid among all children */
1423  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1424 
1425  /*
1426  * The order of operations here is critical: make the XLOG entry for
1427  * commit or abort, then mark the transaction committed or aborted in
1428  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1429  * TransactionIdIsInProgress will stop saying the prepared xact is in
1430  * progress), then run the post-commit or post-abort callbacks. The
1431  * callbacks will release the locks the transaction held.
1432  */
1433  if (isCommit)
1435  hdr->nsubxacts, children,
1436  hdr->ncommitrels, commitrels,
1437  hdr->ninvalmsgs, invalmsgs,
1438  hdr->initfileinval);
1439  else
1441  hdr->nsubxacts, children,
1442  hdr->nabortrels, abortrels);
1443 
1444  ProcArrayRemove(proc, latestXid);
1445 
1446  /*
1447  * In case we fail while running the callbacks, mark the gxact invalid so
1448  * no one else will try to commit/rollback, and so it will be recycled if
1449  * we fail after this point. It is still locked by our backend so it
1450  * won't go away yet.
1451  *
1452  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1453  */
1454  gxact->valid = false;
1455 
1456  /*
1457  * We have to remove any files that were supposed to be dropped. For
1458  * consistency with the regular xact.c code paths, must do this before
1459  * releasing locks, so do it before running the callbacks.
1460  *
1461  * NB: this code knows that we couldn't be dropping any temp rels ...
1462  */
1463  if (isCommit)
1464  {
1465  delrels = commitrels;
1466  ndelrels = hdr->ncommitrels;
1467  }
1468  else
1469  {
1470  delrels = abortrels;
1471  ndelrels = hdr->nabortrels;
1472  }
1473  for (i = 0; i < ndelrels; i++)
1474  {
1475  SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1476 
1477  smgrdounlink(srel, false);
1478  smgrclose(srel);
1479  }
1480 
1481  /*
1482  * Handle cache invalidation messages.
1483  *
1484  * Relcache init file invalidation requires processing both before and
1485  * after we send the SI messages. See AtEOXact_Inval()
1486  */
1487  if (hdr->initfileinval)
1489  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1490  if (hdr->initfileinval)
1492 
1493  /* And now do the callbacks */
1494  if (isCommit)
1496  else
1498 
1499  PredicateLockTwoPhaseFinish(xid, isCommit);
1500 
1501  /* Count the prepared xact as committed or aborted */
1502  AtEOXact_PgStat(isCommit);
1503 
1504  /*
1505  * And now we can clean up any files we may have left.
1506  */
1507  if (gxact->ondisk)
1508  RemoveTwoPhaseFile(xid, true);
1509 
1510  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1511  RemoveGXact(gxact);
1512  LWLockRelease(TwoPhaseStateLock);
1513  MyLockedGxact = NULL;
1514 
1515  pfree(buf);
1516 }
void smgrclose(SMgrRelation reln)
Definition: smgr.c:296
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:445
Definition: proc.h:219
Oid GetUserId(void)
Definition: miscinit.c:284
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels)
Definition: twophase.c:2254
PGXACT * allPgXact
Definition: proc.h:246
TransactionId xid
Definition: proc.h:221
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:1522
void smgrdounlink(SMgrRelation reln, bool isRedo)
Definition: smgr.c:414
const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:33
PROC_HDR * ProcGlobal
Definition: proc.c:80
TransactionId xid
Definition: twophase.c:907
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void pfree(void *pointer)
Definition: mcxt.c:949
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 PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:4896
static char * buf
Definition: pg_test_fsync.c:67
SMgrRelation smgropen(RelFileNode rnode, BackendId backend)
Definition: smgr.c:137
static void RecordTransactionCommitPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval)
Definition: twophase.c:2161
#define InvalidBackendId
Definition: backendid.h:23
const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:42
static char * ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
Definition: twophase.c:1185
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:6087
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1550
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:6061
#define Assert(condition)
Definition: c.h:670
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
#define MAXALIGN(LEN)
Definition: c.h:623
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1296
static GlobalTransaction MyLockedGxact
Definition: twophase.c:203
int i
PGPROC * allProcs
Definition: proc.h:244
Definition: proc.h:95
void AtEOXact_PgStat(bool isCommit)
Definition: pgstat.c:2053

◆ 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:195
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:25
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
void * palloc(Size size)
Definition: mcxt.c:848
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:445
Definition: proc.h:219
PGXACT * allPgXact
Definition: proc.h:246
PROC_HDR * ProcGlobal
Definition: proc.c:80
uint8 nxids
Definition: proc.h:235
struct XidCache subxids
Definition: proc.h:159
bool overflowed
Definition: proc.h:231
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:36
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:40
PGPROC * allProcs
Definition: proc.h:244
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:987
BackendId MyBackendId
Definition: globals.c:73
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
int errcode(int sqlerrcode)
Definition: elog.c:575
PROC_HDR * ProcGlobal
Definition: proc.c:80
static bool twophaseExitRegistered
Definition: twophase.c:205
char gid[GIDSIZE]
Definition: twophase.c:176
BackendId locking_backend
Definition: twophase.c:172
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define ERROR
Definition: elog.h:43
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
Oid databaseId
Definition: proc.h:114
#define ereport(elevel, rest)
Definition: elog.h:122
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
bool superuser_arg(Oid roleid)
Definition: superuser.c:57
#define InvalidBackendId
Definition: backendid.h:23
Oid MyDatabaseId
Definition: globals.c:77
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
static char * user
Definition: pg_regress.c:93
int errmsg(const char *fmt,...)
Definition: elog.c:797
static GlobalTransaction MyLockedGxact
Definition: twophase.c:203
int i
PGPROC * allProcs
Definition: proc.h:244
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:309
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:80
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define Assert(condition)
Definition: c.h:670
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
PGPROC * allProcs
Definition: proc.h:244
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 374 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().

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

◆ MarkAsPreparingGuts()

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

Definition at line 448 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Assert, PGPROC::backendId, PGPROC::databaseId, PGXACT::delayChkpt, GlobalTransactionData::gid, i, GlobalTransactionData::inredo, InvalidBackendId, 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, PGXACT::vacuumFlags, GlobalTransactionData::valid, PGPROC::waitLock, PGPROC::waitProcLock, PGPROC::waitStatus, GlobalTransactionData::xid, PGXACT::xid, and PGXACT::xmin.

Referenced by MarkAsPreparing(), and RecoverPreparedTransactions().

450 {
451  PGPROC *proc;
452  PGXACT *pgxact;
453  int i;
454 
455  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
456 
457  Assert(gxact != NULL);
458  proc = &ProcGlobal->allProcs[gxact->pgprocno];
459  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
460 
461  /* Initialize the PGPROC entry */
462  MemSet(proc, 0, sizeof(PGPROC));
463  proc->pgprocno = gxact->pgprocno;
464  SHMQueueElemInit(&(proc->links));
465  proc->waitStatus = STATUS_OK;
466  /* We set up the gxact's VXID as InvalidBackendId/XID */
467  proc->lxid = (LocalTransactionId) xid;
468  pgxact->xid = xid;
469  pgxact->xmin = InvalidTransactionId;
470  pgxact->delayChkpt = false;
471  pgxact->vacuumFlags = 0;
472  proc->pid = 0;
473  proc->backendId = InvalidBackendId;
474  proc->databaseId = databaseid;
475  proc->roleId = owner;
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:1855
BackendId MyBackendId
Definition: globals.c:73
BackendId backendId
Definition: proc.h:113
Definition: proc.h:219
TransactionId xmin
Definition: proc.h:225
PGXACT * allPgXact
Definition: proc.h:246
TransactionId xid
Definition: proc.h:221
SHM_QUEUE links
Definition: proc.h:98
bool lwWaiting
Definition: proc.h:127
Oid roleId
Definition: proc.h:115
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:853
uint8 lwWaitMode
Definition: proc.h:128
char gid[GIDSIZE]
Definition: twophase.c:176
uint8 vacuumFlags
Definition: proc.h:230
BackendId locking_backend
Definition: twophase.c:172
bool isBackgroundWorker
Definition: proc.h:117
PROCLOCK * waitProcLock
Definition: proc.h:137
uint8 nxids
Definition: proc.h:235
#define InvalidTransactionId
Definition: transam.h:31
Oid databaseId
Definition: proc.h:114
uint32 LocalTransactionId
Definition: c.h:447
LOCK * waitLock
Definition: proc.h:136
#define STATUS_OK
Definition: c.h:953
bool delayChkpt
Definition: proc.h:232
#define InvalidBackendId
Definition: backendid.h:23
bool overflowed
Definition: proc.h:231
int waitStatus
Definition: proc.h:102
#define Assert(condition)
Definition: c.h:670
TransactionId xid
Definition: twophase.c:169
TimestampTz prepared_at
Definition: twophase.c:158
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:203
int i
PGPROC * allProcs
Definition: proc.h:244
SHM_QUEUE myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:157
Definition: proc.h:95
int pid
Definition: proc.h:109
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:117
LocalTransactionId lxid
Definition: proc.h:106

◆ pg_prepared_xact()

Datum pg_prepared_xact ( PG_FUNCTION_ARGS  )

Definition at line 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, OIDOID, 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(), TEXTOID, TimestampTzGetDatum, TIMESTAMPTZOID, TransactionIdGetDatum, FuncCallContext::tuple_desc, TupleDescInitEntry(), FuncCallContext::user_fctx, GlobalTransactionData::valid, values, PGXACT::xid, and XIDOID.

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, false);
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 }
#define TIMESTAMPTZOID
Definition: pg_type.h:525
Definition: proc.h:219
#define OIDOID
Definition: pg_type.h:328
#define TEXTOID
Definition: pg_type.h:324
PGXACT * allPgXact
Definition: proc.h:246
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:293
TransactionId xid
Definition: proc.h:221
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition: twophase.c:673
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:853
#define XIDOID
Definition: pg_type.h:336
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:695
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:297
char gid[GIDSIZE]
Definition: twophase.c:176
TupleDesc tuple_desc
Definition: funcapi.h:121
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:299
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:1032
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:505
#define TransactionIdGetDatum(X)
Definition: postgres.h:527
uintptr_t Datum
Definition: postgres.h:372
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:110
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:230
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:43
static Datum values[MAXATTR]
Definition: bootstrap.c:164
TimestampTz prepared_at
Definition: twophase.c:158
void * user_fctx
Definition: funcapi.h:91
void * palloc(Size size)
Definition: mcxt.c:848
#define CStringGetTextDatum(s)
Definition: builtins.h:91
PGPROC * allProcs
Definition: proc.h:244
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
Definition: proc.h:95
int16 AttrNumber
Definition: attnum.h:21
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:317
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:295

◆ PostPrepare_Twophase()

void PostPrepare_Twophase ( void  )

Definition at line 359 of file twophase.c.

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

360 {
361  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
363  LWLockRelease(TwoPhaseStateLock);
364 
365  MyLockedGxact = NULL;
366 }
BackendId locking_backend
Definition: twophase.c:172
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define InvalidBackendId
Definition: backendid.h:23
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
static GlobalTransaction MyLockedGxact
Definition: twophase.c:203

◆ PrepareRedoAdd()

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

Definition at line 2312 of file twophase.c.

References Assert, DEBUG2, elog, ereport, errcode(), errhint(), errmsg(), ERROR, TwoPhaseStateData::freeGXacts, GlobalTransactionData::gid, GlobalTransactionData::inredo, InvalidBackendId, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockHeldByMeInMode(), max_prepared_xacts, MAXALIGN, GlobalTransactionData::next, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, GlobalTransactionData::owner, TwoPhaseFileHeader::owner, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, GlobalTransactionData::prepared_at, TwoPhaseFileHeader::prepared_at, TwoPhaseStateData::prepXacts, RecoveryInProgress(), GlobalTransactionData::valid, GlobalTransactionData::xid, TwoPhaseFileHeader::xid, and XLogRecPtrIsInvalid.

Referenced by restoreTwoPhaseData(), and xact_redo().

2313 {
2315  char *bufptr;
2316  const char *gid;
2317  GlobalTransaction gxact;
2318 
2319  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2321 
2322  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2323  gid = (const char *) bufptr;
2324 
2325  /*
2326  * Reserve the GID for the given transaction in the redo code path.
2327  *
2328  * This creates a gxact struct and puts it into the active array.
2329  *
2330  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2331  * shared memory. Hence, we only fill up the bare minimum contents here.
2332  * The gxact also gets marked with gxact->inredo set to true to indicate
2333  * that it got added in the redo phase
2334  */
2335 
2336  /* Get a free gxact from the freelist */
2337  if (TwoPhaseState->freeGXacts == NULL)
2338  ereport(ERROR,
2339  (errcode(ERRCODE_OUT_OF_MEMORY),
2340  errmsg("maximum number of prepared transactions reached"),
2341  errhint("Increase max_prepared_transactions (currently %d).",
2342  max_prepared_xacts)));
2343  gxact = TwoPhaseState->freeGXacts;
2344  TwoPhaseState->freeGXacts = gxact->next;
2345 
2346  gxact->prepared_at = hdr->prepared_at;
2347  gxact->prepare_start_lsn = start_lsn;
2348  gxact->prepare_end_lsn = end_lsn;
2349  gxact->xid = hdr->xid;
2350  gxact->owner = hdr->owner;
2352  gxact->valid = false;
2353  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2354  gxact->inredo = true; /* yes, added in redo */
2355  strcpy(gxact->gid, gid);
2356 
2357  /* And insert it into the active array */
2360 
2361  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2362 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1855
int errhint(const char *fmt,...)
Definition: elog.c:987
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
GlobalTransaction freeGXacts
Definition: twophase.c:186
int errcode(int sqlerrcode)
Definition: elog.c:575
TransactionId xid
Definition: twophase.c:907
GlobalTransaction next
Definition: twophase.c:155
bool RecoveryInProgress(void)
Definition: xlog.c:7929
char gid[GIDSIZE]
Definition: twophase.c:176
BackendId locking_backend
Definition: twophase.c:172
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:117
#define DEBUG2
Definition: elog.h:24
static char * buf
Definition: pg_test_fsync.c:67
#define ereport(elevel, rest)
Definition: elog.h:122
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define InvalidBackendId
Definition: backendid.h:23
#define Assert(condition)
Definition: c.h:670
#define MAXALIGN(LEN)
Definition: c.h:623
TransactionId xid
Definition: twophase.c:169
TimestampTz prepared_at
Definition: twophase.c:158
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
TimestampTz prepared_at
Definition: twophase.c:909
XLogRecPtr prepare_end_lsn
Definition: twophase.c:168

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

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

2375 {
2376  GlobalTransaction gxact = NULL;
2377  int i;
2378  bool found = false;
2379 
2380  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2382 
2383  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2384  {
2385  gxact = TwoPhaseState->prepXacts[i];
2386 
2387  if (gxact->xid == xid)
2388  {
2389  Assert(gxact->inredo);
2390  found = true;
2391  break;
2392  }
2393  }
2394 
2395  /*
2396  * Just leave if there is nothing, this is expected during WAL replay.
2397  */
2398  if (!found)
2399  return;
2400 
2401  /*
2402  * And now we can clean up any files we may have left.
2403  */
2404  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2405  if (gxact->ondisk)
2406  RemoveTwoPhaseFile(xid, giveWarning);
2407  RemoveGXact(gxact);
2408 
2409  return;
2410 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1855
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
bool RecoveryInProgress(void)
Definition: xlog.c:7929
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:635
#define DEBUG2
Definition: elog.h:24
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1550
#define Assert(condition)
Definition: c.h:670
TransactionId xid
Definition: twophase.c:169
int i
#define elog
Definition: elog.h:219

◆ PrescanPreparedTransactions()

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

Definition at line 1790 of file twophase.c.

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

Referenced by StartupXLOG(), and xlog_redo().

1791 {
1792  TransactionId origNextXid = ShmemVariableCache->nextXid;
1793  TransactionId result = origNextXid;
1794  TransactionId *xids = NULL;
1795  int nxids = 0;
1796  int allocsize = 0;
1797  int i;
1798 
1799  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1800  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1801  {
1802  TransactionId xid;
1803  char *buf;
1805 
1806  Assert(gxact->inredo);
1807 
1808  xid = gxact->xid;
1809 
1810  buf = ProcessTwoPhaseBuffer(xid,
1811  gxact->prepare_start_lsn,
1812  gxact->ondisk, false, true);
1813 
1814  if (buf == NULL)
1815  continue;
1816 
1817  /*
1818  * OK, we think this file is valid. Incorporate xid into the
1819  * running-minimum result.
1820  */
1821  if (TransactionIdPrecedes(xid, result))
1822  result = xid;
1823 
1824  if (xids_p)
1825  {
1826  if (nxids == allocsize)
1827  {
1828  if (nxids == 0)
1829  {
1830  allocsize = 10;
1831  xids = palloc(allocsize * sizeof(TransactionId));
1832  }
1833  else
1834  {
1835  allocsize = allocsize * 2;
1836  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1837  }
1838  }
1839  xids[nxids++] = xid;
1840  }
1841 
1842  pfree(buf);
1843  }
1844  LWLockRelease(TwoPhaseStateLock);
1845 
1846  if (xids_p)
1847  {
1848  *xids_p = xids;
1849  *nxids_p = nxids;
1850  }
1851 
1852  return result;
1853 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
uint32 TransactionId
Definition: c.h:445
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void pfree(void *pointer)
Definition: mcxt.c:949
TransactionId nextXid
Definition: transam.h:117
static char * buf
Definition: pg_test_fsync.c:67
VariableCache ShmemVariableCache
Definition: varsup.c:34
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
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:2012
#define Assert(condition)
Definition: c.h:670
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:962
TransactionId xid
Definition: twophase.c:169
void * palloc(Size size)
Definition: mcxt.c:848
int i

◆ ProcessRecords()

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

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

1524 {
1525  for (;;)
1526  {
1527  TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1528 
1529  Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1530  if (record->rmid == TWOPHASE_RM_END_ID)
1531  break;
1532 
1533  bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1534 
1535  if (callbacks[record->rmid] != NULL)
1536  callbacks[record->rmid] (xid, record->info,
1537  (void *) bufptr, record->len);
1538 
1539  bufptr += MAXALIGN(record->len);
1540  }
1541 }
#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:670
#define MAXALIGN(LEN)
Definition: c.h:623
TwoPhaseRmgrId rmid
Definition: twophase.c:928

◆ ProcessTwoPhaseBuffer()

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

Definition at line 2012 of file twophase.c.

References Assert, buf, ereport, errmsg(), TwoPhaseFileHeader::gidlen, i, InvalidXLogRecPtr, LW_EXCLUSIVE, LWLockAcquire(), LWLockHeldByMeInMode(), LWLockRelease(), MAXALIGN, VariableCacheData::nextXid, TwoPhaseFileHeader::nsubxacts, pfree(), PrepareRedoRemove(), ReadTwoPhaseFile(), RemoveTwoPhaseFile(), ShmemVariableCache, SubTransSetParent(), TransactionIdAdvance, TransactionIdDidAbort(), TransactionIdDidCommit(), TransactionIdEquals, TransactionIdFollows(), TransactionIdFollowsOrEquals(), WARNING, TwoPhaseFileHeader::xid, and XlogReadTwoPhaseData().

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

2016 {
2017  TransactionId origNextXid = ShmemVariableCache->nextXid;
2018  TransactionId *subxids;
2019  char *buf;
2020  TwoPhaseFileHeader *hdr;
2021  int i;
2022 
2023  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2024 
2025  if (!fromdisk)
2026  Assert(prepare_start_lsn != InvalidXLogRecPtr);
2027 
2028  /* Already processed? */
2030  {
2031  if (fromdisk)
2032  {
2033  ereport(WARNING,
2034  (errmsg("removing stale two-phase state file for transaction %u",
2035  xid)));
2036  RemoveTwoPhaseFile(xid, true);
2037  }
2038  else
2039  {
2040  ereport(WARNING,
2041  (errmsg("removing stale two-phase state from memory for transaction %u",
2042  xid)));
2043  PrepareRedoRemove(xid, true);
2044  }
2045  return NULL;
2046  }
2047 
2048  /* Reject XID if too new */
2049  if (TransactionIdFollowsOrEquals(xid, origNextXid))
2050  {
2051  if (fromdisk)
2052  {
2053  ereport(WARNING,
2054  (errmsg("removing future two-phase state file for transaction %u",
2055  xid)));
2056  RemoveTwoPhaseFile(xid, true);
2057  }
2058  else
2059  {
2060  ereport(WARNING,
2061  (errmsg("removing future two-phase state from memory for transaction %u",
2062  xid)));
2063  PrepareRedoRemove(xid, true);
2064  }
2065  return NULL;
2066  }
2067 
2068  if (fromdisk)
2069  {
2070  /* Read and validate file */
2071  buf = ReadTwoPhaseFile(xid, true);
2072  if (buf == NULL)
2073  {
2074  ereport(WARNING,
2075  (errmsg("removing corrupt two-phase state file for transaction %u",
2076  xid)));
2077  RemoveTwoPhaseFile(xid, true);
2078  return NULL;
2079  }
2080  }
2081  else
2082  {
2083  /* Read xlog data */
2084  XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2085  }
2086 
2087  /* Deconstruct header */
2088  hdr = (TwoPhaseFileHeader *) buf;
2089  if (!TransactionIdEquals(hdr->xid, xid))
2090  {
2091  if (fromdisk)
2092  {
2093  ereport(WARNING,
2094  (errmsg("removing corrupt two-phase state file for transaction %u",
2095  xid)));
2096  RemoveTwoPhaseFile(xid, true);
2097  }
2098  else
2099  {
2100  ereport(WARNING,
2101  (errmsg("removing corrupt two-phase state from memory for transaction %u",
2102  xid)));
2103  PrepareRedoRemove(xid, true);
2104  }
2105  pfree(buf);
2106  return NULL;
2107  }
2108 
2109  /*
2110  * Examine subtransaction XIDs ... they should all follow main XID, and
2111  * they may force us to advance nextXid.
2112  */
2113  subxids = (TransactionId *) (buf +
2114  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2115  MAXALIGN(hdr->gidlen));
2116  for (i = 0; i < hdr->nsubxacts; i++)
2117  {
2118  TransactionId subxid = subxids[i];
2119 
2120  Assert(TransactionIdFollows(subxid, xid));
2121 
2122  /* update nextXid if needed */
2123  if (setNextXid &&
2126  {
2127  /*
2128  * We don't expect anyone else to modify nextXid, hence we don't
2129  * need to hold a lock while examining it. We still acquire the
2130  * lock to modify it, though, so we recheck.
2131  */
2132  LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
2133  if (TransactionIdFollowsOrEquals(subxid,
2135  {
2136  ShmemVariableCache->nextXid = subxid;
2138  }
2139  LWLockRelease(XidGenLock);
2140  }
2141 
2142  if (setParent)
2143  SubTransSetParent(subxid, xid);
2144  }
2145 
2146  return buf;
2147 }
#define TransactionIdAdvance(dest)
Definition: transam.h:48
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1855
void PrepareRedoRemove(TransactionId xid, bool giveWarning)
Definition: twophase.c:2374
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:445
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:349
TransactionId xid
Definition: twophase.c:907
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void pfree(void *pointer)
Definition: mcxt.c:949
TransactionId nextXid
Definition: transam.h:117
static char * buf
Definition: pg_test_fsync.c:67
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define ereport(elevel, rest)
Definition: elog.h:122
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181
#define WARNING
Definition: elog.h:40
static char * ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
Definition: twophase.c:1185
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1550
#define Assert(condition)
Definition: c.h:670
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
#define MAXALIGN(LEN)
Definition: c.h:623
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1296
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition: subtrans.c:74

◆ ReadTwoPhaseFile()

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

Definition at line 1185 of file twophase.c.

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

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

1186 {
1187  char path[MAXPGPATH];
1188  char *buf;
1189  TwoPhaseFileHeader *hdr;
1190  int fd;
1191  struct stat stat;
1192  uint32 crc_offset;
1193  pg_crc32c calc_crc,
1194  file_crc;
1195 
1196  TwoPhaseFilePath(path, xid);
1197 
1198  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
1199  if (fd < 0)
1200  {
1201  if (give_warnings)
1202  ereport(WARNING,
1204  errmsg("could not open two-phase state file \"%s\": %m",
1205  path)));
1206  return NULL;
1207  }
1208 
1209  /*
1210  * Check file length. We can determine a lower bound pretty easily. We
1211  * set an upper bound to avoid palloc() failure on a corrupt file, though
1212  * we can't guarantee that we won't get an out of memory error anyway,
1213  * even on a valid file.
1214  */
1215  if (fstat(fd, &stat))
1216  {
1217  CloseTransientFile(fd);
1218  if (give_warnings)
1219  ereport(WARNING,
1221  errmsg("could not stat two-phase state file \"%s\": %m",
1222  path)));
1223  return NULL;
1224  }
1225 
1226  if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1227  MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1228  sizeof(pg_crc32c)) ||
1229  stat.st_size > MaxAllocSize)
1230  {
1231  CloseTransientFile(fd);
1232  return NULL;
1233  }
1234 
1235  crc_offset = stat.st_size - sizeof(pg_crc32c);
1236  if (crc_offset != MAXALIGN(crc_offset))
1237  {
1238  CloseTransientFile(fd);
1239  return NULL;
1240  }
1241 
1242  /*
1243  * OK, slurp in the file.
1244  */
1245  buf = (char *) palloc(stat.st_size);
1246 
1248  if (read(fd, buf, stat.st_size) != stat.st_size)
1249  {
1251  CloseTransientFile(fd);
1252  if (give_warnings)
1253  ereport(WARNING,
1255  errmsg("could not read two-phase state file \"%s\": %m",
1256  path)));
1257  pfree(buf);
1258  return NULL;
1259  }
1260 
1262  CloseTransientFile(fd);
1263 
1264  hdr = (TwoPhaseFileHeader *) buf;
1265  if (hdr->magic != TWOPHASE_MAGIC || hdr->total_len != stat.st_size)
1266  {
1267  pfree(buf);
1268  return NULL;
1269  }
1270 
1271  INIT_CRC32C(calc_crc);
1272  COMP_CRC32C(calc_crc, buf, crc_offset);
1273  FIN_CRC32C(calc_crc);
1274 
1275  file_crc = *((pg_crc32c *) (buf + crc_offset));
1276 
1277  if (!EQ_CRC32C(calc_crc, file_crc))
1278  {
1279  pfree(buf);
1280  return NULL;
1281  }
1282 
1283  return buf;
1284 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
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:1025
void pfree(void *pointer)
Definition: mcxt.c:949
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:879
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2173
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:67
int errcode_for_file_access(void)
Definition: elog.c:598
unsigned int uint32
Definition: c.h:296
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
#define ereport(elevel, rest)
Definition: elog.h:122
#define MaxAllocSize
Definition: memutils.h:40
int CloseTransientFile(int fd)
Definition: fd.c:2343
#define WARNING
Definition: elog.h:40
#define stat(a, b)
Definition: win32_port.h:266
#define TWOPHASE_MAGIC
Definition: twophase.c:901
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
#define MAXALIGN(LEN)
Definition: c.h:623
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:73
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:78
#define read(a, b, c)
Definition: win32.h:13

◆ RecordTransactionAbortPrepared()

static void RecordTransactionAbortPrepared ( TransactionId  xid,
int  nchildren,
TransactionId children,
int  nrels,
RelFileNode rels 
)
static

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

2259 {
2260  XLogRecPtr recptr;
2261 
2262  /*
2263  * Catch the scenario where we aborted partway through
2264  * RecordTransactionCommitPrepared ...
2265  */
2266  if (TransactionIdDidCommit(xid))
2267  elog(PANIC, "cannot abort transaction %u, it was already committed",
2268  xid);
2269 
2271 
2272  /*
2273  * Emit the XLOG commit record. Note that we mark 2PC aborts as
2274  * potentially having AccessExclusiveLocks since we don't know whether or
2275  * not they do.
2276  */
2278  nchildren, children,
2279  nrels, rels,
2281  xid);
2282 
2283  /* Always flush, since we're about to remove the 2PC state file */
2284  XLogFlush(recptr);
2285 
2286  /*
2287  * Mark the transaction aborted in clog. This is not absolutely necessary
2288  * but we may as well do it while we are here.
2289  */
2290  TransactionIdAbortTree(xid, nchildren, children);
2291 
2292  END_CRIT_SECTION();
2293 
2294  /*
2295  * Wait for synchronous replication, if required.
2296  *
2297  * Note that at this stage we have marked clog, but still show as running
2298  * in the procarray and continue to hold locks.
2299  */
2300  SyncRepWaitForLSN(recptr, false);
2301 }
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:290
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:146
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
#define START_CRIT_SECTION()
Definition: miscadmin.h:131
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define PANIC
Definition: elog.h:53
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2763
XLogRecPtr XactLogAbortRecord(TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileNode *rels, int xactflags, TransactionId twophase_xid)
Definition: xact.c:5401
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:92
int MyXactFlags
Definition: xact.c:118
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define elog
Definition: elog.h:219

◆ RecordTransactionCommitPrepared()

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

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

2169 {
2170  XLogRecPtr recptr;
2171  TimestampTz committs = GetCurrentTimestamp();
2172  bool replorigin;
2173 
2174  /*
2175  * Are we using the replication origins feature? Or, in other words, are
2176  * we replaying remote actions?
2177  */
2178  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2180 
2182 
2183  /* See notes in RecordTransactionCommit */
2184  MyPgXact->delayChkpt = true;
2185 
2186  /*
2187  * Emit the XLOG commit record. Note that we mark 2PC commits as
2188  * potentially having AccessExclusiveLocks since we don't know whether or
2189  * not they do.
2190  */
2191  recptr = XactLogCommitRecord(committs,
2192  nchildren, children, nrels, rels,
2193  ninvalmsgs, invalmsgs,
2194  initfileinval, false,
2196  xid);
2197 
2198 
2199  if (replorigin)
2200  /* Move LSNs forward for this replication origin */
2202  XactLastRecEnd);
2203 
2204  /*
2205  * Record commit timestamp. The value comes from plain commit timestamp
2206  * if replorigin is not enabled, or replorigin already set a value for us
2207  * in replorigin_session_origin_timestamp otherwise.
2208  *
2209  * We don't need to WAL-log anything here, as the commit record written
2210  * above already contains the data.
2211  */
2212  if (!replorigin || replorigin_session_origin_timestamp == 0)
2214 
2215  TransactionTreeSetCommitTsData(xid, nchildren, children,
2217  replorigin_session_origin, false);
2218 
2219  /*
2220  * We don't currently try to sleep before flush here ... nor is there any
2221  * support for async commit of a prepared xact (the very idea is probably
2222  * a contradiction)
2223  */
2224 
2225  /* Flush XLOG to disk */
2226  XLogFlush(recptr);
2227 
2228  /* Mark the transaction committed in pg_xact */
2229  TransactionIdCommitTree(xid, nchildren, children);
2230 
2231  /* Checkpoint can proceed now */
2232  MyPgXact->delayChkpt = false;
2233 
2234  END_CRIT_SECTION();
2235 
2236  /*
2237  * Wait for synchronous replication, if required.
2238  *
2239  * Note that at this stage we have marked clog, but still show as running
2240  * in the procarray and continue to hold locks.
2241  */
2242  SyncRepWaitForLSN(recptr, true);
2243 }
#define DoNotReplicateId
Definition: origin.h:35
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
XLogRecPtr XactLastRecEnd
Definition: xlog.c:339
int64 TimestampTz
Definition: timestamp.h:39
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:146
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
#define START_CRIT_SECTION()
Definition: miscadmin.h:131
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2763
PGXACT * MyPgXact
Definition: proc.c:68
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:92
void TransactionIdCommitTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:260
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)
Definition: xact.c:5254
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:156
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:157
bool delayChkpt
Definition: proc.h:232
int MyXactFlags
Definition: xact.c:118
uint64 XLogRecPtr
Definition: xlogdefs.h:21
RepOriginId replorigin_session_origin
Definition: origin.c:155
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1130
#define InvalidRepOriginId
Definition: origin.h:34
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 1911 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().

1912 {
1913  int i;
1914 
1915  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1916  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1917  {
1918  TransactionId xid;
1919  char *buf;
1921  char *bufptr;
1922  TwoPhaseFileHeader *hdr;
1923  TransactionId *subxids;
1924  const char *gid;
1925 
1926  xid = gxact->xid;
1927 
1928  /*
1929  * Reconstruct subtrans state for the transaction --- needed because
1930  * pg_subtrans is not preserved over a restart. Note that we are
1931  * linking all the subtransactions directly to the top-level XID;
1932  * there may originally have been a more complex hierarchy, but
1933  * there's no need to restore that exactly. It's possible that
1934  * SubTransSetParent has been set before, if the prepared transaction
1935  * generated xid assignment records.
1936  */
1937  buf = ProcessTwoPhaseBuffer(xid,
1938  gxact->prepare_start_lsn,
1939  gxact->ondisk, true, false);
1940  if (buf == NULL)
1941  continue;
1942 
1943  ereport(LOG,
1944  (errmsg("recovering prepared transaction %u from shared memory", xid)));
1945 
1946  hdr = (TwoPhaseFileHeader *) buf;
1947  Assert(TransactionIdEquals(hdr->xid, xid));
1948  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1949  gid = (const char *) bufptr;
1950  bufptr += MAXALIGN(hdr->gidlen);
1951  subxids = (TransactionId *) bufptr;
1952  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1953  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1954  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1955  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1956 
1957  /*
1958  * Recreate its GXACT and dummy PGPROC. But, check whether it was
1959  * added in redo and already has a shmem entry for it.
1960  */
1961  MarkAsPreparingGuts(gxact, xid, gid,
1962  hdr->prepared_at,
1963  hdr->owner, hdr->database);
1964 
1965  /* recovered, so reset the flag for entries generated by redo */
1966  gxact->inredo = false;
1967 
1968  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1969  MarkAsPrepared(gxact, true);
1970 
1971  LWLockRelease(TwoPhaseStateLock);
1972 
1973  /*
1974  * Recover other state (notably locks) using resource managers.
1975  */
1977 
1978  /*
1979  * Release locks held by the standby process after we process each
1980  * prepared transaction. As a result, we don't need too many
1981  * additional locks at any one time.
1982  */
1983  if (InHotStandby)
1984  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
1985 
1986  /*
1987  * We're done with recovering this transaction. Clear MyLockedGxact,
1988  * like we do in PrepareTransaction() during normal operation.
1989  */
1991 
1992  pfree(buf);
1993 
1994  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1995  }
1996 
1997  LWLockRelease(TwoPhaseStateLock);
1998 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:445
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1522
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:907
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void pfree(void *pointer)
Definition: mcxt.c:949
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:448
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:510
static char * buf
Definition: pg_test_fsync.c:67
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:676
#define ereport(elevel, rest)
Definition: elog.h:122
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2012
#define Assert(condition)
Definition: c.h:670
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
#define MAXALIGN(LEN)
Definition: c.h:623
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:537
TransactionId xid
Definition: twophase.c:169
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PostPrepare_Twophase(void)
Definition: twophase.c:359
int i
TimestampTz prepared_at
Definition: twophase.c:909

◆ RecreateTwoPhaseFile()

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

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

1571 {
1572  char path[MAXPGPATH];
1573  pg_crc32c statefile_crc;
1574  int fd;
1575 
1576  /* Recompute CRC */
1577  INIT_CRC32C(statefile_crc);
1578  COMP_CRC32C(statefile_crc, content, len);
1579  FIN_CRC32C(statefile_crc);
1580 
1581  TwoPhaseFilePath(path, xid);
1582 
1583  fd = OpenTransientFile(path,
1584  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY);
1585  if (fd < 0)
1586  ereport(ERROR,
1588  errmsg("could not recreate two-phase state file \"%s\": %m",
1589  path)));
1590 
1591  /* Write content and CRC */
1593  if (write(fd, content, len) != len)
1594  {
1596  CloseTransientFile(fd);
1597  ereport(ERROR,
1599  errmsg("could not write two-phase state file: %m")));
1600  }
1601  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1602  {
1604  CloseTransientFile(fd);
1605  ereport(ERROR,
1607  errmsg("could not write two-phase state file: %m")));
1608  }
1610 
1611  /*
1612  * We must fsync the file because the end-of-replay checkpoint will not do
1613  * so, there being no GXACT in shared memory yet to tell it to.
1614  */
1616  if (pg_fsync(fd) != 0)
1617  {
1618  CloseTransientFile(fd);
1619  ereport(ERROR,
1621  errmsg("could not fsync two-phase state file: %m")));
1622  }
1624 
1625  if (CloseTransientFile(fd) != 0)
1626  ereport(ERROR,
1628  errmsg("could not close two-phase state file: %m")));
1629 }
#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:1025
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:879
#define ERROR
Definition: elog.h:43
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2173
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
#define ereport(elevel, rest)
Definition: elog.h:122
int CloseTransientFile(int fd)
Definition: fd.c:2343
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync(int fd)
Definition: fd.c:338
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:73
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:78

◆ RegisterTwoPhaseRecord()

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

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

1166 {
1167  TwoPhaseRecordOnDisk record;
1168 
1169  record.rmid = rmid;
1170  record.info = info;
1171  record.len = len;
1172  save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1173  if (len > 0)
1174  save_state_data(data, len);
1175 }
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:963
TwoPhaseRmgrId rmid
Definition: twophase.c:928

◆ 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:1855
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
GlobalTransaction freeGXacts
Definition: twophase.c:186
GlobalTransaction next
Definition: twophase.c:155
#define ERROR
Definition: elog.h:43
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
#define Assert(condition)
Definition: c.h:670
int i
#define elog
Definition: elog.h:219

◆ RemoveTwoPhaseFile()

static void RemoveTwoPhaseFile ( TransactionId  xid,
bool  giveWarning 
)
static

Definition at line 1550 of file twophase.c.

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

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

1551 {
1552  char path[MAXPGPATH];
1553 
1554  TwoPhaseFilePath(path, xid);
1555  if (unlink(path))
1556  if (errno != ENOENT || giveWarning)
1557  ereport(WARNING,
1559  errmsg("could not remove two-phase state file \"%s\": %m",
1560  path)));
1561 }
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:879
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1733 of file twophase.c.

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

Referenced by StartupXLOG().

1734 {
1735  DIR *cldir;
1736  struct dirent *clde;
1737 
1738  cldir = AllocateDir(TWOPHASE_DIR);
1739  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1740  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1741  {
1742  if (strlen(clde->d_name) == 8 &&
1743  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1744  {
1745  TransactionId xid;
1746  char *buf;
1747 
1748  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1749 
1751  true, false, false);
1752  if (buf == NULL)
1753  continue;
1754 
1756  }
1757  }
1758  LWLockRelease(TwoPhaseStateLock);
1759  FreeDir(cldir);
1760 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TransactionId
Definition: c.h:445
Definition: dirent.h:9
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
Definition: dirent.c:25
static char * buf
Definition: pg_test_fsync.c:67
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2373
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
Definition: twophase.c:2312
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2012
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2439
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
#define TWOPHASE_DIR
Definition: twophase.c:114
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2482

◆ save_state_data()

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

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

964 {
965  uint32 padlen = MAXALIGN(len);
966 
967  if (padlen > records.bytes_free)
968  {
969  records.tail->next = palloc0(sizeof(StateFileChunk));
971  records.tail->len = 0;
972  records.tail->next = NULL;
974 
975  records.bytes_free = Max(padlen, 512);
977  }
978 
979  memcpy(((char *) records.tail->data) + records.tail->len, data, len);
980  records.tail->len += padlen;
981  records.bytes_free -= padlen;
982  records.total_len += padlen;
983 }
StateFileChunk * tail
Definition: twophase.c:947
uint32 num_chunks
Definition: twophase.c:948
char * data
Definition: twophase.c:939
uint32 bytes_free
Definition: twophase.c:949
uint32 len
Definition: twophase.c:940
unsigned int uint32
Definition: c.h:296
static struct xllist records
uint32 total_len
Definition: twophase.c:950
struct StateFileChunk * next
Definition: twophase.c:941
void * palloc0(Size size)
Definition: mcxt.c:877
#define Max(x, y)
Definition: c.h:796
#define MAXALIGN(LEN)
Definition: c.h:623
void * palloc(Size size)
Definition: mcxt.c:848

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

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

1871 {
1872  int i;
1873 
1874  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1875  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1876  {
1877  TransactionId xid;
1878  char *buf;
1880 
1881  Assert(gxact->inredo);
1882 
1883  xid = gxact->xid;
1884 
1885  buf = ProcessTwoPhaseBuffer(xid,
1886  gxact->prepare_start_lsn,
1887  gxact->ondisk, false, false);
1888  if (buf != NULL)
1889  pfree(buf);
1890  }
1891  LWLockRelease(TwoPhaseStateLock);
1892 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
uint32 TransactionId
Definition: c.h:445
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void pfree(void *pointer)
Definition: mcxt.c:949
static char * buf
Definition: pg_test_fsync.c:67
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2012
#define Assert(condition)
Definition: c.h:670
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
TransactionId xid
Definition: twophase.c:169
int i

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1340 of file twophase.c.

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

1341 {
1342  char *buf;
1343  TwoPhaseFileHeader *hdr;
1344  bool result;
1345 
1347 
1348  if (max_prepared_xacts <= 0)
1349  return false; /* nothing to do */
1350 
1351  /* Read and validate file */
1352  buf = ReadTwoPhaseFile(xid, false);
1353  if (buf == NULL)
1354  return false;
1355 
1356  /* Check header also */
1357  hdr = (TwoPhaseFileHeader *) buf;
1358  result = TransactionIdEquals(hdr->xid, xid);
1359  pfree(buf);
1360 
1361  return result;
1362 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
TransactionId xid
Definition: twophase.c:907
void pfree(void *pointer)
Definition: mcxt.c:949
int max_prepared_xacts
Definition: twophase.c:117
static char * buf
Definition: pg_test_fsync.c:67
static char * ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
Definition: twophase.c:1185
#define Assert(condition)
Definition: c.h:670
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

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

992 {
993  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
994  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
995  TransactionId xid = pgxact->xid;
996  TwoPhaseFileHeader hdr;
997  TransactionId *children;
998  RelFileNode *commitrels;
999  RelFileNode *abortrels;
1000  SharedInvalidationMessage *invalmsgs;
1001 
1002  /* Initialize linked list */
1003  records.head = palloc0(sizeof(StateFileChunk));
1004  records.head->len = 0;
1005  records.head->next = NULL;
1006 
1007  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1009 
1011  records.num_chunks = 1;
1012 
1013  records.total_len = 0;
1014 
1015  /* Create header */
1016  hdr.magic = TWOPHASE_MAGIC;
1017  hdr.total_len = 0; /* EndPrepare will fill this in */
1018  hdr.xid = xid;
1019  hdr.database = proc->databaseId;
1020  hdr.prepared_at = gxact->prepared_at;
1021  hdr.owner = gxact->owner;
1022  hdr.nsubxacts = xactGetCommittedChildren(&children);
1023  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1024  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1026  &hdr.initfileinval);
1027  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1028 
1029  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1030  save_state_data(gxact->gid, hdr.gidlen);
1031 
1032  /*
1033  * Add the additional info about subxacts, deletable files and cache
1034  * invalidation messages.
1035  */
1036  if (hdr.nsubxacts > 0)
1037  {
1038  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1039  /* While we have the child-xact data, stuff it in the gxact too */
1040  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1041  }
1042  if (hdr.ncommitrels > 0)
1043  {
1044  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1045  pfree(commitrels);
1046  }
1047  if (hdr.nabortrels > 0)
1048  {
1049  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1050  pfree(abortrels);
1051  }
1052  if (hdr.ninvalmsgs > 0)
1053  {
1054  save_state_data(invalmsgs,
1055  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1056  pfree(invalmsgs);
1057  }
1058 }
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5230
uint32 TransactionId
Definition: c.h:445
Definition: proc.h:219
PGXACT * allPgXact
Definition: proc.h:246
TransactionId xid
Definition: proc.h:221
StateFileChunk * tail
Definition: twophase.c:947
PROC_HDR * ProcGlobal
Definition: proc.c:80
TransactionId xid
Definition: twophase.c:907
uint32 num_chunks
Definition: twophase.c:948
char gid[GIDSIZE]
Definition: twophase.c:176
char * data
Definition: twophase.c:939
void pfree(void *pointer)
Definition: mcxt.c:949
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:510
uint32 bytes_free
Definition: twophase.c:949
int smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
Definition: storage.c:389
uint32 len
Definition: twophase.c:940
Oid databaseId
Definition: proc.h:114
static struct xllist records
uint32 total_len
Definition: twophase.c:950
struct StateFileChunk * next
Definition: twophase.c:941
void * palloc0(Size size)
Definition: mcxt.c:877
#define TWOPHASE_MAGIC
Definition: twophase.c:901
#define Max(x, y)
Definition: c.h:796
StateFileChunk * head
Definition: twophase.c:946
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:963
TimestampTz prepared_at
Definition: twophase.c:158
void * palloc(Size size)
Definition: mcxt.c:848
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:816
PGPROC * allProcs
Definition: proc.h:244
TimestampTz prepared_at
Definition: twophase.c:909
Definition: proc.h:95

◆ TwoPhaseGetDummyBackendId()

BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid)

Definition at line 856 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

857 {
858  GlobalTransaction gxact = TwoPhaseGetGXact(xid);
859 
860  return gxact->dummyBackendId;
861 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid)
Definition: twophase.c:807
BackendId dummyBackendId
Definition: twophase.c:157

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid)

Definition at line 868 of file twophase.c.

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

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

869 {
870  GlobalTransaction gxact = TwoPhaseGetGXact(xid);
871 
872  return &ProcGlobal->allProcs[gxact->pgprocno];
873 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid)
Definition: twophase.c:807
PROC_HDR * ProcGlobal
Definition: proc.c:80
PGPROC * allProcs
Definition: proc.h:244

◆ TwoPhaseGetGXact()

static GlobalTransaction TwoPhaseGetGXact ( TransactionId  xid)
static

Definition at line 807 of file twophase.c.

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

Referenced by TwoPhaseGetDummyBackendId(), and TwoPhaseGetDummyProc().

808 {
809  GlobalTransaction result = NULL;
810  int i;
811 
812  static TransactionId cached_xid = InvalidTransactionId;
813  static GlobalTransaction cached_gxact = NULL;
814 
815  /*
816  * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
817  * repeatedly for the same XID. We can save work with a simple cache.
818  */
819  if (xid == cached_xid)
820  return cached_gxact;
821 
822  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
823 
824  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
825  {
827  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
828 
829  if (pgxact->xid == xid)
830  {
831  result = gxact;
832  break;
833  }
834  }
835 
836  LWLockRelease(TwoPhaseStateLock);
837 
838  if (result == NULL) /* should not happen */
839  elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
840 
841  cached_xid = xid;
842  cached_gxact = result;
843 
844  return result;
845 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
uint32 TransactionId
Definition: c.h:445
Definition: proc.h:219
PGXACT * allPgXact
Definition: proc.h:246
TransactionId xid
Definition: proc.h:221
PROC_HDR * ProcGlobal
Definition: proc.c:80
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define ERROR
Definition: elog.h:43
#define InvalidTransactionId
Definition: transam.h:31
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
int i
#define elog
Definition: elog.h:219

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

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

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

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 238 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores(), and TwoPhaseShmemInit().

239 {
240  Size size;
241 
242  /* Need the fixed struct, the array of pointers, and the GTD structs */
243  size = offsetof(TwoPhaseStateData, prepXacts);
244  size = add_size(size, mul_size(max_prepared_xacts,
245  sizeof(GlobalTransaction)));
246  size = MAXALIGN(size);
247  size = add_size(size, mul_size(max_prepared_xacts,
248  sizeof(GlobalTransactionData)));
249 
250  return size;
251 }
int max_prepared_xacts
Definition: twophase.c:117
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:404
#define MAXALIGN(LEN)
Definition: c.h:623
#define offsetof(type, field)
Definition: c.h:593

◆ XlogReadTwoPhaseData()

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

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

1297 {
1298  XLogRecord *record;
1299  XLogReaderState *xlogreader;
1300  char *errormsg;
1301 
1303  NULL);
1304  if (!xlogreader)
1305  ereport(ERROR,
1306  (errcode(ERRCODE_OUT_OF_MEMORY),
1307  errmsg("out of memory"),
1308  errdetail("Failed while allocating a WAL reading processor.")));
1309 
1310  record = XLogReadRecord(xlogreader, lsn, &errormsg);
1311  if (record == NULL)
1312  ereport(ERROR,
1314  errmsg("could not read two-phase state from WAL at %X/%X",
1315  (uint32) (lsn >> 32),
1316  (uint32) lsn)));
1317 
1318  if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1320  ereport(ERROR,
1322  errmsg("expected two-phase state data is not present in WAL at %X/%X",
1323  (uint32) (lsn >> 32),
1324  (uint32) lsn)));
1325 
1326  if (len != NULL)
1327  *len = XLogRecGetDataLen(xlogreader);
1328 
1329  *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1330  memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1331 
1332  XLogReaderFree(xlogreader);
1333 }
#define XLOG_XACT_PREPARE
Definition: xact.h:134
int wal_segment_size
Definition: xlog.c:113
int errcode(int sqlerrcode)
Definition: elog.c:575
XLogRecord * XLogReadRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
Definition: xlogreader.c:195
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page, TimeLineID *pageTLI)
Definition: xlogutils.c:910
#define XLogRecGetData(decoder)
Definition: xlogreader.h:226
#define ERROR
Definition: elog.h:43
#define XLogRecGetDataLen(decoder)
Definition: xlogreader.h:227
static char * buf
Definition: pg_test_fsync.c:67
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
unsigned int uint32
Definition: c.h:296
#define ereport(elevel, rest)
Definition: elog.h:122
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:222
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:127
XLogReaderState * XLogReaderAllocate(int wal_segment_size, XLogPageReadCB pagereadfunc, void *private_data)
Definition: xlogreader.c:67
#define XLOG_XACT_OPMASK
Definition: xact.h:143
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:223

Variable Documentation

◆ max_prepared_xacts

◆ MyLockedGxact

GlobalTransaction MyLockedGxact = NULL
static

Definition at line 203 of file twophase.c.

◆ records

struct xllist records
static

◆ twophaseExitRegistered

bool twophaseExitRegistered = false
static

Definition at line 205 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseState

TwoPhaseStateData* TwoPhaseState
static

Definition at line 195 of file twophase.c.