PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
twophase.h File Reference
#include "access/xlogdefs.h"
#include "datatype/timestamp.h"
#include "storage/lock.h"
Include dependency graph for twophase.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef struct
GlobalTransactionData
GlobalTransaction
 

Functions

Size TwoPhaseShmemSize (void)
 
void TwoPhaseShmemInit (void)
 
void AtAbort_Twophase (void)
 
void PostPrepare_Twophase (void)
 
PGPROCTwoPhaseGetDummyProc (TransactionId xid)
 
BackendId TwoPhaseGetDummyBackendId (TransactionId xid)
 
GlobalTransaction MarkAsPreparing (TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
 
void StartPrepare (GlobalTransaction gxact)
 
void EndPrepare (GlobalTransaction gxact)
 
bool StandbyTransactionIdIsPrepared (TransactionId xid)
 
TransactionId PrescanPreparedTransactions (TransactionId **xids_p, int *nxids_p)
 
void StandbyRecoverPreparedTransactions (void)
 
void RecoverPreparedTransactions (void)
 
void CheckPointTwoPhase (XLogRecPtr redo_horizon)
 
void FinishPreparedTransaction (const char *gid, bool isCommit)
 
void PrepareRedoAdd (char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
 
void PrepareRedoRemove (TransactionId xid, bool giveWarning)
 
void restoreTwoPhaseData (void)
 

Variables

int max_prepared_xacts
 

Typedef Documentation

Definition at line 25 of file twophase.h.

Function Documentation

void AtAbort_Twophase ( void  )

Definition at line 319 of file twophase.c.

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

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

Definition at line 1651 of file twophase.c.

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

Referenced by CheckPointGuts().

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

Definition at line 1064 of file twophase.c.

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

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

Definition at line 1367 of file twophase.c.

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

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

Definition at line 374 of file twophase.c.

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

Referenced by PrepareTransaction().

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

Definition at line 359 of file twophase.c.

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

360 {
361  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
363  LWLockRelease(TwoPhaseStateLock);
364 
366 }
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:203
void PrepareRedoAdd ( char *  buf,
XLogRecPtr  start_lsn,
XLogRecPtr  end_lsn 
)

Definition at line 2312 of file twophase.c.

References Assert, DEBUG2, elog, ereport, errcode(), errhint(), errmsg(), ERROR, TwoPhaseStateData::freeGXacts, GlobalTransactionData::gid, GlobalTransactionData::inredo, InvalidBackendId, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockHeldByMeInMode(), max_prepared_xacts, MAXALIGN, GlobalTransactionData::next, 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 
2319  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2321 
2322  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2323  gid = (const char *) bufptr;
2324 
2325  /*
2326  * Reserve the GID for the given transaction in the redo code path.
2327  *
2328  * This creates a gxact struct and puts it into the active array.
2329  *
2330  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2331  * shared memory. Hence, we only fill up the bare minimum contents here.
2332  * The gxact also gets marked with gxact->inredo set to true to indicate
2333  * that it got added in the redo phase
2334  */
2335 
2336  /* Get a free gxact from the freelist */
2337  if (TwoPhaseState->freeGXacts == NULL)
2338  ereport(ERROR,
2339  (errcode(ERRCODE_OUT_OF_MEMORY),
2340  errmsg("maximum number of prepared transactions reached"),
2341  errhint("Increase max_prepared_transactions (currently %d).",
2342  max_prepared_xacts)));
2343  gxact = TwoPhaseState->freeGXacts;
2344  TwoPhaseState->freeGXacts = gxact->next;
2345 
2346  gxact->prepared_at = hdr->prepared_at;
2347  gxact->prepare_start_lsn = start_lsn;
2348  gxact->prepare_end_lsn = end_lsn;
2349  gxact->xid = hdr->xid;
2350  gxact->owner = hdr->owner;
2352  gxact->valid = false;
2353  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2354  gxact->inredo = true; /* yes, added in redo */
2355  strcpy(gxact->gid, gid);
2356 
2357  /* And insert it into the active array */
2360 
2361  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2362 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1849
int errhint(const char *fmt,...)
Definition: elog.c:987
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
GlobalTransaction freeGXacts
Definition: twophase.c:186
int errcode(int sqlerrcode)
Definition: elog.c:575
TransactionId xid
Definition: twophase.c:907
GlobalTransaction next
Definition: twophase.c:155
bool RecoveryInProgress(void)
Definition: xlog.c:7878
char gid[GIDSIZE]
Definition: twophase.c:176
BackendId locking_backend
Definition: twophase.c:172
XLogRecPtr prepare_start_lsn
Definition: twophase.c:167
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:117
#define DEBUG2
Definition: elog.h:24
static char * buf
Definition: pg_test_fsync.c: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
#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:909
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_EXCLUSIVE, LWLockHeldByMeInMode(), 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 
2380  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2382 
2383  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2384  {
2385  gxact = TwoPhaseState->prepXacts[i];
2386 
2387  if (gxact->xid == xid)
2388  {
2389  Assert(gxact->inredo);
2390  found = true;
2391  break;
2392  }
2393  }
2394 
2395  /*
2396  * Just leave if there is nothing, this is expected during WAL replay.
2397  */
2398  if (!found)
2399  return;
2400 
2401  /*
2402  * And now we can clean up any files we may have left.
2403  */
2404  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2405  if (gxact->ondisk)
2406  RemoveTwoPhaseFile(xid, giveWarning);
2407  RemoveGXact(gxact);
2408 
2409  return;
2410 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1849
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
bool RecoveryInProgress(void)
Definition: xlog.c:7878
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:635
#define DEBUG2
Definition: elog.h:24
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:192
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1549
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
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 1790 of file twophase.c.

References Assert, buf, i, GlobalTransactionData::inredo, LW_EXCLUSIVE, 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().

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

Definition at line 1911 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(), PostPrepare_Twophase(), GlobalTransactionData::prepare_start_lsn, TwoPhaseFileHeader::prepared_at, TwoPhaseStateData::prepXacts, ProcessRecords(), ProcessTwoPhaseBuffer(), StandbyReleaseLockTree(), TransactionIdEquals, twophase_recover_callbacks, GlobalTransactionData::xid, and TwoPhaseFileHeader::xid.

Referenced by StartupXLOG().

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

Definition at line 1733 of file twophase.c.

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

Referenced by StartupXLOG().

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

Definition at line 1870 of file twophase.c.

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

Referenced by StartupXLOG(), and xlog_redo().

1871 {
1872  int i;
1873 
1874  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1875  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1876  {
1877  TransactionId xid;
1878  char *buf;
1880 
1881  Assert(gxact->inredo);
1882 
1883  xid = gxact->xid;
1884 
1885  buf = ProcessTwoPhaseBuffer(xid,
1886  gxact->prepare_start_lsn,
1887  gxact->ondisk, false, false);
1888  if (buf != NULL)
1889  pfree(buf);
1890  }
1891  LWLockRelease(TwoPhaseStateLock);
1892 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:195
uint32 TransactionId
Definition: c.h: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
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2012
#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
bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1339 of file twophase.c.

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

1340 {
1341  char *buf;
1342  TwoPhaseFileHeader *hdr;
1343  bool result;
1344 
1346 
1347  if (max_prepared_xacts <= 0)
1348  return false; /* nothing to do */
1349 
1350  /* Read and validate file */
1351  buf = ReadTwoPhaseFile(xid, false);
1352  if (buf == NULL)
1353  return false;
1354 
1355  /* Check header also */
1356  hdr = (TwoPhaseFileHeader *) buf;
1357  result = TransactionIdEquals(hdr->xid, xid);
1358  pfree(buf);
1359 
1360  return result;
1361 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
return result
Definition: formatting.c:1633
TransactionId xid
Definition: twophase.c:907
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:1185
#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 991 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, xllist::bytes_free, StateFileChunk::data, TwoPhaseFileHeader::database, PGPROC::databaseId, GlobalTransactionData::gid, TwoPhaseFileHeader::gidlen, GXactLoadSubxactData(), xllist::head, TwoPhaseFileHeader::initfileinval, StateFileChunk::len, TwoPhaseFileHeader::magic, Max, TwoPhaseFileHeader::nabortrels, TwoPhaseFileHeader::ncommitrels, StateFileChunk::next, TwoPhaseFileHeader::ninvalmsgs, TwoPhaseFileHeader::nsubxacts, 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().

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

Definition at line 856 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

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

Definition at line 868 of file twophase.c.

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

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

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

Definition at line 254 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

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

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

Referenced by CreateSharedMemoryAndSemaphores(), and TwoPhaseShmemInit().

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

Variable Documentation