Line data Source code
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 */
117 : int max_prepared_xacts = 0;
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 */
177 : } GlobalTransactionData;
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 */
186 : GlobalTransaction freeGXacts;
187 :
188 : /* Number of valid prepXacts entries. */
189 : int numPrepXacts;
190 :
191 : /* There are max_prepared_xacts items in this array */
192 : GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER];
193 : } TwoPhaseStateData;
194 :
195 : static TwoPhaseStateData *TwoPhaseState;
196 :
197 : /*
198 : * Global transaction entry currently locked by us, if any. Note that any
199 : * access to the entry pointed to by this variable must be protected by
200 : * TwoPhaseStateLock, though obviously the pointer itself doesn't need to be
201 : * (since it's just local memory).
202 : */
203 : static GlobalTransaction MyLockedGxact = NULL;
204 :
205 : static bool twophaseExitRegistered = false;
206 :
207 : static void RecordTransactionCommitPrepared(TransactionId xid,
208 : int nchildren,
209 : TransactionId *children,
210 : int nrels,
211 : RelFileNode *rels,
212 : int ninvalmsgs,
213 : SharedInvalidationMessage *invalmsgs,
214 : bool initfileinval);
215 : static void RecordTransactionAbortPrepared(TransactionId xid,
216 : int nchildren,
217 : TransactionId *children,
218 : int nrels,
219 : RelFileNode *rels);
220 : static void ProcessRecords(char *bufptr, TransactionId xid,
221 : const TwoPhaseCallback callbacks[]);
222 : static void RemoveGXact(GlobalTransaction gxact);
223 :
224 : static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len);
225 : static char *ProcessTwoPhaseBuffer(TransactionId xid,
226 : XLogRecPtr prepare_start_lsn,
227 : bool fromdisk, bool setParent, bool setNextXid);
228 : static void MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid,
229 : const char *gid, TimestampTz prepared_at, Oid owner,
230 : Oid databaseid);
231 : static void RemoveTwoPhaseFile(TransactionId xid, bool giveWarning);
232 : static void RecreateTwoPhaseFile(TransactionId xid, void *content, int len);
233 :
234 : /*
235 : * Initialization of shared memory
236 : */
237 : Size
238 10 : TwoPhaseShmemSize(void)
239 : {
240 : Size size;
241 :
242 : /* Need the fixed struct, the array of pointers, and the GTD structs */
243 10 : size = offsetof(TwoPhaseStateData, prepXacts);
244 10 : size = add_size(size, mul_size(max_prepared_xacts,
245 : sizeof(GlobalTransaction)));
246 10 : size = MAXALIGN(size);
247 10 : size = add_size(size, mul_size(max_prepared_xacts,
248 : sizeof(GlobalTransactionData)));
249 :
250 10 : return size;
251 : }
252 :
253 : void
254 5 : TwoPhaseShmemInit(void)
255 : {
256 : bool found;
257 :
258 5 : TwoPhaseState = ShmemInitStruct("Prepared Transaction Table",
259 : TwoPhaseShmemSize(),
260 : &found);
261 5 : if (!IsUnderPostmaster)
262 : {
263 : GlobalTransaction gxacts;
264 : int i;
265 :
266 5 : Assert(!found);
267 5 : TwoPhaseState->freeGXacts = NULL;
268 5 : TwoPhaseState->numPrepXacts = 0;
269 :
270 : /*
271 : * Initialize the linked list of free GlobalTransactionData structs
272 : */
273 5 : gxacts = (GlobalTransaction)
274 5 : ((char *) TwoPhaseState +
275 5 : MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
276 : sizeof(GlobalTransaction) * max_prepared_xacts));
277 7 : for (i = 0; i < max_prepared_xacts; i++)
278 : {
279 : /* insert into linked list */
280 2 : gxacts[i].next = TwoPhaseState->freeGXacts;
281 2 : TwoPhaseState->freeGXacts = &gxacts[i];
282 :
283 : /* associate it with a PGPROC assigned by InitProcGlobal */
284 2 : gxacts[i].pgprocno = PreparedXactProcs[i].pgprocno;
285 :
286 : /*
287 : * Assign a unique ID for each dummy proc, so that the range of
288 : * dummy backend IDs immediately follows the range of normal
289 : * backend IDs. We don't dare to assign a real backend ID to dummy
290 : * procs, because prepared transactions don't take part in cache
291 : * invalidation like a real backend ID would imply, but having a
292 : * unique ID for them is nevertheless handy. This arrangement
293 : * allows you to allocate an array of size (MaxBackends +
294 : * max_prepared_xacts + 1), and have a slot for every backend and
295 : * prepared transaction. Currently multixact.c uses that
296 : * technique.
297 : */
298 2 : gxacts[i].dummyBackendId = MaxBackends + 1 + i;
299 : }
300 : }
301 : else
302 0 : Assert(found);
303 5 : }
304 :
305 : /*
306 : * Exit hook to unlock the global transaction entry we're working on.
307 : */
308 : static void
309 2 : AtProcExit_Twophase(int code, Datum arg)
310 : {
311 : /* same logic as abort */
312 2 : AtAbort_Twophase();
313 2 : }
314 :
315 : /*
316 : * Abort hook to unlock the global transaction entry we're working on.
317 : */
318 : void
319 3280 : AtAbort_Twophase(void)
320 : {
321 3280 : if (MyLockedGxact == NULL)
322 6560 : return;
323 :
324 : /*
325 : * What to do with the locked global transaction entry? If we were in the
326 : * process of preparing the transaction, but haven't written the WAL
327 : * record and state file yet, the transaction must not be considered as
328 : * prepared. Likewise, if we are in the process of finishing an
329 : * already-prepared transaction, and fail after having already written the
330 : * 2nd phase commit or rollback record to the WAL, the transaction should
331 : * not be considered as prepared anymore. In those cases, just remove the
332 : * entry from shared memory.
333 : *
334 : * Otherwise, the entry must be left in place so that the transaction can
335 : * be finished later, so just unlock it.
336 : *
337 : * If we abort during prepare, after having written the WAL record, we
338 : * might not have transferred all locks and other state to the prepared
339 : * transaction yet. Likewise, if we abort during commit or rollback,
340 : * after having written the WAL record, we might not have released all the
341 : * resources held by the transaction yet. In those cases, the in-memory
342 : * state can be wrong, but it's too late to back out.
343 : */
344 0 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
345 0 : if (!MyLockedGxact->valid)
346 0 : RemoveGXact(MyLockedGxact);
347 : else
348 0 : MyLockedGxact->locking_backend = InvalidBackendId;
349 0 : LWLockRelease(TwoPhaseStateLock);
350 :
351 0 : MyLockedGxact = NULL;
352 : }
353 :
354 : /*
355 : * This is called after we have finished transferring state to the prepared
356 : * PGXACT entry.
357 : */
358 : void
359 6 : PostPrepare_Twophase(void)
360 : {
361 6 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
362 6 : MyLockedGxact->locking_backend = InvalidBackendId;
363 6 : LWLockRelease(TwoPhaseStateLock);
364 :
365 6 : MyLockedGxact = NULL;
366 6 : }
367 :
368 :
369 : /*
370 : * MarkAsPreparing
371 : * Reserve the GID for the given transaction.
372 : */
373 : GlobalTransaction
374 7 : MarkAsPreparing(TransactionId xid, const char *gid,
375 : TimestampTz prepared_at, Oid owner, Oid databaseid)
376 : {
377 : GlobalTransaction gxact;
378 : int i;
379 :
380 7 : if (strlen(gid) >= GIDSIZE)
381 0 : ereport(ERROR,
382 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
383 : errmsg("transaction identifier \"%s\" is too long",
384 : gid)));
385 :
386 : /* fail immediately if feature is disabled */
387 7 : if (max_prepared_xacts == 0)
388 0 : ereport(ERROR,
389 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
390 : errmsg("prepared transactions are disabled"),
391 : errhint("Set max_prepared_transactions to a nonzero value.")));
392 :
393 : /* on first call, register the exit hook */
394 7 : if (!twophaseExitRegistered)
395 : {
396 1 : before_shmem_exit(AtProcExit_Twophase, 0);
397 1 : twophaseExitRegistered = true;
398 : }
399 :
400 7 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
401 :
402 : /* Check for conflicting GID */
403 8 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
404 : {
405 2 : gxact = TwoPhaseState->prepXacts[i];
406 2 : if (strcmp(gxact->gid, gid) == 0)
407 : {
408 1 : ereport(ERROR,
409 : (errcode(ERRCODE_DUPLICATE_OBJECT),
410 : errmsg("transaction identifier \"%s\" is already in use",
411 : gid)));
412 : }
413 : }
414 :
415 : /* Get a free gxact from the freelist */
416 6 : if (TwoPhaseState->freeGXacts == NULL)
417 0 : ereport(ERROR,
418 : (errcode(ERRCODE_OUT_OF_MEMORY),
419 : errmsg("maximum number of prepared transactions reached"),
420 : errhint("Increase max_prepared_transactions (currently %d).",
421 : max_prepared_xacts)));
422 6 : gxact = TwoPhaseState->freeGXacts;
423 6 : TwoPhaseState->freeGXacts = gxact->next;
424 :
425 6 : MarkAsPreparingGuts(gxact, xid, gid, prepared_at, owner, databaseid);
426 :
427 6 : gxact->ondisk = false;
428 :
429 : /* And insert it into the active array */
430 6 : Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
431 6 : TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
432 :
433 6 : LWLockRelease(TwoPhaseStateLock);
434 :
435 6 : return gxact;
436 : }
437 :
438 : /*
439 : * MarkAsPreparingGuts
440 : *
441 : * This uses a gxact struct and puts it into the active array.
442 : * NOTE: this is also used when reloading a gxact after a crash; so avoid
443 : * assuming that we can use very much backend context.
444 : *
445 : * Note: This function should be called with appropriate locks held.
446 : */
447 : static void
448 6 : MarkAsPreparingGuts(GlobalTransaction gxact, TransactionId xid, const char *gid,
449 : TimestampTz prepared_at, Oid owner, Oid databaseid)
450 : {
451 : PGPROC *proc;
452 : PGXACT *pgxact;
453 : int i;
454 :
455 6 : Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
456 :
457 6 : Assert(gxact != NULL);
458 6 : proc = &ProcGlobal->allProcs[gxact->pgprocno];
459 6 : pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
460 :
461 : /* Initialize the PGPROC entry */
462 6 : MemSet(proc, 0, sizeof(PGPROC));
463 6 : proc->pgprocno = gxact->pgprocno;
464 6 : SHMQueueElemInit(&(proc->links));
465 6 : proc->waitStatus = STATUS_OK;
466 : /* We set up the gxact's VXID as InvalidBackendId/XID */
467 6 : proc->lxid = (LocalTransactionId) xid;
468 6 : pgxact->xid = xid;
469 6 : pgxact->xmin = InvalidTransactionId;
470 6 : pgxact->delayChkpt = false;
471 6 : pgxact->vacuumFlags = 0;
472 6 : proc->pid = 0;
473 6 : proc->backendId = InvalidBackendId;
474 6 : proc->databaseId = databaseid;
475 6 : proc->roleId = owner;
476 6 : proc->isBackgroundWorker = false;
477 6 : proc->lwWaiting = false;
478 6 : proc->lwWaitMode = 0;
479 6 : proc->waitLock = NULL;
480 6 : proc->waitProcLock = NULL;
481 102 : for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
482 96 : SHMQueueInit(&(proc->myProcLocks[i]));
483 : /* subxid data must be filled later by GXactLoadSubxactData */
484 6 : pgxact->overflowed = false;
485 6 : pgxact->nxids = 0;
486 :
487 6 : gxact->prepared_at = prepared_at;
488 6 : gxact->xid = xid;
489 6 : gxact->owner = owner;
490 6 : gxact->locking_backend = MyBackendId;
491 6 : gxact->valid = false;
492 6 : gxact->inredo = false;
493 6 : 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 6 : MyLockedGxact = gxact;
500 6 : }
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
510 1 : GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts,
511 : TransactionId *children)
512 : {
513 1 : PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
514 1 : PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
515 :
516 : /* We need no extra lock since the GXACT isn't valid yet */
517 1 : if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
518 : {
519 0 : pgxact->overflowed = true;
520 0 : nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
521 : }
522 1 : if (nsubxacts > 0)
523 : {
524 1 : memcpy(proc->subxids.xids, children,
525 : nsubxacts * sizeof(TransactionId));
526 1 : pgxact->nxids = nsubxacts;
527 : }
528 1 : }
529 :
530 : /*
531 : * MarkAsPrepared
532 : * Mark the GXACT as fully valid, and enter it into the global ProcArray.
533 : *
534 : * lock_held indicates whether caller already holds TwoPhaseStateLock.
535 : */
536 : static void
537 6 : MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
538 : {
539 : /* Lock here may be overkill, but I'm not convinced of that ... */
540 6 : if (!lock_held)
541 6 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
542 6 : Assert(!gxact->valid);
543 6 : gxact->valid = true;
544 6 : if (!lock_held)
545 6 : LWLockRelease(TwoPhaseStateLock);
546 :
547 : /*
548 : * Put it into the global ProcArray so TransactionIdIsInProgress considers
549 : * the XID as still running.
550 : */
551 6 : ProcArrayAdd(&ProcGlobal->allProcs[gxact->pgprocno]);
552 6 : }
553 :
554 : /*
555 : * LockGXact
556 : * Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
557 : */
558 : static GlobalTransaction
559 6 : LockGXact(const char *gid, Oid user)
560 : {
561 : int i;
562 :
563 : /* on first call, register the exit hook */
564 6 : if (!twophaseExitRegistered)
565 : {
566 1 : before_shmem_exit(AtProcExit_Twophase, 0);
567 1 : twophaseExitRegistered = true;
568 : }
569 :
570 6 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
571 :
572 6 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
573 : {
574 6 : GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
575 6 : PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
576 :
577 : /* Ignore not-yet-valid GIDs */
578 6 : if (!gxact->valid)
579 0 : continue;
580 6 : if (strcmp(gxact->gid, gid) != 0)
581 0 : continue;
582 :
583 : /* Found it, but has someone else got it locked? */
584 6 : if (gxact->locking_backend != InvalidBackendId)
585 0 : ereport(ERROR,
586 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
587 : errmsg("prepared transaction with identifier \"%s\" is busy",
588 : gid)));
589 :
590 6 : if (user != gxact->owner && !superuser_arg(user))
591 0 : ereport(ERROR,
592 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
593 : errmsg("permission denied to finish prepared transaction"),
594 : errhint("Must be superuser or the user that prepared the transaction.")));
595 :
596 : /*
597 : * Note: it probably would be possible to allow committing from
598 : * another database; but at the moment NOTIFY is known not to work and
599 : * there may be some other issues as well. Hence disallow until
600 : * someone gets motivated to make it work.
601 : */
602 6 : if (MyDatabaseId != proc->databaseId)
603 0 : ereport(ERROR,
604 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
605 : errmsg("prepared transaction belongs to another database"),
606 : errhint("Connect to the database where the transaction was prepared to finish it.")));
607 :
608 : /* OK for me to lock it */
609 6 : gxact->locking_backend = MyBackendId;
610 6 : MyLockedGxact = gxact;
611 :
612 6 : LWLockRelease(TwoPhaseStateLock);
613 :
614 6 : return gxact;
615 : }
616 :
617 0 : LWLockRelease(TwoPhaseStateLock);
618 :
619 0 : ereport(ERROR,
620 : (errcode(ERRCODE_UNDEFINED_OBJECT),
621 : errmsg("prepared transaction with identifier \"%s\" does not exist",
622 : gid)));
623 :
624 : /* NOTREACHED */
625 : return NULL;
626 : }
627 :
628 : /*
629 : * RemoveGXact
630 : * Remove the prepared transaction from the shared memory array.
631 : *
632 : * NB: caller should have already removed it from ProcArray
633 : */
634 : static void
635 6 : RemoveGXact(GlobalTransaction gxact)
636 : {
637 : int i;
638 :
639 6 : Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
640 :
641 6 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
642 : {
643 6 : if (gxact == TwoPhaseState->prepXacts[i])
644 : {
645 : /* remove from the active array */
646 6 : TwoPhaseState->numPrepXacts--;
647 6 : TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
648 :
649 : /* and put it back in the freelist */
650 6 : gxact->next = TwoPhaseState->freeGXacts;
651 6 : TwoPhaseState->freeGXacts = gxact;
652 :
653 12 : return;
654 : }
655 : }
656 :
657 0 : 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
673 11 : GetPreparedTransactionList(GlobalTransaction *gxacts)
674 : {
675 : GlobalTransaction array;
676 : int num;
677 : int i;
678 :
679 11 : LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
680 :
681 11 : if (TwoPhaseState->numPrepXacts == 0)
682 : {
683 4 : LWLockRelease(TwoPhaseStateLock);
684 :
685 4 : *gxacts = NULL;
686 4 : return 0;
687 : }
688 :
689 7 : num = TwoPhaseState->numPrepXacts;
690 7 : array = (GlobalTransaction) palloc(sizeof(GlobalTransactionData) * num);
691 7 : *gxacts = array;
692 16 : for (i = 0; i < num; i++)
693 9 : memcpy(array + i, TwoPhaseState->prepXacts[i],
694 : sizeof(GlobalTransactionData));
695 :
696 7 : LWLockRelease(TwoPhaseStateLock);
697 :
698 7 : return num;
699 : }
700 :
701 :
702 : /* Working status for pg_prepared_xact */
703 : typedef struct
704 : {
705 : GlobalTransaction array;
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
718 20 : pg_prepared_xact(PG_FUNCTION_ARGS)
719 : {
720 : FuncCallContext *funcctx;
721 : Working_State *status;
722 :
723 20 : if (SRF_IS_FIRSTCALL())
724 : {
725 : TupleDesc tupdesc;
726 : MemoryContext oldcontext;
727 :
728 : /* create a function context for cross-call persistence */
729 11 : funcctx = SRF_FIRSTCALL_INIT();
730 :
731 : /*
732 : * Switch to memory context appropriate for multiple function calls
733 : */
734 11 : 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 11 : tupdesc = CreateTemplateTupleDesc(5, false);
739 11 : TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
740 : XIDOID, -1, 0);
741 11 : TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
742 : TEXTOID, -1, 0);
743 11 : TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
744 : TIMESTAMPTZOID, -1, 0);
745 11 : TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
746 : OIDOID, -1, 0);
747 11 : TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
748 : OIDOID, -1, 0);
749 :
750 11 : 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 11 : status = (Working_State *) palloc(sizeof(Working_State));
757 11 : funcctx->user_fctx = (void *) status;
758 :
759 11 : status->ngxacts = GetPreparedTransactionList(&status->array);
760 11 : status->currIdx = 0;
761 :
762 11 : MemoryContextSwitchTo(oldcontext);
763 : }
764 :
765 20 : funcctx = SRF_PERCALL_SETUP();
766 20 : status = (Working_State *) funcctx->user_fctx;
767 :
768 40 : while (status->array != NULL && status->currIdx < status->ngxacts)
769 : {
770 9 : GlobalTransaction gxact = &status->array[status->currIdx++];
771 9 : PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
772 9 : PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
773 : Datum values[5];
774 : bool nulls[5];
775 : HeapTuple tuple;
776 : Datum result;
777 :
778 9 : if (!gxact->valid)
779 0 : continue;
780 :
781 : /*
782 : * Form tuple with appropriate data.
783 : */
784 9 : MemSet(values, 0, sizeof(values));
785 9 : MemSet(nulls, 0, sizeof(nulls));
786 :
787 9 : values[0] = TransactionIdGetDatum(pgxact->xid);
788 9 : values[1] = CStringGetTextDatum(gxact->gid);
789 9 : values[2] = TimestampTzGetDatum(gxact->prepared_at);
790 9 : values[3] = ObjectIdGetDatum(gxact->owner);
791 9 : values[4] = ObjectIdGetDatum(proc->databaseId);
792 :
793 9 : tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
794 9 : result = HeapTupleGetDatum(tuple);
795 9 : SRF_RETURN_NEXT(funcctx, result);
796 : }
797 :
798 11 : 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
807 38 : TwoPhaseGetGXact(TransactionId xid)
808 : {
809 38 : GlobalTransaction result = NULL;
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 38 : if (xid == cached_xid)
820 30 : return cached_gxact;
821 :
822 8 : LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
823 :
824 9 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
825 : {
826 9 : GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
827 9 : PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
828 :
829 9 : if (pgxact->xid == xid)
830 : {
831 8 : result = gxact;
832 8 : break;
833 : }
834 : }
835 :
836 8 : LWLockRelease(TwoPhaseStateLock);
837 :
838 8 : if (result == NULL) /* should not happen */
839 0 : elog(ERROR, "failed to find GlobalTransaction for xid %u", xid);
840 :
841 8 : cached_xid = xid;
842 8 : cached_gxact = result;
843 :
844 8 : 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
856 8 : TwoPhaseGetDummyBackendId(TransactionId xid)
857 : {
858 8 : GlobalTransaction gxact = TwoPhaseGetGXact(xid);
859 :
860 8 : return gxact->dummyBackendId;
861 : }
862 :
863 : /*
864 : * TwoPhaseGetDummyProc
865 : * Get the PGPROC that represents a prepared transaction specified by XID
866 : */
867 : PGPROC *
868 30 : TwoPhaseGetDummyProc(TransactionId xid)
869 : {
870 30 : GlobalTransaction gxact = TwoPhaseGetGXact(xid);
871 :
872 30 : 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 */
917 : } TwoPhaseFileHeader;
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 */
930 : } TwoPhaseRecordOnDisk;
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;
940 : uint32 len;
941 : struct StateFileChunk *next;
942 : } StateFileChunk;
943 :
944 : static struct xllist
945 : {
946 : StateFileChunk *head; /* first data block in the chain */
947 : StateFileChunk *tail; /* last block in chain */
948 : uint32 num_chunks;
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 130 : save_state_data(const void *data, uint32 len)
964 : {
965 130 : uint32 padlen = MAXALIGN(len);
966 :
967 130 : if (padlen > records.bytes_free)
968 : {
969 4 : records.tail->next = palloc0(sizeof(StateFileChunk));
970 4 : records.tail = records.tail->next;
971 4 : records.tail->len = 0;
972 4 : records.tail->next = NULL;
973 4 : records.num_chunks++;
974 :
975 4 : records.bytes_free = Max(padlen, 512);
976 4 : records.tail->data = palloc(records.bytes_free);
977 : }
978 :
979 130 : memcpy(((char *) records.tail->data) + records.tail->len, data, len);
980 130 : records.tail->len += padlen;
981 130 : records.bytes_free -= padlen;
982 130 : records.total_len += padlen;
983 130 : }
984 :
985 : /*
986 : * Start preparing a state file.
987 : *
988 : * Initializes data structure and inserts the 2PC file header record.
989 : */
990 : void
991 6 : StartPrepare(GlobalTransaction gxact)
992 : {
993 6 : PGPROC *proc = &ProcGlobal->allProcs[gxact->pgprocno];
994 6 : PGXACT *pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
995 6 : 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 6 : records.head = palloc0(sizeof(StateFileChunk));
1004 6 : records.head->len = 0;
1005 6 : records.head->next = NULL;
1006 :
1007 6 : records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
1008 6 : records.head->data = palloc(records.bytes_free);
1009 :
1010 6 : records.tail = records.head;
1011 6 : records.num_chunks = 1;
1012 :
1013 6 : records.total_len = 0;
1014 :
1015 : /* Create header */
1016 6 : hdr.magic = TWOPHASE_MAGIC;
1017 6 : hdr.total_len = 0; /* EndPrepare will fill this in */
1018 6 : hdr.xid = xid;
1019 6 : hdr.database = proc->databaseId;
1020 6 : hdr.prepared_at = gxact->prepared_at;
1021 6 : hdr.owner = gxact->owner;
1022 6 : hdr.nsubxacts = xactGetCommittedChildren(&children);
1023 6 : hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
1024 6 : hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
1025 6 : hdr.ninvalmsgs = xactGetCommittedInvalidationMessages(&invalmsgs,
1026 : &hdr.initfileinval);
1027 6 : hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
1028 :
1029 6 : save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
1030 6 : 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 6 : if (hdr.nsubxacts > 0)
1037 : {
1038 1 : save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
1039 : /* While we have the child-xact data, stuff it in the gxact too */
1040 1 : GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
1041 : }
1042 6 : if (hdr.ncommitrels > 0)
1043 : {
1044 1 : save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileNode));
1045 1 : pfree(commitrels);
1046 : }
1047 6 : if (hdr.nabortrels > 0)
1048 : {
1049 2 : save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileNode));
1050 2 : pfree(abortrels);
1051 : }
1052 6 : if (hdr.ninvalmsgs > 0)
1053 : {
1054 2 : save_state_data(invalmsgs,
1055 2 : hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
1056 2 : pfree(invalmsgs);
1057 : }
1058 6 : }
1059 :
1060 : /*
1061 : * Finish preparing state data and writing it to WAL.
1062 : */
1063 : void
1064 6 : EndPrepare(GlobalTransaction gxact)
1065 : {
1066 : TwoPhaseFileHeader *hdr;
1067 : StateFileChunk *record;
1068 :
1069 : /* Add the end sentinel to the list of 2PC records */
1070 6 : RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID, 0,
1071 : NULL, 0);
1072 :
1073 : /* Go back and fill in total_len in the file header record */
1074 6 : hdr = (TwoPhaseFileHeader *) records.head->data;
1075 6 : Assert(hdr->magic == TWOPHASE_MAGIC);
1076 6 : 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 6 : if (hdr->total_len > MaxAllocSize)
1084 0 : 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 : */
1101 6 : XLogEnsureRecordSpace(0, records.num_chunks);
1102 :
1103 6 : START_CRIT_SECTION();
1104 :
1105 6 : MyPgXact->delayChkpt = true;
1106 :
1107 6 : XLogBeginInsert();
1108 16 : for (record = records.head; record != NULL; record = record->next)
1109 10 : XLogRegisterData(record->data, record->len);
1110 6 : gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
1111 6 : 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 */
1116 6 : gxact->prepare_start_lsn = ProcLastRecPtr;
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 6 : MarkAsPrepared(gxact, false);
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 6 : 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 6 : MyLockedGxact = gxact;
1145 :
1146 6 : 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 6 : SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
1155 :
1156 6 : records.tail = records.head = NULL;
1157 6 : records.num_chunks = 0;
1158 6 : }
1159 :
1160 : /*
1161 : * Register a 2PC record to be written to state file.
1162 : */
1163 : void
1164 59 : RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info,
1165 : const void *data, uint32 len)
1166 : {
1167 : TwoPhaseRecordOnDisk record;
1168 :
1169 59 : record.rmid = rmid;
1170 59 : record.info = info;
1171 59 : record.len = len;
1172 59 : save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
1173 59 : if (len > 0)
1174 53 : save_state_data(data, len);
1175 59 : }
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 0 : 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 0 : TwoPhaseFilePath(path, xid);
1197 :
1198 0 : fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
1199 0 : if (fd < 0)
1200 : {
1201 0 : if (give_warnings)
1202 0 : ereport(WARNING,
1203 : (errcode_for_file_access(),
1204 : errmsg("could not open two-phase state file \"%s\": %m",
1205 : path)));
1206 0 : 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 0 : if (fstat(fd, &stat))
1216 : {
1217 0 : CloseTransientFile(fd);
1218 0 : if (give_warnings)
1219 0 : ereport(WARNING,
1220 : (errcode_for_file_access(),
1221 : errmsg("could not stat two-phase state file \"%s\": %m",
1222 : path)));
1223 0 : return NULL;
1224 : }
1225 :
1226 0 : if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
1227 : MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
1228 0 : sizeof(pg_crc32c)) ||
1229 0 : stat.st_size > MaxAllocSize)
1230 : {
1231 0 : CloseTransientFile(fd);
1232 0 : return NULL;
1233 : }
1234 :
1235 0 : crc_offset = stat.st_size - sizeof(pg_crc32c);
1236 0 : if (crc_offset != MAXALIGN(crc_offset))
1237 : {
1238 0 : CloseTransientFile(fd);
1239 0 : return NULL;
1240 : }
1241 :
1242 : /*
1243 : * OK, slurp in the file.
1244 : */
1245 0 : buf = (char *) palloc(stat.st_size);
1246 :
1247 0 : pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_READ);
1248 0 : if (read(fd, buf, stat.st_size) != stat.st_size)
1249 : {
1250 0 : pgstat_report_wait_end();
1251 0 : CloseTransientFile(fd);
1252 0 : if (give_warnings)
1253 0 : ereport(WARNING,
1254 : (errcode_for_file_access(),
1255 : errmsg("could not read two-phase state file \"%s\": %m",
1256 : path)));
1257 0 : pfree(buf);
1258 0 : return NULL;
1259 : }
1260 :
1261 0 : pgstat_report_wait_end();
1262 0 : CloseTransientFile(fd);
1263 :
1264 0 : hdr = (TwoPhaseFileHeader *) buf;
1265 0 : if (hdr->magic != TWOPHASE_MAGIC || hdr->total_len != stat.st_size)
1266 : {
1267 0 : pfree(buf);
1268 0 : return NULL;
1269 : }
1270 :
1271 0 : INIT_CRC32C(calc_crc);
1272 0 : COMP_CRC32C(calc_crc, buf, crc_offset);
1273 0 : FIN_CRC32C(calc_crc);
1274 :
1275 0 : file_crc = *((pg_crc32c *) (buf + crc_offset));
1276 :
1277 0 : if (!EQ_CRC32C(calc_crc, file_crc))
1278 : {
1279 0 : pfree(buf);
1280 0 : return NULL;
1281 : }
1282 :
1283 0 : 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 6 : XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, int *len)
1297 : {
1298 : XLogRecord *record;
1299 : XLogReaderState *xlogreader;
1300 : char *errormsg;
1301 :
1302 6 : xlogreader = XLogReaderAllocate(&read_local_xlog_page, NULL);
1303 6 : if (!xlogreader)
1304 0 : ereport(ERROR,
1305 : (errcode(ERRCODE_OUT_OF_MEMORY),
1306 : errmsg("out of memory"),
1307 : errdetail("Failed while allocating a WAL reading processor.")));
1308 :
1309 6 : record = XLogReadRecord(xlogreader, lsn, &errormsg);
1310 6 : if (record == NULL)
1311 0 : ereport(ERROR,
1312 : (errcode_for_file_access(),
1313 : errmsg("could not read two-phase state from WAL at %X/%X",
1314 : (uint32) (lsn >> 32),
1315 : (uint32) lsn)));
1316 :
1317 12 : if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
1318 6 : (XLogRecGetInfo(xlogreader) & XLOG_XACT_OPMASK) != XLOG_XACT_PREPARE)
1319 0 : ereport(ERROR,
1320 : (errcode_for_file_access(),
1321 : errmsg("expected two-phase state data is not present in WAL at %X/%X",
1322 : (uint32) (lsn >> 32),
1323 : (uint32) lsn)));
1324 :
1325 6 : if (len != NULL)
1326 0 : *len = XLogRecGetDataLen(xlogreader);
1327 :
1328 6 : *buf = palloc(sizeof(char) * XLogRecGetDataLen(xlogreader));
1329 6 : memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
1330 :
1331 6 : XLogReaderFree(xlogreader);
1332 6 : }
1333 :
1334 :
1335 : /*
1336 : * Confirms an xid is prepared, during recovery
1337 : */
1338 : bool
1339 0 : StandbyTransactionIdIsPrepared(TransactionId xid)
1340 : {
1341 : char *buf;
1342 : TwoPhaseFileHeader *hdr;
1343 : bool result;
1344 :
1345 0 : Assert(TransactionIdIsValid(xid));
1346 :
1347 0 : if (max_prepared_xacts <= 0)
1348 0 : return false; /* nothing to do */
1349 :
1350 : /* Read and validate file */
1351 0 : buf = ReadTwoPhaseFile(xid, false);
1352 0 : if (buf == NULL)
1353 0 : return false;
1354 :
1355 : /* Check header also */
1356 0 : hdr = (TwoPhaseFileHeader *) buf;
1357 0 : result = TransactionIdEquals(hdr->xid, xid);
1358 0 : pfree(buf);
1359 :
1360 0 : return result;
1361 : }
1362 :
1363 : /*
1364 : * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
1365 : */
1366 : void
1367 6 : 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 6 : gxact = LockGXact(gid, GetUserId());
1390 6 : proc = &ProcGlobal->allProcs[gxact->pgprocno];
1391 6 : pgxact = &ProcGlobal->allPgXact[gxact->pgprocno];
1392 6 : 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 6 : if (gxact->ondisk)
1400 0 : buf = ReadTwoPhaseFile(xid, true);
1401 : else
1402 6 : XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
1403 :
1404 :
1405 : /*
1406 : * Disassemble the header area
1407 : */
1408 6 : hdr = (TwoPhaseFileHeader *) buf;
1409 6 : Assert(TransactionIdEquals(hdr->xid, xid));
1410 6 : bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1411 6 : bufptr += MAXALIGN(hdr->gidlen);
1412 6 : children = (TransactionId *) bufptr;
1413 6 : bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1414 6 : commitrels = (RelFileNode *) bufptr;
1415 6 : bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1416 6 : abortrels = (RelFileNode *) bufptr;
1417 6 : bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1418 6 : invalmsgs = (SharedInvalidationMessage *) bufptr;
1419 6 : bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1420 :
1421 : /* compute latestXid among all children */
1422 6 : 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 6 : if (isCommit)
1433 3 : RecordTransactionCommitPrepared(xid,
1434 : hdr->nsubxacts, children,
1435 : hdr->ncommitrels, commitrels,
1436 : hdr->ninvalmsgs, invalmsgs,
1437 3 : hdr->initfileinval);
1438 : else
1439 3 : RecordTransactionAbortPrepared(xid,
1440 : hdr->nsubxacts, children,
1441 : hdr->nabortrels, abortrels);
1442 :
1443 6 : 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 6 : 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 6 : if (isCommit)
1463 : {
1464 3 : delrels = commitrels;
1465 3 : ndelrels = hdr->ncommitrels;
1466 : }
1467 : else
1468 : {
1469 3 : delrels = abortrels;
1470 3 : ndelrels = hdr->nabortrels;
1471 : }
1472 7 : for (i = 0; i < ndelrels; i++)
1473 : {
1474 1 : SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1475 :
1476 1 : smgrdounlink(srel, false);
1477 1 : 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 6 : if (hdr->initfileinval)
1487 0 : RelationCacheInitFilePreInvalidate();
1488 6 : SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
1489 6 : if (hdr->initfileinval)
1490 0 : RelationCacheInitFilePostInvalidate();
1491 :
1492 : /* And now do the callbacks */
1493 6 : if (isCommit)
1494 3 : ProcessRecords(bufptr, xid, twophase_postcommit_callbacks);
1495 : else
1496 3 : ProcessRecords(bufptr, xid, twophase_postabort_callbacks);
1497 :
1498 6 : PredicateLockTwoPhaseFinish(xid, isCommit);
1499 :
1500 : /* Count the prepared xact as committed or aborted */
1501 6 : AtEOXact_PgStat(isCommit);
1502 :
1503 : /*
1504 : * And now we can clean up any files we may have left.
1505 : */
1506 6 : if (gxact->ondisk)
1507 0 : RemoveTwoPhaseFile(xid, true);
1508 :
1509 6 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1510 6 : RemoveGXact(gxact);
1511 6 : LWLockRelease(TwoPhaseStateLock);
1512 6 : MyLockedGxact = NULL;
1513 :
1514 6 : pfree(buf);
1515 6 : }
1516 :
1517 : /*
1518 : * Scan 2PC state data in memory and call the indicated callbacks for each 2PC record.
1519 : */
1520 : static void
1521 59 : ProcessRecords(char *bufptr, TransactionId xid,
1522 : const TwoPhaseCallback callbacks[])
1523 : {
1524 : for (;;)
1525 : {
1526 59 : TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
1527 :
1528 59 : Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
1529 59 : if (record->rmid == TWOPHASE_RM_END_ID)
1530 6 : break;
1531 :
1532 53 : bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
1533 :
1534 53 : if (callbacks[record->rmid] != NULL)
1535 42 : callbacks[record->rmid] (xid, record->info,
1536 : (void *) bufptr, record->len);
1537 :
1538 53 : bufptr += MAXALIGN(record->len);
1539 53 : }
1540 6 : }
1541 :
1542 : /*
1543 : * Remove the 2PC file for the specified XID.
1544 : *
1545 : * If giveWarning is false, do not complain about file-not-present;
1546 : * this is an expected case during WAL replay.
1547 : */
1548 : static void
1549 0 : RemoveTwoPhaseFile(TransactionId xid, bool giveWarning)
1550 : {
1551 : char path[MAXPGPATH];
1552 :
1553 0 : TwoPhaseFilePath(path, xid);
1554 0 : if (unlink(path))
1555 0 : if (errno != ENOENT || giveWarning)
1556 0 : ereport(WARNING,
1557 : (errcode_for_file_access(),
1558 : errmsg("could not remove two-phase state file \"%s\": %m",
1559 : path)));
1560 0 : }
1561 :
1562 : /*
1563 : * Recreates a state file. This is used in WAL replay and during
1564 : * checkpoint creation.
1565 : *
1566 : * Note: content and len don't include CRC.
1567 : */
1568 : static void
1569 0 : RecreateTwoPhaseFile(TransactionId xid, void *content, int len)
1570 : {
1571 : char path[MAXPGPATH];
1572 : pg_crc32c statefile_crc;
1573 : int fd;
1574 :
1575 : /* Recompute CRC */
1576 0 : INIT_CRC32C(statefile_crc);
1577 0 : COMP_CRC32C(statefile_crc, content, len);
1578 0 : FIN_CRC32C(statefile_crc);
1579 :
1580 0 : TwoPhaseFilePath(path, xid);
1581 :
1582 0 : fd = OpenTransientFile(path,
1583 : O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY,
1584 : S_IRUSR | S_IWUSR);
1585 0 : if (fd < 0)
1586 0 : ereport(ERROR,
1587 : (errcode_for_file_access(),
1588 : errmsg("could not recreate two-phase state file \"%s\": %m",
1589 : path)));
1590 :
1591 : /* Write content and CRC */
1592 0 : pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_WRITE);
1593 0 : if (write(fd, content, len) != len)
1594 : {
1595 0 : pgstat_report_wait_end();
1596 0 : CloseTransientFile(fd);
1597 0 : ereport(ERROR,
1598 : (errcode_for_file_access(),
1599 : errmsg("could not write two-phase state file: %m")));
1600 : }
1601 0 : if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
1602 : {
1603 0 : pgstat_report_wait_end();
1604 0 : CloseTransientFile(fd);
1605 0 : ereport(ERROR,
1606 : (errcode_for_file_access(),
1607 : errmsg("could not write two-phase state file: %m")));
1608 : }
1609 0 : pgstat_report_wait_end();
1610 :
1611 : /*
1612 : * We must fsync the file because the end-of-replay checkpoint will not do
1613 : * so, there being no GXACT in shared memory yet to tell it to.
1614 : */
1615 0 : pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_SYNC);
1616 0 : if (pg_fsync(fd) != 0)
1617 : {
1618 0 : CloseTransientFile(fd);
1619 0 : ereport(ERROR,
1620 : (errcode_for_file_access(),
1621 : errmsg("could not fsync two-phase state file: %m")));
1622 : }
1623 0 : pgstat_report_wait_end();
1624 :
1625 0 : if (CloseTransientFile(fd) != 0)
1626 0 : ereport(ERROR,
1627 : (errcode_for_file_access(),
1628 : errmsg("could not close two-phase state file: %m")));
1629 0 : }
1630 :
1631 : /*
1632 : * CheckPointTwoPhase -- handle 2PC component of checkpointing.
1633 : *
1634 : * We must fsync the state file of any GXACT that is valid or has been
1635 : * generated during redo and has a PREPARE LSN <= the checkpoint's redo
1636 : * horizon. (If the gxact isn't valid yet, has not been generated in
1637 : * redo, or has a later LSN, this checkpoint is not responsible for
1638 : * fsyncing it.)
1639 : *
1640 : * This is deliberately run as late as possible in the checkpoint sequence,
1641 : * because GXACTs ordinarily have short lifespans, and so it is quite
1642 : * possible that GXACTs that were valid at checkpoint start will no longer
1643 : * exist if we wait a little bit. With typical checkpoint settings this
1644 : * will be about 3 minutes for an online checkpoint, so as a result we
1645 : * we expect that there will be no GXACTs that need to be copied to disk.
1646 : *
1647 : * If a GXACT remains valid across multiple checkpoints, it will already
1648 : * be on disk so we don't bother to repeat that write.
1649 : */
1650 : void
1651 11 : CheckPointTwoPhase(XLogRecPtr redo_horizon)
1652 : {
1653 : int i;
1654 11 : int serialized_xacts = 0;
1655 :
1656 11 : if (max_prepared_xacts <= 0)
1657 17 : return; /* nothing to do */
1658 :
1659 : TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
1660 :
1661 : /*
1662 : * We are expecting there to be zero GXACTs that need to be copied to
1663 : * disk, so we perform all I/O while holding TwoPhaseStateLock for
1664 : * simplicity. This prevents any new xacts from preparing while this
1665 : * occurs, which shouldn't be a problem since the presence of long-lived
1666 : * prepared xacts indicates the transaction manager isn't active.
1667 : *
1668 : * It's also possible to move I/O out of the lock, but on every error we
1669 : * should check whether somebody committed our transaction in different
1670 : * backend. Let's leave this optimization for future, if somebody will
1671 : * spot that this place cause bottleneck.
1672 : *
1673 : * Note that it isn't possible for there to be a GXACT with a
1674 : * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
1675 : * because of the efforts with delayChkpt.
1676 : */
1677 5 : LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
1678 5 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1679 : {
1680 : /*
1681 : * Note that we are using gxact not pgxact so this works in recovery
1682 : * also
1683 : */
1684 0 : GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1685 :
1686 0 : if ((gxact->valid || gxact->inredo) &&
1687 0 : !gxact->ondisk &&
1688 0 : gxact->prepare_end_lsn <= redo_horizon)
1689 : {
1690 : char *buf;
1691 : int len;
1692 :
1693 0 : XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
1694 0 : RecreateTwoPhaseFile(gxact->xid, buf, len);
1695 0 : gxact->ondisk = true;
1696 0 : gxact->prepare_start_lsn = InvalidXLogRecPtr;
1697 0 : gxact->prepare_end_lsn = InvalidXLogRecPtr;
1698 0 : pfree(buf);
1699 0 : serialized_xacts++;
1700 : }
1701 : }
1702 5 : LWLockRelease(TwoPhaseStateLock);
1703 :
1704 : /*
1705 : * Flush unconditionally the parent directory to make any information
1706 : * durable on disk. Two-phase files could have been removed and those
1707 : * removals need to be made persistent as well as any files newly created
1708 : * previously since the last checkpoint.
1709 : */
1710 5 : fsync_fname(TWOPHASE_DIR, true);
1711 :
1712 : TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
1713 :
1714 5 : if (log_checkpoints && serialized_xacts > 0)
1715 0 : ereport(LOG,
1716 : (errmsg_plural("%u two-phase state file was written "
1717 : "for a long-running prepared transaction",
1718 : "%u two-phase state files were written "
1719 : "for long-running prepared transactions",
1720 : serialized_xacts,
1721 : serialized_xacts)));
1722 : }
1723 :
1724 : /*
1725 : * restoreTwoPhaseData
1726 : *
1727 : * Scan pg_twophase and fill TwoPhaseState depending on the on-disk data.
1728 : * This is called once at the beginning of recovery, saving any extra
1729 : * lookups in the future. Two-phase files that are newer than the
1730 : * minimum XID horizon are discarded on the way.
1731 : */
1732 : void
1733 3 : restoreTwoPhaseData(void)
1734 : {
1735 : DIR *cldir;
1736 : struct dirent *clde;
1737 :
1738 3 : cldir = AllocateDir(TWOPHASE_DIR);
1739 3 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1740 12 : while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
1741 : {
1742 6 : if (strlen(clde->d_name) == 8 &&
1743 0 : strspn(clde->d_name, "0123456789ABCDEF") == 8)
1744 : {
1745 : TransactionId xid;
1746 : char *buf;
1747 :
1748 0 : xid = (TransactionId) strtoul(clde->d_name, NULL, 16);
1749 :
1750 0 : buf = ProcessTwoPhaseBuffer(xid, InvalidXLogRecPtr,
1751 : true, false, false);
1752 0 : if (buf == NULL)
1753 0 : continue;
1754 :
1755 0 : PrepareRedoAdd(buf, InvalidXLogRecPtr, InvalidXLogRecPtr);
1756 : }
1757 : }
1758 3 : LWLockRelease(TwoPhaseStateLock);
1759 3 : FreeDir(cldir);
1760 3 : }
1761 :
1762 : /*
1763 : * PrescanPreparedTransactions
1764 : *
1765 : * Scan the shared memory entries of TwoPhaseState and determine the range
1766 : * of valid XIDs present. This is run during database startup, after we
1767 : * have completed reading WAL. ShmemVariableCache->nextXid has been set to
1768 : * one more than the highest XID for which evidence exists in WAL.
1769 : *
1770 : * We throw away any prepared xacts with main XID beyond nextXid --- if any
1771 : * are present, it suggests that the DBA has done a PITR recovery to an
1772 : * earlier point in time without cleaning out pg_twophase. We dare not
1773 : * try to recover such prepared xacts since they likely depend on database
1774 : * state that doesn't exist now.
1775 : *
1776 : * However, we will advance nextXid beyond any subxact XIDs belonging to
1777 : * valid prepared xacts. We need to do this since subxact commit doesn't
1778 : * write a WAL entry, and so there might be no evidence in WAL of those
1779 : * subxact XIDs.
1780 : *
1781 : * Our other responsibility is to determine and return the oldest valid XID
1782 : * among the prepared xacts (if none, return ShmemVariableCache->nextXid).
1783 : * This is needed to synchronize pg_subtrans startup properly.
1784 : *
1785 : * If xids_p and nxids_p are not NULL, pointer to a palloc'd array of all
1786 : * top-level xids is stored in *xids_p. The number of entries in the array
1787 : * is returned in *nxids_p.
1788 : */
1789 : TransactionId
1790 3 : PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
1791 : {
1792 3 : TransactionId origNextXid = ShmemVariableCache->nextXid;
1793 3 : TransactionId result = origNextXid;
1794 3 : TransactionId *xids = NULL;
1795 3 : int nxids = 0;
1796 3 : int allocsize = 0;
1797 : int i;
1798 :
1799 3 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1800 3 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1801 : {
1802 : TransactionId xid;
1803 : char *buf;
1804 0 : GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1805 :
1806 0 : Assert(gxact->inredo);
1807 :
1808 0 : xid = gxact->xid;
1809 :
1810 0 : buf = ProcessTwoPhaseBuffer(xid,
1811 : gxact->prepare_start_lsn,
1812 0 : gxact->ondisk, false, true);
1813 :
1814 0 : if (buf == NULL)
1815 0 : continue;
1816 :
1817 : /*
1818 : * OK, we think this file is valid. Incorporate xid into the
1819 : * running-minimum result.
1820 : */
1821 0 : if (TransactionIdPrecedes(xid, result))
1822 0 : result = xid;
1823 :
1824 0 : if (xids_p)
1825 : {
1826 0 : if (nxids == allocsize)
1827 : {
1828 0 : if (nxids == 0)
1829 : {
1830 0 : allocsize = 10;
1831 0 : xids = palloc(allocsize * sizeof(TransactionId));
1832 : }
1833 : else
1834 : {
1835 0 : allocsize = allocsize * 2;
1836 0 : xids = repalloc(xids, allocsize * sizeof(TransactionId));
1837 : }
1838 : }
1839 0 : xids[nxids++] = xid;
1840 : }
1841 :
1842 0 : pfree(buf);
1843 : }
1844 3 : LWLockRelease(TwoPhaseStateLock);
1845 :
1846 3 : if (xids_p)
1847 : {
1848 0 : *xids_p = xids;
1849 0 : *nxids_p = nxids;
1850 : }
1851 :
1852 3 : return result;
1853 : }
1854 :
1855 : /*
1856 : * StandbyRecoverPreparedTransactions
1857 : *
1858 : * Scan the shared memory entries of TwoPhaseState and setup all the required
1859 : * information to allow standby queries to treat prepared transactions as still
1860 : * active.
1861 : *
1862 : * This is never called at the end of recovery - we use
1863 : * RecoverPreparedTransactions() at that point.
1864 : *
1865 : * The lack of calls to SubTransSetParent() calls here is by design;
1866 : * those calls are made by RecoverPreparedTransactions() at the end of recovery
1867 : * for those xacts that need this.
1868 : */
1869 : void
1870 0 : StandbyRecoverPreparedTransactions(void)
1871 : {
1872 : int i;
1873 :
1874 0 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1875 0 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1876 : {
1877 : TransactionId xid;
1878 : char *buf;
1879 0 : GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1880 :
1881 0 : Assert(gxact->inredo);
1882 :
1883 0 : xid = gxact->xid;
1884 :
1885 0 : buf = ProcessTwoPhaseBuffer(xid,
1886 : gxact->prepare_start_lsn,
1887 0 : gxact->ondisk, false, false);
1888 0 : if (buf != NULL)
1889 0 : pfree(buf);
1890 : }
1891 0 : LWLockRelease(TwoPhaseStateLock);
1892 0 : }
1893 :
1894 : /*
1895 : * RecoverPreparedTransactions
1896 : *
1897 : * Scan the shared memory entries of TwoPhaseState and reload the state for
1898 : * each prepared transaction (reacquire locks, etc).
1899 : *
1900 : * This is run at the end of recovery, but before we allow backends to write
1901 : * WAL.
1902 : *
1903 : * At the end of recovery the way we take snapshots will change. We now need
1904 : * to mark all running transactions with their full SubTransSetParent() info
1905 : * to allow normal snapshots to work correctly if snapshots overflow.
1906 : * We do this here because by definition prepared transactions are the only
1907 : * type of write transaction still running, so this is necessary and
1908 : * complete.
1909 : */
1910 : void
1911 3 : RecoverPreparedTransactions(void)
1912 : {
1913 : int i;
1914 :
1915 3 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1916 3 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
1917 : {
1918 : TransactionId xid;
1919 : char *buf;
1920 0 : GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
1921 : char *bufptr;
1922 : TwoPhaseFileHeader *hdr;
1923 : TransactionId *subxids;
1924 : const char *gid;
1925 :
1926 0 : xid = gxact->xid;
1927 :
1928 : /*
1929 : * Reconstruct subtrans state for the transaction --- needed because
1930 : * pg_subtrans is not preserved over a restart. Note that we are
1931 : * linking all the subtransactions directly to the top-level XID;
1932 : * there may originally have been a more complex hierarchy, but
1933 : * there's no need to restore that exactly. It's possible that
1934 : * SubTransSetParent has been set before, if the prepared transaction
1935 : * generated xid assignment records.
1936 : */
1937 0 : buf = ProcessTwoPhaseBuffer(xid,
1938 : gxact->prepare_start_lsn,
1939 0 : gxact->ondisk, true, false);
1940 0 : if (buf == NULL)
1941 0 : continue;
1942 :
1943 0 : ereport(LOG,
1944 : (errmsg("recovering prepared transaction %u from shared memory", xid)));
1945 :
1946 0 : hdr = (TwoPhaseFileHeader *) buf;
1947 0 : Assert(TransactionIdEquals(hdr->xid, xid));
1948 0 : bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
1949 0 : gid = (const char *) bufptr;
1950 0 : bufptr += MAXALIGN(hdr->gidlen);
1951 0 : subxids = (TransactionId *) bufptr;
1952 0 : bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
1953 0 : bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileNode));
1954 0 : bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileNode));
1955 0 : bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
1956 :
1957 : /*
1958 : * Recreate its GXACT and dummy PGPROC. But, check whether it was
1959 : * added in redo and already has a shmem entry for it.
1960 : */
1961 0 : MarkAsPreparingGuts(gxact, xid, gid,
1962 : hdr->prepared_at,
1963 : hdr->owner, hdr->database);
1964 :
1965 : /* recovered, so reset the flag for entries generated by redo */
1966 0 : gxact->inredo = false;
1967 :
1968 0 : GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
1969 0 : MarkAsPrepared(gxact, true);
1970 :
1971 0 : LWLockRelease(TwoPhaseStateLock);
1972 :
1973 : /*
1974 : * Recover other state (notably locks) using resource managers.
1975 : */
1976 0 : ProcessRecords(bufptr, xid, twophase_recover_callbacks);
1977 :
1978 : /*
1979 : * Release locks held by the standby process after we process each
1980 : * prepared transaction. As a result, we don't need too many
1981 : * additional locks at any one time.
1982 : */
1983 0 : if (InHotStandby)
1984 0 : StandbyReleaseLockTree(xid, hdr->nsubxacts, subxids);
1985 :
1986 : /*
1987 : * We're done with recovering this transaction. Clear MyLockedGxact,
1988 : * like we do in PrepareTransaction() during normal operation.
1989 : */
1990 0 : PostPrepare_Twophase();
1991 :
1992 0 : pfree(buf);
1993 :
1994 0 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
1995 : }
1996 :
1997 3 : LWLockRelease(TwoPhaseStateLock);
1998 3 : }
1999 :
2000 : /*
2001 : * ProcessTwoPhaseBuffer
2002 : *
2003 : * Given a transaction id, read it either from disk or read it directly
2004 : * via shmem xlog record pointer using the provided "prepare_start_lsn".
2005 : *
2006 : * If setParent is true, set up subtransaction parent linkages.
2007 : *
2008 : * If setNextXid is true, set ShmemVariableCache->nextXid to the newest
2009 : * value scanned.
2010 : */
2011 : static char *
2012 0 : ProcessTwoPhaseBuffer(TransactionId xid,
2013 : XLogRecPtr prepare_start_lsn,
2014 : bool fromdisk,
2015 : bool setParent, bool setNextXid)
2016 : {
2017 0 : TransactionId origNextXid = ShmemVariableCache->nextXid;
2018 : TransactionId *subxids;
2019 : char *buf;
2020 : TwoPhaseFileHeader *hdr;
2021 : int i;
2022 :
2023 0 : Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2024 :
2025 0 : if (!fromdisk)
2026 0 : Assert(prepare_start_lsn != InvalidXLogRecPtr);
2027 :
2028 : /* Already processed? */
2029 0 : if (TransactionIdDidCommit(xid) || TransactionIdDidAbort(xid))
2030 : {
2031 0 : if (fromdisk)
2032 : {
2033 0 : ereport(WARNING,
2034 : (errmsg("removing stale two-phase state file for \"%u\"",
2035 : xid)));
2036 0 : RemoveTwoPhaseFile(xid, true);
2037 : }
2038 : else
2039 : {
2040 0 : ereport(WARNING,
2041 : (errmsg("removing stale two-phase state from shared memory for \"%u\"",
2042 : xid)));
2043 0 : PrepareRedoRemove(xid, true);
2044 : }
2045 0 : return NULL;
2046 : }
2047 :
2048 : /* Reject XID if too new */
2049 0 : if (TransactionIdFollowsOrEquals(xid, origNextXid))
2050 : {
2051 0 : if (fromdisk)
2052 : {
2053 0 : ereport(WARNING,
2054 : (errmsg("removing future two-phase state file for \"%u\"",
2055 : xid)));
2056 0 : RemoveTwoPhaseFile(xid, true);
2057 : }
2058 : else
2059 : {
2060 0 : ereport(WARNING,
2061 : (errmsg("removing future two-phase state from memory for \"%u\"",
2062 : xid)));
2063 0 : PrepareRedoRemove(xid, true);
2064 : }
2065 0 : return NULL;
2066 : }
2067 :
2068 0 : if (fromdisk)
2069 : {
2070 : /* Read and validate file */
2071 0 : buf = ReadTwoPhaseFile(xid, true);
2072 0 : if (buf == NULL)
2073 : {
2074 0 : ereport(WARNING,
2075 : (errmsg("removing corrupt two-phase state file for \"%u\"",
2076 : xid)));
2077 0 : RemoveTwoPhaseFile(xid, true);
2078 0 : return NULL;
2079 : }
2080 : }
2081 : else
2082 : {
2083 : /* Read xlog data */
2084 0 : XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
2085 : }
2086 :
2087 : /* Deconstruct header */
2088 0 : hdr = (TwoPhaseFileHeader *) buf;
2089 0 : if (!TransactionIdEquals(hdr->xid, xid))
2090 : {
2091 0 : if (fromdisk)
2092 : {
2093 0 : ereport(WARNING,
2094 : (errmsg("removing corrupt two-phase state file for \"%u\"",
2095 : xid)));
2096 0 : RemoveTwoPhaseFile(xid, true);
2097 : }
2098 : else
2099 : {
2100 0 : ereport(WARNING,
2101 : (errmsg("removing corrupt two-phase state from memory for \"%u\"",
2102 : xid)));
2103 0 : PrepareRedoRemove(xid, true);
2104 : }
2105 0 : pfree(buf);
2106 0 : return NULL;
2107 : }
2108 :
2109 : /*
2110 : * Examine subtransaction XIDs ... they should all follow main XID, and
2111 : * they may force us to advance nextXid.
2112 : */
2113 0 : subxids = (TransactionId *) (buf +
2114 0 : MAXALIGN(sizeof(TwoPhaseFileHeader)) +
2115 0 : MAXALIGN(hdr->gidlen));
2116 0 : for (i = 0; i < hdr->nsubxacts; i++)
2117 : {
2118 0 : TransactionId subxid = subxids[i];
2119 :
2120 0 : Assert(TransactionIdFollows(subxid, xid));
2121 :
2122 : /* update nextXid if needed */
2123 0 : if (setNextXid &&
2124 0 : TransactionIdFollowsOrEquals(subxid,
2125 0 : ShmemVariableCache->nextXid))
2126 : {
2127 : /*
2128 : * We don't expect anyone else to modify nextXid, hence we don't
2129 : * need to hold a lock while examining it. We still acquire the
2130 : * lock to modify it, though, so we recheck.
2131 : */
2132 0 : LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
2133 0 : if (TransactionIdFollowsOrEquals(subxid,
2134 0 : ShmemVariableCache->nextXid))
2135 : {
2136 0 : ShmemVariableCache->nextXid = subxid;
2137 0 : TransactionIdAdvance(ShmemVariableCache->nextXid);
2138 : }
2139 0 : LWLockRelease(XidGenLock);
2140 : }
2141 :
2142 0 : if (setParent)
2143 0 : SubTransSetParent(subxid, xid);
2144 : }
2145 :
2146 0 : return buf;
2147 : }
2148 :
2149 :
2150 : /*
2151 : * RecordTransactionCommitPrepared
2152 : *
2153 : * This is basically the same as RecordTransactionCommit (q.v. if you change
2154 : * this function): in particular, we must set the delayChkpt flag to avoid a
2155 : * race condition.
2156 : *
2157 : * We know the transaction made at least one XLOG entry (its PREPARE),
2158 : * so it is never possible to optimize out the commit record.
2159 : */
2160 : static void
2161 3 : RecordTransactionCommitPrepared(TransactionId xid,
2162 : int nchildren,
2163 : TransactionId *children,
2164 : int nrels,
2165 : RelFileNode *rels,
2166 : int ninvalmsgs,
2167 : SharedInvalidationMessage *invalmsgs,
2168 : bool initfileinval)
2169 : {
2170 : XLogRecPtr recptr;
2171 3 : TimestampTz committs = GetCurrentTimestamp();
2172 : bool replorigin;
2173 :
2174 : /*
2175 : * Are we using the replication origins feature? Or, in other words, are
2176 : * we replaying remote actions?
2177 : */
2178 3 : replorigin = (replorigin_session_origin != InvalidRepOriginId &&
2179 0 : replorigin_session_origin != DoNotReplicateId);
2180 :
2181 3 : START_CRIT_SECTION();
2182 :
2183 : /* See notes in RecordTransactionCommit */
2184 3 : MyPgXact->delayChkpt = true;
2185 :
2186 : /*
2187 : * Emit the XLOG commit record. Note that we mark 2PC commits as
2188 : * potentially having AccessExclusiveLocks since we don't know whether or
2189 : * not they do.
2190 : */
2191 3 : recptr = XactLogCommitRecord(committs,
2192 : nchildren, children, nrels, rels,
2193 : ninvalmsgs, invalmsgs,
2194 : initfileinval, false,
2195 3 : MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK,
2196 : xid);
2197 :
2198 :
2199 3 : if (replorigin)
2200 : /* Move LSNs forward for this replication origin */
2201 0 : replorigin_session_advance(replorigin_session_origin_lsn,
2202 : XactLastRecEnd);
2203 :
2204 : /*
2205 : * Record commit timestamp. The value comes from plain commit timestamp
2206 : * if replorigin is not enabled, or replorigin already set a value for us
2207 : * in replorigin_session_origin_timestamp otherwise.
2208 : *
2209 : * We don't need to WAL-log anything here, as the commit record written
2210 : * above already contains the data.
2211 : */
2212 3 : if (!replorigin || replorigin_session_origin_timestamp == 0)
2213 3 : replorigin_session_origin_timestamp = committs;
2214 :
2215 3 : TransactionTreeSetCommitTsData(xid, nchildren, children,
2216 : replorigin_session_origin_timestamp,
2217 : replorigin_session_origin, false);
2218 :
2219 : /*
2220 : * We don't currently try to sleep before flush here ... nor is there any
2221 : * support for async commit of a prepared xact (the very idea is probably
2222 : * a contradiction)
2223 : */
2224 :
2225 : /* Flush XLOG to disk */
2226 3 : XLogFlush(recptr);
2227 :
2228 : /* Mark the transaction committed in pg_xact */
2229 3 : TransactionIdCommitTree(xid, nchildren, children);
2230 :
2231 : /* Checkpoint can proceed now */
2232 3 : MyPgXact->delayChkpt = false;
2233 :
2234 3 : END_CRIT_SECTION();
2235 :
2236 : /*
2237 : * Wait for synchronous replication, if required.
2238 : *
2239 : * Note that at this stage we have marked clog, but still show as running
2240 : * in the procarray and continue to hold locks.
2241 : */
2242 3 : SyncRepWaitForLSN(recptr, true);
2243 3 : }
2244 :
2245 : /*
2246 : * RecordTransactionAbortPrepared
2247 : *
2248 : * This is basically the same as RecordTransactionAbort.
2249 : *
2250 : * We know the transaction made at least one XLOG entry (its PREPARE),
2251 : * so it is never possible to optimize out the abort record.
2252 : */
2253 : static void
2254 3 : RecordTransactionAbortPrepared(TransactionId xid,
2255 : int nchildren,
2256 : TransactionId *children,
2257 : int nrels,
2258 : RelFileNode *rels)
2259 : {
2260 : XLogRecPtr recptr;
2261 :
2262 : /*
2263 : * Catch the scenario where we aborted partway through
2264 : * RecordTransactionCommitPrepared ...
2265 : */
2266 3 : if (TransactionIdDidCommit(xid))
2267 0 : elog(PANIC, "cannot abort transaction %u, it was already committed",
2268 : xid);
2269 :
2270 3 : START_CRIT_SECTION();
2271 :
2272 : /*
2273 : * Emit the XLOG commit record. Note that we mark 2PC aborts as
2274 : * potentially having AccessExclusiveLocks since we don't know whether or
2275 : * not they do.
2276 : */
2277 3 : recptr = XactLogAbortRecord(GetCurrentTimestamp(),
2278 : nchildren, children,
2279 : nrels, rels,
2280 3 : MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK,
2281 : xid);
2282 :
2283 : /* Always flush, since we're about to remove the 2PC state file */
2284 3 : XLogFlush(recptr);
2285 :
2286 : /*
2287 : * Mark the transaction aborted in clog. This is not absolutely necessary
2288 : * but we may as well do it while we are here.
2289 : */
2290 3 : TransactionIdAbortTree(xid, nchildren, children);
2291 :
2292 3 : END_CRIT_SECTION();
2293 :
2294 : /*
2295 : * Wait for synchronous replication, if required.
2296 : *
2297 : * Note that at this stage we have marked clog, but still show as running
2298 : * in the procarray and continue to hold locks.
2299 : */
2300 3 : SyncRepWaitForLSN(recptr, false);
2301 3 : }
2302 :
2303 : /*
2304 : * PrepareRedoAdd
2305 : *
2306 : * Store pointers to the start/end of the WAL record along with the xid in
2307 : * a gxact entry in shared memory TwoPhaseState structure. If caller
2308 : * specifies InvalidXLogRecPtr as WAL location to fetch the two-phase
2309 : * data, the entry is marked as located on disk.
2310 : */
2311 : void
2312 0 : PrepareRedoAdd(char *buf, XLogRecPtr start_lsn, XLogRecPtr end_lsn)
2313 : {
2314 0 : TwoPhaseFileHeader *hdr = (TwoPhaseFileHeader *) buf;
2315 : char *bufptr;
2316 : const char *gid;
2317 : GlobalTransaction gxact;
2318 :
2319 0 : Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2320 0 : Assert(RecoveryInProgress());
2321 :
2322 0 : bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
2323 0 : gid = (const char *) bufptr;
2324 :
2325 : /*
2326 : * Reserve the GID for the given transaction in the redo code path.
2327 : *
2328 : * This creates a gxact struct and puts it into the active array.
2329 : *
2330 : * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
2331 : * shared memory. Hence, we only fill up the bare minimum contents here.
2332 : * The gxact also gets marked with gxact->inredo set to true to indicate
2333 : * that it got added in the redo phase
2334 : */
2335 :
2336 : /* Get a free gxact from the freelist */
2337 0 : if (TwoPhaseState->freeGXacts == NULL)
2338 0 : ereport(ERROR,
2339 : (errcode(ERRCODE_OUT_OF_MEMORY),
2340 : errmsg("maximum number of prepared transactions reached"),
2341 : errhint("Increase max_prepared_transactions (currently %d).",
2342 : max_prepared_xacts)));
2343 0 : gxact = TwoPhaseState->freeGXacts;
2344 0 : TwoPhaseState->freeGXacts = gxact->next;
2345 :
2346 0 : gxact->prepared_at = hdr->prepared_at;
2347 0 : gxact->prepare_start_lsn = start_lsn;
2348 0 : gxact->prepare_end_lsn = end_lsn;
2349 0 : gxact->xid = hdr->xid;
2350 0 : gxact->owner = hdr->owner;
2351 0 : gxact->locking_backend = InvalidBackendId;
2352 0 : gxact->valid = false;
2353 0 : gxact->ondisk = XLogRecPtrIsInvalid(start_lsn);
2354 0 : gxact->inredo = true; /* yes, added in redo */
2355 0 : strcpy(gxact->gid, gid);
2356 :
2357 : /* And insert it into the active array */
2358 0 : Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
2359 0 : TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
2360 :
2361 0 : elog(DEBUG2, "added 2PC data in shared memory for transaction %u", gxact->xid);
2362 0 : }
2363 :
2364 : /*
2365 : * PrepareRedoRemove
2366 : *
2367 : * Remove the corresponding gxact entry from TwoPhaseState. Also remove
2368 : * the 2PC file if a prepared transaction was saved via an earlier checkpoint.
2369 : *
2370 : * Caller must hold TwoPhaseStateLock in exclusive mode, because TwoPhaseState
2371 : * is updated.
2372 : */
2373 : void
2374 0 : PrepareRedoRemove(TransactionId xid, bool giveWarning)
2375 : {
2376 0 : GlobalTransaction gxact = NULL;
2377 : int i;
2378 0 : bool found = false;
2379 :
2380 0 : Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
2381 0 : Assert(RecoveryInProgress());
2382 :
2383 0 : for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
2384 : {
2385 0 : gxact = TwoPhaseState->prepXacts[i];
2386 :
2387 0 : if (gxact->xid == xid)
2388 : {
2389 0 : Assert(gxact->inredo);
2390 0 : found = true;
2391 0 : break;
2392 : }
2393 : }
2394 :
2395 : /*
2396 : * Just leave if there is nothing, this is expected during WAL replay.
2397 : */
2398 0 : if (!found)
2399 0 : return;
2400 :
2401 : /*
2402 : * And now we can clean up any files we may have left.
2403 : */
2404 0 : elog(DEBUG2, "removing 2PC data for transaction %u", xid);
2405 0 : if (gxact->ondisk)
2406 0 : RemoveTwoPhaseFile(xid, giveWarning);
2407 0 : RemoveGXact(gxact);
2408 :
2409 0 : return;
2410 : }
|