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