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 (bool overwriteOK)
 
void RecoverPreparedTransactions (void)
 
void RecreateTwoPhaseFile (TransactionId xid, void *content, int len)
 
void RemoveTwoPhaseFile (TransactionId xid, bool giveWarning)
 
void CheckPointTwoPhase (XLogRecPtr redo_horizon)
 
void FinishPreparedTransaction (const char *gid, bool isCommit)
 

Variables

int max_prepared_xacts
 

Typedef Documentation

Definition at line 25 of file twophase.h.

Function Documentation

void AtAbort_Twophase ( void  )

Definition at line 288 of file twophase.c.

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

Referenced by AbortTransaction(), and AtProcExit_Twophase().

289 {
290  if (MyLockedGxact == NULL)
291  return;
292 
293  /*
294  * What to do with the locked global transaction entry? If we were in the
295  * process of preparing the transaction, but haven't written the WAL
296  * record and state file yet, the transaction must not be considered as
297  * prepared. Likewise, if we are in the process of finishing an
298  * already-prepared transaction, and fail after having already written the
299  * 2nd phase commit or rollback record to the WAL, the transaction should
300  * not be considered as prepared anymore. In those cases, just remove the
301  * entry from shared memory.
302  *
303  * Otherwise, the entry must be left in place so that the transaction can
304  * be finished later, so just unlock it.
305  *
306  * If we abort during prepare, after having written the WAL record, we
307  * might not have transferred all locks and other state to the prepared
308  * transaction yet. Likewise, if we abort during commit or rollback,
309  * after having written the WAL record, we might not have released all the
310  * resources held by the transaction yet. In those cases, the in-memory
311  * state can be wrong, but it's too late to back out.
312  */
313  if (!MyLockedGxact->valid)
314  {
316  }
317  else
318  {
319  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
320 
322 
323  LWLockRelease(TwoPhaseStateLock);
324  }
326 }
BackendId locking_backend
Definition: twophase.c:153
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1714
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:588
#define InvalidBackendId
Definition: backendid.h:23
#define NULL
Definition: c.h:226
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1110
static GlobalTransaction MyLockedGxact
Definition: twophase.c:180
void CheckPointTwoPhase ( XLogRecPtr  redo_horizon)

Definition at line 1597 of file twophase.c.

References PROC_HDR::allPgXact, buf, ereport, errmsg_plural(), i, LOG, log_checkpoints, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_prepared_xacts, TwoPhaseStateData::numPrepXacts, GlobalTransactionData::ondisk, pfree(), GlobalTransactionData::pgprocno, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, TwoPhaseStateData::prepXacts, ProcGlobal, RecreateTwoPhaseFile(), GlobalTransactionData::valid, PGXACT::xid, and XlogReadTwoPhaseData().

Referenced by CheckPointGuts().

1598 {
1599  int i;
1600  int serialized_xacts = 0;
1601 
1602  if (max_prepared_xacts <= 0)
1603  return; /* nothing to do */
1604 
1605  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1606 
1607  /*
1608  * We are expecting there to be zero GXACTs that need to be copied to
1609  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1610  * simplicity. This prevents any new xacts from preparing while this
1611  * occurs, which shouldn't be a problem since the presence of long-lived
1612  * prepared xacts indicates the transaction manager isn't active.
1613  *
1614  * It's also possible to move I/O out of the lock, but on every error we
1615  * should check whether somebody committed our transaction in different
1616  * backend. Let's leave this optimisation for future, if somebody will
1617  * spot that this place cause bottleneck.
1618  *
1619  * Note that it isn't possible for there to be a GXACT with a
1620  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1621  * because of the efforts with delayChkpt.
1622  */
1623  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1624  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1625  {
1627  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1628 
1629  if (gxact->valid &&
1630  !gxact->ondisk &&
1631  gxact->prepare_end_lsn <= redo_horizon)
1632  {
1633  char *buf;
1634  int len;
1635 
1636  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1637  RecreateTwoPhaseFile(pgxact->xid, buf, len);
1638  gxact->ondisk = true;
1639  pfree(buf);
1640  serialized_xacts++;
1641  }
1642  }
1643  LWLockRelease(TwoPhaseStateLock);
1644 
1645  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1646 
1647  if (log_checkpoints && serialized_xacts > 0)
1648  ereport(LOG,
1649  (errmsg_plural("%u two-phase state file was written "
1650  "for a long-running prepared transaction",
1651  "%u two-phase state files were written "
1652  "for long-running prepared transactions",
1653  serialized_xacts,
1654  serialized_xacts)));
1655 }
bool log_checkpoints
Definition: xlog.c:101
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:175
Definition: proc.h:197
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1523
PGXACT * allPgXact
Definition: proc.h:224
TransactionId xid
Definition: proc.h:199
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define LOG
Definition: elog.h:26
XLogRecPtr prepare_start_lsn
Definition: twophase.c:149
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1714
void pfree(void *pointer)
Definition: mcxt.c:992
int max_prepared_xacts
Definition: twophase.c:99
static char * buf
Definition: pg_test_fsync.c:65
#define ereport(elevel, rest)
Definition: elog.h:122
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:172
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1110
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1250
int i
XLogRecPtr prepare_end_lsn
Definition: twophase.c:150
void EndPrepare ( GlobalTransaction  gxact)

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

1022 {
1023  TwoPhaseFileHeader *hdr;
1024  StateFileChunk *record;
1025 
1026  /* Add the end sentinel to the list of 2PC records */
1028  NULL, 0);
1029 
1030  /* Go back and fill in total_len in the file header record */
1031  hdr = (TwoPhaseFileHeader *) records.head->data;
1032  Assert(hdr->magic == TWOPHASE_MAGIC);
1033  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1034 
1035  /*
1036  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1037  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1038  * where we write data to file and then re-read at commit time.
1039  */
1040  if (hdr->total_len > MaxAllocSize)
1041  ereport(ERROR,
1042  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1043  errmsg("two-phase state file maximum length exceeded")));
1044 
1045  /*
1046  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1047  * cover us, so no need to calculate a separate CRC.
1048  *
1049  * We have to set delayChkpt here, too; otherwise a checkpoint starting
1050  * immediately after the WAL record is inserted could complete without
1051  * fsync'ing our state file. (This is essentially the same kind of race
1052  * condition as the COMMIT-to-clog-write case that RecordTransactionCommit
1053  * uses delayChkpt for; see notes there.)
1054  *
1055  * We save the PREPARE record's location in the gxact for later use by
1056  * CheckPointTwoPhase.
1057  */
1059 
1061 
1062  MyPgXact->delayChkpt = true;
1063 
1064  XLogBeginInsert();
1065  for (record = records.head; record != NULL; record = record->next)
1066  XLogRegisterData(record->data, record->len);
1067  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1068  XLogFlush(gxact->prepare_end_lsn);
1069 
1070  /* If we crash now, we have prepared: WAL replay will fix things */
1071 
1072  /* Store record's start location to read that later on Commit */
1074 
1075  /*
1076  * Mark the prepared transaction as valid. As soon as xact.c marks
1077  * MyPgXact as not running our XID (which it will do immediately after
1078  * this function returns), others can commit/rollback the xact.
1079  *
1080  * NB: a side effect of this is to make a dummy ProcArray entry for the
1081  * prepared XID. This must happen before we clear the XID from MyPgXact,
1082  * else there is a window where the XID is not running according to
1083  * TransactionIdIsInProgress, and onlookers would be entitled to assume
1084  * the xact crashed. Instead we have a window where the same XID appears
1085  * twice in ProcArray, which is OK.
1086  */
1087  MarkAsPrepared(gxact);
1088 
1089  /*
1090  * Now we can mark ourselves as out of the commit critical section: a
1091  * checkpoint starting after this will certainly see the gxact as a
1092  * candidate for fsyncing.
1093  */
1094  MyPgXact->delayChkpt = false;
1095 
1096  /*
1097  * Remember that we have this GlobalTransaction entry locked for us. If
1098  * we crash after this point, it's too late to abort, but we must unlock
1099  * it so that the prepared transaction can be committed or rolled back.
1100  */
1101  MyLockedGxact = gxact;
1102 
1103  END_CRIT_SECTION();
1104 
1105  /*
1106  * Wait for synchronous replication, if required.
1107  *
1108  * Note that at this stage we have marked the prepare, but still show as
1109  * running in the procarray (twice!) and continue to hold locks.
1110  */
1111  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1112 
1114  records.num_chunks = 0;
1115 }
#define XLOG_XACT_PREPARE
Definition: xact.h:116
StateFileChunk * tail
Definition: twophase.c:904
uint32 pg_crc32c
Definition: pg_crc32c.h:38
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:335
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:142
#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:905
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2745
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1121
PGXACT * MyPgXact
Definition: proc.c:68
XLogRecPtr prepare_start_lsn
Definition: twophase.c:149
char * data
Definition: twophase.c:896
#define ERROR
Definition: elog.h:43
uint32 len
Definition: twophase.c:897
#define ereport(elevel, rest)
Definition: elog.h:122
bool delayChkpt
Definition: proc.h:210
uint32 total_len
Definition: twophase.c:907
#define MaxAllocSize
Definition: memutils.h:40
struct StateFileChunk * next
Definition: twophase.c:898
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:858
StateFileChunk * head
Definition: twophase.c:903
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
static void MarkAsPrepared(GlobalTransaction gxact)
Definition: twophase.c:492
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:180
static struct xllist records
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr prepare_end_lsn
Definition: twophase.c:150
void FinishPreparedTransaction ( const char *  gid,
bool  isCommit 
)

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

1324 {
1325  GlobalTransaction gxact;
1326  PGPROC *proc;
1327  PGXACT *pgxact;
1328  TransactionId xid;
1329  char *buf;
1330  char *bufptr;
1331  TwoPhaseFileHeader *hdr;
1332  TransactionId latestXid;
1333  TransactionId *children;
1334  RelFileNode *commitrels;
1335  RelFileNode *abortrels;
1336  RelFileNode *delrels;
1337  int ndelrels;
1338  SharedInvalidationMessage *invalmsgs;
1339  int i;
1340 
1341  /*
1342  * Validate the GID, and lock the GXACT to ensure that two backends do not
1343  * try to commit the same GID at once.
1344  */
1345  gxact = LockGXact(gid, GetUserId());
1346  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1347  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1348  xid = pgxact->xid;
1349 
1350  /*
1351  * Read and validate 2PC state data. State data will typically be stored
1352  * in WAL files if the LSN is after the last checkpoint record, or moved
1353  * to disk if for some reason they have lived for a long time.
1354  */
1355  if (gxact->ondisk)
1356  buf = ReadTwoPhaseFile(xid, true);
1357  else
1359 
1360 
1361  /*
1362  * Disassemble the header area
1363  */
1364  hdr = (TwoPhaseFileHeader *) buf;
1365  Assert(TransactionIdEquals(hdr->xid, xid));
1366  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1367  bufptr += MAXALIGN(hdr->gidlen);
1368  children = (TransactionId *) bufptr;
1369  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1370  commitrels = (RelFileNode *) bufptr;
1371  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1372  abortrels = (RelFileNode *) bufptr;
1373  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1374  invalmsgs = (SharedInvalidationMessage *) bufptr;
1375  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1376 
1377  /* compute latestXid among all children */
1378  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1379 
1380  /*
1381  * The order of operations here is critical: make the XLOG entry for
1382  * commit or abort, then mark the transaction committed or aborted in
1383  * pg_clog, then remove its PGPROC from the global ProcArray (which means
1384  * TransactionIdIsInProgress will stop saying the prepared xact is in
1385  * progress), then run the post-commit or post-abort callbacks. The
1386  * callbacks will release the locks the transaction held.
1387  */
1388  if (isCommit)
1390  hdr->nsubxacts, children,
1391  hdr->ncommitrels, commitrels,
1392  hdr->ninvalmsgs, invalmsgs,
1393  hdr->initfileinval);
1394  else
1396  hdr->nsubxacts, children,
1397  hdr->nabortrels, abortrels);
1398 
1399  ProcArrayRemove(proc, latestXid);
1400 
1401  /*
1402  * In case we fail while running the callbacks, mark the gxact invalid so
1403  * no one else will try to commit/rollback, and so it will be recycled if
1404  * we fail after this point. It is still locked by our backend so it
1405  * won't go away yet.
1406  *
1407  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1408  */
1409  gxact->valid = false;
1410 
1411  /*
1412  * We have to remove any files that were supposed to be dropped. For
1413  * consistency with the regular xact.c code paths, must do this before
1414  * releasing locks, so do it before running the callbacks.
1415  *
1416  * NB: this code knows that we couldn't be dropping any temp rels ...
1417  */
1418  if (isCommit)
1419  {
1420  delrels = commitrels;
1421  ndelrels = hdr->ncommitrels;
1422  }
1423  else
1424  {
1425  delrels = abortrels;
1426  ndelrels = hdr->nabortrels;
1427  }
1428  for (i = 0; i < ndelrels; i++)
1429  {
1430  SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1431 
1432  smgrdounlink(srel, false);
1433  smgrclose(srel);
1434  }
1435 
1436  /*
1437  * Handle cache invalidation messages.
1438  *
1439  * Relcache init file invalidation requires processing both before and
1440  * after we send the SI messages. See AtEOXact_Inval()
1441  */
1442  if (hdr->initfileinval)
1444  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1445  if (hdr->initfileinval)
1447 
1448  /* And now do the callbacks */
1449  if (isCommit)
1451  else
1453 
1454  PredicateLockTwoPhaseFinish(xid, isCommit);
1455 
1456  /* Count the prepared xact as committed or aborted */
1457  AtEOXact_PgStat(isCommit);
1458 
1459  /*
1460  * And now we can clean up any files we may have left.
1461  */
1462  if (gxact->ondisk)
1463  RemoveTwoPhaseFile(xid, true);
1464 
1465  RemoveGXact(gxact);
1466  MyLockedGxact = NULL;
1467 
1468  pfree(buf);
1469 }
void smgrclose(SMgrRelation reln)
Definition: smgr.c:296
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:394
Definition: proc.h:197
Oid GetUserId(void)
Definition: miscinit.c:283
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels)
Definition: twophase.c:2123
PGXACT * allPgXact
Definition: proc.h:224
TransactionId xid
Definition: proc.h:199
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:1475
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:864
XLogRecPtr prepare_start_lsn
Definition: twophase.c:149
void pfree(void *pointer)
Definition: mcxt.c:992
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:512
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:331
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:588
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:4813
static char * buf
Definition: pg_test_fsync.c:65
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:2035
void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1503
#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:1142
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:5982
#define NULL
Definition: c.h:226
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:5956
#define Assert(condition)
Definition: c.h:671
#define MAXALIGN(LEN)
Definition: c.h:584
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1250
static GlobalTransaction MyLockedGxact
Definition: twophase.c:180
int i
PGPROC * allProcs
Definition: proc.h:222
Definition: proc.h:84
void AtEOXact_PgStat(bool isCommit)
Definition: pgstat.c:1951
GlobalTransaction MarkAsPreparing ( TransactionId  xid,
const char *  gid,
TimestampTz  prepared_at,
Oid  owner,
Oid  databaseid 
)

Definition at line 352 of file twophase.c.

References PROC_HDR::allPgXact, PROC_HDR::allProcs, Assert, AtProcExit_Twophase(), PGPROC::backendId, before_shmem_exit(), PGPROC::databaseId, PGXACT::delayChkpt, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, TwoPhaseStateData::freeGXacts, GlobalTransactionData::gid, GIDSIZE, i, InvalidBackendId, InvalidTransactionId, InvalidXLogRecPtr, PGPROC::isBackgroundWorker, PGPROC::links, GlobalTransactionData::locking_backend, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), PGPROC::lwWaiting, PGPROC::lwWaitMode, PGPROC::lxid, max_prepared_xacts, MemSet, MyBackendId, PGPROC::myProcLocks, GlobalTransactionData::next, NULL, NUM_LOCK_PARTITIONS, TwoPhaseStateData::numPrepXacts, PGXACT::nxids, GlobalTransactionData::ondisk, PGXACT::overflowed, GlobalTransactionData::owner, PGPROC::pgprocno, GlobalTransactionData::pgprocno, PGPROC::pid, GlobalTransactionData::prepare_end_lsn, GlobalTransactionData::prepare_start_lsn, GlobalTransactionData::prepared_at, TwoPhaseStateData::prepXacts, ProcGlobal, PGPROC::roleId, SHMQueueElemInit(), SHMQueueInit(), STATUS_OK, twophaseExitRegistered, PGXACT::vacuumFlags, GlobalTransactionData::valid, PGPROC::waitLock, PGPROC::waitProcLock, PGPROC::waitStatus, PGXACT::xid, and PGXACT::xmin.

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

354 {
355  GlobalTransaction gxact;
356  PGPROC *proc;
357  PGXACT *pgxact;
358  int i;
359 
360  if (strlen(gid) >= GIDSIZE)
361  ereport(ERROR,
362  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
363  errmsg("transaction identifier \"%s\" is too long",
364  gid)));
365 
366  /* fail immediately if feature is disabled */
367  if (max_prepared_xacts == 0)
368  ereport(ERROR,
369  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
370  errmsg("prepared transactions are disabled"),
371  errhint("Set max_prepared_transactions to a nonzero value.")));
372 
373  /* on first call, register the exit hook */
375  {
377  twophaseExitRegistered = true;
378  }
379 
380  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
381 
382  /* Check for conflicting GID */
383  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
384  {
385  gxact = TwoPhaseState->prepXacts[i];
386  if (strcmp(gxact->gid, gid) == 0)
387  {
388  ereport(ERROR,
390  errmsg("transaction identifier \"%s\" is already in use",
391  gid)));
392  }
393  }
394 
395  /* Get a free gxact from the freelist */
396  if (TwoPhaseState->freeGXacts == NULL)
397  ereport(ERROR,
398  (errcode(ERRCODE_OUT_OF_MEMORY),
399  errmsg("maximum number of prepared transactions reached"),
400  errhint("Increase max_prepared_transactions (currently %d).",
402  gxact = TwoPhaseState->freeGXacts;
403  TwoPhaseState->freeGXacts = gxact->next;
404 
405  proc = &ProcGlobal->allProcs[gxact->pgprocno];
406  pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
407 
408  /* Initialize the PGPROC entry */
409  MemSet(proc, 0, sizeof(PGPROC));
410  proc->pgprocno = gxact->pgprocno;
411  SHMQueueElemInit(&(proc->links));
412  proc->waitStatus = STATUS_OK;
413  /* We set up the gxact's VXID as InvalidBackendId/XID */
414  proc->lxid = (LocalTransactionId) xid;
415  pgxact->xid = xid;
416  pgxact->xmin = InvalidTransactionId;
417  pgxact->delayChkpt = false;
418  pgxact->vacuumFlags = 0;
419  proc->pid = 0;
420  proc->backendId = InvalidBackendId;
421  proc->databaseId = databaseid;
422  proc->roleId = owner;
423  proc->isBackgroundWorker = false;
424  proc->lwWaiting = false;
425  proc->lwWaitMode = 0;
426  proc->waitLock = NULL;
427  proc->waitProcLock = NULL;
428  for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
429  SHMQueueInit(&(proc->myProcLocks[i]));
430  /* subxid data must be filled later by GXactLoadSubxactData */
431  pgxact->overflowed = false;
432  pgxact->nxids = 0;
433 
434  gxact->prepared_at = prepared_at;
435  /* initialize LSN to InvalidXLogRecPtr */
438  gxact->owner = owner;
439  gxact->locking_backend = MyBackendId;
440  gxact->valid = false;
441  gxact->ondisk = false;
442  strcpy(gxact->gid, gid);
443 
444  /* And insert it into the active array */
447 
448  /*
449  * Remember that we have this GlobalTransaction entry locked for us. If we
450  * abort after this, we must release it.
451  */
452  MyLockedGxact = gxact;
453 
454  LWLockRelease(TwoPhaseStateLock);
455 
456  return gxact;
457 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
int errhint(const char *fmt,...)
Definition: elog.c:987
BackendId MyBackendId
Definition: globals.c:72
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:175
BackendId backendId
Definition: proc.h:102
Definition: proc.h:197
TransactionId xmin
Definition: proc.h:203
PGXACT * allPgXact
Definition: proc.h:224
TransactionId xid
Definition: proc.h:199
SHM_QUEUE links
Definition: proc.h:87
bool lwWaiting
Definition: proc.h:116
GlobalTransaction freeGXacts
Definition: twophase.c:166
Oid roleId
Definition: proc.h:104
int errcode(int sqlerrcode)
Definition: elog.c:575
PROC_HDR * ProcGlobal
Definition: proc.c:80
#define MemSet(start, val, len)
Definition: c.h:853
static bool twophaseExitRegistered
Definition: twophase.c:182
uint8 lwWaitMode
Definition: proc.h:117
GlobalTransaction next
Definition: twophase.c:137
char gid[GIDSIZE]
Definition: twophase.c:156
uint8 vacuumFlags
Definition: proc.h:208
BackendId locking_backend
Definition: twophase.c:153
XLogRecPtr prepare_start_lsn
Definition: twophase.c:149
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1714
bool isBackgroundWorker
Definition: proc.h:106
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:99
PROCLOCK * waitProcLock
Definition: proc.h:126
uint8 nxids
Definition: proc.h:213
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
#define InvalidTransactionId
Definition: transam.h:31
Oid databaseId
Definition: proc.h:103
uint32 LocalTransactionId
Definition: c.h:396
LOCK * waitLock
Definition: proc.h:125
#define ereport(elevel, rest)
Definition: elog.h:122
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:172
#define STATUS_OK
Definition: c.h:971
bool delayChkpt
Definition: proc.h:210
#define InvalidBackendId
Definition: backendid.h:23
bool overflowed
Definition: proc.h:209
int waitStatus
Definition: proc.h:91
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1110
#define GIDSIZE
Definition: twophase.c:133
TimestampTz prepared_at
Definition: twophase.c:140
void SHMQueueElemInit(SHM_QUEUE *queue)
Definition: shmqueue.c:57
int pgprocno
Definition: proc.h:99
int errmsg(const char *fmt,...)
Definition: elog.c:797
void SHMQueueInit(SHM_QUEUE *queue)
Definition: shmqueue.c:36
static GlobalTransaction MyLockedGxact
Definition: twophase.c:180
int i
PGPROC * allProcs
Definition: proc.h:222
SHM_QUEUE myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:146
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:278
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:34
Definition: proc.h:84
int pid
Definition: proc.h:98
XLogRecPtr prepare_end_lsn
Definition: twophase.c:150
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:117
LocalTransactionId lxid
Definition: proc.h:95
void PostPrepare_Twophase ( void  )

Definition at line 333 of file twophase.c.

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

Referenced by PrepareTransaction(), and RecoverPreparedTransactions().

334 {
335  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
337  LWLockRelease(TwoPhaseStateLock);
338 
340 }
BackendId locking_backend
Definition: twophase.c:153
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1714
#define InvalidBackendId
Definition: backendid.h:23
#define NULL
Definition: c.h:226
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1110
static GlobalTransaction MyLockedGxact
Definition: twophase.c:180
TransactionId PrescanPreparedTransactions ( TransactionId **  xids_p,
int *  nxids_p 
)

Definition at line 1685 of file twophase.c.

References AllocateDir(), Assert, buf, dirent::d_name, ereport, errmsg(), FreeDir(), TwoPhaseFileHeader::gidlen, i, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXALIGN, VariableCacheData::nextXid, TwoPhaseFileHeader::nsubxacts, NULL, palloc(), pfree(), ReadDir(), ReadTwoPhaseFile(), RemoveTwoPhaseFile(), repalloc(), ShmemVariableCache, TransactionIdAdvance, TransactionIdEquals, TransactionIdFollows(), TransactionIdFollowsOrEquals(), TransactionIdPrecedes(), TWOPHASE_DIR, WARNING, and TwoPhaseFileHeader::xid.

Referenced by StartupXLOG(), and xlog_redo().

1686 {
1687  TransactionId origNextXid = ShmemVariableCache->nextXid;
1688  TransactionId result = origNextXid;
1689  DIR *cldir;
1690  struct dirent *clde;
1691  TransactionId *xids = NULL;
1692  int nxids = 0;
1693  int allocsize = 0;
1694 
1695  cldir = AllocateDir(TWOPHASE_DIR);
1696  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1697  {
1698  if (strlen(clde->d_name) == 8 &&
1699  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1700  {
1701  TransactionId xid;
1702  char *buf;
1703  TwoPhaseFileHeader *hdr;
1704  TransactionId *subxids;
1705  int i;
1706 
1707  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1708 
1709  /* Reject XID if too new */
1710  if (TransactionIdFollowsOrEquals(xid, origNextXid))
1711  {
1712  ereport(WARNING,
1713  (errmsg("removing future two-phase state file \"%s\"",
1714  clde->d_name)));
1715  RemoveTwoPhaseFile(xid, true);
1716  continue;
1717  }
1718 
1719  /*
1720  * Note: we can't check if already processed because clog
1721  * subsystem isn't up yet.
1722  */
1723 
1724  /* Read and validate file */
1725  buf = ReadTwoPhaseFile(xid, true);
1726  if (buf == NULL)
1727  {
1728  ereport(WARNING,
1729  (errmsg("removing corrupt two-phase state file \"%s\"",
1730  clde->d_name)));
1731  RemoveTwoPhaseFile(xid, true);
1732  continue;
1733  }
1734 
1735  /* Deconstruct header */
1736  hdr = (TwoPhaseFileHeader *) buf;
1737  if (!TransactionIdEquals(hdr->xid, xid))
1738  {
1739  ereport(WARNING,
1740  (errmsg("removing corrupt two-phase state file \"%s\"",
1741  clde->d_name)));
1742  RemoveTwoPhaseFile(xid, true);
1743  pfree(buf);
1744  continue;
1745  }
1746 
1747  /*
1748  * OK, we think this file is valid. Incorporate xid into the
1749  * running-minimum result.
1750  */
1751  if (TransactionIdPrecedes(xid, result))
1752  result = xid;
1753 
1754  /*
1755  * Examine subtransaction XIDs ... they should all follow main
1756  * XID, and they may force us to advance nextXid.
1757  *
1758  * We don't expect anyone else to modify nextXid, hence we don't
1759  * need to hold a lock while examining it. We still acquire the
1760  * lock to modify it, though.
1761  */
1762  subxids = (TransactionId *) (buf +
1763  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1764  MAXALIGN(hdr->gidlen));
1765  for (i = 0; i < hdr->nsubxacts; i++)
1766  {
1767  TransactionId subxid = subxids[i];
1768 
1769  Assert(TransactionIdFollows(subxid, xid));
1770  if (TransactionIdFollowsOrEquals(subxid,
1772  {
1773  LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
1774  ShmemVariableCache->nextXid = subxid;
1776  LWLockRelease(XidGenLock);
1777  }
1778  }
1779 
1780 
1781  if (xids_p)
1782  {
1783  if (nxids == allocsize)
1784  {
1785  if (nxids == 0)
1786  {
1787  allocsize = 10;
1788  xids = palloc(allocsize * sizeof(TransactionId));
1789  }
1790  else
1791  {
1792  allocsize = allocsize * 2;
1793  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1794  }
1795  }
1796  xids[nxids++] = xid;
1797  }
1798 
1799  pfree(buf);
1800  }
1801  }
1802  FreeDir(cldir);
1803 
1804  if (xids_p)
1805  {
1806  *xids_p = xids;
1807  *nxids_p = nxids;
1808  }
1809 
1810  return result;
1811 }
#define TransactionIdAdvance(dest)
Definition: transam.h:48
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:394
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:349
TransactionId xid
Definition: twophase.c:864
Definition: dirent.h:9
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1714
void pfree(void *pointer)
Definition: mcxt.c:992
Definition: dirent.c:25
TransactionId nextXid
Definition: transam.h:117
static char * buf
Definition: pg_test_fsync.c:65
VariableCache ShmemVariableCache
Definition: varsup.c:34
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2284
#define ereport(elevel, rest)
Definition: elog.h:122
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1503
#define WARNING
Definition: elog.h:40
static char * ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
Definition: twophase.c:1142
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2350
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1110
#define MAXALIGN(LEN)
Definition: c.h:584
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1021
#define TWOPHASE_DIR
Definition: twophase.c:96
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2393
void RecoverPreparedTransactions ( void  )

Definition at line 1907 of file twophase.c.

References AllocateDir(), Assert, buf, dirent::d_name, TwoPhaseFileHeader::database, ereport, errmsg(), FreeDir(), TwoPhaseFileHeader::gidlen, GXactLoadSubxactData(), i, InHotStandby, LOG, MarkAsPrepared(), MarkAsPreparing(), MAXALIGN, MAXPGPATH, TwoPhaseFileHeader::nabortrels, TwoPhaseFileHeader::ncommitrels, TwoPhaseFileHeader::ninvalmsgs, TwoPhaseFileHeader::nsubxacts, NULL, GlobalTransactionData::ondisk, TwoPhaseFileHeader::owner, pfree(), PGPROC_MAX_CACHED_SUBXIDS, PostPrepare_Twophase(), TwoPhaseFileHeader::prepared_at, ProcessRecords(), ReadDir(), ReadTwoPhaseFile(), RemoveTwoPhaseFile(), snprintf(), StandbyReleaseLockTree(), SubTransSetParent(), TransactionIdDidAbort(), TransactionIdDidCommit(), TransactionIdEquals, TWOPHASE_DIR, twophase_recover_callbacks, WARNING, TwoPhaseFileHeader::xid, and XLogLogicalInfoActive.

Referenced by StartupXLOG().

1908 {
1909  char dir[MAXPGPATH];
1910  DIR *cldir;
1911  struct dirent *clde;
1912  bool overwriteOK = false;
1913 
1914  snprintf(dir, MAXPGPATH, "%s", TWOPHASE_DIR);
1915 
1916  cldir = AllocateDir(dir);
1917  while ((clde = ReadDir(cldir, dir)) != NULL)
1918  {
1919  if (strlen(clde->d_name) == 8 &&
1920  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1921  {
1922  TransactionId xid;
1923  char *buf;
1924  char *bufptr;
1925  TwoPhaseFileHeader *hdr;
1926  TransactionId *subxids;
1927  GlobalTransaction gxact;
1928  const char *gid;
1929  int i;
1930 
1931  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1932 
1933  /* Already processed? */
1935  {
1936  ereport(WARNING,
1937  (errmsg("removing stale two-phase state file \"%s\"",
1938  clde->d_name)));
1939  RemoveTwoPhaseFile(xid, true);
1940  continue;
1941  }
1942 
1943  /* Read and validate file */
1944  buf = ReadTwoPhaseFile(xid, true);
1945  if (buf == NULL)
1946  {
1947  ereport(WARNING,
1948  (errmsg("removing corrupt two-phase state file \"%s\"",
1949  clde->d_name)));
1950  RemoveTwoPhaseFile(xid, true);
1951  continue;
1952  }
1953 
1954  ereport(LOG,
1955  (errmsg("recovering prepared transaction %u", xid)));
1956 
1957  /* Deconstruct header */
1958  hdr = (TwoPhaseFileHeader *) buf;
1959  Assert(TransactionIdEquals(hdr->xid, xid));
1960  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1961  gid = (const char *) bufptr;
1962  bufptr += MAXALIGN(hdr->gidlen);
1963  subxids = (TransactionId *) bufptr;
1964  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1965  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1966  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1967  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1968 
1969  /*
1970  * It's possible that SubTransSetParent has been set before, if
1971  * the prepared transaction generated xid assignment records. Test
1972  * here must match one used in AssignTransactionId().
1973  */
1976  overwriteOK = true;
1977 
1978  /*
1979  * Reconstruct subtrans state for the transaction --- needed
1980  * because pg_subtrans is not preserved over a restart. Note that
1981  * we are linking all the subtransactions directly to the
1982  * top-level XID; there may originally have been a more complex
1983  * hierarchy, but there's no need to restore that exactly.
1984  */
1985  for (i = 0; i < hdr->nsubxacts; i++)
1986  SubTransSetParent(subxids[i], xid, overwriteOK);
1987 
1988  /*
1989  * Recreate its GXACT and dummy PGPROC
1990  */
1991  gxact = MarkAsPreparing(xid, gid,
1992  hdr->prepared_at,
1993  hdr->owner, hdr->database);
1994  gxact->ondisk = true;
1995  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1996  MarkAsPrepared(gxact);
1997 
1998  /*
1999  * Recover other state (notably locks) using resource managers
2000  */
2002 
2003  /*
2004  * Release locks held by the standby process after we process each
2005  * prepared transaction. As a result, we don't need too many
2006  * additional locks at any one time.
2007  */
2008  if (InHotStandby)
2009  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2010 
2011  /*
2012  * We're done with recovering this transaction. Clear
2013  * MyLockedGxact, like we do in PrepareTransaction() during normal
2014  * operation.
2015  */
2017 
2018  pfree(buf);
2019  }
2020  }
2021  FreeDir(cldir);
2022 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:394
void SubTransSetParent(TransactionId xid, TransactionId parent, bool overwriteOK)
Definition: subtrans.c:76
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1475
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
#define InHotStandby
Definition: xlog.h:74
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
TransactionId xid
Definition: twophase.c:864
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
#define LOG
Definition: elog.h:26
Definition: dirent.h:9
GlobalTransaction MarkAsPreparing(TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:352
void pfree(void *pointer)
Definition: mcxt.c:992
Definition: dirent.c:25
#define XLogLogicalInfoActive()
Definition: xlog.h:162
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:467
#define MAXPGPATH
static char * buf
Definition: pg_test_fsync.c:65
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:680
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2284
#define ereport(elevel, rest)
Definition: elog.h:122
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181
void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1503
#define WARNING
Definition: elog.h:40
static char * ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
Definition: twophase.c:1142
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:35
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
static void MarkAsPrepared(GlobalTransaction gxact)
Definition: twophase.c:492
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2350
#define MAXALIGN(LEN)
Definition: c.h:584
#define TWOPHASE_DIR
Definition: twophase.c:96
int errmsg(const char *fmt,...)
Definition: elog.c:797
void PostPrepare_Twophase(void)
Definition: twophase.c:333
int i
char d_name[MAX_PATH]
Definition: dirent.h:14
TimestampTz prepared_at
Definition: twophase.c:866
int FreeDir(DIR *dir)
Definition: fd.c:2393
void RecreateTwoPhaseFile ( TransactionId  xid,
void *  content,
int  len 
)

Definition at line 1523 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(), TwoPhaseFilePath, and write.

Referenced by CheckPointTwoPhase(), and xact_redo().

1524 {
1525  char path[MAXPGPATH];
1526  pg_crc32c statefile_crc;
1527  int fd;
1528 
1529  /* Recompute CRC */
1530  INIT_CRC32C(statefile_crc);
1531  COMP_CRC32C(statefile_crc, content, len);
1532  FIN_CRC32C(statefile_crc);
1533 
1534  TwoPhaseFilePath(path, xid);
1535 
1536  fd = OpenTransientFile(path,
1537  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY,
1538  S_IRUSR | S_IWUSR);
1539  if (fd < 0)
1540  ereport(ERROR,
1542  errmsg("could not recreate two-phase state file \"%s\": %m",
1543  path)));
1544 
1545  /* Write content and CRC */
1546  if (write(fd, content, len) != len)
1547  {
1548  CloseTransientFile(fd);
1549  ereport(ERROR,
1551  errmsg("could not write two-phase state file: %m")));
1552  }
1553  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1554  {
1555  CloseTransientFile(fd);
1556  ereport(ERROR,
1558  errmsg("could not write two-phase state file: %m")));
1559  }
1560 
1561  /*
1562  * We must fsync the file because the end-of-replay checkpoint will not do
1563  * so, there being no GXACT in shared memory yet to tell it to.
1564  */
1565  if (pg_fsync(fd) != 0)
1566  {
1567  CloseTransientFile(fd);
1568  ereport(ERROR,
1570  errmsg("could not fsync two-phase state file: %m")));
1571  }
1572 
1573  if (CloseTransientFile(fd) != 0)
1574  ereport(ERROR,
1576  errmsg("could not close two-phase state file: %m")));
1577 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define write(a, b, c)
Definition: win32.h:19
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:836
#define ERROR
Definition: elog.h:43
#define MAXPGPATH
int OpenTransientFile(FileName fileName, int fileFlags, int fileMode)
Definition: fd.c:2093
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int CloseTransientFile(int fd)
Definition: fd.c:2254
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 RemoveTwoPhaseFile ( TransactionId  xid,
bool  giveWarning 
)

Definition at line 1503 of file twophase.c.

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

Referenced by FinishPreparedTransaction(), PrescanPreparedTransactions(), RecoverPreparedTransactions(), StandbyRecoverPreparedTransactions(), and xact_redo().

1504 {
1505  char path[MAXPGPATH];
1506 
1507  TwoPhaseFilePath(path, xid);
1508  if (unlink(path))
1509  if (errno != ENOENT || giveWarning)
1510  ereport(WARNING,
1512  errmsg("could not remove two-phase state file \"%s\": %m",
1513  path)));
1514 }
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:836
#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 StandbyRecoverPreparedTransactions ( bool  overwriteOK)

Definition at line 1826 of file twophase.c.

References AllocateDir(), Assert, buf, dirent::d_name, ereport, errmsg(), FreeDir(), TwoPhaseFileHeader::gidlen, i, MAXALIGN, TwoPhaseFileHeader::nsubxacts, NULL, pfree(), ReadDir(), ReadTwoPhaseFile(), RemoveTwoPhaseFile(), SubTransSetParent(), TransactionIdDidAbort(), TransactionIdDidCommit(), TransactionIdEquals, TransactionIdFollows(), TWOPHASE_DIR, WARNING, and TwoPhaseFileHeader::xid.

Referenced by StartupXLOG(), and xlog_redo().

1827 {
1828  DIR *cldir;
1829  struct dirent *clde;
1830 
1831  cldir = AllocateDir(TWOPHASE_DIR);
1832  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1833  {
1834  if (strlen(clde->d_name) == 8 &&
1835  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1836  {
1837  TransactionId xid;
1838  char *buf;
1839  TwoPhaseFileHeader *hdr;
1840  TransactionId *subxids;
1841  int i;
1842 
1843  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1844 
1845  /* Already processed? */
1847  {
1848  ereport(WARNING,
1849  (errmsg("removing stale two-phase state file \"%s\"",
1850  clde->d_name)));
1851  RemoveTwoPhaseFile(xid, true);
1852  continue;
1853  }
1854 
1855  /* Read and validate file */
1856  buf = ReadTwoPhaseFile(xid, true);
1857  if (buf == NULL)
1858  {
1859  ereport(WARNING,
1860  (errmsg("removing corrupt two-phase state file \"%s\"",
1861  clde->d_name)));
1862  RemoveTwoPhaseFile(xid, true);
1863  continue;
1864  }
1865 
1866  /* Deconstruct header */
1867  hdr = (TwoPhaseFileHeader *) buf;
1868  if (!TransactionIdEquals(hdr->xid, xid))
1869  {
1870  ereport(WARNING,
1871  (errmsg("removing corrupt two-phase state file \"%s\"",
1872  clde->d_name)));
1873  RemoveTwoPhaseFile(xid, true);
1874  pfree(buf);
1875  continue;
1876  }
1877 
1878  /*
1879  * Examine subtransaction XIDs ... they should all follow main
1880  * XID.
1881  */
1882  subxids = (TransactionId *) (buf +
1883  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1884  MAXALIGN(hdr->gidlen));
1885  for (i = 0; i < hdr->nsubxacts; i++)
1886  {
1887  TransactionId subxid = subxids[i];
1888 
1889  Assert(TransactionIdFollows(subxid, xid));
1890  SubTransSetParent(xid, subxid, overwriteOK);
1891  }
1892 
1893  pfree(buf);
1894  }
1895  }
1896  FreeDir(cldir);
1897 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:394
void SubTransSetParent(TransactionId xid, TransactionId parent, bool overwriteOK)
Definition: subtrans.c:76
TransactionId xid
Definition: twophase.c:864
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
Definition: dirent.h:9
void pfree(void *pointer)
Definition: mcxt.c:992
Definition: dirent.c:25
static char * buf
Definition: pg_test_fsync.c:65
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2284
#define ereport(elevel, rest)
Definition: elog.h:122
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181
void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1503
#define WARNING
Definition: elog.h:40
static char * ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
Definition: twophase.c:1142
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2350
#define MAXALIGN(LEN)
Definition: c.h:584
#define TWOPHASE_DIR
Definition: twophase.c:96
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
char d_name[MAX_PATH]
Definition: dirent.h:14
int FreeDir(DIR *dir)
Definition: fd.c:2393
bool StandbyTransactionIdIsPrepared ( TransactionId  xid)

Definition at line 1295 of file twophase.c.

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

Referenced by KnownAssignedXidsRemovePreceding(), and StandbyReleaseOldLocks().

1296 {
1297  char *buf;
1298  TwoPhaseFileHeader *hdr;
1299  bool result;
1300 
1302 
1303  if (max_prepared_xacts <= 0)
1304  return false; /* nothing to do */
1305 
1306  /* Read and validate file */
1307  buf = ReadTwoPhaseFile(xid, false);
1308  if (buf == NULL)
1309  return false;
1310 
1311  /* Check header also */
1312  hdr = (TwoPhaseFileHeader *) buf;
1313  result = TransactionIdEquals(hdr->xid, xid);
1314  pfree(buf);
1315 
1316  return result;
1317 }
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
TransactionId xid
Definition: twophase.c:864
void pfree(void *pointer)
Definition: mcxt.c:992
int max_prepared_xacts
Definition: twophase.c:99
static char * buf
Definition: pg_test_fsync.c:65
static char * ReadTwoPhaseFile(TransactionId xid, bool give_warnings)
Definition: twophase.c:1142
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void StartPrepare ( GlobalTransaction  gxact)

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

949 {
950  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
951  PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
952  TransactionId xid = pgxact->xid;
953  TwoPhaseFileHeader hdr;
954  TransactionId *children;
955  RelFileNode *commitrels;
956  RelFileNode *abortrels;
957  SharedInvalidationMessage *invalmsgs;
958 
959  /* Initialize linked list */
960  records.head = palloc0(sizeof(StateFileChunk));
961  records.head->len = 0;
962  records.head->next = NULL;
963 
964  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
966 
968  records.num_chunks = 1;
969 
970  records.total_len = 0;
971 
972  /* Create header */
973  hdr.magic = TWOPHASE_MAGIC;
974  hdr.total_len = 0; /* EndPrepare will fill this in */
975  hdr.xid = xid;
976  hdr.database = proc->databaseId;
977  hdr.prepared_at = gxact->prepared_at;
978  hdr.owner = gxact->owner;
979  hdr.nsubxacts = xactGetCommittedChildren(&children);
980  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
981  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
983  &hdr.initfileinval);
984  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
985 
986  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
987  save_state_data(gxact->gid, hdr.gidlen);
988 
989  /*
990  * Add the additional info about subxacts, deletable files and cache
991  * invalidation messages.
992  */
993  if (hdr.nsubxacts > 0)
994  {
995  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
996  /* While we have the child-xact data, stuff it in the gxact too */
997  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
998  }
999  if (hdr.ncommitrels > 0)
1000  {
1001  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1002  pfree(commitrels);
1003  }
1004  if (hdr.nabortrels > 0)
1005  {
1006  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1007  pfree(abortrels);
1008  }
1009  if (hdr.ninvalmsgs > 0)
1010  {
1011  save_state_data(invalmsgs,
1012  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1013  pfree(invalmsgs);
1014  }
1015 }
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5082
uint32 TransactionId
Definition: c.h:394
Definition: proc.h:197
PGXACT * allPgXact
Definition: proc.h:224
TransactionId xid
Definition: proc.h:199
StateFileChunk * tail
Definition: twophase.c:904
PROC_HDR * ProcGlobal
Definition: proc.c:80
TransactionId xid
Definition: twophase.c:864
uint32 num_chunks
Definition: twophase.c:905
char gid[GIDSIZE]
Definition: twophase.c:156
char * data
Definition: twophase.c:896
void pfree(void *pointer)
Definition: mcxt.c:992
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:467
uint32 bytes_free
Definition: twophase.c:906
int smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
Definition: storage.c:389
uint32 len
Definition: twophase.c:897
Oid databaseId
Definition: proc.h:103
uint32 total_len
Definition: twophase.c:907
struct StateFileChunk * next
Definition: twophase.c:898
void * palloc0(Size size)
Definition: mcxt.c:920
#define TWOPHASE_MAGIC
Definition: twophase.c:858
#define Max(x, y)
Definition: c.h:796
StateFileChunk * head
Definition: twophase.c:903
#define NULL
Definition: c.h:226
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:920
TimestampTz prepared_at
Definition: twophase.c:140
void * palloc(Size size)
Definition: mcxt.c:891
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:809
static struct xllist records
PGPROC * allProcs
Definition: proc.h:222
TimestampTz prepared_at
Definition: twophase.c:866
Definition: proc.h:84
BackendId TwoPhaseGetDummyBackendId ( TransactionId  xid)

Definition at line 813 of file twophase.c.

References GlobalTransactionData::dummyBackendId, and TwoPhaseGetGXact().

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

814 {
815  GlobalTransaction gxact = TwoPhaseGetGXact(xid);
816 
817  return gxact->dummyBackendId;
818 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid)
Definition: twophase.c:764
BackendId dummyBackendId
Definition: twophase.c:139
PGPROC* TwoPhaseGetDummyProc ( TransactionId  xid)

Definition at line 825 of file twophase.c.

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

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

826 {
827  GlobalTransaction gxact = TwoPhaseGetGXact(xid);
828 
829  return &ProcGlobal->allProcs[gxact->pgprocno];
830 }
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid)
Definition: twophase.c:764
PROC_HDR * ProcGlobal
Definition: proc.c:80
PGPROC * allProcs
Definition: proc.h:222
void TwoPhaseShmemInit ( void  )

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

224 {
225  bool found;
226 
227  TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
229  &found);
230  if (!IsUnderPostmaster)
231  {
232  GlobalTransaction gxacts;
233  int i;
234 
235  Assert(!found);
238 
239  /*
240  * Initialize the linked list of free GlobalTransactionData structs
241  */
242  gxacts = (GlobalTransaction)
243  ((char *) TwoPhaseState +
244  MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
246  for (i = 0; i < max_prepared_xacts; i++)
247  {
248  /* insert into linked list */
249  gxacts[i].next = TwoPhaseState->freeGXacts;
250  TwoPhaseState->freeGXacts = &gxacts[i];
251 
252  /* associate it with a PGPROC assigned by InitProcGlobal */
254 
255  /*
256  * Assign a unique ID for each dummy proc, so that the range of
257  * dummy backend IDs immediately follows the range of normal
258  * backend IDs. We don't dare to assign a real backend ID to dummy
259  * procs, because prepared transactions don't take part in cache
260  * invalidation like a real backend ID would imply, but having a
261  * unique ID for them is nevertheless handy. This arrangement
262  * allows you to allocate an array of size (MaxBackends +
263  * max_prepared_xacts + 1), and have a slot for every backend and
264  * prepared transaction. Currently multixact.c uses that
265  * technique.
266  */
267  gxacts[i].dummyBackendId = MaxBackends + 1 + i;
268  }
269  }
270  else
271  Assert(found);
272 }
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:175
GlobalTransaction freeGXacts
Definition: twophase.c:166
PGPROC * PreparedXactProcs
Definition: proc.c:82
Size TwoPhaseShmemSize(void)
Definition: twophase.c:207
GlobalTransaction next
Definition: twophase.c:137
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:25
int max_prepared_xacts
Definition: twophase.c:99
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:226
#define Assert(condition)
Definition: c.h:671
#define MAXALIGN(LEN)
Definition: c.h:584
int pgprocno
Definition: proc.h:99
int i
#define offsetof(type, field)
Definition: c.h:551
BackendId dummyBackendId
Definition: twophase.c:139
Size TwoPhaseShmemSize ( void  )

Definition at line 207 of file twophase.c.

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

Referenced by CreateSharedMemoryAndSemaphores(), and TwoPhaseShmemInit().

208 {
209  Size size;
210 
211  /* Need the fixed struct, the array of pointers, and the GTD structs */
212  size = offsetof(TwoPhaseStateData, prepXacts);
213  size = add_size(size, mul_size(max_prepared_xacts,
214  sizeof(GlobalTransaction)));
215  size = MAXALIGN(size);
216  size = add_size(size, mul_size(max_prepared_xacts,
217  sizeof(GlobalTransactionData)));
218 
219  return size;
220 }
int max_prepared_xacts
Definition: twophase.c:99
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:353
#define MAXALIGN(LEN)
Definition: c.h:584
#define offsetof(type, field)
Definition: c.h:551

Variable Documentation