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