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