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

Go to the source code of this file.

Data Structures

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

Macros

#define TWOPHASE_DIR   "pg_twophase"
 
#define TwoPhaseFilePath(path, xid)   snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
 
#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */
 

Typedefs

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

Functions

static void RecordTransactionCommitPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval, const char *gid)
 
static void RecordTransactionAbortPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, const char *gid)
 
static void ProcessRecords (char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
 
static void RemoveGXact (GlobalTransaction gxact)
 
static void XlogReadTwoPhaseData (XLogRecPtr lsn, char **buf, int *len)
 
static char * ProcessTwoPhaseBuffer (TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
 
static void MarkAsPreparingGuts (GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
static void RemoveTwoPhaseFile (TransactionId xid, bool giveWarning)
 
static void RecreateTwoPhaseFile (TransactionId xid, void *content, int len)
 
Size TwoPhaseShmemSize (void)
 
void TwoPhaseShmemInit (void)
 
static void AtProcExit_Twophase (int code, Datum arg)
 
void AtAbort_Twophase (void)
 
void PostPrepare_Twophase (void)
 
GlobalTransaction MarkAsPreparing (TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
static void GXactLoadSubxactData (GlobalTransaction gxact, int nsubxacts, TransactionId *children)
 
static void MarkAsPrepared (GlobalTransaction gxact, bool lock_held)
 
static GlobalTransaction LockGXact (const char *gid, Oid user)
 
static int GetPreparedTransactionList (GlobalTransaction *gxacts)
 
Datum pg_prepared_xact (PG_FUNCTION_ARGS)
 
static GlobalTransaction TwoPhaseGetGXact (TransactionId xid, bool lock_held)
 
BackendId TwoPhaseGetDummyBackendId (TransactionId xid, bool lock_held)
 
PGPROCTwoPhaseGetDummyProc (TransactionId xid, bool lock_held)
 
static void save_state_data (const void *data, uint32 len)
 
void StartPrepare (GlobalTransaction gxact)
 
void EndPrepare (GlobalTransaction gxact)
 
void RegisterTwoPhaseRecord (TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
 
static char * ReadTwoPhaseFile (TransactionId xid, bool missing_ok)
 
bool StandbyTransactionIdIsPrepared (TransactionId xid)
 
void FinishPreparedTransaction (const char *gid, bool isCommit)
 
void CheckPointTwoPhase (XLogRecPtr redo_horizon)
 
void restoreTwoPhaseData (void)
 
TransactionId PrescanPreparedTransactions (TransactionId **xids_p, int *nxids_p)
 
void StandbyRecoverPreparedTransactions (void)
 
void RecoverPreparedTransactions (void)
 
void PrepareRedoAdd (char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
 
void PrepareRedoRemove (TransactionId xid, bool giveWarning)
 
bool LookupGXact (const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
 

Variables

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

Macro Definition Documentation

◆ TWOPHASE_DIR

#define TWOPHASE_DIR   "pg_twophase"

Definition at line 114 of file twophase.c.

Referenced by CheckPointTwoPhase(), and restoreTwoPhaseData().

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */

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

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

Typedef Documentation

◆ GlobalTransactionData

◆ StateFileChunk

◆ TwoPhaseFileHeader

Definition at line 909 of file twophase.c.

◆ TwoPhaseRecordOnDisk

◆ TwoPhaseStateData

Function Documentation

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 317 of file twophase.c.

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

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

◆ AtProcExit_Twophase()

static void AtProcExit_Twophase ( int  code,
Datum  arg 
)
static

Definition at line 307 of file twophase.c.

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

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

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

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

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

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1055 of file twophase.c.

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

Referenced by PrepareTransaction().

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

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1409 of file twophase.c.

References PROC_HDR::allProcs, Assert, AtEOXact_PgStat(), buf, DropRelationFiles(), GetUserId(), xl_xact_prepare::gidlen, HOLD_INTERRUPTS, xl_xact_prepare::initfileinval, LockGXact(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, xl_xact_prepare::nabortrels, xl_xact_prepare::ncommitrels, xl_xact_prepare::ninvalmsgs, xl_xact_prepare::nsubxacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::pgprocno, PredicateLockTwoPhaseFinish(), GlobalTransactionData::prepare_start_lsn, ProcArrayRemove(), ProcessRecords(), ProcGlobal, ReadTwoPhaseFile(), RecordTransactionAbortPrepared(), RecordTransactionCommitPrepared(), RelationCacheInitFilePostInvalidate(), RelationCacheInitFilePreInvalidate(), RemoveGXact(), RemoveTwoPhaseFile(), RESUME_INTERRUPTS, SendSharedInvalidMessages(), TransactionIdEquals, TransactionIdLatest(), twophase_postabort_callbacks, twophase_postcommit_callbacks, GlobalTransactionData::valid, GlobalTransactionData::xid, xl_xact_prepare::xid, and XlogReadTwoPhaseData().

Referenced by apply_handle_commit_prepared(), apply_handle_rollback_prepared(), and standard_ProcessUtility().

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

◆ GetPreparedTransactionList()

static int GetPreparedTransactionList ( GlobalTransaction gxacts)
static

Definition at line 670 of file twophase.c.

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

Referenced by pg_prepared_xact().

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

◆ GXactLoadSubxactData()

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

Definition at line 508 of file twophase.c.

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

Referenced by RecoverPreparedTransactions(), and StartPrepare().

510 {
511  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
512 
513  /* We need no extra lock since the GXACT isn't valid yet */
514  if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
515  {
516  proc->subxidStatus.overflowed = true;
517  nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
518  }
519  if (nsubxacts > 0)
520  {
521  memcpy(proc->subxids.xids, children,
522  nsubxacts * sizeof(TransactionId));
523  proc->subxidStatus.count = nsubxacts;
524  }
525 }
uint32 TransactionId
Definition: c.h:587
PROC_HDR * ProcGlobal
Definition: proc.c:80
XidCacheStatus subxidStatus
Definition: proc.h:210
bool overflowed
Definition: proc.h:43
struct XidCache subxids
Definition: proc.h:212
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:36
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:48
uint8 count
Definition: proc.h:41
PGPROC * allProcs
Definition: proc.h:318
Definition: proc.h:121

◆ LockGXact()

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

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

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

◆ LookupGXact()

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

Definition at line 2478 of file twophase.c.

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

Referenced by apply_handle_rollback_prepared().

2480 {
2481  int i;
2482  bool found = false;
2483 
2484  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
2485  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2486  {
2488 
2489  /* Ignore not-yet-valid GIDs. */
2490  if (gxact->valid && strcmp(gxact->gid, gid) == 0)
2491  {
2492  char *buf;
2493  TwoPhaseFileHeader *hdr;
2494 
2495  /*
2496  * We are not expecting collisions of GXACTs (same gid) between
2497  * publisher and subscribers, so we perform all I/O while holding
2498  * TwoPhaseStateLock for simplicity.
2499  *
2500  * To move the I/O out of the lock, we need to ensure that no
2501  * other backend commits the prepared xact in the meantime. We can
2502  * do this optimization if we encounter many collisions in GID
2503  * between publisher and subscriber.
2504  */
2505  if (gxact->ondisk)
2506  buf = ReadTwoPhaseFile(gxact->xid, false);
2507  else
2508  {
2509  Assert(gxact->prepare_start_lsn);
2510  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
2511  }
2512 
2513  hdr = (TwoPhaseFileHeader *) buf;
2514 
2515  if (hdr->origin_lsn == prepare_end_lsn &&
2516  hdr->origin_timestamp == origin_prepare_timestamp)
2517  {
2518  found = true;
2519  pfree(buf);
2520  break;
2521  }
2522 
2523  pfree(buf);
2524  }
2525  }
2526  LWLockRelease(TwoPhaseStateLock);
2527  return found;
2528 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1205
char gid[GIDSIZE]
Definition: twophase.c:172
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void pfree(void *pointer)
Definition: mcxt.c:1169
static char * buf
Definition: pg_test_fsync.c:68
XLogRecPtr origin_lsn
Definition: xact.h:314
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define Assert(condition)
Definition: c.h:804
TimestampTz origin_timestamp
Definition: xact.h:315
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
TransactionId xid
Definition: twophase.c:165
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1326
int i

◆ MarkAsPrepared()

static void MarkAsPrepared ( GlobalTransaction  gxact,
bool  lock_held 
)
static

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

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

◆ MarkAsPreparing()

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

Definition at line 372 of file twophase.c.

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

Referenced by PrepareTransaction().

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

◆ MarkAsPreparingGuts()

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

Definition at line 446 of file twophase.c.

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

Referenced by MarkAsPreparing(), and RecoverPreparedTransactions().

448 {
449  PGPROC *proc;
450  int i;
451 
452  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
453 
454  Assert(gxact != NULL);
455  proc = &ProcGlobal->allProcs[gxact->pgprocno];
456 
457  /* Initialize the PGPROC entry */
458  MemSet(proc, 0, sizeof(PGPROC));
459  proc->pgprocno = gxact->pgprocno;
460  SHMQueueElemInit(&(proc->links));
462  /* We set up the gxact's VXID as InvalidBackendId/XID */
463  proc->lxid = (LocalTransactionId) xid;
464  proc->xid = xid;
465  Assert(proc->xmin == InvalidTransactionId);
466  proc->delayChkpt = false;
467  proc->statusFlags = 0;
468  proc->pid = 0;
469  proc->backendId = InvalidBackendId;
470  proc->databaseId = databaseid;
471  proc->roleId = owner;
472  proc->tempNamespaceId = InvalidOid;
473  proc->isBackgroundWorker = false;
474  proc->lwWaiting = false;
475  proc->lwWaitMode = 0;
476  proc->waitLock = NULL;
477  proc->waitProcLock = NULL;
478  pg_atomic_init_u64(&proc->waitStart, 0);
479  for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
480  SHMQueueInit(&(proc->myProcLocks[i]));
481  /* subxid data must be filled later by GXactLoadSubxactData */
482  proc->subxidStatus.overflowed = false;
483  proc->subxidStatus.count = 0;
484 
485  gxact->prepared_at = prepared_at;
486  gxact->xid = xid;
487  gxact->owner = owner;
488  gxact->locking_backend = MyBackendId;
489  gxact->valid = false;
490  gxact->inredo = false;
491  strcpy(gxact->gid, gid);
492 
493  /*
494  * Remember that we have this GlobalTransaction entry locked for us. If we
495  * abort after this, we must release it.
496  */
497  MyLockedGxact = gxact;
498 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1937
BackendId MyBackendId
Definition: globals.c:84
BackendId backendId
Definition: proc.h:153
Oid tempNamespaceId
Definition: proc.h:157
SHM_QUEUE links
Definition: proc.h:124
bool lwWaiting
Definition: proc.h:170
Oid roleId
Definition: proc.h:155
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:1008
uint8 statusFlags
Definition: proc.h:189
uint8 lwWaitMode
Definition: proc.h:171
ProcWaitStatus waitStatus
Definition: proc.h:128
XidCacheStatus subxidStatus
Definition: proc.h:210
char gid[GIDSIZE]
Definition: twophase.c:172
bool overflowed
Definition: proc.h:43
BackendId locking_backend
Definition: twophase.c:168
bool isBackgroundWorker
Definition: proc.h:160
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:415
bool delayChkpt
Definition: proc.h:187
TransactionId xmin
Definition: proc.h:138
PROCLOCK * waitProcLock
Definition: proc.h:180
#define InvalidTransactionId
Definition: transam.h:31
Oid databaseId
Definition: proc.h:154
uint32 LocalTransactionId
Definition: c.h:589
LOCK * waitLock
Definition: proc.h:179
#define InvalidBackendId
Definition: backendid.h:23
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:804
uint8 count
Definition: proc.h:41
TransactionId xid
Definition: proc.h:133
TransactionId xid
Definition: twophase.c:165
TimestampTz prepared_at
Definition: twophase.c:154
void SHMQueueElemInit(SHM_QUEUE *queue)
Definition: shmqueue.c:57
int pgprocno
Definition: proc.h:150
void SHMQueueInit(SHM_QUEUE *queue)
Definition: shmqueue.c:36
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
int i
PGPROC * allProcs
Definition: proc.h:318
SHM_QUEUE myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:208
pg_atomic_uint64 waitStart
Definition: proc.h:184
Definition: proc.h:121
int pid
Definition: proc.h:146
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:87
LocalTransactionId lxid
Definition: proc.h:143

◆ pg_prepared_xact()

Datum pg_prepared_xact ( PG_FUNCTION_ARGS  )

Definition at line 715 of file twophase.c.

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

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

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

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

◆ PrepareRedoAdd()

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

Definition at line 2356 of file twophase.c.

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

Referenced by restoreTwoPhaseData(), and xact_redo().

2358 {
2360  char *bufptr;
2361  const char *gid;
2362  GlobalTransaction gxact;
2363 
2364  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2366 
2367  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2368  gid = (const char *) bufptr;
2369 
2370  /*
2371  * Reserve the GID for the given transaction in the redo code path.
2372  *
2373  * This creates a gxact struct and puts it into the active array.
2374  *
2375  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2376  * shared memory. Hence, we only fill up the bare minimum contents here.
2377  * The gxact also gets marked with gxact->inredo set to true to indicate
2378  * that it got added in the redo phase
2379  */
2380 
2381  /* Get a free gxact from the freelist */
2382  if (TwoPhaseState->freeGXacts == NULL)
2383  ereport(ERROR,
2384  (errcode(ERRCODE_OUT_OF_MEMORY),
2385  errmsg("maximum number of prepared transactions reached"),
2386  errhint("Increase max_prepared_transactions (currently %d).",
2387  max_prepared_xacts)));
2388  gxact = TwoPhaseState->freeGXacts;
2389  TwoPhaseState->freeGXacts = gxact->next;
2390 
2391  gxact->prepared_at = hdr->prepared_at;
2392  gxact->prepare_start_lsn = start_lsn;
2393  gxact->prepare_end_lsn = end_lsn;
2394  gxact->xid = hdr->xid;
2395  gxact->owner = hdr->owner;
2397  gxact->valid = false;
2398  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2399  gxact->inredo = true; /* yes, added in redo */
2400  strcpy(gxact->gid, gid);
2401 
2402  /* And insert it into the active array */
2405 
2406  if (origin_id != InvalidRepOriginId)
2407  {
2408  /* recover apply progress */
2409  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2410  false /* backward */ , false /* WAL */ );
2411  }
2412 
2413  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2414 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1937
int errhint(const char *fmt,...)
Definition: elog.c:1156
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
GlobalTransaction freeGXacts
Definition: twophase.c:182
int errcode(int sqlerrcode)
Definition: elog.c:698
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:872
GlobalTransaction next
Definition: twophase.c:151
bool RecoveryInProgress(void)
Definition: xlog.c:8248
char gid[GIDSIZE]
Definition: twophase.c:172
BackendId locking_backend
Definition: twophase.c:168
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
#define ERROR
Definition: elog.h:46
int max_prepared_xacts
Definition: twophase.c:117
#define DEBUG2
Definition: elog.h:24
static char * buf
Definition: pg_test_fsync.c:68
XLogRecPtr origin_lsn
Definition: xact.h:314
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define InvalidBackendId
Definition: backendid.h:23
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
#define MAXALIGN(LEN)
Definition: c.h:757
TransactionId xid
Definition: xact.h:304
#define InvalidRepOriginId
Definition: origin.h:33
TransactionId xid
Definition: twophase.c:165
TimestampTz prepared_at
Definition: twophase.c:154
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
TimestampTz prepared_at
Definition: xact.h:306
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

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

2427 {
2428  GlobalTransaction gxact = NULL;
2429  int i;
2430  bool found = false;
2431 
2432  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2434 
2435  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2436  {
2437  gxact = TwoPhaseState->prepXacts[i];
2438 
2439  if (gxact->xid == xid)
2440  {
2441  Assert(gxact->inredo);
2442  found = true;
2443  break;
2444  }
2445  }
2446 
2447  /*
2448  * Just leave if there is nothing, this is expected during WAL replay.
2449  */
2450  if (!found)
2451  return;
2452 
2453  /*
2454  * And now we can clean up any files we may have left.
2455  */
2456  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2457  if (gxact->ondisk)
2458  RemoveTwoPhaseFile(xid, giveWarning);
2459  RemoveGXact(gxact);
2460 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1937
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
bool RecoveryInProgress(void)
Definition: xlog.c:8248
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:632
#define DEBUG2
Definition: elog.h:24
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1604
#define Assert(condition)
Definition: c.h:804
TransactionId xid
Definition: twophase.c:165
#define elog(elevel,...)
Definition: elog.h:232
int i

◆ PrescanPreparedTransactions()

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

Definition at line 1847 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(), GlobalTransactionData::xid, and XidFromFullTransactionId.

Referenced by StartupXLOG(), and xlog_redo().

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

◆ ProcessRecords()

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

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

1578 {
1579  for (;;)
1580  {
1581  TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1582 
1583  Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1584  if (record->rmid == TWOPHASE_RM_END_ID)
1585  break;
1586 
1587  bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1588 
1589  if (callbacks[record->rmid] != NULL)
1590  callbacks[record->rmid] (xid, record->info,
1591  (void *) bufptr, record->len);
1592 
1593  bufptr += MAXALIGN(record->len);
1594  }
1595 }
#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:804
#define MAXALIGN(LEN)
Definition: c.h:757
TwoPhaseRmgrId rmid
Definition: twophase.c:920

◆ ProcessTwoPhaseBuffer()

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

Definition at line 2070 of file twophase.c.

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

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

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

◆ ReadTwoPhaseFile()

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

Definition at line 1205 of file twophase.c.

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

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

1206 {
1207  char path[MAXPGPATH];
1208  char *buf;
1209  TwoPhaseFileHeader *hdr;
1210  int fd;
1211  struct stat stat;
1212  uint32 crc_offset;
1213  pg_crc32c calc_crc,
1214  file_crc;
1215  int r;
1216 
1217  TwoPhaseFilePath(path, xid);
1218 
1219  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
1220  if (fd < 0)
1221  {
1222  if (missing_ok && errno == ENOENT)
1223  return NULL;
1224 
1225  ereport(ERROR,
1227  errmsg("could not open file \"%s\": %m", path)));
1228  }
1229 
1230  /*
1231  * Check file length. We can determine a lower bound pretty easily. We
1232  * set an upper bound to avoid palloc() failure on a corrupt file, though
1233  * we can't guarantee that we won't get an out of memory error anyway,
1234  * even on a valid file.
1235  */
1236  if (fstat(fd, &stat))
1237  ereport(ERROR,
1239  errmsg("could not stat file \"%s\": %m", path)));
1240 
1241  if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1242  MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1243  sizeof(pg_crc32c)) ||
1245  ereport(ERROR,
1247  errmsg_plural("incorrect size of file \"%s\": %lld byte",
1248  "incorrect size of file \"%s\": %lld bytes",
1249  (long long int) stat.st_size, path,
1250  (long long int) stat.st_size)));
1251 
1252  crc_offset = stat.st_size - sizeof(pg_crc32c);
1253  if (crc_offset != MAXALIGN(crc_offset))
1254  ereport(ERROR,
1256  errmsg("incorrect alignment of CRC offset for file \"%s\"",
1257  path)));
1258 
1259  /*
1260  * OK, slurp in the file.
1261  */
1262  buf = (char *) palloc(stat.st_size);
1263 
1265  r = read(fd, buf, stat.st_size);
1266  if (r != stat.st_size)
1267  {
1268  if (r < 0)
1269  ereport(ERROR,
1271  errmsg("could not read file \"%s\": %m", path)));
1272  else
1273  ereport(ERROR,
1274  (errmsg("could not read file \"%s\": read %d of %lld",
1275  path, r, (long long int) stat.st_size)));
1276  }
1277 
1279 
1280  if (CloseTransientFile(fd) != 0)
1281  ereport(ERROR,
1283  errmsg("could not close file \"%s\": %m", path)));
1284 
1285  hdr = (TwoPhaseFileHeader *) buf;
1286  if (hdr->magic != TWOPHASE_MAGIC)
1287  ereport(ERROR,
1289  errmsg("invalid magic number stored in file \"%s\"",
1290  path)));
1291 
1292  if (hdr->total_len != stat.st_size)
1293  ereport(ERROR,
1295  errmsg("invalid size stored in file \"%s\"",
1296  path)));
1297 
1298  INIT_CRC32C(calc_crc);
1299  COMP_CRC32C(calc_crc, buf, crc_offset);
1300  FIN_CRC32C(calc_crc);
1301 
1302  file_crc = *((pg_crc32c *) (buf + crc_offset));
1303 
1304  if (!EQ_CRC32C(calc_crc, file_crc))
1305  ereport(ERROR,
1307  errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
1308  path)));
1309 
1310  return buf;
1311 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1019
uint32 pg_crc32c
Definition: pg_crc32c.h:38
int errcode(int sqlerrcode)
Definition: elog.c:698
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1271
#define fstat
Definition: win32_port.h:274
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:885
#define ERROR
Definition: elog.h:46
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2467
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:68
int errcode_for_file_access(void)
Definition: elog.c:721
uint32 total_len
Definition: xact.h:303
unsigned int uint32
Definition: c.h:441
__int64 st_size
Definition: win32_port.h:265
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:262
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:45
#define MaxAllocSize
Definition: memutils.h:40
int CloseTransientFile(int fd)
Definition: fd.c:2644
#define TWOPHASE_MAGIC
Definition: twophase.c:907
#define ereport(elevel,...)
Definition: elog.h:157
#define MAXALIGN(LEN)
Definition: c.h:757
uint32 magic
Definition: xact.h:302
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
#define read(a, b, c)
Definition: win32.h:13

◆ RecordTransactionAbortPrepared()

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

Definition at line 2284 of file twophase.c.

References DoNotReplicateId, elog, END_CRIT_SECTION, GetCurrentTimestamp(), InvalidRepOriginId, MyXactFlags, PANIC, replorigin_session_advance(), replorigin_session_origin, replorigin_session_origin_lsn, START_CRIT_SECTION, SyncRepWaitForLSN(), TransactionIdAbortTree(), TransactionIdDidCommit(), XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK, XactLastRecEnd, XactLogAbortRecord(), and XLogFlush().

Referenced by FinishPreparedTransaction().

2290 {
2291  XLogRecPtr recptr;
2292  bool replorigin;
2293 
2294  /*
2295  * Are we using the replication origins feature? Or, in other words, are
2296  * we replaying remote actions?
2297  */
2298  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2300 
2301  /*
2302  * Catch the scenario where we aborted partway through
2303  * RecordTransactionCommitPrepared ...
2304  */
2305  if (TransactionIdDidCommit(xid))
2306  elog(PANIC, "cannot abort transaction %u, it was already committed",
2307  xid);
2308 
2310 
2311  /*
2312  * Emit the XLOG commit record. Note that we mark 2PC aborts as
2313  * potentially having AccessExclusiveLocks since we don't know whether or
2314  * not they do.
2315  */
2317  nchildren, children,
2318  nrels, rels,
2320  xid, gid);
2321 
2322  if (replorigin)
2323  /* Move LSNs forward for this replication origin */
2325  XactLastRecEnd);
2326 
2327  /* Always flush, since we're about to remove the 2PC state file */
2328  XLogFlush(recptr);
2329 
2330  /*
2331  * Mark the transaction aborted in clog. This is not absolutely necessary
2332  * but we may as well do it while we are here.
2333  */
2334  TransactionIdAbortTree(xid, nchildren, children);
2335 
2336  END_CRIT_SECTION();
2337 
2338  /*
2339  * Wait for synchronous replication, if required.
2340  *
2341  * Note that at this stage we have marked clog, but still show as running
2342  * in the procarray and continue to hold locks.
2343  */
2344  SyncRepWaitForLSN(recptr, false);
2345 }
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:290
XLogRecPtr XactLogAbortRecord(TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileNode *rels, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition: xact.c:5653
#define DoNotReplicateId
Definition: origin.h:34
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
XLogRecPtr XactLastRecEnd
Definition: xlog.c:363
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:148
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define PANIC
Definition: elog.h:50
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2881
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:108
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:155
int MyXactFlags
Definition: xact.c:132
uint64 XLogRecPtr
Definition: xlogdefs.h:21
RepOriginId replorigin_session_origin
Definition: origin.c:154
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1188
#define InvalidRepOriginId
Definition: origin.h:33
#define elog(elevel,...)
Definition: elog.h:232

◆ RecordTransactionCommitPrepared()

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

Definition at line 2190 of file twophase.c.

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

Referenced by FinishPreparedTransaction().

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

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 1969 of file twophase.c.

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

Referenced by StartupXLOG().

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

◆ RecreateTwoPhaseFile()

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

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

1624 {
1625  char path[MAXPGPATH];
1626  pg_crc32c statefile_crc;
1627  int fd;
1628 
1629  /* Recompute CRC */
1630  INIT_CRC32C(statefile_crc);
1631  COMP_CRC32C(statefile_crc, content, len);
1632  FIN_CRC32C(statefile_crc);
1633 
1634  TwoPhaseFilePath(path, xid);
1635 
1636  fd = OpenTransientFile(path,
1637  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY);
1638  if (fd < 0)
1639  ereport(ERROR,
1641  errmsg("could not recreate file \"%s\": %m", path)));
1642 
1643  /* Write content and CRC */
1644  errno = 0;
1646  if (write(fd, content, len) != len)
1647  {
1648  /* if write didn't set errno, assume problem is no disk space */
1649  if (errno == 0)
1650  errno = ENOSPC;
1651  ereport(ERROR,
1653  errmsg("could not write file \"%s\": %m", path)));
1654  }
1655  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1656  {
1657  /* if write didn't set errno, assume problem is no disk space */
1658  if (errno == 0)
1659  errno = ENOSPC;
1660  ereport(ERROR,
1662  errmsg("could not write file \"%s\": %m", path)));
1663  }
1665 
1666  /*
1667  * We must fsync the file because the end-of-replay checkpoint will not do
1668  * so, there being no GXACT in shared memory yet to tell it to.
1669  */
1671  if (pg_fsync(fd) != 0)
1672  ereport(ERROR,
1674  errmsg("could not fsync file \"%s\": %m", path)));
1676 
1677  if (CloseTransientFile(fd) != 0)
1678  ereport(ERROR,
1680  errmsg("could not close file \"%s\": %m", path)));
1681 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
#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:1271
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:885
#define ERROR
Definition: elog.h:46
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2467
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:721
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:262
int CloseTransientFile(int fd)
Definition: fd.c:2644
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
int pg_fsync(int fd)
Definition: fd.c:352
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94

◆ RegisterTwoPhaseRecord()

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

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

1184 {
1185  TwoPhaseRecordOnDisk record;
1186 
1187  record.rmid = rmid;
1188  record.info = info;
1189  record.len = len;
1190  save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1191  if (len > 0)
1192  save_state_data(data, len);
1193 }
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:955
TwoPhaseRmgrId rmid
Definition: twophase.c:920

◆ RemoveGXact()

static void RemoveGXact ( GlobalTransaction  gxact)
static

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

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

◆ RemoveTwoPhaseFile()

static void RemoveTwoPhaseFile ( TransactionId  xid,
bool  giveWarning 
)
static

Definition at line 1604 of file twophase.c.

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

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

1605 {
1606  char path[MAXPGPATH];
1607 
1608  TwoPhaseFilePath(path, xid);
1609  if (unlink(path))
1610  if (errno != ENOENT || giveWarning)
1611  ereport(WARNING,
1613  errmsg("could not remove file \"%s\": %m", path)));
1614 }
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:885
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:721
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1785 of file twophase.c.

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

Referenced by StartupXLOG().

1786 {
1787  DIR *cldir;
1788  struct dirent *clde;
1789 
1790  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1791  cldir = AllocateDir(TWOPHASE_DIR);
1792  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1793  {
1794  if (strlen(clde->d_name) == 8 &&
1795  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1796  {
1797  TransactionId xid;
1798  char *buf;
1799 
1800  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1801 
1803  true, false, false);
1804  if (buf == NULL)
1805  continue;
1806 
1809  }
1810  }
1811  LWLockRelease(TwoPhaseStateLock);
1812  FreeDir(cldir);
1813 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TransactionId
Definition: c.h:587
Definition: dirent.h:9
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
Definition: dirent.c:25
static char * buf
Definition: pg_test_fsync.c:68
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2678
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2070
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2356
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2744
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
#define InvalidRepOriginId
Definition: origin.h:33
#define TWOPHASE_DIR
Definition: twophase.c:114
char d_name[MAX_PATH]
Definition: dirent.h:15
int FreeDir(DIR *dir)
Definition: fd.c:2796

◆ save_state_data()

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

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

956 {
957  uint32 padlen = MAXALIGN(len);
958 
959  if (padlen > records.bytes_free)
960  {
961  records.tail->next = palloc0(sizeof(StateFileChunk));
963  records.tail->len = 0;
964  records.tail->next = NULL;
966 
967  records.bytes_free = Max(padlen, 512);
969  }
970 
971  memcpy(((char *) records.tail->data) + records.tail->len, data, len);
972  records.tail->len += padlen;
973  records.bytes_free -= padlen;
974  records.total_len += padlen;
975 }
StateFileChunk * tail
Definition: twophase.c:939
uint32 num_chunks
Definition: twophase.c:940
char * data
Definition: twophase.c:931
uint32 bytes_free
Definition: twophase.c:941
uint32 len
Definition: twophase.c:932
unsigned int uint32
Definition: c.h:441
static struct xllist records
uint32 total_len
Definition: twophase.c:942
struct StateFileChunk * next
Definition: twophase.c:933
void * palloc0(Size size)
Definition: mcxt.c:1093
#define Max(x, y)
Definition: c.h:980
#define MAXALIGN(LEN)
Definition: c.h:757
void * palloc(Size size)
Definition: mcxt.c:1062

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

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

1929 {
1930  int i;
1931 
1932  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1933  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1934  {
1935  TransactionId xid;
1936  char *buf;
1938 
1939  Assert(gxact->inredo);
1940 
1941  xid = gxact->xid;
1942 
1943  buf = ProcessTwoPhaseBuffer(xid,
1944  gxact->prepare_start_lsn,
1945  gxact->ondisk, false, false);
1946  if (buf != NULL)
1947  pfree(buf);
1948  }
1949  LWLockRelease(TwoPhaseStateLock);
1950 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:587
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void pfree(void *pointer)
Definition: mcxt.c:1169
static char * buf
Definition: pg_test_fsync.c:68
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2070
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
TransactionId xid
Definition: twophase.c:165
int i

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1381 of file twophase.c.

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

1382 {
1383  char *buf;
1384  TwoPhaseFileHeader *hdr;
1385  bool result;
1386 
1388 
1389  if (max_prepared_xacts <= 0)
1390  return false; /* nothing to do */
1391 
1392  /* Read and validate file */
1393  buf = ReadTwoPhaseFile(xid, true);
1394  if (buf == NULL)
1395  return false;
1396 
1397  /* Check header also */
1398  hdr = (TwoPhaseFileHeader *) buf;
1399  result = TransactionIdEquals(hdr->xid, xid);
1400  pfree(buf);
1401 
1402  return result;
1403 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1205
void pfree(void *pointer)
Definition: mcxt.c:1169
int max_prepared_xacts
Definition: twophase.c:117
static char * buf
Definition: pg_test_fsync.c:68
#define Assert(condition)
Definition: c.h:804
TransactionId xid
Definition: xact.h:304
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 983 of file twophase.c.

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

Referenced by PrepareTransaction().

984 {
985  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
986  TransactionId xid = gxact->xid;
987  TwoPhaseFileHeader hdr;
988  TransactionId *children;
989  RelFileNode *commitrels;
990  RelFileNode *abortrels;
991  SharedInvalidationMessage *invalmsgs;
992 
993  /* Initialize linked list */
994  records.head = palloc0(sizeof(StateFileChunk));
995  records.head->len = 0;
996  records.head->next = NULL;
997 
998  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1000 
1002  records.num_chunks = 1;
1003 
1004  records.total_len = 0;
1005 
1006  /* Create header */
1007  hdr.magic = TWOPHASE_MAGIC;
1008  hdr.total_len = 0; /* EndPrepare will fill this in */
1009  hdr.xid = xid;
1010  hdr.database = proc->databaseId;
1011  hdr.prepared_at = gxact->prepared_at;
1012  hdr.owner = gxact->owner;
1013  hdr.nsubxacts = xactGetCommittedChildren(&children);
1014  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1015  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1017  &hdr.initfileinval);
1018  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1019 
1020  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1021  save_state_data(gxact->gid, hdr.gidlen);
1022 
1023  /*
1024  * Add the additional info about subxacts, deletable files and cache
1025  * invalidation messages.
1026  */
1027  if (hdr.nsubxacts > 0)
1028  {
1029  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1030  /* While we have the child-xact data, stuff it in the gxact too */
1031  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1032  }
1033  if (hdr.ncommitrels > 0)
1034  {
1035  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1036  pfree(commitrels);
1037  }
1038  if (hdr.nabortrels > 0)
1039  {
1040  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1041  pfree(abortrels);
1042  }
1043  if (hdr.ninvalmsgs > 0)
1044  {
1045  save_state_data(invalmsgs,
1046  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1047  pfree(invalmsgs);
1048  }
1049 }
int32 ninvalmsgs
Definition: xact.h:311
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5473
int32 nsubxacts
Definition: xact.h:308
uint32 TransactionId
Definition: c.h:587
int32 ncommitrels
Definition: xact.h:309
StateFileChunk * tail
Definition: twophase.c:939
PROC_HDR * ProcGlobal
Definition: proc.c:80
uint16 gidlen
Definition: xact.h:313
uint32 num_chunks
Definition: twophase.c:940
char gid[GIDSIZE]
Definition: twophase.c:172
Oid database
Definition: xact.h:305
char * data
Definition: twophase.c:931
int32 nabortrels
Definition: xact.h:310
void pfree(void *pointer)
Definition: mcxt.c:1169
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:508
uint32 bytes_free
Definition: twophase.c:941
int smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
Definition: storage.c:832
uint32 total_len
Definition: xact.h:303
uint32 len
Definition: twophase.c:932
Oid databaseId
Definition: proc.h:154
static struct xllist records
uint32 total_len
Definition: twophase.c:942
struct StateFileChunk * next
Definition: twophase.c:933
void * palloc0(Size size)
Definition: mcxt.c:1093
#define TWOPHASE_MAGIC
Definition: twophase.c:907
bool initfileinval
Definition: xact.h:312
#define Max(x, y)
Definition: c.h:980
StateFileChunk * head
Definition: twophase.c:938
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:955
TransactionId xid
Definition: xact.h:304
TransactionId xid
Definition: twophase.c:165
TimestampTz prepared_at
Definition: twophase.c:154
uint32 magic
Definition: xact.h:302
void * palloc(Size size)
Definition: mcxt.c:1062
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:832
TimestampTz prepared_at
Definition: xact.h:306
PGPROC * allProcs
Definition: proc.h:318
Definition: proc.h:121

◆ TwoPhaseGetDummyBackendId()

BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid,
bool  lock_held 
)

Definition at line 859 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

860 {
861  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
862 
863  return gxact->dummyBackendId;
864 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:806
BackendId dummyBackendId
Definition: twophase.c:153

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid,
bool  lock_held 
)

Definition at line 874 of file twophase.c.

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

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

875 {
876  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
877 
878  return &ProcGlobal->allProcs[gxact->pgprocno];
879 }
PROC_HDR * ProcGlobal
Definition: proc.c:80
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:806
PGPROC * allProcs
Definition: proc.h:318

◆ TwoPhaseGetGXact()

static GlobalTransaction TwoPhaseGetGXact ( TransactionId  xid,
bool  lock_held 
)
static

Definition at line 806 of file twophase.c.

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

Referenced by TwoPhaseGetDummyBackendId(), and TwoPhaseGetDummyProc().

807 {
808  GlobalTransaction result = NULL;
809  int i;
810 
811  static TransactionId cached_xid = InvalidTransactionId;
812  static GlobalTransaction cached_gxact = NULL;
813 
814  Assert(!lock_held || LWLockHeldByMe(TwoPhaseStateLock));
815 
816  /*
817  * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
818  * repeatedly for the same XID. We can save work with a simple cache.
819  */
820  if (xid == cached_xid)
821  return cached_gxact;
822 
823  if (!lock_held)
824  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
825 
826  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
827  {
829 
830  if (gxact->xid == xid)
831  {
832  result = gxact;
833  break;
834  }
835  }
836 
837  if (!lock_held)
838  LWLockRelease(TwoPhaseStateLock);
839 
840  if (result == NULL) /* should not happen */
841  elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
842 
843  cached_xid = xid;
844  cached_gxact = result;
845 
846  return result;
847 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
uint32 TransactionId
Definition: c.h:587
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1919
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define ERROR
Definition: elog.h:46
#define InvalidTransactionId
Definition: transam.h:31
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
TransactionId xid
Definition: twophase.c:165
#define elog(elevel,...)
Definition: elog.h:232
int i

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 252 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

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

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 236 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores(), and TwoPhaseShmemInit().

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

◆ XlogReadTwoPhaseData()

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

Definition at line 1326 of file twophase.c.

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

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

1327 {
1328  XLogRecord *record;
1330  char *errormsg;
1331  TimeLineID save_currtli = ThisTimeLineID;
1332 
1333  xlogreader = XLogReaderAllocate(wal_segment_size, NULL,
1334  XL_ROUTINE(.page_read = &read_local_xlog_page,
1335  .segment_open = &wal_segment_open,
1336  .segment_close = &wal_segment_close),
1337  NULL);
1338  if (!xlogreader)
1339  ereport(ERROR,
1340  (errcode(ERRCODE_OUT_OF_MEMORY),
1341  errmsg("out of memory"),
1342  errdetail("Failed while allocating a WAL reading processor.")));
1343 
1344  XLogBeginRead(xlogreader, lsn);
1345  record = XLogReadRecord(xlogreader, &errormsg);
1346 
1347  /*
1348  * Restore immediately the timeline where it was previously, as
1349  * read_local_xlog_page() could have changed it if the record was read
1350  * while recovery was finishing or if the timeline has jumped in-between.
1351  */
1352  ThisTimeLineID = save_currtli;
1353 
1354  if (record == NULL)
1355  ereport(ERROR,
1357  errmsg("could not read two-phase state from WAL at %X/%X",
1358  LSN_FORMAT_ARGS(lsn))));
1359 
1360  if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1362  ereport(ERROR,
1364  errmsg("expected two-phase state data is not present in WAL at %X/%X",
1365  LSN_FORMAT_ARGS(lsn))));
1366 
1367  if (len != NULL)
1368  *len = XLogRecGetDataLen(xlogreader);
1369 
1370  *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1371  memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1372 
1373  XLogReaderFree(xlogreader);
1374 }
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:809
uint32 TimeLineID
Definition: xlogdefs.h:59
#define XLOG_XACT_PREPARE
Definition: xact.h:149
int wal_segment_size
Definition: xlog.c:119
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:784
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:271
#define XLogRecGetData(decoder)
Definition: xlogreader.h:310
#define ERROR
Definition: elog.h:46
#define XLogRecGetDataLen(decoder)
Definition: xlogreader.h:311
static char * buf
Definition: pg_test_fsync.c:68
int errdetail(const char *fmt,...)
Definition: elog.c:1042
int errcode_for_file_access(void)
Definition: elog.c:721
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:243
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:78
static XLogReaderState * xlogreader
Definition: walsender.c:137
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:305
#define XL_ROUTINE(...)
Definition: xlogreader.h:116
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:142
TimeLineID ThisTimeLineID
Definition: xlog.c:194
#define ereport(elevel,...)
Definition: elog.h:157
#define XLOG_XACT_OPMASK
Definition: xact.h:158
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:828
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:306

Variable Documentation

◆ max_prepared_xacts

◆ MyLockedGxact

GlobalTransaction MyLockedGxact = NULL
static

Definition at line 199 of file twophase.c.

◆ records

struct xllist records
static

◆ twophaseExitRegistered

bool twophaseExitRegistered = false
static

Definition at line 201 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseState

TwoPhaseStateData* TwoPhaseState
static

Definition at line 191 of file twophase.c.