PostgreSQL Source Code  git master
twophase.c File Reference
#include "postgres.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "access/commit_ts.h"
#include "access/htup_details.h"
#include "access/subtrans.h"
#include "access/transam.h"
#include "access/twophase.h"
#include "access/twophase_rmgr.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "access/xlogreader.h"
#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "catalog/pg_type.h"
#include "catalog/storage.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "pgstat.h"
#include "replication/origin.h"
#include "replication/syncrep.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/md.h"
#include "storage/predicate.h"
#include "storage/proc.h"
#include "storage/procarray.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 TWOPHASE_MAGIC   0x57F94534 /* format identifier */
 

Typedefs

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

Functions

static void RecordTransactionCommitPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileLocator *rels, int nstats, xl_xact_stats_item *stats, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval, const char *gid)
 
static void RecordTransactionAbortPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileLocator *rels, int nstats, xl_xact_stats_item *stats, const char *gid)
 
static void ProcessRecords (char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
 
static void RemoveGXact (GlobalTransaction gxact)
 
static void XlogReadTwoPhaseData (XLogRecPtr lsn, char **buf, int *len)
 
static char * ProcessTwoPhaseBuffer (TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
 
static void MarkAsPreparingGuts (GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
static void RemoveTwoPhaseFile (TransactionId xid, bool giveWarning)
 
static void RecreateTwoPhaseFile (TransactionId xid, void *content, int len)
 
Size TwoPhaseShmemSize (void)
 
void TwoPhaseShmemInit (void)
 
static void AtProcExit_Twophase (int code, Datum arg)
 
void AtAbort_Twophase (void)
 
void PostPrepare_Twophase (void)
 
GlobalTransaction MarkAsPreparing (TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
static void GXactLoadSubxactData (GlobalTransaction gxact, int nsubxacts, TransactionId *children)
 
static void MarkAsPrepared (GlobalTransaction gxact, bool lock_held)
 
static GlobalTransaction LockGXact (const char *gid, Oid user)
 
static int GetPreparedTransactionList (GlobalTransaction *gxacts)
 
Datum pg_prepared_xact (PG_FUNCTION_ARGS)
 
static GlobalTransaction TwoPhaseGetGXact (TransactionId xid, bool lock_held)
 
TransactionId TwoPhaseGetXidByVirtualXID (VirtualTransactionId vxid, bool *have_more)
 
ProcNumber TwoPhaseGetDummyProcNumber (TransactionId xid, bool lock_held)
 
PGPROCTwoPhaseGetDummyProc (TransactionId xid, bool lock_held)
 
static FullTransactionId AdjustToFullTransactionId (TransactionId xid)
 
static int TwoPhaseFilePath (char *path, TransactionId xid)
 
static void save_state_data (const void *data, uint32 len)
 
void StartPrepare (GlobalTransaction gxact)
 
void EndPrepare (GlobalTransaction gxact)
 
void RegisterTwoPhaseRecord (TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
 
static char * ReadTwoPhaseFile (TransactionId xid, bool 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)
 
void TwoPhaseTransactionGid (Oid subid, TransactionId xid, char *gid_res, int szgid)
 
static bool IsTwoPhaseTransactionGidForSubid (Oid subid, char *gid)
 
bool LookupGXactBySubid (Oid subid)
 

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

◆ TWOPHASE_MAGIC

#define TWOPHASE_MAGIC   0x57F94534 /* format identifier */

Definition at line 989 of file twophase.c.

Typedef Documentation

◆ GlobalTransactionData

◆ StateFileChunk

◆ TwoPhaseFileHeader

Definition at line 991 of file twophase.c.

◆ TwoPhaseRecordOnDisk

◆ TwoPhaseStateData

Function Documentation

◆ AdjustToFullTransactionId()

static FullTransactionId AdjustToFullTransactionId ( TransactionId  xid)
inlinestatic

Definition at line 936 of file twophase.c.

937 {
938  FullTransactionId nextFullXid;
939  TransactionId nextXid;
940  uint32 epoch;
941 
943 
944  LWLockAcquire(XidGenLock, LW_SHARED);
945  nextFullXid = TransamVariables->nextXid;
946  LWLockRelease(XidGenLock);
947 
948  nextXid = XidFromFullTransactionId(nextFullXid);
949  epoch = EpochFromFullTransactionId(nextFullXid);
950  if (unlikely(xid > nextXid))
951  {
952  /* Wraparound occurred, must be from a prev epoch. */
953  Assert(epoch > 0);
954  epoch--;
955  }
956 
958 }
unsigned int uint32
Definition: c.h:509
#define Assert(condition)
Definition: c.h:861
#define unlikely(x)
Definition: c.h:314
uint32 TransactionId
Definition: c.h:655
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
@ LW_SHARED
Definition: lwlock.h:115
FullTransactionId nextXid
Definition: transam.h:220
#define EpochFromFullTransactionId(x)
Definition: transam.h:47
#define XidFromFullTransactionId(x)
Definition: transam.h:48
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static FullTransactionId FullTransactionIdFromEpochAndXid(uint32 epoch, TransactionId xid)
Definition: transam.h:71
TransamVariablesData * TransamVariables
Definition: varsup.c:34
static const unsigned __int64 epoch

References Assert, epoch, EpochFromFullTransactionId, FullTransactionIdFromEpochAndXid(), LW_SHARED, LWLockAcquire(), LWLockRelease(), TransamVariablesData::nextXid, TransactionIdIsValid, TransamVariables, unlikely, and XidFromFullTransactionId.

Referenced by TwoPhaseFilePath().

◆ AtAbort_Twophase()

void AtAbort_Twophase ( void  )

Definition at line 304 of file twophase.c.

305 {
306  if (MyLockedGxact == NULL)
307  return;
308 
309  /*
310  * What to do with the locked global transaction entry? If we were in the
311  * process of preparing the transaction, but haven't written the WAL
312  * record and state file yet, the transaction must not be considered as
313  * prepared. Likewise, if we are in the process of finishing an
314  * already-prepared transaction, and fail after having already written the
315  * 2nd phase commit or rollback record to the WAL, the transaction should
316  * not be considered as prepared anymore. In those cases, just remove the
317  * entry from shared memory.
318  *
319  * Otherwise, the entry must be left in place so that the transaction can
320  * be finished later, so just unlock it.
321  *
322  * If we abort during prepare, after having written the WAL record, we
323  * might not have transferred all locks and other state to the prepared
324  * transaction yet. Likewise, if we abort during commit or rollback,
325  * after having written the WAL record, we might not have released all the
326  * resources held by the transaction yet. In those cases, the in-memory
327  * state can be wrong, but it's too late to back out.
328  */
329  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
330  if (!MyLockedGxact->valid)
332  else
334  LWLockRelease(TwoPhaseStateLock);
335 
336  MyLockedGxact = NULL;
337 }
@ LW_EXCLUSIVE
Definition: lwlock.h:114
#define INVALID_PROC_NUMBER
Definition: procnumber.h:26
ProcNumber locking_backend
Definition: twophase.c:165
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:628
static GlobalTransaction MyLockedGxact
Definition: twophase.c:196

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

◆ AtProcExit_Twophase()

static void AtProcExit_Twophase ( int  code,
Datum  arg 
)
static

Definition at line 294 of file twophase.c.

295 {
296  /* same logic as abort */
298 }
void AtAbort_Twophase(void)
Definition: twophase.c:304

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

◆ CheckPointTwoPhase()

void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1823 of file twophase.c.

1824 {
1825  int i;
1826  int serialized_xacts = 0;
1827 
1828  if (max_prepared_xacts <= 0)
1829  return; /* nothing to do */
1830 
1831  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1832 
1833  /*
1834  * We are expecting there to be zero GXACTs that need to be copied to
1835  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1836  * simplicity. This prevents any new xacts from preparing while this
1837  * occurs, which shouldn't be a problem since the presence of long-lived
1838  * prepared xacts indicates the transaction manager isn't active.
1839  *
1840  * It's also possible to move I/O out of the lock, but on every error we
1841  * should check whether somebody committed our transaction in different
1842  * backend. Let's leave this optimization for future, if somebody will
1843  * spot that this place cause bottleneck.
1844  *
1845  * Note that it isn't possible for there to be a GXACT with a
1846  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1847  * because of the efforts with delayChkptFlags.
1848  */
1849  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1850  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1851  {
1852  /*
1853  * Note that we are using gxact not PGPROC so this works in recovery
1854  * also
1855  */
1857 
1858  if ((gxact->valid || gxact->inredo) &&
1859  !gxact->ondisk &&
1860  gxact->prepare_end_lsn <= redo_horizon)
1861  {
1862  char *buf;
1863  int len;
1864 
1866  RecreateTwoPhaseFile(gxact->xid, buf, len);
1867  gxact->ondisk = true;
1870  pfree(buf);
1871  serialized_xacts++;
1872  }
1873  }
1874  LWLockRelease(TwoPhaseStateLock);
1875 
1876  /*
1877  * Flush unconditionally the parent directory to make any information
1878  * durable on disk. Two-phase files could have been removed and those
1879  * removals need to be made persistent as well as any files newly created
1880  * previously since the last checkpoint.
1881  */
1882  fsync_fname(TWOPHASE_DIR, true);
1883 
1884  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1885 
1886  if (log_checkpoints && serialized_xacts > 0)
1887  ereport(LOG,
1888  (errmsg_plural("%u two-phase state file was written "
1889  "for a long-running prepared transaction",
1890  "%u two-phase state files were written "
1891  "for long-running prepared transactions",
1892  serialized_xacts,
1893  serialized_xacts)));
1894 }
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1180
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:756
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1521
const void size_t len
static char * buf
Definition: pg_test_fsync.c:73
TransactionId xid
Definition: twophase.c:162
XLogRecPtr prepare_start_lsn
Definition: twophase.c:160
XLogRecPtr prepare_end_lsn
Definition: twophase.c:161
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:185
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1420
#define TWOPHASE_DIR
Definition: twophase.c:112
int max_prepared_xacts
Definition: twophase.c:115
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:188
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1743
bool log_checkpoints
Definition: xlog.c:128
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

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

Referenced by CheckPointGuts().

◆ EndPrepare()

void EndPrepare ( GlobalTransaction  gxact)

Definition at line 1158 of file twophase.c.

1159 {
1160  TwoPhaseFileHeader *hdr;
1161  StateFileChunk *record;
1162  bool replorigin;
1163 
1164  /* Add the end sentinel to the list of 2PC records */
1166  NULL, 0);
1167 
1168  /* Go back and fill in total_len in the file header record */
1169  hdr = (TwoPhaseFileHeader *) records.head->data;
1170  Assert(hdr->magic == TWOPHASE_MAGIC);
1171  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1172 
1173  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1175 
1176  if (replorigin)
1177  {
1180  }
1181 
1182  /*
1183  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1184  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1185  * where we write data to file and then re-read at commit time.
1186  */
1187  if (hdr->total_len > MaxAllocSize)
1188  ereport(ERROR,
1189  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1190  errmsg("two-phase state file maximum length exceeded")));
1191 
1192  /*
1193  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1194  * cover us, so no need to calculate a separate CRC.
1195  *
1196  * We have to set DELAY_CHKPT_START here, too; otherwise a checkpoint
1197  * starting immediately after the WAL record is inserted could complete
1198  * without fsync'ing our state file. (This is essentially the same kind
1199  * of race condition as the COMMIT-to-clog-write case that
1200  * RecordTransactionCommit uses DELAY_CHKPT_START for; see notes there.)
1201  *
1202  * We save the PREPARE record's location in the gxact for later use by
1203  * CheckPointTwoPhase.
1204  */
1206 
1208 
1211 
1212  XLogBeginInsert();
1213  for (record = records.head; record != NULL; record = record->next)
1214  XLogRegisterData(record->data, record->len);
1215 
1217 
1218  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1219 
1220  if (replorigin)
1221  {
1222  /* Move LSNs forward for this replication origin */
1224  gxact->prepare_end_lsn);
1225  }
1226 
1227  XLogFlush(gxact->prepare_end_lsn);
1228 
1229  /* If we crash now, we have prepared: WAL replay will fix things */
1230 
1231  /* Store record's start location to read that later on Commit */
1233 
1234  /*
1235  * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
1236  * as not running our XID (which it will do immediately after this
1237  * function returns), others can commit/rollback the xact.
1238  *
1239  * NB: a side effect of this is to make a dummy ProcArray entry for the
1240  * prepared XID. This must happen before we clear the XID from MyProc /
1241  * ProcGlobal->xids[], else there is a window where the XID is not running
1242  * according to TransactionIdIsInProgress, and onlookers would be entitled
1243  * to assume the xact crashed. Instead we have a window where the same
1244  * XID appears twice in ProcArray, which is OK.
1245  */
1246  MarkAsPrepared(gxact, false);
1247 
1248  /*
1249  * Now we can mark ourselves as out of the commit critical section: a
1250  * checkpoint starting after this will certainly see the gxact as a
1251  * candidate for fsyncing.
1252  */
1254 
1255  /*
1256  * Remember that we have this GlobalTransaction entry locked for us. If
1257  * we crash after this point, it's too late to abort, but we must unlock
1258  * it so that the prepared transaction can be committed or rolled back.
1259  */
1260  MyLockedGxact = gxact;
1261 
1262  END_CRIT_SECTION();
1263 
1264  /*
1265  * Wait for synchronous replication, if required.
1266  *
1267  * Note that at this stage we have marked the prepare, but still show as
1268  * running in the procarray (twice!) and continue to hold locks.
1269  */
1270  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1271 
1272  records.tail = records.head = NULL;
1273  records.num_chunks = 0;
1274 }
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define MaxAllocSize
Definition: memutils.h:40
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:161
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1223
RepOriginId replorigin_session_origin
Definition: origin.c:159
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:160
#define DoNotReplicateId
Definition: origin.h:34
#define InvalidRepOriginId
Definition: origin.h:33
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define DELAY_CHKPT_START
Definition: proc.h:119
PGPROC * MyProc
Definition: proc.c:67
int delayChkptFlags
Definition: proc.h:240
struct StateFileChunk * next
Definition: twophase.c:1015
TimestampTz origin_timestamp
Definition: xact.h:369
uint32 total_len
Definition: xact.h:355
XLogRecPtr origin_lsn
Definition: xact.h:368
uint32 magic
Definition: xact.h:354
uint32 total_len
Definition: twophase.c:1024
uint32 num_chunks
Definition: twophase.c:1022
StateFileChunk * head
Definition: twophase.c:1020
StateFileChunk * tail
Definition: twophase.c:1021
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:148
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1280
#define TWOPHASE_MAGIC
Definition: twophase.c:989
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:530
static struct xllist records
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
#define XLOG_XACT_PREPARE
Definition: xact.h:170
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:252
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2795
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:154
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:474
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:456
void XLogRegisterData(const char *data, uint32 len)
Definition: xloginsert.c:364
void XLogBeginInsert(void)
Definition: xloginsert.c:149
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition: xloginsert.c:175

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

Referenced by PrepareTransaction().

◆ FinishPreparedTransaction()

void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

Definition at line 1503 of file twophase.c.

1504 {
1505  GlobalTransaction gxact;
1506  PGPROC *proc;
1507  TransactionId xid;
1508  bool ondisk;
1509  char *buf;
1510  char *bufptr;
1511  TwoPhaseFileHeader *hdr;
1512  TransactionId latestXid;
1513  TransactionId *children;
1514  RelFileLocator *commitrels;
1515  RelFileLocator *abortrels;
1516  RelFileLocator *delrels;
1517  int ndelrels;
1518  xl_xact_stats_item *commitstats;
1519  xl_xact_stats_item *abortstats;
1520  SharedInvalidationMessage *invalmsgs;
1521 
1522  /*
1523  * Validate the GID, and lock the GXACT to ensure that two backends do not
1524  * try to commit the same GID at once.
1525  */
1526  gxact = LockGXact(gid, GetUserId());
1527  proc = GetPGProcByNumber(gxact->pgprocno);
1528  xid = gxact->xid;
1529 
1530  /*
1531  * Read and validate 2PC state data. State data will typically be stored
1532  * in WAL files if the LSN is after the last checkpoint record, or moved
1533  * to disk if for some reason they have lived for a long time.
1534  */
1535  if (gxact->ondisk)
1536  buf = ReadTwoPhaseFile(xid, false);
1537  else
1538  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1539 
1540 
1541  /*
1542  * Disassemble the header area
1543  */
1544  hdr = (TwoPhaseFileHeader *) buf;
1545  Assert(TransactionIdEquals(hdr->xid, xid));
1546  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1547  bufptr += MAXALIGN(hdr->gidlen);
1548  children = (TransactionId *) bufptr;
1549  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1550  commitrels = (RelFileLocator *) bufptr;
1551  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
1552  abortrels = (RelFileLocator *) bufptr;
1553  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
1554  commitstats = (xl_xact_stats_item *) bufptr;
1555  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
1556  abortstats = (xl_xact_stats_item *) bufptr;
1557  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
1558  invalmsgs = (SharedInvalidationMessage *) bufptr;
1559  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1560 
1561  /* compute latestXid among all children */
1562  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1563 
1564  /* Prevent cancel/die interrupt while cleaning up */
1565  HOLD_INTERRUPTS();
1566 
1567  /*
1568  * The order of operations here is critical: make the XLOG entry for
1569  * commit or abort, then mark the transaction committed or aborted in
1570  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1571  * TransactionIdIsInProgress will stop saying the prepared xact is in
1572  * progress), then run the post-commit or post-abort callbacks. The
1573  * callbacks will release the locks the transaction held.
1574  */
1575  if (isCommit)
1577  hdr->nsubxacts, children,
1578  hdr->ncommitrels, commitrels,
1579  hdr->ncommitstats,
1580  commitstats,
1581  hdr->ninvalmsgs, invalmsgs,
1582  hdr->initfileinval, gid);
1583  else
1585  hdr->nsubxacts, children,
1586  hdr->nabortrels, abortrels,
1587  hdr->nabortstats,
1588  abortstats,
1589  gid);
1590 
1591  ProcArrayRemove(proc, latestXid);
1592 
1593  /*
1594  * In case we fail while running the callbacks, mark the gxact invalid so
1595  * no one else will try to commit/rollback, and so it will be recycled if
1596  * we fail after this point. It is still locked by our backend so it
1597  * won't go away yet.
1598  *
1599  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1600  */
1601  gxact->valid = false;
1602 
1603  /*
1604  * We have to remove any files that were supposed to be dropped. For
1605  * consistency with the regular xact.c code paths, must do this before
1606  * releasing locks, so do it before running the callbacks.
1607  *
1608  * NB: this code knows that we couldn't be dropping any temp rels ...
1609  */
1610  if (isCommit)
1611  {
1612  delrels = commitrels;
1613  ndelrels = hdr->ncommitrels;
1614  }
1615  else
1616  {
1617  delrels = abortrels;
1618  ndelrels = hdr->nabortrels;
1619  }
1620 
1621  /* Make sure files supposed to be dropped are dropped */
1622  DropRelationFiles(delrels, ndelrels, false);
1623 
1624  if (isCommit)
1625  pgstat_execute_transactional_drops(hdr->ncommitstats, commitstats, false);
1626  else
1627  pgstat_execute_transactional_drops(hdr->nabortstats, abortstats, false);
1628 
1629  /*
1630  * Handle cache invalidation messages.
1631  *
1632  * Relcache init file invalidation requires processing both before and
1633  * after we send the SI messages, only when committing. See
1634  * AtEOXact_Inval().
1635  */
1636  if (isCommit)
1637  {
1638  if (hdr->initfileinval)
1640  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1641  if (hdr->initfileinval)
1643  }
1644 
1645  /*
1646  * Acquire the two-phase lock. We want to work on the two-phase callbacks
1647  * while holding it to avoid potential conflicts with other transactions
1648  * attempting to use the same GID, so the lock is released once the shared
1649  * memory state is cleared.
1650  */
1651  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1652 
1653  /* And now do the callbacks */
1654  if (isCommit)
1656  else
1658 
1659  PredicateLockTwoPhaseFinish(xid, isCommit);
1660 
1661  /*
1662  * Read this value while holding the two-phase lock, as the on-disk 2PC
1663  * file is physically removed after the lock is released.
1664  */
1665  ondisk = gxact->ondisk;
1666 
1667  /* Clear shared memory state */
1668  RemoveGXact(gxact);
1669 
1670  /*
1671  * Release the lock as all callbacks are called and shared memory cleanup
1672  * is done.
1673  */
1674  LWLockRelease(TwoPhaseStateLock);
1675 
1676  /* Count the prepared xact as committed or aborted */
1677  AtEOXact_PgStat(isCommit, false);
1678 
1679  /*
1680  * And now we can clean up any files we may have left.
1681  */
1682  if (ondisk)
1683  RemoveTwoPhaseFile(xid, true);
1684 
1685  MyLockedGxact = NULL;
1686 
1688 
1689  pfree(buf);
1690 }
#define MAXALIGN(LEN)
Definition: c.h:814
void DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo)
Definition: md.c:1446
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
Oid GetUserId(void)
Definition: miscinit.c:514
void pgstat_execute_transactional_drops(int ndrops, struct xl_xact_stats_item *items, bool is_redo)
Definition: pgstat_xact.c:314
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat_xact.c:40
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:4867
#define GetPGProcByNumber(n)
Definition: proc.h:432
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:565
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:6795
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:6770
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:47
Definition: proc.h:162
int32 nabortrels
Definition: xact.h:362
int32 ninvalmsgs
Definition: xact.h:365
bool initfileinval
Definition: xact.h:366
int32 ncommitstats
Definition: xact.h:363
uint16 gidlen
Definition: xact.h:367
int32 nabortstats
Definition: xact.h:364
int32 ncommitrels
Definition: xact.h:361
TransactionId xid
Definition: xact.h:356
int32 nsubxacts
Definition: xact.h:360
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:345
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileLocator *rels, int nstats, xl_xact_stats_item *stats, const char *gid)
Definition: twophase.c:2411
static void RecordTransactionCommitPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileLocator *rels, int nstats, xl_xact_stats_item *stats, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval, const char *gid)
Definition: twophase.c:2313
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1696
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1724
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1303
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:552
const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:33
const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:42

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

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

◆ GetPreparedTransactionList()

static int GetPreparedTransactionList ( GlobalTransaction gxacts)
static

Definition at line 666 of file twophase.c.

667 {
668  GlobalTransaction array;
669  int num;
670  int i;
671 
672  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
673 
674  if (TwoPhaseState->numPrepXacts == 0)
675  {
676  LWLockRelease(TwoPhaseStateLock);
677 
678  *gxacts = NULL;
679  return 0;
680  }
681 
683  array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
684  *gxacts = array;
685  for (i = 0; i < num; i++)
686  memcpy(array + i, TwoPhaseState->prepXacts[i],
687  sizeof(GlobalTransactionData));
688 
689  LWLockRelease(TwoPhaseStateLock);
690 
691  return num;
692 }
void * palloc(Size size)
Definition: mcxt.c:1317
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:26

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

Referenced by pg_prepared_xact().

◆ GXactLoadSubxactData()

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

Definition at line 504 of file twophase.c.

506 {
507  PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
508 
509  /* We need no extra lock since the GXACT isn't valid yet */
510  if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
511  {
512  proc->subxidStatus.overflowed = true;
513  nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
514  }
515  if (nsubxacts > 0)
516  {
517  memcpy(proc->subxids.xids, children,
518  nsubxacts * sizeof(TransactionId));
519  proc->subxidStatus.count = nsubxacts;
520  }
521 }
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:39
XidCacheStatus subxidStatus
Definition: proc.h:263
struct XidCache subxids
Definition: proc.h:265
bool overflowed
Definition: proc.h:46
uint8 count
Definition: proc.h:44
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:51

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

Referenced by RecoverPreparedTransactions(), and StartPrepare().

◆ IsTwoPhaseTransactionGidForSubid()

static bool IsTwoPhaseTransactionGidForSubid ( Oid  subid,
char *  gid 
)
static

Definition at line 2717 of file twophase.c.

2718 {
2719  int ret;
2720  Oid subid_from_gid;
2721  TransactionId xid_from_gid;
2722  char gid_tmp[GIDSIZE];
2723 
2724  /* Extract the subid and xid from the given GID */
2725  ret = sscanf(gid, "pg_gid_%u_%u", &subid_from_gid, &xid_from_gid);
2726 
2727  /*
2728  * Check that the given GID has expected format, and at least the subid
2729  * matches.
2730  */
2731  if (ret != 2 || subid != subid_from_gid)
2732  return false;
2733 
2734  /*
2735  * Reconstruct a temporary GID based on the subid and xid extracted from
2736  * the given GID and check whether the temporary GID and the given GID
2737  * match.
2738  */
2739  TwoPhaseTransactionGid(subid, xid_from_gid, gid_tmp, sizeof(gid_tmp));
2740 
2741  return strcmp(gid, gid_tmp) == 0;
2742 }
unsigned int Oid
Definition: postgres_ext.h:31
void TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid_res, int szgid)
Definition: twophase.c:2699
#define GIDSIZE
Definition: xact.h:31

References GIDSIZE, and TwoPhaseTransactionGid().

Referenced by LookupGXactBySubid().

◆ LockGXact()

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

Definition at line 552 of file twophase.c.

553 {
554  int i;
555 
556  /* on first call, register the exit hook */
558  {
560  twophaseExitRegistered = true;
561  }
562 
563  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
564 
565  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
566  {
568  PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
569 
570  /* Ignore not-yet-valid GIDs */
571  if (!gxact->valid)
572  continue;
573  if (strcmp(gxact->gid, gid) != 0)
574  continue;
575 
576  /* Found it, but has someone else got it locked? */
577  if (gxact->locking_backend != INVALID_PROC_NUMBER)
578  ereport(ERROR,
579  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
580  errmsg("prepared transaction with identifier \"%s\" is busy",
581  gid)));
582 
583  if (user != gxact->owner && !superuser_arg(user))
584  ereport(ERROR,
585  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
586  errmsg("permission denied to finish prepared transaction"),
587  errhint("Must be superuser or the user that prepared the transaction.")));
588 
589  /*
590  * Note: it probably would be possible to allow committing from
591  * another database; but at the moment NOTIFY is known not to work and
592  * there may be some other issues as well. Hence disallow until
593  * someone gets motivated to make it work.
594  */
595  if (MyDatabaseId != proc->databaseId)
596  ereport(ERROR,
597  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
598  errmsg("prepared transaction belongs to another database"),
599  errhint("Connect to the database where the transaction was prepared to finish it.")));
600 
601  /* OK for me to lock it */
602  gxact->locking_backend = MyProcNumber;
603  MyLockedGxact = gxact;
604 
605  LWLockRelease(TwoPhaseStateLock);
606 
607  return gxact;
608  }
609 
610  LWLockRelease(TwoPhaseStateLock);
611 
612  ereport(ERROR,
613  (errcode(ERRCODE_UNDEFINED_OBJECT),
614  errmsg("prepared transaction with identifier \"%s\" does not exist",
615  gid)));
616 
617  /* NOTREACHED */
618  return NULL;
619 }
int errhint(const char *fmt,...)
Definition: elog.c:1317
ProcNumber MyProcNumber
Definition: globals.c:89
Oid MyDatabaseId
Definition: globals.c:93
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
static char * user
Definition: pg_regress.c:120
char gid[GIDSIZE]
Definition: twophase.c:169
Oid databaseId
Definition: proc.h:207
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
static bool twophaseExitRegistered
Definition: twophase.c:198
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:294

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

Referenced by FinishPreparedTransaction().

◆ LookupGXact()

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

Definition at line 2640 of file twophase.c.

2642 {
2643  int i;
2644  bool found = false;
2645 
2646  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
2647  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2648  {
2650 
2651  /* Ignore not-yet-valid GIDs. */
2652  if (gxact->valid && strcmp(gxact->gid, gid) == 0)
2653  {
2654  char *buf;
2655  TwoPhaseFileHeader *hdr;
2656 
2657  /*
2658  * We are not expecting collisions of GXACTs (same gid) between
2659  * publisher and subscribers, so we perform all I/O while holding
2660  * TwoPhaseStateLock for simplicity.
2661  *
2662  * To move the I/O out of the lock, we need to ensure that no
2663  * other backend commits the prepared xact in the meantime. We can
2664  * do this optimization if we encounter many collisions in GID
2665  * between publisher and subscriber.
2666  */
2667  if (gxact->ondisk)
2668  buf = ReadTwoPhaseFile(gxact->xid, false);
2669  else
2670  {
2671  Assert(gxact->prepare_start_lsn);
2672  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
2673  }
2674 
2675  hdr = (TwoPhaseFileHeader *) buf;
2676 
2677  if (hdr->origin_lsn == prepare_end_lsn &&
2678  hdr->origin_timestamp == origin_prepare_timestamp)
2679  {
2680  found = true;
2681  pfree(buf);
2682  break;
2683  }
2684 
2685  pfree(buf);
2686  }
2687  }
2688  LWLockRelease(TwoPhaseStateLock);
2689  return found;
2690 }

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

Referenced by apply_handle_rollback_prepared().

◆ LookupGXactBySubid()

bool LookupGXactBySubid ( Oid  subid)

Definition at line 2749 of file twophase.c.

2750 {
2751  bool found = false;
2752 
2753  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
2754  for (int i = 0; i < TwoPhaseState->numPrepXacts; i++)
2755  {
2757 
2758  /* Ignore not-yet-valid GIDs. */
2759  if (gxact->valid &&
2760  IsTwoPhaseTransactionGidForSubid(subid, gxact->gid))
2761  {
2762  found = true;
2763  break;
2764  }
2765  }
2766  LWLockRelease(TwoPhaseStateLock);
2767 
2768  return found;
2769 }
static bool IsTwoPhaseTransactionGidForSubid(Oid subid, char *gid)
Definition: twophase.c:2717

References GlobalTransactionData::gid, i, IsTwoPhaseTransactionGidForSubid(), LW_SHARED, LWLockAcquire(), LWLockRelease(), TwoPhaseStateData::numPrepXacts, TwoPhaseStateData::prepXacts, TwoPhaseState, and GlobalTransactionData::valid.

Referenced by AlterSubscription().

◆ MarkAsPrepared()

static void MarkAsPrepared ( GlobalTransaction  gxact,
bool  lock_held 
)
static

Definition at line 530 of file twophase.c.

531 {
532  /* Lock here may be overkill, but I'm not convinced of that ... */
533  if (!lock_held)
534  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
535  Assert(!gxact->valid);
536  gxact->valid = true;
537  if (!lock_held)
538  LWLockRelease(TwoPhaseStateLock);
539 
540  /*
541  * Put it into the global ProcArray so TransactionIdIsInProgress considers
542  * the XID as still running.
543  */
545 }
void ProcArrayAdd(PGPROC *proc)
Definition: procarray.c:468

References Assert, GetPGProcByNumber, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), GlobalTransactionData::pgprocno, ProcArrayAdd(), and GlobalTransactionData::valid.

Referenced by EndPrepare(), and RecoverPreparedTransactions().

◆ MarkAsPreparing()

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

Definition at line 359 of file twophase.c.

361 {
362  GlobalTransaction gxact;
363  int i;
364 
365  if (strlen(gid) >= GIDSIZE)
366  ereport(ERROR,
367  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
368  errmsg("transaction identifier \"%s\" is too long",
369  gid)));
370 
371  /* fail immediately if feature is disabled */
372  if (max_prepared_xacts == 0)
373  ereport(ERROR,
374  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
375  errmsg("prepared transactions are disabled"),
376  errhint("Set \"max_prepared_transactions\" to a nonzero value.")));
377 
378  /* on first call, register the exit hook */
380  {
382  twophaseExitRegistered = true;
383  }
384 
385  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
386 
387  /* Check for conflicting GID */
388  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
389  {
390  gxact = TwoPhaseState->prepXacts[i];
391  if (strcmp(gxact->gid, gid) == 0)
392  {
393  ereport(ERROR,
395  errmsg("transaction identifier \"%s\" is already in use",
396  gid)));
397  }
398  }
399 
400  /* Get a free gxact from the freelist */
401  if (TwoPhaseState->freeGXacts == NULL)
402  ereport(ERROR,
403  (errcode(ERRCODE_OUT_OF_MEMORY),
404  errmsg("maximum number of prepared transactions reached"),
405  errhint("Increase \"max_prepared_transactions\" (currently %d).",
407  gxact = TwoPhaseState->freeGXacts;
408  TwoPhaseState->freeGXacts = gxact->next;
409 
410  MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
411 
412  gxact->ondisk = false;
413 
414  /* And insert it into the active array */
417 
418  LWLockRelease(TwoPhaseStateLock);
419 
420  return gxact;
421 }
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
GlobalTransaction next
Definition: twophase.c:149
GlobalTransaction freeGXacts
Definition: twophase.c:179
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:433

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

Referenced by PrepareTransaction().

◆ MarkAsPreparingGuts()

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

Definition at line 433 of file twophase.c.

435 {
436  PGPROC *proc;
437  int i;
438 
439  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
440 
441  Assert(gxact != NULL);
442  proc = GetPGProcByNumber(gxact->pgprocno);
443 
444  /* Initialize the PGPROC entry */
445  MemSet(proc, 0, sizeof(PGPROC));
446  dlist_node_init(&proc->links);
449  {
450  /* clone VXID, for TwoPhaseGetXidByVirtualXID() to find */
451  proc->vxid.lxid = MyProc->vxid.lxid;
452  proc->vxid.procNumber = MyProcNumber;
453  }
454  else
455  {
457  /* GetLockConflicts() uses this to specify a wait on the XID */
458  proc->vxid.lxid = xid;
460  }
461  proc->xid = xid;
462  Assert(proc->xmin == InvalidTransactionId);
463  proc->delayChkptFlags = 0;
464  proc->statusFlags = 0;
465  proc->pid = 0;
466  proc->databaseId = databaseid;
467  proc->roleId = owner;
468  proc->tempNamespaceId = InvalidOid;
469  proc->isBackgroundWorker = false;
471  proc->lwWaitMode = 0;
472  proc->waitLock = NULL;
473  proc->waitProcLock = NULL;
474  pg_atomic_init_u64(&proc->waitStart, 0);
475  for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
476  dlist_init(&proc->myProcLocks[i]);
477  /* subxid data must be filled later by GXactLoadSubxactData */
478  proc->subxidStatus.overflowed = false;
479  proc->subxidStatus.count = 0;
480 
481  gxact->prepared_at = prepared_at;
482  gxact->xid = xid;
483  gxact->owner = owner;
484  gxact->locking_backend = MyProcNumber;
485  gxact->valid = false;
486  gxact->inredo = false;
487  strcpy(gxact->gid, gid);
488 
489  /*
490  * Remember that we have this GlobalTransaction entry locked for us. If we
491  * abort after this, we must release it.
492  */
493  MyLockedGxact = gxact;
494 }
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:453
#define MemSet(start, val, len)
Definition: c.h:1023
bool IsPostmasterEnvironment
Definition: globals.c:118
static void dlist_init(dlist_head *head)
Definition: ilist.h:314
static void dlist_node_init(dlist_node *node)
Definition: ilist.h:325
#define LocalTransactionIdIsValid(lxid)
Definition: lock.h:66
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1937
@ LW_WS_NOT_WAITING
Definition: lwlock.h:30
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:97
#define AmStartupProcess()
Definition: miscadmin.h:379
#define InvalidOid
Definition: postgres_ext.h:36
@ PROC_WAIT_STATUS_OK
Definition: proc.h:124
TimestampTz prepared_at
Definition: twophase.c:151
TransactionId xmin
Definition: proc.h:177
LocalTransactionId lxid
Definition: proc.h:200
PROCLOCK * waitProcLock
Definition: proc.h:233
uint8 lwWaitMode
Definition: proc.h:224
uint8 statusFlags
Definition: proc.h:242
pg_atomic_uint64 waitStart
Definition: proc.h:237
ProcNumber procNumber
Definition: proc.h:195
int pid
Definition: proc.h:182
bool isBackgroundWorker
Definition: proc.h:213
LOCK * waitLock
Definition: proc.h:232
TransactionId xid
Definition: proc.h:172
struct PGPROC::@119 vxid
dlist_head myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:261
Oid roleId
Definition: proc.h:208
ProcWaitStatus waitStatus
Definition: proc.h:167
Oid tempNamespaceId
Definition: proc.h:210
dlist_node links
Definition: proc.h:163
uint8 lwWaiting
Definition: proc.h:223
#define InvalidTransactionId
Definition: transam.h:31

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

Referenced by MarkAsPreparing(), and RecoverPreparedTransactions().

◆ pg_prepared_xact()

Datum pg_prepared_xact ( PG_FUNCTION_ARGS  )

Definition at line 711 of file twophase.c.

712 {
713  FuncCallContext *funcctx;
714  Working_State *status;
715 
716  if (SRF_IS_FIRSTCALL())
717  {
718  TupleDesc tupdesc;
719  MemoryContext oldcontext;
720 
721  /* create a function context for cross-call persistence */
722  funcctx = SRF_FIRSTCALL_INIT();
723 
724  /*
725  * Switch to memory context appropriate for multiple function calls
726  */
727  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
728 
729  /* build tupdesc for result tuples */
730  /* this had better match pg_prepared_xacts view in system_views.sql */
731  tupdesc = CreateTemplateTupleDesc(5);
732  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
733  XIDOID, -1, 0);
734  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
735  TEXTOID, -1, 0);
736  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
737  TIMESTAMPTZOID, -1, 0);
738  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
739  OIDOID, -1, 0);
740  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
741  OIDOID, -1, 0);
742 
743  funcctx->tuple_desc = BlessTupleDesc(tupdesc);
744 
745  /*
746  * Collect all the 2PC status information that we will format and send
747  * out as a result set.
748  */
749  status = (Working_State *) palloc(sizeof(Working_State));
750  funcctx->user_fctx = (void *) status;
751 
752  status->ngxacts = GetPreparedTransactionList(&status->array);
753  status->currIdx = 0;
754 
755  MemoryContextSwitchTo(oldcontext);
756  }
757 
758  funcctx = SRF_PERCALL_SETUP();
759  status = (Working_State *) funcctx->user_fctx;
760 
761  while (status->array != NULL && status->currIdx < status->ngxacts)
762  {
763  GlobalTransaction gxact = &status->array[status->currIdx++];
764  PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
765  Datum values[5] = {0};
766  bool nulls[5] = {0};
767  HeapTuple tuple;
768  Datum result;
769 
770  if (!gxact->valid)
771  continue;
772 
773  /*
774  * Form tuple with appropriate data.
775  */
776 
777  values[0] = TransactionIdGetDatum(proc->xid);
778  values[1] = CStringGetTextDatum(gxact->gid);
780  values[3] = ObjectIdGetDatum(gxact->owner);
781  values[4] = ObjectIdGetDatum(proc->databaseId);
782 
783  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
784  result = HeapTupleGetDatum(tuple);
785  SRF_RETURN_NEXT(funcctx, result);
786  }
787 
788  SRF_RETURN_DONE(funcctx);
789 }
int16 AttrNumber
Definition: attnum.h:21
static Datum values[MAXATTR]
Definition: bootstrap.c:150
#define CStringGetTextDatum(s)
Definition: builtins.h:97
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2158
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:308
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:306
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition: funcapi.h:230
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:328
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
while(p+4<=pend)
static Datum TransactionIdGetDatum(TransactionId X)
Definition: postgres.h:272
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
MemoryContextSwitchTo(old_ctx)
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
TupleDesc tuple_desc
Definition: funcapi.h:112
GlobalTransaction array
Definition: twophase.c:698
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:67
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:651
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition: twophase.c:666
static Datum TimestampTzGetDatum(TimestampTz X)
Definition: timestamp.h:52

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

◆ PostPrepare_Twophase()

void PostPrepare_Twophase ( void  )

Definition at line 344 of file twophase.c.

345 {
346  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
348  LWLockRelease(TwoPhaseStateLock);
349 
350  MyLockedGxact = NULL;
351 }

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

◆ PrepareRedoAdd()

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

Definition at line 2486 of file twophase.c.

2488 {
2490  char *bufptr;
2491  const char *gid;
2492  GlobalTransaction gxact;
2493 
2494  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2496 
2497  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2498  gid = (const char *) bufptr;
2499 
2500  /*
2501  * Reserve the GID for the given transaction in the redo code path.
2502  *
2503  * This creates a gxact struct and puts it into the active array.
2504  *
2505  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2506  * shared memory. Hence, we only fill up the bare minimum contents here.
2507  * The gxact also gets marked with gxact->inredo set to true to indicate
2508  * that it got added in the redo phase
2509  */
2510 
2511  /*
2512  * In the event of a crash while a checkpoint was running, it may be
2513  * possible that some two-phase data found its way to disk while its
2514  * corresponding record needs to be replayed in the follow-up recovery. As
2515  * the 2PC data was on disk, it has already been restored at the beginning
2516  * of recovery with restoreTwoPhaseData(), so skip this record to avoid
2517  * duplicates in TwoPhaseState. If a consistent state has been reached,
2518  * the record is added to TwoPhaseState and it should have no
2519  * corresponding file in pg_twophase.
2520  */
2521  if (!XLogRecPtrIsInvalid(start_lsn))
2522  {
2523  char path[MAXPGPATH];
2524 
2525  TwoPhaseFilePath(path, hdr->xid);
2526 
2527  if (access(path, F_OK) == 0)
2528  {
2530  (errmsg("could not recover two-phase state file for transaction %u",
2531  hdr->xid),
2532  errdetail("Two-phase state file has been found in WAL record %X/%X, but this transaction has already been restored from disk.",
2533  LSN_FORMAT_ARGS(start_lsn))));
2534  return;
2535  }
2536 
2537  if (errno != ENOENT)
2538  ereport(ERROR,
2540  errmsg("could not access file \"%s\": %m", path)));
2541  }
2542 
2543  /* Get a free gxact from the freelist */
2544  if (TwoPhaseState->freeGXacts == NULL)
2545  ereport(ERROR,
2546  (errcode(ERRCODE_OUT_OF_MEMORY),
2547  errmsg("maximum number of prepared transactions reached"),
2548  errhint("Increase \"max_prepared_transactions\" (currently %d).",
2549  max_prepared_xacts)));
2550  gxact = TwoPhaseState->freeGXacts;
2551  TwoPhaseState->freeGXacts = gxact->next;
2552 
2553  gxact->prepared_at = hdr->prepared_at;
2554  gxact->prepare_start_lsn = start_lsn;
2555  gxact->prepare_end_lsn = end_lsn;
2556  gxact->xid = hdr->xid;
2557  gxact->owner = hdr->owner;
2559  gxact->valid = false;
2560  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2561  gxact->inredo = true; /* yes, added in redo */
2562  strcpy(gxact->gid, gid);
2563 
2564  /* And insert it into the active array */
2567 
2568  if (origin_id != InvalidRepOriginId)
2569  {
2570  /* recover apply progress */
2571  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2572  false /* backward */ , false /* WAL */ );
2573  }
2574 
2575  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2576 }
int errcode_for_file_access(void)
Definition: elog.c:876
int errdetail(const char *fmt,...)
Definition: elog.c:1203
#define WARNING
Definition: elog.h:36
#define DEBUG2
Definition: elog.h:29
#define elog(elevel,...)
Definition: elog.h:225
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:892
#define MAXPGPATH
short access
Definition: preproc-type.c:36
TimestampTz prepared_at
Definition: xact.h:358
static int TwoPhaseFilePath(char *path, TransactionId xid)
Definition: twophase.c:961
bool RecoveryInProgress(void)
Definition: xlog.c:6333
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
bool reachedConsistency
Definition: xlogrecovery.c:295

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

Referenced by restoreTwoPhaseData(), and xact_redo().

◆ PrepareRedoRemove()

void PrepareRedoRemove ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 2588 of file twophase.c.

2589 {
2590  GlobalTransaction gxact = NULL;
2591  int i;
2592  bool found = false;
2593 
2594  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2596 
2597  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2598  {
2599  gxact = TwoPhaseState->prepXacts[i];
2600 
2601  if (gxact->xid == xid)
2602  {
2603  Assert(gxact->inredo);
2604  found = true;
2605  break;
2606  }
2607  }
2608 
2609  /*
2610  * Just leave if there is nothing, this is expected during WAL replay.
2611  */
2612  if (!found)
2613  return;
2614 
2615  /*
2616  * And now we can clean up any files we may have left.
2617  */
2618  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2619  if (gxact->ondisk)
2620  RemoveTwoPhaseFile(xid, giveWarning);
2621  RemoveGXact(gxact);
2622 }

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

Referenced by ProcessTwoPhaseBuffer(), and xact_redo().

◆ PrescanPreparedTransactions()

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

Definition at line 1969 of file twophase.c.

1970 {
1972  TransactionId origNextXid = XidFromFullTransactionId(nextXid);
1973  TransactionId result = origNextXid;
1974  TransactionId *xids = NULL;
1975  int nxids = 0;
1976  int allocsize = 0;
1977  int i;
1978 
1979  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1980  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1981  {
1982  TransactionId xid;
1983  char *buf;
1985 
1986  Assert(gxact->inredo);
1987 
1988  xid = gxact->xid;
1989 
1990  buf = ProcessTwoPhaseBuffer(xid,
1991  gxact->prepare_start_lsn,
1992  gxact->ondisk, false, true);
1993 
1994  if (buf == NULL)
1995  continue;
1996 
1997  /*
1998  * OK, we think this file is valid. Incorporate xid into the
1999  * running-minimum result.
2000  */
2001  if (TransactionIdPrecedes(xid, result))
2002  result = xid;
2003 
2004  if (xids_p)
2005  {
2006  if (nxids == allocsize)
2007  {
2008  if (nxids == 0)
2009  {
2010  allocsize = 10;
2011  xids = palloc(allocsize * sizeof(TransactionId));
2012  }
2013  else
2014  {
2015  allocsize = allocsize * 2;
2016  xids = repalloc(xids, allocsize * sizeof(TransactionId));
2017  }
2018  }
2019  xids[nxids++] = xid;
2020  }
2021 
2022  pfree(buf);
2023  }
2024  LWLockRelease(TwoPhaseStateLock);
2025 
2026  if (xids_p)
2027  {
2028  *xids_p = xids;
2029  *nxids_p = nxids;
2030  }
2031 
2032  return result;
2033 }
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1541
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2193

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

Referenced by StartupXLOG(), and xlog_redo().

◆ ProcessRecords()

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

Definition at line 1696 of file twophase.c.

1698 {
1699  for (;;)
1700  {
1701  TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1702 
1703  Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1704  if (record->rmid == TWOPHASE_RM_END_ID)
1705  break;
1706 
1707  bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1708 
1709  if (callbacks[record->rmid] != NULL)
1710  callbacks[record->rmid] (xid, record->info,
1711  (void *) bufptr, record->len);
1712 
1713  bufptr += MAXALIGN(record->len);
1714  }
1715 }
TwoPhaseRmgrId rmid
Definition: twophase.c:1002
#define TWOPHASE_RM_MAX_ID
Definition: twophase_rmgr.h:29

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

Referenced by FinishPreparedTransaction(), and RecoverPreparedTransactions().

◆ ProcessTwoPhaseBuffer()

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

Definition at line 2193 of file twophase.c.

2197 {
2199  TransactionId origNextXid = XidFromFullTransactionId(nextXid);
2200  TransactionId *subxids;
2201  char *buf;
2202  TwoPhaseFileHeader *hdr;
2203  int i;
2204 
2205  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2206 
2207  if (!fromdisk)
2208  Assert(prepare_start_lsn != InvalidXLogRecPtr);
2209 
2210  /* Already processed? */
2212  {
2213  if (fromdisk)
2214  {
2215  ereport(WARNING,
2216  (errmsg("removing stale two-phase state file for transaction %u",
2217  xid)));
2218  RemoveTwoPhaseFile(xid, true);
2219  }
2220  else
2221  {
2222  ereport(WARNING,
2223  (errmsg("removing stale two-phase state from memory for transaction %u",
2224  xid)));
2225  PrepareRedoRemove(xid, true);
2226  }
2227  return NULL;
2228  }
2229 
2230  /* Reject XID if too new */
2231  if (TransactionIdFollowsOrEquals(xid, origNextXid))
2232  {
2233  if (fromdisk)
2234  {
2235  ereport(WARNING,
2236  (errmsg("removing future two-phase state file for transaction %u",
2237  xid)));
2238  RemoveTwoPhaseFile(xid, true);
2239  }
2240  else
2241  {
2242  ereport(WARNING,
2243  (errmsg("removing future two-phase state from memory for transaction %u",
2244  xid)));
2245  PrepareRedoRemove(xid, true);
2246  }
2247  return NULL;
2248  }
2249 
2250  if (fromdisk)
2251  {
2252  /* Read and validate file */
2253  buf = ReadTwoPhaseFile(xid, false);
2254  }
2255  else
2256  {
2257  /* Read xlog data */
2258  XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2259  }
2260 
2261  /* Deconstruct header */
2262  hdr = (TwoPhaseFileHeader *) buf;
2263  if (!TransactionIdEquals(hdr->xid, xid))
2264  {
2265  if (fromdisk)
2266  ereport(ERROR,
2268  errmsg("corrupted two-phase state file for transaction %u",
2269  xid)));
2270  else
2271  ereport(ERROR,
2273  errmsg("corrupted two-phase state in memory for transaction %u",
2274  xid)));
2275  }
2276 
2277  /*
2278  * Examine subtransaction XIDs ... they should all follow main XID, and
2279  * they may force us to advance nextXid.
2280  */
2281  subxids = (TransactionId *) (buf +
2282  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2283  MAXALIGN(hdr->gidlen));
2284  for (i = 0; i < hdr->nsubxacts; i++)
2285  {
2286  TransactionId subxid = subxids[i];
2287 
2288  Assert(TransactionIdFollows(subxid, xid));
2289 
2290  /* update nextXid if needed */
2291  if (setNextXid)
2293 
2294  if (setParent)
2295  SubTransSetParent(subxid, xid);
2296  }
2297 
2298  return buf;
2299 }
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition: subtrans.c:85
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:188
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:314
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:329
void PrepareRedoRemove(TransactionId xid, bool giveWarning)
Definition: twophase.c:2588
void AdvanceNextFullTransactionIdPastXid(TransactionId xid)
Definition: varsup.c:304

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

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

◆ ReadTwoPhaseFile()

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

Definition at line 1303 of file twophase.c.

1304 {
1305  char path[MAXPGPATH];
1306  char *buf;
1307  TwoPhaseFileHeader *hdr;
1308  int fd;
1309  struct stat stat;
1310  uint32 crc_offset;
1311  pg_crc32c calc_crc,
1312  file_crc;
1313  int r;
1314 
1315  TwoPhaseFilePath(path, xid);
1316 
1317  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
1318  if (fd < 0)
1319  {
1320  if (missing_ok && errno == ENOENT)
1321  return NULL;
1322 
1323  ereport(ERROR,
1325  errmsg("could not open file \"%s\": %m", path)));
1326  }
1327 
1328  /*
1329  * Check file length. We can determine a lower bound pretty easily. We
1330  * set an upper bound to avoid palloc() failure on a corrupt file, though
1331  * we can't guarantee that we won't get an out of memory error anyway,
1332  * even on a valid file.
1333  */
1334  if (fstat(fd, &stat))
1335  ereport(ERROR,
1337  errmsg("could not stat file \"%s\": %m", path)));
1338 
1339  if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1340  MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1341  sizeof(pg_crc32c)) ||
1343  ereport(ERROR,
1345  errmsg_plural("incorrect size of file \"%s\": %lld byte",
1346  "incorrect size of file \"%s\": %lld bytes",
1347  (long long int) stat.st_size, path,
1348  (long long int) stat.st_size)));
1349 
1350  crc_offset = stat.st_size - sizeof(pg_crc32c);
1351  if (crc_offset != MAXALIGN(crc_offset))
1352  ereport(ERROR,
1354  errmsg("incorrect alignment of CRC offset for file \"%s\"",
1355  path)));
1356 
1357  /*
1358  * OK, slurp in the file.
1359  */
1360  buf = (char *) palloc(stat.st_size);
1361 
1362  pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_READ);
1363  r = read(fd, buf, stat.st_size);
1364  if (r != stat.st_size)
1365  {
1366  if (r < 0)
1367  ereport(ERROR,
1369  errmsg("could not read file \"%s\": %m", path)));
1370  else
1371  ereport(ERROR,
1372  (errmsg("could not read file \"%s\": read %d of %lld",
1373  path, r, (long long int) stat.st_size)));
1374  }
1375 
1377 
1378  if (CloseTransientFile(fd) != 0)
1379  ereport(ERROR,
1381  errmsg("could not close file \"%s\": %m", path)));
1382 
1383  hdr = (TwoPhaseFileHeader *) buf;
1384  if (hdr->magic != TWOPHASE_MAGIC)
1385  ereport(ERROR,
1387  errmsg("invalid magic number stored in file \"%s\"",
1388  path)));
1389 
1390  if (hdr->total_len != stat.st_size)
1391  ereport(ERROR,
1393  errmsg("invalid size stored in file \"%s\"",
1394  path)));
1395 
1396  INIT_CRC32C(calc_crc);
1397  COMP_CRC32C(calc_crc, buf, crc_offset);
1398  FIN_CRC32C(calc_crc);
1399 
1400  file_crc = *((pg_crc32c *) (buf + crc_offset));
1401 
1402  if (!EQ_CRC32C(calc_crc, file_crc))
1403  ereport(ERROR,
1405  errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
1406  path)));
1407 
1408  return buf;
1409 }
#define PG_BINARY
Definition: c.h:1276
int CloseTransientFile(int fd)
Definition: fd.c:2832
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2656
#define read(a, b, c)
Definition: win32.h:13
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:98
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:103
static int fd(const char *x, int i)
Definition: preproc-init.c:105
__int64 st_size
Definition: win32_port.h:273
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:85
static void pgstat_report_wait_end(void)
Definition: wait_event.h:101
#define fstat
Definition: win32_port.h:283

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

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

◆ RecordTransactionAbortPrepared()

static void RecordTransactionAbortPrepared ( TransactionId  xid,
int  nchildren,
TransactionId children,
int  nrels,
RelFileLocator rels,
int  nstats,
xl_xact_stats_item stats,
const char *  gid 
)
static

Definition at line 2411 of file twophase.c.

2419 {
2420  XLogRecPtr recptr;
2421  bool replorigin;
2422 
2423  /*
2424  * Are we using the replication origins feature? Or, in other words, are
2425  * we replaying remote actions?
2426  */
2427  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2429 
2430  /*
2431  * Catch the scenario where we aborted partway through
2432  * RecordTransactionCommitPrepared ...
2433  */
2434  if (TransactionIdDidCommit(xid))
2435  elog(PANIC, "cannot abort transaction %u, it was already committed",
2436  xid);
2437 
2439 
2440  /*
2441  * Emit the XLOG commit record. Note that we mark 2PC aborts as
2442  * potentially having AccessExclusiveLocks since we don't know whether or
2443  * not they do.
2444  */
2446  nchildren, children,
2447  nrels, rels,
2448  nstats, stats,
2450  xid, gid);
2451 
2452  if (replorigin)
2453  /* Move LSNs forward for this replication origin */
2455  XactLastRecEnd);
2456 
2457  /* Always flush, since we're about to remove the 2PC state file */
2458  XLogFlush(recptr);
2459 
2460  /*
2461  * Mark the transaction aborted in clog. This is not absolutely necessary
2462  * but we may as well do it while we are here.
2463  */
2464  TransactionIdAbortTree(xid, nchildren, children);
2465 
2466  END_CRIT_SECTION();
2467 
2468  /*
2469  * Wait for synchronous replication, if required.
2470  *
2471  * Note that at this stage we have marked clog, but still show as running
2472  * in the procarray and continue to hold locks.
2473  */
2474  SyncRepWaitForLSN(recptr, false);
2475 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1644
#define PANIC
Definition: elog.h:42
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:270
int MyXactFlags
Definition: xact.c:135
XLogRecPtr XactLogAbortRecord(TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileLocator *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition: xact.c:5973
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:108
XLogRecPtr XactLastRecEnd
Definition: xlog.c:253
uint64 XLogRecPtr
Definition: xlogdefs.h:21

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

Referenced by FinishPreparedTransaction().

◆ RecordTransactionCommitPrepared()

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

Definition at line 2313 of file twophase.c.

2324 {
2325  XLogRecPtr recptr;
2326  TimestampTz committs = GetCurrentTimestamp();
2327  bool replorigin;
2328 
2329  /*
2330  * Are we using the replication origins feature? Or, in other words, are
2331  * we replaying remote actions?
2332  */
2333  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2335 
2337 
2338  /* See notes in RecordTransactionCommit */
2341 
2342  /*
2343  * Emit the XLOG commit record. Note that we mark 2PC commits as
2344  * potentially having AccessExclusiveLocks since we don't know whether or
2345  * not they do.
2346  */
2347  recptr = XactLogCommitRecord(committs,
2348  nchildren, children, nrels, rels,
2349  nstats, stats,
2350  ninvalmsgs, invalmsgs,
2351  initfileinval,
2353  xid, gid);
2354 
2355 
2356  if (replorigin)
2357  /* Move LSNs forward for this replication origin */
2359  XactLastRecEnd);
2360 
2361  /*
2362  * Record commit timestamp. The value comes from plain commit timestamp
2363  * if replorigin is not enabled, or replorigin already set a value for us
2364  * in replorigin_session_origin_timestamp otherwise.
2365  *
2366  * We don't need to WAL-log anything here, as the commit record written
2367  * above already contains the data.
2368  */
2369  if (!replorigin || replorigin_session_origin_timestamp == 0)
2371 
2372  TransactionTreeSetCommitTsData(xid, nchildren, children,
2375 
2376  /*
2377  * We don't currently try to sleep before flush here ... nor is there any
2378  * support for async commit of a prepared xact (the very idea is probably
2379  * a contradiction)
2380  */
2381 
2382  /* Flush XLOG to disk */
2383  XLogFlush(recptr);
2384 
2385  /* Mark the transaction committed in pg_xact */
2386  TransactionIdCommitTree(xid, nchildren, children);
2387 
2388  /* Checkpoint can proceed now */
2390 
2391  END_CRIT_SECTION();
2392 
2393  /*
2394  * Wait for synchronous replication, if required.
2395  *
2396  * Note that at this stage we have marked clog, but still show as running
2397  * in the procarray and continue to hold locks.
2398  */
2399  SyncRepWaitForLSN(recptr, true);
2400 }
void TransactionTreeSetCommitTsData(TransactionId xid, int nsubxids, TransactionId *subxids, TimestampTz timestamp, RepOriginId nodeid)
Definition: commit_ts.c:141
int64 TimestampTz
Definition: timestamp.h:39
void TransactionIdCommitTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:240
XLogRecPtr XactLogCommitRecord(TimestampTz commit_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileLocator *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, int nmsgs, SharedInvalidationMessage *msgs, bool relcacheInval, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition: xact.c:5801

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

Referenced by FinishPreparedTransaction().

◆ RecoverPreparedTransactions()

void RecoverPreparedTransactions ( void  )

Definition at line 2090 of file twophase.c.

2091 {
2092  int i;
2093 
2094  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2095  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2096  {
2097  TransactionId xid;
2098  char *buf;
2100  char *bufptr;
2101  TwoPhaseFileHeader *hdr;
2102  TransactionId *subxids;
2103  const char *gid;
2104 
2105  xid = gxact->xid;
2106 
2107  /*
2108  * Reconstruct subtrans state for the transaction --- needed because
2109  * pg_subtrans is not preserved over a restart. Note that we are
2110  * linking all the subtransactions directly to the top-level XID;
2111  * there may originally have been a more complex hierarchy, but
2112  * there's no need to restore that exactly. It's possible that
2113  * SubTransSetParent has been set before, if the prepared transaction
2114  * generated xid assignment records.
2115  */
2116  buf = ProcessTwoPhaseBuffer(xid,
2117  gxact->prepare_start_lsn,
2118  gxact->ondisk, true, false);
2119  if (buf == NULL)
2120  continue;
2121 
2122  ereport(LOG,
2123  (errmsg("recovering prepared transaction %u from shared memory", xid)));
2124 
2125  hdr = (TwoPhaseFileHeader *) buf;
2126  Assert(TransactionIdEquals(hdr->xid, xid));
2127  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2128  gid = (const char *) bufptr;
2129  bufptr += MAXALIGN(hdr->gidlen);
2130  subxids = (TransactionId *) bufptr;
2131  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
2132  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
2133  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
2134  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
2135  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
2136  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
2137 
2138  /*
2139  * Recreate its GXACT and dummy PGPROC. But, check whether it was
2140  * added in redo and already has a shmem entry for it.
2141  */
2142  MarkAsPreparingGuts(gxact, xid, gid,
2143  hdr->prepared_at,
2144  hdr->owner, hdr->database);
2145 
2146  /* recovered, so reset the flag for entries generated by redo */
2147  gxact->inredo = false;
2148 
2149  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
2150  MarkAsPrepared(gxact, true);
2151 
2152  LWLockRelease(TwoPhaseStateLock);
2153 
2154  /*
2155  * Recover other state (notably locks) using resource managers.
2156  */
2158 
2159  /*
2160  * Release locks held by the standby process after we process each
2161  * prepared transaction. As a result, we don't need too many
2162  * additional locks at any one time.
2163  */
2164  if (InHotStandby)
2165  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2166 
2167  /*
2168  * We're done with recovering this transaction. Clear MyLockedGxact,
2169  * like we do in PrepareTransaction() during normal operation.
2170  */
2172 
2173  pfree(buf);
2174 
2175  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2176  }
2177 
2178  LWLockRelease(TwoPhaseStateLock);
2179 }
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:1091
Oid database
Definition: xact.h:357
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:504
void PostPrepare_Twophase(void)
Definition: twophase.c:344
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlogutils.h:60

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

Referenced by StartupXLOG().

◆ RecreateTwoPhaseFile()

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

Definition at line 1743 of file twophase.c.

1744 {
1745  char path[MAXPGPATH];
1746  pg_crc32c statefile_crc;
1747  int fd;
1748 
1749  /* Recompute CRC */
1750  INIT_CRC32C(statefile_crc);
1751  COMP_CRC32C(statefile_crc, content, len);
1752  FIN_CRC32C(statefile_crc);
1753 
1754  TwoPhaseFilePath(path, xid);
1755 
1756  fd = OpenTransientFile(path,
1757  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY);
1758  if (fd < 0)
1759  ereport(ERROR,
1761  errmsg("could not recreate file \"%s\": %m", path)));
1762 
1763  /* Write content and CRC */
1764  errno = 0;
1765  pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_WRITE);
1766  if (write(fd, content, len) != len)
1767  {
1768  /* if write didn't set errno, assume problem is no disk space */
1769  if (errno == 0)
1770  errno = ENOSPC;
1771  ereport(ERROR,
1773  errmsg("could not write file \"%s\": %m", path)));
1774  }
1775  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1776  {
1777  /* if write didn't set errno, assume problem is no disk space */
1778  if (errno == 0)
1779  errno = ENOSPC;
1780  ereport(ERROR,
1782  errmsg("could not write file \"%s\": %m", path)));
1783  }
1785 
1786  /*
1787  * We must fsync the file because the end-of-replay checkpoint will not do
1788  * so, there being no GXACT in shared memory yet to tell it to.
1789  */
1790  pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_SYNC);
1791  if (pg_fsync(fd) != 0)
1792  ereport(ERROR,
1794  errmsg("could not fsync file \"%s\": %m", path)));
1796 
1797  if (CloseTransientFile(fd) != 0)
1798  ereport(ERROR,
1800  errmsg("could not close file \"%s\": %m", path)));
1801 }
int pg_fsync(int fd)
Definition: fd.c:386
#define write(a, b, c)
Definition: win32.h:14

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

Referenced by CheckPointTwoPhase().

◆ RegisterTwoPhaseRecord()

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

Definition at line 1280 of file twophase.c.

1282 {
1283  TwoPhaseRecordOnDisk record;
1284 
1285  record.rmid = rmid;
1286  record.info = info;
1287  record.len = len;
1288  save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1289  if (len > 0)
1291 }
const void * data
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:1037

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

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

◆ RemoveGXact()

static void RemoveGXact ( GlobalTransaction  gxact)
static

Definition at line 628 of file twophase.c.

629 {
630  int i;
631 
632  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
633 
634  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
635  {
636  if (gxact == TwoPhaseState->prepXacts[i])
637  {
638  /* remove from the active array */
641 
642  /* and put it back in the freelist */
643  gxact->next = TwoPhaseState->freeGXacts;
644  TwoPhaseState->freeGXacts = gxact;
645 
646  return;
647  }
648  }
649 
650  elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
651 }

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

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

◆ RemoveTwoPhaseFile()

static void RemoveTwoPhaseFile ( TransactionId  xid,
bool  giveWarning 
)
static

Definition at line 1724 of file twophase.c.

1725 {
1726  char path[MAXPGPATH];
1727 
1728  TwoPhaseFilePath(path, xid);
1729  if (unlink(path))
1730  if (errno != ENOENT || giveWarning)
1731  ereport(WARNING,
1733  errmsg("could not remove file \"%s\": %m", path)));
1734 }

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

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

◆ restoreTwoPhaseData()

void restoreTwoPhaseData ( void  )

Definition at line 1905 of file twophase.c.

1906 {
1907  DIR *cldir;
1908  struct dirent *clde;
1909 
1910  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1911  cldir = AllocateDir(TWOPHASE_DIR);
1912  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1913  {
1914  if (strlen(clde->d_name) == 16 &&
1915  strspn(clde->d_name, "0123456789ABCDEF") == 16)
1916  {
1917  TransactionId xid;
1918  FullTransactionId fxid;
1919  char *buf;
1920 
1921  fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
1922  xid = XidFromFullTransactionId(fxid);
1923 
1925  true, false, false);
1926  if (buf == NULL)
1927  continue;
1928 
1931  }
1932  }
1933  LWLockRelease(TwoPhaseStateLock);
1934  FreeDir(cldir);
1935 }
#define strtou64(str, endptr, base)
Definition: c.h:1301
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2932
int FreeDir(DIR *dir)
Definition: fd.c:2984
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2866
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
static FullTransactionId FullTransactionIdFromU64(uint64 value)
Definition: transam.h:81
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2486

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

Referenced by StartupXLOG().

◆ save_state_data()

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

Definition at line 1037 of file twophase.c.

1038 {
1039  uint32 padlen = MAXALIGN(len);
1040 
1041  if (padlen > records.bytes_free)
1042  {
1043  records.tail->next = palloc0(sizeof(StateFileChunk));
1045  records.tail->len = 0;
1046  records.tail->next = NULL;
1047  records.num_chunks++;
1048 
1049  records.bytes_free = Max(padlen, 512);
1051  }
1052 
1053  memcpy(((char *) records.tail->data) + records.tail->len, data, len);
1054  records.tail->len += padlen;
1055  records.bytes_free -= padlen;
1056  records.total_len += padlen;
1057 }
#define Max(x, y)
Definition: c.h:1001
void * palloc0(Size size)
Definition: mcxt.c:1347
uint32 bytes_free
Definition: twophase.c:1023

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

Referenced by RegisterTwoPhaseRecord(), and StartPrepare().

◆ StandbyRecoverPreparedTransactions()

void StandbyRecoverPreparedTransactions ( void  )

Definition at line 2049 of file twophase.c.

2050 {
2051  int i;
2052 
2053  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2054  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2055  {
2056  TransactionId xid;
2057  char *buf;
2059 
2060  Assert(gxact->inredo);
2061 
2062  xid = gxact->xid;
2063 
2064  buf = ProcessTwoPhaseBuffer(xid,
2065  gxact->prepare_start_lsn,
2066  gxact->ondisk, true, false);
2067  if (buf != NULL)
2068  pfree(buf);
2069  }
2070  LWLockRelease(TwoPhaseStateLock);
2071 }

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

Referenced by StartupXLOG(), and xlog_redo().

◆ StandbyTransactionIdIsPrepared()

bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1475 of file twophase.c.

1476 {
1477  char *buf;
1478  TwoPhaseFileHeader *hdr;
1479  bool result;
1480 
1482 
1483  if (max_prepared_xacts <= 0)
1484  return false; /* nothing to do */
1485 
1486  /* Read and validate file */
1487  buf = ReadTwoPhaseFile(xid, true);
1488  if (buf == NULL)
1489  return false;
1490 
1491  /* Check header also */
1492  hdr = (TwoPhaseFileHeader *) buf;
1493  result = TransactionIdEquals(hdr->xid, xid);
1494  pfree(buf);
1495 
1496  return result;
1497 }

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

◆ StartPrepare()

void StartPrepare ( GlobalTransaction  gxact)

Definition at line 1065 of file twophase.c.

1066 {
1067  PGPROC *proc = GetPGProcByNumber(gxact->pgprocno);
1068  TransactionId xid = gxact->xid;
1069  TwoPhaseFileHeader hdr;
1070  TransactionId *children;
1071  RelFileLocator *commitrels;
1072  RelFileLocator *abortrels;
1073  xl_xact_stats_item *abortstats = NULL;
1074  xl_xact_stats_item *commitstats = NULL;
1075  SharedInvalidationMessage *invalmsgs;
1076 
1077  /* Initialize linked list */
1078  records.head = palloc0(sizeof(StateFileChunk));
1079  records.head->len = 0;
1080  records.head->next = NULL;
1081 
1082  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1084 
1086  records.num_chunks = 1;
1087 
1088  records.total_len = 0;
1089 
1090  /* Create header */
1091  hdr.magic = TWOPHASE_MAGIC;
1092  hdr.total_len = 0; /* EndPrepare will fill this in */
1093  hdr.xid = xid;
1094  hdr.database = proc->databaseId;
1095  hdr.prepared_at = gxact->prepared_at;
1096  hdr.owner = gxact->owner;
1097  hdr.nsubxacts = xactGetCommittedChildren(&children);
1098  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1099  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1100  hdr.ncommitstats =
1101  pgstat_get_transactional_drops(true, &commitstats);
1102  hdr.nabortstats =
1103  pgstat_get_transactional_drops(false, &abortstats);
1105  &hdr.initfileinval);
1106  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1107  /* EndPrepare will fill the origin data, if necessary */
1109  hdr.origin_timestamp = 0;
1110 
1111  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1112  save_state_data(gxact->gid, hdr.gidlen);
1113 
1114  /*
1115  * Add the additional info about subxacts, deletable files and cache
1116  * invalidation messages.
1117  */
1118  if (hdr.nsubxacts > 0)
1119  {
1120  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1121  /* While we have the child-xact data, stuff it in the gxact too */
1122  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1123  }
1124  if (hdr.ncommitrels > 0)
1125  {
1126  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileLocator));
1127  pfree(commitrels);
1128  }
1129  if (hdr.nabortrels > 0)
1130  {
1131  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileLocator));
1132  pfree(abortrels);
1133  }
1134  if (hdr.ncommitstats > 0)
1135  {
1136  save_state_data(commitstats,
1137  hdr.ncommitstats * sizeof(xl_xact_stats_item));
1138  pfree(commitstats);
1139  }
1140  if (hdr.nabortstats > 0)
1141  {
1142  save_state_data(abortstats,
1143  hdr.nabortstats * sizeof(xl_xact_stats_item));
1144  pfree(abortstats);
1145  }
1146  if (hdr.ninvalmsgs > 0)
1147  {
1148  save_state_data(invalmsgs,
1149  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1150  pfree(invalmsgs);
1151  }
1152 }
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:882
int pgstat_get_transactional_drops(bool isCommit, xl_xact_stats_item **items)
Definition: pgstat_xact.c:272
int smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
Definition: storage.c:852
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5777

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

Referenced by PrepareTransaction().

◆ TwoPhaseFilePath()

static int TwoPhaseFilePath ( char *  path,
TransactionId  xid 
)
inlinestatic

Definition at line 961 of file twophase.c.

962 {
964 
965  return snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X%08X",
968 }
#define snprintf
Definition: port.h:238
static FullTransactionId AdjustToFullTransactionId(TransactionId xid)
Definition: twophase.c:936

References AdjustToFullTransactionId(), EpochFromFullTransactionId, MAXPGPATH, snprintf, TWOPHASE_DIR, and XidFromFullTransactionId.

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

◆ TwoPhaseGetDummyProc()

PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid,
bool  lock_held 
)

Definition at line 918 of file twophase.c.

919 {
920  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
921 
922  return GetPGProcByNumber(gxact->pgprocno);
923 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:800

References GetPGProcByNumber, GlobalTransactionData::pgprocno, and TwoPhaseGetGXact().

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

◆ TwoPhaseGetDummyProcNumber()

ProcNumber TwoPhaseGetDummyProcNumber ( TransactionId  xid,
bool  lock_held 
)

Definition at line 903 of file twophase.c.

904 {
905  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
906 
907  return gxact->pgprocno;
908 }

References GlobalTransactionData::pgprocno, and TwoPhaseGetGXact().

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

◆ TwoPhaseGetGXact()

static GlobalTransaction TwoPhaseGetGXact ( TransactionId  xid,
bool  lock_held 
)
static

Definition at line 800 of file twophase.c.

801 {
802  GlobalTransaction result = NULL;
803  int i;
804 
805  static TransactionId cached_xid = InvalidTransactionId;
806  static GlobalTransaction cached_gxact = NULL;
807 
808  Assert(!lock_held || LWLockHeldByMe(TwoPhaseStateLock));
809 
810  /*
811  * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
812  * repeatedly for the same XID. We can save work with a simple cache.
813  */
814  if (xid == cached_xid)
815  return cached_gxact;
816 
817  if (!lock_held)
818  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
819 
820  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
821  {
823 
824  if (gxact->xid == xid)
825  {
826  result = gxact;
827  break;
828  }
829  }
830 
831  if (!lock_held)
832  LWLockRelease(TwoPhaseStateLock);
833 
834  if (result == NULL) /* should not happen */
835  elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
836 
837  cached_xid = xid;
838  cached_gxact = result;
839 
840  return result;
841 }
bool LWLockHeldByMe(LWLock *lock)
Definition: lwlock.c:1893

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

Referenced by TwoPhaseGetDummyProc(), and TwoPhaseGetDummyProcNumber().

◆ TwoPhaseGetXidByVirtualXID()

TransactionId TwoPhaseGetXidByVirtualXID ( VirtualTransactionId  vxid,
bool have_more 
)

Definition at line 852 of file twophase.c.

854 {
855  int i;
857 
859  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
860 
861  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
862  {
864  PGPROC *proc;
865  VirtualTransactionId proc_vxid;
866 
867  if (!gxact->valid)
868  continue;
869  proc = GetPGProcByNumber(gxact->pgprocno);
870  GET_VXID_FROM_PGPROC(proc_vxid, *proc);
871  if (VirtualTransactionIdEquals(vxid, proc_vxid))
872  {
873  /*
874  * Startup process sets proc->vxid.procNumber to
875  * INVALID_PROC_NUMBER.
876  */
877  Assert(!gxact->inredo);
878 
879  if (result != InvalidTransactionId)
880  {
881  *have_more = true;
882  break;
883  }
884  result = gxact->xid;
885  }
886  }
887 
888  LWLockRelease(TwoPhaseStateLock);
889 
890  return result;
891 }
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:67
#define GET_VXID_FROM_PGPROC(vxid_dst, proc)
Definition: lock.h:77
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:71

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

Referenced by XactLockForVirtualXact().

◆ TwoPhaseShmemInit()

void TwoPhaseShmemInit ( void  )

Definition at line 253 of file twophase.c.

254 {
255  bool found;
256 
257  TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
259  &found);
260  if (!IsUnderPostmaster)
261  {
262  GlobalTransaction gxacts;
263  int i;
264 
265  Assert(!found);
266  TwoPhaseState->freeGXacts = NULL;
268 
269  /*
270  * Initialize the linked list of free GlobalTransactionData structs
271  */
272  gxacts = (GlobalTransaction)
273  ((char *) TwoPhaseState +
274  MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
276  for (i = 0; i < max_prepared_xacts; i++)
277  {
278  /* insert into linked list */
279  gxacts[i].next = TwoPhaseState->freeGXacts;
280  TwoPhaseState->freeGXacts = &gxacts[i];
281 
282  /* associate it with a PGPROC assigned by InitProcGlobal */
284  }
285  }
286  else
287  Assert(found);
288 }
bool IsUnderPostmaster
Definition: globals.c:119
#define GetNumberFromPGProc(proc)
Definition: proc.h:433
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387
PGPROC * PreparedXactProcs
Definition: proc.c:81
Size TwoPhaseShmemSize(void)
Definition: twophase.c:237

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

Referenced by CreateOrAttachShmemStructs().

◆ TwoPhaseShmemSize()

Size TwoPhaseShmemSize ( void  )

Definition at line 237 of file twophase.c.

238 {
239  Size size;
240 
241  /* Need the fixed struct, the array of pointers, and the GTD structs */
242  size = offsetof(TwoPhaseStateData, prepXacts);
244  sizeof(GlobalTransaction)));
245  size = MAXALIGN(size);
247  sizeof(GlobalTransactionData)));
248 
249  return size;
250 }
size_t Size
Definition: c.h:608
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
static pg_noinline void Size size
Definition: slab.c:607

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

Referenced by CalculateShmemSize(), and TwoPhaseShmemInit().

◆ TwoPhaseTransactionGid()

void TwoPhaseTransactionGid ( Oid  subid,
TransactionId  xid,
char *  gid_res,
int  szgid 
)

Definition at line 2699 of file twophase.c.

2700 {
2701  Assert(OidIsValid(subid));
2702 
2703  if (!TransactionIdIsValid(xid))
2704  ereport(ERROR,
2705  (errcode(ERRCODE_PROTOCOL_VIOLATION),
2706  errmsg_internal("invalid two-phase transaction ID")));
2707 
2708  snprintf(gid_res, szgid, "pg_gid_%u_%u", subid, xid);
2709 }
#define OidIsValid(objectId)
Definition: c.h:778
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157

References Assert, ereport, errcode(), errmsg_internal(), ERROR, OidIsValid, snprintf, and TransactionIdIsValid.

Referenced by apply_handle_commit_prepared(), apply_handle_prepare_internal(), apply_handle_rollback_prepared(), and IsTwoPhaseTransactionGidForSubid().

◆ XlogReadTwoPhaseData()

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

Definition at line 1420 of file twophase.c.

1421 {
1422  XLogRecord *record;
1424  char *errormsg;
1425 
1427  XL_ROUTINE(.page_read = &read_local_xlog_page,
1428  .segment_open = &wal_segment_open,
1429  .segment_close = &wal_segment_close),
1430  NULL);
1431  if (!xlogreader)
1432  ereport(ERROR,
1433  (errcode(ERRCODE_OUT_OF_MEMORY),
1434  errmsg("out of memory"),
1435  errdetail("Failed while allocating a WAL reading processor.")));
1436 
1437  XLogBeginRead(xlogreader, lsn);
1438  record = XLogReadRecord(xlogreader, &errormsg);
1439 
1440  if (record == NULL)
1441  {
1442  if (errormsg)
1443  ereport(ERROR,
1445  errmsg("could not read two-phase state from WAL at %X/%X: %s",
1446  LSN_FORMAT_ARGS(lsn), errormsg)));
1447  else
1448  ereport(ERROR,
1450  errmsg("could not read two-phase state from WAL at %X/%X",
1451  LSN_FORMAT_ARGS(lsn))));
1452  }
1453 
1454  if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1456  ereport(ERROR,
1458  errmsg("expected two-phase state data is not present in WAL at %X/%X",
1459  LSN_FORMAT_ARGS(lsn))));
1460 
1461  if (len != NULL)
1463 
1464  *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1465  memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1466 
1468 }
#define XLOG_XACT_OPMASK
Definition: xact.h:179
int wal_segment_size
Definition: xlog.c:142
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:389
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:161
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:106
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:231
#define XLogRecGetDataLen(decoder)
Definition: xlogreader.h:416
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:410
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:411
#define XLogRecGetData(decoder)
Definition: xlogreader.h:415
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
static XLogReaderState * xlogreader
Definition: xlogrecovery.c:189
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:842
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:817
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:861

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

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

Variable Documentation

◆ max_prepared_xacts

◆ MyLockedGxact

◆ records

struct xllist records
static

◆ twophaseExitRegistered

bool twophaseExitRegistered = false
static

Definition at line 198 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

◆ TwoPhaseState