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

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Functions

static void RecordTransactionCommitPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval)
 
static void RecordTransactionAbortPrepared (TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels)
 
static void ProcessRecords (char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
 
static void RemoveGXact (GlobalTransaction gxact)
 
static void XlogReadTwoPhaseData (XLogRecPtr lsn, char **buf, int *len)
 
static char * ProcessTwoPhaseBuffer (TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool overwriteOK, 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)
 
static GlobalTransaction LockGXact (const char *gid, Oid user)
 
static int GetPreparedTransactionList (GlobalTransaction *gxacts)
 
Datum pg_prepared_xact (PG_FUNCTION_ARGS)
 
static GlobalTransaction TwoPhaseGetGXact (TransactionId xid)
 
BackendId TwoPhaseGetDummyBackendId (TransactionId xid)
 
PGPROCTwoPhaseGetDummyProc (TransactionId xid)
 
static void save_state_data (const void *data, uint32 len)
 
void StartPrepare (GlobalTransaction gxact)
 
void EndPrepare (GlobalTransaction gxact)
 
void RegisterTwoPhaseRecord (TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
 
static char * ReadTwoPhaseFile (TransactionId xid, bool give_warnings)
 
bool StandbyTransactionIdIsPrepared (TransactionId xid)
 
void FinishPreparedTransaction (const char *gid, bool isCommit)
 
void CheckPointTwoPhase (XLogRecPtr redo_horizon)
 
void restoreTwoPhaseData (void)
 
TransactionId PrescanPreparedTransactions (TransactionId **xids_p, int *nxids_p)
 
void StandbyRecoverPreparedTransactions (bool overwriteOK)
 
void RecoverPreparedTransactions (void)
 
void PrepareRedoAdd (char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
 
void PrepareRedoRemove (TransactionId xid, bool giveWarning)
 

Variables

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

Macro Definition Documentation

#define GIDSIZE   200

Definition at line 151 of file twophase.c.

Referenced by MarkAsPreparing().

#define TWOPHASE_DIR   "pg_twophase"

Definition at line 114 of file twophase.c.

Referenced by CheckPointTwoPhase(), and restoreTwoPhaseData().

#define TWOPHASE_MAGIC   0x57F94533 /* format identifier */

Definition at line 902 of file twophase.c.

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

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

Definition at line 880 of file twophase.c.

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

Typedef Documentation

Function Documentation

void AtAbort_Twophase ( void  )

Definition at line 317 of file twophase.c.

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

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

Definition at line 307 of file twophase.c.

References AtAbort_Twophase().

Referenced by LockGXact(), and MarkAsPreparing().

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

Definition at line 1650 of file twophase.c.

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

Referenced by CheckPointGuts().

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

Definition at line 1065 of file twophase.c.

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

Referenced by PrepareTransaction().

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

Definition at line 1368 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Assert, AtEOXact_PgStat(), buf, GetUserId(), TwoPhaseFileHeader::gidlen, i, TwoPhaseFileHeader::initfileinval, InvalidBackendId, LockGXact(), MAXALIGN, TwoPhaseFileHeader::nabortrels, TwoPhaseFileHeader::ncommitrels, TwoPhaseFileHeader::ninvalmsgs, TwoPhaseFileHeader::nsubxacts, NULL, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::pgprocno, PredicateLockTwoPhaseFinish(), GlobalTransactionData::prepare_start_lsn, ProcArrayRemove(), ProcessRecords(), ProcGlobal, ReadTwoPhaseFile(), RecordTransactionAbortPrepared(), RecordTransactionCommitPrepared(), RelationCacheInitFilePostInvalidate(), RelationCacheInitFilePreInvalidate(), RemoveGXact(), RemoveTwoPhaseFile(), SendSharedInvalidMessages(), smgrclose(), smgrdounlink(), smgropen(), TransactionIdEquals, TransactionIdLatest(), twophase_postabort_callbacks, twophase_postcommit_callbacks, GlobalTransactionData::valid, PGXACT::xid, TwoPhaseFileHeader::xid, and XlogReadTwoPhaseData().

Referenced by standard_ProcessUtility().

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

Definition at line 674 of file twophase.c.

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

Referenced by pg_prepared_xact().

675 {
676  GlobalTransaction array;
677  int num;
678  int i;
679 
680  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
681 
682  if (TwoPhaseState->numPrepXacts == 0)
683  {
684  LWLockRelease(TwoPhaseStateLock);
685 
686  *gxacts = NULL;
687  return 0;
688  }
689 
691  array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
692  *gxacts = array;
693  for (i = 0; i < num; i++)
694  memcpy(array + i, TwoPhaseState->prepXacts[i],
695  sizeof(GlobalTransactionData));
696 
697  LWLockRelease(TwoPhaseStateLock);
698 
699  return num;
700 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:25
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
#define NULL
Definition: c.h:229
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
void * palloc(Size size)
Definition: mcxt.c:849
int i
static void GXactLoadSubxactData ( GlobalTransaction  gxact,
int  nsubxacts,
TransactionId children 
)
static

Definition at line 511 of file twophase.c.

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

Referenced by RecoverPreparedTransactions(), and StartPrepare().

513 {
514  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
515  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
516 
517  /* We need no extra lock since the GXACT isn't valid yet */
518  if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
519  {
520  pgxact->overflowed = true;
521  nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
522  }
523  if (nsubxacts > 0)
524  {
525  memcpy(proc->subxids.xids, children,
526  nsubxacts * sizeof(TransactionId));
527  pgxact->nxids = nsubxacts;
528  }
529 }
uint32 TransactionId
Definition: c.h:397
Definition: proc.h:207
PGXACT * allPgXact
Definition: proc.h:234
PROC_HDR * ProcGlobal
Definition: proc.c:80
uint8 nxids
Definition: proc.h:223
struct XidCache subxids
Definition: proc.h:158
bool overflowed
Definition: proc.h:219
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:35
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:39
PGPROC * allProcs
Definition: proc.h:232
Definition: proc.h:94
static GlobalTransaction LockGXact ( const char *  gid,
Oid  user 
)
static

Definition at line 556 of file twophase.c.

References PROC_HDR::allProcs, AtProcExit_Twophase(), before_shmem_exit(), PGPROC::databaseId, ereport, errcode(), errhint(), errmsg(), ERROR, GlobalTransactionData::gid, i, InvalidBackendId, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyBackendId, MyDatabaseId, NULL, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::owner, GlobalTransactionData::pgprocno, TwoPhaseStateData::prepXacts, ProcGlobal, superuser_arg(), twophaseExitRegistered, and GlobalTransactionData::valid.

Referenced by FinishPreparedTransaction().

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

Definition at line 536 of file twophase.c.

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

Referenced by EndPrepare(), and RecoverPreparedTransactions().

537 {
538  /* Lock here may be overkill, but I'm not convinced of that ... */
539  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
540  Assert(!gxact->valid);
541  gxact->valid = true;
542  LWLockRelease(TwoPhaseStateLock);
543 
544  /*
545  * Put it into the global ProcArray so TransactionIdIsInProgress considers
546  * the XID as still running.
547  */
549 }
PROC_HDR * ProcGlobal
Definition: proc.c:80
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define Assert(condition)
Definition: c.h:675
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
PGPROC * allProcs
Definition: proc.h:232
void ProcArrayAdd(PGPROC *proc)
Definition: procarray.c:274
GlobalTransaction MarkAsPreparing ( TransactionId  xid,
const char *  gid,
TimestampTz  prepared_at,
Oid  owner,
Oid  databaseid 
)

Definition at line 377 of file twophase.c.

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

Referenced by PrepareTransaction().

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

Definition at line 451 of file twophase.c.

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

Referenced by MarkAsPreparing(), and RecoverPreparedTransactions().

453 {
454  PGPROC *proc;
455  PGXACT *pgxact;
456  int i;
457 
458  Assert(gxact != NULL);
459  proc = &ProcGlobal->allProcs[gxact->pgprocno];
460  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
461 
462  /* Initialize the PGPROC entry */
463  MemSet(proc, 0, sizeof(PGPROC));
464  proc->pgprocno = gxact->pgprocno;
465  SHMQueueElemInit(&(proc->links));
466  proc->waitStatus = STATUS_OK;
467  /* We set up the gxact's VXID as InvalidBackendId/XID */
468  proc->lxid = (LocalTransactionId) xid;
469  pgxact->xid = xid;
470  pgxact->xmin = InvalidTransactionId;
471  pgxact->delayChkpt = false;
472  pgxact->vacuumFlags = 0;
473  proc->pid = 0;
474  proc->backendId = InvalidBackendId;
475  proc->databaseId = databaseid;
476  proc->roleId = owner;
477  proc->isBackgroundWorker = false;
478  proc->lwWaiting = false;
479  proc->lwWaitMode = 0;
480  proc->waitLock = NULL;
481  proc->waitProcLock = NULL;
482  for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
483  SHMQueueInit(&(proc->myProcLocks[i]));
484  /* subxid data must be filled later by GXactLoadSubxactData */
485  pgxact->overflowed = false;
486  pgxact->nxids = 0;
487 
488  gxact->prepared_at = prepared_at;
489  gxact->xid = xid;
490  gxact->owner = owner;
491  gxact->locking_backend = MyBackendId;
492  gxact->valid = false;
493  gxact->inredo = false;
494  strcpy(gxact->gid, gid);
495 
496  /*
497  * Remember that we have this GlobalTransaction entry locked for us. If we
498  * abort after this, we must release it.
499  */
500  MyLockedGxact = gxact;
501 }
BackendId MyBackendId
Definition: globals.c:72
BackendId backendId
Definition: proc.h:112
Definition: proc.h:207
TransactionId xmin
Definition: proc.h:213
PGXACT * allPgXact
Definition: proc.h:234
TransactionId xid
Definition: proc.h:209
SHM_QUEUE links
Definition: proc.h:97
bool lwWaiting
Definition: proc.h:126
Oid roleId
Definition: proc.h:114
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:857
uint8 lwWaitMode
Definition: proc.h:127
char gid[GIDSIZE]
Definition: twophase.c:176
uint8 vacuumFlags
Definition: proc.h:218
BackendId locking_backend
Definition: twophase.c:172
bool isBackgroundWorker
Definition: proc.h:116
PROCLOCK * waitProcLock
Definition: proc.h:136
uint8 nxids
Definition: proc.h:223
#define InvalidTransactionId
Definition: transam.h:31
Oid databaseId
Definition: proc.h:113
uint32 LocalTransactionId
Definition: c.h:399
LOCK * waitLock
Definition: proc.h:135
#define STATUS_OK
Definition: c.h:975
bool delayChkpt
Definition: proc.h:220
#define InvalidBackendId
Definition: backendid.h:23
bool overflowed
Definition: proc.h:219
int waitStatus
Definition: proc.h:101
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
TransactionId xid
Definition: twophase.c:169
TimestampTz prepared_at
Definition: twophase.c:158
void SHMQueueElemInit(SHM_QUEUE *queue)
Definition: shmqueue.c:57
int pgprocno
Definition: proc.h:109
void SHMQueueInit(SHM_QUEUE *queue)
Definition: shmqueue.c:36
static GlobalTransaction MyLockedGxact
Definition: twophase.c:200
int i
PGPROC * allProcs
Definition: proc.h:232
SHM_QUEUE myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:156
Definition: proc.h:94
int pid
Definition: proc.h:108
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:117
LocalTransactionId lxid
Definition: proc.h:105
Datum pg_prepared_xact ( PG_FUNCTION_ARGS  )

Definition at line 719 of file twophase.c.

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

720 {
721  FuncCallContext *funcctx;
723 
724  if (SRF_IS_FIRSTCALL())
725  {
726  TupleDesc tupdesc;
727  MemoryContext oldcontext;
728 
729  /* create a function context for cross-call persistence */
730  funcctx = SRF_FIRSTCALL_INIT();
731 
732  /*
733  * Switch to memory context appropriate for multiple function calls
734  */
735  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
736 
737  /* build tupdesc for result tuples */
738  /* this had better match pg_prepared_xacts view in system_views.sql */
739  tupdesc = CreateTemplateTupleDesc(5, false);
740  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
741  XIDOID, -1, 0);
742  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
743  TEXTOID, -1, 0);
744  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
745  TIMESTAMPTZOID, -1, 0);
746  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
747  OIDOID, -1, 0);
748  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
749  OIDOID, -1, 0);
750 
751  funcctx->tuple_desc = BlessTupleDesc(tupdesc);
752 
753  /*
754  * Collect all the 2PC status information that we will format and send
755  * out as a result set.
756  */
757  status = (Working_State *) palloc(sizeof(Working_State));
758  funcctx->user_fctx = (void *) status;
759 
760  status->ngxacts = GetPreparedTransactionList(&status->array);
761  status->currIdx = 0;
762 
763  MemoryContextSwitchTo(oldcontext);
764  }
765 
766  funcctx = SRF_PERCALL_SETUP();
767  status = (Working_State *) funcctx->user_fctx;
768 
769  while (status->array != NULL && status->currIdx < status->ngxacts)
770  {
771  GlobalTransaction gxact = &status->array[status->currIdx++];
772  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
773  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
774  Datum values[5];
775  bool nulls[5];
776  HeapTuple tuple;
777  Datum result;
778 
779  if (!gxact->valid)
780  continue;
781 
782  /*
783  * Form tuple with appropriate data.
784  */
785  MemSet(values, 0, sizeof(values));
786  MemSet(nulls, 0, sizeof(nulls));
787 
788  values[0] = TransactionIdGetDatum(pgxact->xid);
789  values[1] = CStringGetTextDatum(gxact->gid);
790  values[2] = TimestampTzGetDatum(gxact->prepared_at);
791  values[3] = ObjectIdGetDatum(gxact->owner);
792  values[4] = ObjectIdGetDatum(proc->databaseId);
793 
794  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
795  result = HeapTupleGetDatum(tuple);
796  SRF_RETURN_NEXT(funcctx, result);
797  }
798 
799  SRF_RETURN_DONE(funcctx);
800 }
#define TIMESTAMPTZOID
Definition: pg_type.h:525
Definition: proc.h:207
#define OIDOID
Definition: pg_type.h:328
#define TEXTOID
Definition: pg_type.h:324
PGXACT * allPgXact
Definition: proc.h:234
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:285
TransactionId xid
Definition: proc.h:209
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition: twophase.c:674
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:857
return result
Definition: formatting.c:1618
#define XIDOID
Definition: pg_type.h:336
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:289
char gid[GIDSIZE]
Definition: twophase.c:176
TupleDesc tuple_desc
Definition: funcapi.h:120
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:291
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:1031
Oid databaseId
Definition: proc.h:113
GlobalTransaction array
Definition: twophase.c:706
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:497
#define TransactionIdGetDatum(X)
Definition: postgres.h:527
uintptr_t Datum
Definition: postgres.h:372
#define NULL
Definition: c.h:229
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:109
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:222
TupleDesc CreateTemplateTupleDesc(int natts, bool hasoid)
Definition: tupdesc.c:41
static Datum values[MAXATTR]
Definition: bootstrap.c:163
TimestampTz prepared_at
Definition: twophase.c:158
void * user_fctx
Definition: funcapi.h:90
void * palloc(Size size)
Definition: mcxt.c:849
#define CStringGetTextDatum(s)
Definition: builtins.h:91
PGPROC * allProcs
Definition: proc.h:232
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
Definition: proc.h:94
int16 AttrNumber
Definition: attnum.h:21
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:309
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:287
void PostPrepare_Twophase ( void  )

Definition at line 362 of file twophase.c.

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

363 {
364  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
366  LWLockRelease(TwoPhaseStateLock);
367 
369 }
BackendId locking_backend
Definition: twophase.c:172
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define InvalidBackendId
Definition: backendid.h:23
#define NULL
Definition: c.h:229
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
static GlobalTransaction MyLockedGxact
Definition: twophase.c:200
void PrepareRedoAdd ( char *  buf,
XLogRecPtr  start_lsn,
XLogRecPtr  end_lsn 
)

Definition at line 2312 of file twophase.c.

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

Referenced by restoreTwoPhaseData(), and xact_redo().

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

Definition at line 2374 of file twophase.c.

References Assert, DEBUG2, elog, i, GlobalTransactionData::inredo, LW_SHARED, LWLockAcquire(), LWLockRelease(), NULL, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, TwoPhaseStateData::prepXacts, RecoveryInProgress(), RemoveGXact(), RemoveTwoPhaseFile(), and GlobalTransactionData::xid.

Referenced by ProcessTwoPhaseBuffer(), and xact_redo().

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

Definition at line 1785 of file twophase.c.

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

Referenced by StartupXLOG(), and xlog_redo().

1786 {
1787  TransactionId origNextXid = ShmemVariableCache->nextXid;
1788  TransactionId result = origNextXid;
1789  TransactionId *xids = NULL;
1790  int nxids = 0;
1791  int allocsize = 0;
1792  int i;
1793 
1794  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1795  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1796  {
1797  TransactionId xid;
1798  char *buf;
1800 
1801  Assert(gxact->inredo);
1802 
1803  xid = gxact->xid;
1804 
1805  buf = ProcessTwoPhaseBuffer(xid,
1806  gxact->prepare_start_lsn,
1807  gxact->ondisk, false, false,
1808  true);
1809 
1810  if (buf == NULL)
1811  continue;
1812 
1813  /*
1814  * OK, we think this file is valid. Incorporate xid into the
1815  * running-minimum result.
1816  */
1817  if (TransactionIdPrecedes(xid, result))
1818  result = xid;
1819 
1820  if (xids_p)
1821  {
1822  if (nxids == allocsize)
1823  {
1824  if (nxids == 0)
1825  {
1826  allocsize = 10;
1827  xids = palloc(allocsize * sizeof(TransactionId));
1828  }
1829  else
1830  {
1831  allocsize = allocsize * 2;
1832  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1833  }
1834  }
1835  xids[nxids++] = xid;
1836  }
1837 
1838  pfree(buf);
1839  }
1840  LWLockRelease(TwoPhaseStateLock);
1841 
1842  if (xids_p)
1843  {
1844  *xids_p = xids;
1845  *nxids_p = nxids;
1846  }
1847 
1848  return result;
1849 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
uint32 TransactionId
Definition: c.h:397
return result
Definition: formatting.c:1618
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
void pfree(void *pointer)
Definition: mcxt.c:950
TransactionId nextXid
Definition: transam.h:117
static char * buf
Definition: pg_test_fsync.c:66
VariableCache ShmemVariableCache
Definition: varsup.c:34
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool overwriteOK, bool setParent, bool setNextXid)
Definition: twophase.c:2016
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:963
TransactionId xid
Definition: twophase.c:169
void * palloc(Size size)
Definition: mcxt.c:849
int i
static void ProcessRecords ( char *  bufptr,
TransactionId  xid,
const TwoPhaseCallback  callbacks[] 
)
static

Definition at line 1520 of file twophase.c.

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

Referenced by FinishPreparedTransaction(), and RecoverPreparedTransactions().

1522 {
1523  for (;;)
1524  {
1525  TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1526 
1527  Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1528  if (record->rmid == TWOPHASE_RM_END_ID)
1529  break;
1530 
1531  bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1532 
1533  if (callbacks[record->rmid] != NULL)
1534  callbacks[record->rmid] (xid, record->info,
1535  (void *) bufptr, record->len);
1536 
1537  bufptr += MAXALIGN(record->len);
1538  }
1539 }
#define TWOPHASE_RM_MAX_ID
Definition: twophase_rmgr.h:29
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define MAXALIGN(LEN)
Definition: c.h:588
TwoPhaseRmgrId rmid
Definition: twophase.c:929
static char * ProcessTwoPhaseBuffer ( TransactionId  xid,
XLogRecPtr  prepare_start_lsn,
bool  fromdisk,
bool  overwriteOK,
bool  setParent,
bool  setNextXid 
)
static

Definition at line 2016 of file twophase.c.

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

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

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

Definition at line 1186 of file twophase.c.

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

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

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

Definition at line 2255 of file twophase.c.

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

Referenced by FinishPreparedTransaction().

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

Definition at line 2163 of file twophase.c.

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

Referenced by FinishPreparedTransaction().

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

Definition at line 1900 of file twophase.c.

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

Referenced by StartupXLOG().

1901 {
1902  int i;
1903 
1904  /*
1905  * Don't need a lock in the recovery phase.
1906  */
1907  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1908  {
1909  TransactionId xid;
1910  char *buf;
1912  char *bufptr;
1913  TwoPhaseFileHeader *hdr;
1914  TransactionId *subxids;
1915  const char *gid;
1916  bool overwriteOK = false;
1917  int i;
1918 
1919  xid = gxact->xid;
1920 
1921  buf = ProcessTwoPhaseBuffer(xid,
1922  gxact->prepare_start_lsn,
1923  gxact->ondisk, false, false,
1924  false);
1925  if (buf == NULL)
1926  continue;
1927 
1928  ereport(LOG,
1929  (errmsg("recovering prepared transaction %u from shared memory", xid)));
1930 
1931  hdr = (TwoPhaseFileHeader *) buf;
1932  Assert(TransactionIdEquals(hdr->xid, xid));
1933  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1934  gid = (const char *) bufptr;
1935  bufptr += MAXALIGN(hdr->gidlen);
1936  subxids = (TransactionId *) bufptr;
1937  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1938  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1939  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1940  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1941 
1942  /*
1943  * It's possible that SubTransSetParent has been set before, if
1944  * the prepared transaction generated xid assignment records. Test
1945  * here must match one used in AssignTransactionId().
1946  */
1949  overwriteOK = true;
1950 
1951  /*
1952  * Reconstruct subtrans state for the transaction --- needed
1953  * because pg_subtrans is not preserved over a restart. Note that
1954  * we are linking all the subtransactions directly to the
1955  * top-level XID; there may originally have been a more complex
1956  * hierarchy, but there's no need to restore that exactly.
1957  */
1958  for (i = 0; i < hdr->nsubxacts; i++)
1959  SubTransSetParent(subxids[i], xid, true);
1960 
1961  /*
1962  * Recreate its GXACT and dummy PGPROC. But, check whether
1963  * it was added in redo and already has a shmem entry for
1964  * it.
1965  */
1966  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1967  MarkAsPreparingGuts(gxact, xid, gid,
1968  hdr->prepared_at,
1969  hdr->owner, hdr->database);
1970 
1971  /* recovered, so reset the flag for entries generated by redo */
1972  gxact->inredo = false;
1973 
1974  LWLockRelease(TwoPhaseStateLock);
1975 
1976  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1977  MarkAsPrepared(gxact);
1978 
1979  /*
1980  * Recover other state (notably locks) using resource managers
1981  */
1983 
1984  /*
1985  * Release locks held by the standby process after we process each
1986  * prepared transaction. As a result, we don't need too many
1987  * additional locks at any one time.
1988  */
1989  if (InHotStandby)
1990  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
1991 
1992  /*
1993  * We're done with recovering this transaction. Clear
1994  * MyLockedGxact, like we do in PrepareTransaction() during normal
1995  * operation.
1996  */
1998 
1999  pfree(buf);
2000  }
2001 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:397
void SubTransSetParent(TransactionId xid, TransactionId parent, bool overwriteOK)
Definition: subtrans.c:75
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1520
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlog.h:74
TransactionId xid
Definition: twophase.c:908
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
void pfree(void *pointer)
Definition: mcxt.c:950
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:451
#define XLogLogicalInfoActive()
Definition: xlog.h:162
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:511
static char * buf
Definition: pg_test_fsync.c:66
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:676
#define ereport(elevel, rest)
Definition: elog.h:122
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:35
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void MarkAsPrepared(GlobalTransaction gxact)
Definition: twophase.c:536
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool overwriteOK, bool setParent, bool setNextXid)
Definition: twophase.c:2016
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
#define MAXALIGN(LEN)
Definition: c.h:588
TransactionId xid
Definition: twophase.c:169
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PostPrepare_Twophase(void)
Definition: twophase.c:362
int i
TimestampTz prepared_at
Definition: twophase.c:910
static void RecreateTwoPhaseFile ( TransactionId  xid,
void *  content,
int  len 
)
static

Definition at line 1568 of file twophase.c.

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

Referenced by CheckPointTwoPhase().

1569 {
1570  char path[MAXPGPATH];
1571  pg_crc32c statefile_crc;
1572  int fd;
1573 
1574  /* Recompute CRC */
1575  INIT_CRC32C(statefile_crc);
1576  COMP_CRC32C(statefile_crc, content, len);
1577  FIN_CRC32C(statefile_crc);
1578 
1579  TwoPhaseFilePath(path, xid);
1580 
1581  fd = OpenTransientFile(path,
1582  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY,
1583  S_IRUSR | S_IWUSR);
1584  if (fd < 0)
1585  ereport(ERROR,
1587  errmsg("could not recreate two-phase state file \"%s\": %m",
1588  path)));
1589 
1590  /* Write content and CRC */
1592  if (write(fd, content, len) != len)
1593  {
1595  CloseTransientFile(fd);
1596  ereport(ERROR,
1598  errmsg("could not write two-phase state file: %m")));
1599  }
1600  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1601  {
1603  CloseTransientFile(fd);
1604  ereport(ERROR,
1606  errmsg("could not write two-phase state file: %m")));
1607  }
1609 
1610  /*
1611  * We must fsync the file because the end-of-replay checkpoint will not do
1612  * so, there being no GXACT in shared memory yet to tell it to.
1613  */
1615  if (pg_fsync(fd) != 0)
1616  {
1617  CloseTransientFile(fd);
1618  ereport(ERROR,
1620  errmsg("could not fsync two-phase state file: %m")));
1621  }
1623 
1624  if (CloseTransientFile(fd) != 0)
1625  ereport(ERROR,
1627  errmsg("could not close two-phase state file: %m")));
1628 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define write(a, b, c)
Definition: win32.h:14
uint32 pg_crc32c
Definition: pg_crc32c.h:38
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1038
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:880
#define ERROR
Definition: elog.h:43
#define MAXPGPATH
int OpenTransientFile(FileName fileName, int fileFlags, int fileMode)
Definition: fd.c:2144
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1232
#define ereport(elevel, rest)
Definition: elog.h:122
int CloseTransientFile(int fd)
Definition: fd.c:2305
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1208
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync(int fd)
Definition: fd.c:333
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:73
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:78
void RegisterTwoPhaseRecord ( TwoPhaseRmgrId  rmid,
uint16  info,
const void *  data,
uint32  len 
)

Definition at line 1165 of file twophase.c.

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

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

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

Definition at line 632 of file twophase.c.

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

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

633 {
634  int i;
635 
636  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
637 
638  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
639  {
640  if (gxact == TwoPhaseState->prepXacts[i])
641  {
642  /* remove from the active array */
645 
646  /* and put it back in the freelist */
647  gxact->next = TwoPhaseState->freeGXacts;
648  TwoPhaseState->freeGXacts = gxact;
649 
650  LWLockRelease(TwoPhaseStateLock);
651 
652  return;
653  }
654  }
655 
656  LWLockRelease(TwoPhaseStateLock);
657 
658  elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
659 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
GlobalTransaction freeGXacts
Definition: twophase.c:186
GlobalTransaction next
Definition: twophase.c:155
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define ERROR
Definition: elog.h:43
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
int i
#define elog
Definition: elog.h:219
static void RemoveTwoPhaseFile ( TransactionId  xid,
bool  giveWarning 
)
static

Definition at line 1548 of file twophase.c.

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

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

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

Definition at line 1729 of file twophase.c.

References AllocateDir(), buf, dirent::d_name, FreeDir(), InvalidXLogRecPtr, NULL, PrepareRedoAdd(), ProcessTwoPhaseBuffer(), ReadDir(), and TWOPHASE_DIR.

Referenced by StartupXLOG().

1730 {
1731  DIR *cldir;
1732  struct dirent *clde;
1733 
1734  cldir = AllocateDir(TWOPHASE_DIR);
1735  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1736  {
1737  if (strlen(clde->d_name) == 8 &&
1738  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1739  {
1740  TransactionId xid;
1741  char *buf;
1742 
1743  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1744 
1746  true, false, false,
1747  false);
1748  if (buf == NULL)
1749  continue;
1750 
1752  }
1753  }
1754  FreeDir(cldir);
1755 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TransactionId
Definition: c.h:397
Definition: dirent.h:9
Definition: dirent.c:25
static char * buf
Definition: pg_test_fsync.c:66
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2335
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
Definition: twophase.c:2312
#define NULL
Definition: c.h:229
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2401
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool overwriteOK, bool setParent, bool setNextXid)
Definition: twophase.c:2016
#define TWOPHASE_DIR
Definition: twophase.c:114
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2444
static void save_state_data ( const void *  data,
uint32  len 
)
static

Definition at line 964 of file twophase.c.

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

Referenced by RegisterTwoPhaseRecord(), and StartPrepare().

965 {
966  uint32 padlen = MAXALIGN(len);
967 
968  if (padlen > records.bytes_free)
969  {
970  records.tail->next = palloc0(sizeof(StateFileChunk));
972  records.tail->len = 0;
973  records.tail->next = NULL;
975 
976  records.bytes_free = Max(padlen, 512);
978  }
979 
980  memcpy(((char *) records.tail->data) + records.tail->len, data, len);
981  records.tail->len += padlen;
982  records.bytes_free -= padlen;
983  records.total_len += padlen;
984 }
StateFileChunk * tail
Definition: twophase.c:948
uint32 num_chunks
Definition: twophase.c:949
char * data
Definition: twophase.c:940
uint32 bytes_free
Definition: twophase.c:950
uint32 len
Definition: twophase.c:941
unsigned int uint32
Definition: c.h:268
uint32 total_len
Definition: twophase.c:951
struct StateFileChunk * next
Definition: twophase.c:942
void * palloc0(Size size)
Definition: mcxt.c:878
#define Max(x, y)
Definition: c.h:800
#define NULL
Definition: c.h:229
#define MAXALIGN(LEN)
Definition: c.h:588
void * palloc(Size size)
Definition: mcxt.c:849
static struct xllist records
void StandbyRecoverPreparedTransactions ( bool  overwriteOK)

Definition at line 1866 of file twophase.c.

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

Referenced by StartupXLOG(), and xlog_redo().

1867 {
1868  int i;
1869 
1870  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1871  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1872  {
1873  TransactionId xid;
1874  char *buf;
1876 
1877  Assert(gxact->inredo);
1878 
1879  xid = gxact->xid;
1880 
1881  buf = ProcessTwoPhaseBuffer(xid,
1882  gxact->prepare_start_lsn,
1883  gxact->ondisk, overwriteOK, true,
1884  false);
1885  if (buf != NULL)
1886  pfree(buf);
1887  }
1888  LWLockRelease(TwoPhaseStateLock);
1889 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
uint32 TransactionId
Definition: c.h:397
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
void pfree(void *pointer)
Definition: mcxt.c:950
static char * buf
Definition: pg_test_fsync.c:66
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool overwriteOK, bool setParent, bool setNextXid)
Definition: twophase.c:2016
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
TransactionId xid
Definition: twophase.c:169
int i
bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1340 of file twophase.c.

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

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

Definition at line 992 of file twophase.c.

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

Referenced by PrepareTransaction().

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

Definition at line 857 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

858 {
859  GlobalTransaction gxact = TwoPhaseGetGXact(xid);
860 
861  return gxact->dummyBackendId;
862 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid)
Definition: twophase.c:808
BackendId dummyBackendId
Definition: twophase.c:157
PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid)

Definition at line 869 of file twophase.c.

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

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

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

Definition at line 808 of file twophase.c.

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

Referenced by TwoPhaseGetDummyBackendId(), and TwoPhaseGetDummyProc().

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

Definition at line 252 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

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

Definition at line 236 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores(), and TwoPhaseShmemInit().

237 {
238  Size size;
239 
240  /* Need the fixed struct, the array of pointers, and the GTD structs */
241  size = offsetof(TwoPhaseStateData, prepXacts);
242  size = add_size(size, mul_size(max_prepared_xacts,
243  sizeof(GlobalTransaction)));
244  size = MAXALIGN(size);
245  size = add_size(size, mul_size(max_prepared_xacts,
246  sizeof(GlobalTransactionData)));
247 
248  return size;
249 }
int max_prepared_xacts
Definition: twophase.c:117
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
size_t Size
Definition: c.h:356
#define MAXALIGN(LEN)
Definition: c.h:588
#define offsetof(type, field)
Definition: c.h:555
static void XlogReadTwoPhaseData ( XLogRecPtr  lsn,
char **  buf,
int *  len 
)
static

Definition at line 1297 of file twophase.c.

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

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

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

Variable Documentation

GlobalTransaction MyLockedGxact = NULL
static

Definition at line 200 of file twophase.c.

struct xllist records
static
bool twophaseExitRegistered = false
static

Definition at line 202 of file twophase.c.

Referenced by LockGXact(), and MarkAsPreparing().

TwoPhaseStateData* TwoPhaseState
static

Definition at line 195 of file twophase.c.