PostgreSQL Source Code  git master
twophase.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * twophase.c
4  * Two-phase commit support functions.
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * IDENTIFICATION
10  * src/backend/access/transam/twophase.c
11  *
12  * NOTES
13  * Each global transaction is associated with a global transaction
14  * identifier (GID). The client assigns a GID to a postgres
15  * transaction with the PREPARE TRANSACTION command.
16  *
17  * We keep all active global transactions in a shared memory array.
18  * When the PREPARE TRANSACTION command is issued, the GID is
19  * reserved for the transaction in the array. This is done before
20  * a WAL entry is made, because the reservation checks for duplicate
21  * GIDs and aborts the transaction if there already is a global
22  * transaction in prepared state with the same GID.
23  *
24  * A global transaction (gxact) also has dummy PGPROC; this is what keeps
25  * the XID considered running by TransactionIdIsInProgress. It is also
26  * convenient as a PGPROC to hook the gxact's locks to.
27  *
28  * Information to recover prepared transactions in case of crash is
29  * now stored in WAL for the common case. In some cases there will be
30  * an extended period between preparing a GXACT and commit/abort, in
31  * which case we need to separately record prepared transaction data
32  * in permanent storage. This includes locking information, pending
33  * notifications etc. All that state information is written to the
34  * per-transaction state file in the pg_twophase directory.
35  * All prepared transactions will be written prior to shutdown.
36  *
37  * Life track of state data is following:
38  *
39  * * On PREPARE TRANSACTION backend writes state data only to the WAL and
40  * stores pointer to the start of the WAL record in
41  * gxact->prepare_start_lsn.
42  * * If COMMIT occurs before checkpoint then backend reads data from WAL
43  * using prepare_start_lsn.
44  * * On checkpoint state data copied to files in pg_twophase directory and
45  * fsynced
46  * * If COMMIT happens after checkpoint then backend reads state data from
47  * files
48  *
49  * During replay and replication, TwoPhaseState also holds information
50  * about active prepared transactions that haven't been moved to disk yet.
51  *
52  * Replay of twophase records happens by the following rules:
53  *
54  * * At the beginning of recovery, pg_twophase is scanned once, filling
55  * TwoPhaseState with entries marked with gxact->inredo and
56  * gxact->ondisk. Two-phase file data older than the XID horizon of
57  * the redo position are discarded.
58  * * On PREPARE redo, the transaction is added to TwoPhaseState->prepXacts.
59  * gxact->inredo is set to true for such entries.
60  * * On Checkpoint we iterate through TwoPhaseState->prepXacts entries
61  * that have gxact->inredo set and are behind the redo_horizon. We
62  * save them to disk and then switch gxact->ondisk to true.
63  * * On COMMIT/ABORT we delete the entry from TwoPhaseState->prepXacts.
64  * If gxact->ondisk is true, the corresponding entry from the disk
65  * is additionally deleted.
66  * * RecoverPreparedTransactions(), StandbyRecoverPreparedTransactions()
67  * and PrescanPreparedTransactions() have been modified to go through
68  * gxact->inredo entries that have not made it to disk.
69  *
70  *-------------------------------------------------------------------------
71  */
72 #include "postgres.h"
73 
74 #include <fcntl.h>
75 #include <sys/stat.h>
76 #include <time.h>
77 #include <unistd.h>
78 
79 #include "access/commit_ts.h"
80 #include "access/htup_details.h"
81 #include "access/subtrans.h"
82 #include "access/transam.h"
83 #include "access/twophase.h"
84 #include "access/twophase_rmgr.h"
85 #include "access/xact.h"
86 #include "access/xlog.h"
87 #include "access/xloginsert.h"
88 #include "access/xlogreader.h"
89 #include "access/xlogutils.h"
90 #include "catalog/pg_type.h"
91 #include "catalog/storage.h"
92 #include "funcapi.h"
93 #include "miscadmin.h"
94 #include "pg_trace.h"
95 #include "pgstat.h"
96 #include "replication/origin.h"
97 #include "replication/syncrep.h"
98 #include "replication/walsender.h"
99 #include "storage/fd.h"
100 #include "storage/ipc.h"
101 #include "storage/md.h"
102 #include "storage/predicate.h"
103 #include "storage/proc.h"
104 #include "storage/procarray.h"
105 #include "storage/sinvaladt.h"
106 #include "storage/smgr.h"
107 #include "utils/builtins.h"
108 #include "utils/memutils.h"
109 #include "utils/timestamp.h"
110 
111 /*
112  * Directory where Two-phase commit files reside within PGDATA
113  */
114 #define TWOPHASE_DIR "pg_twophase"
115 
116 /* GUC variable, can't be changed after startup */
118 
119 /*
120  * This struct describes one global transaction that is in prepared state
121  * or attempting to become prepared.
122  *
123  * The lifecycle of a global transaction is:
124  *
125  * 1. After checking that the requested GID is not in use, set up an entry in
126  * the TwoPhaseState->prepXacts array with the correct GID and valid = false,
127  * and mark it as locked by my backend.
128  *
129  * 2. After successfully completing prepare, set valid = true and enter the
130  * referenced PGPROC into the global ProcArray.
131  *
132  * 3. To begin COMMIT PREPARED or ROLLBACK PREPARED, check that the entry is
133  * valid and not locked, then mark the entry as locked by storing my current
134  * backend ID into locking_backend. This prevents concurrent attempts to
135  * commit or rollback the same prepared xact.
136  *
137  * 4. On completion of COMMIT PREPARED or ROLLBACK PREPARED, remove the entry
138  * from the ProcArray and the TwoPhaseState->prepXacts array and return it to
139  * the freelist.
140  *
141  * Note that if the preparing transaction fails between steps 1 and 2, the
142  * entry must be removed so that the GID and the GlobalTransaction struct
143  * can be reused. See AtAbort_Twophase().
144  *
145  * typedef struct GlobalTransactionData *GlobalTransaction appears in
146  * twophase.h
147  */
148 
149 typedef struct GlobalTransactionData
150 {
151  GlobalTransaction next; /* list link for free list */
152  int pgprocno; /* ID of associated dummy PGPROC */
153  BackendId dummyBackendId; /* similar to backend id for backends */
154  TimestampTz prepared_at; /* time of preparation */
155 
156  /*
157  * Note that we need to keep track of two LSNs for each GXACT. We keep
158  * track of the start LSN because this is the address we must use to read
159  * state data back from WAL when committing a prepared GXACT. We keep
160  * track of the end LSN because that is the LSN we need to wait for prior
161  * to commit.
162  */
163  XLogRecPtr prepare_start_lsn; /* XLOG offset of prepare record start */
164  XLogRecPtr prepare_end_lsn; /* XLOG offset of prepare record end */
165  TransactionId xid; /* The GXACT id */
166 
167  Oid owner; /* ID of user that executed the xact */
168  BackendId locking_backend; /* backend currently working on the xact */
169  bool valid; /* true if PGPROC entry is in proc array */
170  bool ondisk; /* true if prepare state file is on disk */
171  bool inredo; /* true if entry was added via xlog_redo */
172  char gid[GIDSIZE]; /* The GID assigned to the prepared xact */
174 
175 /*
176  * Two Phase Commit shared state. Access to this struct is protected
177  * by TwoPhaseStateLock.
178  */
179 typedef struct TwoPhaseStateData
180 {
181  /* Head of linked list of free GlobalTransactionData structs */
183 
184  /* Number of valid prepXacts entries. */
186 
187  /* There are max_prepared_xacts items in this array */
190 
192 
193 /*
194  * Global transaction entry currently locked by us, if any. Note that any
195  * access to the entry pointed to by this variable must be protected by
196  * TwoPhaseStateLock, though obviously the pointer itself doesn't need to be
197  * (since it's just local memory).
198  */
200 
201 static bool twophaseExitRegistered = false;
202 
204  int nchildren,
205  TransactionId *children,
206  int nrels,
207  RelFileNode *rels,
208  int nstats,
209  xl_xact_stats_item *stats,
210  int ninvalmsgs,
211  SharedInvalidationMessage *invalmsgs,
212  bool initfileinval,
213  const char *gid);
215  int nchildren,
216  TransactionId *children,
217  int nrels,
218  RelFileNode *rels,
219  int nstats,
220  xl_xact_stats_item *stats,
221  const char *gid);
222 static void ProcessRecords(char *bufptr, TransactionId xid,
223  const TwoPhaseCallback callbacks[]);
224 static void RemoveGXact(GlobalTransaction gxact);
225 
226 static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len);
227 static char *ProcessTwoPhaseBuffer(TransactionId xid,
228  XLogRecPtr prepare_start_lsn,
229  bool fromdisk, bool setParent, bool setNextXid);
231  const char *gid, TimestampTz prepared_at, Oid owner,
232  Oid databaseid);
233 static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning);
234 static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len);
235 
236 /*
237  * Initialization of shared memory
238  */
239 Size
241 {
242  Size size;
243 
244  /* Need the fixed struct, the array of pointers, and the GTD structs */
245  size = offsetof(TwoPhaseStateData, prepXacts);
246  size = add_size(size, mul_size(max_prepared_xacts,
247  sizeof(GlobalTransaction)));
248  size = MAXALIGN(size);
249  size = add_size(size, mul_size(max_prepared_xacts,
250  sizeof(GlobalTransactionData)));
251 
252  return size;
253 }
254 
255 void
257 {
258  bool found;
259 
260  TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
262  &found);
263  if (!IsUnderPostmaster)
264  {
265  GlobalTransaction gxacts;
266  int i;
267 
268  Assert(!found);
269  TwoPhaseState->freeGXacts = NULL;
271 
272  /*
273  * Initialize the linked list of free GlobalTransactionData structs
274  */
275  gxacts = (GlobalTransaction)
276  ((char *) TwoPhaseState +
277  MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
279  for (i = 0; i < max_prepared_xacts; i++)
280  {
281  /* insert into linked list */
282  gxacts[i].next = TwoPhaseState->freeGXacts;
283  TwoPhaseState->freeGXacts = &gxacts[i];
284 
285  /* associate it with a PGPROC assigned by InitProcGlobal */
287 
288  /*
289  * Assign a unique ID for each dummy proc, so that the range of
290  * dummy backend IDs immediately follows the range of normal
291  * backend IDs. We don't dare to assign a real backend ID to dummy
292  * procs, because prepared transactions don't take part in cache
293  * invalidation like a real backend ID would imply, but having a
294  * unique ID for them is nevertheless handy. This arrangement
295  * allows you to allocate an array of size (MaxBackends +
296  * max_prepared_xacts + 1), and have a slot for every backend and
297  * prepared transaction. Currently multixact.c uses that
298  * technique.
299  */
300  gxacts[i].dummyBackendId = MaxBackends + 1 + i;
301  }
302  }
303  else
304  Assert(found);
305 }
306 
307 /*
308  * Exit hook to unlock the global transaction entry we're working on.
309  */
310 static void
312 {
313  /* same logic as abort */
315 }
316 
317 /*
318  * Abort hook to unlock the global transaction entry we're working on.
319  */
320 void
322 {
323  if (MyLockedGxact == NULL)
324  return;
325 
326  /*
327  * What to do with the locked global transaction entry? If we were in the
328  * process of preparing the transaction, but haven't written the WAL
329  * record and state file yet, the transaction must not be considered as
330  * prepared. Likewise, if we are in the process of finishing an
331  * already-prepared transaction, and fail after having already written the
332  * 2nd phase commit or rollback record to the WAL, the transaction should
333  * not be considered as prepared anymore. In those cases, just remove the
334  * entry from shared memory.
335  *
336  * Otherwise, the entry must be left in place so that the transaction can
337  * be finished later, so just unlock it.
338  *
339  * If we abort during prepare, after having written the WAL record, we
340  * might not have transferred all locks and other state to the prepared
341  * transaction yet. Likewise, if we abort during commit or rollback,
342  * after having written the WAL record, we might not have released all the
343  * resources held by the transaction yet. In those cases, the in-memory
344  * state can be wrong, but it's too late to back out.
345  */
346  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
347  if (!MyLockedGxact->valid)
349  else
351  LWLockRelease(TwoPhaseStateLock);
352 
353  MyLockedGxact = NULL;
354 }
355 
356 /*
357  * This is called after we have finished transferring state to the prepared
358  * PGPROC entry.
359  */
360 void
362 {
363  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
365  LWLockRelease(TwoPhaseStateLock);
366 
367  MyLockedGxact = NULL;
368 }
369 
370 
371 /*
372  * MarkAsPreparing
373  * Reserve the GID for the given transaction.
374  */
376 MarkAsPreparing(TransactionId xid, const char *gid,
377  TimestampTz prepared_at, Oid owner, Oid databaseid)
378 {
379  GlobalTransaction gxact;
380  int i;
381 
382  if (strlen(gid) >= GIDSIZE)
383  ereport(ERROR,
384  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
385  errmsg("transaction identifier \"%s\" is too long",
386  gid)));
387 
388  /* fail immediately if feature is disabled */
389  if (max_prepared_xacts == 0)
390  ereport(ERROR,
391  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
392  errmsg("prepared transactions are disabled"),
393  errhint("Set max_prepared_transactions to a nonzero value.")));
394 
395  /* on first call, register the exit hook */
397  {
399  twophaseExitRegistered = true;
400  }
401 
402  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
403 
404  /* Check for conflicting GID */
405  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
406  {
407  gxact = TwoPhaseState->prepXacts[i];
408  if (strcmp(gxact->gid, gid) == 0)
409  {
410  ereport(ERROR,
412  errmsg("transaction identifier \"%s\" is already in use",
413  gid)));
414  }
415  }
416 
417  /* Get a free gxact from the freelist */
418  if (TwoPhaseState->freeGXacts == NULL)
419  ereport(ERROR,
420  (errcode(ERRCODE_OUT_OF_MEMORY),
421  errmsg("maximum number of prepared transactions reached"),
422  errhint("Increase max_prepared_transactions (currently %d).",
424  gxact = TwoPhaseState->freeGXacts;
425  TwoPhaseState->freeGXacts = gxact->next;
426 
427  MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
428 
429  gxact->ondisk = false;
430 
431  /* And insert it into the active array */
434 
435  LWLockRelease(TwoPhaseStateLock);
436 
437  return gxact;
438 }
439 
440 /*
441  * MarkAsPreparingGuts
442  *
443  * This uses a gxact struct and puts it into the active array.
444  * NOTE: this is also used when reloading a gxact after a crash; so avoid
445  * assuming that we can use very much backend context.
446  *
447  * Note: This function should be called with appropriate locks held.
448  */
449 static void
451  TimestampTz prepared_at, Oid owner, Oid databaseid)
452 {
453  PGPROC *proc;
454  int i;
455 
456  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
457 
458  Assert(gxact != NULL);
459  proc = &ProcGlobal->allProcs[gxact->pgprocno];
460 
461  /* Initialize the PGPROC entry */
462  MemSet(proc, 0, sizeof(PGPROC));
463  proc->pgprocno = gxact->pgprocno;
464  SHMQueueElemInit(&(proc->links));
467  {
468  /* clone VXID, for TwoPhaseGetXidByVirtualXID() to find */
469  proc->lxid = MyProc->lxid;
470  proc->backendId = MyBackendId;
471  }
472  else
473  {
475  /* GetLockConflicts() uses this to specify a wait on the XID */
476  proc->lxid = xid;
477  proc->backendId = InvalidBackendId;
478  }
479  proc->xid = xid;
480  Assert(proc->xmin == InvalidTransactionId);
481  proc->delayChkptFlags = 0;
482  proc->statusFlags = 0;
483  proc->pid = 0;
484  proc->databaseId = databaseid;
485  proc->roleId = owner;
486  proc->tempNamespaceId = InvalidOid;
487  proc->isBackgroundWorker = false;
488  proc->lwWaiting = false;
489  proc->lwWaitMode = 0;
490  proc->waitLock = NULL;
491  proc->waitProcLock = NULL;
492  pg_atomic_init_u64(&proc->waitStart, 0);
493  for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
494  SHMQueueInit(&(proc->myProcLocks[i]));
495  /* subxid data must be filled later by GXactLoadSubxactData */
496  proc->subxidStatus.overflowed = false;
497  proc->subxidStatus.count = 0;
498 
499  gxact->prepared_at = prepared_at;
500  gxact->xid = xid;
501  gxact->owner = owner;
502  gxact->locking_backend = MyBackendId;
503  gxact->valid = false;
504  gxact->inredo = false;
505  strcpy(gxact->gid, gid);
506 
507  /*
508  * Remember that we have this GlobalTransaction entry locked for us. If we
509  * abort after this, we must release it.
510  */
511  MyLockedGxact = gxact;
512 }
513 
514 /*
515  * GXactLoadSubxactData
516  *
517  * If the transaction being persisted had any subtransactions, this must
518  * be called before MarkAsPrepared() to load information into the dummy
519  * PGPROC.
520  */
521 static void
523  TransactionId *children)
524 {
525  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
526 
527  /* We need no extra lock since the GXACT isn't valid yet */
528  if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
529  {
530  proc->subxidStatus.overflowed = true;
531  nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
532  }
533  if (nsubxacts > 0)
534  {
535  memcpy(proc->subxids.xids, children,
536  nsubxacts * sizeof(TransactionId));
537  proc->subxidStatus.count = nsubxacts;
538  }
539 }
540 
541 /*
542  * MarkAsPrepared
543  * Mark the GXACT as fully valid, and enter it into the global ProcArray.
544  *
545  * lock_held indicates whether caller already holds TwoPhaseStateLock.
546  */
547 static void
548 MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
549 {
550  /* Lock here may be overkill, but I'm not convinced of that ... */
551  if (!lock_held)
552  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
553  Assert(!gxact->valid);
554  gxact->valid = true;
555  if (!lock_held)
556  LWLockRelease(TwoPhaseStateLock);
557 
558  /*
559  * Put it into the global ProcArray so TransactionIdIsInProgress considers
560  * the XID as still running.
561  */
563 }
564 
565 /*
566  * LockGXact
567  * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
568  */
569 static GlobalTransaction
570 LockGXact(const char *gid, Oid user)
571 {
572  int i;
573 
574  /* on first call, register the exit hook */
576  {
578  twophaseExitRegistered = true;
579  }
580 
581  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
582 
583  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
584  {
586  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
587 
588  /* Ignore not-yet-valid GIDs */
589  if (!gxact->valid)
590  continue;
591  if (strcmp(gxact->gid, gid) != 0)
592  continue;
593 
594  /* Found it, but has someone else got it locked? */
595  if (gxact->locking_backend != InvalidBackendId)
596  ereport(ERROR,
597  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
598  errmsg("prepared transaction with identifier \"%s\" is busy",
599  gid)));
600 
601  if (user != gxact->owner && !superuser_arg(user))
602  ereport(ERROR,
603  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
604  errmsg("permission denied to finish prepared transaction"),
605  errhint("Must be superuser or the user that prepared the transaction.")));
606 
607  /*
608  * Note: it probably would be possible to allow committing from
609  * another database; but at the moment NOTIFY is known not to work and
610  * there may be some other issues as well. Hence disallow until
611  * someone gets motivated to make it work.
612  */
613  if (MyDatabaseId != proc->databaseId)
614  ereport(ERROR,
615  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
616  errmsg("prepared transaction belongs to another database"),
617  errhint("Connect to the database where the transaction was prepared to finish it.")));
618 
619  /* OK for me to lock it */
620  gxact->locking_backend = MyBackendId;
621  MyLockedGxact = gxact;
622 
623  LWLockRelease(TwoPhaseStateLock);
624 
625  return gxact;
626  }
627 
628  LWLockRelease(TwoPhaseStateLock);
629 
630  ereport(ERROR,
631  (errcode(ERRCODE_UNDEFINED_OBJECT),
632  errmsg("prepared transaction with identifier \"%s\" does not exist",
633  gid)));
634 
635  /* NOTREACHED */
636  return NULL;
637 }
638 
639 /*
640  * RemoveGXact
641  * Remove the prepared transaction from the shared memory array.
642  *
643  * NB: caller should have already removed it from ProcArray
644  */
645 static void
647 {
648  int i;
649 
650  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
651 
652  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
653  {
654  if (gxact == TwoPhaseState->prepXacts[i])
655  {
656  /* remove from the active array */
659 
660  /* and put it back in the freelist */
661  gxact->next = TwoPhaseState->freeGXacts;
662  TwoPhaseState->freeGXacts = gxact;
663 
664  return;
665  }
666  }
667 
668  elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
669 }
670 
671 /*
672  * Returns an array of all prepared transactions for the user-level
673  * function pg_prepared_xact.
674  *
675  * The returned array and all its elements are copies of internal data
676  * structures, to minimize the time we need to hold the TwoPhaseStateLock.
677  *
678  * WARNING -- we return even those transactions that are not fully prepared
679  * yet. The caller should filter them out if he doesn't want them.
680  *
681  * The returned array is palloc'd.
682  */
683 static int
685 {
686  GlobalTransaction array;
687  int num;
688  int i;
689 
690  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
691 
692  if (TwoPhaseState->numPrepXacts == 0)
693  {
694  LWLockRelease(TwoPhaseStateLock);
695 
696  *gxacts = NULL;
697  return 0;
698  }
699 
701  array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
702  *gxacts = array;
703  for (i = 0; i < num; i++)
704  memcpy(array + i, TwoPhaseState->prepXacts[i],
705  sizeof(GlobalTransactionData));
706 
707  LWLockRelease(TwoPhaseStateLock);
708 
709  return num;
710 }
711 
712 
713 /* Working status for pg_prepared_xact */
714 typedef struct
715 {
717  int ngxacts;
718  int currIdx;
719 } Working_State;
720 
721 /*
722  * pg_prepared_xact
723  * Produce a view with one row per prepared transaction.
724  *
725  * This function is here so we don't have to export the
726  * GlobalTransactionData struct definition.
727  */
728 Datum
730 {
731  FuncCallContext *funcctx;
733 
734  if (SRF_IS_FIRSTCALL())
735  {
736  TupleDesc tupdesc;
737  MemoryContext oldcontext;
738 
739  /* create a function context for cross-call persistence */
740  funcctx = SRF_FIRSTCALL_INIT();
741 
742  /*
743  * Switch to memory context appropriate for multiple function calls
744  */
745  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
746 
747  /* build tupdesc for result tuples */
748  /* this had better match pg_prepared_xacts view in system_views.sql */
749  tupdesc = CreateTemplateTupleDesc(5);
750  TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
751  XIDOID, -1, 0);
752  TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
753  TEXTOID, -1, 0);
754  TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
755  TIMESTAMPTZOID, -1, 0);
756  TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
757  OIDOID, -1, 0);
758  TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
759  OIDOID, -1, 0);
760 
761  funcctx->tuple_desc = BlessTupleDesc(tupdesc);
762 
763  /*
764  * Collect all the 2PC status information that we will format and send
765  * out as a result set.
766  */
767  status = (Working_State *) palloc(sizeof(Working_State));
768  funcctx->user_fctx = (void *) status;
769 
770  status->ngxacts = GetPreparedTransactionList(&status->array);
771  status->currIdx = 0;
772 
773  MemoryContextSwitchTo(oldcontext);
774  }
775 
776  funcctx = SRF_PERCALL_SETUP();
777  status = (Working_State *) funcctx->user_fctx;
778 
779  while (status->array != NULL && status->currIdx < status->ngxacts)
780  {
781  GlobalTransaction gxact = &status->array[status->currIdx++];
782  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
783  Datum values[5];
784  bool nulls[5];
785  HeapTuple tuple;
786  Datum result;
787 
788  if (!gxact->valid)
789  continue;
790 
791  /*
792  * Form tuple with appropriate data.
793  */
794  MemSet(values, 0, sizeof(values));
795  MemSet(nulls, 0, sizeof(nulls));
796 
797  values[0] = TransactionIdGetDatum(proc->xid);
798  values[1] = CStringGetTextDatum(gxact->gid);
800  values[3] = ObjectIdGetDatum(gxact->owner);
801  values[4] = ObjectIdGetDatum(proc->databaseId);
802 
803  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
804  result = HeapTupleGetDatum(tuple);
805  SRF_RETURN_NEXT(funcctx, result);
806  }
807 
808  SRF_RETURN_DONE(funcctx);
809 }
810 
811 /*
812  * TwoPhaseGetGXact
813  * Get the GlobalTransaction struct for a prepared transaction
814  * specified by XID
815  *
816  * If lock_held is set to true, TwoPhaseStateLock will not be taken, so the
817  * caller had better hold it.
818  */
819 static GlobalTransaction
820 TwoPhaseGetGXact(TransactionId xid, bool lock_held)
821 {
822  GlobalTransaction result = NULL;
823  int i;
824 
825  static TransactionId cached_xid = InvalidTransactionId;
826  static GlobalTransaction cached_gxact = NULL;
827 
828  Assert(!lock_held || LWLockHeldByMe(TwoPhaseStateLock));
829 
830  /*
831  * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
832  * repeatedly for the same XID. We can save work with a simple cache.
833  */
834  if (xid == cached_xid)
835  return cached_gxact;
836 
837  if (!lock_held)
838  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
839 
840  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
841  {
843 
844  if (gxact->xid == xid)
845  {
846  result = gxact;
847  break;
848  }
849  }
850 
851  if (!lock_held)
852  LWLockRelease(TwoPhaseStateLock);
853 
854  if (result == NULL) /* should not happen */
855  elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
856 
857  cached_xid = xid;
858  cached_gxact = result;
859 
860  return result;
861 }
862 
863 /*
864  * TwoPhaseGetXidByVirtualXID
865  * Lookup VXID among xacts prepared since last startup.
866  *
867  * (This won't find recovered xacts.) If more than one matches, return any
868  * and set "have_more" to true. To witness multiple matches, a single
869  * BackendId must consume 2^32 LXIDs, with no intervening database restart.
870  */
873  bool *have_more)
874 {
875  int i;
877 
879  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
880 
881  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
882  {
884  PGPROC *proc;
885  VirtualTransactionId proc_vxid;
886 
887  if (!gxact->valid)
888  continue;
889  proc = &ProcGlobal->allProcs[gxact->pgprocno];
890  GET_VXID_FROM_PGPROC(proc_vxid, *proc);
891  if (VirtualTransactionIdEquals(vxid, proc_vxid))
892  {
893  /* Startup process sets proc->backendId to InvalidBackendId. */
894  Assert(!gxact->inredo);
895 
896  if (result != InvalidTransactionId)
897  {
898  *have_more = true;
899  break;
900  }
901  result = gxact->xid;
902  }
903  }
904 
905  LWLockRelease(TwoPhaseStateLock);
906 
907  return result;
908 }
909 
910 /*
911  * TwoPhaseGetDummyBackendId
912  * Get the dummy backend ID for prepared transaction specified by XID
913  *
914  * Dummy backend IDs are similar to real backend IDs of real backends.
915  * They start at MaxBackends + 1, and are unique across all currently active
916  * real backends and prepared transactions. If lock_held is set to true,
917  * TwoPhaseStateLock will not be taken, so the caller had better hold it.
918  */
919 BackendId
921 {
922  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
923 
924  return gxact->dummyBackendId;
925 }
926 
927 /*
928  * TwoPhaseGetDummyProc
929  * Get the PGPROC that represents a prepared transaction specified by XID
930  *
931  * If lock_held is set to true, TwoPhaseStateLock will not be taken, so the
932  * caller had better hold it.
933  */
934 PGPROC *
936 {
937  GlobalTransaction gxact = TwoPhaseGetGXact(xid, lock_held);
938 
939  return &ProcGlobal->allProcs[gxact->pgprocno];
940 }
941 
942 /************************************************************************/
943 /* State file support */
944 /************************************************************************/
945 
946 #define TwoPhaseFilePath(path, xid) \
947  snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X", xid)
948 
949 /*
950  * 2PC state file format:
951  *
952  * 1. TwoPhaseFileHeader
953  * 2. TransactionId[] (subtransactions)
954  * 3. RelFileNode[] (files to be deleted at commit)
955  * 4. RelFileNode[] (files to be deleted at abort)
956  * 5. SharedInvalidationMessage[] (inval messages to be sent at commit)
957  * 6. TwoPhaseRecordOnDisk
958  * 7. ...
959  * 8. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
960  * 9. checksum (CRC-32C)
961  *
962  * Each segment except the final checksum is MAXALIGN'd.
963  */
964 
965 /*
966  * Header for a 2PC state file
967  */
968 #define TWOPHASE_MAGIC 0x57F94534 /* format identifier */
969 
971 
972 /*
973  * Header for each record in a state file
974  *
975  * NOTE: len counts only the rmgr data, not the TwoPhaseRecordOnDisk header.
976  * The rmgr data will be stored starting on a MAXALIGN boundary.
977  */
978 typedef struct TwoPhaseRecordOnDisk
979 {
980  uint32 len; /* length of rmgr data */
981  TwoPhaseRmgrId rmid; /* resource manager for this record */
982  uint16 info; /* flag bits for use by rmgr */
984 
985 /*
986  * During prepare, the state file is assembled in memory before writing it
987  * to WAL and the actual state file. We use a chain of StateFileChunk blocks
988  * for that.
989  */
990 typedef struct StateFileChunk
991 {
992  char *data;
996 
997 static struct xllist
998 {
999  StateFileChunk *head; /* first data block in the chain */
1000  StateFileChunk *tail; /* last block in chain */
1002  uint32 bytes_free; /* free bytes left in tail block */
1003  uint32 total_len; /* total data bytes in chain */
1005 
1006 
1007 /*
1008  * Append a block of data to records data structure.
1009  *
1010  * NB: each block is padded to a MAXALIGN multiple. This must be
1011  * accounted for when the file is later read!
1012  *
1013  * The data is copied, so the caller is free to modify it afterwards.
1014  */
1015 static void
1017 {
1018  uint32 padlen = MAXALIGN(len);
1019 
1020  if (padlen > records.bytes_free)
1021  {
1022  records.tail->next = palloc0(sizeof(StateFileChunk));
1024  records.tail->len = 0;
1025  records.tail->next = NULL;
1026  records.num_chunks++;
1027 
1028  records.bytes_free = Max(padlen, 512);
1030  }
1031 
1032  memcpy(((char *) records.tail->data) + records.tail->len, data, len);
1033  records.tail->len += padlen;
1034  records.bytes_free -= padlen;
1035  records.total_len += padlen;
1036 }
1037 
1038 /*
1039  * Start preparing a state file.
1040  *
1041  * Initializes data structure and inserts the 2PC file header record.
1042  */
1043 void
1045 {
1046  PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
1047  TransactionId xid = gxact->xid;
1048  TwoPhaseFileHeader hdr;
1049  TransactionId *children;
1050  RelFileNode *commitrels;
1051  RelFileNode *abortrels;
1052  xl_xact_stats_item *abortstats = NULL;
1053  xl_xact_stats_item *commitstats = NULL;
1054  SharedInvalidationMessage *invalmsgs;
1055 
1056  /* Initialize linked list */
1057  records.head = palloc0(sizeof(StateFileChunk));
1058  records.head->len = 0;
1059  records.head->next = NULL;
1060 
1061  records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1063 
1065  records.num_chunks = 1;
1066 
1067  records.total_len = 0;
1068 
1069  /* Create header */
1070  hdr.magic = TWOPHASE_MAGIC;
1071  hdr.total_len = 0; /* EndPrepare will fill this in */
1072  hdr.xid = xid;
1073  hdr.database = proc->databaseId;
1074  hdr.prepared_at = gxact->prepared_at;
1075  hdr.owner = gxact->owner;
1076  hdr.nsubxacts = xactGetCommittedChildren(&children);
1077  hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1078  hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1079  hdr.ncommitstats =
1080  pgstat_get_transactional_drops(true, &commitstats);
1081  hdr.nabortstats =
1082  pgstat_get_transactional_drops(false, &abortstats);
1084  &hdr.initfileinval);
1085  hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1086  /* EndPrepare will fill the origin data, if necessary */
1088  hdr.origin_timestamp = 0;
1089 
1090  save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1091  save_state_data(gxact->gid, hdr.gidlen);
1092 
1093  /*
1094  * Add the additional info about subxacts, deletable files and cache
1095  * invalidation messages.
1096  */
1097  if (hdr.nsubxacts > 0)
1098  {
1099  save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1100  /* While we have the child-xact data, stuff it in the gxact too */
1101  GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1102  }
1103  if (hdr.ncommitrels > 0)
1104  {
1105  save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1106  pfree(commitrels);
1107  }
1108  if (hdr.nabortrels > 0)
1109  {
1110  save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1111  pfree(abortrels);
1112  }
1113  if (hdr.ncommitstats > 0)
1114  {
1115  save_state_data(commitstats,
1116  hdr.ncommitstats * sizeof(xl_xact_stats_item));
1117  pfree(commitstats);
1118  }
1119  if (hdr.nabortstats > 0)
1120  {
1121  save_state_data(abortstats,
1122  hdr.nabortstats * sizeof(xl_xact_stats_item));
1123  pfree(abortstats);
1124  }
1125  if (hdr.ninvalmsgs > 0)
1126  {
1127  save_state_data(invalmsgs,
1128  hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1129  pfree(invalmsgs);
1130  }
1131 }
1132 
1133 /*
1134  * Finish preparing state data and writing it to WAL.
1135  */
1136 void
1138 {
1139  TwoPhaseFileHeader *hdr;
1140  StateFileChunk *record;
1141  bool replorigin;
1142 
1143  /* Add the end sentinel to the list of 2PC records */
1145  NULL, 0);
1146 
1147  /* Go back and fill in total_len in the file header record */
1148  hdr = (TwoPhaseFileHeader *) records.head->data;
1149  Assert(hdr->magic == TWOPHASE_MAGIC);
1150  hdr->total_len = records.total_len + sizeof(pg_crc32c);
1151 
1152  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1154 
1155  if (replorigin)
1156  {
1159  }
1160 
1161  /*
1162  * If the data size exceeds MaxAllocSize, we won't be able to read it in
1163  * ReadTwoPhaseFile. Check for that now, rather than fail in the case
1164  * where we write data to file and then re-read at commit time.
1165  */
1166  if (hdr->total_len > MaxAllocSize)
1167  ereport(ERROR,
1168  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1169  errmsg("two-phase state file maximum length exceeded")));
1170 
1171  /*
1172  * Now writing 2PC state data to WAL. We let the WAL's CRC protection
1173  * cover us, so no need to calculate a separate CRC.
1174  *
1175  * We have to set DELAY_CHKPT_START here, too; otherwise a checkpoint
1176  * starting immediately after the WAL record is inserted could complete
1177  * without fsync'ing our state file. (This is essentially the same kind
1178  * of race condition as the COMMIT-to-clog-write case that
1179  * RecordTransactionCommit uses DELAY_CHKPT_START for; see notes there.)
1180  *
1181  * We save the PREPARE record's location in the gxact for later use by
1182  * CheckPointTwoPhase.
1183  */
1185 
1187 
1190 
1191  XLogBeginInsert();
1192  for (record = records.head; record != NULL; record = record->next)
1193  XLogRegisterData(record->data, record->len);
1194 
1196 
1197  gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1198 
1199  if (replorigin)
1200  {
1201  /* Move LSNs forward for this replication origin */
1203  gxact->prepare_end_lsn);
1204  }
1205 
1206  XLogFlush(gxact->prepare_end_lsn);
1207 
1208  /* If we crash now, we have prepared: WAL replay will fix things */
1209 
1210  /* Store record's start location to read that later on Commit */
1212 
1213  /*
1214  * Mark the prepared transaction as valid. As soon as xact.c marks MyProc
1215  * as not running our XID (which it will do immediately after this
1216  * function returns), others can commit/rollback the xact.
1217  *
1218  * NB: a side effect of this is to make a dummy ProcArray entry for the
1219  * prepared XID. This must happen before we clear the XID from MyProc /
1220  * ProcGlobal->xids[], else there is a window where the XID is not running
1221  * according to TransactionIdIsInProgress, and onlookers would be entitled
1222  * to assume the xact crashed. Instead we have a window where the same
1223  * XID appears twice in ProcArray, which is OK.
1224  */
1225  MarkAsPrepared(gxact, false);
1226 
1227  /*
1228  * Now we can mark ourselves as out of the commit critical section: a
1229  * checkpoint starting after this will certainly see the gxact as a
1230  * candidate for fsyncing.
1231  */
1233 
1234  /*
1235  * Remember that we have this GlobalTransaction entry locked for us. If
1236  * we crash after this point, it's too late to abort, but we must unlock
1237  * it so that the prepared transaction can be committed or rolled back.
1238  */
1239  MyLockedGxact = gxact;
1240 
1241  END_CRIT_SECTION();
1242 
1243  /*
1244  * Wait for synchronous replication, if required.
1245  *
1246  * Note that at this stage we have marked the prepare, but still show as
1247  * running in the procarray (twice!) and continue to hold locks.
1248  */
1249  SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1250 
1251  records.tail = records.head = NULL;
1252  records.num_chunks = 0;
1253 }
1254 
1255 /*
1256  * Register a 2PC record to be written to state file.
1257  */
1258 void
1260  const void *data, uint32 len)
1261 {
1262  TwoPhaseRecordOnDisk record;
1263 
1264  record.rmid = rmid;
1265  record.info = info;
1266  record.len = len;
1267  save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1268  if (len > 0)
1270 }
1271 
1272 
1273 /*
1274  * Read and validate the state file for xid.
1275  *
1276  * If it looks OK (has a valid magic number and CRC), return the palloc'd
1277  * contents of the file, issuing an error when finding corrupted data. If
1278  * missing_ok is true, which indicates that missing files can be safely
1279  * ignored, then return NULL. This state can be reached when doing recovery.
1280  */
1281 static char *
1282 ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
1283 {
1284  char path[MAXPGPATH];
1285  char *buf;
1286  TwoPhaseFileHeader *hdr;
1287  int fd;
1288  struct stat stat;
1289  uint32 crc_offset;
1290  pg_crc32c calc_crc,
1291  file_crc;
1292  int r;
1293 
1294  TwoPhaseFilePath(path, xid);
1295 
1296  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
1297  if (fd < 0)
1298  {
1299  if (missing_ok && errno == ENOENT)
1300  return NULL;
1301 
1302  ereport(ERROR,
1304  errmsg("could not open file \"%s\": %m", path)));
1305  }
1306 
1307  /*
1308  * Check file length. We can determine a lower bound pretty easily. We
1309  * set an upper bound to avoid palloc() failure on a corrupt file, though
1310  * we can't guarantee that we won't get an out of memory error anyway,
1311  * even on a valid file.
1312  */
1313  if (fstat(fd, &stat))
1314  ereport(ERROR,
1316  errmsg("could not stat file \"%s\": %m", path)));
1317 
1318  if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1319  MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1320  sizeof(pg_crc32c)) ||
1322  ereport(ERROR,
1324  errmsg_plural("incorrect size of file \"%s\": %lld byte",
1325  "incorrect size of file \"%s\": %lld bytes",
1326  (long long int) stat.st_size, path,
1327  (long long int) stat.st_size)));
1328 
1329  crc_offset = stat.st_size - sizeof(pg_crc32c);
1330  if (crc_offset != MAXALIGN(crc_offset))
1331  ereport(ERROR,
1333  errmsg("incorrect alignment of CRC offset for file \"%s\"",
1334  path)));
1335 
1336  /*
1337  * OK, slurp in the file.
1338  */
1339  buf = (char *) palloc(stat.st_size);
1340 
1342  r = read(fd, buf, stat.st_size);
1343  if (r != stat.st_size)
1344  {
1345  if (r < 0)
1346  ereport(ERROR,
1348  errmsg("could not read file \"%s\": %m", path)));
1349  else
1350  ereport(ERROR,
1351  (errmsg("could not read file \"%s\": read %d of %lld",
1352  path, r, (long long int) stat.st_size)));
1353  }
1354 
1356 
1357  if (CloseTransientFile(fd) != 0)
1358  ereport(ERROR,
1360  errmsg("could not close file \"%s\": %m", path)));
1361 
1362  hdr = (TwoPhaseFileHeader *) buf;
1363  if (hdr->magic != TWOPHASE_MAGIC)
1364  ereport(ERROR,
1366  errmsg("invalid magic number stored in file \"%s\"",
1367  path)));
1368 
1369  if (hdr->total_len != stat.st_size)
1370  ereport(ERROR,
1372  errmsg("invalid size stored in file \"%s\"",
1373  path)));
1374 
1375  INIT_CRC32C(calc_crc);
1376  COMP_CRC32C(calc_crc, buf, crc_offset);
1377  FIN_CRC32C(calc_crc);
1378 
1379  file_crc = *((pg_crc32c *) (buf + crc_offset));
1380 
1381  if (!EQ_CRC32C(calc_crc, file_crc))
1382  ereport(ERROR,
1384  errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
1385  path)));
1386 
1387  return buf;
1388 }
1389 
1390 
1391 /*
1392  * Reads 2PC data from xlog. During checkpoint this data will be moved to
1393  * twophase files and ReadTwoPhaseFile should be used instead.
1394  *
1395  * Note clearly that this function can access WAL during normal operation,
1396  * similarly to the way WALSender or Logical Decoding would do.
1397  */
1398 static void
1400 {
1401  XLogRecord *record;
1403  char *errormsg;
1404 
1406  XL_ROUTINE(.page_read = &read_local_xlog_page,
1407  .segment_open = &wal_segment_open,
1408  .segment_close = &wal_segment_close),
1409  NULL);
1410  if (!xlogreader)
1411  ereport(ERROR,
1412  (errcode(ERRCODE_OUT_OF_MEMORY),
1413  errmsg("out of memory"),
1414  errdetail("Failed while allocating a WAL reading processor.")));
1415 
1416  XLogBeginRead(xlogreader, lsn);
1417  record = XLogReadRecord(xlogreader, &errormsg);
1418 
1419  if (record == NULL)
1420  {
1421  if (errormsg)
1422  ereport(ERROR,
1424  errmsg("could not read two-phase state from WAL at %X/%X: %s",
1425  LSN_FORMAT_ARGS(lsn), errormsg)));
1426  else
1427  ereport(ERROR,
1429  errmsg("could not read two-phase state from WAL at %X/%X",
1430  LSN_FORMAT_ARGS(lsn))));
1431  }
1432 
1433  if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1435  ereport(ERROR,
1437  errmsg("expected two-phase state data is not present in WAL at %X/%X",
1438  LSN_FORMAT_ARGS(lsn))));
1439 
1440  if (len != NULL)
1442 
1443  *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1444  memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1445 
1447 }
1448 
1449 
1450 /*
1451  * Confirms an xid is prepared, during recovery
1452  */
1453 bool
1455 {
1456  char *buf;
1457  TwoPhaseFileHeader *hdr;
1458  bool result;
1459 
1461 
1462  if (max_prepared_xacts <= 0)
1463  return false; /* nothing to do */
1464 
1465  /* Read and validate file */
1466  buf = ReadTwoPhaseFile(xid, true);
1467  if (buf == NULL)
1468  return false;
1469 
1470  /* Check header also */
1471  hdr = (TwoPhaseFileHeader *) buf;
1472  result = TransactionIdEquals(hdr->xid, xid);
1473  pfree(buf);
1474 
1475  return result;
1476 }
1477 
1478 /*
1479  * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1480  */
1481 void
1482 FinishPreparedTransaction(const char *gid, bool isCommit)
1483 {
1484  GlobalTransaction gxact;
1485  PGPROC *proc;
1486  TransactionId xid;
1487  char *buf;
1488  char *bufptr;
1489  TwoPhaseFileHeader *hdr;
1490  TransactionId latestXid;
1491  TransactionId *children;
1492  RelFileNode *commitrels;
1493  RelFileNode *abortrels;
1494  RelFileNode *delrels;
1495  int ndelrels;
1496  xl_xact_stats_item *commitstats;
1497  xl_xact_stats_item *abortstats;
1498  SharedInvalidationMessage *invalmsgs;
1499 
1500  /*
1501  * Validate the GID, and lock the GXACT to ensure that two backends do not
1502  * try to commit the same GID at once.
1503  */
1504  gxact = LockGXact(gid, GetUserId());
1505  proc = &ProcGlobal->allProcs[gxact->pgprocno];
1506  xid = gxact->xid;
1507 
1508  /*
1509  * Read and validate 2PC state data. State data will typically be stored
1510  * in WAL files if the LSN is after the last checkpoint record, or moved
1511  * to disk if for some reason they have lived for a long time.
1512  */
1513  if (gxact->ondisk)
1514  buf = ReadTwoPhaseFile(xid, false);
1515  else
1516  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1517 
1518 
1519  /*
1520  * Disassemble the header area
1521  */
1522  hdr = (TwoPhaseFileHeader *) buf;
1523  Assert(TransactionIdEquals(hdr->xid, xid));
1524  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1525  bufptr += MAXALIGN(hdr->gidlen);
1526  children = (TransactionId *) bufptr;
1527  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1528  commitrels = (RelFileNode *) bufptr;
1529  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1530  abortrels = (RelFileNode *) bufptr;
1531  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1532  commitstats = (xl_xact_stats_item *) bufptr;
1533  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
1534  abortstats = (xl_xact_stats_item *) bufptr;
1535  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
1536  invalmsgs = (SharedInvalidationMessage *) bufptr;
1537  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1538 
1539  /* compute latestXid among all children */
1540  latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
1541 
1542  /* Prevent cancel/die interrupt while cleaning up */
1543  HOLD_INTERRUPTS();
1544 
1545  /*
1546  * The order of operations here is critical: make the XLOG entry for
1547  * commit or abort, then mark the transaction committed or aborted in
1548  * pg_xact, then remove its PGPROC from the global ProcArray (which means
1549  * TransactionIdIsInProgress will stop saying the prepared xact is in
1550  * progress), then run the post-commit or post-abort callbacks. The
1551  * callbacks will release the locks the transaction held.
1552  */
1553  if (isCommit)
1555  hdr->nsubxacts, children,
1556  hdr->ncommitrels, commitrels,
1557  hdr->ncommitstats,
1558  commitstats,
1559  hdr->ninvalmsgs, invalmsgs,
1560  hdr->initfileinval, gid);
1561  else
1563  hdr->nsubxacts, children,
1564  hdr->nabortrels, abortrels,
1565  hdr->nabortstats,
1566  abortstats,
1567  gid);
1568 
1569  ProcArrayRemove(proc, latestXid);
1570 
1571  /*
1572  * In case we fail while running the callbacks, mark the gxact invalid so
1573  * no one else will try to commit/rollback, and so it will be recycled if
1574  * we fail after this point. It is still locked by our backend so it
1575  * won't go away yet.
1576  *
1577  * (We assume it's safe to do this without taking TwoPhaseStateLock.)
1578  */
1579  gxact->valid = false;
1580 
1581  /*
1582  * We have to remove any files that were supposed to be dropped. For
1583  * consistency with the regular xact.c code paths, must do this before
1584  * releasing locks, so do it before running the callbacks.
1585  *
1586  * NB: this code knows that we couldn't be dropping any temp rels ...
1587  */
1588  if (isCommit)
1589  {
1590  delrels = commitrels;
1591  ndelrels = hdr->ncommitrels;
1592  }
1593  else
1594  {
1595  delrels = abortrels;
1596  ndelrels = hdr->nabortrels;
1597  }
1598 
1599  /* Make sure files supposed to be dropped are dropped */
1600  DropRelationFiles(delrels, ndelrels, false);
1601 
1602  if (isCommit)
1603  pgstat_execute_transactional_drops(hdr->ncommitstats, commitstats, false);
1604  else
1605  pgstat_execute_transactional_drops(hdr->nabortstats, abortstats, false);
1606 
1607  /*
1608  * Handle cache invalidation messages.
1609  *
1610  * Relcache init file invalidation requires processing both before and
1611  * after we send the SI messages, only when committing. See
1612  * AtEOXact_Inval().
1613  */
1614  if (isCommit)
1615  {
1616  if (hdr->initfileinval)
1618  SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1619  if (hdr->initfileinval)
1621  }
1622 
1623  /*
1624  * Acquire the two-phase lock. We want to work on the two-phase callbacks
1625  * while holding it to avoid potential conflicts with other transactions
1626  * attempting to use the same GID, so the lock is released once the shared
1627  * memory state is cleared.
1628  */
1629  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1630 
1631  /* And now do the callbacks */
1632  if (isCommit)
1634  else
1636 
1637  PredicateLockTwoPhaseFinish(xid, isCommit);
1638 
1639  /* Clear shared memory state */
1640  RemoveGXact(gxact);
1641 
1642  /*
1643  * Release the lock as all callbacks are called and shared memory cleanup
1644  * is done.
1645  */
1646  LWLockRelease(TwoPhaseStateLock);
1647 
1648  /* Count the prepared xact as committed or aborted */
1649  AtEOXact_PgStat(isCommit, false);
1650 
1651  /*
1652  * And now we can clean up any files we may have left.
1653  */
1654  if (gxact->ondisk)
1655  RemoveTwoPhaseFile(xid, true);
1656 
1657  MyLockedGxact = NULL;
1658 
1660 
1661  pfree(buf);
1662 }
1663 
1664 /*
1665  * Scan 2PC state data in memory and call the indicated callbacks for each 2PC record.
1666  */
1667 static void
1668 ProcessRecords(char *bufptr, TransactionId xid,
1669  const TwoPhaseCallback callbacks[])
1670 {
1671  for (;;)
1672  {
1673  TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1674 
1675  Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1676  if (record->rmid == TWOPHASE_RM_END_ID)
1677  break;
1678 
1679  bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1680 
1681  if (callbacks[record->rmid] != NULL)
1682  callbacks[record->rmid] (xid, record->info,
1683  (void *) bufptr, record->len);
1684 
1685  bufptr += MAXALIGN(record->len);
1686  }
1687 }
1688 
1689 /*
1690  * Remove the 2PC file for the specified XID.
1691  *
1692  * If giveWarning is false, do not complain about file-not-present;
1693  * this is an expected case during WAL replay.
1694  */
1695 static void
1696 RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
1697 {
1698  char path[MAXPGPATH];
1699 
1700  TwoPhaseFilePath(path, xid);
1701  if (unlink(path))
1702  if (errno != ENOENT || giveWarning)
1703  ereport(WARNING,
1705  errmsg("could not remove file \"%s\": %m", path)));
1706 }
1707 
1708 /*
1709  * Recreates a state file. This is used in WAL replay and during
1710  * checkpoint creation.
1711  *
1712  * Note: content and len don't include CRC.
1713  */
1714 static void
1715 RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
1716 {
1717  char path[MAXPGPATH];
1718  pg_crc32c statefile_crc;
1719  int fd;
1720 
1721  /* Recompute CRC */
1722  INIT_CRC32C(statefile_crc);
1723  COMP_CRC32C(statefile_crc, content, len);
1724  FIN_CRC32C(statefile_crc);
1725 
1726  TwoPhaseFilePath(path, xid);
1727 
1728  fd = OpenTransientFile(path,
1729  O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY);
1730  if (fd < 0)
1731  ereport(ERROR,
1733  errmsg("could not recreate file \"%s\": %m", path)));
1734 
1735  /* Write content and CRC */
1736  errno = 0;
1738  if (write(fd, content, len) != len)
1739  {
1740  /* if write didn't set errno, assume problem is no disk space */
1741  if (errno == 0)
1742  errno = ENOSPC;
1743  ereport(ERROR,
1745  errmsg("could not write file \"%s\": %m", path)));
1746  }
1747  if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1748  {
1749  /* if write didn't set errno, assume problem is no disk space */
1750  if (errno == 0)
1751  errno = ENOSPC;
1752  ereport(ERROR,
1754  errmsg("could not write file \"%s\": %m", path)));
1755  }
1757 
1758  /*
1759  * We must fsync the file because the end-of-replay checkpoint will not do
1760  * so, there being no GXACT in shared memory yet to tell it to.
1761  */
1763  if (pg_fsync(fd) != 0)
1764  ereport(ERROR,
1766  errmsg("could not fsync file \"%s\": %m", path)));
1768 
1769  if (CloseTransientFile(fd) != 0)
1770  ereport(ERROR,
1772  errmsg("could not close file \"%s\": %m", path)));
1773 }
1774 
1775 /*
1776  * CheckPointTwoPhase -- handle 2PC component of checkpointing.
1777  *
1778  * We must fsync the state file of any GXACT that is valid or has been
1779  * generated during redo and has a PREPARE LSN <= the checkpoint's redo
1780  * horizon. (If the gxact isn't valid yet, has not been generated in
1781  * redo, or has a later LSN, this checkpoint is not responsible for
1782  * fsyncing it.)
1783  *
1784  * This is deliberately run as late as possible in the checkpoint sequence,
1785  * because GXACTs ordinarily have short lifespans, and so it is quite
1786  * possible that GXACTs that were valid at checkpoint start will no longer
1787  * exist if we wait a little bit. With typical checkpoint settings this
1788  * will be about 3 minutes for an online checkpoint, so as a result we
1789  * expect that there will be no GXACTs that need to be copied to disk.
1790  *
1791  * If a GXACT remains valid across multiple checkpoints, it will already
1792  * be on disk so we don't bother to repeat that write.
1793  */
1794 void
1796 {
1797  int i;
1798  int serialized_xacts = 0;
1799 
1800  if (max_prepared_xacts <= 0)
1801  return; /* nothing to do */
1802 
1803  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1804 
1805  /*
1806  * We are expecting there to be zero GXACTs that need to be copied to
1807  * disk, so we perform all I/O while holding TwoPhaseStateLock for
1808  * simplicity. This prevents any new xacts from preparing while this
1809  * occurs, which shouldn't be a problem since the presence of long-lived
1810  * prepared xacts indicates the transaction manager isn't active.
1811  *
1812  * It's also possible to move I/O out of the lock, but on every error we
1813  * should check whether somebody committed our transaction in different
1814  * backend. Let's leave this optimization for future, if somebody will
1815  * spot that this place cause bottleneck.
1816  *
1817  * Note that it isn't possible for there to be a GXACT with a
1818  * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1819  * because of the efforts with delayChkptFlags.
1820  */
1821  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1822  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1823  {
1824  /*
1825  * Note that we are using gxact not PGPROC so this works in recovery
1826  * also
1827  */
1829 
1830  if ((gxact->valid || gxact->inredo) &&
1831  !gxact->ondisk &&
1832  gxact->prepare_end_lsn <= redo_horizon)
1833  {
1834  char *buf;
1835  int len;
1836 
1838  RecreateTwoPhaseFile(gxact->xid, buf, len);
1839  gxact->ondisk = true;
1842  pfree(buf);
1843  serialized_xacts++;
1844  }
1845  }
1846  LWLockRelease(TwoPhaseStateLock);
1847 
1848  /*
1849  * Flush unconditionally the parent directory to make any information
1850  * durable on disk. Two-phase files could have been removed and those
1851  * removals need to be made persistent as well as any files newly created
1852  * previously since the last checkpoint.
1853  */
1854  fsync_fname(TWOPHASE_DIR, true);
1855 
1856  TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1857 
1858  if (log_checkpoints && serialized_xacts > 0)
1859  ereport(LOG,
1860  (errmsg_plural("%u two-phase state file was written "
1861  "for a long-running prepared transaction",
1862  "%u two-phase state files were written "
1863  "for long-running prepared transactions",
1864  serialized_xacts,
1865  serialized_xacts)));
1866 }
1867 
1868 /*
1869  * restoreTwoPhaseData
1870  *
1871  * Scan pg_twophase and fill TwoPhaseState depending on the on-disk data.
1872  * This is called once at the beginning of recovery, saving any extra
1873  * lookups in the future. Two-phase files that are newer than the
1874  * minimum XID horizon are discarded on the way.
1875  */
1876 void
1878 {
1879  DIR *cldir;
1880  struct dirent *clde;
1881 
1882  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1883  cldir = AllocateDir(TWOPHASE_DIR);
1884  while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1885  {
1886  if (strlen(clde->d_name) == 8 &&
1887  strspn(clde->d_name, "0123456789ABCDEF") == 8)
1888  {
1889  TransactionId xid;
1890  char *buf;
1891 
1892  xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1893 
1895  true, false, false);
1896  if (buf == NULL)
1897  continue;
1898 
1901  }
1902  }
1903  LWLockRelease(TwoPhaseStateLock);
1904  FreeDir(cldir);
1905 }
1906 
1907 /*
1908  * PrescanPreparedTransactions
1909  *
1910  * Scan the shared memory entries of TwoPhaseState and determine the range
1911  * of valid XIDs present. This is run during database startup, after we
1912  * have completed reading WAL. ShmemVariableCache->nextXid has been set to
1913  * one more than the highest XID for which evidence exists in WAL.
1914  *
1915  * We throw away any prepared xacts with main XID beyond nextXid --- if any
1916  * are present, it suggests that the DBA has done a PITR recovery to an
1917  * earlier point in time without cleaning out pg_twophase. We dare not
1918  * try to recover such prepared xacts since they likely depend on database
1919  * state that doesn't exist now.
1920  *
1921  * However, we will advance nextXid beyond any subxact XIDs belonging to
1922  * valid prepared xacts. We need to do this since subxact commit doesn't
1923  * write a WAL entry, and so there might be no evidence in WAL of those
1924  * subxact XIDs.
1925  *
1926  * On corrupted two-phase files, fail immediately. Keeping around broken
1927  * entries and let replay continue causes harm on the system, and a new
1928  * backup should be rolled in.
1929  *
1930  * Our other responsibility is to determine and return the oldest valid XID
1931  * among the prepared xacts (if none, return ShmemVariableCache->nextXid).
1932  * This is needed to synchronize pg_subtrans startup properly.
1933  *
1934  * If xids_p and nxids_p are not NULL, pointer to a palloc'd array of all
1935  * top-level xids is stored in *xids_p. The number of entries in the array
1936  * is returned in *nxids_p.
1937  */
1940 {
1942  TransactionId origNextXid = XidFromFullTransactionId(nextXid);
1943  TransactionId result = origNextXid;
1944  TransactionId *xids = NULL;
1945  int nxids = 0;
1946  int allocsize = 0;
1947  int i;
1948 
1949  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1950  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1951  {
1952  TransactionId xid;
1953  char *buf;
1955 
1956  Assert(gxact->inredo);
1957 
1958  xid = gxact->xid;
1959 
1960  buf = ProcessTwoPhaseBuffer(xid,
1961  gxact->prepare_start_lsn,
1962  gxact->ondisk, false, true);
1963 
1964  if (buf == NULL)
1965  continue;
1966 
1967  /*
1968  * OK, we think this file is valid. Incorporate xid into the
1969  * running-minimum result.
1970  */
1971  if (TransactionIdPrecedes(xid, result))
1972  result = xid;
1973 
1974  if (xids_p)
1975  {
1976  if (nxids == allocsize)
1977  {
1978  if (nxids == 0)
1979  {
1980  allocsize = 10;
1981  xids = palloc(allocsize * sizeof(TransactionId));
1982  }
1983  else
1984  {
1985  allocsize = allocsize * 2;
1986  xids = repalloc(xids, allocsize * sizeof(TransactionId));
1987  }
1988  }
1989  xids[nxids++] = xid;
1990  }
1991 
1992  pfree(buf);
1993  }
1994  LWLockRelease(TwoPhaseStateLock);
1995 
1996  if (xids_p)
1997  {
1998  *xids_p = xids;
1999  *nxids_p = nxids;
2000  }
2001 
2002  return result;
2003 }
2004 
2005 /*
2006  * StandbyRecoverPreparedTransactions
2007  *
2008  * Scan the shared memory entries of TwoPhaseState and setup all the required
2009  * information to allow standby queries to treat prepared transactions as still
2010  * active.
2011  *
2012  * This is never called at the end of recovery - we use
2013  * RecoverPreparedTransactions() at that point.
2014  *
2015  * The lack of calls to SubTransSetParent() calls here is by design;
2016  * those calls are made by RecoverPreparedTransactions() at the end of recovery
2017  * for those xacts that need this.
2018  */
2019 void
2021 {
2022  int i;
2023 
2024  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2025  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2026  {
2027  TransactionId xid;
2028  char *buf;
2030 
2031  Assert(gxact->inredo);
2032 
2033  xid = gxact->xid;
2034 
2035  buf = ProcessTwoPhaseBuffer(xid,
2036  gxact->prepare_start_lsn,
2037  gxact->ondisk, false, false);
2038  if (buf != NULL)
2039  pfree(buf);
2040  }
2041  LWLockRelease(TwoPhaseStateLock);
2042 }
2043 
2044 /*
2045  * RecoverPreparedTransactions
2046  *
2047  * Scan the shared memory entries of TwoPhaseState and reload the state for
2048  * each prepared transaction (reacquire locks, etc).
2049  *
2050  * This is run at the end of recovery, but before we allow backends to write
2051  * WAL.
2052  *
2053  * At the end of recovery the way we take snapshots will change. We now need
2054  * to mark all running transactions with their full SubTransSetParent() info
2055  * to allow normal snapshots to work correctly if snapshots overflow.
2056  * We do this here because by definition prepared transactions are the only
2057  * type of write transaction still running, so this is necessary and
2058  * complete.
2059  */
2060 void
2062 {
2063  int i;
2064 
2065  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2066  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2067  {
2068  TransactionId xid;
2069  char *buf;
2071  char *bufptr;
2072  TwoPhaseFileHeader *hdr;
2073  TransactionId *subxids;
2074  const char *gid;
2075 
2076  xid = gxact->xid;
2077 
2078  /*
2079  * Reconstruct subtrans state for the transaction --- needed because
2080  * pg_subtrans is not preserved over a restart. Note that we are
2081  * linking all the subtransactions directly to the top-level XID;
2082  * there may originally have been a more complex hierarchy, but
2083  * there's no need to restore that exactly. It's possible that
2084  * SubTransSetParent has been set before, if the prepared transaction
2085  * generated xid assignment records.
2086  */
2087  buf = ProcessTwoPhaseBuffer(xid,
2088  gxact->prepare_start_lsn,
2089  gxact->ondisk, true, false);
2090  if (buf == NULL)
2091  continue;
2092 
2093  ereport(LOG,
2094  (errmsg("recovering prepared transaction %u from shared memory", xid)));
2095 
2096  hdr = (TwoPhaseFileHeader *) buf;
2097  Assert(TransactionIdEquals(hdr->xid, xid));
2098  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2099  gid = (const char *) bufptr;
2100  bufptr += MAXALIGN(hdr->gidlen);
2101  subxids = (TransactionId *) bufptr;
2102  bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
2103  bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
2104  bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
2105  bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
2106  bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
2107  bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
2108 
2109  /*
2110  * Recreate its GXACT and dummy PGPROC. But, check whether it was
2111  * added in redo and already has a shmem entry for it.
2112  */
2113  MarkAsPreparingGuts(gxact, xid, gid,
2114  hdr->prepared_at,
2115  hdr->owner, hdr->database);
2116 
2117  /* recovered, so reset the flag for entries generated by redo */
2118  gxact->inredo = false;
2119 
2120  GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
2121  MarkAsPrepared(gxact, true);
2122 
2123  LWLockRelease(TwoPhaseStateLock);
2124 
2125  /*
2126  * Recover other state (notably locks) using resource managers.
2127  */
2129 
2130  /*
2131  * Release locks held by the standby process after we process each
2132  * prepared transaction. As a result, we don't need too many
2133  * additional locks at any one time.
2134  */
2135  if (InHotStandby)
2136  StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
2137 
2138  /*
2139  * We're done with recovering this transaction. Clear MyLockedGxact,
2140  * like we do in PrepareTransaction() during normal operation.
2141  */
2143 
2144  pfree(buf);
2145 
2146  LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
2147  }
2148 
2149  LWLockRelease(TwoPhaseStateLock);
2150 }
2151 
2152 /*
2153  * ProcessTwoPhaseBuffer
2154  *
2155  * Given a transaction id, read it either from disk or read it directly
2156  * via shmem xlog record pointer using the provided "prepare_start_lsn".
2157  *
2158  * If setParent is true, set up subtransaction parent linkages.
2159  *
2160  * If setNextXid is true, set ShmemVariableCache->nextXid to the newest
2161  * value scanned.
2162  */
2163 static char *
2165  XLogRecPtr prepare_start_lsn,
2166  bool fromdisk,
2167  bool setParent, bool setNextXid)
2168 {
2170  TransactionId origNextXid = XidFromFullTransactionId(nextXid);
2171  TransactionId *subxids;
2172  char *buf;
2173  TwoPhaseFileHeader *hdr;
2174  int i;
2175 
2176  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2177 
2178  if (!fromdisk)
2179  Assert(prepare_start_lsn != InvalidXLogRecPtr);
2180 
2181  /* Already processed? */
2183  {
2184  if (fromdisk)
2185  {
2186  ereport(WARNING,
2187  (errmsg("removing stale two-phase state file for transaction %u",
2188  xid)));
2189  RemoveTwoPhaseFile(xid, true);
2190  }
2191  else
2192  {
2193  ereport(WARNING,
2194  (errmsg("removing stale two-phase state from memory for transaction %u",
2195  xid)));
2196  PrepareRedoRemove(xid, true);
2197  }
2198  return NULL;
2199  }
2200 
2201  /* Reject XID if too new */
2202  if (TransactionIdFollowsOrEquals(xid, origNextXid))
2203  {
2204  if (fromdisk)
2205  {
2206  ereport(WARNING,
2207  (errmsg("removing future two-phase state file for transaction %u",
2208  xid)));
2209  RemoveTwoPhaseFile(xid, true);
2210  }
2211  else
2212  {
2213  ereport(WARNING,
2214  (errmsg("removing future two-phase state from memory for transaction %u",
2215  xid)));
2216  PrepareRedoRemove(xid, true);
2217  }
2218  return NULL;
2219  }
2220 
2221  if (fromdisk)
2222  {
2223  /* Read and validate file */
2224  buf = ReadTwoPhaseFile(xid, false);
2225  }
2226  else
2227  {
2228  /* Read xlog data */
2229  XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2230  }
2231 
2232  /* Deconstruct header */
2233  hdr = (TwoPhaseFileHeader *) buf;
2234  if (!TransactionIdEquals(hdr->xid, xid))
2235  {
2236  if (fromdisk)
2237  ereport(ERROR,
2239  errmsg("corrupted two-phase state file for transaction %u",
2240  xid)));
2241  else
2242  ereport(ERROR,
2244  errmsg("corrupted two-phase state in memory for transaction %u",
2245  xid)));
2246  }
2247 
2248  /*
2249  * Examine subtransaction XIDs ... they should all follow main XID, and
2250  * they may force us to advance nextXid.
2251  */
2252  subxids = (TransactionId *) (buf +
2253  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2254  MAXALIGN(hdr->gidlen));
2255  for (i = 0; i < hdr->nsubxacts; i++)
2256  {
2257  TransactionId subxid = subxids[i];
2258 
2259  Assert(TransactionIdFollows(subxid, xid));
2260 
2261  /* update nextXid if needed */
2262  if (setNextXid)
2264 
2265  if (setParent)
2266  SubTransSetParent(subxid, xid);
2267  }
2268 
2269  return buf;
2270 }
2271 
2272 
2273 /*
2274  * RecordTransactionCommitPrepared
2275  *
2276  * This is basically the same as RecordTransactionCommit (q.v. if you change
2277  * this function): in particular, we must set DELAY_CHKPT_START to avoid a
2278  * race condition.
2279  *
2280  * We know the transaction made at least one XLOG entry (its PREPARE),
2281  * so it is never possible to optimize out the commit record.
2282  */
2283 static void
2285  int nchildren,
2286  TransactionId *children,
2287  int nrels,
2288  RelFileNode *rels,
2289  int nstats,
2290  xl_xact_stats_item *stats,
2291  int ninvalmsgs,
2292  SharedInvalidationMessage *invalmsgs,
2293  bool initfileinval,
2294  const char *gid)
2295 {
2296  XLogRecPtr recptr;
2297  TimestampTz committs = GetCurrentTimestamp();
2298  bool replorigin;
2299 
2300  /*
2301  * Are we using the replication origins feature? Or, in other words, are
2302  * we replaying remote actions?
2303  */
2304  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2306 
2308 
2309  /* See notes in RecordTransactionCommit */
2312 
2313  /*
2314  * Emit the XLOG commit record. Note that we mark 2PC commits as
2315  * potentially having AccessExclusiveLocks since we don't know whether or
2316  * not they do.
2317  */
2318  recptr = XactLogCommitRecord(committs,
2319  nchildren, children, nrels, rels,
2320  nstats, stats,
2321  ninvalmsgs, invalmsgs,
2322  initfileinval,
2324  xid, gid);
2325 
2326 
2327  if (replorigin)
2328  /* Move LSNs forward for this replication origin */
2330  XactLastRecEnd);
2331 
2332  /*
2333  * Record commit timestamp. The value comes from plain commit timestamp
2334  * if replorigin is not enabled, or replorigin already set a value for us
2335  * in replorigin_session_origin_timestamp otherwise.
2336  *
2337  * We don't need to WAL-log anything here, as the commit record written
2338  * above already contains the data.
2339  */
2340  if (!replorigin || replorigin_session_origin_timestamp == 0)
2342 
2343  TransactionTreeSetCommitTsData(xid, nchildren, children,
2346 
2347  /*
2348  * We don't currently try to sleep before flush here ... nor is there any
2349  * support for async commit of a prepared xact (the very idea is probably
2350  * a contradiction)
2351  */
2352 
2353  /* Flush XLOG to disk */
2354  XLogFlush(recptr);
2355 
2356  /* Mark the transaction committed in pg_xact */
2357  TransactionIdCommitTree(xid, nchildren, children);
2358 
2359  /* Checkpoint can proceed now */
2361 
2362  END_CRIT_SECTION();
2363 
2364  /*
2365  * Wait for synchronous replication, if required.
2366  *
2367  * Note that at this stage we have marked clog, but still show as running
2368  * in the procarray and continue to hold locks.
2369  */
2370  SyncRepWaitForLSN(recptr, true);
2371 }
2372 
2373 /*
2374  * RecordTransactionAbortPrepared
2375  *
2376  * This is basically the same as RecordTransactionAbort.
2377  *
2378  * We know the transaction made at least one XLOG entry (its PREPARE),
2379  * so it is never possible to optimize out the abort record.
2380  */
2381 static void
2383  int nchildren,
2384  TransactionId *children,
2385  int nrels,
2386  RelFileNode *rels,
2387  int nstats,
2388  xl_xact_stats_item *stats,
2389  const char *gid)
2390 {
2391  XLogRecPtr recptr;
2392  bool replorigin;
2393 
2394  /*
2395  * Are we using the replication origins feature? Or, in other words, are
2396  * we replaying remote actions?
2397  */
2398  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2400 
2401  /*
2402  * Catch the scenario where we aborted partway through
2403  * RecordTransactionCommitPrepared ...
2404  */
2405  if (TransactionIdDidCommit(xid))
2406  elog(PANIC, "cannot abort transaction %u, it was already committed",
2407  xid);
2408 
2410 
2411  /*
2412  * Emit the XLOG commit record. Note that we mark 2PC aborts as
2413  * potentially having AccessExclusiveLocks since we don't know whether or
2414  * not they do.
2415  */
2417  nchildren, children,
2418  nrels, rels,
2419  nstats, stats,
2421  xid, gid);
2422 
2423  if (replorigin)
2424  /* Move LSNs forward for this replication origin */
2426  XactLastRecEnd);
2427 
2428  /* Always flush, since we're about to remove the 2PC state file */
2429  XLogFlush(recptr);
2430 
2431  /*
2432  * Mark the transaction aborted in clog. This is not absolutely necessary
2433  * but we may as well do it while we are here.
2434  */
2435  TransactionIdAbortTree(xid, nchildren, children);
2436 
2437  END_CRIT_SECTION();
2438 
2439  /*
2440  * Wait for synchronous replication, if required.
2441  *
2442  * Note that at this stage we have marked clog, but still show as running
2443  * in the procarray and continue to hold locks.
2444  */
2445  SyncRepWaitForLSN(recptr, false);
2446 }
2447 
2448 /*
2449  * PrepareRedoAdd
2450  *
2451  * Store pointers to the start/end of the WAL record along with the xid in
2452  * a gxact entry in shared memory TwoPhaseState structure. If caller
2453  * specifies InvalidXLogRecPtr as WAL location to fetch the two-phase
2454  * data, the entry is marked as located on disk.
2455  */
2456 void
2457 PrepareRedoAdd(char *buf, XLogRecPtr start_lsn,
2458  XLogRecPtr end_lsn, RepOriginId origin_id)
2459 {
2461  char *bufptr;
2462  const char *gid;
2463  GlobalTransaction gxact;
2464 
2465  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2467 
2468  bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2469  gid = (const char *) bufptr;
2470 
2471  /*
2472  * Reserve the GID for the given transaction in the redo code path.
2473  *
2474  * This creates a gxact struct and puts it into the active array.
2475  *
2476  * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2477  * shared memory. Hence, we only fill up the bare minimum contents here.
2478  * The gxact also gets marked with gxact->inredo set to true to indicate
2479  * that it got added in the redo phase
2480  */
2481 
2482  /* Get a free gxact from the freelist */
2483  if (TwoPhaseState->freeGXacts == NULL)
2484  ereport(ERROR,
2485  (errcode(ERRCODE_OUT_OF_MEMORY),
2486  errmsg("maximum number of prepared transactions reached"),
2487  errhint("Increase max_prepared_transactions (currently %d).",
2488  max_prepared_xacts)));
2489  gxact = TwoPhaseState->freeGXacts;
2490  TwoPhaseState->freeGXacts = gxact->next;
2491 
2492  gxact->prepared_at = hdr->prepared_at;
2493  gxact->prepare_start_lsn = start_lsn;
2494  gxact->prepare_end_lsn = end_lsn;
2495  gxact->xid = hdr->xid;
2496  gxact->owner = hdr->owner;
2498  gxact->valid = false;
2499  gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2500  gxact->inredo = true; /* yes, added in redo */
2501  strcpy(gxact->gid, gid);
2502 
2503  /* And insert it into the active array */
2506 
2507  if (origin_id != InvalidRepOriginId)
2508  {
2509  /* recover apply progress */
2510  replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
2511  false /* backward */ , false /* WAL */ );
2512  }
2513 
2514  elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2515 }
2516 
2517 /*
2518  * PrepareRedoRemove
2519  *
2520  * Remove the corresponding gxact entry from TwoPhaseState. Also remove
2521  * the 2PC file if a prepared transaction was saved via an earlier checkpoint.
2522  *
2523  * Caller must hold TwoPhaseStateLock in exclusive mode, because TwoPhaseState
2524  * is updated.
2525  */
2526 void
2527 PrepareRedoRemove(TransactionId xid, bool giveWarning)
2528 {
2529  GlobalTransaction gxact = NULL;
2530  int i;
2531  bool found = false;
2532 
2533  Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2535 
2536  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2537  {
2538  gxact = TwoPhaseState->prepXacts[i];
2539 
2540  if (gxact->xid == xid)
2541  {
2542  Assert(gxact->inredo);
2543  found = true;
2544  break;
2545  }
2546  }
2547 
2548  /*
2549  * Just leave if there is nothing, this is expected during WAL replay.
2550  */
2551  if (!found)
2552  return;
2553 
2554  /*
2555  * And now we can clean up any files we may have left.
2556  */
2557  elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2558  if (gxact->ondisk)
2559  RemoveTwoPhaseFile(xid, giveWarning);
2560  RemoveGXact(gxact);
2561 }
2562 
2563 /*
2564  * LookupGXact
2565  * Check if the prepared transaction with the given GID, lsn and timestamp
2566  * exists.
2567  *
2568  * Note that we always compare with the LSN where prepare ends because that is
2569  * what is stored as origin_lsn in the 2PC file.
2570  *
2571  * This function is primarily used to check if the prepared transaction
2572  * received from the upstream (remote node) already exists. Checking only GID
2573  * is not sufficient because a different prepared xact with the same GID can
2574  * exist on the same node. So, we are ensuring to match origin_lsn and
2575  * origin_timestamp of prepared xact to avoid the possibility of a match of
2576  * prepared xact from two different nodes.
2577  */
2578 bool
2579 LookupGXact(const char *gid, XLogRecPtr prepare_end_lsn,
2580  TimestampTz origin_prepare_timestamp)
2581 {
2582  int i;
2583  bool found = false;
2584 
2585  LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
2586  for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2587  {
2589 
2590  /* Ignore not-yet-valid GIDs. */
2591  if (gxact->valid && strcmp(gxact->gid, gid) == 0)
2592  {
2593  char *buf;
2594  TwoPhaseFileHeader *hdr;
2595 
2596  /*
2597  * We are not expecting collisions of GXACTs (same gid) between
2598  * publisher and subscribers, so we perform all I/O while holding
2599  * TwoPhaseStateLock for simplicity.
2600  *
2601  * To move the I/O out of the lock, we need to ensure that no
2602  * other backend commits the prepared xact in the meantime. We can
2603  * do this optimization if we encounter many collisions in GID
2604  * between publisher and subscriber.
2605  */
2606  if (gxact->ondisk)
2607  buf = ReadTwoPhaseFile(gxact->xid, false);
2608  else
2609  {
2610  Assert(gxact->prepare_start_lsn);
2611  XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
2612  }
2613 
2614  hdr = (TwoPhaseFileHeader *) buf;
2615 
2616  if (hdr->origin_lsn == prepare_end_lsn &&
2617  hdr->origin_timestamp == origin_prepare_timestamp)
2618  {
2619  found = true;
2620  pfree(buf);
2621  break;
2622  }
2623 
2624  pfree(buf);
2625  }
2626  }
2627  LWLockRelease(TwoPhaseStateLock);
2628  return found;
2629 }
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:415
int16 AttrNumber
Definition: attnum.h:21
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
int BackendId
Definition: backendid.h:21
#define InvalidBackendId
Definition: backendid.h:23
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:85
unsigned short uint16
Definition: c.h:440
unsigned int uint32
Definition: c.h:441
#define MAXALIGN(LEN)
Definition: c.h:757
#define offsetof(type, field)
Definition: c.h:727
#define Max(x, y)
Definition: c.h:980
#define PG_BINARY
Definition: c.h:1268
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:350
#define MemSet(start, val, len)
Definition: c.h:1008
uint32 TransactionId
Definition: c.h:587
size_t Size
Definition: c.h:540
void TransactionTreeSetCommitTsData(TransactionId xid, int nsubxids, TransactionId *subxids, TimestampTz timestamp, RepOriginId nodeid)
Definition: commit_ts.c:137
int64 TimestampTz
Definition: timestamp.h:39
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1014
int errcode_for_file_access(void)
Definition: elog.c:716
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define LOG
Definition: elog.h:25
#define WARNING
Definition: elog.h:30
#define DEBUG2
Definition: elog.h:23
#define PANIC
Definition: elog.h:36
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2071
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2788
int FreeDir(DIR *dir)
Definition: fd.c:2840
int CloseTransientFile(int fd)
Definition: fd.c:2688
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:673
int pg_fsync(int fd)
Definition: fd.c:359
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2511
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2722
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:299
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:303
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:220
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:305
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:301
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:323
bool IsUnderPostmaster
Definition: globals.c:113
BackendId MyBackendId
Definition: globals.c:85
int MaxBackends
Definition: globals.c:140
bool IsPostmasterEnvironment
Definition: globals.c:112
Oid MyDatabaseId
Definition: globals.c:89
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define write(a, b, c)
Definition: win32.h:14
#define read(a, b, c)
Definition: win32.h:13
int xactGetCommittedInvalidationMessages(SharedInvalidationMessage **msgs, bool *RelcacheInitFileInval)
Definition: inval.c:884
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
#define VirtualTransactionIdIsValid(vxid)
Definition: lock.h:72
#define LocalTransactionIdIsValid(lxid)
Definition: lock.h:71
#define VirtualTransactionIdEquals(vxid1, vxid2)
Definition: lock.h:76
#define GET_VXID_FROM_PGPROC(vxid, proc)
Definition: lock.h:82
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1196
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1800
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1934
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1916
#define NUM_LOCK_PARTITIONS
Definition: lwlock.h:87
@ LW_SHARED
Definition: lwlock.h:105
@ LW_EXCLUSIVE
Definition: lwlock.h:104
void pfree(void *pointer)
Definition: mcxt.c:1175
void * palloc0(Size size)
Definition: mcxt.c:1099
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1188
void * palloc(Size size)
Definition: mcxt.c:1068
void DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
Definition: md.c:1057
#define MaxAllocSize
Definition: memutils.h:40
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:134
#define AmStartupProcess()
Definition: miscadmin.h:444
#define START_CRIT_SECTION()
Definition: miscadmin.h:148
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:132
#define END_CRIT_SECTION()
Definition: miscadmin.h:150
Oid GetUserId(void)
Definition: miscinit.c:492
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:157
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1188
RepOriginId replorigin_session_origin
Definition: origin.c:155
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:872
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:156
#define DoNotReplicateId
Definition: origin.h:34
#define InvalidRepOriginId
Definition: origin.h:33
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void * arg
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:43
#define MAXPGPATH
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
const void size_t len
const void * data
while(p+4<=pend)
static char * user
Definition: pg_regress.c:95
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
static char * buf
Definition: pg_test_fsync.c:67
void pgstat_execute_transactional_drops(int ndrops, struct xl_xact_stats_item *items, bool is_redo)
Definition: pgstat_xact.c:320
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat_xact.c:41
int pgstat_get_transactional_drops(bool isCommit, xl_xact_stats_item **items)
Definition: pgstat_xact.c:278
#define TransactionIdGetDatum(X)
Definition: postgres.h:565
uintptr_t Datum
Definition: postgres.h:411
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void PredicateLockTwoPhaseFinish(TransactionId xid, bool isCommit)
Definition: predicate.c:5026
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:36
#define DELAY_CHKPT_START
Definition: proc.h:117
@ PROC_WAIT_STATUS_OK
Definition: proc.h:122
void ProcArrayAdd(PGPROC *proc)
Definition: procarray.c:455
void ProcArrayRemove(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:551
void RelationCacheInitFilePostInvalidate(void)
Definition: relcache.c:6646
void RelationCacheInitFilePreInvalidate(void)
Definition: relcache.c:6621
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
void SHMQueueInit(SHM_QUEUE *queue)
Definition: shmqueue.c:36
void SHMQueueElemInit(SHM_QUEUE *queue)
Definition: shmqueue.c:57
void SendSharedInvalidMessages(const SharedInvalidationMessage *msgs, int n)
Definition: sinval.c:49
PGPROC * MyProc
Definition: proc.c:68
PGPROC * PreparedXactProcs
Definition: proc.c:82
PROC_HDR * ProcGlobal
Definition: proc.c:80
void StandbyReleaseLockTree(TransactionId xid, int nsubxids, TransactionId *subxids)
Definition: standby.c:1037
int smgrGetPendingDeletes(bool forCommit, RelFileNode **ptr)
Definition: storage.c:869
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Definition: dirent.c:26
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
TupleDesc tuple_desc
Definition: funcapi.h:112
TimestampTz prepared_at
Definition: twophase.c:154
BackendId dummyBackendId
Definition: twophase.c:153
TransactionId xid
Definition: twophase.c:165
XLogRecPtr prepare_start_lsn
Definition: twophase.c:163
XLogRecPtr prepare_end_lsn
Definition: twophase.c:164
GlobalTransaction next
Definition: twophase.c:151
BackendId locking_backend
Definition: twophase.c:168
char gid[GIDSIZE]
Definition: twophase.c:172
Definition: proc.h:160
TransactionId xmin
Definition: proc.h:176
LocalTransactionId lxid
Definition: proc.h:181
PROCLOCK * waitProcLock
Definition: proc.h:218
SHM_QUEUE links
Definition: proc.h:162
uint8 lwWaitMode
Definition: proc.h:209
uint8 statusFlags
Definition: proc.h:227
Oid databaseId
Definition: proc.h:192
pg_atomic_uint64 waitStart
Definition: proc.h:222
BackendId backendId
Definition: proc.h:191
int pid
Definition: proc.h:184
bool isBackgroundWorker
Definition: proc.h:198
XidCacheStatus subxidStatus
Definition: proc.h:248
LOCK * waitLock
Definition: proc.h:217
TransactionId xid
Definition: proc.h:171
int pgprocno
Definition: proc.h:188
struct XidCache subxids
Definition: proc.h:250
bool lwWaiting
Definition: proc.h:208
int delayChkptFlags
Definition: proc.h:225
Oid roleId
Definition: proc.h:193
ProcWaitStatus waitStatus
Definition: proc.h:166
Oid tempNamespaceId
Definition: proc.h:195
SHM_QUEUE myProcLocks[NUM_LOCK_PARTITIONS]
Definition: proc.h:246
PGPROC * allProcs
Definition: proc.h:356
struct StateFileChunk * next
Definition: twophase.c:994
uint32 len
Definition: twophase.c:993
char * data
Definition: twophase.c:992
TwoPhaseRmgrId rmid
Definition: twophase.c:981
GlobalTransaction freeGXacts
Definition: twophase.c:182
GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER]
Definition: twophase.c:188
FullTransactionId nextXid
Definition: transam.h:220
GlobalTransaction array
Definition: twophase.c:716
bool overflowed
Definition: proc.h:43
uint8 count
Definition: proc.h:41
TransactionId xids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: proc.h:48
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
__int64 st_size
Definition: win32_port.h:273
TimestampTz prepared_at
Definition: xact.h:339
int32 nabortrels
Definition: xact.h:343
int32 ninvalmsgs
Definition: xact.h:346
bool initfileinval
Definition: xact.h:347
int32 ncommitstats
Definition: xact.h:344
TimestampTz origin_timestamp
Definition: xact.h:350
uint16 gidlen
Definition: xact.h:348
uint32 total_len
Definition: xact.h:336
int32 nabortstats
Definition: xact.h:345
Oid database
Definition: xact.h:338
XLogRecPtr origin_lsn
Definition: xact.h:349
uint32 magic
Definition: xact.h:335
int32 ncommitrels
Definition: xact.h:342
TransactionId xid
Definition: xact.h:337
int32 nsubxacts
Definition: xact.h:341
uint32 total_len
Definition: twophase.c:1003
uint32 num_chunks
Definition: twophase.c:1001
StateFileChunk * head
Definition: twophase.c:999
StateFileChunk * tail
Definition: twophase.c:1000
uint32 bytes_free
Definition: twophase.c:1002
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition: subtrans.c:74
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
void SyncRepWaitForLSN(XLogRecPtr lsn, bool commit)
Definition: syncrep.c:148
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:365
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:125
void TransactionIdCommitTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:260
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:290
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
bool TransactionIdDidAbort(TransactionId transactionId)
Definition: transam.c:181
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:349
#define InvalidTransactionId
Definition: transam.h:31
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
#define XidFromFullTransactionId(x)
Definition: transam.h:48
#define TransactionIdIsValid(xid)
Definition: transam.h:41
TupleDesc CreateTemplateTupleDesc(int natts)
Definition: tupdesc.c:45
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition: tupdesc.c:583
static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
Definition: twophase.c:1399
static void RecordTransactionCommitPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, int nstats, xl_xact_stats_item *stats, int ninvalmsgs, SharedInvalidationMessage *invalmsgs, bool initfileinval, const char *gid)
Definition: twophase.c:2284
void RecoverPreparedTransactions(void)
Definition: twophase.c:2061
static bool twophaseExitRegistered
Definition: twophase.c:201
void restoreTwoPhaseData(void)
Definition: twophase.c:1877
bool LookupGXact(const char *gid, XLogRecPtr prepare_end_lsn, TimestampTz origin_prepare_timestamp)
Definition: twophase.c:2579
Size TwoPhaseShmemSize(void)
Definition: twophase.c:240
#define TWOPHASE_DIR
Definition: twophase.c:114
void RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info, const void *data, uint32 len)
Definition: twophase.c:1259
int max_prepared_xacts
Definition: twophase.c:117
static void RemoveGXact(GlobalTransaction gxact)
Definition: twophase.c:646
struct TwoPhaseStateData TwoPhaseStateData
static GlobalTransaction MyLockedGxact
Definition: twophase.c:199
static TwoPhaseStateData * TwoPhaseState
Definition: twophase.c:191
static void ProcessRecords(char *bufptr, TransactionId xid, const TwoPhaseCallback callbacks[])
Definition: twophase.c:1668
void AtAbort_Twophase(void)
Definition: twophase.c:321
BackendId TwoPhaseGetDummyBackendId(TransactionId xid, bool lock_held)
Definition: twophase.c:920
static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:450
struct GlobalTransactionData GlobalTransactionData
static void save_state_data(const void *data, uint32 len)
Definition: twophase.c:1016
static void RecordTransactionAbortPrepared(TransactionId xid, int nchildren, TransactionId *children, int nrels, RelFileNode *rels, int nstats, xl_xact_stats_item *stats, const char *gid)
Definition: twophase.c:2382
#define TWOPHASE_MAGIC
Definition: twophase.c:968
void FinishPreparedTransaction(const char *gid, bool isCommit)
Definition: twophase.c:1482
#define TwoPhaseFilePath(path, xid)
Definition: twophase.c:946
struct TwoPhaseRecordOnDisk TwoPhaseRecordOnDisk
TransactionId TwoPhaseGetXidByVirtualXID(VirtualTransactionId vxid, bool *have_more)
Definition: twophase.c:872
static void GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts, TransactionId *children)
Definition: twophase.c:522
void PrepareRedoRemove(TransactionId xid, bool giveWarning)
Definition: twophase.c:2527
Datum pg_prepared_xact(PG_FUNCTION_ARGS)
Definition: twophase.c:729
void EndPrepare(GlobalTransaction gxact)
Definition: twophase.c:1137
static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
Definition: twophase.c:1696
TransactionId PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
Definition: twophase.c:1939
static char * ReadTwoPhaseFile(TransactionId xid, bool missing_ok)
Definition: twophase.c:1282
void StartPrepare(GlobalTransaction gxact)
Definition: twophase.c:1044
static int GetPreparedTransactionList(GlobalTransaction *gxacts)
Definition: twophase.c:684
PGPROC * TwoPhaseGetDummyProc(TransactionId xid, bool lock_held)
Definition: twophase.c:935
void TwoPhaseShmemInit(void)
Definition: twophase.c:256
void PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn, RepOriginId origin_id)
Definition: twophase.c:2457
static GlobalTransaction TwoPhaseGetGXact(TransactionId xid, bool lock_held)
Definition: twophase.c:820
void StandbyRecoverPreparedTransactions(void)
Definition: twophase.c:2020
static void AtProcExit_Twophase(int code, Datum arg)
Definition: twophase.c:311
static char * ProcessTwoPhaseBuffer(TransactionId xid, XLogRecPtr prepare_start_lsn, bool fromdisk, bool setParent, bool setNextXid)
Definition: twophase.c:2164
static void MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
Definition: twophase.c:548
void PostPrepare_Twophase(void)
Definition: twophase.c:361
xl_xact_prepare TwoPhaseFileHeader
Definition: twophase.c:970
void CheckPointTwoPhase(XLogRecPtr redo_horizon)
Definition: twophase.c:1795
struct StateFileChunk StateFileChunk
bool StandbyTransactionIdIsPrepared(TransactionId xid)
Definition: twophase.c:1454
static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
Definition: twophase.c:1715
GlobalTransaction MarkAsPreparing(TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:376
static GlobalTransaction LockGXact(const char *gid, Oid user)
Definition: twophase.c:570
static struct xllist records
struct GlobalTransactionData * GlobalTransaction
Definition: twophase.h:26
const TwoPhaseCallback twophase_postcommit_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:33
const TwoPhaseCallback twophase_recover_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:24
const TwoPhaseCallback twophase_postabort_callbacks[TWOPHASE_RM_MAX_ID+1]
Definition: twophase_rmgr.c:42
#define TWOPHASE_RM_MAX_ID
Definition: twophase_rmgr.h:29
uint8 TwoPhaseRmgrId
Definition: twophase_rmgr.h:19
#define TWOPHASE_RM_END_ID
Definition: twophase_rmgr.h:24
void(* TwoPhaseCallback)(TransactionId xid, uint16 info, void *recdata, uint32 len)
Definition: twophase_rmgr.h:17
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
void AdvanceNextFullTransactionIdPastXid(TransactionId xid)
Definition: varsup.c:277
VariableCache ShmemVariableCache
Definition: varsup.c:34
@ WAIT_EVENT_TWOPHASE_FILE_READ
Definition: wait_event.h:217
@ WAIT_EVENT_TWOPHASE_FILE_WRITE
Definition: wait_event.h:219
@ WAIT_EVENT_TWOPHASE_FILE_SYNC
Definition: wait_event.h:218
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:266
static void pgstat_report_wait_end(void)
Definition: wait_event.h:282
#define fstat
Definition: win32_port.h:282
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5563
XLogRecPtr XactLogCommitRecord(TimestampTz commit_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileNode *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, int nmsgs, SharedInvalidationMessage *msgs, bool relcacheInval, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition: xact.c:5587
XLogRecPtr XactLogAbortRecord(TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileNode *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition: xact.c:5759
int MyXactFlags
Definition: xact.c:135
#define XLOG_XACT_PREPARE
Definition: xact.h:157
#define XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK
Definition: xact.h:108
#define XLOG_XACT_OPMASK
Definition: xact.h:166
#define GIDSIZE
Definition: xact.h:31
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:250
bool RecoveryInProgress(void)
Definition: xlog.c:5753
XLogRecPtr XactLastRecEnd
Definition: xlog.c:251
int wal_segment_size
Definition: xlog.c:144
bool log_checkpoints
Definition: xlog.c:130
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2509
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:149
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint16 RepOriginId
Definition: xlogdefs.h:65
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:443
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:425
void XLogBeginInsert(void)
Definition: xloginsert.c:150
void XLogEnsureRecordSpace(int max_block_id, int ndatas)
Definition: xloginsert.c:176
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:351
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:418
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:170
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
Definition: xlogreader.c:108
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:264
#define XLogRecGetDataLen(decoder)
Definition: xlogreader.h:414
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:408
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:409
#define XLogRecGetData(decoder)
Definition: xlogreader.h:413
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
static XLogReaderState * xlogreader
Definition: xlogrecovery.c:185
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:856
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:831
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:875
#define InHotStandby
Definition: xlogutils.h:57