LCOV - code coverage report
Current view: top level - src/backend/access/transam - twophase.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 88.1 % 822 724
Test Date: 2026-10-29 00:16:02 Functions: 97.8 % 46 45
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 55.7 % 456 254

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * twophase.c
       4                 :             :  *      Two-phase commit support functions.
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, 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 PGPROC; this is what keeps
      25                 :             :  *      the XID considered running by TransactionIdIsInProgress.  It is also
      26                 :             :  *      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/xlogreader.h"
      89                 :             : #include "access/xlogrecovery.h"
      90                 :             : #include "access/xlogutils.h"
      91                 :             : #include "catalog/pg_type.h"
      92                 :             : #include "catalog/storage.h"
      93                 :             : #include "common/string.h"
      94                 :             : #include "funcapi.h"
      95                 :             : #include "miscadmin.h"
      96                 :             : #include "pg_trace.h"
      97                 :             : #include "pgstat.h"
      98                 :             : #include "replication/origin.h"
      99                 :             : #include "replication/syncrep.h"
     100                 :             : #include "storage/fd.h"
     101                 :             : #include "storage/ipc.h"
     102                 :             : #include "storage/md.h"
     103                 :             : #include "storage/predicate.h"
     104                 :             : #include "storage/proc.h"
     105                 :             : #include "storage/procarray.h"
     106                 :             : #include "storage/subsystems.h"
     107                 :             : #include "utils/builtins.h"
     108                 :             : #include "utils/injection_point.h"
     109                 :             : #include "utils/memutils.h"
     110                 :             : #include "utils/timestamp.h"
     111                 :             : #include "utils/wait_event.h"
     112                 :             : 
     113                 :             : /*
     114                 :             :  * Directory where Two-phase commit files reside within PGDATA
     115                 :             :  */
     116                 :             : #define TWOPHASE_DIR "pg_twophase"
     117                 :             : 
     118                 :             : /* GUC variable, can't be changed after startup */
     119                 :             : int         max_prepared_xacts = 0;
     120                 :             : 
     121                 :             : /*
     122                 :             :  * This struct describes one global transaction that is in prepared state
     123                 :             :  * or attempting to become prepared.
     124                 :             :  *
     125                 :             :  * The lifecycle of a global transaction is:
     126                 :             :  *
     127                 :             :  * 1. After checking that the requested GID is not in use, set up an entry in
     128                 :             :  * the TwoPhaseState->prepXacts array with the correct GID and valid = false,
     129                 :             :  * and mark it as locked by my backend.
     130                 :             :  *
     131                 :             :  * 2. After successfully completing prepare, set valid = true and enter the
     132                 :             :  * referenced PGPROC into the global ProcArray.
     133                 :             :  *
     134                 :             :  * 3. To begin COMMIT PREPARED or ROLLBACK PREPARED, check that the entry is
     135                 :             :  * valid and not locked, then mark the entry as locked by storing my current
     136                 :             :  * proc number into locking_backend.  This prevents concurrent attempts to
     137                 :             :  * commit or rollback the same prepared xact.
     138                 :             :  *
     139                 :             :  * 4. On completion of COMMIT PREPARED or ROLLBACK PREPARED, remove the entry
     140                 :             :  * from the ProcArray and the TwoPhaseState->prepXacts array and return it to
     141                 :             :  * the freelist.
     142                 :             :  *
     143                 :             :  * Note that if the preparing transaction fails between steps 1 and 2, the
     144                 :             :  * entry must be removed so that the GID and the GlobalTransaction struct
     145                 :             :  * can be reused.  See AtAbort_Twophase().
     146                 :             :  *
     147                 :             :  * typedef struct GlobalTransactionData *GlobalTransaction appears in
     148                 :             :  * twophase.h
     149                 :             :  */
     150                 :             : 
     151                 :             : typedef struct GlobalTransactionData
     152                 :             : {
     153                 :             :     GlobalTransaction next;     /* list link for free list */
     154                 :             :     int         pgprocno;       /* ID of associated dummy PGPROC */
     155                 :             :     TimestampTz prepared_at;    /* time of preparation */
     156                 :             : 
     157                 :             :     /*
     158                 :             :      * Note that we need to keep track of two LSNs for each GXACT. We keep
     159                 :             :      * track of the start LSN because this is the address we must use to read
     160                 :             :      * state data back from WAL when committing a prepared GXACT. We keep
     161                 :             :      * track of the end LSN because that is the LSN we need to wait for prior
     162                 :             :      * to commit.
     163                 :             :      */
     164                 :             :     XLogRecPtr  prepare_start_lsn;  /* XLOG offset of prepare record start */
     165                 :             :     XLogRecPtr  prepare_end_lsn;    /* XLOG offset of prepare record end */
     166                 :             :     FullTransactionId fxid;     /* The GXACT full xid */
     167                 :             : 
     168                 :             :     Oid         owner;          /* ID of user that executed the xact */
     169                 :             :     ProcNumber  locking_backend;    /* backend currently working on the xact */
     170                 :             :     bool        valid;          /* true if PGPROC entry is in proc array */
     171                 :             :     bool        ondisk;         /* true if prepare state file is on disk */
     172                 :             :     bool        inredo;         /* true if entry was added via xlog_redo */
     173                 :             :     char        gid[GIDSIZE];   /* The GID assigned to the prepared xact */
     174                 :             : } GlobalTransactionData;
     175                 :             : 
     176                 :             : /*
     177                 :             :  * Two Phase Commit shared state.  Access to this struct is protected
     178                 :             :  * by TwoPhaseStateLock.
     179                 :             :  */
     180                 :             : typedef struct TwoPhaseStateData
     181                 :             : {
     182                 :             :     /* Head of linked list of free GlobalTransactionData structs */
     183                 :             :     GlobalTransaction freeGXacts;
     184                 :             : 
     185                 :             :     /* Number of valid prepXacts entries. */
     186                 :             :     int         numPrepXacts;
     187                 :             : 
     188                 :             :     /* There are max_prepared_xacts items in this array */
     189                 :             :     GlobalTransaction prepXacts[FLEXIBLE_ARRAY_MEMBER];
     190                 :             : } TwoPhaseStateData;
     191                 :             : 
     192                 :             : static TwoPhaseStateData *TwoPhaseState;
     193                 :             : 
     194                 :             : static void TwoPhaseShmemRequest(void *arg);
     195                 :             : static void TwoPhaseShmemInit(void *arg);
     196                 :             : 
     197                 :             : const ShmemCallbacks TwoPhaseShmemCallbacks = {
     198                 :             :     .request_fn = TwoPhaseShmemRequest,
     199                 :             :     .init_fn = TwoPhaseShmemInit,
     200                 :             : };
     201                 :             : 
     202                 :             : /*
     203                 :             :  * Global transaction entry currently locked by us, if any.  Note that any
     204                 :             :  * access to the entry pointed to by this variable must be protected by
     205                 :             :  * TwoPhaseStateLock, though obviously the pointer itself doesn't need to be
     206                 :             :  * (since it's just local memory).
     207                 :             :  */
     208                 :             : static GlobalTransaction MyLockedGxact = NULL;
     209                 :             : 
     210                 :             : static bool twophaseExitRegistered = false;
     211                 :             : 
     212                 :             : static void PrepareRedoRemoveFull(FullTransactionId fxid, bool giveWarning);
     213                 :             : static void RecordTransactionCommitPrepared(TransactionId xid,
     214                 :             :                                             int nchildren,
     215                 :             :                                             TransactionId *children,
     216                 :             :                                             int nrels,
     217                 :             :                                             RelFileLocator *rels,
     218                 :             :                                             int nstats,
     219                 :             :                                             xl_xact_stats_item *stats,
     220                 :             :                                             int ninvalmsgs,
     221                 :             :                                             SharedInvalidationMessage *invalmsgs,
     222                 :             :                                             bool initfileinval,
     223                 :             :                                             const char *gid);
     224                 :             : static void RecordTransactionAbortPrepared(TransactionId xid,
     225                 :             :                                            int nchildren,
     226                 :             :                                            TransactionId *children,
     227                 :             :                                            int nrels,
     228                 :             :                                            RelFileLocator *rels,
     229                 :             :                                            int nstats,
     230                 :             :                                            xl_xact_stats_item *stats,
     231                 :             :                                            const char *gid);
     232                 :             : static void ProcessRecords(char *bufptr, FullTransactionId fxid,
     233                 :             :                            const TwoPhaseCallback callbacks[]);
     234                 :             : static void RemoveGXact(GlobalTransaction gxact);
     235                 :             : 
     236                 :             : static void XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, size_t *len);
     237                 :             : static char *ProcessTwoPhaseBuffer(FullTransactionId fxid,
     238                 :             :                                    XLogRecPtr prepare_start_lsn,
     239                 :             :                                    bool fromdisk, bool setParent, bool setNextXid);
     240                 :             : static void MarkAsPreparingGuts(GlobalTransaction gxact, FullTransactionId fxid,
     241                 :             :                                 const char *gid, TimestampTz prepared_at, Oid owner,
     242                 :             :                                 Oid databaseid);
     243                 :             : static void RemoveTwoPhaseFile(FullTransactionId fxid, bool giveWarning);
     244                 :             : static void RecreateTwoPhaseFile(FullTransactionId fxid, const void *content, size_t len);
     245                 :             : 
     246                 :             : /*
     247                 :             :  * Register shared memory for two-phase state.
     248                 :             :  */
     249                 :             : static void
     250                 :        1332 : TwoPhaseShmemRequest(void *arg)
     251                 :             : {
     252                 :             :     Size        size;
     253                 :             : 
     254                 :             :     /* Need the fixed struct, the array of pointers, and the GTD structs */
     255                 :        1332 :     size = offsetof(TwoPhaseStateData, prepXacts);
     256                 :        1332 :     size = add_size(size, mul_size(max_prepared_xacts,
     257                 :             :                                    sizeof(GlobalTransaction)));
     258                 :        1332 :     size = MAXALIGN(size);
     259                 :        1332 :     size = add_size(size, mul_size(max_prepared_xacts,
     260                 :             :                                    sizeof(GlobalTransactionData)));
     261                 :        1332 :     ShmemRequestStruct(.name = "Prepared Transaction Table",
     262                 :             :                        .size = size,
     263                 :             :                        .ptr = (void **) &TwoPhaseState,
     264                 :             :         );
     265                 :        1332 : }
     266                 :             : 
     267                 :             : /*
     268                 :             :  * Initialize shared memory for two-phase state.
     269                 :             :  */
     270                 :             : static void
     271                 :        1328 : TwoPhaseShmemInit(void *arg)
     272                 :             : {
     273                 :             :     GlobalTransaction gxacts;
     274                 :             :     int         i;
     275                 :             : 
     276                 :        1328 :     TwoPhaseState->freeGXacts = NULL;
     277                 :        1328 :     TwoPhaseState->numPrepXacts = 0;
     278                 :             : 
     279                 :             :     /*
     280                 :             :      * Initialize the linked list of free GlobalTransactionData structs
     281                 :             :      */
     282                 :        1328 :     gxacts = (GlobalTransaction)
     283                 :        1328 :         ((char *) TwoPhaseState +
     284                 :        1328 :          MAXALIGN(offsetof(TwoPhaseStateData, prepXacts) +
     285                 :             :                   sizeof(GlobalTransaction) * max_prepared_xacts));
     286         [ +  + ]:        2243 :     for (i = 0; i < max_prepared_xacts; i++)
     287                 :             :     {
     288                 :             :         /* insert into linked list */
     289                 :         915 :         gxacts[i].next = TwoPhaseState->freeGXacts;
     290                 :         915 :         TwoPhaseState->freeGXacts = &gxacts[i];
     291                 :             : 
     292                 :             :         /* associate it with a PGPROC assigned by ProcGlobalShmemInit */
     293                 :         915 :         gxacts[i].pgprocno = GetNumberFromPGProc(&PreparedXactProcs[i]);
     294                 :             :     }
     295                 :        1328 : }
     296                 :             : 
     297                 :             : /*
     298                 :             :  * Exit hook to unlock the global transaction entry we're working on.
     299                 :             :  */
     300                 :             : static void
     301                 :         149 : AtProcExit_Twophase(int code, Datum arg)
     302                 :             : {
     303                 :             :     /* same logic as abort */
     304                 :         149 :     AtAbort_Twophase();
     305                 :         149 : }
     306                 :             : 
     307                 :             : /*
     308                 :             :  * Abort hook to unlock the global transaction entry we're working on.
     309                 :             :  */
     310                 :             : void
     311                 :       36266 : AtAbort_Twophase(void)
     312                 :             : {
     313         [ +  + ]:       36266 :     if (MyLockedGxact == NULL)
     314                 :       36264 :         return;
     315                 :             : 
     316                 :             :     /*
     317                 :             :      * What to do with the locked global transaction entry?  If we were in the
     318                 :             :      * process of preparing the transaction, but haven't written the WAL
     319                 :             :      * record and state file yet, the transaction must not be considered as
     320                 :             :      * prepared.  Likewise, if we are in the process of finishing an
     321                 :             :      * already-prepared transaction, and fail after having already written the
     322                 :             :      * 2nd phase commit or rollback record to the WAL, the transaction should
     323                 :             :      * not be considered as prepared anymore.  In those cases, just remove the
     324                 :             :      * entry from shared memory.
     325                 :             :      *
     326                 :             :      * Otherwise, the entry must be left in place so that the transaction can
     327                 :             :      * be finished later, so just unlock it.
     328                 :             :      *
     329                 :             :      * If we abort during prepare, after having written the WAL record, we
     330                 :             :      * might not have transferred all locks and other state to the prepared
     331                 :             :      * transaction yet.  Likewise, if we abort during commit or rollback,
     332                 :             :      * after having written the WAL record, we might not have released all the
     333                 :             :      * resources held by the transaction yet.  In those cases, the in-memory
     334                 :             :      * state can be wrong, but it's too late to back out.
     335                 :             :      */
     336                 :           2 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
     337         [ +  - ]:           2 :     if (!MyLockedGxact->valid)
     338                 :           2 :         RemoveGXact(MyLockedGxact);
     339                 :             :     else
     340                 :           0 :         MyLockedGxact->locking_backend = INVALID_PROC_NUMBER;
     341                 :           2 :     LWLockRelease(TwoPhaseStateLock);
     342                 :             : 
     343                 :           2 :     MyLockedGxact = NULL;
     344                 :             : }
     345                 :             : 
     346                 :             : /*
     347                 :             :  * This is called after we have finished transferring state to the prepared
     348                 :             :  * PGPROC entry.
     349                 :             :  */
     350                 :             : void
     351                 :         349 : PostPrepare_Twophase(void)
     352                 :             : {
     353                 :         349 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
     354                 :         349 :     MyLockedGxact->locking_backend = INVALID_PROC_NUMBER;
     355                 :         349 :     LWLockRelease(TwoPhaseStateLock);
     356                 :             : 
     357                 :         349 :     MyLockedGxact = NULL;
     358                 :         349 : }
     359                 :             : 
     360                 :             : 
     361                 :             : /*
     362                 :             :  * MarkAsPreparing
     363                 :             :  *      Reserve the GID for the given transaction.
     364                 :             :  */
     365                 :             : GlobalTransaction
     366                 :         335 : MarkAsPreparing(FullTransactionId fxid, const char *gid,
     367                 :             :                 TimestampTz prepared_at, Oid owner, Oid databaseid)
     368                 :             : {
     369                 :             :     GlobalTransaction gxact;
     370                 :             :     int         i;
     371                 :             : 
     372         [ -  + ]:         335 :     if (strlen(gid) >= GIDSIZE)
     373         [ #  # ]:           0 :         ereport(ERROR,
     374                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     375                 :             :                  errmsg("transaction identifier \"%s\" is too long",
     376                 :             :                         gid)));
     377                 :             : 
     378                 :             :     /* fail immediately if feature is disabled */
     379         [ +  + ]:         335 :     if (max_prepared_xacts == 0)
     380         [ +  - ]:          16 :         ereport(ERROR,
     381                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     382                 :             :                  errmsg("prepared transactions are disabled"),
     383                 :             :                  errhint("Set \"max_prepared_transactions\" to a nonzero value.")));
     384                 :             : 
     385                 :             :     /* on first call, register the exit hook */
     386         [ +  + ]:         319 :     if (!twophaseExitRegistered)
     387                 :             :     {
     388                 :          84 :         before_shmem_exit(AtProcExit_Twophase, 0);
     389                 :          84 :         twophaseExitRegistered = true;
     390                 :             :     }
     391                 :             : 
     392                 :         319 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
     393                 :             : 
     394                 :             :     /* Check for conflicting GID */
     395         [ +  + ]:         548 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
     396                 :             :     {
     397                 :         231 :         gxact = TwoPhaseState->prepXacts[i];
     398         [ +  + ]:         231 :         if (strcmp(gxact->gid, gid) == 0)
     399                 :             :         {
     400         [ +  - ]:           2 :             ereport(ERROR,
     401                 :             :                     (errcode(ERRCODE_DUPLICATE_OBJECT),
     402                 :             :                      errmsg("transaction identifier \"%s\" is already in use",
     403                 :             :                             gid)));
     404                 :             :         }
     405                 :             :     }
     406                 :             : 
     407                 :             :     /* Get a free gxact from the freelist */
     408         [ -  + ]:         317 :     if (TwoPhaseState->freeGXacts == NULL)
     409         [ #  # ]:           0 :         ereport(ERROR,
     410                 :             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
     411                 :             :                  errmsg("maximum number of prepared transactions reached"),
     412                 :             :                  errhint("Increase \"max_prepared_transactions\" (currently %d).",
     413                 :             :                          max_prepared_xacts)));
     414                 :         317 :     gxact = TwoPhaseState->freeGXacts;
     415                 :         317 :     TwoPhaseState->freeGXacts = gxact->next;
     416                 :             : 
     417                 :         317 :     MarkAsPreparingGuts(gxact, fxid, gid, prepared_at, owner, databaseid);
     418                 :             : 
     419                 :         317 :     gxact->ondisk = false;
     420                 :             : 
     421                 :             :     /* And insert it into the active array */
     422                 :             :     Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
     423                 :         317 :     TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
     424                 :             : 
     425                 :         317 :     LWLockRelease(TwoPhaseStateLock);
     426                 :             : 
     427                 :         317 :     return gxact;
     428                 :             : }
     429                 :             : 
     430                 :             : /*
     431                 :             :  * MarkAsPreparingGuts
     432                 :             :  *
     433                 :             :  * This uses a gxact struct and puts it into the active array.
     434                 :             :  * NOTE: this is also used when reloading a gxact after a crash; so avoid
     435                 :             :  * assuming that we can use very much backend context.
     436                 :             :  *
     437                 :             :  * Note: This function should be called with appropriate locks held.
     438                 :             :  */
     439                 :             : static void
     440                 :         351 : MarkAsPreparingGuts(GlobalTransaction gxact, FullTransactionId fxid,
     441                 :             :                     const char *gid, TimestampTz prepared_at, Oid owner,
     442                 :             :                     Oid databaseid)
     443                 :             : {
     444                 :             :     PGPROC     *proc;
     445                 :             :     int         i;
     446                 :         351 :     TransactionId xid = XidFromFullTransactionId(fxid);
     447                 :             : 
     448                 :             :     Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
     449                 :             : 
     450                 :             :     Assert(gxact != NULL);
     451                 :         351 :     proc = GetPGProcByNumber(gxact->pgprocno);
     452                 :             : 
     453                 :             :     /* Initialize the PGPROC entry */
     454   [ +  -  +  -  :       39663 :     MemSet(proc, 0, sizeof(PGPROC));
          +  -  +  -  +  
                      + ]
     455                 :         351 :     proc->waitStatus = PROC_WAIT_STATUS_OK;
     456         [ +  + ]:         351 :     if (LocalTransactionIdIsValid(MyProc->vxid.lxid))
     457                 :             :     {
     458                 :             :         /* clone VXID, for TwoPhaseGetXidByVirtualXID() to find */
     459                 :         317 :         proc->vxid.lxid = MyProc->vxid.lxid;
     460                 :         317 :         proc->vxid.procNumber = MyProcNumber;
     461                 :             :     }
     462                 :             :     else
     463                 :             :     {
     464                 :             :         Assert(AmStartupProcess() || !IsPostmasterEnvironment);
     465                 :             :         /* GetLockConflicts() uses this to specify a wait on the XID */
     466                 :          34 :         proc->vxid.lxid = xid;
     467                 :          34 :         proc->vxid.procNumber = INVALID_PROC_NUMBER;
     468                 :             :     }
     469                 :         351 :     proc->xid = xid;
     470                 :             :     Assert(proc->xmin == InvalidTransactionId);
     471                 :         351 :     proc->delayChkptFlags = 0;
     472                 :         351 :     proc->statusFlags = 0;
     473                 :         351 :     proc->pid = 0;
     474                 :         351 :     proc->databaseId = databaseid;
     475                 :         351 :     proc->roleId = owner;
     476                 :         351 :     proc->tempNamespaceId = InvalidOid;
     477                 :         351 :     proc->backendType = B_INVALID;
     478                 :         351 :     proc->lwWaiting = LW_WS_NOT_WAITING;
     479                 :         351 :     proc->lwWaitMode = 0;
     480                 :         351 :     proc->waitLock = NULL;
     481                 :         351 :     dlist_node_init(&proc->waitLink);
     482                 :         351 :     proc->waitProcLock = NULL;
     483                 :         351 :     pg_atomic_init_u64(&proc->waitStart, 0);
     484         [ +  + ]:        5967 :     for (i = 0; i < NUM_LOCK_PARTITIONS; i++)
     485                 :        5616 :         dlist_init(&proc->myProcLocks[i]);
     486                 :             :     /* subxid data must be filled later by GXactLoadSubxactData */
     487                 :         351 :     proc->subxidStatus.overflowed = false;
     488                 :         351 :     proc->subxidStatus.count = 0;
     489                 :             : 
     490                 :         351 :     gxact->prepared_at = prepared_at;
     491                 :         351 :     gxact->fxid = fxid;
     492                 :         351 :     gxact->owner = owner;
     493                 :         351 :     gxact->locking_backend = MyProcNumber;
     494                 :         351 :     gxact->valid = false;
     495                 :         351 :     gxact->inredo = false;
     496                 :         351 :     strlcpy(gxact->gid, gid, GIDSIZE);
     497                 :             : 
     498                 :             :     /*
     499                 :             :      * Remember that we have this GlobalTransaction entry locked for us. If we
     500                 :             :      * abort after this, we must release it.
     501                 :             :      */
     502                 :         351 :     MyLockedGxact = gxact;
     503                 :         351 : }
     504                 :             : 
     505                 :             : /*
     506                 :             :  * GXactLoadSubxactData
     507                 :             :  *
     508                 :             :  * If the transaction being persisted had any subtransactions, this must
     509                 :             :  * be called before MarkAsPrepared() to load information into the dummy
     510                 :             :  * PGPROC.
     511                 :             :  */
     512                 :             : static void
     513                 :         148 : GXactLoadSubxactData(GlobalTransaction gxact, int nsubxacts,
     514                 :             :                      TransactionId *children)
     515                 :             : {
     516                 :         148 :     PGPROC     *proc = GetPGProcByNumber(gxact->pgprocno);
     517                 :             : 
     518                 :             :     /* We need no extra lock since the GXACT isn't valid yet */
     519         [ +  + ]:         148 :     if (nsubxacts > PGPROC_MAX_CACHED_SUBXIDS)
     520                 :             :     {
     521                 :           4 :         proc->subxidStatus.overflowed = true;
     522                 :           4 :         nsubxacts = PGPROC_MAX_CACHED_SUBXIDS;
     523                 :             :     }
     524         [ +  + ]:         148 :     if (nsubxacts > 0)
     525                 :             :     {
     526                 :         130 :         memcpy(proc->subxids.xids, children,
     527                 :             :                nsubxacts * sizeof(TransactionId));
     528                 :         130 :         proc->subxidStatus.count = nsubxacts;
     529                 :             :     }
     530                 :         148 : }
     531                 :             : 
     532                 :             : /*
     533                 :             :  * MarkAsPrepared
     534                 :             :  *      Mark the GXACT as fully valid, and enter it into the global ProcArray.
     535                 :             :  *
     536                 :             :  * lock_held indicates whether caller already holds TwoPhaseStateLock.
     537                 :             :  */
     538                 :             : static void
     539                 :         349 : MarkAsPrepared(GlobalTransaction gxact, bool lock_held)
     540                 :             : {
     541                 :             :     /* Lock here may be overkill, but I'm not convinced of that ... */
     542         [ +  + ]:         349 :     if (!lock_held)
     543                 :         315 :         LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
     544                 :             :     Assert(!gxact->valid);
     545                 :         349 :     gxact->valid = true;
     546         [ +  + ]:         349 :     if (!lock_held)
     547                 :         315 :         LWLockRelease(TwoPhaseStateLock);
     548                 :             : 
     549                 :             :     /*
     550                 :             :      * Put it into the global ProcArray so TransactionIdIsInProgress considers
     551                 :             :      * the XID as still running.
     552                 :             :      */
     553                 :         349 :     ProcArrayAdd(GetPGProcByNumber(gxact->pgprocno));
     554                 :         349 : }
     555                 :             : 
     556                 :             : /*
     557                 :             :  * LockGXact
     558                 :             :  *      Locate the prepared transaction and mark it busy for COMMIT or PREPARE.
     559                 :             :  */
     560                 :             : static GlobalTransaction
     561                 :         335 : LockGXact(const char *gid, Oid user)
     562                 :             : {
     563                 :             :     int         i;
     564                 :             : 
     565                 :             :     /* on first call, register the exit hook */
     566         [ +  + ]:         335 :     if (!twophaseExitRegistered)
     567                 :             :     {
     568                 :          65 :         before_shmem_exit(AtProcExit_Twophase, 0);
     569                 :          65 :         twophaseExitRegistered = true;
     570                 :             :     }
     571                 :             : 
     572                 :         335 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
     573                 :             : 
     574         [ +  + ]:         531 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
     575                 :             :     {
     576                 :         517 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
     577                 :         517 :         PGPROC     *proc = GetPGProcByNumber(gxact->pgprocno);
     578                 :             : 
     579                 :             :         /* Ignore not-yet-valid GIDs */
     580         [ -  + ]:         517 :         if (!gxact->valid)
     581                 :           0 :             continue;
     582         [ +  + ]:         517 :         if (strcmp(gxact->gid, gid) != 0)
     583                 :         196 :             continue;
     584                 :             : 
     585                 :             :         /* Found it, but has someone else got it locked? */
     586         [ -  + ]:         321 :         if (gxact->locking_backend != INVALID_PROC_NUMBER)
     587         [ #  # ]:           0 :             ereport(ERROR,
     588                 :             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     589                 :             :                      errmsg("prepared transaction with identifier \"%s\" is busy",
     590                 :             :                             gid)));
     591                 :             : 
     592   [ -  +  -  - ]:         321 :         if (user != gxact->owner && !superuser_arg(user))
     593         [ #  # ]:           0 :             ereport(ERROR,
     594                 :             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     595                 :             :                      errmsg("permission denied to finish prepared transaction"),
     596                 :             :                      errhint("Must be superuser or the user that prepared the transaction.")));
     597                 :             : 
     598                 :             :         /*
     599                 :             :          * Note: it probably would be possible to allow committing from
     600                 :             :          * another database; but at the moment NOTIFY is known not to work and
     601                 :             :          * there may be some other issues as well.  Hence disallow until
     602                 :             :          * someone gets motivated to make it work.
     603                 :             :          */
     604         [ -  + ]:         321 :         if (MyDatabaseId != proc->databaseId)
     605         [ #  # ]:           0 :             ereport(ERROR,
     606                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     607                 :             :                      errmsg("prepared transaction belongs to another database"),
     608                 :             :                      errhint("Connect to the database where the transaction was prepared to finish it.")));
     609                 :             : 
     610                 :             :         /* OK for me to lock it */
     611                 :         321 :         gxact->locking_backend = MyProcNumber;
     612                 :         321 :         MyLockedGxact = gxact;
     613                 :             : 
     614                 :         321 :         LWLockRelease(TwoPhaseStateLock);
     615                 :             : 
     616                 :         321 :         return gxact;
     617                 :             :     }
     618                 :             : 
     619                 :          14 :     LWLockRelease(TwoPhaseStateLock);
     620                 :             : 
     621         [ +  - ]:          14 :     ereport(ERROR,
     622                 :             :             (errcode(ERRCODE_UNDEFINED_OBJECT),
     623                 :             :              errmsg("prepared transaction with identifier \"%s\" does not exist",
     624                 :             :                     gid)));
     625                 :             : 
     626                 :             :     /* NOTREACHED */
     627                 :             :     return NULL;
     628                 :             : }
     629                 :             : 
     630                 :             : /*
     631                 :             :  * RemoveGXact
     632                 :             :  *      Remove the prepared transaction from the shared memory array.
     633                 :             :  *
     634                 :             :  * NB: caller should have already removed it from ProcArray
     635                 :             :  */
     636                 :             : static void
     637                 :         385 : RemoveGXact(GlobalTransaction gxact)
     638                 :             : {
     639                 :             :     int         i;
     640                 :             : 
     641                 :             :     Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
     642                 :             : 
     643         [ +  - ]:         573 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
     644                 :             :     {
     645         [ +  + ]:         573 :         if (gxact == TwoPhaseState->prepXacts[i])
     646                 :             :         {
     647                 :             :             /* remove from the active array */
     648                 :         385 :             TwoPhaseState->numPrepXacts--;
     649                 :         385 :             TwoPhaseState->prepXacts[i] = TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts];
     650                 :             : 
     651                 :             :             /* and put it back in the freelist */
     652                 :         385 :             gxact->next = TwoPhaseState->freeGXacts;
     653                 :         385 :             TwoPhaseState->freeGXacts = gxact;
     654                 :             : 
     655                 :         385 :             return;
     656                 :             :         }
     657                 :             :     }
     658                 :             : 
     659         [ #  # ]:           0 :     elog(ERROR, "failed to find %p in GlobalTransaction array", gxact);
     660                 :             : }
     661                 :             : 
     662                 :             : /*
     663                 :             :  * Returns an array of all prepared transactions for the user-level
     664                 :             :  * function pg_prepared_xact.
     665                 :             :  *
     666                 :             :  * The returned array and all its elements are copies of internal data
     667                 :             :  * structures, to minimize the time we need to hold the TwoPhaseStateLock.
     668                 :             :  *
     669                 :             :  * WARNING -- we return even those transactions that are not fully prepared
     670                 :             :  * yet.  The caller should filter them out if he doesn't want them.
     671                 :             :  *
     672                 :             :  * The returned array is palloc'd.
     673                 :             :  */
     674                 :             : static int
     675                 :         116 : GetPreparedTransactionList(GlobalTransaction *gxacts)
     676                 :             : {
     677                 :             :     GlobalTransaction array;
     678                 :             :     int         num;
     679                 :             :     int         i;
     680                 :             : 
     681                 :         116 :     LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
     682                 :             : 
     683         [ +  + ]:         116 :     if (TwoPhaseState->numPrepXacts == 0)
     684                 :             :     {
     685                 :          75 :         LWLockRelease(TwoPhaseStateLock);
     686                 :             : 
     687                 :          75 :         *gxacts = NULL;
     688                 :          75 :         return 0;
     689                 :             :     }
     690                 :             : 
     691                 :          41 :     num = TwoPhaseState->numPrepXacts;
     692                 :          41 :     array = palloc_array(GlobalTransactionData, num);
     693                 :          41 :     *gxacts = array;
     694         [ +  + ]:          87 :     for (i = 0; i < num; i++)
     695                 :          46 :         memcpy(array + i, TwoPhaseState->prepXacts[i],
     696                 :             :                sizeof(GlobalTransactionData));
     697                 :             : 
     698                 :          41 :     LWLockRelease(TwoPhaseStateLock);
     699                 :             : 
     700                 :          41 :     return num;
     701                 :             : }
     702                 :             : 
     703                 :             : 
     704                 :             : /* Working status for pg_prepared_xact */
     705                 :             : typedef struct
     706                 :             : {
     707                 :             :     GlobalTransaction array;
     708                 :             :     int         ngxacts;
     709                 :             :     int         currIdx;
     710                 :             : } Working_State;
     711                 :             : 
     712                 :             : /*
     713                 :             :  * pg_prepared_xact
     714                 :             :  *      Produce a view with one row per prepared transaction.
     715                 :             :  *
     716                 :             :  * This function is here so we don't have to export the
     717                 :             :  * GlobalTransactionData struct definition.
     718                 :             :  */
     719                 :             : Datum
     720                 :         162 : pg_prepared_xact(PG_FUNCTION_ARGS)
     721                 :             : {
     722                 :             :     FuncCallContext *funcctx;
     723                 :             :     Working_State *status;
     724                 :             : 
     725         [ +  + ]:         162 :     if (SRF_IS_FIRSTCALL())
     726                 :             :     {
     727                 :             :         TupleDesc   tupdesc;
     728                 :             :         MemoryContext oldcontext;
     729                 :             : 
     730                 :             :         /* create a function context for cross-call persistence */
     731                 :         116 :         funcctx = SRF_FIRSTCALL_INIT();
     732                 :             : 
     733                 :             :         /*
     734                 :             :          * Switch to memory context appropriate for multiple function calls
     735                 :             :          */
     736                 :         116 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
     737                 :             : 
     738                 :             :         /* build tupdesc for result tuples */
     739                 :             :         /* this had better match pg_prepared_xacts view in system_views.sql */
     740                 :         116 :         tupdesc = CreateTemplateTupleDesc(5);
     741                 :         116 :         TupleDescInitEntry(tupdesc, (AttrNumber) 1, "transaction",
     742                 :             :                            XIDOID, -1, 0);
     743                 :         116 :         TupleDescInitEntry(tupdesc, (AttrNumber) 2, "gid",
     744                 :             :                            TEXTOID, -1, 0);
     745                 :         116 :         TupleDescInitEntry(tupdesc, (AttrNumber) 3, "prepared",
     746                 :             :                            TIMESTAMPTZOID, -1, 0);
     747                 :         116 :         TupleDescInitEntry(tupdesc, (AttrNumber) 4, "ownerid",
     748                 :             :                            OIDOID, -1, 0);
     749                 :         116 :         TupleDescInitEntry(tupdesc, (AttrNumber) 5, "dbid",
     750                 :             :                            OIDOID, -1, 0);
     751                 :             : 
     752                 :         116 :         TupleDescFinalize(tupdesc);
     753                 :         116 :         funcctx->tuple_desc = BlessTupleDesc(tupdesc);
     754                 :             : 
     755                 :             :         /*
     756                 :             :          * Collect all the 2PC status information that we will format and send
     757                 :             :          * out as a result set.
     758                 :             :          */
     759                 :         116 :         status = palloc_object(Working_State);
     760                 :         116 :         funcctx->user_fctx = status;
     761                 :             : 
     762                 :         116 :         status->ngxacts = GetPreparedTransactionList(&status->array);
     763                 :         116 :         status->currIdx = 0;
     764                 :             : 
     765                 :         116 :         MemoryContextSwitchTo(oldcontext);
     766                 :             :     }
     767                 :             : 
     768                 :         162 :     funcctx = SRF_PERCALL_SETUP();
     769                 :         162 :     status = (Working_State *) funcctx->user_fctx;
     770                 :             : 
     771   [ +  +  +  + ]:         162 :     while (status->array != NULL && status->currIdx < status->ngxacts)
     772                 :             :     {
     773                 :          46 :         GlobalTransaction gxact = &status->array[status->currIdx++];
     774                 :          46 :         PGPROC     *proc = GetPGProcByNumber(gxact->pgprocno);
     775                 :          46 :         Datum       values[5] = {0};
     776                 :          46 :         bool        nulls[5] = {0};
     777                 :             :         HeapTuple   tuple;
     778                 :             :         Datum       result;
     779                 :             : 
     780         [ -  + ]:          46 :         if (!gxact->valid)
     781                 :           0 :             continue;
     782                 :             : 
     783                 :             :         /*
     784                 :             :          * Form tuple with appropriate data.
     785                 :             :          */
     786                 :             : 
     787                 :          46 :         values[0] = TransactionIdGetDatum(proc->xid);
     788                 :          46 :         values[1] = CStringGetTextDatum(gxact->gid);
     789                 :          46 :         values[2] = TimestampTzGetDatum(gxact->prepared_at);
     790                 :          46 :         values[3] = ObjectIdGetDatum(gxact->owner);
     791                 :          46 :         values[4] = ObjectIdGetDatum(proc->databaseId);
     792                 :             : 
     793                 :          46 :         tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
     794                 :          46 :         result = HeapTupleGetDatum(tuple);
     795                 :          46 :         SRF_RETURN_NEXT(funcctx, result);
     796                 :             :     }
     797                 :             : 
     798                 :         116 :     SRF_RETURN_DONE(funcctx);
     799                 :             : }
     800                 :             : 
     801                 :             : /*
     802                 :             :  * TwoPhaseGetGXact
     803                 :             :  *      Get the GlobalTransaction struct for a prepared transaction
     804                 :             :  *      specified by XID
     805                 :             :  *
     806                 :             :  * If lock_held is set to true, TwoPhaseStateLock will not be taken, so the
     807                 :             :  * caller had better hold it.
     808                 :             :  */
     809                 :             : static GlobalTransaction
     810                 :        1461 : TwoPhaseGetGXact(FullTransactionId fxid, bool lock_held)
     811                 :             : {
     812                 :        1461 :     GlobalTransaction result = NULL;
     813                 :             :     int         i;
     814                 :             : 
     815                 :             :     static FullTransactionId cached_fxid = {InvalidTransactionId};
     816                 :             :     static GlobalTransaction cached_gxact = NULL;
     817                 :             : 
     818                 :             :     Assert(!lock_held || LWLockHeldByMe(TwoPhaseStateLock));
     819                 :             : 
     820                 :             :     /*
     821                 :             :      * During a recovery, COMMIT PREPARED, or ABORT PREPARED, we'll be called
     822                 :             :      * repeatedly for the same XID.  We can save work with a simple cache.
     823                 :             :      */
     824         [ +  + ]:        1461 :     if (FullTransactionIdEquals(fxid, cached_fxid))
     825                 :        1034 :         return cached_gxact;
     826                 :             : 
     827         [ +  + ]:         427 :     if (!lock_held)
     828                 :         349 :         LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
     829                 :             : 
     830         [ +  - ]:         660 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
     831                 :             :     {
     832                 :         660 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
     833                 :             : 
     834         [ +  + ]:         660 :         if (FullTransactionIdEquals(gxact->fxid, fxid))
     835                 :             :         {
     836                 :         427 :             result = gxact;
     837                 :         427 :             break;
     838                 :             :         }
     839                 :             :     }
     840                 :             : 
     841         [ +  + ]:         427 :     if (!lock_held)
     842                 :         349 :         LWLockRelease(TwoPhaseStateLock);
     843                 :             : 
     844         [ -  + ]:         427 :     if (result == NULL)         /* should not happen */
     845         [ #  # ]:           0 :         elog(ERROR, "failed to find GlobalTransaction for xid %u",
     846                 :             :              XidFromFullTransactionId(fxid));
     847                 :             : 
     848                 :         427 :     cached_fxid = fxid;
     849                 :         427 :     cached_gxact = result;
     850                 :             : 
     851                 :         427 :     return result;
     852                 :             : }
     853                 :             : 
     854                 :             : /*
     855                 :             :  * TwoPhaseGetXidByVirtualXID
     856                 :             :  *      Lookup VXID among xacts prepared since last startup.
     857                 :             :  *
     858                 :             :  * (This won't find recovered xacts.)  If more than one matches, return any
     859                 :             :  * and set "have_more" to true.  To witness multiple matches, a single
     860                 :             :  * proc number must consume 2^32 LXIDs, with no intervening database restart.
     861                 :             :  */
     862                 :             : TransactionId
     863                 :         119 : TwoPhaseGetXidByVirtualXID(VirtualTransactionId vxid,
     864                 :             :                            bool *have_more)
     865                 :             : {
     866                 :             :     int         i;
     867                 :         119 :     TransactionId result = InvalidTransactionId;
     868                 :             : 
     869                 :             :     Assert(VirtualTransactionIdIsValid(vxid));
     870                 :         119 :     LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
     871                 :             : 
     872         [ +  + ]:         204 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
     873                 :             :     {
     874                 :          85 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
     875                 :             :         PGPROC     *proc;
     876                 :             :         VirtualTransactionId proc_vxid;
     877                 :             : 
     878         [ -  + ]:          85 :         if (!gxact->valid)
     879                 :           0 :             continue;
     880                 :          85 :         proc = GetPGProcByNumber(gxact->pgprocno);
     881                 :          85 :         GET_VXID_FROM_PGPROC(proc_vxid, *proc);
     882   [ +  +  +  + ]:          85 :         if (VirtualTransactionIdEquals(vxid, proc_vxid))
     883                 :             :         {
     884                 :             :             /*
     885                 :             :              * Startup process sets proc->vxid.procNumber to
     886                 :             :              * INVALID_PROC_NUMBER.
     887                 :             :              */
     888                 :             :             Assert(!gxact->inredo);
     889                 :             : 
     890         [ -  + ]:          24 :             if (result != InvalidTransactionId)
     891                 :             :             {
     892                 :           0 :                 *have_more = true;
     893                 :           0 :                 break;
     894                 :             :             }
     895                 :          24 :             result = XidFromFullTransactionId(gxact->fxid);
     896                 :             :         }
     897                 :             :     }
     898                 :             : 
     899                 :         119 :     LWLockRelease(TwoPhaseStateLock);
     900                 :             : 
     901                 :         119 :     return result;
     902                 :             : }
     903                 :             : 
     904                 :             : /*
     905                 :             :  * TwoPhaseGetDummyProcNumber
     906                 :             :  *      Get the dummy proc number for prepared transaction
     907                 :             :  *
     908                 :             :  * Dummy proc numbers are similar to proc numbers of real backends.  They
     909                 :             :  * start at FIRST_PREPARED_XACT_PROC_NUMBER, and are unique across all
     910                 :             :  * currently active real backends and prepared transactions.  If lock_held is
     911                 :             :  * set to true, TwoPhaseStateLock will not be taken, so the caller had better
     912                 :             :  * hold it.
     913                 :             :  */
     914                 :             : ProcNumber
     915                 :         157 : TwoPhaseGetDummyProcNumber(FullTransactionId fxid, bool lock_held)
     916                 :             : {
     917                 :         157 :     GlobalTransaction gxact = TwoPhaseGetGXact(fxid, lock_held);
     918                 :             : 
     919                 :         157 :     return gxact->pgprocno;
     920                 :             : }
     921                 :             : 
     922                 :             : /*
     923                 :             :  * TwoPhaseGetDummyProc
     924                 :             :  *      Get the PGPROC that represents a prepared transaction
     925                 :             :  *
     926                 :             :  * If lock_held is set to true, TwoPhaseStateLock will not be taken, so the
     927                 :             :  * caller had better hold it.
     928                 :             :  */
     929                 :             : PGPROC *
     930                 :        1304 : TwoPhaseGetDummyProc(FullTransactionId fxid, bool lock_held)
     931                 :             : {
     932                 :        1304 :     GlobalTransaction gxact = TwoPhaseGetGXact(fxid, lock_held);
     933                 :             : 
     934                 :        1304 :     return GetPGProcByNumber(gxact->pgprocno);
     935                 :             : }
     936                 :             : 
     937                 :             : /************************************************************************/
     938                 :             : /* State file support                                                   */
     939                 :             : /************************************************************************/
     940                 :             : 
     941                 :             : /*
     942                 :             :  * Compute the FullTransactionId for the given TransactionId.
     943                 :             :  *
     944                 :             :  * This is safe if the xid has not yet reached COMMIT PREPARED or ROLLBACK
     945                 :             :  * PREPARED.  After those commands, concurrent vac_truncate_clog() may make
     946                 :             :  * the xid cease to qualify as allowable.  XXX Not all callers limit their
     947                 :             :  * calls accordingly.
     948                 :             :  */
     949                 :             : static inline FullTransactionId
     950                 :         267 : AdjustToFullTransactionId(TransactionId xid)
     951                 :             : {
     952                 :             :     Assert(TransactionIdIsValid(xid));
     953                 :         267 :     return FullTransactionIdFromAllowableAt(ReadNextFullTransactionId(), xid);
     954                 :             : }
     955                 :             : 
     956                 :             : static inline int
     957                 :         483 : TwoPhaseFilePath(char *path, FullTransactionId fxid)
     958                 :             : {
     959                 :         966 :     return snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%08X%08X",
     960                 :         483 :                     EpochFromFullTransactionId(fxid),
     961                 :         483 :                     XidFromFullTransactionId(fxid));
     962                 :             : }
     963                 :             : 
     964                 :             : /*
     965                 :             :  * 2PC state file format:
     966                 :             :  *
     967                 :             :  *  1. TwoPhaseFileHeader
     968                 :             :  *  2. TransactionId[] (subtransactions)
     969                 :             :  *  3. RelFileLocator[] (files to be deleted at commit)
     970                 :             :  *  4. RelFileLocator[] (files to be deleted at abort)
     971                 :             :  *  5. SharedInvalidationMessage[] (inval messages to be sent at commit)
     972                 :             :  *  6. TwoPhaseRecordOnDisk
     973                 :             :  *  7. ...
     974                 :             :  *  8. TwoPhaseRecordOnDisk (end sentinel, rmid == TWOPHASE_RM_END_ID)
     975                 :             :  *  9. checksum (CRC-32C)
     976                 :             :  *
     977                 :             :  * Each segment except the final checksum is MAXALIGN'd.
     978                 :             :  */
     979                 :             : 
     980                 :             : /*
     981                 :             :  * Header for a 2PC state file
     982                 :             :  */
     983                 :             : #define TWOPHASE_MAGIC  0x57F94534  /* format identifier */
     984                 :             : 
     985                 :             : typedef xl_xact_prepare TwoPhaseFileHeader;
     986                 :             : 
     987                 :             : /*
     988                 :             :  * Header for each record in a state file
     989                 :             :  *
     990                 :             :  * NOTE: len counts only the rmgr data, not the TwoPhaseRecordOnDisk header.
     991                 :             :  * The rmgr data will be stored starting on a MAXALIGN boundary.
     992                 :             :  */
     993                 :             : typedef struct TwoPhaseRecordOnDisk
     994                 :             : {
     995                 :             :     uint32      len;            /* length of rmgr data */
     996                 :             :     TwoPhaseRmgrId rmid;        /* resource manager for this record */
     997                 :             :     uint16      info;           /* flag bits for use by rmgr */
     998                 :             : } TwoPhaseRecordOnDisk;
     999                 :             : 
    1000                 :             : /*
    1001                 :             :  * During prepare, the state file is assembled in memory before writing it
    1002                 :             :  * to WAL and the actual state file.  We use a chain of StateFileChunk blocks
    1003                 :             :  * for that.
    1004                 :             :  */
    1005                 :             : typedef struct StateFileChunk
    1006                 :             : {
    1007                 :             :     char       *data;
    1008                 :             :     uint32      len;
    1009                 :             :     struct StateFileChunk *next;
    1010                 :             : } StateFileChunk;
    1011                 :             : 
    1012                 :             : static struct xllist
    1013                 :             : {
    1014                 :             :     StateFileChunk *head;       /* first data block in the chain */
    1015                 :             :     StateFileChunk *tail;       /* last block in chain */
    1016                 :             :     uint32      num_chunks;
    1017                 :             :     uint32      bytes_free;     /* free bytes left in tail block */
    1018                 :             :     uint32      total_len;      /* total data bytes in chain */
    1019                 :             : }           records;
    1020                 :             : 
    1021                 :             : 
    1022                 :             : /*
    1023                 :             :  * Append a block of data to records data structure.
    1024                 :             :  *
    1025                 :             :  * NB: each block is padded to a MAXALIGN multiple.  This must be
    1026                 :             :  * accounted for when the file is later read!
    1027                 :             :  *
    1028                 :             :  * The data is copied, so the caller is free to modify it afterwards.
    1029                 :             :  */
    1030                 :             : static void
    1031                 :        3984 : save_state_data(const void *data, uint32 len)
    1032                 :             : {
    1033                 :        3984 :     uint32      padlen = MAXALIGN(len);
    1034                 :             : 
    1035         [ +  + ]:        3984 :     if (padlen > records.bytes_free)
    1036                 :             :     {
    1037                 :          79 :         records.tail->next = palloc0_object(StateFileChunk);
    1038                 :          79 :         records.tail = records.tail->next;
    1039                 :          79 :         records.tail->len = 0;
    1040                 :          79 :         records.tail->next = NULL;
    1041                 :          79 :         records.num_chunks++;
    1042                 :             : 
    1043                 :          79 :         records.bytes_free = Max(padlen, 512);
    1044                 :          79 :         records.tail->data = palloc(records.bytes_free);
    1045                 :             :     }
    1046                 :             : 
    1047                 :        3984 :     memcpy(records.tail->data + records.tail->len, data, len);
    1048                 :        3984 :     records.tail->len += padlen;
    1049                 :        3984 :     records.bytes_free -= padlen;
    1050                 :        3984 :     records.total_len += padlen;
    1051                 :        3984 : }
    1052                 :             : 
    1053                 :             : /*
    1054                 :             :  * Start preparing a state file.
    1055                 :             :  *
    1056                 :             :  * Initializes data structure and inserts the 2PC file header record.
    1057                 :             :  */
    1058                 :             : void
    1059                 :         317 : StartPrepare(GlobalTransaction gxact)
    1060                 :             : {
    1061                 :         317 :     PGPROC     *proc = GetPGProcByNumber(gxact->pgprocno);
    1062                 :         317 :     TransactionId xid = XidFromFullTransactionId(gxact->fxid);
    1063                 :             :     TwoPhaseFileHeader hdr;
    1064                 :             :     TransactionId *children;
    1065                 :             :     RelFileLocator *commitrels;
    1066                 :             :     RelFileLocator *abortrels;
    1067                 :         317 :     xl_xact_stats_item *abortstats = NULL;
    1068                 :         317 :     xl_xact_stats_item *commitstats = NULL;
    1069                 :             :     SharedInvalidationMessage *invalmsgs;
    1070                 :             : 
    1071                 :             :     /* Initialize linked list */
    1072                 :         317 :     records.head = palloc0_object(StateFileChunk);
    1073                 :         317 :     records.head->len = 0;
    1074                 :         317 :     records.head->next = NULL;
    1075                 :             : 
    1076                 :         317 :     records.bytes_free = Max(sizeof(TwoPhaseFileHeader), 512);
    1077                 :         317 :     records.head->data = palloc(records.bytes_free);
    1078                 :             : 
    1079                 :         317 :     records.tail = records.head;
    1080                 :         317 :     records.num_chunks = 1;
    1081                 :             : 
    1082                 :         317 :     records.total_len = 0;
    1083                 :             : 
    1084                 :             :     /* Create header */
    1085                 :         317 :     hdr.magic = TWOPHASE_MAGIC;
    1086                 :         317 :     hdr.total_len = 0;          /* EndPrepare will fill this in */
    1087                 :         317 :     hdr.xid = xid;
    1088                 :         317 :     hdr.database = proc->databaseId;
    1089                 :         317 :     hdr.prepared_at = gxact->prepared_at;
    1090                 :         317 :     hdr.owner = gxact->owner;
    1091                 :         317 :     hdr.nsubxacts = xactGetCommittedChildren(&children);
    1092                 :         317 :     hdr.ncommitrels = smgrGetPendingDeletes(true, &commitrels);
    1093                 :         317 :     hdr.nabortrels = smgrGetPendingDeletes(false, &abortrels);
    1094                 :         317 :     hdr.ncommitstats =
    1095                 :         317 :         pgstat_get_transactional_drops(true, &commitstats);
    1096                 :         317 :     hdr.nabortstats =
    1097                 :         317 :         pgstat_get_transactional_drops(false, &abortstats);
    1098                 :         317 :     hdr.ninvalmsgs = xactGetCommittedInvalidationMessages(&invalmsgs,
    1099                 :             :                                                           &hdr.initfileinval);
    1100                 :         317 :     hdr.gidlen = strlen(gxact->gid) + 1; /* Include '\0' */
    1101                 :             :     /* EndPrepare will fill the origin data, if necessary */
    1102                 :         317 :     hdr.origin_lsn = InvalidXLogRecPtr;
    1103                 :         317 :     hdr.origin_timestamp = 0;
    1104                 :             : 
    1105                 :         317 :     save_state_data(&hdr, sizeof(TwoPhaseFileHeader));
    1106                 :         317 :     save_state_data(gxact->gid, hdr.gidlen);
    1107                 :             : 
    1108                 :             :     /*
    1109                 :             :      * Add the additional info about subxacts, deletable files and cache
    1110                 :             :      * invalidation messages.
    1111                 :             :      */
    1112         [ +  + ]:         317 :     if (hdr.nsubxacts > 0)
    1113                 :             :     {
    1114                 :         114 :         save_state_data(children, hdr.nsubxacts * sizeof(TransactionId));
    1115                 :             :         /* While we have the child-xact data, stuff it in the gxact too */
    1116                 :         114 :         GXactLoadSubxactData(gxact, hdr.nsubxacts, children);
    1117                 :             :     }
    1118         [ +  + ]:         317 :     if (hdr.ncommitrels > 0)
    1119                 :             :     {
    1120                 :          21 :         save_state_data(commitrels, hdr.ncommitrels * sizeof(RelFileLocator));
    1121                 :          21 :         pfree(commitrels);
    1122                 :             :     }
    1123         [ +  + ]:         317 :     if (hdr.nabortrels > 0)
    1124                 :             :     {
    1125                 :          29 :         save_state_data(abortrels, hdr.nabortrels * sizeof(RelFileLocator));
    1126                 :          29 :         pfree(abortrels);
    1127                 :             :     }
    1128         [ +  + ]:         317 :     if (hdr.ncommitstats > 0)
    1129                 :             :     {
    1130                 :          21 :         save_state_data(commitstats,
    1131                 :          21 :                         hdr.ncommitstats * sizeof(xl_xact_stats_item));
    1132                 :          21 :         pfree(commitstats);
    1133                 :             :     }
    1134         [ +  + ]:         317 :     if (hdr.nabortstats > 0)
    1135                 :             :     {
    1136                 :          25 :         save_state_data(abortstats,
    1137                 :          25 :                         hdr.nabortstats * sizeof(xl_xact_stats_item));
    1138                 :          25 :         pfree(abortstats);
    1139                 :             :     }
    1140         [ +  + ]:         317 :     if (hdr.ninvalmsgs > 0)
    1141                 :             :     {
    1142                 :          37 :         save_state_data(invalmsgs,
    1143                 :          37 :                         hdr.ninvalmsgs * sizeof(SharedInvalidationMessage));
    1144                 :          37 :         pfree(invalmsgs);
    1145                 :             :     }
    1146                 :         317 : }
    1147                 :             : 
    1148                 :             : /*
    1149                 :             :  * Finish preparing state data and writing it to WAL.
    1150                 :             :  */
    1151                 :             : void
    1152                 :         315 : EndPrepare(GlobalTransaction gxact)
    1153                 :             : {
    1154                 :             :     TwoPhaseFileHeader *hdr;
    1155                 :             :     StateFileChunk *record;
    1156                 :             :     bool        replorigin;
    1157                 :             : 
    1158                 :             :     /* Add the end sentinel to the list of 2PC records */
    1159                 :         315 :     RegisterTwoPhaseRecord(TWOPHASE_RM_END_ID, 0,
    1160                 :             :                            NULL, 0);
    1161                 :             : 
    1162                 :             :     /* Go back and fill in total_len in the file header record */
    1163                 :         315 :     hdr = (TwoPhaseFileHeader *) records.head->data;
    1164                 :             :     Assert(hdr->magic == TWOPHASE_MAGIC);
    1165                 :         315 :     hdr->total_len = records.total_len + sizeof(pg_crc32c);
    1166                 :             : 
    1167         [ +  + ]:         341 :     replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
    1168         [ +  - ]:          26 :                   replorigin_xact_state.origin != DoNotReplicateId);
    1169                 :             : 
    1170         [ +  + ]:         315 :     if (replorigin)
    1171                 :             :     {
    1172                 :          26 :         hdr->origin_lsn = replorigin_xact_state.origin_lsn;
    1173                 :          26 :         hdr->origin_timestamp = replorigin_xact_state.origin_timestamp;
    1174                 :             :     }
    1175                 :             : 
    1176                 :             :     /*
    1177                 :             :      * If the data size exceeds MaxAllocSize, we won't be able to read it in
    1178                 :             :      * ReadTwoPhaseFile. Check for that now, rather than fail in the case
    1179                 :             :      * where we write data to file and then re-read at commit time.
    1180                 :             :      */
    1181         [ -  + ]:         315 :     if (hdr->total_len > MaxAllocSize)
    1182         [ #  # ]:           0 :         ereport(ERROR,
    1183                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1184                 :             :                  errmsg("two-phase state file maximum length exceeded")));
    1185                 :             : 
    1186                 :             :     /*
    1187                 :             :      * Now writing 2PC state data to WAL. We let the WAL's CRC protection
    1188                 :             :      * cover us, so no need to calculate a separate CRC.
    1189                 :             :      *
    1190                 :             :      * We have to set DELAY_CHKPT_START here, too; otherwise a checkpoint
    1191                 :             :      * starting immediately after the WAL record is inserted could complete
    1192                 :             :      * without fsync'ing our state file.  (This is essentially the same kind
    1193                 :             :      * of race condition as the COMMIT-to-clog-write case that
    1194                 :             :      * RecordTransactionCommit uses DELAY_CHKPT_IN_COMMIT for; see notes
    1195                 :             :      * there.) Note that DELAY_CHKPT_IN_COMMIT is used to find transactions in
    1196                 :             :      * the critical commit section. We need to know about such transactions
    1197                 :             :      * for conflict detection in logical replication. See
    1198                 :             :      * GetOldestActiveTransactionId(true, false) and its use.
    1199                 :             :      *
    1200                 :             :      * We save the PREPARE record's location in the gxact for later use by
    1201                 :             :      * CheckPointTwoPhase.
    1202                 :             :      */
    1203                 :         315 :     XLogEnsureRecordSpace(0, records.num_chunks);
    1204                 :             : 
    1205                 :         315 :     START_CRIT_SECTION();
    1206                 :             : 
    1207                 :             :     Assert((MyProc->delayChkptFlags & DELAY_CHKPT_START) == 0);
    1208                 :         315 :     MyProc->delayChkptFlags |= DELAY_CHKPT_START;
    1209                 :             : 
    1210                 :         315 :     XLogBeginInsert();
    1211         [ +  + ]:         709 :     for (record = records.head; record != NULL; record = record->next)
    1212                 :         394 :         XLogRegisterData(record->data, record->len);
    1213                 :             : 
    1214                 :         315 :     XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
    1215                 :             : 
    1216                 :         315 :     gxact->prepare_end_lsn = XLogInsert(RM_XACT_ID, XLOG_XACT_PREPARE);
    1217                 :             : 
    1218         [ +  + ]:         315 :     if (replorigin)
    1219                 :             :     {
    1220                 :             :         /* Move LSNs forward for this replication origin */
    1221                 :          26 :         replorigin_session_advance(replorigin_xact_state.origin_lsn,
    1222                 :             :                                    gxact->prepare_end_lsn);
    1223                 :             :     }
    1224                 :             : 
    1225                 :         315 :     XLogFlush(gxact->prepare_end_lsn);
    1226                 :             : 
    1227                 :             :     /* If we crash now, we have prepared: WAL replay will fix things */
    1228                 :             : 
    1229                 :             :     /* Store record's start location to read that later on Commit */
    1230                 :         315 :     gxact->prepare_start_lsn = ProcLastRecPtr;
    1231                 :             : 
    1232                 :             :     /*
    1233                 :             :      * Mark the prepared transaction as valid.  As soon as xact.c marks MyProc
    1234                 :             :      * as not running our XID (which it will do immediately after this
    1235                 :             :      * function returns), others can commit/rollback the xact.
    1236                 :             :      *
    1237                 :             :      * NB: a side effect of this is to make a dummy ProcArray entry for the
    1238                 :             :      * prepared XID.  This must happen before we clear the XID from MyProc /
    1239                 :             :      * ProcGlobal->xids[], else there is a window where the XID is not running
    1240                 :             :      * according to TransactionIdIsInProgress, and onlookers would be entitled
    1241                 :             :      * to assume the xact crashed.  Instead we have a window where the same
    1242                 :             :      * XID appears twice in ProcArray, which is OK.
    1243                 :             :      */
    1244                 :         315 :     MarkAsPrepared(gxact, false);
    1245                 :             : 
    1246                 :             :     /*
    1247                 :             :      * Now we can mark ourselves as out of the commit critical section: a
    1248                 :             :      * checkpoint starting after this will certainly see the gxact as a
    1249                 :             :      * candidate for fsyncing.
    1250                 :             :      */
    1251                 :         315 :     MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
    1252                 :             : 
    1253                 :             :     /*
    1254                 :             :      * Remember that we have this GlobalTransaction entry locked for us.  If
    1255                 :             :      * we crash after this point, it's too late to abort, but we must unlock
    1256                 :             :      * it so that the prepared transaction can be committed or rolled back.
    1257                 :             :      */
    1258                 :         315 :     MyLockedGxact = gxact;
    1259                 :             : 
    1260                 :         315 :     END_CRIT_SECTION();
    1261                 :             : 
    1262                 :             :     /*
    1263                 :             :      * Wait for synchronous replication, if required.
    1264                 :             :      *
    1265                 :             :      * Note that at this stage we have marked the prepare, but still show as
    1266                 :             :      * running in the procarray (twice!) and continue to hold locks.
    1267                 :             :      */
    1268                 :         315 :     SyncRepWaitForLSN(gxact->prepare_end_lsn, false);
    1269                 :             : 
    1270                 :         315 :     records.tail = records.head = NULL;
    1271                 :         315 :     records.num_chunks = 0;
    1272                 :         315 : }
    1273                 :             : 
    1274                 :             : /*
    1275                 :             :  * Register a 2PC record to be written to state file.
    1276                 :             :  */
    1277                 :             : void
    1278                 :        1709 : RegisterTwoPhaseRecord(TwoPhaseRmgrId rmid, uint16 info,
    1279                 :             :                        const void *data, uint32 len)
    1280                 :             : {
    1281                 :             :     TwoPhaseRecordOnDisk record;
    1282                 :             : 
    1283                 :        1709 :     record.rmid = rmid;
    1284                 :        1709 :     record.info = info;
    1285                 :        1709 :     record.len = len;
    1286                 :        1709 :     save_state_data(&record, sizeof(TwoPhaseRecordOnDisk));
    1287         [ +  + ]:        1709 :     if (len > 0)
    1288                 :        1394 :         save_state_data(data, len);
    1289                 :        1709 : }
    1290                 :             : 
    1291                 :             : 
    1292                 :             : /*
    1293                 :             :  * Read and validate the state file for xid.
    1294                 :             :  *
    1295                 :             :  * If it looks OK (has a valid magic number and CRC), return the palloc'd
    1296                 :             :  * contents of the file, issuing an error when finding corrupted data.  If
    1297                 :             :  * missing_ok is true, which indicates that missing files can be safely
    1298                 :             :  * ignored, then return NULL.  This state can be reached when doing recovery
    1299                 :             :  * after discarding two-phase files from frozen epochs.
    1300                 :             :  */
    1301                 :             : static char *
    1302                 :         343 : ReadTwoPhaseFile(FullTransactionId fxid, bool missing_ok)
    1303                 :             : {
    1304                 :             :     char        path[MAXPGPATH];
    1305                 :             :     size_t      buflen;
    1306                 :             :     char       *buf;
    1307                 :             :     TwoPhaseFileHeader *hdr;
    1308                 :             :     int         fd;
    1309                 :             :     struct stat stat;
    1310                 :             :     uint32      crc_offset;
    1311                 :             :     pg_crc32c   calc_crc,
    1312                 :             :                 file_crc;
    1313                 :             :     ssize_t     r;
    1314                 :             : 
    1315                 :         343 :     TwoPhaseFilePath(path, fxid);
    1316                 :             : 
    1317                 :         343 :     fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
    1318         [ +  + ]:         343 :     if (fd < 0)
    1319                 :             :     {
    1320   [ +  -  +  - ]:         267 :         if (missing_ok && errno == ENOENT)
    1321                 :         267 :             return NULL;
    1322                 :             : 
    1323         [ #  # ]:           0 :         ereport(ERROR,
    1324                 :             :                 (errcode_for_file_access(),
    1325                 :             :                  errmsg("could not open file \"%s\": %m", path)));
    1326                 :             :     }
    1327                 :             : 
    1328                 :             :     /*
    1329                 :             :      * Check file length.  We can determine a lower bound pretty easily. We
    1330                 :             :      * set an upper bound to avoid palloc() failure on a corrupt file, though
    1331                 :             :      * we can't guarantee that we won't get an out of memory error anyway,
    1332                 :             :      * even on a valid file.
    1333                 :             :      */
    1334         [ -  + ]:          76 :     if (fstat(fd, &stat))
    1335         [ #  # ]:           0 :         ereport(ERROR,
    1336                 :             :                 (errcode_for_file_access(),
    1337                 :             :                  errmsg("could not stat file \"%s\": %m", path)));
    1338                 :             : 
    1339         [ +  - ]:          76 :     if (stat.st_size < (MAXALIGN(sizeof(TwoPhaseFileHeader)) +
    1340                 :             :                         MAXALIGN(sizeof(TwoPhaseRecordOnDisk)) +
    1341                 :          76 :                         sizeof(pg_crc32c)) ||
    1342         [ -  + ]:          76 :         stat.st_size > MaxAllocSize)
    1343         [ #  # ]:           0 :         ereport(ERROR,
    1344                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1345                 :             :                  errmsg_plural("incorrect size of file \"%s\": %lld byte",
    1346                 :             :                                "incorrect size of file \"%s\": %lld bytes",
    1347                 :             :                                (long long int) stat.st_size, path,
    1348                 :             :                                (long long int) stat.st_size)));
    1349                 :             : 
    1350                 :          76 :     crc_offset = stat.st_size - sizeof(pg_crc32c);
    1351         [ -  + ]:          76 :     if (crc_offset != MAXALIGN(crc_offset))
    1352         [ #  # ]:           0 :         ereport(ERROR,
    1353                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1354                 :             :                  errmsg("incorrect alignment of CRC offset for file \"%s\"",
    1355                 :             :                         path)));
    1356                 :             : 
    1357                 :             :     /*
    1358                 :             :      * OK, slurp in the file.
    1359                 :             :      */
    1360                 :          76 :     buflen = stat.st_size;
    1361                 :          76 :     buf = (char *) palloc(buflen);
    1362                 :             : 
    1363                 :          76 :     pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_READ);
    1364                 :          76 :     r = read(fd, buf, buflen);
    1365         [ -  + ]:          76 :     if (r != buflen)
    1366                 :             :     {
    1367         [ #  # ]:           0 :         if (r < 0)
    1368         [ #  # ]:           0 :             ereport(ERROR,
    1369                 :             :                     (errcode_for_file_access(),
    1370                 :             :                      errmsg("could not read file \"%s\": %m", path)));
    1371                 :             :         else
    1372         [ #  # ]:           0 :             ereport(ERROR,
    1373                 :             :                     (errmsg("could not read file \"%s\": read %zd of %zu",
    1374                 :             :                             path, r, buflen)));
    1375                 :             :     }
    1376                 :             : 
    1377                 :          76 :     pgstat_report_wait_end();
    1378                 :             : 
    1379         [ -  + ]:          76 :     if (CloseTransientFile(fd) != 0)
    1380         [ #  # ]:           0 :         ereport(ERROR,
    1381                 :             :                 (errcode_for_file_access(),
    1382                 :             :                  errmsg("could not close file \"%s\": %m", path)));
    1383                 :             : 
    1384                 :          76 :     hdr = (TwoPhaseFileHeader *) buf;
    1385         [ -  + ]:          76 :     if (hdr->magic != TWOPHASE_MAGIC)
    1386         [ #  # ]:           0 :         ereport(ERROR,
    1387                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1388                 :             :                  errmsg("invalid magic number stored in file \"%s\"",
    1389                 :             :                         path)));
    1390                 :             : 
    1391         [ -  + ]:          76 :     if (hdr->total_len != stat.st_size)
    1392         [ #  # ]:           0 :         ereport(ERROR,
    1393                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1394                 :             :                  errmsg("invalid size stored in file \"%s\"",
    1395                 :             :                         path)));
    1396                 :             : 
    1397                 :          76 :     INIT_CRC32C(calc_crc);
    1398                 :          76 :     COMP_CRC32C(calc_crc, buf, crc_offset);
    1399                 :          76 :     FIN_CRC32C(calc_crc);
    1400                 :             : 
    1401                 :          76 :     file_crc = *((pg_crc32c *) (buf + crc_offset));
    1402                 :             : 
    1403         [ -  + ]:          76 :     if (!EQ_CRC32C(calc_crc, file_crc))
    1404         [ #  # ]:           0 :         ereport(ERROR,
    1405                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
    1406                 :             :                  errmsg("calculated CRC checksum does not match value stored in file \"%s\"",
    1407                 :             :                         path)));
    1408                 :             : 
    1409                 :          76 :     return buf;
    1410                 :             : }
    1411                 :             : 
    1412                 :             : 
    1413                 :             : /*
    1414                 :             :  * Reads 2PC data from xlog. During checkpoint this data will be moved to
    1415                 :             :  * twophase files and ReadTwoPhaseFile should be used instead.
    1416                 :             :  *
    1417                 :             :  * Note clearly that this function can access WAL during normal operation,
    1418                 :             :  * similarly to the way WALSender or Logical Decoding would do.
    1419                 :             :  */
    1420                 :             : static void
    1421                 :         403 : XlogReadTwoPhaseData(XLogRecPtr lsn, char **buf, size_t *len)
    1422                 :             : {
    1423                 :             :     XLogRecord *record;
    1424                 :             :     XLogReaderState *xlogreader;
    1425                 :             :     char       *errormsg;
    1426                 :             : 
    1427                 :         403 :     xlogreader = XLogReaderAllocate(wal_segment_size, NULL,
    1428                 :         403 :                                     XL_ROUTINE(.page_read = &read_local_xlog_page,
    1429                 :             :                                                .segment_open = &wal_segment_open,
    1430                 :             :                                                .segment_close = &wal_segment_close),
    1431                 :             :                                     NULL);
    1432         [ -  + ]:         403 :     if (!xlogreader)
    1433         [ #  # ]:           0 :         ereport(ERROR,
    1434                 :             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    1435                 :             :                  errmsg("out of memory"),
    1436                 :             :                  errdetail("Failed while allocating a WAL reading processor.")));
    1437                 :             : 
    1438                 :         403 :     XLogBeginRead(xlogreader, lsn);
    1439                 :         403 :     record = XLogReadRecord(xlogreader, &errormsg);
    1440                 :             : 
    1441         [ -  + ]:         403 :     if (record == NULL)
    1442                 :             :     {
    1443         [ #  # ]:           0 :         if (errormsg)
    1444         [ #  # ]:           0 :             ereport(ERROR,
    1445                 :             :                     (errcode_for_file_access(),
    1446                 :             :                      errmsg("could not read two-phase state from WAL at %X/%08X: %s",
    1447                 :             :                             LSN_FORMAT_ARGS(lsn), errormsg)));
    1448                 :             :         else
    1449         [ #  # ]:           0 :             ereport(ERROR,
    1450                 :             :                     (errcode_for_file_access(),
    1451                 :             :                      errmsg("could not read two-phase state from WAL at %X/%08X",
    1452                 :             :                             LSN_FORMAT_ARGS(lsn))));
    1453                 :             :     }
    1454                 :             : 
    1455         [ +  - ]:         403 :     if (XLogRecGetRmid(xlogreader) != RM_XACT_ID ||
    1456         [ -  + ]:         403 :         (XLogRecGetInfo(xlogreader) & XLOG_XACT_OPMASK) != XLOG_XACT_PREPARE)
    1457         [ #  # ]:           0 :         ereport(ERROR,
    1458                 :             :                 (errcode_for_file_access(),
    1459                 :             :                  errmsg("expected two-phase state data is not present in WAL at %X/%08X",
    1460                 :             :                         LSN_FORMAT_ARGS(lsn))));
    1461                 :             : 
    1462         [ +  + ]:         403 :     if (len != NULL)
    1463                 :          27 :         *len = XLogRecGetDataLen(xlogreader);
    1464                 :             : 
    1465                 :         403 :     *buf = palloc_array(char, XLogRecGetDataLen(xlogreader));
    1466                 :         403 :     memcpy(*buf, XLogRecGetData(xlogreader), sizeof(char) * XLogRecGetDataLen(xlogreader));
    1467                 :             : 
    1468                 :         403 :     XLogReaderFree(xlogreader);
    1469                 :         403 : }
    1470                 :             : 
    1471                 :             : 
    1472                 :             : /*
    1473                 :             :  * Confirms an xid is prepared, during recovery
    1474                 :             :  */
    1475                 :             : bool
    1476                 :         267 : StandbyTransactionIdIsPrepared(TransactionId xid)
    1477                 :             : {
    1478                 :             :     char       *buf;
    1479                 :             :     TwoPhaseFileHeader *hdr;
    1480                 :             :     bool        result;
    1481                 :             :     FullTransactionId fxid;
    1482                 :             : 
    1483                 :             :     Assert(TransactionIdIsValid(xid));
    1484                 :             : 
    1485         [ -  + ]:         267 :     if (max_prepared_xacts <= 0)
    1486                 :           0 :         return false;           /* nothing to do */
    1487                 :             : 
    1488                 :             :     /* Read and validate file */
    1489                 :         267 :     fxid = AdjustToFullTransactionId(xid);
    1490                 :         267 :     buf = ReadTwoPhaseFile(fxid, true);
    1491         [ +  - ]:         267 :     if (buf == NULL)
    1492                 :         267 :         return false;
    1493                 :             : 
    1494                 :             :     /* Check header also */
    1495                 :           0 :     hdr = (TwoPhaseFileHeader *) buf;
    1496                 :           0 :     result = TransactionIdEquals(hdr->xid, xid);
    1497                 :           0 :     pfree(buf);
    1498                 :             : 
    1499                 :           0 :     return result;
    1500                 :             : }
    1501                 :             : 
    1502                 :             : /*
    1503                 :             :  * FinishPreparedTransaction: execute COMMIT PREPARED or ROLLBACK PREPARED
    1504                 :             :  */
    1505                 :             : void
    1506                 :         335 : FinishPreparedTransaction(const char *gid, bool isCommit)
    1507                 :             : {
    1508                 :             :     GlobalTransaction gxact;
    1509                 :             :     PGPROC     *proc;
    1510                 :             :     FullTransactionId fxid;
    1511                 :             :     TransactionId xid;
    1512                 :             :     bool        ondisk;
    1513                 :             :     char       *buf;
    1514                 :             :     char       *bufptr;
    1515                 :             :     TwoPhaseFileHeader *hdr;
    1516                 :             :     TransactionId latestXid;
    1517                 :             :     TransactionId *children;
    1518                 :             :     RelFileLocator *commitrels;
    1519                 :             :     RelFileLocator *abortrels;
    1520                 :             :     RelFileLocator *delrels;
    1521                 :             :     int         ndelrels;
    1522                 :             :     xl_xact_stats_item *commitstats;
    1523                 :             :     xl_xact_stats_item *abortstats;
    1524                 :             :     SharedInvalidationMessage *invalmsgs;
    1525                 :             : 
    1526                 :             :     /*
    1527                 :             :      * Validate the GID, and lock the GXACT to ensure that two backends do not
    1528                 :             :      * try to commit the same GID at once.
    1529                 :             :      */
    1530                 :         335 :     gxact = LockGXact(gid, GetUserId());
    1531                 :         321 :     proc = GetPGProcByNumber(gxact->pgprocno);
    1532                 :         321 :     fxid = gxact->fxid;
    1533                 :         321 :     xid = XidFromFullTransactionId(fxid);
    1534                 :             : 
    1535                 :             :     /*
    1536                 :             :      * Read and validate 2PC state data. State data will typically be stored
    1537                 :             :      * in WAL files if the LSN is after the last checkpoint record, or moved
    1538                 :             :      * to disk if for some reason they have lived for a long time.
    1539                 :             :      */
    1540         [ +  + ]:         321 :     if (gxact->ondisk)
    1541                 :          26 :         buf = ReadTwoPhaseFile(fxid, false);
    1542                 :             :     else
    1543                 :         295 :         XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
    1544                 :             : 
    1545                 :             : 
    1546                 :             :     /*
    1547                 :             :      * Disassemble the header area
    1548                 :             :      */
    1549                 :         321 :     hdr = (TwoPhaseFileHeader *) buf;
    1550                 :             :     Assert(TransactionIdEquals(hdr->xid, xid));
    1551                 :         321 :     bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
    1552                 :         321 :     bufptr += MAXALIGN(hdr->gidlen);
    1553                 :         321 :     children = (TransactionId *) bufptr;
    1554                 :         321 :     bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
    1555                 :         321 :     commitrels = (RelFileLocator *) bufptr;
    1556                 :         321 :     bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
    1557                 :         321 :     abortrels = (RelFileLocator *) bufptr;
    1558                 :         321 :     bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
    1559                 :         321 :     commitstats = (xl_xact_stats_item *) bufptr;
    1560                 :         321 :     bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
    1561                 :         321 :     abortstats = (xl_xact_stats_item *) bufptr;
    1562                 :         321 :     bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
    1563                 :         321 :     invalmsgs = (SharedInvalidationMessage *) bufptr;
    1564                 :         321 :     bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
    1565                 :             : 
    1566                 :             :     /* compute latestXid among all children */
    1567                 :         321 :     latestXid = TransactionIdLatest(xid, hdr->nsubxacts, children);
    1568                 :             : 
    1569                 :             :     /* Prevent cancel/die interrupt while cleaning up */
    1570                 :         321 :     HOLD_INTERRUPTS();
    1571                 :             : 
    1572                 :             :     /*
    1573                 :             :      * The order of operations here is critical: make the XLOG entry for
    1574                 :             :      * commit or abort, then mark the transaction committed or aborted in
    1575                 :             :      * pg_xact, then remove its PGPROC from the global ProcArray (which means
    1576                 :             :      * TransactionIdIsInProgress will stop saying the prepared xact is in
    1577                 :             :      * progress), then run the post-commit or post-abort callbacks. The
    1578                 :             :      * callbacks will release the locks the transaction held.
    1579                 :             :      */
    1580         [ +  + ]:         321 :     if (isCommit)
    1581                 :         271 :         RecordTransactionCommitPrepared(xid,
    1582                 :             :                                         hdr->nsubxacts, children,
    1583                 :             :                                         hdr->ncommitrels, commitrels,
    1584                 :             :                                         hdr->ncommitstats,
    1585                 :             :                                         commitstats,
    1586                 :             :                                         hdr->ninvalmsgs, invalmsgs,
    1587                 :         271 :                                         hdr->initfileinval, gid);
    1588                 :             :     else
    1589                 :          50 :         RecordTransactionAbortPrepared(xid,
    1590                 :             :                                        hdr->nsubxacts, children,
    1591                 :             :                                        hdr->nabortrels, abortrels,
    1592                 :             :                                        hdr->nabortstats,
    1593                 :             :                                        abortstats,
    1594                 :             :                                        gid);
    1595                 :             : 
    1596                 :         321 :     ProcArrayRemove(proc, latestXid);
    1597                 :             : 
    1598                 :             :     /*
    1599                 :             :      * In case we fail while running the callbacks, mark the gxact invalid so
    1600                 :             :      * no one else will try to commit/rollback, and so it will be recycled if
    1601                 :             :      * we fail after this point.  It is still locked by our backend so it
    1602                 :             :      * won't go away yet.
    1603                 :             :      *
    1604                 :             :      * (We assume it's safe to do this without taking TwoPhaseStateLock.)
    1605                 :             :      */
    1606                 :         321 :     gxact->valid = false;
    1607                 :             : 
    1608                 :             :     /*
    1609                 :             :      * We have to remove any files that were supposed to be dropped. For
    1610                 :             :      * consistency with the regular xact.c code paths, must do this before
    1611                 :             :      * releasing locks, so do it before running the callbacks.
    1612                 :             :      *
    1613                 :             :      * NB: this code knows that we couldn't be dropping any temp rels ...
    1614                 :             :      */
    1615         [ +  + ]:         321 :     if (isCommit)
    1616                 :             :     {
    1617                 :         271 :         delrels = commitrels;
    1618                 :         271 :         ndelrels = hdr->ncommitrels;
    1619                 :             :     }
    1620                 :             :     else
    1621                 :             :     {
    1622                 :          50 :         delrels = abortrels;
    1623                 :          50 :         ndelrels = hdr->nabortrels;
    1624                 :             :     }
    1625                 :             : 
    1626                 :             :     /* Make sure files supposed to be dropped are dropped */
    1627                 :         321 :     DropRelationFiles(delrels, ndelrels, false);
    1628                 :             : 
    1629         [ +  + ]:         321 :     if (isCommit)
    1630                 :         271 :         pgstat_execute_transactional_drops(hdr->ncommitstats, commitstats, false);
    1631                 :             :     else
    1632                 :          50 :         pgstat_execute_transactional_drops(hdr->nabortstats, abortstats, false);
    1633                 :             : 
    1634                 :             :     /*
    1635                 :             :      * Handle cache invalidation messages.
    1636                 :             :      *
    1637                 :             :      * Relcache init file invalidation requires processing both before and
    1638                 :             :      * after we send the SI messages, only when committing.  See
    1639                 :             :      * AtEOXact_Inval().
    1640                 :             :      */
    1641         [ +  + ]:         321 :     if (isCommit)
    1642                 :             :     {
    1643         [ -  + ]:         271 :         if (hdr->initfileinval)
    1644                 :           0 :             RelationCacheInitFilePreInvalidate();
    1645                 :         271 :         SendSharedInvalidMessages(invalmsgs, hdr->ninvalmsgs);
    1646         [ -  + ]:         271 :         if (hdr->initfileinval)
    1647                 :           0 :             RelationCacheInitFilePostInvalidate();
    1648                 :             :     }
    1649                 :             : 
    1650                 :             :     /*
    1651                 :             :      * Acquire the two-phase lock.  We want to work on the two-phase callbacks
    1652                 :             :      * while holding it to avoid potential conflicts with other transactions
    1653                 :             :      * attempting to use the same GID, so the lock is released once the shared
    1654                 :             :      * memory state is cleared.
    1655                 :             :      */
    1656                 :         321 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
    1657                 :             : 
    1658                 :             :     /* And now do the callbacks */
    1659         [ +  + ]:         321 :     if (isCommit)
    1660                 :         271 :         ProcessRecords(bufptr, fxid, twophase_postcommit_callbacks);
    1661                 :             :     else
    1662                 :          50 :         ProcessRecords(bufptr, fxid, twophase_postabort_callbacks);
    1663                 :             : 
    1664                 :         321 :     PredicateLockTwoPhaseFinish(fxid, isCommit);
    1665                 :             : 
    1666                 :             :     /*
    1667                 :             :      * Read this value while holding the two-phase lock, as the on-disk 2PC
    1668                 :             :      * file is physically removed after the lock is released.
    1669                 :             :      */
    1670                 :         321 :     ondisk = gxact->ondisk;
    1671                 :             : 
    1672                 :             :     /* Clear shared memory state */
    1673                 :         321 :     RemoveGXact(gxact);
    1674                 :             : 
    1675                 :             :     /*
    1676                 :             :      * Release the lock as all callbacks are called and shared memory cleanup
    1677                 :             :      * is done.
    1678                 :             :      */
    1679                 :         321 :     LWLockRelease(TwoPhaseStateLock);
    1680                 :             : 
    1681                 :             :     /* Count the prepared xact as committed or aborted */
    1682                 :         321 :     AtEOXact_PgStat(isCommit, false);
    1683                 :             : 
    1684                 :             :     /*
    1685                 :             :      * And now we can clean up any files we may have left.
    1686                 :             :      */
    1687         [ +  + ]:         321 :     if (ondisk)
    1688                 :          26 :         RemoveTwoPhaseFile(fxid, true);
    1689                 :             : 
    1690                 :         321 :     MyLockedGxact = NULL;
    1691                 :             : 
    1692                 :         321 :     RESUME_INTERRUPTS();
    1693                 :             : 
    1694                 :         321 :     pfree(buf);
    1695                 :         321 : }
    1696                 :             : 
    1697                 :             : /*
    1698                 :             :  * Scan 2PC state data in memory and call the indicated callbacks for each 2PC record.
    1699                 :             :  */
    1700                 :             : static void
    1701                 :         355 : ProcessRecords(char *bufptr, FullTransactionId fxid,
    1702                 :             :                const TwoPhaseCallback callbacks[])
    1703                 :             : {
    1704                 :             :     for (;;)
    1705                 :        1597 :     {
    1706                 :        1952 :         TwoPhaseRecordOnDisk *record = (TwoPhaseRecordOnDisk *) bufptr;
    1707                 :             : 
    1708                 :             :         Assert(record->rmid <= TWOPHASE_RM_MAX_ID);
    1709         [ +  + ]:        1952 :         if (record->rmid == TWOPHASE_RM_END_ID)
    1710                 :         355 :             break;
    1711                 :             : 
    1712                 :        1597 :         bufptr += MAXALIGN(sizeof(TwoPhaseRecordOnDisk));
    1713                 :             : 
    1714         [ +  + ]:        1597 :         if (callbacks[record->rmid] != NULL)
    1715                 :        1517 :             callbacks[record->rmid] (fxid, record->info, bufptr, record->len);
    1716                 :             : 
    1717                 :        1597 :         bufptr += MAXALIGN(record->len);
    1718                 :             :     }
    1719                 :         355 : }
    1720                 :             : 
    1721                 :             : /*
    1722                 :             :  * Remove the 2PC file.
    1723                 :             :  *
    1724                 :             :  * If giveWarning is false, do not complain about file-not-present;
    1725                 :             :  * this is an expected case during WAL replay.
    1726                 :             :  *
    1727                 :             :  * This routine is used at early stages at recovery where future and
    1728                 :             :  * past orphaned files are checked, hence the FullTransactionId to build
    1729                 :             :  * a complete file name fit for the removal.
    1730                 :             :  */
    1731                 :             : static void
    1732                 :          31 : RemoveTwoPhaseFile(FullTransactionId fxid, bool giveWarning)
    1733                 :             : {
    1734                 :             :     char        path[MAXPGPATH];
    1735                 :             : 
    1736                 :          31 :     TwoPhaseFilePath(path, fxid);
    1737         [ -  + ]:          31 :     if (unlink(path))
    1738   [ #  #  #  # ]:           0 :         if (errno != ENOENT || giveWarning)
    1739         [ #  # ]:           0 :             ereport(WARNING,
    1740                 :             :                     (errcode_for_file_access(),
    1741                 :             :                      errmsg("could not remove file \"%s\": %m", path)));
    1742                 :          31 : }
    1743                 :             : 
    1744                 :             : /*
    1745                 :             :  * Recreates a state file. This is used in WAL replay and during
    1746                 :             :  * checkpoint creation.
    1747                 :             :  *
    1748                 :             :  * Note: content and len don't include CRC.
    1749                 :             :  */
    1750                 :             : static void
    1751                 :          27 : RecreateTwoPhaseFile(FullTransactionId fxid, const void *content, size_t len)
    1752                 :             : {
    1753                 :             :     char        path[MAXPGPATH];
    1754                 :             :     char        tmppath[MAXPGPATH];
    1755                 :             :     pg_crc32c   statefile_crc;
    1756                 :             :     int         fd;
    1757                 :             : 
    1758                 :             :     /* Recompute CRC */
    1759                 :          27 :     INIT_CRC32C(statefile_crc);
    1760                 :          27 :     COMP_CRC32C(statefile_crc, content, len);
    1761                 :          27 :     FIN_CRC32C(statefile_crc);
    1762                 :             : 
    1763                 :          27 :     TwoPhaseFilePath(path, fxid);
    1764                 :             : 
    1765                 :             :     /* Write to a temp file and rename it into place */
    1766                 :          27 :     snprintf(tmppath, sizeof(tmppath), "%s.tmp", path);
    1767                 :             : 
    1768                 :          27 :     fd = OpenTransientFile(tmppath,
    1769                 :             :                            O_CREAT | O_TRUNC | O_WRONLY | PG_BINARY);
    1770         [ -  + ]:          27 :     if (fd < 0)
    1771         [ #  # ]:           0 :         ereport(ERROR,
    1772                 :             :                 (errcode_for_file_access(),
    1773                 :             :                  errmsg("could not recreate file \"%s\": %m", tmppath)));
    1774                 :             : 
    1775                 :             :     /* Write content and CRC */
    1776                 :          27 :     errno = 0;
    1777                 :          27 :     pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_WRITE);
    1778         [ -  + ]:          27 :     if (write(fd, content, len) != len)
    1779                 :             :     {
    1780                 :             :         /* if write didn't set errno, assume problem is no disk space */
    1781         [ #  # ]:           0 :         if (errno == 0)
    1782                 :           0 :             errno = ENOSPC;
    1783         [ #  # ]:           0 :         ereport(ERROR,
    1784                 :             :                 (errcode_for_file_access(),
    1785                 :             :                  errmsg("could not write file \"%s\": %m", tmppath)));
    1786                 :             :     }
    1787         [ -  + ]:          27 :     if (write(fd, &statefile_crc, sizeof(pg_crc32c)) != sizeof(pg_crc32c))
    1788                 :             :     {
    1789                 :             :         /* if write didn't set errno, assume problem is no disk space */
    1790         [ #  # ]:           0 :         if (errno == 0)
    1791                 :           0 :             errno = ENOSPC;
    1792         [ #  # ]:           0 :         ereport(ERROR,
    1793                 :             :                 (errcode_for_file_access(),
    1794                 :             :                  errmsg("could not write file \"%s\": %m", tmppath)));
    1795                 :             :     }
    1796                 :          27 :     pgstat_report_wait_end();
    1797                 :             : 
    1798                 :             :     /*
    1799                 :             :      * We must fsync the file because the end-of-replay checkpoint will not do
    1800                 :             :      * so, there being no GXACT in shared memory yet to tell it to.
    1801                 :             :      */
    1802                 :          27 :     pgstat_report_wait_start(WAIT_EVENT_TWOPHASE_FILE_SYNC);
    1803         [ -  + ]:          27 :     if (pg_fsync(fd) != 0)
    1804         [ #  # ]:           0 :         ereport(ERROR,
    1805                 :             :                 (errcode_for_file_access(),
    1806                 :             :                  errmsg("could not fsync file \"%s\": %m", tmppath)));
    1807                 :          27 :     pgstat_report_wait_end();
    1808                 :             : 
    1809         [ -  + ]:          27 :     if (CloseTransientFile(fd) != 0)
    1810         [ #  # ]:           0 :         ereport(ERROR,
    1811                 :             :                 (errcode_for_file_access(),
    1812                 :             :                  errmsg("could not close file \"%s\": %m", tmppath)));
    1813                 :             : 
    1814                 :             :     /*
    1815                 :             :      * No durable_rename(), as CheckPointTwoPhase() fsyncs the parent
    1816                 :             :      * directory.
    1817                 :             :      */
    1818         [ -  + ]:          27 :     if (rename(tmppath, path) != 0)
    1819         [ #  # ]:           0 :         ereport(ERROR,
    1820                 :             :                 (errcode_for_file_access(),
    1821                 :             :                  errmsg("could not rename file \"%s\" to \"%s\": %m",
    1822                 :             :                         tmppath, path)));
    1823                 :          27 : }
    1824                 :             : 
    1825                 :             : /*
    1826                 :             :  * CheckPointTwoPhase -- handle 2PC component of checkpointing.
    1827                 :             :  *
    1828                 :             :  * We must fsync the state file of any GXACT that is valid or has been
    1829                 :             :  * generated during redo and has a PREPARE LSN <= the checkpoint's redo
    1830                 :             :  * horizon.  (If the gxact isn't valid yet, has not been generated in
    1831                 :             :  * redo, or has a later LSN, this checkpoint is not responsible for
    1832                 :             :  * fsyncing it.)
    1833                 :             :  *
    1834                 :             :  * This is deliberately run as late as possible in the checkpoint sequence,
    1835                 :             :  * because GXACTs ordinarily have short lifespans, and so it is quite
    1836                 :             :  * possible that GXACTs that were valid at checkpoint start will no longer
    1837                 :             :  * exist if we wait a little bit. With typical checkpoint settings this
    1838                 :             :  * will be about 3 minutes for an online checkpoint, so as a result we
    1839                 :             :  * expect that there will be no GXACTs that need to be copied to disk.
    1840                 :             :  *
    1841                 :             :  * If a GXACT remains valid across multiple checkpoints, it will already
    1842                 :             :  * be on disk so we don't bother to repeat that write.
    1843                 :             :  */
    1844                 :             : void
    1845                 :        2038 : CheckPointTwoPhase(XLogRecPtr redo_horizon)
    1846                 :             : {
    1847                 :             :     int         i;
    1848                 :        2038 :     int         serialized_xacts = 0;
    1849                 :             : 
    1850         [ +  + ]:        2038 :     if (max_prepared_xacts <= 0)
    1851                 :        1476 :         return;                 /* nothing to do */
    1852                 :             : 
    1853                 :             :     TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_START();
    1854                 :             : 
    1855                 :             :     /*
    1856                 :             :      * We are expecting there to be zero GXACTs that need to be copied to
    1857                 :             :      * disk, so we perform all I/O while holding TwoPhaseStateLock for
    1858                 :             :      * simplicity. This prevents any new xacts from preparing while this
    1859                 :             :      * occurs, which shouldn't be a problem since the presence of long-lived
    1860                 :             :      * prepared xacts indicates the transaction manager isn't active.
    1861                 :             :      *
    1862                 :             :      * It's also possible to move I/O out of the lock, but on every error we
    1863                 :             :      * should check whether somebody committed our transaction in different
    1864                 :             :      * backend. Let's leave this optimization for future, if somebody will
    1865                 :             :      * spot that this place cause bottleneck.
    1866                 :             :      *
    1867                 :             :      * Note that it isn't possible for there to be a GXACT with a
    1868                 :             :      * prepare_end_lsn set prior to the last checkpoint yet is marked invalid,
    1869                 :             :      * because of the efforts with delayChkptFlags.
    1870                 :             :      */
    1871                 :         562 :     LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
    1872         [ +  + ]:         596 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
    1873                 :             :     {
    1874                 :             :         /*
    1875                 :             :          * Note that we are using gxact not PGPROC so this works in recovery
    1876                 :             :          * also
    1877                 :             :          */
    1878                 :          34 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
    1879                 :             : 
    1880   [ +  +  +  - ]:          34 :         if ((gxact->valid || gxact->inredo) &&
    1881         [ +  + ]:          34 :             !gxact->ondisk &&
    1882         [ +  + ]:          29 :             gxact->prepare_end_lsn <= redo_horizon)
    1883                 :             :         {
    1884                 :             :             char       *buf;
    1885                 :             :             size_t      len;
    1886                 :             : 
    1887                 :          27 :             XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, &len);
    1888                 :          27 :             RecreateTwoPhaseFile(gxact->fxid, buf, len);
    1889                 :          27 :             gxact->ondisk = true;
    1890                 :          27 :             gxact->prepare_start_lsn = InvalidXLogRecPtr;
    1891                 :          27 :             gxact->prepare_end_lsn = InvalidXLogRecPtr;
    1892                 :          27 :             pfree(buf);
    1893                 :          27 :             serialized_xacts++;
    1894                 :             :         }
    1895                 :             :     }
    1896                 :         562 :     LWLockRelease(TwoPhaseStateLock);
    1897                 :             : 
    1898                 :             :     /*
    1899                 :             :      * Flush unconditionally the parent directory to make any information
    1900                 :             :      * durable on disk.  Two-phase files could have been removed and those
    1901                 :             :      * removals need to be made persistent as well as any files newly created
    1902                 :             :      * previously since the last checkpoint.
    1903                 :             :      */
    1904                 :         562 :     fsync_fname(TWOPHASE_DIR, true);
    1905                 :             : 
    1906                 :             :     TRACE_POSTGRESQL_TWOPHASE_CHECKPOINT_DONE();
    1907                 :             : 
    1908   [ +  -  +  + ]:         562 :     if (log_checkpoints && serialized_xacts > 0)
    1909         [ +  - ]:          23 :         ereport(LOG,
    1910                 :             :                 (errmsg_plural("%u two-phase state file was written "
    1911                 :             :                                "for a long-running prepared transaction",
    1912                 :             :                                "%u two-phase state files were written "
    1913                 :             :                                "for long-running prepared transactions",
    1914                 :             :                                serialized_xacts,
    1915                 :             :                                serialized_xacts)));
    1916                 :             : }
    1917                 :             : 
    1918                 :             : /*
    1919                 :             :  * restoreTwoPhaseData
    1920                 :             :  *
    1921                 :             :  * Scan pg_twophase and fill TwoPhaseState depending on the on-disk data.
    1922                 :             :  * This is called once at the beginning of recovery, saving any extra
    1923                 :             :  * lookups in the future.  Two-phase files that are newer than the
    1924                 :             :  * minimum XID horizon are discarded on the way.
    1925                 :             :  */
    1926                 :             : void
    1927                 :        1150 : restoreTwoPhaseData(void)
    1928                 :             : {
    1929                 :             :     DIR        *cldir;
    1930                 :             :     struct dirent *clde;
    1931                 :             : 
    1932                 :        1150 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
    1933                 :        1150 :     cldir = AllocateDir(TWOPHASE_DIR);
    1934         [ +  + ]:        3466 :     while ((clde = ReadDir(cldir, TWOPHASE_DIR)) != NULL)
    1935                 :             :     {
    1936                 :             :         /* Ignore temp files created by RecreateTwoPhaseFile(). */
    1937         [ -  + ]:        2316 :         if (pg_str_endswith(clde->d_name, ".tmp"))
    1938                 :           0 :         {
    1939                 :             :             char        path[MAXPGPATH];
    1940                 :             : 
    1941                 :           0 :             snprintf(path, MAXPGPATH, TWOPHASE_DIR "/%s", clde->d_name);
    1942         [ #  # ]:           0 :             if (unlink(path) < 0)
    1943         [ #  # ]:           0 :                 ereport(WARNING,
    1944                 :             :                         (errcode_for_file_access(),
    1945                 :             :                          errmsg("could not remove file \"%s\": %m", path)));
    1946                 :           0 :             continue;
    1947                 :             :         }
    1948                 :             : 
    1949         [ +  + ]:        2316 :         if (strlen(clde->d_name) == 16 &&
    1950         [ +  - ]:          16 :             strspn(clde->d_name, "0123456789ABCDEF") == 16)
    1951                 :             :         {
    1952                 :             :             FullTransactionId fxid;
    1953                 :             :             char       *buf;
    1954                 :             : 
    1955                 :          16 :             fxid = FullTransactionIdFromU64(strtou64(clde->d_name, NULL, 16));
    1956                 :             : 
    1957                 :          16 :             buf = ProcessTwoPhaseBuffer(fxid, InvalidXLogRecPtr,
    1958                 :             :                                         true, false, false);
    1959         [ -  + ]:          16 :             if (buf == NULL)
    1960                 :           0 :                 continue;
    1961                 :             : 
    1962                 :          16 :             PrepareRedoAdd(fxid, buf, InvalidXLogRecPtr,
    1963                 :             :                            InvalidXLogRecPtr, InvalidReplOriginId);
    1964                 :             :         }
    1965                 :             :     }
    1966                 :        1150 :     LWLockRelease(TwoPhaseStateLock);
    1967                 :        1150 :     FreeDir(cldir);
    1968                 :        1150 : }
    1969                 :             : 
    1970                 :             : /*
    1971                 :             :  * PrescanPreparedTransactions
    1972                 :             :  *
    1973                 :             :  * Scan the shared memory entries of TwoPhaseState and determine the range
    1974                 :             :  * of valid XIDs present.  This is run during database startup, after we
    1975                 :             :  * have completed reading WAL.  TransamVariables->nextXid has been set to
    1976                 :             :  * one more than the highest XID for which evidence exists in WAL.
    1977                 :             :  *
    1978                 :             :  * We throw away any prepared xacts with main XID beyond nextXid --- if any
    1979                 :             :  * are present, it suggests that the DBA has done a PITR recovery to an
    1980                 :             :  * earlier point in time without cleaning out pg_twophase.  We dare not
    1981                 :             :  * try to recover such prepared xacts since they likely depend on database
    1982                 :             :  * state that doesn't exist now.
    1983                 :             :  *
    1984                 :             :  * However, we will advance nextXid beyond any subxact XIDs belonging to
    1985                 :             :  * valid prepared xacts.  We need to do this since subxact commit doesn't
    1986                 :             :  * write a WAL entry, and so there might be no evidence in WAL of those
    1987                 :             :  * subxact XIDs.
    1988                 :             :  *
    1989                 :             :  * On corrupted two-phase files, fail immediately.  Keeping around broken
    1990                 :             :  * entries and let replay continue causes harm on the system, and a new
    1991                 :             :  * backup should be rolled in.
    1992                 :             :  *
    1993                 :             :  * Our other responsibility is to determine and return the oldest valid XID
    1994                 :             :  * among the prepared xacts (if none, return TransamVariables->nextXid).
    1995                 :             :  * This is needed to synchronize pg_subtrans startup properly.
    1996                 :             :  *
    1997                 :             :  * If xids_p and nxids_p are not NULL, pointer to a palloc'd array of all
    1998                 :             :  * top-level xids is stored in *xids_p. The number of entries in the array
    1999                 :             :  * is returned in *nxids_p.
    2000                 :             :  */
    2001                 :             : TransactionId
    2002                 :        1153 : PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
    2003                 :             : {
    2004                 :        1153 :     FullTransactionId nextXid = TransamVariables->nextXid;
    2005                 :        1153 :     TransactionId origNextXid = XidFromFullTransactionId(nextXid);
    2006                 :        1153 :     TransactionId result = origNextXid;
    2007                 :        1153 :     TransactionId *xids = NULL;
    2008                 :        1153 :     int         nxids = 0;
    2009                 :        1153 :     int         allocsize = 0;
    2010                 :             :     int         i;
    2011                 :             : 
    2012                 :        1153 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
    2013         [ +  + ]:        1208 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
    2014                 :             :     {
    2015                 :             :         TransactionId xid;
    2016                 :             :         char       *buf;
    2017                 :          55 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
    2018                 :             : 
    2019                 :             :         Assert(gxact->inredo);
    2020                 :             : 
    2021                 :          55 :         buf = ProcessTwoPhaseBuffer(gxact->fxid,
    2022                 :             :                                     gxact->prepare_start_lsn,
    2023                 :          55 :                                     gxact->ondisk, false, true);
    2024                 :             : 
    2025         [ -  + ]:          55 :         if (buf == NULL)
    2026                 :           0 :             continue;
    2027                 :             : 
    2028                 :             :         /*
    2029                 :             :          * OK, we think this file is valid.  Incorporate xid into the
    2030                 :             :          * running-minimum result.
    2031                 :             :          */
    2032                 :          55 :         xid = XidFromFullTransactionId(gxact->fxid);
    2033         [ +  + ]:          55 :         if (TransactionIdPrecedes(xid, result))
    2034                 :          49 :             result = xid;
    2035                 :             : 
    2036         [ +  + ]:          55 :         if (xids_p)
    2037                 :             :         {
    2038         [ +  + ]:          21 :             if (nxids == allocsize)
    2039                 :             :             {
    2040         [ +  - ]:          17 :                 if (nxids == 0)
    2041                 :             :                 {
    2042                 :          17 :                     allocsize = 10;
    2043                 :          17 :                     xids = palloc_array(TransactionId, allocsize);
    2044                 :             :                 }
    2045                 :             :                 else
    2046                 :             :                 {
    2047                 :           0 :                     allocsize = allocsize * 2;
    2048                 :           0 :                     xids = repalloc_array(xids, TransactionId, allocsize);
    2049                 :             :                 }
    2050                 :             :             }
    2051                 :          21 :             xids[nxids++] = xid;
    2052                 :             :         }
    2053                 :             : 
    2054                 :          55 :         pfree(buf);
    2055                 :             :     }
    2056                 :        1153 :     LWLockRelease(TwoPhaseStateLock);
    2057                 :             : 
    2058         [ +  + ]:        1153 :     if (xids_p)
    2059                 :             :     {
    2060                 :          76 :         *xids_p = xids;
    2061                 :          76 :         *nxids_p = nxids;
    2062                 :             :     }
    2063                 :             : 
    2064                 :        1153 :     return result;
    2065                 :             : }
    2066                 :             : 
    2067                 :             : /*
    2068                 :             :  * StandbyRecoverPreparedTransactions
    2069                 :             :  *
    2070                 :             :  * Scan the shared memory entries of TwoPhaseState and setup all the required
    2071                 :             :  * information to allow standby queries to treat prepared transactions as still
    2072                 :             :  * active.
    2073                 :             :  *
    2074                 :             :  * This is never called at the end of recovery - we use
    2075                 :             :  * RecoverPreparedTransactions() at that point.
    2076                 :             :  *
    2077                 :             :  * This updates pg_subtrans, so that any subtransactions will be correctly
    2078                 :             :  * seen as in-progress in snapshots taken during recovery.
    2079                 :             :  */
    2080                 :             : void
    2081                 :          76 : StandbyRecoverPreparedTransactions(void)
    2082                 :             : {
    2083                 :             :     int         i;
    2084                 :             : 
    2085                 :          76 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
    2086         [ +  + ]:          97 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
    2087                 :             :     {
    2088                 :             :         char       *buf;
    2089                 :          21 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
    2090                 :             : 
    2091                 :             :         Assert(gxact->inredo);
    2092                 :             : 
    2093                 :          21 :         buf = ProcessTwoPhaseBuffer(gxact->fxid,
    2094                 :             :                                     gxact->prepare_start_lsn,
    2095                 :          21 :                                     gxact->ondisk, true, false);
    2096         [ +  - ]:          21 :         if (buf != NULL)
    2097                 :          21 :             pfree(buf);
    2098                 :             :     }
    2099                 :          76 :     LWLockRelease(TwoPhaseStateLock);
    2100                 :          76 : }
    2101                 :             : 
    2102                 :             : /*
    2103                 :             :  * RecoverPreparedTransactions
    2104                 :             :  *
    2105                 :             :  * Scan the shared memory entries of TwoPhaseState and reload the state for
    2106                 :             :  * each prepared transaction (reacquire locks, etc).
    2107                 :             :  *
    2108                 :             :  * This is run at the end of recovery, but before we allow backends to write
    2109                 :             :  * WAL.
    2110                 :             :  *
    2111                 :             :  * At the end of recovery the way we take snapshots will change. We now need
    2112                 :             :  * to mark all running transactions with their full SubTransSetParent() info
    2113                 :             :  * to allow normal snapshots to work correctly if snapshots overflow.
    2114                 :             :  * We do this here because by definition prepared transactions are the only
    2115                 :             :  * type of write transaction still running, so this is necessary and
    2116                 :             :  * complete.
    2117                 :             :  */
    2118                 :             : void
    2119                 :        1077 : RecoverPreparedTransactions(void)
    2120                 :             : {
    2121                 :             :     int         i;
    2122                 :             : 
    2123                 :        1077 :     LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
    2124         [ +  + ]:        1111 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
    2125                 :             :     {
    2126                 :             :         char       *buf;
    2127                 :          34 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
    2128                 :          34 :         FullTransactionId fxid = gxact->fxid;
    2129                 :             :         char       *bufptr;
    2130                 :             :         TwoPhaseFileHeader *hdr;
    2131                 :             :         TransactionId *subxids;
    2132                 :             :         const char *gid;
    2133                 :             : 
    2134                 :             :         /*
    2135                 :             :          * Reconstruct subtrans state for the transaction --- needed because
    2136                 :             :          * pg_subtrans is not preserved over a restart.  Note that we are
    2137                 :             :          * linking all the subtransactions directly to the top-level XID;
    2138                 :             :          * there may originally have been a more complex hierarchy, but
    2139                 :             :          * there's no need to restore that exactly. It's possible that
    2140                 :             :          * SubTransSetParent has been set before, if the prepared transaction
    2141                 :             :          * generated xid assignment records.
    2142                 :             :          */
    2143                 :          34 :         buf = ProcessTwoPhaseBuffer(gxact->fxid,
    2144                 :             :                                     gxact->prepare_start_lsn,
    2145                 :          34 :                                     gxact->ondisk, true, false);
    2146         [ -  + ]:          34 :         if (buf == NULL)
    2147                 :           0 :             continue;
    2148                 :             : 
    2149         [ +  - ]:          34 :         ereport(LOG,
    2150                 :             :                 (errmsg("recovering prepared transaction %u of epoch %u from shared memory",
    2151                 :             :                         XidFromFullTransactionId(gxact->fxid),
    2152                 :             :                         EpochFromFullTransactionId(gxact->fxid))));
    2153                 :             : 
    2154                 :          34 :         hdr = (TwoPhaseFileHeader *) buf;
    2155                 :             :         Assert(TransactionIdEquals(hdr->xid,
    2156                 :             :                                    XidFromFullTransactionId(gxact->fxid)));
    2157                 :          34 :         bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
    2158                 :          34 :         gid = (const char *) bufptr;
    2159                 :          34 :         bufptr += MAXALIGN(hdr->gidlen);
    2160                 :          34 :         subxids = (TransactionId *) bufptr;
    2161                 :          34 :         bufptr += MAXALIGN(hdr->nsubxacts * sizeof(TransactionId));
    2162                 :          34 :         bufptr += MAXALIGN(hdr->ncommitrels * sizeof(RelFileLocator));
    2163                 :          34 :         bufptr += MAXALIGN(hdr->nabortrels * sizeof(RelFileLocator));
    2164                 :          34 :         bufptr += MAXALIGN(hdr->ncommitstats * sizeof(xl_xact_stats_item));
    2165                 :          34 :         bufptr += MAXALIGN(hdr->nabortstats * sizeof(xl_xact_stats_item));
    2166                 :          34 :         bufptr += MAXALIGN(hdr->ninvalmsgs * sizeof(SharedInvalidationMessage));
    2167                 :             : 
    2168                 :             :         /*
    2169                 :             :          * Recreate its GXACT and dummy PGPROC. But, check whether it was
    2170                 :             :          * added in redo and already has a shmem entry for it.
    2171                 :             :          */
    2172                 :          34 :         MarkAsPreparingGuts(gxact, gxact->fxid, gid,
    2173                 :             :                             hdr->prepared_at,
    2174                 :             :                             hdr->owner, hdr->database);
    2175                 :             : 
    2176                 :             :         /* recovered, so reset the flag for entries generated by redo */
    2177                 :          34 :         gxact->inredo = false;
    2178                 :             : 
    2179                 :          34 :         GXactLoadSubxactData(gxact, hdr->nsubxacts, subxids);
    2180                 :          34 :         MarkAsPrepared(gxact, true);
    2181                 :             : 
    2182                 :          34 :         LWLockRelease(TwoPhaseStateLock);
    2183                 :             : 
    2184                 :             :         /*
    2185                 :             :          * Recover other state (notably locks) using resource managers.
    2186                 :             :          */
    2187                 :          34 :         ProcessRecords(bufptr, fxid, twophase_recover_callbacks);
    2188                 :             : 
    2189                 :             :         /*
    2190                 :             :          * Release locks held by the standby process after we process each
    2191                 :             :          * prepared transaction. As a result, we don't need too many
    2192                 :             :          * additional locks at any one time.
    2193                 :             :          */
    2194         [ +  + ]:          34 :         if (InHotStandby)
    2195                 :           7 :             StandbyReleaseLockTree(hdr->xid, hdr->nsubxacts, subxids);
    2196                 :             : 
    2197                 :             :         /*
    2198                 :             :          * We're done with recovering this transaction. Clear MyLockedGxact,
    2199                 :             :          * like we do in PrepareTransaction() during normal operation.
    2200                 :             :          */
    2201                 :          34 :         PostPrepare_Twophase();
    2202                 :             : 
    2203                 :          34 :         pfree(buf);
    2204                 :             : 
    2205                 :          34 :         LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
    2206                 :             :     }
    2207                 :             : 
    2208                 :        1077 :     LWLockRelease(TwoPhaseStateLock);
    2209                 :        1077 : }
    2210                 :             : 
    2211                 :             : /*
    2212                 :             :  * ProcessTwoPhaseBuffer
    2213                 :             :  *
    2214                 :             :  * Given a FullTransactionId, read it either from disk or read it directly
    2215                 :             :  * via shmem xlog record pointer using the provided "prepare_start_lsn".
    2216                 :             :  *
    2217                 :             :  * If setParent is true, set up subtransaction parent linkages.
    2218                 :             :  *
    2219                 :             :  * If setNextXid is true, set TransamVariables->nextXid to the newest
    2220                 :             :  * value scanned.
    2221                 :             :  */
    2222                 :             : static char *
    2223                 :         126 : ProcessTwoPhaseBuffer(FullTransactionId fxid,
    2224                 :             :                       XLogRecPtr prepare_start_lsn,
    2225                 :             :                       bool fromdisk,
    2226                 :             :                       bool setParent, bool setNextXid)
    2227                 :             : {
    2228                 :         126 :     FullTransactionId nextXid = TransamVariables->nextXid;
    2229                 :             :     TransactionId *subxids;
    2230                 :             :     char       *buf;
    2231                 :             :     TwoPhaseFileHeader *hdr;
    2232                 :             :     int         i;
    2233                 :             : 
    2234                 :             :     Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
    2235                 :             : 
    2236                 :         126 :     if (!fromdisk)
    2237                 :             :         Assert(XLogRecPtrIsValid(prepare_start_lsn));
    2238                 :             : 
    2239                 :             :     /* Already processed? */
    2240   [ +  -  -  + ]:         252 :     if (TransactionIdDidCommit(XidFromFullTransactionId(fxid)) ||
    2241                 :         126 :         TransactionIdDidAbort(XidFromFullTransactionId(fxid)))
    2242                 :             :     {
    2243         [ #  # ]:           0 :         if (fromdisk)
    2244                 :             :         {
    2245         [ #  # ]:           0 :             ereport(WARNING,
    2246                 :             :                     (errmsg("removing stale two-phase state file for transaction %u of epoch %u",
    2247                 :             :                             XidFromFullTransactionId(fxid),
    2248                 :             :                             EpochFromFullTransactionId(fxid))));
    2249                 :           0 :             RemoveTwoPhaseFile(fxid, true);
    2250                 :             :         }
    2251                 :             :         else
    2252                 :             :         {
    2253         [ #  # ]:           0 :             ereport(WARNING,
    2254                 :             :                     (errmsg("removing stale two-phase state from memory for transaction %u of epoch %u",
    2255                 :             :                             XidFromFullTransactionId(fxid),
    2256                 :             :                             EpochFromFullTransactionId(fxid))));
    2257                 :           0 :             PrepareRedoRemoveFull(fxid, true);
    2258                 :             :         }
    2259                 :           0 :         return NULL;
    2260                 :             :     }
    2261                 :             : 
    2262                 :             :     /* Reject XID if too new */
    2263         [ -  + ]:         126 :     if (FullTransactionIdFollowsOrEquals(fxid, nextXid))
    2264                 :             :     {
    2265         [ #  # ]:           0 :         if (fromdisk)
    2266                 :             :         {
    2267         [ #  # ]:           0 :             ereport(WARNING,
    2268                 :             :                     (errmsg("removing future two-phase state file for transaction %u of epoch %u",
    2269                 :             :                             XidFromFullTransactionId(fxid),
    2270                 :             :                             EpochFromFullTransactionId(fxid))));
    2271                 :           0 :             RemoveTwoPhaseFile(fxid, true);
    2272                 :             :         }
    2273                 :             :         else
    2274                 :             :         {
    2275         [ #  # ]:           0 :             ereport(WARNING,
    2276                 :             :                     (errmsg("removing future two-phase state from memory for transaction %u of epoch %u",
    2277                 :             :                             XidFromFullTransactionId(fxid),
    2278                 :             :                             EpochFromFullTransactionId(fxid))));
    2279                 :           0 :             PrepareRedoRemoveFull(fxid, true);
    2280                 :             :         }
    2281                 :           0 :         return NULL;
    2282                 :             :     }
    2283                 :             : 
    2284         [ +  + ]:         126 :     if (fromdisk)
    2285                 :             :     {
    2286                 :             :         /* Read and validate file */
    2287                 :          50 :         buf = ReadTwoPhaseFile(fxid, false);
    2288                 :             :     }
    2289                 :             :     else
    2290                 :             :     {
    2291                 :             :         /* Read xlog data */
    2292                 :          76 :         XlogReadTwoPhaseData(prepare_start_lsn, &buf, NULL);
    2293                 :             :     }
    2294                 :             : 
    2295                 :             :     /* Deconstruct header */
    2296                 :         126 :     hdr = (TwoPhaseFileHeader *) buf;
    2297         [ -  + ]:         126 :     if (!TransactionIdEquals(hdr->xid, XidFromFullTransactionId(fxid)))
    2298                 :             :     {
    2299         [ #  # ]:           0 :         if (fromdisk)
    2300         [ #  # ]:           0 :             ereport(ERROR,
    2301                 :             :                     (errcode(ERRCODE_DATA_CORRUPTED),
    2302                 :             :                      errmsg("corrupted two-phase state file for transaction %u of epoch %u",
    2303                 :             :                             XidFromFullTransactionId(fxid),
    2304                 :             :                             EpochFromFullTransactionId(fxid))));
    2305                 :             :         else
    2306         [ #  # ]:           0 :             ereport(ERROR,
    2307                 :             :                     (errcode(ERRCODE_DATA_CORRUPTED),
    2308                 :             :                      errmsg("corrupted two-phase state in memory for transaction %u of epoch %u",
    2309                 :             :                             XidFromFullTransactionId(fxid),
    2310                 :             :                             EpochFromFullTransactionId(fxid))));
    2311                 :             :     }
    2312                 :             : 
    2313                 :             :     /*
    2314                 :             :      * Examine subtransaction XIDs ... they should all follow main XID, and
    2315                 :             :      * they may force us to advance nextXid.
    2316                 :             :      */
    2317                 :         126 :     subxids = (TransactionId *) (buf +
    2318                 :         126 :                                  MAXALIGN(sizeof(TwoPhaseFileHeader)) +
    2319                 :         126 :                                  MAXALIGN(hdr->gidlen));
    2320         [ +  + ]:        1913 :     for (i = 0; i < hdr->nsubxacts; i++)
    2321                 :             :     {
    2322                 :        1787 :         TransactionId subxid = subxids[i];
    2323                 :             : 
    2324                 :             :         Assert(TransactionIdFollows(subxid, XidFromFullTransactionId(fxid)));
    2325                 :             : 
    2326                 :             :         /* update nextXid if needed */
    2327         [ +  + ]:        1787 :         if (setNextXid)
    2328                 :         823 :             AdvanceNextFullTransactionIdPastXid(subxid);
    2329                 :             : 
    2330         [ +  + ]:        1787 :         if (setParent)
    2331                 :         823 :             SubTransSetParent(subxid, XidFromFullTransactionId(fxid));
    2332                 :             :     }
    2333                 :             : 
    2334                 :         126 :     return buf;
    2335                 :             : }
    2336                 :             : 
    2337                 :             : 
    2338                 :             : /*
    2339                 :             :  *  RecordTransactionCommitPrepared
    2340                 :             :  *
    2341                 :             :  * This is basically the same as RecordTransactionCommit (q.v. if you change
    2342                 :             :  * this function): in particular, we must set DELAY_CHKPT_IN_COMMIT to avoid a
    2343                 :             :  * race condition.
    2344                 :             :  *
    2345                 :             :  * We know the transaction made at least one XLOG entry (its PREPARE),
    2346                 :             :  * so it is never possible to optimize out the commit record.
    2347                 :             :  */
    2348                 :             : static void
    2349                 :         271 : RecordTransactionCommitPrepared(TransactionId xid,
    2350                 :             :                                 int nchildren,
    2351                 :             :                                 TransactionId *children,
    2352                 :             :                                 int nrels,
    2353                 :             :                                 RelFileLocator *rels,
    2354                 :             :                                 int nstats,
    2355                 :             :                                 xl_xact_stats_item *stats,
    2356                 :             :                                 int ninvalmsgs,
    2357                 :             :                                 SharedInvalidationMessage *invalmsgs,
    2358                 :             :                                 bool initfileinval,
    2359                 :             :                                 const char *gid)
    2360                 :             : {
    2361                 :             :     XLogRecPtr  recptr;
    2362                 :             :     TimestampTz committs;
    2363                 :             :     bool        replorigin;
    2364                 :             : 
    2365                 :             :     /*
    2366                 :             :      * Are we using the replication origins feature?  Or, in other words, are
    2367                 :             :      * we replaying remote actions?
    2368                 :             :      */
    2369         [ +  + ]:         294 :     replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
    2370         [ +  - ]:          23 :                   replorigin_xact_state.origin != DoNotReplicateId);
    2371                 :             : 
    2372                 :             :     /* Load the injection point before entering the critical section */
    2373                 :         271 :     INJECTION_POINT_LOAD("commit-after-delay-checkpoint");
    2374                 :             : 
    2375                 :         271 :     START_CRIT_SECTION();
    2376                 :             : 
    2377                 :             :     /* See notes in RecordTransactionCommit */
    2378                 :             :     Assert((MyProc->delayChkptFlags & DELAY_CHKPT_IN_COMMIT) == 0);
    2379                 :         271 :     MyProc->delayChkptFlags |= DELAY_CHKPT_IN_COMMIT;
    2380                 :             : 
    2381                 :         271 :     INJECTION_POINT_CACHED("commit-after-delay-checkpoint", NULL);
    2382                 :             : 
    2383                 :             :     /*
    2384                 :             :      * Ensures the DELAY_CHKPT_IN_COMMIT flag write is globally visible before
    2385                 :             :      * commit time is written.
    2386                 :             :      */
    2387                 :         271 :     pg_write_barrier();
    2388                 :             : 
    2389                 :             :     /*
    2390                 :             :      * Note it is important to set committs value after marking ourselves as
    2391                 :             :      * in the commit critical section (DELAY_CHKPT_IN_COMMIT). This is because
    2392                 :             :      * we want to ensure all transactions that have acquired commit timestamp
    2393                 :             :      * are finished before we allow the logical replication client to advance
    2394                 :             :      * its xid which is used to hold back dead rows for conflict detection.
    2395                 :             :      * See comments atop worker.c.
    2396                 :             :      */
    2397                 :         271 :     committs = GetCurrentTimestamp();
    2398                 :             : 
    2399                 :             :     /*
    2400                 :             :      * Emit the XLOG commit record. Note that we mark 2PC commits as
    2401                 :             :      * potentially having AccessExclusiveLocks since we don't know whether or
    2402                 :             :      * not they do.
    2403                 :             :      */
    2404                 :         271 :     recptr = XactLogCommitRecord(committs,
    2405                 :             :                                  nchildren, children, nrels, rels,
    2406                 :             :                                  nstats, stats,
    2407                 :             :                                  ninvalmsgs, invalmsgs,
    2408                 :             :                                  initfileinval,
    2409                 :         271 :                                  MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK,
    2410                 :             :                                  xid, gid);
    2411                 :             : 
    2412                 :             : 
    2413         [ +  + ]:         271 :     if (replorigin)
    2414                 :             :         /* Move LSNs forward for this replication origin */
    2415                 :          23 :         replorigin_session_advance(replorigin_xact_state.origin_lsn,
    2416                 :             :                                    XactLastRecEnd);
    2417                 :             : 
    2418                 :             :     /*
    2419                 :             :      * Record commit timestamp.  The value comes from plain commit timestamp
    2420                 :             :      * if replorigin is not enabled, or replorigin already set a value for us
    2421                 :             :      * in replorigin_xact_state.origin_timestamp otherwise.
    2422                 :             :      *
    2423                 :             :      * We don't need to WAL-log anything here, as the commit record written
    2424                 :             :      * above already contains the data.
    2425                 :             :      */
    2426   [ +  +  -  + ]:         271 :     if (!replorigin || replorigin_xact_state.origin_timestamp == 0)
    2427                 :         248 :         replorigin_xact_state.origin_timestamp = committs;
    2428                 :             : 
    2429                 :         271 :     TransactionTreeSetCommitTsData(xid, nchildren, children,
    2430                 :             :                                    replorigin_xact_state.origin_timestamp,
    2431                 :         271 :                                    replorigin_xact_state.origin);
    2432                 :             : 
    2433                 :             :     /*
    2434                 :             :      * We don't currently try to sleep before flush here ... nor is there any
    2435                 :             :      * support for async commit of a prepared xact (the very idea is probably
    2436                 :             :      * a contradiction)
    2437                 :             :      */
    2438                 :             : 
    2439                 :             :     /* Flush XLOG to disk */
    2440                 :         271 :     XLogFlush(recptr);
    2441                 :             : 
    2442                 :             :     /* Mark the transaction committed in pg_xact */
    2443                 :         271 :     TransactionIdCommitTree(xid, nchildren, children);
    2444                 :             : 
    2445                 :             :     /* Checkpoint can proceed now */
    2446                 :         271 :     MyProc->delayChkptFlags &= ~DELAY_CHKPT_IN_COMMIT;
    2447                 :             : 
    2448                 :         271 :     END_CRIT_SECTION();
    2449                 :             : 
    2450                 :             :     /*
    2451                 :             :      * Wait for synchronous replication, if required.
    2452                 :             :      *
    2453                 :             :      * Note that at this stage we have marked clog, but still show as running
    2454                 :             :      * in the procarray and continue to hold locks.
    2455                 :             :      */
    2456                 :         271 :     SyncRepWaitForLSN(recptr, true);
    2457                 :         271 : }
    2458                 :             : 
    2459                 :             : /*
    2460                 :             :  *  RecordTransactionAbortPrepared
    2461                 :             :  *
    2462                 :             :  * This is basically the same as RecordTransactionAbort.
    2463                 :             :  *
    2464                 :             :  * We know the transaction made at least one XLOG entry (its PREPARE),
    2465                 :             :  * so it is never possible to optimize out the abort record.
    2466                 :             :  */
    2467                 :             : static void
    2468                 :          50 : RecordTransactionAbortPrepared(TransactionId xid,
    2469                 :             :                                int nchildren,
    2470                 :             :                                TransactionId *children,
    2471                 :             :                                int nrels,
    2472                 :             :                                RelFileLocator *rels,
    2473                 :             :                                int nstats,
    2474                 :             :                                xl_xact_stats_item *stats,
    2475                 :             :                                const char *gid)
    2476                 :             : {
    2477                 :             :     XLogRecPtr  recptr;
    2478                 :             :     bool        replorigin;
    2479                 :             : 
    2480                 :             :     /*
    2481                 :             :      * Are we using the replication origins feature?  Or, in other words, are
    2482                 :             :      * we replaying remote actions?
    2483                 :             :      */
    2484         [ +  + ]:          56 :     replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
    2485         [ +  - ]:           6 :                   replorigin_xact_state.origin != DoNotReplicateId);
    2486                 :             : 
    2487                 :             :     /*
    2488                 :             :      * Catch the scenario where we aborted partway through
    2489                 :             :      * RecordTransactionCommitPrepared ...
    2490                 :             :      */
    2491         [ -  + ]:          50 :     if (TransactionIdDidCommit(xid))
    2492         [ #  # ]:           0 :         elog(PANIC, "cannot abort transaction %u, it was already committed",
    2493                 :             :              xid);
    2494                 :             : 
    2495                 :          50 :     START_CRIT_SECTION();
    2496                 :             : 
    2497                 :             :     /*
    2498                 :             :      * Emit the XLOG commit record. Note that we mark 2PC aborts as
    2499                 :             :      * potentially having AccessExclusiveLocks since we don't know whether or
    2500                 :             :      * not they do.
    2501                 :             :      */
    2502                 :          50 :     recptr = XactLogAbortRecord(GetCurrentTimestamp(),
    2503                 :             :                                 nchildren, children,
    2504                 :             :                                 nrels, rels,
    2505                 :             :                                 nstats, stats,
    2506                 :          50 :                                 MyXactFlags | XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK,
    2507                 :             :                                 xid, gid);
    2508                 :             : 
    2509         [ +  + ]:          50 :     if (replorigin)
    2510                 :             :         /* Move LSNs forward for this replication origin */
    2511                 :           6 :         replorigin_session_advance(replorigin_xact_state.origin_lsn,
    2512                 :             :                                    XactLastRecEnd);
    2513                 :             : 
    2514                 :             :     /* Always flush, since we're about to remove the 2PC state file */
    2515                 :          50 :     XLogFlush(recptr);
    2516                 :             : 
    2517                 :             :     /*
    2518                 :             :      * Mark the transaction aborted in clog.  This is not absolutely necessary
    2519                 :             :      * but we may as well do it while we are here.
    2520                 :             :      */
    2521                 :          50 :     TransactionIdAbortTree(xid, nchildren, children);
    2522                 :             : 
    2523                 :          50 :     END_CRIT_SECTION();
    2524                 :             : 
    2525                 :             :     /*
    2526                 :             :      * Wait for synchronous replication, if required.
    2527                 :             :      *
    2528                 :             :      * Note that at this stage we have marked clog, but still show as running
    2529                 :             :      * in the procarray and continue to hold locks.
    2530                 :             :      */
    2531                 :          50 :     SyncRepWaitForLSN(recptr, false);
    2532                 :          50 : }
    2533                 :             : 
    2534                 :             : /*
    2535                 :             :  * PrepareRedoAdd
    2536                 :             :  *
    2537                 :             :  * Store pointers to the start/end of the WAL record along with the xid in
    2538                 :             :  * a gxact entry in shared memory TwoPhaseState structure.  If caller
    2539                 :             :  * specifies InvalidXLogRecPtr as WAL location to fetch the two-phase
    2540                 :             :  * data, the entry is marked as located on disk.
    2541                 :             :  */
    2542                 :             : void
    2543                 :          98 : PrepareRedoAdd(FullTransactionId fxid, char *buf,
    2544                 :             :                XLogRecPtr start_lsn, XLogRecPtr end_lsn,
    2545                 :             :                ReplOriginId origin_id)
    2546                 :             : {
    2547                 :          98 :     TwoPhaseFileHeader *hdr = (TwoPhaseFileHeader *) buf;
    2548                 :             :     char       *bufptr;
    2549                 :             :     const char *gid;
    2550                 :             :     GlobalTransaction gxact;
    2551                 :             : 
    2552                 :             :     Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
    2553                 :             :     Assert(RecoveryInProgress());
    2554                 :             : 
    2555         [ +  + ]:          98 :     if (!FullTransactionIdIsValid(fxid))
    2556                 :             :     {
    2557                 :             :         Assert(InRecovery);
    2558                 :          82 :         fxid = FullTransactionIdFromAllowableAt(TransamVariables->nextXid,
    2559                 :             :                                                 hdr->xid);
    2560                 :             :     }
    2561                 :             : 
    2562                 :          98 :     bufptr = buf + MAXALIGN(sizeof(TwoPhaseFileHeader));
    2563                 :          98 :     gid = (const char *) bufptr;
    2564                 :             : 
    2565                 :             :     /*
    2566                 :             :      * Reserve the GID for the given transaction in the redo code path.
    2567                 :             :      *
    2568                 :             :      * This creates a gxact struct and puts it into the active array.
    2569                 :             :      *
    2570                 :             :      * In redo, this struct is mainly used to track PREPARE/COMMIT entries in
    2571                 :             :      * shared memory. Hence, we only fill up the bare minimum contents here.
    2572                 :             :      * The gxact also gets marked with gxact->inredo set to true to indicate
    2573                 :             :      * that it got added in the redo phase
    2574                 :             :      */
    2575                 :             : 
    2576                 :             :     /*
    2577                 :             :      * In the event of a crash while a checkpoint was running, it may be
    2578                 :             :      * possible that some two-phase data found its way to disk while its
    2579                 :             :      * corresponding record needs to be replayed in the follow-up recovery. As
    2580                 :             :      * the 2PC data was on disk, it has already been restored at the beginning
    2581                 :             :      * of recovery with restoreTwoPhaseData(), so skip this record to avoid
    2582                 :             :      * duplicates in TwoPhaseState.  If a consistent state has been reached,
    2583                 :             :      * the record is added to TwoPhaseState and it should have no
    2584                 :             :      * corresponding file in pg_twophase.
    2585                 :             :      */
    2586         [ +  + ]:          98 :     if (XLogRecPtrIsValid(start_lsn))
    2587                 :             :     {
    2588                 :             :         char        path[MAXPGPATH];
    2589                 :             : 
    2590                 :             :         Assert(InRecovery);
    2591                 :          82 :         TwoPhaseFilePath(path, fxid);
    2592                 :             : 
    2593         [ -  + ]:          82 :         if (access(path, F_OK) == 0)
    2594                 :             :         {
    2595   [ #  #  #  # ]:           0 :             ereport(reachedConsistency ? ERROR : WARNING,
    2596                 :             :                     (errmsg("could not recover two-phase state file for transaction %u",
    2597                 :             :                             hdr->xid),
    2598                 :             :                      errdetail("Two-phase state file has been found in WAL record %X/%08X, but this transaction has already been restored from disk.",
    2599                 :             :                                LSN_FORMAT_ARGS(start_lsn))));
    2600                 :           0 :             return;
    2601                 :             :         }
    2602                 :             : 
    2603         [ -  + ]:          82 :         if (errno != ENOENT)
    2604         [ #  # ]:           0 :             ereport(ERROR,
    2605                 :             :                     (errcode_for_file_access(),
    2606                 :             :                      errmsg("could not access file \"%s\": %m", path)));
    2607                 :             :     }
    2608                 :             : 
    2609                 :             :     /* Get a free gxact from the freelist */
    2610         [ -  + ]:          98 :     if (TwoPhaseState->freeGXacts == NULL)
    2611         [ #  # ]:           0 :         ereport(ERROR,
    2612                 :             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
    2613                 :             :                  errmsg("maximum number of prepared transactions reached"),
    2614                 :             :                  errhint("Increase \"max_prepared_transactions\" (currently %d).",
    2615                 :             :                          max_prepared_xacts)));
    2616                 :          98 :     gxact = TwoPhaseState->freeGXacts;
    2617                 :          98 :     TwoPhaseState->freeGXacts = gxact->next;
    2618                 :             : 
    2619                 :          98 :     gxact->prepared_at = hdr->prepared_at;
    2620                 :          98 :     gxact->prepare_start_lsn = start_lsn;
    2621                 :          98 :     gxact->prepare_end_lsn = end_lsn;
    2622                 :          98 :     gxact->fxid = fxid;
    2623                 :          98 :     gxact->owner = hdr->owner;
    2624                 :          98 :     gxact->locking_backend = INVALID_PROC_NUMBER;
    2625                 :          98 :     gxact->valid = false;
    2626                 :          98 :     gxact->ondisk = !XLogRecPtrIsValid(start_lsn);
    2627                 :          98 :     gxact->inredo = true;        /* yes, added in redo */
    2628                 :          98 :     strlcpy(gxact->gid, gid, GIDSIZE);
    2629                 :             : 
    2630                 :             :     /* And insert it into the active array */
    2631                 :             :     Assert(TwoPhaseState->numPrepXacts < max_prepared_xacts);
    2632                 :          98 :     TwoPhaseState->prepXacts[TwoPhaseState->numPrepXacts++] = gxact;
    2633                 :             : 
    2634         [ +  + ]:          98 :     if (origin_id != InvalidReplOriginId)
    2635                 :             :     {
    2636                 :             :         /* recover apply progress */
    2637                 :          13 :         replorigin_advance(origin_id, hdr->origin_lsn, end_lsn,
    2638                 :             :                            false /* backward */ , false /* WAL */ );
    2639                 :             :     }
    2640                 :             : 
    2641         [ -  + ]:          98 :     elog(DEBUG2, "added 2PC data in shared memory for transaction %u of epoch %u",
    2642                 :             :          XidFromFullTransactionId(gxact->fxid),
    2643                 :             :          EpochFromFullTransactionId(gxact->fxid));
    2644                 :             : }
    2645                 :             : 
    2646                 :             : /*
    2647                 :             :  * PrepareRedoRemoveFull
    2648                 :             :  *
    2649                 :             :  * Remove the corresponding gxact entry from TwoPhaseState. Also remove
    2650                 :             :  * the 2PC file if a prepared transaction was saved via an earlier checkpoint.
    2651                 :             :  *
    2652                 :             :  * Caller must hold TwoPhaseStateLock in exclusive mode, because TwoPhaseState
    2653                 :             :  * is updated.
    2654                 :             :  */
    2655                 :             : static void
    2656                 :          71 : PrepareRedoRemoveFull(FullTransactionId fxid, bool giveWarning)
    2657                 :             : {
    2658                 :          71 :     GlobalTransaction gxact = NULL;
    2659                 :             :     int         i;
    2660                 :          71 :     bool        found = false;
    2661                 :             : 
    2662                 :             :     Assert(LWLockHeldByMeInMode(TwoPhaseStateLock, LW_EXCLUSIVE));
    2663                 :             :     Assert(RecoveryInProgress());
    2664                 :             : 
    2665         [ +  + ]:          71 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
    2666                 :             :     {
    2667                 :          62 :         gxact = TwoPhaseState->prepXacts[i];
    2668                 :             : 
    2669         [ +  - ]:          62 :         if (FullTransactionIdEquals(gxact->fxid, fxid))
    2670                 :             :         {
    2671                 :             :             Assert(gxact->inredo);
    2672                 :          62 :             found = true;
    2673                 :          62 :             break;
    2674                 :             :         }
    2675                 :             :     }
    2676                 :             : 
    2677                 :             :     /*
    2678                 :             :      * Just leave if there is nothing, this is expected during WAL replay.
    2679                 :             :      */
    2680         [ +  + ]:          71 :     if (!found)
    2681                 :           9 :         return;
    2682                 :             : 
    2683                 :             :     /*
    2684                 :             :      * And now we can clean up any files we may have left.
    2685                 :             :      */
    2686         [ -  + ]:          62 :     elog(DEBUG2, "removing 2PC data for transaction %u of epoch %u ",
    2687                 :             :          XidFromFullTransactionId(fxid),
    2688                 :             :          EpochFromFullTransactionId(fxid));
    2689                 :             : 
    2690         [ +  + ]:          62 :     if (gxact->ondisk)
    2691                 :           5 :         RemoveTwoPhaseFile(fxid, giveWarning);
    2692                 :             : 
    2693                 :          62 :     RemoveGXact(gxact);
    2694                 :             : }
    2695                 :             : 
    2696                 :             : /*
    2697                 :             :  * Wrapper of PrepareRedoRemoveFull(), for TransactionIds.
    2698                 :             :  */
    2699                 :             : void
    2700                 :          71 : PrepareRedoRemove(TransactionId xid, bool giveWarning)
    2701                 :             : {
    2702                 :             :     FullTransactionId fxid =
    2703                 :          71 :         FullTransactionIdFromAllowableAt(TransamVariables->nextXid, xid);
    2704                 :             : 
    2705                 :          71 :     PrepareRedoRemoveFull(fxid, giveWarning);
    2706                 :          71 : }
    2707                 :             : 
    2708                 :             : /*
    2709                 :             :  * LookupGXact
    2710                 :             :  *      Check if the prepared transaction with the given GID, lsn and timestamp
    2711                 :             :  *      exists.
    2712                 :             :  *
    2713                 :             :  * Note that we always compare with the LSN where prepare ends because that is
    2714                 :             :  * what is stored as origin_lsn in the 2PC file.
    2715                 :             :  *
    2716                 :             :  * This function is primarily used to check if the prepared transaction
    2717                 :             :  * received from the upstream (remote node) already exists. Checking only GID
    2718                 :             :  * is not sufficient because a different prepared xact with the same GID can
    2719                 :             :  * exist on the same node. So, we are ensuring to match origin_lsn and
    2720                 :             :  * origin_timestamp of prepared xact to avoid the possibility of a match of
    2721                 :             :  * prepared xact from two different nodes.
    2722                 :             :  */
    2723                 :             : bool
    2724                 :           5 : LookupGXact(const char *gid, XLogRecPtr prepare_end_lsn,
    2725                 :             :             TimestampTz origin_prepare_timestamp)
    2726                 :             : {
    2727                 :             :     int         i;
    2728                 :           5 :     bool        found = false;
    2729                 :             : 
    2730                 :           5 :     LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
    2731         [ +  - ]:           5 :     for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
    2732                 :             :     {
    2733                 :           5 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
    2734                 :             : 
    2735                 :             :         /* Ignore not-yet-valid GIDs. */
    2736   [ +  -  +  - ]:           5 :         if (gxact->valid && strcmp(gxact->gid, gid) == 0)
    2737                 :             :         {
    2738                 :             :             char       *buf;
    2739                 :             :             TwoPhaseFileHeader *hdr;
    2740                 :             : 
    2741                 :             :             /*
    2742                 :             :              * We are not expecting collisions of GXACTs (same gid) between
    2743                 :             :              * publisher and subscribers, so we perform all I/O while holding
    2744                 :             :              * TwoPhaseStateLock for simplicity.
    2745                 :             :              *
    2746                 :             :              * To move the I/O out of the lock, we need to ensure that no
    2747                 :             :              * other backend commits the prepared xact in the meantime. We can
    2748                 :             :              * do this optimization if we encounter many collisions in GID
    2749                 :             :              * between publisher and subscriber.
    2750                 :             :              */
    2751         [ -  + ]:           5 :             if (gxact->ondisk)
    2752                 :           0 :                 buf = ReadTwoPhaseFile(gxact->fxid, false);
    2753                 :             :             else
    2754                 :             :             {
    2755                 :             :                 Assert(gxact->prepare_start_lsn);
    2756                 :           5 :                 XlogReadTwoPhaseData(gxact->prepare_start_lsn, &buf, NULL);
    2757                 :             :             }
    2758                 :             : 
    2759                 :           5 :             hdr = (TwoPhaseFileHeader *) buf;
    2760                 :             : 
    2761         [ +  - ]:           5 :             if (hdr->origin_lsn == prepare_end_lsn &&
    2762         [ +  - ]:           5 :                 hdr->origin_timestamp == origin_prepare_timestamp)
    2763                 :             :             {
    2764                 :           5 :                 found = true;
    2765                 :           5 :                 pfree(buf);
    2766                 :           5 :                 break;
    2767                 :             :             }
    2768                 :             : 
    2769                 :           0 :             pfree(buf);
    2770                 :             :         }
    2771                 :             :     }
    2772                 :           5 :     LWLockRelease(TwoPhaseStateLock);
    2773                 :           5 :     return found;
    2774                 :             : }
    2775                 :             : 
    2776                 :             : /*
    2777                 :             :  * TwoPhaseTransactionGid
    2778                 :             :  *      Form the prepared transaction GID for two_phase transactions.
    2779                 :             :  *
    2780                 :             :  * Return the GID in the supplied buffer.
    2781                 :             :  */
    2782                 :             : void
    2783                 :          53 : TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid_res, int szgid)
    2784                 :             : {
    2785                 :             :     Assert(OidIsValid(subid));
    2786                 :             : 
    2787         [ -  + ]:          53 :     if (!TransactionIdIsValid(xid))
    2788         [ #  # ]:           0 :         ereport(ERROR,
    2789                 :             :                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
    2790                 :             :                  errmsg_internal("invalid two-phase transaction ID")));
    2791                 :             : 
    2792                 :          53 :     snprintf(gid_res, szgid, "pg_gid_%u_%u", subid, xid);
    2793                 :          53 : }
    2794                 :             : 
    2795                 :             : /*
    2796                 :             :  * IsTwoPhaseTransactionGidForSubid
    2797                 :             :  *      Check whether the given GID (as formed by TwoPhaseTransactionGid) is
    2798                 :             :  *      for the specified 'subid'.
    2799                 :             :  */
    2800                 :             : static bool
    2801                 :           0 : IsTwoPhaseTransactionGidForSubid(Oid subid, char *gid)
    2802                 :             : {
    2803                 :             :     int         ret;
    2804                 :             :     Oid         subid_from_gid;
    2805                 :             :     TransactionId xid_from_gid;
    2806                 :             :     char        gid_tmp[GIDSIZE];
    2807                 :             : 
    2808                 :             :     /* Extract the subid and xid from the given GID */
    2809                 :           0 :     ret = sscanf(gid, "pg_gid_%u_%u", &subid_from_gid, &xid_from_gid);
    2810                 :             : 
    2811                 :             :     /*
    2812                 :             :      * Check that the given GID has expected format, and at least the subid
    2813                 :             :      * matches.
    2814                 :             :      */
    2815   [ #  #  #  # ]:           0 :     if (ret != 2 || subid != subid_from_gid)
    2816                 :           0 :         return false;
    2817                 :             : 
    2818                 :             :     /*
    2819                 :             :      * Reconstruct a temporary GID based on the subid and xid extracted from
    2820                 :             :      * the given GID and check whether the temporary GID and the given GID
    2821                 :             :      * match.
    2822                 :             :      */
    2823                 :           0 :     TwoPhaseTransactionGid(subid, xid_from_gid, gid_tmp, sizeof(gid_tmp));
    2824                 :             : 
    2825                 :           0 :     return strcmp(gid, gid_tmp) == 0;
    2826                 :             : }
    2827                 :             : 
    2828                 :             : /*
    2829                 :             :  * LookupGXactBySubid
    2830                 :             :  *      Check if the prepared transaction done by apply worker exists.
    2831                 :             :  */
    2832                 :             : bool
    2833                 :           1 : LookupGXactBySubid(Oid subid)
    2834                 :             : {
    2835                 :           1 :     bool        found = false;
    2836                 :             : 
    2837                 :           1 :     LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
    2838         [ -  + ]:           1 :     for (int i = 0; i < TwoPhaseState->numPrepXacts; i++)
    2839                 :             :     {
    2840                 :           0 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
    2841                 :             : 
    2842                 :             :         /* Ignore not-yet-valid GIDs. */
    2843   [ #  #  #  # ]:           0 :         if (gxact->valid &&
    2844                 :           0 :             IsTwoPhaseTransactionGidForSubid(subid, gxact->gid))
    2845                 :             :         {
    2846                 :           0 :             found = true;
    2847                 :           0 :             break;
    2848                 :             :         }
    2849                 :             :     }
    2850                 :           1 :     LWLockRelease(TwoPhaseStateLock);
    2851                 :             : 
    2852                 :           1 :     return found;
    2853                 :             : }
    2854                 :             : 
    2855                 :             : /*
    2856                 :             :  * TwoPhaseGetOldestXidInCommit
    2857                 :             :  *      Return the oldest transaction ID from prepared transactions that are
    2858                 :             :  *      currently in the commit critical section.
    2859                 :             :  *
    2860                 :             :  * This function only considers transactions in the currently connected
    2861                 :             :  * database. If no matching transactions are found, it returns
    2862                 :             :  * InvalidTransactionId.
    2863                 :             :  */
    2864                 :             : TransactionId
    2865                 :       14811 : TwoPhaseGetOldestXidInCommit(void)
    2866                 :             : {
    2867                 :       14811 :     TransactionId oldestRunningXid = InvalidTransactionId;
    2868                 :             : 
    2869                 :       14811 :     LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
    2870                 :             : 
    2871         [ +  + ]:       29414 :     for (int i = 0; i < TwoPhaseState->numPrepXacts; i++)
    2872                 :             :     {
    2873                 :       14603 :         GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
    2874                 :             :         PGPROC     *commitproc;
    2875                 :             :         TransactionId xid;
    2876                 :             : 
    2877         [ -  + ]:       14603 :         if (!gxact->valid)
    2878                 :           0 :             continue;
    2879                 :             : 
    2880         [ -  + ]:       14603 :         if (gxact->locking_backend == INVALID_PROC_NUMBER)
    2881                 :           0 :             continue;
    2882                 :             : 
    2883                 :             :         /*
    2884                 :             :          * Get the backend that is handling the transaction. It's safe to
    2885                 :             :          * access this backend while holding TwoPhaseStateLock, as the backend
    2886                 :             :          * can only be destroyed after either removing or unlocking the
    2887                 :             :          * current global transaction, both of which require an exclusive
    2888                 :             :          * TwoPhaseStateLock.
    2889                 :             :          */
    2890                 :       14603 :         commitproc = GetPGProcByNumber(gxact->locking_backend);
    2891                 :             : 
    2892         [ -  + ]:       14603 :         if (MyDatabaseId != commitproc->databaseId)
    2893                 :           0 :             continue;
    2894                 :             : 
    2895         [ -  + ]:       14603 :         if ((commitproc->delayChkptFlags & DELAY_CHKPT_IN_COMMIT) == 0)
    2896                 :           0 :             continue;
    2897                 :             : 
    2898                 :       14603 :         xid = XidFromFullTransactionId(gxact->fxid);
    2899                 :             : 
    2900   [ -  +  -  - ]:       14603 :         if (!TransactionIdIsValid(oldestRunningXid) ||
    2901                 :           0 :             TransactionIdPrecedes(xid, oldestRunningXid))
    2902                 :       14603 :             oldestRunningXid = xid;
    2903                 :             :     }
    2904                 :             : 
    2905                 :       14811 :     LWLockRelease(TwoPhaseStateLock);
    2906                 :             : 
    2907                 :       14811 :     return oldestRunningXid;
    2908                 :             : }
        

Generated by: LCOV version 2.0-1