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