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