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