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