LCOV - code coverage report
Current view: top level - src/backend/access/transam - xlogrecovery.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 86.6 % 1442 1249
Test Date: 2026-07-07 08:15:41 Functions: 98.6 % 69 68
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 65.2 % 1169 762

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * xlogrecovery.c
       4                 :             :  *      Functions for WAL recovery, standby mode
       5                 :             :  *
       6                 :             :  * This source file contains functions controlling WAL recovery.
       7                 :             :  * InitWalRecovery() initializes the system for crash or archive recovery,
       8                 :             :  * or standby mode, depending on configuration options and the state of
       9                 :             :  * the control file and possible backup label file.  PerformWalRecovery()
      10                 :             :  * performs the actual WAL replay, calling the rmgr-specific redo routines.
      11                 :             :  * FinishWalRecovery() performs end-of-recovery checks and cleanup actions,
      12                 :             :  * and prepares information needed to initialize the WAL for writes.  In
      13                 :             :  * addition to these three main functions, there are a bunch of functions
      14                 :             :  * for interrogating recovery state and controlling the recovery process.
      15                 :             :  *
      16                 :             :  *
      17                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      18                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
      19                 :             :  *
      20                 :             :  * src/backend/access/transam/xlogrecovery.c
      21                 :             :  *
      22                 :             :  *-------------------------------------------------------------------------
      23                 :             :  */
      24                 :             : 
      25                 :             : #include "postgres.h"
      26                 :             : 
      27                 :             : #include <ctype.h>
      28                 :             : #include <time.h>
      29                 :             : #include <sys/stat.h>
      30                 :             : #include <sys/time.h>
      31                 :             : #include <unistd.h>
      32                 :             : 
      33                 :             : #include "access/timeline.h"
      34                 :             : #include "access/transam.h"
      35                 :             : #include "access/xact.h"
      36                 :             : #include "access/xlog_internal.h"
      37                 :             : #include "access/xlogarchive.h"
      38                 :             : #include "access/xlogprefetcher.h"
      39                 :             : #include "access/xlogreader.h"
      40                 :             : #include "access/xlogrecovery.h"
      41                 :             : #include "access/xlogutils.h"
      42                 :             : #include "access/xlogwait.h"
      43                 :             : #include "backup/basebackup.h"
      44                 :             : #include "catalog/pg_control.h"
      45                 :             : #include "commands/tablespace.h"
      46                 :             : #include "common/file_utils.h"
      47                 :             : #include "miscadmin.h"
      48                 :             : #include "nodes/miscnodes.h"
      49                 :             : #include "pgstat.h"
      50                 :             : #include "postmaster/bgwriter.h"
      51                 :             : #include "postmaster/startup.h"
      52                 :             : #include "replication/slot.h"
      53                 :             : #include "replication/slotsync.h"
      54                 :             : #include "replication/walreceiver.h"
      55                 :             : #include "storage/fd.h"
      56                 :             : #include "storage/ipc.h"
      57                 :             : #include "storage/latch.h"
      58                 :             : #include "storage/pmsignal.h"
      59                 :             : #include "storage/procarray.h"
      60                 :             : #include "storage/spin.h"
      61                 :             : #include "storage/subsystems.h"
      62                 :             : #include "utils/datetime.h"
      63                 :             : #include "utils/fmgrprotos.h"
      64                 :             : #include "utils/guc_hooks.h"
      65                 :             : #include "utils/pgstat_internal.h"
      66                 :             : #include "utils/pg_lsn.h"
      67                 :             : #include "utils/ps_status.h"
      68                 :             : #include "utils/pg_rusage.h"
      69                 :             : #include "utils/wait_event.h"
      70                 :             : 
      71                 :             : /* Unsupported old recovery command file names (relative to $PGDATA) */
      72                 :             : #define RECOVERY_COMMAND_FILE   "recovery.conf"
      73                 :             : #define RECOVERY_COMMAND_DONE   "recovery.done"
      74                 :             : 
      75                 :             : /*
      76                 :             :  * GUC support
      77                 :             :  */
      78                 :             : const struct config_enum_entry recovery_target_action_options[] = {
      79                 :             :     {"pause", RECOVERY_TARGET_ACTION_PAUSE, false},
      80                 :             :     {"promote", RECOVERY_TARGET_ACTION_PROMOTE, false},
      81                 :             :     {"shutdown", RECOVERY_TARGET_ACTION_SHUTDOWN, false},
      82                 :             :     {NULL, 0, false}
      83                 :             : };
      84                 :             : 
      85                 :             : /* options formerly taken from recovery.conf for archive recovery */
      86                 :             : char       *recoveryRestoreCommand = NULL;
      87                 :             : char       *recoveryEndCommand = NULL;
      88                 :             : char       *archiveCleanupCommand = NULL;
      89                 :             : RecoveryTargetType recoveryTarget = RECOVERY_TARGET_UNSET;
      90                 :             : bool        recoveryTargetInclusive = true;
      91                 :             : int         recoveryTargetAction = RECOVERY_TARGET_ACTION_PAUSE;
      92                 :             : TransactionId recoveryTargetXid;
      93                 :             : char       *recovery_target_time_string;
      94                 :             : TimestampTz recoveryTargetTime;
      95                 :             : const char *recoveryTargetName;
      96                 :             : XLogRecPtr  recoveryTargetLSN;
      97                 :             : int         recovery_min_apply_delay = 0;
      98                 :             : 
      99                 :             : /* options formerly taken from recovery.conf for XLOG streaming */
     100                 :             : char       *PrimaryConnInfo = NULL;
     101                 :             : char       *PrimarySlotName = NULL;
     102                 :             : bool        wal_receiver_create_temp_slot = false;
     103                 :             : 
     104                 :             : /*
     105                 :             :  * recoveryTargetTimeLineGoal: what the user requested, if any
     106                 :             :  *
     107                 :             :  * recoveryTargetTLIRequested: numeric value of requested timeline, if constant
     108                 :             :  *
     109                 :             :  * recoveryTargetTLI: the currently understood target timeline; changes
     110                 :             :  *
     111                 :             :  * expectedTLEs: a list of TimeLineHistoryEntries for recoveryTargetTLI and
     112                 :             :  * the timelines of its known parents, newest first (so recoveryTargetTLI is
     113                 :             :  * always the first list member).  Only these TLIs are expected to be seen in
     114                 :             :  * the WAL segments we read, and indeed only these TLIs will be considered as
     115                 :             :  * candidate WAL files to open at all.
     116                 :             :  *
     117                 :             :  * curFileTLI: the TLI appearing in the name of the current input WAL file.
     118                 :             :  * (This is not necessarily the same as the timeline from which we are
     119                 :             :  * replaying WAL, which StartupXLOG calls replayTLI, because we could be
     120                 :             :  * scanning data that was copied from an ancestor timeline when the current
     121                 :             :  * file was created.)  During a sequential scan we do not allow this value
     122                 :             :  * to decrease.
     123                 :             :  */
     124                 :             : RecoveryTargetTimeLineGoal recoveryTargetTimeLineGoal = RECOVERY_TARGET_TIMELINE_LATEST;
     125                 :             : TimeLineID  recoveryTargetTLIRequested = 0;
     126                 :             : TimeLineID  recoveryTargetTLI = 0;
     127                 :             : static List *expectedTLEs;
     128                 :             : static TimeLineID curFileTLI;
     129                 :             : 
     130                 :             : /*
     131                 :             :  * When ArchiveRecoveryRequested is set, archive recovery was requested,
     132                 :             :  * ie. signal files were present.  When InArchiveRecovery is set, we are
     133                 :             :  * currently recovering using offline XLOG archives.  These variables are only
     134                 :             :  * valid in the startup process.
     135                 :             :  *
     136                 :             :  * When ArchiveRecoveryRequested is true, but InArchiveRecovery is false, we're
     137                 :             :  * currently performing crash recovery using only XLOG files in pg_wal, but
     138                 :             :  * will switch to using offline XLOG archives as soon as we reach the end of
     139                 :             :  * WAL in pg_wal.
     140                 :             :  */
     141                 :             : bool        ArchiveRecoveryRequested = false;
     142                 :             : bool        InArchiveRecovery = false;
     143                 :             : 
     144                 :             : /*
     145                 :             :  * When StandbyModeRequested is set, standby mode was requested, i.e.
     146                 :             :  * standby.signal file was present.  When StandbyMode is set, we are currently
     147                 :             :  * in standby mode.  These variables are only valid in the startup process.
     148                 :             :  * They work similarly to ArchiveRecoveryRequested and InArchiveRecovery.
     149                 :             :  */
     150                 :             : static bool StandbyModeRequested = false;
     151                 :             : bool        StandbyMode = false;
     152                 :             : 
     153                 :             : /* was a signal file present at startup? */
     154                 :             : static bool standby_signal_file_found = false;
     155                 :             : static bool recovery_signal_file_found = false;
     156                 :             : 
     157                 :             : /*
     158                 :             :  * CheckPointLoc is the position of the checkpoint record that determines
     159                 :             :  * where to start the replay.  It comes from the backup label file or the
     160                 :             :  * control file.
     161                 :             :  *
     162                 :             :  * RedoStartLSN is the checkpoint's REDO location, also from the backup label
     163                 :             :  * file or the control file.  In standby mode, XLOG streaming usually starts
     164                 :             :  * from the position where an invalid record was found.  But if we fail to
     165                 :             :  * read even the initial checkpoint record, we use the REDO location instead
     166                 :             :  * of the checkpoint location as the start position of XLOG streaming.
     167                 :             :  * Otherwise we would have to jump backwards to the REDO location after
     168                 :             :  * reading the checkpoint record, because the REDO record can precede the
     169                 :             :  * checkpoint record.
     170                 :             :  */
     171                 :             : static XLogRecPtr CheckPointLoc = InvalidXLogRecPtr;
     172                 :             : static TimeLineID CheckPointTLI = 0;
     173                 :             : static XLogRecPtr RedoStartLSN = InvalidXLogRecPtr;
     174                 :             : static TimeLineID RedoStartTLI = 0;
     175                 :             : 
     176                 :             : /*
     177                 :             :  * Local copy of SharedHotStandbyActive variable. False actually means "not
     178                 :             :  * known, need to check the shared state".
     179                 :             :  */
     180                 :             : static bool LocalHotStandbyActive = false;
     181                 :             : 
     182                 :             : /*
     183                 :             :  * Local copy of SharedPromoteIsTriggered variable. False actually means "not
     184                 :             :  * known, need to check the shared state".
     185                 :             :  */
     186                 :             : static bool LocalPromoteIsTriggered = false;
     187                 :             : 
     188                 :             : /* Has the recovery code requested a walreceiver wakeup? */
     189                 :             : static bool doRequestWalReceiverReply;
     190                 :             : 
     191                 :             : /* XLogReader object used to parse the WAL records */
     192                 :             : static XLogReaderState *xlogreader = NULL;
     193                 :             : 
     194                 :             : /* XLogPrefetcher object used to consume WAL records with read-ahead */
     195                 :             : static XLogPrefetcher *xlogprefetcher = NULL;
     196                 :             : 
     197                 :             : /* Parameters passed down from ReadRecord to the XLogPageRead callback. */
     198                 :             : typedef struct XLogPageReadPrivate
     199                 :             : {
     200                 :             :     int         emode;
     201                 :             :     bool        fetching_ckpt;  /* are we fetching a checkpoint record? */
     202                 :             :     bool        randAccess;
     203                 :             :     TimeLineID  replayTLI;
     204                 :             : } XLogPageReadPrivate;
     205                 :             : 
     206                 :             : /* flag to tell XLogPageRead that we have started replaying */
     207                 :             : static bool InRedo = false;
     208                 :             : 
     209                 :             : /*
     210                 :             :  * Codes indicating where we got a WAL file from during recovery, or where
     211                 :             :  * to attempt to get one.
     212                 :             :  */
     213                 :             : typedef enum
     214                 :             : {
     215                 :             :     XLOG_FROM_ANY = 0,          /* request to read WAL from any source */
     216                 :             :     XLOG_FROM_ARCHIVE,          /* restored using restore_command */
     217                 :             :     XLOG_FROM_PG_WAL,           /* existing file in pg_wal */
     218                 :             :     XLOG_FROM_STREAM,           /* streamed from primary */
     219                 :             : } XLogSource;
     220                 :             : 
     221                 :             : /* human-readable names for XLogSources, for debugging output */
     222                 :             : static const char *const xlogSourceNames[] = {"any", "archive", "pg_wal", "stream"};
     223                 :             : 
     224                 :             : /*
     225                 :             :  * readFile is -1 or a kernel FD for the log file segment that's currently
     226                 :             :  * open for reading.  readSegNo identifies the segment.  readOff is the offset
     227                 :             :  * of the page just read, readLen indicates how much of it has been read into
     228                 :             :  * readBuf, and readSource indicates where we got the currently open file from.
     229                 :             :  *
     230                 :             :  * Note: we could use Reserve/ReleaseExternalFD to track consumption of this
     231                 :             :  * FD too (like for openLogFile in xlog.c); but it doesn't currently seem
     232                 :             :  * worthwhile, since the XLOG is not read by general-purpose sessions.
     233                 :             :  */
     234                 :             : static int  readFile = -1;
     235                 :             : static XLogSegNo readSegNo = 0;
     236                 :             : static uint32 readOff = 0;
     237                 :             : static uint32 readLen = 0;
     238                 :             : static XLogSource readSource = XLOG_FROM_ANY;
     239                 :             : 
     240                 :             : /*
     241                 :             :  * Keeps track of which source we're currently reading from. This is
     242                 :             :  * different from readSource in that this is always set, even when we don't
     243                 :             :  * currently have a WAL file open. If lastSourceFailed is set, our last
     244                 :             :  * attempt to read from currentSource failed, and we should try another source
     245                 :             :  * next.
     246                 :             :  *
     247                 :             :  * pendingWalRcvRestart is set when a config change occurs that requires a
     248                 :             :  * walreceiver restart.  This is only valid in XLOG_FROM_STREAM state.
     249                 :             :  */
     250                 :             : static XLogSource currentSource = XLOG_FROM_ANY;
     251                 :             : static bool lastSourceFailed = false;
     252                 :             : static bool pendingWalRcvRestart = false;
     253                 :             : 
     254                 :             : /*
     255                 :             :  * These variables track when we last obtained some WAL data to process,
     256                 :             :  * and where we got it from.  (XLogReceiptSource is initially the same as
     257                 :             :  * readSource, but readSource gets reset to zero when we don't have data
     258                 :             :  * to process right now.  It is also different from currentSource, which
     259                 :             :  * also changes when we try to read from a source and fail, while
     260                 :             :  * XLogReceiptSource tracks where we last successfully read some WAL.)
     261                 :             :  */
     262                 :             : static TimestampTz XLogReceiptTime = 0;
     263                 :             : static XLogSource XLogReceiptSource = XLOG_FROM_ANY;
     264                 :             : 
     265                 :             : /* Local copy of WalRcv->flushedUpto */
     266                 :             : static XLogRecPtr flushedUpto = InvalidXLogRecPtr;
     267                 :             : static TimeLineID receiveTLI = 0;
     268                 :             : 
     269                 :             : /*
     270                 :             :  * Copy of minRecoveryPoint and backupEndPoint from the control file.
     271                 :             :  *
     272                 :             :  * In order to reach consistency, we must replay the WAL up to
     273                 :             :  * minRecoveryPoint.  If backupEndRequired is true, we must also reach
     274                 :             :  * backupEndPoint, or if it's invalid, an end-of-backup record corresponding
     275                 :             :  * to backupStartPoint.
     276                 :             :  *
     277                 :             :  * Note: In archive recovery, after consistency has been reached, the
     278                 :             :  * functions in xlog.c will start updating minRecoveryPoint in the control
     279                 :             :  * file.  But this copy of minRecoveryPoint variable reflects the value at the
     280                 :             :  * beginning of recovery, and is *not* updated after consistency is reached.
     281                 :             :  */
     282                 :             : static XLogRecPtr minRecoveryPoint;
     283                 :             : static TimeLineID minRecoveryPointTLI;
     284                 :             : 
     285                 :             : static XLogRecPtr backupStartPoint;
     286                 :             : static XLogRecPtr backupEndPoint;
     287                 :             : static bool backupEndRequired = false;
     288                 :             : 
     289                 :             : /*
     290                 :             :  * Have we reached a consistent database state?  In crash recovery, we have
     291                 :             :  * to replay all the WAL, so reachedConsistency is never set.  During archive
     292                 :             :  * recovery, the database is consistent once minRecoveryPoint is reached.
     293                 :             :  *
     294                 :             :  * Consistent state means that the system is internally consistent, all
     295                 :             :  * the WAL has been replayed up to a certain point, and importantly, there
     296                 :             :  * is no trace of later actions on disk.
     297                 :             :  *
     298                 :             :  * This flag is used only by the startup process and postmaster. When
     299                 :             :  * minRecoveryPoint is reached, the startup process sets it to true and
     300                 :             :  * sends a PMSIGNAL_RECOVERY_CONSISTENT signal to the postmaster,
     301                 :             :  * which then sets it to true upon receiving the signal.
     302                 :             :  */
     303                 :             : bool        reachedConsistency = false;
     304                 :             : 
     305                 :             : /* Buffers dedicated to consistency checks of size BLCKSZ */
     306                 :             : static char *replay_image_masked = NULL;
     307                 :             : static char *primary_image_masked = NULL;
     308                 :             : 
     309                 :             : XLogRecoveryCtlData *XLogRecoveryCtl = NULL;
     310                 :             : 
     311                 :             : static void XLogRecoveryShmemRequest(void *arg);
     312                 :             : static void XLogRecoveryShmemInit(void *arg);
     313                 :             : 
     314                 :             : const ShmemCallbacks XLogRecoveryShmemCallbacks = {
     315                 :             :     .request_fn = XLogRecoveryShmemRequest,
     316                 :             :     .init_fn = XLogRecoveryShmemInit,
     317                 :             : };
     318                 :             : 
     319                 :             : /*
     320                 :             :  * abortedRecPtr is the start pointer of a broken record at end of WAL when
     321                 :             :  * recovery completes; missingContrecPtr is the location of the first
     322                 :             :  * contrecord that went missing.  See CreateOverwriteContrecordRecord for
     323                 :             :  * details.
     324                 :             :  */
     325                 :             : static XLogRecPtr abortedRecPtr;
     326                 :             : static XLogRecPtr missingContrecPtr;
     327                 :             : 
     328                 :             : /*
     329                 :             :  * if recoveryStopsBefore/After returns true, it saves information of the stop
     330                 :             :  * point here
     331                 :             :  */
     332                 :             : static TransactionId recoveryStopXid;
     333                 :             : static TimestampTz recoveryStopTime;
     334                 :             : static XLogRecPtr recoveryStopLSN;
     335                 :             : static char recoveryStopName[MAXFNAMELEN];
     336                 :             : static bool recoveryStopAfter;
     337                 :             : 
     338                 :             : /* prototypes for local functions */
     339                 :             : static void ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI);
     340                 :             : 
     341                 :             : static void EnableStandbyMode(void);
     342                 :             : static void readRecoverySignalFile(void);
     343                 :             : static void validateRecoveryParameters(void);
     344                 :             : static bool read_backup_label(XLogRecPtr *checkPointLoc,
     345                 :             :                               TimeLineID *backupLabelTLI,
     346                 :             :                               bool *backupEndRequired, bool *backupFromStandby);
     347                 :             : static bool read_tablespace_map(List **tablespaces);
     348                 :             : 
     349                 :             : static void xlogrecovery_redo(XLogReaderState *record, TimeLineID replayTLI);
     350                 :             : static void CheckRecoveryConsistency(void);
     351                 :             : static void rm_redo_error_callback(void *arg);
     352                 :             : #ifdef WAL_DEBUG
     353                 :             : static void xlog_outrec(StringInfo buf, XLogReaderState *record);
     354                 :             : #endif
     355                 :             : static void xlog_block_info(StringInfo buf, XLogReaderState *record);
     356                 :             : static void checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI,
     357                 :             :                                 TimeLineID prevTLI, TimeLineID replayTLI);
     358                 :             : static bool getRecordTimestamp(XLogReaderState *record, TimestampTz *recordXtime);
     359                 :             : static void verifyBackupPageConsistency(XLogReaderState *record);
     360                 :             : 
     361                 :             : static bool recoveryStopsBefore(XLogReaderState *record);
     362                 :             : static bool recoveryStopsAfter(XLogReaderState *record);
     363                 :             : static char *getRecoveryStopReason(void);
     364                 :             : static void recoveryPausesHere(bool endOfRecovery);
     365                 :             : static bool recoveryApplyDelay(XLogReaderState *record);
     366                 :             : static void ConfirmRecoveryPaused(void);
     367                 :             : 
     368                 :             : static XLogRecord *ReadRecord(XLogPrefetcher *xlogprefetcher,
     369                 :             :                               int emode, bool fetching_ckpt,
     370                 :             :                               TimeLineID replayTLI);
     371                 :             : 
     372                 :             : static int  XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr,
     373                 :             :                          int reqLen, XLogRecPtr targetRecPtr, char *readBuf);
     374                 :             : static XLogPageReadResult WaitForWALToBecomeAvailable(XLogRecPtr RecPtr,
     375                 :             :                                                       bool randAccess,
     376                 :             :                                                       bool fetching_ckpt,
     377                 :             :                                                       XLogRecPtr tliRecPtr,
     378                 :             :                                                       TimeLineID replayTLI,
     379                 :             :                                                       XLogRecPtr replayLSN,
     380                 :             :                                                       bool nonblocking);
     381                 :             : static int  emode_for_corrupt_record(int emode, XLogRecPtr RecPtr);
     382                 :             : static XLogRecord *ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher,
     383                 :             :                                         XLogRecPtr RecPtr, TimeLineID replayTLI);
     384                 :             : static bool rescanLatestTimeLine(TimeLineID replayTLI, XLogRecPtr replayLSN);
     385                 :             : static int  XLogFileRead(XLogSegNo segno, TimeLineID tli,
     386                 :             :                          XLogSource source, bool notfoundOk);
     387                 :             : static int  XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
     388                 :             : 
     389                 :             : static bool CheckForStandbyTrigger(void);
     390                 :             : static void SetPromoteIsTriggered(void);
     391                 :             : static bool HotStandbyActiveInReplay(void);
     392                 :             : 
     393                 :             : static void SetCurrentChunkStartTime(TimestampTz xtime);
     394                 :             : static void SetLatestXTime(TimestampTz xtime);
     395                 :             : 
     396                 :             : /*
     397                 :             :  * Register shared memory for WAL recovery
     398                 :             :  */
     399                 :             : static void
     400                 :        1249 : XLogRecoveryShmemRequest(void *arg)
     401                 :             : {
     402                 :        1249 :     ShmemRequestStruct(.name = "XLOG Recovery Ctl",
     403                 :             :                        .size = sizeof(XLogRecoveryCtlData),
     404                 :             :                        .ptr = (void **) &XLogRecoveryCtl,
     405                 :             :         );
     406                 :        1249 : }
     407                 :             : 
     408                 :             : static void
     409                 :        1246 : XLogRecoveryShmemInit(void *arg)
     410                 :             : {
     411                 :        1246 :     memset(XLogRecoveryCtl, 0, sizeof(XLogRecoveryCtlData));
     412                 :             : 
     413                 :        1246 :     SpinLockInit(&XLogRecoveryCtl->info_lck);
     414                 :        1246 :     InitSharedLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
     415                 :        1246 :     ConditionVariableInit(&XLogRecoveryCtl->recoveryNotPausedCV);
     416                 :        1246 : }
     417                 :             : 
     418                 :             : /*
     419                 :             :  * A thin wrapper to enable StandbyMode and do other preparatory work as
     420                 :             :  * needed.
     421                 :             :  */
     422                 :             : static void
     423                 :         122 : EnableStandbyMode(void)
     424                 :             : {
     425                 :         122 :     StandbyMode = true;
     426                 :             : 
     427                 :             :     /*
     428                 :             :      * To avoid server log bloat, we don't report recovery progress in a
     429                 :             :      * standby as it will always be in recovery unless promoted. We disable
     430                 :             :      * startup progress timeout in standby mode to avoid calling
     431                 :             :      * startup_progress_timeout_handler() unnecessarily.
     432                 :             :      */
     433                 :         122 :     disable_startup_progress_timeout();
     434                 :         122 : }
     435                 :             : 
     436                 :             : /*
     437                 :             :  * Prepare the system for WAL recovery, if needed.
     438                 :             :  *
     439                 :             :  * This is called by StartupXLOG() which coordinates the server startup
     440                 :             :  * sequence.  This function analyzes the control file and the backup label
     441                 :             :  * file, if any, and figures out whether we need to perform crash recovery or
     442                 :             :  * archive recovery, and how far we need to replay the WAL to reach a
     443                 :             :  * consistent state.
     444                 :             :  *
     445                 :             :  * This doesn't yet change the on-disk state, except for creating the symlinks
     446                 :             :  * from table space map file if any, and for fetching WAL files needed to find
     447                 :             :  * the checkpoint record.  On entry, the caller has already read the control
     448                 :             :  * file into memory, and passes it as argument.  This function updates it to
     449                 :             :  * reflect the recovery state, and the caller is expected to write it back to
     450                 :             :  * disk after initializing other subsystems, but before calling
     451                 :             :  * PerformWalRecovery().
     452                 :             :  *
     453                 :             :  * This initializes some global variables like ArchiveRecoveryRequested, and
     454                 :             :  * StandbyModeRequested and InRecovery.
     455                 :             :  */
     456                 :             : void
     457                 :        1089 : InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr,
     458                 :             :                 bool *haveBackupLabel_ptr, bool *haveTblspcMap_ptr)
     459                 :             : {
     460                 :             :     XLogPageReadPrivate *private;
     461                 :             :     struct stat st;
     462                 :             :     bool        wasShutdown;
     463                 :             :     XLogRecord *record;
     464                 :             :     DBState     dbstate_at_startup;
     465                 :        1089 :     bool        haveTblspcMap = false;
     466                 :        1089 :     bool        haveBackupLabel = false;
     467                 :             :     CheckPoint  checkPoint;
     468                 :        1089 :     bool        backupFromStandby = false;
     469                 :             : 
     470                 :        1089 :     dbstate_at_startup = ControlFile->state;
     471                 :             : 
     472                 :             :     /*
     473                 :             :      * Initialize on the assumption we want to recover to the latest timeline
     474                 :             :      * that's active according to pg_control.
     475                 :             :      */
     476                 :        1089 :     if (ControlFile->minRecoveryPointTLI >
     477         [ +  + ]:        1089 :         ControlFile->checkPointCopy.ThisTimeLineID)
     478                 :           2 :         recoveryTargetTLI = ControlFile->minRecoveryPointTLI;
     479                 :             :     else
     480                 :        1087 :         recoveryTargetTLI = ControlFile->checkPointCopy.ThisTimeLineID;
     481                 :             : 
     482                 :             :     /*
     483                 :             :      * Check for signal files, and if so set up state for offline recovery
     484                 :             :      */
     485                 :        1089 :     readRecoverySignalFile();
     486                 :        1089 :     validateRecoveryParameters();
     487                 :             : 
     488                 :             :     /*
     489                 :             :      * Take ownership of the wakeup latch if we're going to sleep during
     490                 :             :      * recovery, if required.
     491                 :             :      */
     492         [ +  + ]:        1089 :     if (ArchiveRecoveryRequested)
     493                 :         127 :         OwnLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
     494                 :             : 
     495                 :             :     /*
     496                 :             :      * Set the WAL reading processor now, as it will be needed when reading
     497                 :             :      * the checkpoint record required (backup_label or not).
     498                 :             :      */
     499                 :        1089 :     private = palloc0_object(XLogPageReadPrivate);
     500                 :        1089 :     xlogreader =
     501                 :        1089 :         XLogReaderAllocate(wal_segment_size, NULL,
     502                 :        1089 :                            XL_ROUTINE(.page_read = &XLogPageRead,
     503                 :             :                                       .segment_open = NULL,
     504                 :             :                                       .segment_close = wal_segment_close),
     505                 :             :                            private);
     506         [ -  + ]:        1089 :     if (!xlogreader)
     507         [ #  # ]:           0 :         ereport(ERROR,
     508                 :             :                 (errcode(ERRCODE_OUT_OF_MEMORY),
     509                 :             :                  errmsg("out of memory"),
     510                 :             :                  errdetail("Failed while allocating a WAL reading processor.")));
     511                 :        1089 :     xlogreader->system_identifier = ControlFile->system_identifier;
     512                 :             : 
     513                 :             :     /*
     514                 :             :      * Set the WAL decode buffer size.  This limits how far ahead we can read
     515                 :             :      * in the WAL.
     516                 :             :      */
     517                 :        1089 :     XLogReaderSetDecodeBuffer(xlogreader, NULL, wal_decode_buffer_size);
     518                 :             : 
     519                 :             :     /* Create a WAL prefetcher. */
     520                 :        1089 :     xlogprefetcher = XLogPrefetcherAllocate(xlogreader);
     521                 :             : 
     522                 :             :     /*
     523                 :             :      * Allocate two page buffers dedicated to WAL consistency checks.  We do
     524                 :             :      * it this way, rather than just making static arrays, for two reasons:
     525                 :             :      * (1) no need to waste the storage in most instantiations of the backend;
     526                 :             :      * (2) a static char array isn't guaranteed to have any particular
     527                 :             :      * alignment, whereas palloc() will provide MAXALIGN'd storage.
     528                 :             :      */
     529                 :        1089 :     replay_image_masked = (char *) palloc(BLCKSZ);
     530                 :        1089 :     primary_image_masked = (char *) palloc(BLCKSZ);
     531                 :             : 
     532                 :             :     /*
     533                 :             :      * Read the backup_label file.  We want to run this part of the recovery
     534                 :             :      * process after checking for signal files and after performing validation
     535                 :             :      * of the recovery parameters.
     536                 :             :      */
     537         [ +  + ]:        1089 :     if (read_backup_label(&CheckPointLoc, &CheckPointTLI, &backupEndRequired,
     538                 :             :                           &backupFromStandby))
     539                 :             :     {
     540                 :          89 :         List       *tablespaces = NIL;
     541                 :             : 
     542                 :             :         /*
     543                 :             :          * Archive recovery was requested, and thanks to the backup label
     544                 :             :          * file, we know how far we need to replay to reach consistency. Enter
     545                 :             :          * archive recovery directly.
     546                 :             :          */
     547                 :          89 :         InArchiveRecovery = true;
     548         [ +  + ]:          89 :         if (StandbyModeRequested)
     549                 :          77 :             EnableStandbyMode();
     550                 :             : 
     551                 :             :         /*
     552                 :             :          * Omitting backup_label when creating a new replica, PITR node etc.
     553                 :             :          * unfortunately is a common cause of corruption.  Logging that
     554                 :             :          * backup_label was used makes it a bit easier to exclude that as the
     555                 :             :          * cause of observed corruption.
     556                 :             :          *
     557                 :             :          * Do so before we try to read the checkpoint record (which can fail),
     558                 :             :          * as otherwise it can be hard to understand why a checkpoint other
     559                 :             :          * than ControlFile->checkPoint is used.
     560                 :             :          */
     561         [ +  - ]:          89 :         ereport(LOG,
     562                 :             :                 errmsg("starting backup recovery with redo LSN %X/%08X, checkpoint LSN %X/%08X, on timeline ID %u",
     563                 :             :                        LSN_FORMAT_ARGS(RedoStartLSN),
     564                 :             :                        LSN_FORMAT_ARGS(CheckPointLoc),
     565                 :             :                        CheckPointTLI));
     566                 :             : 
     567                 :             :         /*
     568                 :             :          * When a backup_label file is present, we want to roll forward from
     569                 :             :          * the checkpoint it identifies, rather than using pg_control.
     570                 :             :          */
     571                 :          89 :         record = ReadCheckpointRecord(xlogprefetcher, CheckPointLoc,
     572                 :             :                                       CheckPointTLI);
     573         [ +  - ]:          89 :         if (record != NULL)
     574                 :             :         {
     575                 :          89 :             memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
     576                 :          89 :             wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
     577         [ +  + ]:          89 :             ereport(DEBUG1,
     578                 :             :                     errmsg_internal("checkpoint record is at %X/%08X",
     579                 :             :                                     LSN_FORMAT_ARGS(CheckPointLoc)));
     580                 :          89 :             InRecovery = true;  /* force recovery even if SHUTDOWNED */
     581                 :             : 
     582                 :             :             /*
     583                 :             :              * Make sure that REDO location exists. This may not be the case
     584                 :             :              * if there was a crash during an online backup, which left a
     585                 :             :              * backup_label around that references a WAL segment that's
     586                 :             :              * already been archived.
     587                 :             :              */
     588         [ +  - ]:          89 :             if (checkPoint.redo < CheckPointLoc)
     589                 :             :             {
     590                 :          89 :                 XLogPrefetcherBeginRead(xlogprefetcher, checkPoint.redo);
     591         [ -  + ]:          89 :                 if (!ReadRecord(xlogprefetcher, LOG, false,
     592                 :             :                                 checkPoint.ThisTimeLineID))
     593         [ #  # ]:           0 :                     ereport(FATAL,
     594                 :             :                             errmsg("could not find redo location %X/%08X referenced by checkpoint record at %X/%08X",
     595                 :             :                                    LSN_FORMAT_ARGS(checkPoint.redo), LSN_FORMAT_ARGS(CheckPointLoc)),
     596                 :             :                             errhint("If you are restoring from a backup, touch \"%s/recovery.signal\" or \"%s/standby.signal\" and add required recovery options.\n"
     597                 :             :                                     "If you are not restoring from a backup, try removing the file \"%s/backup_label\".\n"
     598                 :             :                                     "Be careful: removing \"%s/backup_label\" will result in a corrupt cluster if restoring from a backup.",
     599                 :             :                                     DataDir, DataDir, DataDir, DataDir));
     600                 :             :             }
     601                 :             :         }
     602                 :             :         else
     603                 :             :         {
     604         [ #  # ]:           0 :             ereport(FATAL,
     605                 :             :                     errmsg("could not locate required checkpoint record at %X/%08X",
     606                 :             :                            LSN_FORMAT_ARGS(CheckPointLoc)),
     607                 :             :                     errhint("If you are restoring from a backup, touch \"%s/recovery.signal\" or \"%s/standby.signal\" and add required recovery options.\n"
     608                 :             :                             "If you are not restoring from a backup, try removing the file \"%s/backup_label\".\n"
     609                 :             :                             "Be careful: removing \"%s/backup_label\" will result in a corrupt cluster if restoring from a backup.",
     610                 :             :                             DataDir, DataDir, DataDir, DataDir));
     611                 :             :             wasShutdown = false;    /* keep compiler quiet */
     612                 :             :         }
     613                 :             : 
     614                 :             :         /* Read the tablespace_map file if present and create symlinks. */
     615         [ +  + ]:          89 :         if (read_tablespace_map(&tablespaces))
     616                 :             :         {
     617                 :             :             ListCell   *lc;
     618                 :             : 
     619   [ +  -  +  +  :           4 :             foreach(lc, tablespaces)
                   +  + ]
     620                 :             :             {
     621                 :           2 :                 tablespaceinfo *ti = lfirst(lc);
     622                 :             :                 char       *linkloc;
     623                 :             : 
     624                 :           2 :                 linkloc = psprintf("%s/%u", PG_TBLSPC_DIR, ti->oid);
     625                 :             : 
     626                 :             :                 /*
     627                 :             :                  * Remove the existing symlink if any and Create the symlink
     628                 :             :                  * under PGDATA.
     629                 :             :                  */
     630                 :           2 :                 remove_tablespace_symlink(linkloc);
     631                 :             : 
     632         [ -  + ]:           2 :                 if (symlink(ti->path, linkloc) < 0)
     633         [ #  # ]:           0 :                     ereport(ERROR,
     634                 :             :                             (errcode_for_file_access(),
     635                 :             :                              errmsg("could not create symbolic link \"%s\": %m",
     636                 :             :                                     linkloc)));
     637                 :             : 
     638                 :           2 :                 pfree(ti->path);
     639                 :           2 :                 pfree(ti);
     640                 :             :             }
     641                 :             : 
     642                 :             :             /* tell the caller to delete it later */
     643                 :           2 :             haveTblspcMap = true;
     644                 :             :         }
     645                 :             : 
     646                 :             :         /* tell the caller to delete it later */
     647                 :          89 :         haveBackupLabel = true;
     648                 :             :     }
     649                 :             :     else
     650                 :             :     {
     651                 :             :         /* No backup_label file has been found if we are here. */
     652                 :             : 
     653                 :             :         /*
     654                 :             :          * If tablespace_map file is present without backup_label file, there
     655                 :             :          * is no use of such file.  There is no harm in retaining it, but it
     656                 :             :          * is better to get rid of the map file so that we don't have any
     657                 :             :          * redundant file in data directory and it will avoid any sort of
     658                 :             :          * confusion.  It seems prudent though to just rename the file out of
     659                 :             :          * the way rather than delete it completely, also we ignore any error
     660                 :             :          * that occurs in rename operation as even if map file is present
     661                 :             :          * without backup_label file, it is harmless.
     662                 :             :          */
     663         [ +  + ]:        1000 :         if (stat(TABLESPACE_MAP, &st) == 0)
     664                 :             :         {
     665                 :           1 :             unlink(TABLESPACE_MAP_OLD);
     666         [ +  - ]:           1 :             if (durable_rename(TABLESPACE_MAP, TABLESPACE_MAP_OLD, DEBUG1) == 0)
     667         [ +  - ]:           1 :                 ereport(LOG,
     668                 :             :                         (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
     669                 :             :                                 TABLESPACE_MAP, BACKUP_LABEL_FILE),
     670                 :             :                          errdetail("File \"%s\" was renamed to \"%s\".",
     671                 :             :                                    TABLESPACE_MAP, TABLESPACE_MAP_OLD)));
     672                 :             :             else
     673         [ #  # ]:           0 :                 ereport(LOG,
     674                 :             :                         (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
     675                 :             :                                 TABLESPACE_MAP, BACKUP_LABEL_FILE),
     676                 :             :                          errdetail("Could not rename file \"%s\" to \"%s\": %m.",
     677                 :             :                                    TABLESPACE_MAP, TABLESPACE_MAP_OLD)));
     678                 :             :         }
     679                 :             : 
     680                 :             :         /*
     681                 :             :          * It's possible that archive recovery was requested, but we don't
     682                 :             :          * know how far we need to replay the WAL before we reach consistency.
     683                 :             :          * This can happen for example if a base backup is taken from a
     684                 :             :          * running server using an atomic filesystem snapshot, without calling
     685                 :             :          * pg_backup_start/stop. Or if you just kill a running primary server
     686                 :             :          * and put it into archive recovery by creating a recovery signal
     687                 :             :          * file.
     688                 :             :          *
     689                 :             :          * Our strategy in that case is to perform crash recovery first,
     690                 :             :          * replaying all the WAL present in pg_wal, and only enter archive
     691                 :             :          * recovery after that.
     692                 :             :          *
     693                 :             :          * But usually we already know how far we need to replay the WAL (up
     694                 :             :          * to minRecoveryPoint, up to backupEndPoint, or until we see an
     695                 :             :          * end-of-backup record), and we can enter archive recovery directly.
     696                 :             :          */
     697         [ +  + ]:        1000 :         if (ArchiveRecoveryRequested &&
     698         [ +  + ]:          45 :             (XLogRecPtrIsValid(ControlFile->minRecoveryPoint) ||
     699         [ +  - ]:           9 :              ControlFile->backupEndRequired ||
     700         [ +  - ]:           9 :              XLogRecPtrIsValid(ControlFile->backupEndPoint) ||
     701         [ +  + ]:           9 :              ControlFile->state == DB_SHUTDOWNED))
     702                 :             :         {
     703                 :          44 :             InArchiveRecovery = true;
     704         [ +  - ]:          44 :             if (StandbyModeRequested)
     705                 :          44 :                 EnableStandbyMode();
     706                 :             :         }
     707                 :             : 
     708                 :             :         /*
     709                 :             :          * For the same reason as when starting up with backup_label present,
     710                 :             :          * emit a log message when we continue initializing from a base
     711                 :             :          * backup.
     712                 :             :          */
     713         [ -  + ]:        1000 :         if (XLogRecPtrIsValid(ControlFile->backupStartPoint))
     714         [ #  # ]:           0 :             ereport(LOG,
     715                 :             :                     errmsg("restarting backup recovery with redo LSN %X/%08X",
     716                 :             :                            LSN_FORMAT_ARGS(ControlFile->backupStartPoint)));
     717                 :             : 
     718                 :             :         /* Get the last valid checkpoint record. */
     719                 :        1000 :         CheckPointLoc = ControlFile->checkPoint;
     720                 :        1000 :         CheckPointTLI = ControlFile->checkPointCopy.ThisTimeLineID;
     721                 :        1000 :         RedoStartLSN = ControlFile->checkPointCopy.redo;
     722                 :        1000 :         RedoStartTLI = ControlFile->checkPointCopy.ThisTimeLineID;
     723                 :        1000 :         record = ReadCheckpointRecord(xlogprefetcher, CheckPointLoc,
     724                 :             :                                       CheckPointTLI);
     725         [ +  + ]:        1000 :         if (record != NULL)
     726                 :             :         {
     727         [ +  + ]:         999 :             ereport(DEBUG1,
     728                 :             :                     errmsg_internal("checkpoint record is at %X/%08X",
     729                 :             :                                     LSN_FORMAT_ARGS(CheckPointLoc)));
     730                 :             :         }
     731                 :             :         else
     732                 :             :         {
     733                 :             :             /*
     734                 :             :              * We used to attempt to go back to a secondary checkpoint record
     735                 :             :              * here, but only when not in standby mode. We now just fail if we
     736                 :             :              * can't read the last checkpoint because this allows us to
     737                 :             :              * simplify processing around checkpoints.
     738                 :             :              */
     739         [ +  - ]:           1 :             ereport(FATAL,
     740                 :             :                     errmsg("could not locate a valid checkpoint record at %X/%08X",
     741                 :             :                            LSN_FORMAT_ARGS(CheckPointLoc)));
     742                 :             :         }
     743                 :         999 :         memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
     744                 :         999 :         wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
     745                 :             : 
     746                 :             :         /* Make sure that REDO location exists. */
     747         [ +  + ]:         999 :         if (checkPoint.redo < CheckPointLoc)
     748                 :             :         {
     749                 :          45 :             XLogPrefetcherBeginRead(xlogprefetcher, checkPoint.redo);
     750         [ +  + ]:          45 :             if (!ReadRecord(xlogprefetcher, LOG, false, checkPoint.ThisTimeLineID))
     751         [ +  - ]:           1 :                 ereport(FATAL,
     752                 :             :                         errmsg("could not find redo location %X/%08X referenced by checkpoint record at %X/%08X",
     753                 :             :                                LSN_FORMAT_ARGS(checkPoint.redo), LSN_FORMAT_ARGS(CheckPointLoc)));
     754                 :             :         }
     755                 :             :     }
     756                 :             : 
     757         [ +  + ]:        1087 :     if (ArchiveRecoveryRequested)
     758                 :             :     {
     759         [ +  + ]:         127 :         if (StandbyModeRequested)
     760         [ +  - ]:         122 :             ereport(LOG,
     761                 :             :                     (errmsg("entering standby mode")));
     762         [ -  + ]:           5 :         else if (recoveryTarget == RECOVERY_TARGET_XID)
     763         [ #  # ]:           0 :             ereport(LOG,
     764                 :             :                     (errmsg("starting point-in-time recovery to XID %u",
     765                 :             :                             recoveryTargetXid)));
     766         [ -  + ]:           5 :         else if (recoveryTarget == RECOVERY_TARGET_TIME)
     767         [ #  # ]:           0 :             ereport(LOG,
     768                 :             :                     (errmsg("starting point-in-time recovery to %s",
     769                 :             :                             timestamptz_to_str(recoveryTargetTime))));
     770         [ +  + ]:           5 :         else if (recoveryTarget == RECOVERY_TARGET_NAME)
     771         [ +  - ]:           3 :             ereport(LOG,
     772                 :             :                     (errmsg("starting point-in-time recovery to \"%s\"",
     773                 :             :                             recoveryTargetName)));
     774         [ -  + ]:           2 :         else if (recoveryTarget == RECOVERY_TARGET_LSN)
     775         [ #  # ]:           0 :             ereport(LOG,
     776                 :             :                     errmsg("starting point-in-time recovery to WAL location (LSN) \"%X/%08X\"",
     777                 :             :                            LSN_FORMAT_ARGS(recoveryTargetLSN)));
     778         [ -  + ]:           2 :         else if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE)
     779         [ #  # ]:           0 :             ereport(LOG,
     780                 :             :                     (errmsg("starting point-in-time recovery to earliest consistent point")));
     781                 :             :         else
     782         [ +  - ]:           2 :             ereport(LOG,
     783                 :             :                     (errmsg("starting archive recovery")));
     784                 :             :     }
     785                 :             : 
     786                 :             :     /*
     787                 :             :      * If the location of the checkpoint record is not on the expected
     788                 :             :      * timeline in the history of the requested timeline, we cannot proceed:
     789                 :             :      * the backup is not part of the history of the requested timeline.
     790                 :             :      */
     791                 :             :     Assert(expectedTLEs);       /* was initialized by reading checkpoint
     792                 :             :                                  * record */
     793         [ -  + ]:        1087 :     if (tliOfPointInHistory(CheckPointLoc, expectedTLEs) !=
     794                 :             :         CheckPointTLI)
     795                 :             :     {
     796                 :             :         XLogRecPtr  switchpoint;
     797                 :             : 
     798                 :             :         /*
     799                 :             :          * tliSwitchPoint will throw an error if the checkpoint's timeline is
     800                 :             :          * not in expectedTLEs at all.
     801                 :             :          */
     802                 :           0 :         switchpoint = tliSwitchPoint(CheckPointTLI, expectedTLEs, NULL);
     803   [ #  #  #  # ]:           0 :         ereport(FATAL,
     804                 :             :                 (errmsg("requested timeline %u is not a child of this server's history",
     805                 :             :                         recoveryTargetTLI),
     806                 :             :         /* translator: %s is a backup_label file or a pg_control file */
     807                 :             :                  errdetail("Latest checkpoint in file \"%s\" is at %X/%08X on timeline %u, but in the history of the requested timeline, the server forked off from that timeline at %X/%08X.",
     808                 :             :                            haveBackupLabel ? "backup_label" : "pg_control",
     809                 :             :                            LSN_FORMAT_ARGS(CheckPointLoc),
     810                 :             :                            CheckPointTLI,
     811                 :             :                            LSN_FORMAT_ARGS(switchpoint))));
     812                 :             :     }
     813                 :             : 
     814                 :             :     /*
     815                 :             :      * The min recovery point should be part of the requested timeline's
     816                 :             :      * history, too.
     817                 :             :      */
     818         [ +  + ]:        1087 :     if (XLogRecPtrIsValid(ControlFile->minRecoveryPoint) &&
     819                 :          45 :         tliOfPointInHistory(ControlFile->minRecoveryPoint - 1, expectedTLEs) !=
     820         [ -  + ]:          45 :         ControlFile->minRecoveryPointTLI)
     821         [ #  # ]:           0 :         ereport(FATAL,
     822                 :             :                 errmsg("requested timeline %u does not contain minimum recovery point %X/%08X on timeline %u",
     823                 :             :                        recoveryTargetTLI,
     824                 :             :                        LSN_FORMAT_ARGS(ControlFile->minRecoveryPoint),
     825                 :             :                        ControlFile->minRecoveryPointTLI));
     826                 :             : 
     827   [ +  +  +  + ]:        1087 :     ereport(DEBUG1,
     828                 :             :             errmsg_internal("redo record is at %X/%08X; shutdown %s",
     829                 :             :                             LSN_FORMAT_ARGS(checkPoint.redo),
     830                 :             :                             wasShutdown ? "true" : "false"));
     831         [ +  + ]:        1087 :     ereport(DEBUG1,
     832                 :             :             (errmsg_internal("next transaction ID: " UINT64_FORMAT "; next OID: %u",
     833                 :             :                              U64FromFullTransactionId(checkPoint.nextXid),
     834                 :             :                              checkPoint.nextOid)));
     835         [ +  + ]:        1087 :     ereport(DEBUG1,
     836                 :             :             (errmsg_internal("next MultiXactId: %u; next MultiXactOffset: %" PRIu64,
     837                 :             :                              checkPoint.nextMulti, checkPoint.nextMultiOffset)));
     838         [ +  + ]:        1087 :     ereport(DEBUG1,
     839                 :             :             (errmsg_internal("oldest unfrozen transaction ID: %u, in database %u",
     840                 :             :                              checkPoint.oldestXid, checkPoint.oldestXidDB)));
     841         [ +  + ]:        1087 :     ereport(DEBUG1,
     842                 :             :             (errmsg_internal("oldest MultiXactId: %u, in database %u",
     843                 :             :                              checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
     844         [ +  + ]:        1087 :     ereport(DEBUG1,
     845                 :             :             (errmsg_internal("commit timestamp Xid oldest/newest: %u/%u",
     846                 :             :                              checkPoint.oldestCommitTsXid,
     847                 :             :                              checkPoint.newestCommitTsXid)));
     848         [ -  + ]:        1087 :     if (!TransactionIdIsNormal(XidFromFullTransactionId(checkPoint.nextXid)))
     849         [ #  # ]:           0 :         ereport(PANIC,
     850                 :             :                 (errmsg("invalid next transaction ID")));
     851                 :             : 
     852                 :             :     /* sanity check */
     853         [ -  + ]:        1087 :     if (checkPoint.redo > CheckPointLoc)
     854         [ #  # ]:           0 :         ereport(PANIC,
     855                 :             :                 (errmsg("invalid redo in checkpoint record")));
     856                 :             : 
     857                 :             :     /*
     858                 :             :      * Check whether we need to force recovery from WAL.  If it appears to
     859                 :             :      * have been a clean shutdown and we did not have a recovery signal file,
     860                 :             :      * then assume no recovery needed.
     861                 :             :      */
     862         [ +  + ]:        1087 :     if (checkPoint.redo < CheckPointLoc)
     863                 :             :     {
     864         [ -  + ]:         133 :         if (wasShutdown)
     865         [ #  # ]:           0 :             ereport(PANIC,
     866                 :             :                     (errmsg("invalid redo record in shutdown checkpoint")));
     867                 :         133 :         InRecovery = true;
     868                 :             :     }
     869         [ +  + ]:         954 :     else if (ControlFile->state != DB_SHUTDOWNED)
     870                 :          94 :         InRecovery = true;
     871         [ +  + ]:         860 :     else if (ArchiveRecoveryRequested)
     872                 :             :     {
     873                 :             :         /* force recovery due to presence of recovery signal file */
     874                 :           8 :         InRecovery = true;
     875                 :             :     }
     876                 :             : 
     877                 :             :     /*
     878                 :             :      * If recovery is needed, update our in-memory copy of pg_control to show
     879                 :             :      * that we are recovering and to show the selected checkpoint as the place
     880                 :             :      * we are starting from. We also mark pg_control with any minimum recovery
     881                 :             :      * stop point obtained from a backup history file.
     882                 :             :      *
     883                 :             :      * We don't write the changes to disk yet, though. Only do that after
     884                 :             :      * initializing various subsystems.
     885                 :             :      */
     886         [ +  + ]:        1087 :     if (InRecovery)
     887                 :             :     {
     888         [ +  + ]:         235 :         if (InArchiveRecovery)
     889                 :             :         {
     890                 :         133 :             ControlFile->state = DB_IN_ARCHIVE_RECOVERY;
     891                 :             :         }
     892                 :             :         else
     893                 :             :         {
     894         [ +  - ]:         102 :             ereport(LOG,
     895                 :             :                     (errmsg("database system was not properly shut down; "
     896                 :             :                             "automatic recovery in progress")));
     897         [ +  + ]:         102 :             if (recoveryTargetTLI > ControlFile->checkPointCopy.ThisTimeLineID)
     898         [ +  - ]:           2 :                 ereport(LOG,
     899                 :             :                         (errmsg("crash recovery starts in timeline %u "
     900                 :             :                                 "and has target timeline %u",
     901                 :             :                                 ControlFile->checkPointCopy.ThisTimeLineID,
     902                 :             :                                 recoveryTargetTLI)));
     903                 :         102 :             ControlFile->state = DB_IN_CRASH_RECOVERY;
     904                 :             :         }
     905                 :         235 :         ControlFile->checkPoint = CheckPointLoc;
     906                 :         235 :         ControlFile->checkPointCopy = checkPoint;
     907         [ +  + ]:         235 :         if (InArchiveRecovery)
     908                 :             :         {
     909                 :             :             /* initialize minRecoveryPoint if not set yet */
     910         [ +  + ]:         133 :             if (ControlFile->minRecoveryPoint < checkPoint.redo)
     911                 :             :             {
     912                 :          90 :                 ControlFile->minRecoveryPoint = checkPoint.redo;
     913                 :          90 :                 ControlFile->minRecoveryPointTLI = checkPoint.ThisTimeLineID;
     914                 :             :             }
     915                 :             :         }
     916                 :             : 
     917                 :             :         /*
     918                 :             :          * Set backupStartPoint if we're starting recovery from a base backup.
     919                 :             :          *
     920                 :             :          * Also set backupEndPoint and use minRecoveryPoint as the backup end
     921                 :             :          * location if we're starting recovery from a base backup which was
     922                 :             :          * taken from a standby. In this case, the database system status in
     923                 :             :          * pg_control must indicate that the database was already in recovery.
     924                 :             :          * Usually that will be DB_IN_ARCHIVE_RECOVERY but also can be
     925                 :             :          * DB_SHUTDOWNED_IN_RECOVERY if recovery previously was interrupted
     926                 :             :          * before reaching this point; e.g. because restore_command or
     927                 :             :          * primary_conninfo were faulty.
     928                 :             :          *
     929                 :             :          * Any other state indicates that the backup somehow became corrupted
     930                 :             :          * and we can't sensibly continue with recovery.
     931                 :             :          */
     932         [ +  + ]:         235 :         if (haveBackupLabel)
     933                 :             :         {
     934                 :          89 :             ControlFile->backupStartPoint = checkPoint.redo;
     935                 :          89 :             ControlFile->backupEndRequired = backupEndRequired;
     936                 :             : 
     937         [ +  + ]:          89 :             if (backupFromStandby)
     938                 :             :             {
     939   [ -  +  -  - ]:           7 :                 if (dbstate_at_startup != DB_IN_ARCHIVE_RECOVERY &&
     940                 :             :                     dbstate_at_startup != DB_SHUTDOWNED_IN_RECOVERY)
     941         [ #  # ]:           0 :                     ereport(FATAL,
     942                 :             :                             (errmsg("backup_label contains data inconsistent with control file"),
     943                 :             :                              errhint("This means that the backup is corrupted and you will "
     944                 :             :                                      "have to use another backup for recovery.")));
     945                 :           7 :                 ControlFile->backupEndPoint = ControlFile->minRecoveryPoint;
     946                 :             :             }
     947                 :             :         }
     948                 :             :     }
     949                 :             : 
     950                 :             :     /* remember these, so that we know when we have reached consistency */
     951                 :        1087 :     backupStartPoint = ControlFile->backupStartPoint;
     952                 :        1087 :     backupEndRequired = ControlFile->backupEndRequired;
     953                 :        1087 :     backupEndPoint = ControlFile->backupEndPoint;
     954         [ +  + ]:        1087 :     if (InArchiveRecovery)
     955                 :             :     {
     956                 :         133 :         minRecoveryPoint = ControlFile->minRecoveryPoint;
     957                 :         133 :         minRecoveryPointTLI = ControlFile->minRecoveryPointTLI;
     958                 :             :     }
     959                 :             :     else
     960                 :             :     {
     961                 :         954 :         minRecoveryPoint = InvalidXLogRecPtr;
     962                 :         954 :         minRecoveryPointTLI = 0;
     963                 :             :     }
     964                 :             : 
     965                 :             :     /*
     966                 :             :      * Start recovery assuming that the final record isn't lost.
     967                 :             :      */
     968                 :        1087 :     abortedRecPtr = InvalidXLogRecPtr;
     969                 :        1087 :     missingContrecPtr = InvalidXLogRecPtr;
     970                 :             : 
     971                 :        1087 :     *wasShutdown_ptr = wasShutdown;
     972                 :        1087 :     *haveBackupLabel_ptr = haveBackupLabel;
     973                 :        1087 :     *haveTblspcMap_ptr = haveTblspcMap;
     974                 :        1087 : }
     975                 :             : 
     976                 :             : /*
     977                 :             :  * See if there are any recovery signal files and if so, set state for
     978                 :             :  * recovery.
     979                 :             :  *
     980                 :             :  * See if there is a recovery command file (recovery.conf), and if so
     981                 :             :  * throw an ERROR since as of PG12 we no longer recognize that.
     982                 :             :  */
     983                 :             : static void
     984                 :        1089 : readRecoverySignalFile(void)
     985                 :             : {
     986                 :             :     struct stat stat_buf;
     987                 :             : 
     988         [ +  + ]:        1089 :     if (IsBootstrapProcessingMode())
     989                 :         962 :         return;
     990                 :             : 
     991                 :             :     /*
     992                 :             :      * Check for old recovery API file: recovery.conf
     993                 :             :      */
     994         [ -  + ]:        1032 :     if (stat(RECOVERY_COMMAND_FILE, &stat_buf) == 0)
     995         [ #  # ]:           0 :         ereport(FATAL,
     996                 :             :                 (errcode_for_file_access(),
     997                 :             :                  errmsg("using recovery command file \"%s\" is not supported",
     998                 :             :                         RECOVERY_COMMAND_FILE)));
     999                 :             : 
    1000                 :             :     /*
    1001                 :             :      * Remove unused .done file, if present. Ignore if absent.
    1002                 :             :      */
    1003                 :        1032 :     unlink(RECOVERY_COMMAND_DONE);
    1004                 :             : 
    1005                 :             :     /*
    1006                 :             :      * Check for recovery signal files and if found, fsync them since they
    1007                 :             :      * represent server state information.  We don't sweat too much about the
    1008                 :             :      * possibility of fsync failure, however.
    1009                 :             :      */
    1010         [ +  + ]:        1032 :     if (stat(STANDBY_SIGNAL_FILE, &stat_buf) == 0)
    1011                 :             :     {
    1012                 :             :         int         fd;
    1013                 :             : 
    1014                 :         122 :         fd = BasicOpenFilePerm(STANDBY_SIGNAL_FILE, O_RDWR | PG_BINARY,
    1015                 :             :                                S_IRUSR | S_IWUSR);
    1016         [ +  - ]:         122 :         if (fd >= 0)
    1017                 :             :         {
    1018                 :         122 :             (void) pg_fsync(fd);
    1019                 :         122 :             close(fd);
    1020                 :             :         }
    1021                 :         122 :         standby_signal_file_found = true;
    1022                 :             :     }
    1023                 :             : 
    1024         [ +  + ]:        1032 :     if (stat(RECOVERY_SIGNAL_FILE, &stat_buf) == 0)
    1025                 :             :     {
    1026                 :             :         int         fd;
    1027                 :             : 
    1028                 :           6 :         fd = BasicOpenFilePerm(RECOVERY_SIGNAL_FILE, O_RDWR | PG_BINARY,
    1029                 :             :                                S_IRUSR | S_IWUSR);
    1030         [ +  - ]:           6 :         if (fd >= 0)
    1031                 :             :         {
    1032                 :           6 :             (void) pg_fsync(fd);
    1033                 :           6 :             close(fd);
    1034                 :             :         }
    1035                 :           6 :         recovery_signal_file_found = true;
    1036                 :             :     }
    1037                 :             : 
    1038                 :             :     /*
    1039                 :             :      * If both signal files are present, standby signal file takes precedence.
    1040                 :             :      * If neither is present then we won't enter archive recovery.
    1041                 :             :      */
    1042                 :        1032 :     StandbyModeRequested = false;
    1043                 :        1032 :     ArchiveRecoveryRequested = false;
    1044         [ +  + ]:        1032 :     if (standby_signal_file_found)
    1045                 :             :     {
    1046                 :         122 :         StandbyModeRequested = true;
    1047                 :         122 :         ArchiveRecoveryRequested = true;
    1048                 :             :     }
    1049         [ +  + ]:         910 :     else if (recovery_signal_file_found)
    1050                 :             :     {
    1051                 :           5 :         StandbyModeRequested = false;
    1052                 :           5 :         ArchiveRecoveryRequested = true;
    1053                 :             :     }
    1054                 :             :     else
    1055                 :         905 :         return;
    1056                 :             : 
    1057                 :             :     /*
    1058                 :             :      * We don't support standby mode in standalone backends; that requires
    1059                 :             :      * other processes such as the WAL receiver to be alive.
    1060                 :             :      */
    1061   [ +  +  -  + ]:         127 :     if (StandbyModeRequested && !IsUnderPostmaster)
    1062         [ #  # ]:           0 :         ereport(FATAL,
    1063                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1064                 :             :                  errmsg("standby mode is not supported by single-user servers")));
    1065                 :             : }
    1066                 :             : 
    1067                 :             : static void
    1068                 :        1089 : validateRecoveryParameters(void)
    1069                 :             : {
    1070         [ +  + ]:        1089 :     if (!ArchiveRecoveryRequested)
    1071                 :         962 :         return;
    1072                 :             : 
    1073                 :             :     /*
    1074                 :             :      * Check for compulsory parameters
    1075                 :             :      */
    1076         [ +  + ]:         127 :     if (StandbyModeRequested)
    1077                 :             :     {
    1078   [ +  -  +  + ]:         122 :         if ((PrimaryConnInfo == NULL || strcmp(PrimaryConnInfo, "") == 0) &&
    1079   [ +  -  +  + ]:          12 :             (recoveryRestoreCommand == NULL || strcmp(recoveryRestoreCommand, "") == 0))
    1080         [ +  - ]:           2 :             ereport(WARNING,
    1081                 :             :                     (errmsg("specified neither \"primary_conninfo\" nor \"restore_command\""),
    1082                 :             :                      errhint("The database server will regularly poll the pg_wal subdirectory to check for files placed there.")));
    1083                 :             :     }
    1084                 :             :     else
    1085                 :             :     {
    1086         [ +  - ]:           5 :         if (recoveryRestoreCommand == NULL ||
    1087         [ -  + ]:           5 :             strcmp(recoveryRestoreCommand, "") == 0)
    1088         [ #  # ]:           0 :             ereport(FATAL,
    1089                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1090                 :             :                      errmsg("must specify \"restore_command\" when standby mode is not enabled")));
    1091                 :             :     }
    1092                 :             : 
    1093                 :             :     /*
    1094                 :             :      * Override any inconsistent requests. Note that this is a change of
    1095                 :             :      * behaviour in 9.5; prior to this we simply ignored a request to pause if
    1096                 :             :      * hot_standby = off, which was surprising behaviour.
    1097                 :             :      */
    1098         [ +  + ]:         127 :     if (recoveryTargetAction == RECOVERY_TARGET_ACTION_PAUSE &&
    1099         [ +  + ]:         120 :         !EnableHotStandby)
    1100                 :           3 :         recoveryTargetAction = RECOVERY_TARGET_ACTION_SHUTDOWN;
    1101                 :             : 
    1102                 :             :     /*
    1103                 :             :      * Final parsing of recovery_target_time string; see also
    1104                 :             :      * check_recovery_target_time().
    1105                 :             :      */
    1106         [ -  + ]:         127 :     if (recoveryTarget == RECOVERY_TARGET_TIME)
    1107                 :             :     {
    1108                 :           0 :         recoveryTargetTime = DatumGetTimestampTz(DirectFunctionCall3(timestamptz_in,
    1109                 :             :                                                                      CStringGetDatum(recovery_target_time_string),
    1110                 :             :                                                                      ObjectIdGetDatum(InvalidOid),
    1111                 :             :                                                                      Int32GetDatum(-1)));
    1112                 :             :     }
    1113                 :             : 
    1114                 :             :     /*
    1115                 :             :      * If user specified recovery_target_timeline, validate it or compute the
    1116                 :             :      * "latest" value.  We can't do this until after we've gotten the restore
    1117                 :             :      * command and set InArchiveRecovery, because we need to fetch timeline
    1118                 :             :      * history files from the archive.
    1119                 :             :      */
    1120         [ -  + ]:         127 :     if (recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_NUMERIC)
    1121                 :             :     {
    1122                 :           0 :         TimeLineID  rtli = recoveryTargetTLIRequested;
    1123                 :             : 
    1124                 :             :         /* Timeline 1 does not have a history file, all else should */
    1125   [ #  #  #  # ]:           0 :         if (rtli != 1 && !existsTimeLineHistory(rtli))
    1126         [ #  # ]:           0 :             ereport(FATAL,
    1127                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1128                 :             :                      errmsg("recovery target timeline %u does not exist",
    1129                 :             :                             rtli)));
    1130                 :           0 :         recoveryTargetTLI = rtli;
    1131                 :             :     }
    1132         [ +  - ]:         127 :     else if (recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_LATEST)
    1133                 :             :     {
    1134                 :             :         /* We start the "latest" search from pg_control's timeline */
    1135                 :         127 :         recoveryTargetTLI = findNewestTimeLine(recoveryTargetTLI);
    1136                 :             :     }
    1137                 :             :     else
    1138                 :             :     {
    1139                 :             :         /*
    1140                 :             :          * else we just use the recoveryTargetTLI as already read from
    1141                 :             :          * ControlFile
    1142                 :             :          */
    1143                 :             :         Assert(recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_CONTROLFILE);
    1144                 :             :     }
    1145                 :             : }
    1146                 :             : 
    1147                 :             : /*
    1148                 :             :  * read_backup_label: check to see if a backup_label file is present
    1149                 :             :  *
    1150                 :             :  * If we see a backup_label during recovery, we assume that we are recovering
    1151                 :             :  * from a backup dump file, and we therefore roll forward from the checkpoint
    1152                 :             :  * identified by the label file, NOT what pg_control says.  This avoids the
    1153                 :             :  * problem that pg_control might have been archived one or more checkpoints
    1154                 :             :  * later than the start of the dump, and so if we rely on it as the start
    1155                 :             :  * point, we will fail to restore a consistent database state.
    1156                 :             :  *
    1157                 :             :  * Returns true if a backup_label was found (and fills the checkpoint
    1158                 :             :  * location and TLI into *checkPointLoc and *backupLabelTLI, respectively);
    1159                 :             :  * returns false if not. If this backup_label came from a streamed backup,
    1160                 :             :  * *backupEndRequired is set to true. If this backup_label was created during
    1161                 :             :  * recovery, *backupFromStandby is set to true.
    1162                 :             :  *
    1163                 :             :  * Also sets the global variables RedoStartLSN and RedoStartTLI with the LSN
    1164                 :             :  * and TLI read from the backup file.
    1165                 :             :  */
    1166                 :             : static bool
    1167                 :        1089 : read_backup_label(XLogRecPtr *checkPointLoc, TimeLineID *backupLabelTLI,
    1168                 :             :                   bool *backupEndRequired, bool *backupFromStandby)
    1169                 :             : {
    1170                 :             :     char        startxlogfilename[MAXFNAMELEN];
    1171                 :             :     TimeLineID  tli_from_walseg,
    1172                 :             :                 tli_from_file;
    1173                 :             :     FILE       *lfp;
    1174                 :             :     char        ch;
    1175                 :             :     char        backuptype[20];
    1176                 :             :     char        backupfrom[20];
    1177                 :             :     char        backuplabel[MAXPGPATH];
    1178                 :             :     char        backuptime[128];
    1179                 :             :     uint32      hi,
    1180                 :             :                 lo;
    1181                 :             : 
    1182                 :             :     /* suppress possible uninitialized-variable warnings */
    1183                 :        1089 :     *checkPointLoc = InvalidXLogRecPtr;
    1184                 :        1089 :     *backupLabelTLI = 0;
    1185                 :        1089 :     *backupEndRequired = false;
    1186                 :        1089 :     *backupFromStandby = false;
    1187                 :             : 
    1188                 :             :     /*
    1189                 :             :      * See if label file is present
    1190                 :             :      */
    1191                 :        1089 :     lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
    1192         [ +  + ]:        1089 :     if (!lfp)
    1193                 :             :     {
    1194         [ -  + ]:        1000 :         if (errno != ENOENT)
    1195         [ #  # ]:           0 :             ereport(FATAL,
    1196                 :             :                     (errcode_for_file_access(),
    1197                 :             :                      errmsg("could not read file \"%s\": %m",
    1198                 :             :                             BACKUP_LABEL_FILE)));
    1199                 :        1000 :         return false;           /* it's not there, all is fine */
    1200                 :             :     }
    1201                 :             : 
    1202                 :             :     /*
    1203                 :             :      * Read and parse the START WAL LOCATION and CHECKPOINT lines (this code
    1204                 :             :      * is pretty crude, but we are not expecting any variability in the file
    1205                 :             :      * format).
    1206                 :             :      */
    1207         [ +  - ]:          89 :     if (fscanf(lfp, "START WAL LOCATION: %X/%08X (file %08X%16s)%c",
    1208         [ -  + ]:          89 :                &hi, &lo, &tli_from_walseg, startxlogfilename, &ch) != 5 || ch != '\n')
    1209         [ #  # ]:           0 :         ereport(FATAL,
    1210                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1211                 :             :                  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
    1212                 :          89 :     RedoStartLSN = ((uint64) hi) << 32 | lo;
    1213                 :          89 :     RedoStartTLI = tli_from_walseg;
    1214         [ +  - ]:          89 :     if (fscanf(lfp, "CHECKPOINT LOCATION: %X/%08X%c",
    1215         [ -  + ]:          89 :                &hi, &lo, &ch) != 3 || ch != '\n')
    1216         [ #  # ]:           0 :         ereport(FATAL,
    1217                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1218                 :             :                  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
    1219                 :          89 :     *checkPointLoc = ((uint64) hi) << 32 | lo;
    1220                 :          89 :     *backupLabelTLI = tli_from_walseg;
    1221                 :             : 
    1222                 :             :     /*
    1223                 :             :      * BACKUP METHOD lets us know if this was a typical backup ("streamed",
    1224                 :             :      * which could mean either pg_basebackup or the pg_backup_start/stop
    1225                 :             :      * method was used) or if this label came from somewhere else (the only
    1226                 :             :      * other option today being from pg_rewind).  If this was a streamed
    1227                 :             :      * backup then we know that we need to play through until we get to the
    1228                 :             :      * end of the WAL which was generated during the backup (at which point we
    1229                 :             :      * will have reached consistency and backupEndRequired will be reset to be
    1230                 :             :      * false).
    1231                 :             :      */
    1232         [ +  - ]:          89 :     if (fscanf(lfp, "BACKUP METHOD: %19s\n", backuptype) == 1)
    1233                 :             :     {
    1234         [ +  + ]:          89 :         if (strcmp(backuptype, "streamed") == 0)
    1235                 :          88 :             *backupEndRequired = true;
    1236                 :             :     }
    1237                 :             : 
    1238                 :             :     /*
    1239                 :             :      * BACKUP FROM lets us know if this was from a primary or a standby.  If
    1240                 :             :      * it was from a standby, we'll double-check that the control file state
    1241                 :             :      * matches that of a standby.
    1242                 :             :      */
    1243         [ +  - ]:          89 :     if (fscanf(lfp, "BACKUP FROM: %19s\n", backupfrom) == 1)
    1244                 :             :     {
    1245         [ +  + ]:          89 :         if (strcmp(backupfrom, "standby") == 0)
    1246                 :           7 :             *backupFromStandby = true;
    1247                 :             :     }
    1248                 :             : 
    1249                 :             :     /*
    1250                 :             :      * Parse START TIME and LABEL. Those are not mandatory fields for recovery
    1251                 :             :      * but checking for their presence is useful for debugging and the next
    1252                 :             :      * sanity checks. Cope also with the fact that the result buffers have a
    1253                 :             :      * pre-allocated size, hence if the backup_label file has been generated
    1254                 :             :      * with strings longer than the maximum assumed here an incorrect parsing
    1255                 :             :      * happens. That's fine as only minor consistency checks are done
    1256                 :             :      * afterwards.
    1257                 :             :      */
    1258         [ +  - ]:          89 :     if (fscanf(lfp, "START TIME: %127[^\n]\n", backuptime) == 1)
    1259         [ +  + ]:          89 :         ereport(DEBUG1,
    1260                 :             :                 (errmsg_internal("backup time %s in file \"%s\"",
    1261                 :             :                                  backuptime, BACKUP_LABEL_FILE)));
    1262                 :             : 
    1263         [ +  + ]:          89 :     if (fscanf(lfp, "LABEL: %1023[^\n]\n", backuplabel) == 1)
    1264         [ +  + ]:          88 :         ereport(DEBUG1,
    1265                 :             :                 (errmsg_internal("backup label %s in file \"%s\"",
    1266                 :             :                                  backuplabel, BACKUP_LABEL_FILE)));
    1267                 :             : 
    1268                 :             :     /*
    1269                 :             :      * START TIMELINE is new as of 11. Its parsing is not mandatory, still use
    1270                 :             :      * it as a sanity check if present.
    1271                 :             :      */
    1272         [ +  + ]:          89 :     if (fscanf(lfp, "START TIMELINE: %u\n", &tli_from_file) == 1)
    1273                 :             :     {
    1274         [ -  + ]:          88 :         if (tli_from_walseg != tli_from_file)
    1275         [ #  # ]:           0 :             ereport(FATAL,
    1276                 :             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1277                 :             :                      errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE),
    1278                 :             :                      errdetail("Timeline ID parsed is %u, but expected %u.",
    1279                 :             :                                tli_from_file, tli_from_walseg)));
    1280                 :             : 
    1281         [ +  + ]:          88 :         ereport(DEBUG1,
    1282                 :             :                 (errmsg_internal("backup timeline %u in file \"%s\"",
    1283                 :             :                                  tli_from_file, BACKUP_LABEL_FILE)));
    1284                 :             :     }
    1285                 :             : 
    1286         [ -  + ]:          89 :     if (fscanf(lfp, "INCREMENTAL FROM LSN: %X/%08X\n", &hi, &lo) > 0)
    1287         [ #  # ]:           0 :         ereport(FATAL,
    1288                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1289                 :             :                  errmsg("this is an incremental backup, not a data directory"),
    1290                 :             :                  errhint("Use pg_combinebackup to reconstruct a valid data directory.")));
    1291                 :             : 
    1292   [ +  -  -  + ]:          89 :     if (ferror(lfp) || FreeFile(lfp))
    1293         [ #  # ]:           0 :         ereport(FATAL,
    1294                 :             :                 (errcode_for_file_access(),
    1295                 :             :                  errmsg("could not read file \"%s\": %m",
    1296                 :             :                         BACKUP_LABEL_FILE)));
    1297                 :             : 
    1298                 :          89 :     return true;
    1299                 :             : }
    1300                 :             : 
    1301                 :             : /*
    1302                 :             :  * read_tablespace_map: check to see if a tablespace_map file is present
    1303                 :             :  *
    1304                 :             :  * If we see a tablespace_map file during recovery, we assume that we are
    1305                 :             :  * recovering from a backup dump file, and we therefore need to create symlinks
    1306                 :             :  * as per the information present in tablespace_map file.
    1307                 :             :  *
    1308                 :             :  * Returns true if a tablespace_map file was found (and fills *tablespaces
    1309                 :             :  * with a tablespaceinfo struct for each tablespace listed in the file);
    1310                 :             :  * returns false if not.
    1311                 :             :  */
    1312                 :             : static bool
    1313                 :          89 : read_tablespace_map(List **tablespaces)
    1314                 :             : {
    1315                 :             :     tablespaceinfo *ti;
    1316                 :             :     FILE       *lfp;
    1317                 :             :     char        str[MAXPGPATH];
    1318                 :             :     int         ch,
    1319                 :             :                 i,
    1320                 :             :                 n;
    1321                 :             :     bool        was_backslash;
    1322                 :             : 
    1323                 :             :     /*
    1324                 :             :      * See if tablespace_map file is present
    1325                 :             :      */
    1326                 :          89 :     lfp = AllocateFile(TABLESPACE_MAP, "r");
    1327         [ +  + ]:          89 :     if (!lfp)
    1328                 :             :     {
    1329         [ -  + ]:          87 :         if (errno != ENOENT)
    1330         [ #  # ]:           0 :             ereport(FATAL,
    1331                 :             :                     (errcode_for_file_access(),
    1332                 :             :                      errmsg("could not read file \"%s\": %m",
    1333                 :             :                             TABLESPACE_MAP)));
    1334                 :          87 :         return false;           /* it's not there, all is fine */
    1335                 :             :     }
    1336                 :             : 
    1337                 :             :     /*
    1338                 :             :      * Read and parse the link name and path lines from tablespace_map file
    1339                 :             :      * (this code is pretty crude, but we are not expecting any variability in
    1340                 :             :      * the file format).  De-escape any backslashes that were inserted.
    1341                 :             :      */
    1342                 :           2 :     i = 0;
    1343                 :           2 :     was_backslash = false;
    1344         [ +  + ]:          77 :     while ((ch = fgetc(lfp)) != EOF)
    1345                 :             :     {
    1346   [ +  -  +  +  :          75 :         if (!was_backslash && (ch == '\n' || ch == '\r'))
                   -  + ]
    1347                 :           2 :         {
    1348                 :             :             char       *endp;
    1349                 :             : 
    1350         [ -  + ]:           2 :             if (i == 0)
    1351                 :           0 :                 continue;       /* \r immediately followed by \n */
    1352                 :             : 
    1353                 :             :             /*
    1354                 :             :              * The de-escaped line should contain an OID followed by exactly
    1355                 :             :              * one space followed by a path.  The path might start with
    1356                 :             :              * spaces, so don't be too liberal about parsing.
    1357                 :             :              */
    1358                 :           2 :             str[i] = '\0';
    1359                 :           2 :             n = 0;
    1360   [ +  -  +  + ]:          12 :             while (str[n] && str[n] != ' ')
    1361                 :          10 :                 n++;
    1362   [ +  -  -  + ]:           2 :             if (n < 1 || n >= i - 1)
    1363         [ #  # ]:           0 :                 ereport(FATAL,
    1364                 :             :                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1365                 :             :                          errmsg("invalid data in file \"%s\"", TABLESPACE_MAP)));
    1366                 :           2 :             str[n++] = '\0';
    1367                 :             : 
    1368                 :           2 :             ti = palloc0_object(tablespaceinfo);
    1369                 :           2 :             errno = 0;
    1370                 :           2 :             ti->oid = strtoul(str, &endp, 10);
    1371   [ +  -  +  -  :           2 :             if (*endp != '\0' || errno == EINVAL || errno == ERANGE)
                   -  + ]
    1372         [ #  # ]:           0 :                 ereport(FATAL,
    1373                 :             :                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1374                 :             :                          errmsg("invalid data in file \"%s\"", TABLESPACE_MAP)));
    1375                 :           2 :             ti->path = pstrdup(str + n);
    1376                 :           2 :             *tablespaces = lappend(*tablespaces, ti);
    1377                 :             : 
    1378                 :           2 :             i = 0;
    1379                 :           2 :             continue;
    1380                 :             :         }
    1381   [ +  -  -  + ]:          73 :         else if (!was_backslash && ch == '\\')
    1382                 :           0 :             was_backslash = true;
    1383                 :             :         else
    1384                 :             :         {
    1385         [ +  - ]:          73 :             if (i < sizeof(str) - 1)
    1386                 :          73 :                 str[i++] = ch;
    1387                 :          73 :             was_backslash = false;
    1388                 :             :         }
    1389                 :             :     }
    1390                 :             : 
    1391   [ +  -  -  + ]:           2 :     if (i != 0 || was_backslash)    /* last line not terminated? */
    1392         [ #  # ]:           0 :         ereport(FATAL,
    1393                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1394                 :             :                  errmsg("invalid data in file \"%s\"", TABLESPACE_MAP)));
    1395                 :             : 
    1396   [ +  -  -  + ]:           2 :     if (ferror(lfp) || FreeFile(lfp))
    1397         [ #  # ]:           0 :         ereport(FATAL,
    1398                 :             :                 (errcode_for_file_access(),
    1399                 :             :                  errmsg("could not read file \"%s\": %m",
    1400                 :             :                         TABLESPACE_MAP)));
    1401                 :             : 
    1402                 :           2 :     return true;
    1403                 :             : }
    1404                 :             : 
    1405                 :             : /*
    1406                 :             :  * Finish WAL recovery.
    1407                 :             :  *
    1408                 :             :  * This does not close the 'xlogreader' yet, because in some cases the caller
    1409                 :             :  * still wants to re-read the last checkpoint record by calling
    1410                 :             :  * ReadCheckpointRecord().
    1411                 :             :  *
    1412                 :             :  * Returns the position of the last valid or applied record, after which new
    1413                 :             :  * WAL should be appended, information about why recovery was ended, and some
    1414                 :             :  * other things. See the EndOfWalRecoveryInfo struct for details.
    1415                 :             :  */
    1416                 :             : EndOfWalRecoveryInfo *
    1417                 :        1019 : FinishWalRecovery(void)
    1418                 :             : {
    1419                 :        1019 :     EndOfWalRecoveryInfo *result = palloc_object(EndOfWalRecoveryInfo);
    1420                 :             :     XLogRecPtr  lastRec;
    1421                 :             :     TimeLineID  lastRecTLI;
    1422                 :             :     XLogRecPtr  endOfLog;
    1423                 :             : 
    1424                 :             :     /*
    1425                 :             :      * Kill WAL receiver, if it's still running, before we continue to write
    1426                 :             :      * the startup checkpoint and aborted-contrecord records. It will trump
    1427                 :             :      * over these records and subsequent ones if it's still alive when we
    1428                 :             :      * start writing WAL.
    1429                 :             :      */
    1430                 :        1019 :     XLogShutdownWalRcv();
    1431                 :             : 
    1432                 :             :     /*
    1433                 :             :      * Shutdown the slot sync worker to drop any temporary slots acquired by
    1434                 :             :      * it and to prevent it from keep trying to fetch the failover slots.
    1435                 :             :      *
    1436                 :             :      * We do not update the 'synced' column in 'pg_replication_slots' system
    1437                 :             :      * view from true to false here, as any failed update could leave 'synced'
    1438                 :             :      * column false for some slots. This could cause issues during slot sync
    1439                 :             :      * after restarting the server as a standby. While updating the 'synced'
    1440                 :             :      * column after switching to the new timeline is an option, it does not
    1441                 :             :      * simplify the handling for the 'synced' column. Therefore, we retain the
    1442                 :             :      * 'synced' column as true after promotion as it may provide useful
    1443                 :             :      * information about the slot origin.
    1444                 :             :      */
    1445                 :        1019 :     ShutDownSlotSync();
    1446                 :             : 
    1447                 :             :     /*
    1448                 :             :      * We are now done reading the xlog from stream. Turn off streaming
    1449                 :             :      * recovery to force fetching the files (which would be required at end of
    1450                 :             :      * recovery, e.g., timeline history file) from archive or pg_wal.
    1451                 :             :      *
    1452                 :             :      * Note that standby mode must be turned off after killing WAL receiver,
    1453                 :             :      * i.e., calling XLogShutdownWalRcv().
    1454                 :             :      */
    1455                 :             :     Assert(!WalRcvStreaming());
    1456                 :        1019 :     StandbyMode = false;
    1457                 :             : 
    1458                 :             :     /*
    1459                 :             :      * Determine where to start writing WAL next.
    1460                 :             :      *
    1461                 :             :      * Re-fetch the last valid or last applied record, so we can identify the
    1462                 :             :      * exact endpoint of what we consider the valid portion of WAL.  There may
    1463                 :             :      * be an incomplete continuation record after that, in which case
    1464                 :             :      * 'abortedRecPtr' and 'missingContrecPtr' are set and the caller will
    1465                 :             :      * write a special OVERWRITE_CONTRECORD message to mark that the rest of
    1466                 :             :      * it is intentionally missing.  See CreateOverwriteContrecordRecord().
    1467                 :             :      *
    1468                 :             :      * An important side-effect of this is to load the last page into
    1469                 :             :      * xlogreader. The caller uses it to initialize the WAL for writing.
    1470                 :             :      */
    1471         [ +  + ]:        1019 :     if (!InRecovery)
    1472                 :             :     {
    1473                 :         851 :         lastRec = CheckPointLoc;
    1474                 :         851 :         lastRecTLI = CheckPointTLI;
    1475                 :             :     }
    1476                 :             :     else
    1477                 :             :     {
    1478                 :         168 :         lastRec = XLogRecoveryCtl->lastReplayedReadRecPtr;
    1479                 :         168 :         lastRecTLI = XLogRecoveryCtl->lastReplayedTLI;
    1480                 :             :     }
    1481                 :        1019 :     XLogPrefetcherBeginRead(xlogprefetcher, lastRec);
    1482                 :        1019 :     (void) ReadRecord(xlogprefetcher, PANIC, false, lastRecTLI);
    1483                 :        1019 :     endOfLog = xlogreader->EndRecPtr;
    1484                 :             : 
    1485                 :             :     /*
    1486                 :             :      * Remember the TLI in the filename of the XLOG segment containing the
    1487                 :             :      * end-of-log.  It could be different from the timeline that endOfLog
    1488                 :             :      * nominally belongs to, if there was a timeline switch in that segment,
    1489                 :             :      * and we were reading the old WAL from a segment belonging to a higher
    1490                 :             :      * timeline.
    1491                 :             :      */
    1492                 :        1019 :     result->endOfLogTLI = xlogreader->seg.ws_tli;
    1493                 :             : 
    1494         [ +  + ]:        1019 :     if (ArchiveRecoveryRequested)
    1495                 :             :     {
    1496                 :             :         /*
    1497                 :             :          * We are no longer in archive recovery state.
    1498                 :             :          *
    1499                 :             :          * We are now done reading the old WAL.  Turn off archive fetching if
    1500                 :             :          * it was active.
    1501                 :             :          */
    1502                 :             :         Assert(InArchiveRecovery);
    1503                 :          60 :         InArchiveRecovery = false;
    1504                 :             : 
    1505                 :             :         /*
    1506                 :             :          * If the ending log segment is still open, close it (to avoid
    1507                 :             :          * problems on Windows with trying to rename or delete an open file).
    1508                 :             :          */
    1509         [ +  - ]:          60 :         if (readFile >= 0)
    1510                 :             :         {
    1511                 :          60 :             close(readFile);
    1512                 :          60 :             readFile = -1;
    1513                 :             :         }
    1514                 :             :     }
    1515                 :             : 
    1516                 :             :     /*
    1517                 :             :      * Copy the last partial block to the caller, for initializing the WAL
    1518                 :             :      * buffer for appending new WAL.
    1519                 :             :      */
    1520         [ +  + ]:        1019 :     if (endOfLog % XLOG_BLCKSZ != 0)
    1521                 :             :     {
    1522                 :             :         char       *page;
    1523                 :             :         int         len;
    1524                 :             :         XLogRecPtr  pageBeginPtr;
    1525                 :             : 
    1526                 :         997 :         pageBeginPtr = endOfLog - (endOfLog % XLOG_BLCKSZ);
    1527                 :             :         Assert(readOff == XLogSegmentOffset(pageBeginPtr, wal_segment_size));
    1528                 :             : 
    1529                 :             :         /* Copy the valid part of the last block */
    1530                 :         997 :         len = endOfLog % XLOG_BLCKSZ;
    1531                 :         997 :         page = palloc(len);
    1532                 :         997 :         memcpy(page, xlogreader->readBuf, len);
    1533                 :             : 
    1534                 :         997 :         result->lastPageBeginPtr = pageBeginPtr;
    1535                 :         997 :         result->lastPage = page;
    1536                 :             :     }
    1537                 :             :     else
    1538                 :             :     {
    1539                 :             :         /* There is no partial block to copy. */
    1540                 :          22 :         result->lastPageBeginPtr = endOfLog;
    1541                 :          22 :         result->lastPage = NULL;
    1542                 :             :     }
    1543                 :             : 
    1544                 :             :     /*
    1545                 :             :      * Create a comment for the history file to explain why and where timeline
    1546                 :             :      * changed.
    1547                 :             :      */
    1548                 :        1019 :     result->recoveryStopReason = getRecoveryStopReason();
    1549                 :             : 
    1550                 :        1019 :     result->lastRec = lastRec;
    1551                 :        1019 :     result->lastRecTLI = lastRecTLI;
    1552                 :        1019 :     result->endOfLog = endOfLog;
    1553                 :             : 
    1554                 :        1019 :     result->abortedRecPtr = abortedRecPtr;
    1555                 :        1019 :     result->missingContrecPtr = missingContrecPtr;
    1556                 :             : 
    1557                 :        1019 :     result->standby_signal_file_found = standby_signal_file_found;
    1558                 :        1019 :     result->recovery_signal_file_found = recovery_signal_file_found;
    1559                 :             : 
    1560                 :        1019 :     return result;
    1561                 :             : }
    1562                 :             : 
    1563                 :             : /*
    1564                 :             :  * Clean up the WAL reader and leftovers from restoring WAL from archive
    1565                 :             :  */
    1566                 :             : void
    1567                 :        1019 : ShutdownWalRecovery(void)
    1568                 :             : {
    1569                 :             :     char        recoveryPath[MAXPGPATH];
    1570                 :             : 
    1571                 :             :     /* Final update of pg_stat_recovery_prefetch. */
    1572                 :        1019 :     XLogPrefetcherComputeStats(xlogprefetcher);
    1573                 :             : 
    1574                 :             :     /* Shut down xlogreader */
    1575         [ +  + ]:        1019 :     if (readFile >= 0)
    1576                 :             :     {
    1577                 :         959 :         close(readFile);
    1578                 :         959 :         readFile = -1;
    1579                 :             :     }
    1580                 :        1019 :     pfree(xlogreader->private_data);
    1581                 :        1019 :     XLogReaderFree(xlogreader);
    1582                 :        1019 :     XLogPrefetcherFree(xlogprefetcher);
    1583                 :             : 
    1584         [ +  + ]:        1019 :     if (ArchiveRecoveryRequested)
    1585                 :             :     {
    1586                 :             :         /*
    1587                 :             :          * Since there might be a partial WAL segment named RECOVERYXLOG, get
    1588                 :             :          * rid of it.
    1589                 :             :          */
    1590                 :          60 :         snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
    1591                 :          60 :         unlink(recoveryPath);   /* ignore any error */
    1592                 :             : 
    1593                 :             :         /* Get rid of any remaining recovered timeline-history file, too */
    1594                 :          60 :         snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
    1595                 :          60 :         unlink(recoveryPath);   /* ignore any error */
    1596                 :             :     }
    1597                 :             : 
    1598                 :             :     /*
    1599                 :             :      * We don't need the latch anymore. It's not strictly necessary to disown
    1600                 :             :      * it, but let's do it for the sake of tidiness.
    1601                 :             :      */
    1602         [ +  + ]:        1019 :     if (ArchiveRecoveryRequested)
    1603                 :          60 :         DisownLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
    1604                 :        1019 : }
    1605                 :             : 
    1606                 :             : /*
    1607                 :             :  * Perform WAL recovery.
    1608                 :             :  *
    1609                 :             :  * If the system was shut down cleanly, this is never called.
    1610                 :             :  */
    1611                 :             : void
    1612                 :         234 : PerformWalRecovery(void)
    1613                 :             : {
    1614                 :             :     XLogRecord *record;
    1615                 :         234 :     bool        reachedRecoveryTarget = false;
    1616                 :             :     TimeLineID  replayTLI;
    1617                 :             : 
    1618                 :             :     /*
    1619                 :             :      * Initialize shared variables for tracking progress of WAL replay, as if
    1620                 :             :      * we had just replayed the record before the REDO location (or the
    1621                 :             :      * checkpoint record itself, if it's a shutdown checkpoint).
    1622                 :             :      */
    1623                 :         234 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    1624         [ +  + ]:         234 :     if (RedoStartLSN < CheckPointLoc)
    1625                 :             :     {
    1626                 :         132 :         XLogRecoveryCtl->lastReplayedReadRecPtr = InvalidXLogRecPtr;
    1627                 :         132 :         XLogRecoveryCtl->lastReplayedEndRecPtr = RedoStartLSN;
    1628                 :         132 :         XLogRecoveryCtl->lastReplayedTLI = RedoStartTLI;
    1629                 :             :     }
    1630                 :             :     else
    1631                 :             :     {
    1632                 :         102 :         XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
    1633                 :         102 :         XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
    1634                 :         102 :         XLogRecoveryCtl->lastReplayedTLI = CheckPointTLI;
    1635                 :             :     }
    1636                 :         234 :     XLogRecoveryCtl->replayEndRecPtr = XLogRecoveryCtl->lastReplayedEndRecPtr;
    1637                 :         234 :     XLogRecoveryCtl->replayEndTLI = XLogRecoveryCtl->lastReplayedTLI;
    1638                 :         234 :     XLogRecoveryCtl->recoveryLastXTime = 0;
    1639                 :         234 :     XLogRecoveryCtl->currentChunkStartTime = 0;
    1640                 :         234 :     XLogRecoveryCtl->recoveryPauseState = RECOVERY_NOT_PAUSED;
    1641                 :         234 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    1642                 :             : 
    1643                 :             :     /* Also ensure XLogReceiptTime has a sane value */
    1644                 :         234 :     XLogReceiptTime = GetCurrentTimestamp();
    1645                 :             : 
    1646                 :             :     /*
    1647                 :             :      * Let postmaster know we've started redo now, so that it can launch the
    1648                 :             :      * archiver if necessary.
    1649                 :             :      */
    1650         [ +  + ]:         234 :     if (IsUnderPostmaster)
    1651                 :         225 :         SendPostmasterSignal(PMSIGNAL_RECOVERY_STARTED);
    1652                 :             : 
    1653                 :             :     /*
    1654                 :             :      * Allow read-only connections immediately if we're consistent already.
    1655                 :             :      */
    1656                 :         234 :     CheckRecoveryConsistency();
    1657                 :             : 
    1658                 :             :     /*
    1659                 :             :      * Find the first record that logically follows the checkpoint --- it
    1660                 :             :      * might physically precede it, though.
    1661                 :             :      */
    1662         [ +  + ]:         234 :     if (RedoStartLSN < CheckPointLoc)
    1663                 :             :     {
    1664                 :             :         /* back up to find the record */
    1665                 :         132 :         replayTLI = RedoStartTLI;
    1666                 :         132 :         XLogPrefetcherBeginRead(xlogprefetcher, RedoStartLSN);
    1667                 :         132 :         record = ReadRecord(xlogprefetcher, PANIC, false, replayTLI);
    1668                 :             : 
    1669                 :             :         /*
    1670                 :             :          * If a checkpoint record's redo pointer points back to an earlier
    1671                 :             :          * LSN, the record at that LSN should be an XLOG_CHECKPOINT_REDO
    1672                 :             :          * record.
    1673                 :             :          */
    1674         [ +  - ]:         132 :         if (record->xl_rmid != RM_XLOG_ID ||
    1675         [ -  + ]:         132 :             (record->xl_info & ~XLR_INFO_MASK) != XLOG_CHECKPOINT_REDO)
    1676         [ #  # ]:           0 :             ereport(FATAL,
    1677                 :             :                     errmsg("unexpected record type found at redo point %X/%08X",
    1678                 :             :                            LSN_FORMAT_ARGS(xlogreader->ReadRecPtr)));
    1679                 :             :     }
    1680                 :             :     else
    1681                 :             :     {
    1682                 :             :         /* just have to read next record after CheckPoint */
    1683                 :             :         Assert(xlogreader->ReadRecPtr == CheckPointLoc);
    1684                 :         102 :         replayTLI = CheckPointTLI;
    1685                 :         102 :         record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
    1686                 :             :     }
    1687                 :             : 
    1688         [ +  + ]:         234 :     if (record != NULL)
    1689                 :             :     {
    1690                 :             :         TimestampTz xtime;
    1691                 :             :         PGRUsage    ru0;
    1692                 :             : 
    1693                 :         225 :         pg_rusage_init(&ru0);
    1694                 :             : 
    1695                 :         225 :         InRedo = true;
    1696                 :             : 
    1697                 :         225 :         RmgrStartup();
    1698                 :             : 
    1699         [ +  - ]:         225 :         ereport(LOG,
    1700                 :             :                 errmsg("redo starts at %X/%08X",
    1701                 :             :                        LSN_FORMAT_ARGS(xlogreader->ReadRecPtr)));
    1702                 :             : 
    1703                 :             :         /* Prepare to report progress of the redo phase. */
    1704         [ +  + ]:         225 :         if (!StandbyMode)
    1705                 :         108 :             begin_startup_progress_phase();
    1706                 :             : 
    1707                 :             :         /*
    1708                 :             :          * main redo apply loop
    1709                 :             :          */
    1710                 :             :         do
    1711                 :             :         {
    1712         [ +  + ]:     2964629 :             if (!StandbyMode)
    1713   [ -  +  -  - ]:      327477 :                 ereport_startup_progress("redo in progress, elapsed time: %ld.%02d s, current LSN: %X/%08X",
    1714                 :             :                                          LSN_FORMAT_ARGS(xlogreader->ReadRecPtr));
    1715                 :             : 
    1716                 :             : #ifdef WAL_DEBUG
    1717                 :             :             if (XLOG_DEBUG)
    1718                 :             :             {
    1719                 :             :                 StringInfoData buf;
    1720                 :             : 
    1721                 :             :                 initStringInfo(&buf);
    1722                 :             :                 appendStringInfo(&buf, "REDO @ %X/%08X; LSN %X/%08X: ",
    1723                 :             :                                  LSN_FORMAT_ARGS(xlogreader->ReadRecPtr),
    1724                 :             :                                  LSN_FORMAT_ARGS(xlogreader->EndRecPtr));
    1725                 :             :                 xlog_outrec(&buf, xlogreader);
    1726                 :             :                 appendStringInfoString(&buf, " - ");
    1727                 :             :                 xlog_outdesc(&buf, xlogreader);
    1728                 :             :                 elog(LOG, "%s", buf.data);
    1729                 :             :                 pfree(buf.data);
    1730                 :             :             }
    1731                 :             : #endif
    1732                 :             : 
    1733                 :             :             /* Handle interrupt signals of startup process */
    1734                 :     2964629 :             ProcessStartupProcInterrupts();
    1735                 :             : 
    1736                 :             :             /*
    1737                 :             :              * Pause WAL replay, if requested by a hot-standby session via
    1738                 :             :              * SetRecoveryPause().
    1739                 :             :              *
    1740                 :             :              * Note that we intentionally don't take the info_lck spinlock
    1741                 :             :              * here.  We might therefore read a slightly stale value of the
    1742                 :             :              * recoveryPause flag, but it can't be very stale (no worse than
    1743                 :             :              * the last spinlock we did acquire).  Since a pause request is a
    1744                 :             :              * pretty asynchronous thing anyway, possibly responding to it one
    1745                 :             :              * WAL record later than we otherwise would is a minor issue, so
    1746                 :             :              * it doesn't seem worth adding another spinlock cycle to prevent
    1747                 :             :              * that.
    1748                 :             :              */
    1749         [ -  + ]:     2964629 :             if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
    1750                 :             :                 RECOVERY_NOT_PAUSED)
    1751                 :           0 :                 recoveryPausesHere(false);
    1752                 :             : 
    1753                 :             :             /*
    1754                 :             :              * Have we reached our recovery target?
    1755                 :             :              */
    1756         [ +  + ]:     2964629 :             if (recoveryStopsBefore(xlogreader))
    1757                 :             :             {
    1758                 :           2 :                 reachedRecoveryTarget = true;
    1759                 :           2 :                 break;
    1760                 :             :             }
    1761                 :             : 
    1762                 :             :             /*
    1763                 :             :              * If we've been asked to lag the primary, wait on latch until
    1764                 :             :              * enough time has passed.
    1765                 :             :              */
    1766         [ +  + ]:     2964627 :             if (recoveryApplyDelay(xlogreader))
    1767                 :             :             {
    1768                 :             :                 /*
    1769                 :             :                  * We test for paused recovery again here. If user sets
    1770                 :             :                  * delayed apply, it may be because they expect to pause
    1771                 :             :                  * recovery in case of problems, so we must test again here
    1772                 :             :                  * otherwise pausing during the delay-wait wouldn't work.
    1773                 :             :                  */
    1774         [ +  + ]:          21 :                 if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
    1775                 :             :                     RECOVERY_NOT_PAUSED)
    1776                 :           1 :                     recoveryPausesHere(false);
    1777                 :             :             }
    1778                 :             : 
    1779                 :             :             /*
    1780                 :             :              * Apply the record
    1781                 :             :              */
    1782                 :     2964627 :             ApplyWalRecord(xlogreader, record, &replayTLI);
    1783                 :             : 
    1784                 :             :             /*
    1785                 :             :              * Wake up processes waiting for standby replay, write, or flush
    1786                 :             :              * LSN to reach current replay position.  Replay implies that the
    1787                 :             :              * WAL was already written and flushed to disk, so write and flush
    1788                 :             :              * waiters can be woken at the replay position too.
    1789                 :             :              */
    1790                 :     2964625 :             WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_REPLAY,
    1791                 :     2964625 :                           XLogRecoveryCtl->lastReplayedEndRecPtr);
    1792                 :     2964625 :             WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_WRITE,
    1793                 :     2964625 :                           XLogRecoveryCtl->lastReplayedEndRecPtr);
    1794                 :     2964625 :             WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_FLUSH,
    1795                 :     2964625 :                           XLogRecoveryCtl->lastReplayedEndRecPtr);
    1796                 :             : 
    1797                 :             :             /* Exit loop if we reached inclusive recovery target */
    1798         [ +  + ]:     2964625 :             if (recoveryStopsAfter(xlogreader))
    1799                 :             :             {
    1800                 :           5 :                 reachedRecoveryTarget = true;
    1801                 :           5 :                 break;
    1802                 :             :             }
    1803                 :             : 
    1804                 :             :             /* Else, try to fetch the next WAL record */
    1805                 :     2964620 :             record = ReadRecord(xlogprefetcher, LOG, false, replayTLI);
    1806         [ +  + ]:     2964557 :         } while (record != NULL);
    1807                 :             : 
    1808                 :             :         /*
    1809                 :             :          * end of main redo apply loop
    1810                 :             :          */
    1811                 :             : 
    1812         [ +  + ]:         160 :         if (reachedRecoveryTarget)
    1813                 :             :         {
    1814         [ -  + ]:           7 :             if (!reachedConsistency)
    1815         [ #  # ]:           0 :                 ereport(FATAL,
    1816                 :             :                         (errmsg("requested recovery stop point is before consistent recovery point")));
    1817                 :             : 
    1818                 :             :             /*
    1819                 :             :              * This is the last point where we can restart recovery with a new
    1820                 :             :              * recovery target, if we shutdown and begin again. After this,
    1821                 :             :              * Resource Managers may choose to do permanent corrective actions
    1822                 :             :              * at end of recovery.
    1823                 :             :              */
    1824   [ -  +  +  - ]:           7 :             switch (recoveryTargetAction)
    1825                 :             :             {
    1826                 :           0 :                 case RECOVERY_TARGET_ACTION_SHUTDOWN:
    1827                 :             : 
    1828                 :             :                     /*
    1829                 :             :                      * exit with special return code to request shutdown of
    1830                 :             :                      * postmaster.  Log messages issued from postmaster.
    1831                 :             :                      */
    1832                 :           0 :                     proc_exit(3);
    1833                 :             : 
    1834                 :           1 :                 case RECOVERY_TARGET_ACTION_PAUSE:
    1835                 :           1 :                     SetRecoveryPause(true);
    1836                 :           1 :                     recoveryPausesHere(true);
    1837                 :             : 
    1838                 :             :                     /* drop into promote */
    1839                 :             :                     pg_fallthrough;
    1840                 :             : 
    1841                 :           7 :                 case RECOVERY_TARGET_ACTION_PROMOTE:
    1842                 :           7 :                     break;
    1843                 :             :             }
    1844                 :             :         }
    1845                 :             : 
    1846                 :         160 :         RmgrCleanup();
    1847                 :             : 
    1848         [ +  - ]:         160 :         ereport(LOG,
    1849                 :             :                 errmsg("redo done at %X/%08X system usage: %s",
    1850                 :             :                        LSN_FORMAT_ARGS(xlogreader->ReadRecPtr),
    1851                 :             :                        pg_rusage_show(&ru0)));
    1852                 :         160 :         xtime = GetLatestXTime();
    1853         [ +  + ]:         160 :         if (xtime)
    1854         [ +  - ]:          43 :             ereport(LOG,
    1855                 :             :                     (errmsg("last completed transaction was at log time %s",
    1856                 :             :                             timestamptz_to_str(xtime))));
    1857                 :             : 
    1858                 :         160 :         InRedo = false;
    1859                 :             :     }
    1860                 :             :     else
    1861                 :             :     {
    1862                 :             :         /* there are no WAL records following the checkpoint */
    1863         [ +  - ]:           9 :         ereport(LOG,
    1864                 :             :                 (errmsg("redo is not required")));
    1865                 :             :     }
    1866                 :             : 
    1867                 :             :     /*
    1868                 :             :      * This check is intentionally after the above log messages that indicate
    1869                 :             :      * how far recovery went.
    1870                 :             :      */
    1871         [ +  + ]:         169 :     if (ArchiveRecoveryRequested &&
    1872         [ +  + ]:          61 :         recoveryTarget != RECOVERY_TARGET_UNSET &&
    1873         [ +  + ]:           8 :         !reachedRecoveryTarget)
    1874         [ +  - ]:           1 :         ereport(FATAL,
    1875                 :             :                 (errcode(ERRCODE_CONFIG_FILE_ERROR),
    1876                 :             :                  errmsg("recovery ended before configured recovery target was reached")));
    1877                 :         168 : }
    1878                 :             : 
    1879                 :             : /*
    1880                 :             :  * Subroutine of PerformWalRecovery, to apply one WAL record.
    1881                 :             :  */
    1882                 :             : static void
    1883                 :     2964627 : ApplyWalRecord(XLogReaderState *xlogreader, XLogRecord *record, TimeLineID *replayTLI)
    1884                 :             : {
    1885                 :             :     ErrorContextCallback errcallback;
    1886                 :     2964627 :     bool        switchedTLI = false;
    1887                 :             : 
    1888                 :             :     /* Setup error traceback support for ereport() */
    1889                 :     2964627 :     errcallback.callback = rm_redo_error_callback;
    1890                 :     2964627 :     errcallback.arg = xlogreader;
    1891                 :     2964627 :     errcallback.previous = error_context_stack;
    1892                 :     2964627 :     error_context_stack = &errcallback;
    1893                 :             : 
    1894                 :             :     /*
    1895                 :             :      * TransamVariables->nextXid must be beyond record's xid.
    1896                 :             :      */
    1897                 :     2964627 :     AdvanceNextFullTransactionIdPastXid(record->xl_xid);
    1898                 :             : 
    1899                 :             :     /*
    1900                 :             :      * Before replaying this record, check if this record causes the current
    1901                 :             :      * timeline to change. The record is already considered to be part of the
    1902                 :             :      * new timeline, so we update replayTLI before replaying it. That's
    1903                 :             :      * important so that replayEndTLI, which is recorded as the minimum
    1904                 :             :      * recovery point's TLI if recovery stops after this record, is set
    1905                 :             :      * correctly.
    1906                 :             :      */
    1907         [ +  + ]:     2964627 :     if (record->xl_rmid == RM_XLOG_ID)
    1908                 :             :     {
    1909                 :      118476 :         TimeLineID  newReplayTLI = *replayTLI;
    1910                 :      118476 :         TimeLineID  prevReplayTLI = *replayTLI;
    1911                 :      118476 :         uint8       info = record->xl_info & ~XLR_INFO_MASK;
    1912                 :             : 
    1913         [ +  + ]:      118476 :         if (info == XLOG_CHECKPOINT_SHUTDOWN)
    1914                 :             :         {
    1915                 :             :             CheckPoint  checkPoint;
    1916                 :             : 
    1917                 :          44 :             memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
    1918                 :          44 :             newReplayTLI = checkPoint.ThisTimeLineID;
    1919                 :          44 :             prevReplayTLI = checkPoint.PrevTimeLineID;
    1920                 :             :         }
    1921         [ +  + ]:      118432 :         else if (info == XLOG_END_OF_RECOVERY)
    1922                 :             :         {
    1923                 :             :             xl_end_of_recovery xlrec;
    1924                 :             : 
    1925                 :          13 :             memcpy(&xlrec, XLogRecGetData(xlogreader), sizeof(xl_end_of_recovery));
    1926                 :          13 :             newReplayTLI = xlrec.ThisTimeLineID;
    1927                 :          13 :             prevReplayTLI = xlrec.PrevTimeLineID;
    1928                 :             :         }
    1929                 :             : 
    1930         [ +  + ]:      118476 :         if (newReplayTLI != *replayTLI)
    1931                 :             :         {
    1932                 :             :             /* Check that it's OK to switch to this TLI */
    1933                 :          14 :             checkTimeLineSwitch(xlogreader->EndRecPtr,
    1934                 :             :                                 newReplayTLI, prevReplayTLI, *replayTLI);
    1935                 :             : 
    1936                 :             :             /* Following WAL records should be run with new TLI */
    1937                 :          14 :             *replayTLI = newReplayTLI;
    1938                 :          14 :             switchedTLI = true;
    1939                 :             :         }
    1940                 :             :     }
    1941                 :             : 
    1942                 :             :     /*
    1943                 :             :      * Update shared replayEndRecPtr before replaying this record, so that
    1944                 :             :      * XLogFlush will update minRecoveryPoint correctly.
    1945                 :             :      */
    1946                 :     2964627 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    1947                 :     2964627 :     XLogRecoveryCtl->replayEndRecPtr = xlogreader->EndRecPtr;
    1948                 :     2964627 :     XLogRecoveryCtl->replayEndTLI = *replayTLI;
    1949                 :     2964627 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    1950                 :             : 
    1951                 :             :     /*
    1952                 :             :      * If we are attempting to enter Hot Standby mode, process XIDs we see
    1953                 :             :      */
    1954         [ +  + ]:     2964627 :     if (standbyState >= STANDBY_INITIALIZED &&
    1955         [ +  + ]:     2656800 :         TransactionIdIsValid(record->xl_xid))
    1956                 :     2594138 :         RecordKnownAssignedTransactionIds(record->xl_xid);
    1957                 :             : 
    1958                 :             :     /*
    1959                 :             :      * Some XLOG record types that are related to recovery are processed
    1960                 :             :      * directly here, rather than in xlog_redo()
    1961                 :             :      */
    1962         [ +  + ]:     2964627 :     if (record->xl_rmid == RM_XLOG_ID)
    1963                 :      118476 :         xlogrecovery_redo(xlogreader, *replayTLI);
    1964                 :             : 
    1965                 :             :     /* Now apply the WAL record itself */
    1966                 :     2964627 :     GetRmgr(record->xl_rmid).rm_redo(xlogreader);
    1967                 :             : 
    1968                 :             :     /*
    1969                 :             :      * After redo, check whether the backup pages associated with the WAL
    1970                 :             :      * record are consistent with the existing pages. This check is done only
    1971                 :             :      * if consistency check is enabled for this record.
    1972                 :             :      */
    1973         [ +  + ]:     2964625 :     if ((record->xl_info & XLR_CHECK_CONSISTENCY) != 0)
    1974                 :     2275675 :         verifyBackupPageConsistency(xlogreader);
    1975                 :             : 
    1976                 :             :     /* Pop the error context stack */
    1977                 :     2964625 :     error_context_stack = errcallback.previous;
    1978                 :             : 
    1979                 :             :     /*
    1980                 :             :      * Update lastReplayedEndRecPtr after this record has been successfully
    1981                 :             :      * replayed.
    1982                 :             :      */
    1983                 :     2964625 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    1984                 :     2964625 :     XLogRecoveryCtl->lastReplayedReadRecPtr = xlogreader->ReadRecPtr;
    1985                 :     2964625 :     XLogRecoveryCtl->lastReplayedEndRecPtr = xlogreader->EndRecPtr;
    1986                 :     2964625 :     XLogRecoveryCtl->lastReplayedTLI = *replayTLI;
    1987                 :     2964625 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    1988                 :             : 
    1989                 :             :     /* ------
    1990                 :             :      * Wakeup walsenders:
    1991                 :             :      *
    1992                 :             :      * On the standby, the WAL is flushed first (which will only wake up
    1993                 :             :      * physical walsenders) and then applied, which will only wake up logical
    1994                 :             :      * walsenders.
    1995                 :             :      *
    1996                 :             :      * Indeed, logical walsenders on standby can't decode and send data until
    1997                 :             :      * it's been applied.
    1998                 :             :      *
    1999                 :             :      * Physical walsenders don't need to be woken up during replay unless
    2000                 :             :      * cascading replication is allowed and time line change occurred (so that
    2001                 :             :      * they can notice that they are on a new time line).
    2002                 :             :      *
    2003                 :             :      * That's why the wake up conditions are for:
    2004                 :             :      *
    2005                 :             :      *  - physical walsenders in case of new time line and cascade
    2006                 :             :      *    replication is allowed
    2007                 :             :      *  - logical walsenders in case cascade replication is allowed (could not
    2008                 :             :      *    be created otherwise)
    2009                 :             :      * ------
    2010                 :             :      */
    2011   [ +  +  +  + ]:     2964625 :     if (AllowCascadeReplication())
    2012                 :     2712739 :         WalSndWakeup(switchedTLI, true);
    2013                 :             : 
    2014                 :             :     /*
    2015                 :             :      * If rm_redo called XLogRequestWalReceiverReply, then we wake up the
    2016                 :             :      * receiver so that it notices the updated lastReplayedEndRecPtr and sends
    2017                 :             :      * a reply to the primary.
    2018                 :             :      */
    2019         [ +  + ]:     2964625 :     if (doRequestWalReceiverReply)
    2020                 :             :     {
    2021                 :           2 :         doRequestWalReceiverReply = false;
    2022                 :           2 :         WalRcvRequestApplyReply();
    2023                 :             :     }
    2024                 :             : 
    2025                 :             :     /* Allow read-only connections if we're consistent now */
    2026                 :     2964625 :     CheckRecoveryConsistency();
    2027                 :             : 
    2028                 :             :     /* Is this a timeline switch? */
    2029         [ +  + ]:     2964625 :     if (switchedTLI)
    2030                 :             :     {
    2031                 :             :         /*
    2032                 :             :          * Before we continue on the new timeline, clean up any (possibly
    2033                 :             :          * bogus) future WAL segments on the old timeline.
    2034                 :             :          */
    2035                 :          14 :         RemoveNonParentXlogFiles(xlogreader->EndRecPtr, *replayTLI);
    2036                 :             : 
    2037                 :             :         /* Reset the prefetcher. */
    2038                 :          14 :         XLogPrefetchReconfigure();
    2039                 :             :     }
    2040                 :     2964625 : }
    2041                 :             : 
    2042                 :             : /*
    2043                 :             :  * Some XLOG RM record types that are directly related to WAL recovery are
    2044                 :             :  * handled here rather than in the xlog_redo()
    2045                 :             :  */
    2046                 :             : static void
    2047                 :      118476 : xlogrecovery_redo(XLogReaderState *record, TimeLineID replayTLI)
    2048                 :             : {
    2049                 :      118476 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
    2050                 :      118476 :     XLogRecPtr  lsn = record->EndRecPtr;
    2051                 :             : 
    2052                 :             :     Assert(XLogRecGetRmid(record) == RM_XLOG_ID);
    2053                 :             : 
    2054         [ +  + ]:      118476 :     if (info == XLOG_OVERWRITE_CONTRECORD)
    2055                 :             :     {
    2056                 :             :         /* Verify the payload of a XLOG_OVERWRITE_CONTRECORD record. */
    2057                 :             :         xl_overwrite_contrecord xlrec;
    2058                 :             : 
    2059                 :           1 :         memcpy(&xlrec, XLogRecGetData(record), sizeof(xl_overwrite_contrecord));
    2060         [ -  + ]:           1 :         if (xlrec.overwritten_lsn != record->overwrittenRecPtr)
    2061         [ #  # ]:           0 :             elog(FATAL, "mismatching overwritten LSN %X/%08X -> %X/%08X",
    2062                 :             :                  LSN_FORMAT_ARGS(xlrec.overwritten_lsn),
    2063                 :             :                  LSN_FORMAT_ARGS(record->overwrittenRecPtr));
    2064                 :             : 
    2065                 :             :         /* We have safely skipped the aborted record */
    2066                 :           1 :         abortedRecPtr = InvalidXLogRecPtr;
    2067                 :           1 :         missingContrecPtr = InvalidXLogRecPtr;
    2068                 :             : 
    2069         [ +  - ]:           1 :         ereport(LOG,
    2070                 :             :                 errmsg("successfully skipped missing contrecord at %X/%08X, overwritten at %s",
    2071                 :             :                        LSN_FORMAT_ARGS(xlrec.overwritten_lsn),
    2072                 :             :                        timestamptz_to_str(xlrec.overwrite_time)));
    2073                 :             : 
    2074                 :             :         /* Verifying the record should only happen once */
    2075                 :           1 :         record->overwrittenRecPtr = InvalidXLogRecPtr;
    2076                 :             :     }
    2077         [ +  + ]:      118475 :     else if (info == XLOG_BACKUP_END)
    2078                 :             :     {
    2079                 :             :         XLogRecPtr  startpoint;
    2080                 :             : 
    2081                 :         104 :         memcpy(&startpoint, XLogRecGetData(record), sizeof(startpoint));
    2082                 :             : 
    2083         [ +  + ]:         104 :         if (backupStartPoint == startpoint)
    2084                 :             :         {
    2085                 :             :             /*
    2086                 :             :              * We have reached the end of base backup, the point where
    2087                 :             :              * pg_backup_stop() was done.  The data on disk is now consistent
    2088                 :             :              * (assuming we have also reached minRecoveryPoint).  Set
    2089                 :             :              * backupEndPoint to the current LSN, so that the next call to
    2090                 :             :              * CheckRecoveryConsistency() will notice it and do the
    2091                 :             :              * end-of-backup processing.
    2092                 :             :              */
    2093         [ +  + ]:          86 :             elog(DEBUG1, "end of backup record reached");
    2094                 :             : 
    2095                 :          86 :             backupEndPoint = lsn;
    2096                 :             :         }
    2097                 :             :         else
    2098         [ +  + ]:          18 :             elog(DEBUG1, "saw end-of-backup record for backup starting at %X/%08X, waiting for %X/%08X",
    2099                 :             :                  LSN_FORMAT_ARGS(startpoint), LSN_FORMAT_ARGS(backupStartPoint));
    2100                 :             :     }
    2101                 :      118476 : }
    2102                 :             : 
    2103                 :             : /*
    2104                 :             :  * Verify that, in non-test mode, ./pg_tblspc doesn't contain any real
    2105                 :             :  * directories.
    2106                 :             :  *
    2107                 :             :  * Replay of database creation XLOG records for databases that were later
    2108                 :             :  * dropped can create fake directories in pg_tblspc.  By the time consistency
    2109                 :             :  * is reached these directories should have been removed; here we verify
    2110                 :             :  * that this did indeed happen.  This is to be called at the point where
    2111                 :             :  * consistent state is reached.
    2112                 :             :  *
    2113                 :             :  * allow_in_place_tablespaces turns the PANIC into a WARNING, which is
    2114                 :             :  * useful for testing purposes, and also allows for an escape hatch in case
    2115                 :             :  * things go south.
    2116                 :             :  */
    2117                 :             : static void
    2118                 :         133 : CheckTablespaceDirectory(void)
    2119                 :             : {
    2120                 :             :     DIR        *dir;
    2121                 :             :     struct dirent *de;
    2122                 :             : 
    2123                 :         133 :     dir = AllocateDir(PG_TBLSPC_DIR);
    2124         [ +  + ]:         406 :     while ((de = ReadDir(dir, PG_TBLSPC_DIR)) != NULL)
    2125                 :             :     {
    2126                 :             :         char        path[MAXPGPATH + sizeof(PG_TBLSPC_DIR)];
    2127                 :             : 
    2128                 :             :         /* Skip entries of non-oid names */
    2129         [ +  + ]:         273 :         if (strspn(de->d_name, "0123456789") != strlen(de->d_name))
    2130                 :         266 :             continue;
    2131                 :             : 
    2132                 :           7 :         snprintf(path, sizeof(path), "%s/%s", PG_TBLSPC_DIR, de->d_name);
    2133                 :             : 
    2134         [ +  + ]:           7 :         if (get_dirent_type(path, de, false, ERROR) != PGFILETYPE_LNK)
    2135   [ +  -  +  - ]:           4 :             ereport(allow_in_place_tablespaces ? WARNING : PANIC,
    2136                 :             :                     (errcode(ERRCODE_DATA_CORRUPTED),
    2137                 :             :                      errmsg("unexpected directory entry \"%s\" found in %s",
    2138                 :             :                             de->d_name, PG_TBLSPC_DIR),
    2139                 :             :                      errdetail("All directory entries in %s/ should be symbolic links.",
    2140                 :             :                                PG_TBLSPC_DIR),
    2141                 :             :                      errhint("Remove those directories, or set \"allow_in_place_tablespaces\" to ON transiently to let recovery complete.")));
    2142                 :             :     }
    2143                 :         133 : }
    2144                 :             : 
    2145                 :             : /*
    2146                 :             :  * Checks if recovery has reached a consistent state. When consistency is
    2147                 :             :  * reached and we have a valid starting standby snapshot, tell postmaster
    2148                 :             :  * that it can start accepting read-only connections.
    2149                 :             :  */
    2150                 :             : static void
    2151                 :     2964860 : CheckRecoveryConsistency(void)
    2152                 :             : {
    2153                 :             :     XLogRecPtr  lastReplayedEndRecPtr;
    2154                 :             :     TimeLineID  lastReplayedTLI;
    2155                 :             : 
    2156                 :             :     /*
    2157                 :             :      * During crash recovery, we don't reach a consistent state until we've
    2158                 :             :      * replayed all the WAL.
    2159                 :             :      */
    2160         [ +  + ]:     2964860 :     if (!XLogRecPtrIsValid(minRecoveryPoint))
    2161                 :      322367 :         return;
    2162                 :             : 
    2163                 :             :     Assert(InArchiveRecovery);
    2164                 :             : 
    2165                 :             :     /*
    2166                 :             :      * assume that we are called in the startup process, and hence don't need
    2167                 :             :      * a lock to read lastReplayedEndRecPtr
    2168                 :             :      */
    2169                 :     2642493 :     lastReplayedEndRecPtr = XLogRecoveryCtl->lastReplayedEndRecPtr;
    2170                 :     2642493 :     lastReplayedTLI = XLogRecoveryCtl->lastReplayedTLI;
    2171                 :             : 
    2172                 :             :     /*
    2173                 :             :      * Have we reached the point where our base backup was completed?
    2174                 :             :      */
    2175         [ +  + ]:     2642493 :     if (XLogRecPtrIsValid(backupEndPoint) &&
    2176         [ +  + ]:        1555 :         backupEndPoint <= lastReplayedEndRecPtr)
    2177                 :             :     {
    2178                 :          89 :         XLogRecPtr  saveBackupStartPoint = backupStartPoint;
    2179                 :          89 :         XLogRecPtr  saveBackupEndPoint = backupEndPoint;
    2180                 :             : 
    2181         [ +  + ]:          89 :         elog(DEBUG1, "end of backup reached");
    2182                 :             : 
    2183                 :             :         /*
    2184                 :             :          * We have reached the end of base backup, as indicated by pg_control.
    2185                 :             :          * Update the control file accordingly.
    2186                 :             :          */
    2187                 :          89 :         ReachedEndOfBackup(lastReplayedEndRecPtr, lastReplayedTLI);
    2188                 :          89 :         backupStartPoint = InvalidXLogRecPtr;
    2189                 :          89 :         backupEndPoint = InvalidXLogRecPtr;
    2190                 :          89 :         backupEndRequired = false;
    2191                 :             : 
    2192         [ +  - ]:          89 :         ereport(LOG,
    2193                 :             :                 errmsg("completed backup recovery with redo LSN %X/%08X and end LSN %X/%08X",
    2194                 :             :                        LSN_FORMAT_ARGS(saveBackupStartPoint),
    2195                 :             :                        LSN_FORMAT_ARGS(saveBackupEndPoint)));
    2196                 :             :     }
    2197                 :             : 
    2198                 :             :     /*
    2199                 :             :      * Have we passed our safe starting point? Note that minRecoveryPoint is
    2200                 :             :      * known to be incorrectly set if recovering from a backup, until the
    2201                 :             :      * XLOG_BACKUP_END arrives to advise us of the correct minRecoveryPoint.
    2202                 :             :      * All we know prior to that is that we're not consistent yet.
    2203                 :             :      */
    2204   [ +  +  +  + ]:     2642493 :     if (!reachedConsistency && !backupEndRequired &&
    2205         [ +  + ]:        7978 :         minRecoveryPoint <= lastReplayedEndRecPtr)
    2206                 :             :     {
    2207                 :             :         /*
    2208                 :             :          * Check to see if the XLOG sequence contained any unresolved
    2209                 :             :          * references to uninitialized pages.
    2210                 :             :          */
    2211                 :         133 :         XLogCheckInvalidPages();
    2212                 :             : 
    2213                 :             :         /*
    2214                 :             :          * Check that pg_tblspc doesn't contain any real directories. Replay
    2215                 :             :          * of Database/CREATE_* records may have created fictitious tablespace
    2216                 :             :          * directories that should have been removed by the time consistency
    2217                 :             :          * was reached.
    2218                 :             :          */
    2219                 :         133 :         CheckTablespaceDirectory();
    2220                 :             : 
    2221                 :         133 :         reachedConsistency = true;
    2222                 :         133 :         SendPostmasterSignal(PMSIGNAL_RECOVERY_CONSISTENT);
    2223         [ +  - ]:         133 :         ereport(LOG,
    2224                 :             :                 errmsg("consistent recovery state reached at %X/%08X",
    2225                 :             :                        LSN_FORMAT_ARGS(lastReplayedEndRecPtr)));
    2226                 :             :     }
    2227                 :             : 
    2228                 :             :     /*
    2229                 :             :      * Have we got a valid starting snapshot that will allow queries to be
    2230                 :             :      * run? If so, we can tell postmaster that the database is consistent now,
    2231                 :             :      * enabling connections.
    2232                 :             :      */
    2233         [ +  + ]:     2642493 :     if (standbyState == STANDBY_SNAPSHOT_READY &&
    2234   [ +  +  +  + ]:     2642232 :         !LocalHotStandbyActive &&
    2235         [ +  - ]:         124 :         reachedConsistency &&
    2236                 :             :         IsUnderPostmaster)
    2237                 :             :     {
    2238                 :         124 :         SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    2239                 :         124 :         XLogRecoveryCtl->SharedHotStandbyActive = true;
    2240                 :         124 :         SpinLockRelease(&XLogRecoveryCtl->info_lck);
    2241                 :             : 
    2242                 :         124 :         LocalHotStandbyActive = true;
    2243                 :             : 
    2244                 :         124 :         SendPostmasterSignal(PMSIGNAL_BEGIN_HOT_STANDBY);
    2245                 :             :     }
    2246                 :             : }
    2247                 :             : 
    2248                 :             : /*
    2249                 :             :  * Error context callback for errors occurring during rm_redo().
    2250                 :             :  */
    2251                 :             : static void
    2252                 :         173 : rm_redo_error_callback(void *arg)
    2253                 :             : {
    2254                 :         173 :     XLogReaderState *record = (XLogReaderState *) arg;
    2255                 :             :     StringInfoData buf;
    2256                 :             : 
    2257                 :         173 :     initStringInfo(&buf);
    2258                 :         173 :     xlog_outdesc(&buf, record);
    2259                 :         173 :     xlog_block_info(&buf, record);
    2260                 :             : 
    2261                 :             :     /* translator: %s is a WAL record description */
    2262                 :         173 :     errcontext("WAL redo at %X/%08X for %s",
    2263                 :         173 :                LSN_FORMAT_ARGS(record->ReadRecPtr),
    2264                 :             :                buf.data);
    2265                 :             : 
    2266                 :         173 :     pfree(buf.data);
    2267                 :         173 : }
    2268                 :             : 
    2269                 :             : /*
    2270                 :             :  * Returns a string describing an XLogRecord, consisting of its identity
    2271                 :             :  * optionally followed by a colon, a space, and a further description.
    2272                 :             :  */
    2273                 :             : void
    2274                 :         173 : xlog_outdesc(StringInfo buf, XLogReaderState *record)
    2275                 :             : {
    2276                 :         173 :     RmgrData    rmgr = GetRmgr(XLogRecGetRmid(record));
    2277                 :         173 :     uint8       info = XLogRecGetInfo(record);
    2278                 :             :     const char *id;
    2279                 :             : 
    2280                 :         173 :     appendStringInfoString(buf, rmgr.rm_name);
    2281                 :         173 :     appendStringInfoChar(buf, '/');
    2282                 :             : 
    2283                 :         173 :     id = rmgr.rm_identify(info);
    2284         [ -  + ]:         173 :     if (id == NULL)
    2285                 :           0 :         appendStringInfo(buf, "UNKNOWN (%X): ", info & ~XLR_INFO_MASK);
    2286                 :             :     else
    2287                 :         173 :         appendStringInfo(buf, "%s: ", id);
    2288                 :             : 
    2289                 :         173 :     rmgr.rm_desc(buf, record);
    2290                 :         173 : }
    2291                 :             : 
    2292                 :             : #ifdef WAL_DEBUG
    2293                 :             : 
    2294                 :             : static void
    2295                 :             : xlog_outrec(StringInfo buf, XLogReaderState *record)
    2296                 :             : {
    2297                 :             :     appendStringInfo(buf, "prev %X/%08X; xid %u",
    2298                 :             :                      LSN_FORMAT_ARGS(XLogRecGetPrev(record)),
    2299                 :             :                      XLogRecGetXid(record));
    2300                 :             : 
    2301                 :             :     appendStringInfo(buf, "; len %u",
    2302                 :             :                      XLogRecGetDataLen(record));
    2303                 :             : 
    2304                 :             :     xlog_block_info(buf, record);
    2305                 :             : }
    2306                 :             : #endif                          /* WAL_DEBUG */
    2307                 :             : 
    2308                 :             : /*
    2309                 :             :  * Returns a string giving information about all the blocks in an
    2310                 :             :  * XLogRecord.
    2311                 :             :  */
    2312                 :             : static void
    2313                 :         173 : xlog_block_info(StringInfo buf, XLogReaderState *record)
    2314                 :             : {
    2315                 :             :     int         block_id;
    2316                 :             : 
    2317                 :             :     /* decode block references */
    2318         [ +  + ]:         244 :     for (block_id = 0; block_id <= XLogRecMaxBlockId(record); block_id++)
    2319                 :             :     {
    2320                 :             :         RelFileLocator rlocator;
    2321                 :             :         ForkNumber  forknum;
    2322                 :             :         BlockNumber blk;
    2323                 :             : 
    2324         [ -  + ]:          71 :         if (!XLogRecGetBlockTagExtended(record, block_id,
    2325                 :             :                                         &rlocator, &forknum, &blk, NULL))
    2326                 :           0 :             continue;
    2327                 :             : 
    2328         [ +  + ]:          71 :         if (forknum != MAIN_FORKNUM)
    2329                 :           9 :             appendStringInfo(buf, "; blkref #%d: rel %u/%u/%u, fork %u, blk %u",
    2330                 :             :                              block_id,
    2331                 :             :                              rlocator.spcOid, rlocator.dbOid,
    2332                 :             :                              rlocator.relNumber,
    2333                 :             :                              forknum,
    2334                 :             :                              blk);
    2335                 :             :         else
    2336                 :          62 :             appendStringInfo(buf, "; blkref #%d: rel %u/%u/%u, blk %u",
    2337                 :             :                              block_id,
    2338                 :             :                              rlocator.spcOid, rlocator.dbOid,
    2339                 :             :                              rlocator.relNumber,
    2340                 :             :                              blk);
    2341         [ +  + ]:          71 :         if (XLogRecHasBlockImage(record, block_id))
    2342                 :          51 :             appendStringInfoString(buf, " FPW");
    2343                 :             :     }
    2344                 :         173 : }
    2345                 :             : 
    2346                 :             : 
    2347                 :             : /*
    2348                 :             :  * Check that it's OK to switch to new timeline during recovery.
    2349                 :             :  *
    2350                 :             :  * 'lsn' is the address of the shutdown checkpoint record we're about to
    2351                 :             :  * replay. (Currently, timeline can only change at a shutdown checkpoint).
    2352                 :             :  */
    2353                 :             : static void
    2354                 :          14 : checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI, TimeLineID prevTLI,
    2355                 :             :                     TimeLineID replayTLI)
    2356                 :             : {
    2357                 :             :     /* Check that the record agrees on what the current (old) timeline is */
    2358         [ -  + ]:          14 :     if (prevTLI != replayTLI)
    2359         [ #  # ]:           0 :         ereport(PANIC,
    2360                 :             :                 (errmsg("unexpected previous timeline ID %u (current timeline ID %u) in checkpoint record",
    2361                 :             :                         prevTLI, replayTLI)));
    2362                 :             : 
    2363                 :             :     /*
    2364                 :             :      * The new timeline better be in the list of timelines we expect to see,
    2365                 :             :      * according to the timeline history. It should also not decrease.
    2366                 :             :      */
    2367   [ +  -  -  + ]:          14 :     if (newTLI < replayTLI || !tliInHistory(newTLI, expectedTLEs))
    2368         [ #  # ]:           0 :         ereport(PANIC,
    2369                 :             :                 (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
    2370                 :             :                         newTLI, replayTLI)));
    2371                 :             : 
    2372                 :             :     /*
    2373                 :             :      * If we have not yet reached min recovery point, and we're about to
    2374                 :             :      * switch to a timeline greater than the timeline of the min recovery
    2375                 :             :      * point: trouble. After switching to the new timeline, we could not
    2376                 :             :      * possibly visit the min recovery point on the correct timeline anymore.
    2377                 :             :      * This can happen if there is a newer timeline in the archive that
    2378                 :             :      * branched before the timeline the min recovery point is on, and you
    2379                 :             :      * attempt to do PITR to the new timeline.
    2380                 :             :      */
    2381         [ +  + ]:          14 :     if (XLogRecPtrIsValid(minRecoveryPoint) &&
    2382         [ +  + ]:          12 :         lsn < minRecoveryPoint &&
    2383         [ -  + ]:           1 :         newTLI > minRecoveryPointTLI)
    2384         [ #  # ]:           0 :         ereport(PANIC,
    2385                 :             :                 errmsg("unexpected timeline ID %u in checkpoint record, before reaching minimum recovery point %X/%08X on timeline %u",
    2386                 :             :                        newTLI,
    2387                 :             :                        LSN_FORMAT_ARGS(minRecoveryPoint),
    2388                 :             :                        minRecoveryPointTLI));
    2389                 :             : 
    2390                 :             :     /* Looks good */
    2391                 :          14 : }
    2392                 :             : 
    2393                 :             : 
    2394                 :             : /*
    2395                 :             :  * Extract timestamp from WAL record.
    2396                 :             :  *
    2397                 :             :  * If the record contains a timestamp, returns true, and saves the timestamp
    2398                 :             :  * in *recordXtime. If the record type has no timestamp, returns false.
    2399                 :             :  * Currently, only transaction commit/abort records and restore points contain
    2400                 :             :  * timestamps.
    2401                 :             :  */
    2402                 :             : static bool
    2403                 :       47920 : getRecordTimestamp(XLogReaderState *record, TimestampTz *recordXtime)
    2404                 :             : {
    2405                 :       47920 :     uint8       info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
    2406                 :       47920 :     uint8       xact_info = info & XLOG_XACT_OPMASK;
    2407                 :       47920 :     uint8       rmid = XLogRecGetRmid(record);
    2408                 :             : 
    2409   [ +  +  +  - ]:       47920 :     if (rmid == RM_XLOG_ID && info == XLOG_RESTORE_POINT)
    2410                 :             :     {
    2411                 :           2 :         *recordXtime = ((xl_restore_point *) XLogRecGetData(record))->rp_time;
    2412                 :           2 :         return true;
    2413                 :             :     }
    2414   [ +  -  +  +  :       47918 :     if (rmid == RM_XACT_ID && (xact_info == XLOG_XACT_COMMIT ||
                   +  + ]
    2415                 :             :                                xact_info == XLOG_XACT_COMMIT_PREPARED))
    2416                 :             :     {
    2417                 :       43882 :         *recordXtime = ((xl_xact_commit *) XLogRecGetData(record))->xact_time;
    2418                 :       43882 :         return true;
    2419                 :             :     }
    2420   [ +  -  +  +  :        4036 :     if (rmid == RM_XACT_ID && (xact_info == XLOG_XACT_ABORT ||
                   +  - ]
    2421                 :             :                                xact_info == XLOG_XACT_ABORT_PREPARED))
    2422                 :             :     {
    2423                 :        4036 :         *recordXtime = ((xl_xact_abort *) XLogRecGetData(record))->xact_time;
    2424                 :        4036 :         return true;
    2425                 :             :     }
    2426                 :           0 :     return false;
    2427                 :             : }
    2428                 :             : 
    2429                 :             : /*
    2430                 :             :  * Checks whether the current buffer page and backup page stored in the
    2431                 :             :  * WAL record are consistent or not. Before comparing the two pages, a
    2432                 :             :  * masking can be applied to the pages to ignore certain areas like hint bits,
    2433                 :             :  * unused space between pd_lower and pd_upper among other things. This
    2434                 :             :  * function should be called once WAL replay has been completed for a
    2435                 :             :  * given record.
    2436                 :             :  */
    2437                 :             : static void
    2438                 :     2275675 : verifyBackupPageConsistency(XLogReaderState *record)
    2439                 :             : {
    2440                 :     2275675 :     RmgrData    rmgr = GetRmgr(XLogRecGetRmid(record));
    2441                 :             :     RelFileLocator rlocator;
    2442                 :             :     ForkNumber  forknum;
    2443                 :             :     BlockNumber blkno;
    2444                 :             :     int         block_id;
    2445                 :             : 
    2446                 :             :     /* Records with no backup blocks have no need for consistency checks. */
    2447         [ +  + ]:     2275675 :     if (!XLogRecHasAnyBlockRefs(record))
    2448                 :          75 :         return;
    2449                 :             : 
    2450                 :             :     Assert((XLogRecGetInfo(record) & XLR_CHECK_CONSISTENCY) != 0);
    2451                 :             : 
    2452         [ +  + ]:     4723087 :     for (block_id = 0; block_id <= XLogRecMaxBlockId(record); block_id++)
    2453                 :             :     {
    2454                 :             :         Buffer      buf;
    2455                 :             :         Page        page;
    2456                 :             : 
    2457         [ +  + ]:     2447487 :         if (!XLogRecGetBlockTagExtended(record, block_id,
    2458                 :             :                                         &rlocator, &forknum, &blkno, NULL))
    2459                 :             :         {
    2460                 :             :             /*
    2461                 :             :              * WAL record doesn't contain a block reference with the given id.
    2462                 :             :              * Do nothing.
    2463                 :             :              */
    2464                 :        2090 :             continue;
    2465                 :             :         }
    2466                 :             : 
    2467                 :             :         Assert(XLogRecHasBlockImage(record, block_id));
    2468                 :             : 
    2469         [ +  + ]:     2445397 :         if (XLogRecBlockImageApply(record, block_id))
    2470                 :             :         {
    2471                 :             :             /*
    2472                 :             :              * WAL record has already applied the page, so bypass the
    2473                 :             :              * consistency check as that would result in comparing the full
    2474                 :             :              * page stored in the record with itself.
    2475                 :             :              */
    2476                 :       27046 :             continue;
    2477                 :             :         }
    2478                 :             : 
    2479                 :             :         /*
    2480                 :             :          * Read the contents from the current buffer and store it in a
    2481                 :             :          * temporary page.
    2482                 :             :          */
    2483                 :     2418351 :         buf = XLogReadBufferExtended(rlocator, forknum, blkno,
    2484                 :             :                                      RBM_NORMAL_NO_LOG,
    2485                 :             :                                      InvalidBuffer);
    2486         [ -  + ]:     2418351 :         if (!BufferIsValid(buf))
    2487                 :           0 :             continue;
    2488                 :             : 
    2489                 :     2418351 :         LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
    2490                 :     2418351 :         page = BufferGetPage(buf);
    2491                 :             : 
    2492                 :             :         /*
    2493                 :             :          * Take a copy of the local page where WAL has been applied to have a
    2494                 :             :          * comparison base before masking it...
    2495                 :             :          */
    2496                 :     2418351 :         memcpy(replay_image_masked, page, BLCKSZ);
    2497                 :             : 
    2498                 :             :         /* No need for this page anymore now that a copy is in. */
    2499                 :     2418351 :         UnlockReleaseBuffer(buf);
    2500                 :             : 
    2501                 :             :         /*
    2502                 :             :          * If the block LSN is already ahead of this WAL record, we can't
    2503                 :             :          * expect contents to match.  This can happen if recovery is
    2504                 :             :          * restarted.
    2505                 :             :          */
    2506         [ -  + ]:     2418351 :         if (PageGetLSN(replay_image_masked) > record->EndRecPtr)
    2507                 :           0 :             continue;
    2508                 :             : 
    2509                 :             :         /*
    2510                 :             :          * Read the contents from the backup copy, stored in WAL record and
    2511                 :             :          * store it in a temporary page. There is no need to allocate a new
    2512                 :             :          * page here, a local buffer is fine to hold its contents and a mask
    2513                 :             :          * can be directly applied on it.
    2514                 :             :          */
    2515         [ -  + ]:     2418351 :         if (!RestoreBlockImage(record, block_id, primary_image_masked))
    2516         [ #  # ]:           0 :             ereport(ERROR,
    2517                 :             :                     (errcode(ERRCODE_INTERNAL_ERROR),
    2518                 :             :                      errmsg_internal("%s", record->errormsg_buf)));
    2519                 :             : 
    2520                 :             :         /*
    2521                 :             :          * If masking function is defined, mask both the primary and replay
    2522                 :             :          * images
    2523                 :             :          */
    2524         [ +  - ]:     2418351 :         if (rmgr.rm_mask != NULL)
    2525                 :             :         {
    2526                 :     2418351 :             rmgr.rm_mask(replay_image_masked, blkno);
    2527                 :     2418351 :             rmgr.rm_mask(primary_image_masked, blkno);
    2528                 :             :         }
    2529                 :             : 
    2530                 :             :         /* Time to compare the primary and replay images. */
    2531         [ -  + ]:     2418351 :         if (memcmp(replay_image_masked, primary_image_masked, BLCKSZ) != 0)
    2532                 :             :         {
    2533         [ #  # ]:           0 :             elog(FATAL,
    2534                 :             :                  "inconsistent page found, rel %u/%u/%u, forknum %u, blkno %u",
    2535                 :             :                  rlocator.spcOid, rlocator.dbOid, rlocator.relNumber,
    2536                 :             :                  forknum, blkno);
    2537                 :             :         }
    2538                 :             :     }
    2539                 :             : }
    2540                 :             : 
    2541                 :             : /*
    2542                 :             :  * For point-in-time recovery, this function decides whether we want to
    2543                 :             :  * stop applying the XLOG before the current record.
    2544                 :             :  *
    2545                 :             :  * Returns true if we are stopping, false otherwise. If stopping, some
    2546                 :             :  * information is saved in recoveryStopXid et al for use in annotating the
    2547                 :             :  * new timeline's history file.
    2548                 :             :  */
    2549                 :             : static bool
    2550                 :     2964629 : recoveryStopsBefore(XLogReaderState *record)
    2551                 :             : {
    2552                 :     2964629 :     bool        stopsHere = false;
    2553                 :             :     uint8       xact_info;
    2554                 :             :     bool        isCommit;
    2555                 :     2964629 :     TimestampTz recordXtime = 0;
    2556                 :             :     TransactionId recordXid;
    2557                 :             : 
    2558                 :             :     /*
    2559                 :             :      * Ignore recovery target settings when not in archive recovery (meaning
    2560                 :             :      * we are in crash recovery).
    2561                 :             :      */
    2562         [ +  + ]:     2964629 :     if (!ArchiveRecoveryRequested)
    2563                 :      307813 :         return false;
    2564                 :             : 
    2565                 :             :     /* Check if we should stop as soon as reaching consistency */
    2566   [ -  +  -  - ]:     2656816 :     if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE && reachedConsistency)
    2567                 :             :     {
    2568         [ #  # ]:           0 :         ereport(LOG,
    2569                 :             :                 (errmsg("recovery stopping after reaching consistency")));
    2570                 :             : 
    2571                 :           0 :         recoveryStopAfter = false;
    2572                 :           0 :         recoveryStopXid = InvalidTransactionId;
    2573                 :           0 :         recoveryStopLSN = InvalidXLogRecPtr;
    2574                 :           0 :         recoveryStopTime = 0;
    2575                 :           0 :         recoveryStopName[0] = '\0';
    2576                 :           0 :         return true;
    2577                 :             :     }
    2578                 :             : 
    2579                 :             :     /* Check if target LSN has been reached */
    2580         [ +  + ]:     2656816 :     if (recoveryTarget == RECOVERY_TARGET_LSN &&
    2581         [ +  + ]:        8554 :         !recoveryTargetInclusive &&
    2582         [ +  + ]:         482 :         record->ReadRecPtr >= recoveryTargetLSN)
    2583                 :             :     {
    2584                 :           2 :         recoveryStopAfter = false;
    2585                 :           2 :         recoveryStopXid = InvalidTransactionId;
    2586                 :           2 :         recoveryStopLSN = record->ReadRecPtr;
    2587                 :           2 :         recoveryStopTime = 0;
    2588                 :           2 :         recoveryStopName[0] = '\0';
    2589         [ +  - ]:           2 :         ereport(LOG,
    2590                 :             :                 errmsg("recovery stopping before WAL location (LSN) \"%X/%08X\"",
    2591                 :             :                        LSN_FORMAT_ARGS(recoveryStopLSN)));
    2592                 :           2 :         return true;
    2593                 :             :     }
    2594                 :             : 
    2595                 :             :     /* Otherwise we only consider stopping before COMMIT or ABORT records. */
    2596         [ +  + ]:     2656814 :     if (XLogRecGetRmid(record) != RM_XACT_ID)
    2597                 :     2632550 :         return false;
    2598                 :             : 
    2599                 :       24264 :     xact_info = XLogRecGetInfo(record) & XLOG_XACT_OPMASK;
    2600                 :             : 
    2601         [ +  + ]:       24264 :     if (xact_info == XLOG_XACT_COMMIT)
    2602                 :             :     {
    2603                 :       21901 :         isCommit = true;
    2604                 :       21901 :         recordXid = XLogRecGetXid(record);
    2605                 :             :     }
    2606         [ +  + ]:        2363 :     else if (xact_info == XLOG_XACT_COMMIT_PREPARED)
    2607                 :             :     {
    2608                 :          26 :         xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
    2609                 :             :         xl_xact_parsed_commit parsed;
    2610                 :             : 
    2611                 :          26 :         isCommit = true;
    2612                 :          26 :         ParseCommitRecord(XLogRecGetInfo(record),
    2613                 :             :                           xlrec,
    2614                 :             :                           &parsed);
    2615                 :          26 :         recordXid = parsed.twophase_xid;
    2616                 :             :     }
    2617         [ +  + ]:        2337 :     else if (xact_info == XLOG_XACT_ABORT)
    2618                 :             :     {
    2619                 :        2003 :         isCommit = false;
    2620                 :        2003 :         recordXid = XLogRecGetXid(record);
    2621                 :             :     }
    2622         [ +  + ]:         334 :     else if (xact_info == XLOG_XACT_ABORT_PREPARED)
    2623                 :             :     {
    2624                 :          15 :         xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
    2625                 :             :         xl_xact_parsed_abort parsed;
    2626                 :             : 
    2627                 :          15 :         isCommit = false;
    2628                 :          15 :         ParseAbortRecord(XLogRecGetInfo(record),
    2629                 :             :                          xlrec,
    2630                 :             :                          &parsed);
    2631                 :          15 :         recordXid = parsed.twophase_xid;
    2632                 :             :     }
    2633                 :             :     else
    2634                 :         319 :         return false;
    2635                 :             : 
    2636   [ -  +  -  - ]:       23945 :     if (recoveryTarget == RECOVERY_TARGET_XID && !recoveryTargetInclusive)
    2637                 :             :     {
    2638                 :             :         /*
    2639                 :             :          * There can be only one transaction end record with this exact
    2640                 :             :          * transactionid
    2641                 :             :          *
    2642                 :             :          * when testing for an xid, we MUST test for equality only, since
    2643                 :             :          * transactions are numbered in the order they start, not the order
    2644                 :             :          * they complete. A higher numbered xid will complete before you about
    2645                 :             :          * 50% of the time...
    2646                 :             :          */
    2647                 :           0 :         stopsHere = (recordXid == recoveryTargetXid);
    2648                 :             :     }
    2649                 :             : 
    2650                 :             :     /*
    2651                 :             :      * Note: we must fetch recordXtime regardless of recoveryTarget setting.
    2652                 :             :      * We don't expect getRecordTimestamp ever to fail, since we already know
    2653                 :             :      * this is a commit or abort record; but test its result anyway.
    2654                 :             :      */
    2655         [ +  - ]:       23945 :     if (getRecordTimestamp(record, &recordXtime) &&
    2656         [ -  + ]:       23945 :         recoveryTarget == RECOVERY_TARGET_TIME)
    2657                 :             :     {
    2658                 :             :         /*
    2659                 :             :          * There can be many transactions that share the same commit time, so
    2660                 :             :          * we stop after the last one, if we are inclusive, or stop at the
    2661                 :             :          * first one if we are exclusive
    2662                 :             :          */
    2663         [ #  # ]:           0 :         if (recoveryTargetInclusive)
    2664                 :           0 :             stopsHere = (recordXtime > recoveryTargetTime);
    2665                 :             :         else
    2666                 :           0 :             stopsHere = (recordXtime >= recoveryTargetTime);
    2667                 :             :     }
    2668                 :             : 
    2669         [ -  + ]:       23945 :     if (stopsHere)
    2670                 :             :     {
    2671                 :           0 :         recoveryStopAfter = false;
    2672                 :           0 :         recoveryStopXid = recordXid;
    2673                 :           0 :         recoveryStopTime = recordXtime;
    2674                 :           0 :         recoveryStopLSN = InvalidXLogRecPtr;
    2675                 :           0 :         recoveryStopName[0] = '\0';
    2676                 :             : 
    2677         [ #  # ]:           0 :         if (isCommit)
    2678                 :             :         {
    2679         [ #  # ]:           0 :             ereport(LOG,
    2680                 :             :                     (errmsg("recovery stopping before commit of transaction %u, time %s",
    2681                 :             :                             recoveryStopXid,
    2682                 :             :                             timestamptz_to_str(recoveryStopTime))));
    2683                 :             :         }
    2684                 :             :         else
    2685                 :             :         {
    2686         [ #  # ]:           0 :             ereport(LOG,
    2687                 :             :                     (errmsg("recovery stopping before abort of transaction %u, time %s",
    2688                 :             :                             recoveryStopXid,
    2689                 :             :                             timestamptz_to_str(recoveryStopTime))));
    2690                 :             :         }
    2691                 :             :     }
    2692                 :             : 
    2693                 :       23945 :     return stopsHere;
    2694                 :             : }
    2695                 :             : 
    2696                 :             : /*
    2697                 :             :  * Same as recoveryStopsBefore, but called after applying the record.
    2698                 :             :  *
    2699                 :             :  * We also track the timestamp of the latest applied COMMIT/ABORT
    2700                 :             :  * record in XLogRecoveryCtl->recoveryLastXTime.
    2701                 :             :  */
    2702                 :             : static bool
    2703                 :     2964625 : recoveryStopsAfter(XLogReaderState *record)
    2704                 :             : {
    2705                 :             :     uint8       info;
    2706                 :             :     uint8       xact_info;
    2707                 :             :     uint8       rmid;
    2708                 :     2964625 :     TimestampTz recordXtime = 0;
    2709                 :             : 
    2710                 :             :     /*
    2711                 :             :      * Ignore recovery target settings when not in archive recovery (meaning
    2712                 :             :      * we are in crash recovery).
    2713                 :             :      */
    2714         [ +  + ]:     2964625 :     if (!ArchiveRecoveryRequested)
    2715                 :      307813 :         return false;
    2716                 :             : 
    2717                 :     2656812 :     info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
    2718                 :     2656812 :     rmid = XLogRecGetRmid(record);
    2719                 :             : 
    2720                 :             :     /*
    2721                 :             :      * There can be many restore points that share the same name; we stop at
    2722                 :             :      * the first one.
    2723                 :             :      */
    2724   [ +  +  +  + ]:     2656812 :     if (recoveryTarget == RECOVERY_TARGET_NAME &&
    2725         [ +  + ]:          20 :         rmid == RM_XLOG_ID && info == XLOG_RESTORE_POINT)
    2726                 :             :     {
    2727                 :             :         xl_restore_point *recordRestorePointData;
    2728                 :             : 
    2729                 :           3 :         recordRestorePointData = (xl_restore_point *) XLogRecGetData(record);
    2730                 :             : 
    2731         [ +  + ]:           3 :         if (strcmp(recordRestorePointData->rp_name, recoveryTargetName) == 0)
    2732                 :             :         {
    2733                 :           2 :             recoveryStopAfter = true;
    2734                 :           2 :             recoveryStopXid = InvalidTransactionId;
    2735                 :           2 :             recoveryStopLSN = InvalidXLogRecPtr;
    2736                 :           2 :             (void) getRecordTimestamp(record, &recoveryStopTime);
    2737                 :           2 :             strlcpy(recoveryStopName, recordRestorePointData->rp_name, MAXFNAMELEN);
    2738                 :             : 
    2739         [ +  - ]:           2 :             ereport(LOG,
    2740                 :             :                     (errmsg("recovery stopping at restore point \"%s\", time %s",
    2741                 :             :                             recoveryStopName,
    2742                 :             :                             timestamptz_to_str(recoveryStopTime))));
    2743                 :           2 :             return true;
    2744                 :             :         }
    2745                 :             :     }
    2746                 :             : 
    2747                 :             :     /* Check if the target LSN has been reached */
    2748   [ +  +  +  + ]:     2656810 :     if (recoveryTarget == RECOVERY_TARGET_LSN &&
    2749                 :        8072 :         recoveryTargetInclusive &&
    2750         [ +  + ]:        8072 :         record->ReadRecPtr >= recoveryTargetLSN)
    2751                 :             :     {
    2752                 :           3 :         recoveryStopAfter = true;
    2753                 :           3 :         recoveryStopXid = InvalidTransactionId;
    2754                 :           3 :         recoveryStopLSN = record->ReadRecPtr;
    2755                 :           3 :         recoveryStopTime = 0;
    2756                 :           3 :         recoveryStopName[0] = '\0';
    2757         [ +  - ]:           3 :         ereport(LOG,
    2758                 :             :                 errmsg("recovery stopping after WAL location (LSN) \"%X/%08X\"",
    2759                 :             :                        LSN_FORMAT_ARGS(recoveryStopLSN)));
    2760                 :           3 :         return true;
    2761                 :             :     }
    2762                 :             : 
    2763         [ +  + ]:     2656807 :     if (rmid != RM_XACT_ID)
    2764                 :     2632545 :         return false;
    2765                 :             : 
    2766                 :       24262 :     xact_info = info & XLOG_XACT_OPMASK;
    2767                 :             : 
    2768   [ +  +  +  + ]:       24262 :     if (xact_info == XLOG_XACT_COMMIT ||
    2769         [ +  + ]:        2337 :         xact_info == XLOG_XACT_COMMIT_PREPARED ||
    2770         [ +  + ]:         334 :         xact_info == XLOG_XACT_ABORT ||
    2771                 :             :         xact_info == XLOG_XACT_ABORT_PREPARED)
    2772                 :             :     {
    2773                 :             :         TransactionId recordXid;
    2774                 :             : 
    2775                 :             :         /* Update the last applied transaction timestamp */
    2776         [ +  - ]:       23943 :         if (getRecordTimestamp(record, &recordXtime))
    2777                 :       23943 :             SetLatestXTime(recordXtime);
    2778                 :             : 
    2779                 :             :         /* Extract the XID of the committed/aborted transaction */
    2780         [ +  + ]:       23943 :         if (xact_info == XLOG_XACT_COMMIT_PREPARED)
    2781                 :             :         {
    2782                 :          26 :             xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
    2783                 :             :             xl_xact_parsed_commit parsed;
    2784                 :             : 
    2785                 :          26 :             ParseCommitRecord(XLogRecGetInfo(record),
    2786                 :             :                               xlrec,
    2787                 :             :                               &parsed);
    2788                 :          26 :             recordXid = parsed.twophase_xid;
    2789                 :             :         }
    2790         [ +  + ]:       23917 :         else if (xact_info == XLOG_XACT_ABORT_PREPARED)
    2791                 :             :         {
    2792                 :          15 :             xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
    2793                 :             :             xl_xact_parsed_abort parsed;
    2794                 :             : 
    2795                 :          15 :             ParseAbortRecord(XLogRecGetInfo(record),
    2796                 :             :                              xlrec,
    2797                 :             :                              &parsed);
    2798                 :          15 :             recordXid = parsed.twophase_xid;
    2799                 :             :         }
    2800                 :             :         else
    2801                 :       23902 :             recordXid = XLogRecGetXid(record);
    2802                 :             : 
    2803                 :             :         /*
    2804                 :             :          * There can be only one transaction end record with this exact
    2805                 :             :          * transactionid
    2806                 :             :          *
    2807                 :             :          * when testing for an xid, we MUST test for equality only, since
    2808                 :             :          * transactions are numbered in the order they start, not the order
    2809                 :             :          * they complete. A higher numbered xid will complete before you about
    2810                 :             :          * 50% of the time...
    2811                 :             :          */
    2812   [ -  +  -  - ]:       23943 :         if (recoveryTarget == RECOVERY_TARGET_XID && recoveryTargetInclusive &&
    2813         [ #  # ]:           0 :             recordXid == recoveryTargetXid)
    2814                 :             :         {
    2815                 :           0 :             recoveryStopAfter = true;
    2816                 :           0 :             recoveryStopXid = recordXid;
    2817                 :           0 :             recoveryStopTime = recordXtime;
    2818                 :           0 :             recoveryStopLSN = InvalidXLogRecPtr;
    2819                 :           0 :             recoveryStopName[0] = '\0';
    2820                 :             : 
    2821   [ #  #  #  # ]:           0 :             if (xact_info == XLOG_XACT_COMMIT ||
    2822                 :             :                 xact_info == XLOG_XACT_COMMIT_PREPARED)
    2823                 :             :             {
    2824         [ #  # ]:           0 :                 ereport(LOG,
    2825                 :             :                         (errmsg("recovery stopping after commit of transaction %u, time %s",
    2826                 :             :                                 recoveryStopXid,
    2827                 :             :                                 timestamptz_to_str(recoveryStopTime))));
    2828                 :             :             }
    2829   [ #  #  #  # ]:           0 :             else if (xact_info == XLOG_XACT_ABORT ||
    2830                 :             :                      xact_info == XLOG_XACT_ABORT_PREPARED)
    2831                 :             :             {
    2832         [ #  # ]:           0 :                 ereport(LOG,
    2833                 :             :                         (errmsg("recovery stopping after abort of transaction %u, time %s",
    2834                 :             :                                 recoveryStopXid,
    2835                 :             :                                 timestamptz_to_str(recoveryStopTime))));
    2836                 :             :             }
    2837                 :           0 :             return true;
    2838                 :             :         }
    2839                 :             :     }
    2840                 :             : 
    2841                 :             :     /* Check if we should stop as soon as reaching consistency */
    2842   [ -  +  -  - ]:       24262 :     if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE && reachedConsistency)
    2843                 :             :     {
    2844         [ #  # ]:           0 :         ereport(LOG,
    2845                 :             :                 (errmsg("recovery stopping after reaching consistency")));
    2846                 :             : 
    2847                 :           0 :         recoveryStopAfter = true;
    2848                 :           0 :         recoveryStopXid = InvalidTransactionId;
    2849                 :           0 :         recoveryStopTime = 0;
    2850                 :           0 :         recoveryStopLSN = InvalidXLogRecPtr;
    2851                 :           0 :         recoveryStopName[0] = '\0';
    2852                 :           0 :         return true;
    2853                 :             :     }
    2854                 :             : 
    2855                 :       24262 :     return false;
    2856                 :             : }
    2857                 :             : 
    2858                 :             : /*
    2859                 :             :  * Create a comment for the history file to explain why and where
    2860                 :             :  * timeline changed.
    2861                 :             :  */
    2862                 :             : static char *
    2863                 :        1019 : getRecoveryStopReason(void)
    2864                 :             : {
    2865                 :             :     char        reason[200];
    2866                 :             : 
    2867         [ -  + ]:        1019 :     if (recoveryTarget == RECOVERY_TARGET_XID)
    2868                 :           0 :         snprintf(reason, sizeof(reason),
    2869                 :             :                  "%s transaction %u",
    2870         [ #  # ]:           0 :                  recoveryStopAfter ? "after" : "before",
    2871                 :             :                  recoveryStopXid);
    2872         [ -  + ]:        1019 :     else if (recoveryTarget == RECOVERY_TARGET_TIME)
    2873                 :           0 :         snprintf(reason, sizeof(reason),
    2874                 :             :                  "%s %s\n",
    2875         [ #  # ]:           0 :                  recoveryStopAfter ? "after" : "before",
    2876                 :             :                  timestamptz_to_str(recoveryStopTime));
    2877         [ +  + ]:        1019 :     else if (recoveryTarget == RECOVERY_TARGET_LSN)
    2878                 :           6 :         snprintf(reason, sizeof(reason),
    2879                 :             :                  "%s LSN %X/%08X\n",
    2880                 :           6 :                  recoveryStopAfter ? "after" : "before",
    2881         [ +  + ]:           6 :                  LSN_FORMAT_ARGS(recoveryStopLSN));
    2882         [ +  + ]:        1013 :     else if (recoveryTarget == RECOVERY_TARGET_NAME)
    2883                 :           3 :         snprintf(reason, sizeof(reason),
    2884                 :             :                  "at restore point \"%s\"",
    2885                 :             :                  recoveryStopName);
    2886         [ -  + ]:        1010 :     else if (recoveryTarget == RECOVERY_TARGET_IMMEDIATE)
    2887                 :           0 :         snprintf(reason, sizeof(reason), "reached consistency");
    2888                 :             :     else
    2889                 :        1010 :         snprintf(reason, sizeof(reason), "no recovery target specified");
    2890                 :             : 
    2891                 :        1019 :     return pstrdup(reason);
    2892                 :             : }
    2893                 :             : 
    2894                 :             : /*
    2895                 :             :  * Wait until shared recoveryPauseState is set to RECOVERY_NOT_PAUSED.
    2896                 :             :  *
    2897                 :             :  * endOfRecovery is true if the recovery target is reached and
    2898                 :             :  * the paused state starts at the end of recovery because of
    2899                 :             :  * recovery_target_action=pause, and false otherwise.
    2900                 :             :  */
    2901                 :             : static void
    2902                 :           9 : recoveryPausesHere(bool endOfRecovery)
    2903                 :             : {
    2904                 :             :     /* Don't pause unless users can connect! */
    2905         [ -  + ]:           9 :     if (!LocalHotStandbyActive)
    2906                 :           0 :         return;
    2907                 :             : 
    2908                 :             :     /* Don't pause after standby promotion has been triggered */
    2909         [ -  + ]:           9 :     if (LocalPromoteIsTriggered)
    2910                 :           0 :         return;
    2911                 :             : 
    2912         [ +  + ]:           9 :     if (endOfRecovery)
    2913         [ +  - ]:           1 :         ereport(LOG,
    2914                 :             :                 (errmsg("pausing at the end of recovery"),
    2915                 :             :                  errhint("Execute pg_wal_replay_resume() to promote.")));
    2916                 :             :     else
    2917         [ +  - ]:           8 :         ereport(LOG,
    2918                 :             :                 (errmsg("recovery has paused"),
    2919                 :             :                  errhint("Execute pg_wal_replay_resume() to continue.")));
    2920                 :             : 
    2921                 :             :     /* loop until recoveryPauseState is set to RECOVERY_NOT_PAUSED */
    2922         [ +  + ]:          28 :     while (GetRecoveryPauseState() != RECOVERY_NOT_PAUSED)
    2923                 :             :     {
    2924                 :          21 :         ProcessStartupProcInterrupts();
    2925         [ +  + ]:          21 :         if (CheckForStandbyTrigger())
    2926                 :           2 :             return;
    2927                 :             : 
    2928                 :             :         /*
    2929                 :             :          * If recovery pause is requested then set it paused.  While we are in
    2930                 :             :          * the loop, user might resume and pause again so set this every time.
    2931                 :             :          */
    2932                 :          19 :         ConfirmRecoveryPaused();
    2933                 :             : 
    2934                 :             :         /*
    2935                 :             :          * We wait on a condition variable that will wake us as soon as the
    2936                 :             :          * pause ends, but we use a timeout so we can check the above exit
    2937                 :             :          * condition periodically too.
    2938                 :             :          */
    2939                 :          19 :         ConditionVariableTimedSleep(&XLogRecoveryCtl->recoveryNotPausedCV, 1000,
    2940                 :             :                                     WAIT_EVENT_RECOVERY_PAUSE);
    2941                 :             :     }
    2942                 :           7 :     ConditionVariableCancelSleep();
    2943                 :             : }
    2944                 :             : 
    2945                 :             : /*
    2946                 :             :  * When recovery_min_apply_delay is set, we wait long enough to make sure
    2947                 :             :  * certain record types are applied at least that interval behind the primary.
    2948                 :             :  *
    2949                 :             :  * Returns true if we waited.
    2950                 :             :  *
    2951                 :             :  * Note that the delay is calculated between the WAL record log time and
    2952                 :             :  * the current time on standby. We would prefer to keep track of when this
    2953                 :             :  * standby received each WAL record, which would allow a more consistent
    2954                 :             :  * approach and one not affected by time synchronisation issues, but that
    2955                 :             :  * is significantly more effort and complexity for little actual gain in
    2956                 :             :  * usability.
    2957                 :             :  */
    2958                 :             : static bool
    2959                 :     2964627 : recoveryApplyDelay(XLogReaderState *record)
    2960                 :             : {
    2961                 :             :     uint8       xact_info;
    2962                 :             :     TimestampTz xtime;
    2963                 :             :     TimestampTz delayUntil;
    2964                 :             :     long        msecs;
    2965                 :             : 
    2966                 :             :     /* nothing to do if no delay configured */
    2967         [ +  + ]:     2964627 :     if (recovery_min_apply_delay <= 0)
    2968                 :     2964473 :         return false;
    2969                 :             : 
    2970                 :             :     /* no delay is applied on a database not yet consistent */
    2971         [ +  + ]:         154 :     if (!reachedConsistency)
    2972                 :           4 :         return false;
    2973                 :             : 
    2974                 :             :     /* nothing to do if crash recovery is requested */
    2975         [ -  + ]:         150 :     if (!ArchiveRecoveryRequested)
    2976                 :           0 :         return false;
    2977                 :             : 
    2978                 :             :     /*
    2979                 :             :      * Is it a COMMIT record?
    2980                 :             :      *
    2981                 :             :      * We deliberately choose not to delay aborts since they have no effect on
    2982                 :             :      * MVCC. We already allow replay of records that don't have a timestamp,
    2983                 :             :      * so there is already opportunity for issues caused by early conflicts on
    2984                 :             :      * standbys.
    2985                 :             :      */
    2986         [ +  + ]:         150 :     if (XLogRecGetRmid(record) != RM_XACT_ID)
    2987                 :         120 :         return false;
    2988                 :             : 
    2989                 :          30 :     xact_info = XLogRecGetInfo(record) & XLOG_XACT_OPMASK;
    2990                 :             : 
    2991   [ -  +  -  - ]:          30 :     if (xact_info != XLOG_XACT_COMMIT &&
    2992                 :             :         xact_info != XLOG_XACT_COMMIT_PREPARED)
    2993                 :           0 :         return false;
    2994                 :             : 
    2995         [ -  + ]:          30 :     if (!getRecordTimestamp(record, &xtime))
    2996                 :           0 :         return false;
    2997                 :             : 
    2998                 :          30 :     delayUntil = TimestampTzPlusMilliseconds(xtime, recovery_min_apply_delay);
    2999                 :             : 
    3000                 :             :     /*
    3001                 :             :      * Exit without arming the latch if it's already past time to apply this
    3002                 :             :      * record
    3003                 :             :      */
    3004                 :          30 :     msecs = TimestampDifferenceMilliseconds(GetCurrentTimestamp(), delayUntil);
    3005         [ +  + ]:          30 :     if (msecs <= 0)
    3006                 :           9 :         return false;
    3007                 :             : 
    3008                 :             :     while (true)
    3009                 :             :     {
    3010                 :          82 :         ResetLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
    3011                 :             : 
    3012                 :             :         /* This might change recovery_min_apply_delay. */
    3013                 :          82 :         ProcessStartupProcInterrupts();
    3014                 :             : 
    3015         [ -  + ]:          82 :         if (CheckForStandbyTrigger())
    3016                 :           0 :             break;
    3017                 :             : 
    3018                 :             :         /*
    3019                 :             :          * Recalculate delayUntil as recovery_min_apply_delay could have
    3020                 :             :          * changed while waiting in this loop.
    3021                 :             :          */
    3022                 :          82 :         delayUntil = TimestampTzPlusMilliseconds(xtime, recovery_min_apply_delay);
    3023                 :             : 
    3024                 :             :         /*
    3025                 :             :          * Wait for difference between GetCurrentTimestamp() and delayUntil.
    3026                 :             :          */
    3027                 :          82 :         msecs = TimestampDifferenceMilliseconds(GetCurrentTimestamp(),
    3028                 :             :                                                 delayUntil);
    3029                 :             : 
    3030         [ +  + ]:          82 :         if (msecs <= 0)
    3031                 :          21 :             break;
    3032                 :             : 
    3033         [ -  + ]:          61 :         elog(DEBUG2, "recovery apply delay %ld milliseconds", msecs);
    3034                 :             : 
    3035                 :          61 :         (void) WaitLatch(&XLogRecoveryCtl->recoveryWakeupLatch,
    3036                 :             :                          WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
    3037                 :             :                          msecs,
    3038                 :             :                          WAIT_EVENT_RECOVERY_APPLY_DELAY);
    3039                 :             :     }
    3040                 :          21 :     return true;
    3041                 :             : }
    3042                 :             : 
    3043                 :             : /*
    3044                 :             :  * Get the current state of the recovery pause request.
    3045                 :             :  */
    3046                 :             : RecoveryPauseState
    3047                 :          37 : GetRecoveryPauseState(void)
    3048                 :             : {
    3049                 :             :     RecoveryPauseState state;
    3050                 :             : 
    3051                 :          37 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    3052                 :          37 :     state = XLogRecoveryCtl->recoveryPauseState;
    3053                 :          37 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    3054                 :             : 
    3055                 :          37 :     return state;
    3056                 :             : }
    3057                 :             : 
    3058                 :             : /*
    3059                 :             :  * Set the recovery pause state.
    3060                 :             :  *
    3061                 :             :  * If recovery pause is requested then sets the recovery pause state to
    3062                 :             :  * 'pause requested' if it is not already 'paused'.  Otherwise, sets it
    3063                 :             :  * to 'not paused' to resume the recovery.  The recovery pause will be
    3064                 :             :  * confirmed by the ConfirmRecoveryPaused.
    3065                 :             :  */
    3066                 :             : void
    3067                 :          69 : SetRecoveryPause(bool recoveryPause)
    3068                 :             : {
    3069                 :          69 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    3070                 :             : 
    3071         [ +  + ]:          69 :     if (!recoveryPause)
    3072                 :          60 :         XLogRecoveryCtl->recoveryPauseState = RECOVERY_NOT_PAUSED;
    3073         [ +  - ]:           9 :     else if (XLogRecoveryCtl->recoveryPauseState == RECOVERY_NOT_PAUSED)
    3074                 :           9 :         XLogRecoveryCtl->recoveryPauseState = RECOVERY_PAUSE_REQUESTED;
    3075                 :             : 
    3076                 :          69 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    3077                 :             : 
    3078         [ +  + ]:          69 :     if (!recoveryPause)
    3079                 :          60 :         ConditionVariableBroadcast(&XLogRecoveryCtl->recoveryNotPausedCV);
    3080                 :          69 : }
    3081                 :             : 
    3082                 :             : /*
    3083                 :             :  * Confirm the recovery pause by setting the recovery pause state to
    3084                 :             :  * RECOVERY_PAUSED.
    3085                 :             :  */
    3086                 :             : static void
    3087                 :          19 : ConfirmRecoveryPaused(void)
    3088                 :             : {
    3089                 :             :     /* If recovery pause is requested then set it paused */
    3090                 :          19 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    3091         [ +  + ]:          19 :     if (XLogRecoveryCtl->recoveryPauseState == RECOVERY_PAUSE_REQUESTED)
    3092                 :           9 :         XLogRecoveryCtl->recoveryPauseState = RECOVERY_PAUSED;
    3093                 :          19 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    3094                 :          19 : }
    3095                 :             : 
    3096                 :             : 
    3097                 :             : /*
    3098                 :             :  * Attempt to read the next XLOG record.
    3099                 :             :  *
    3100                 :             :  * Before first call, the reader needs to be positioned to the first record
    3101                 :             :  * by calling XLogPrefetcherBeginRead().
    3102                 :             :  *
    3103                 :             :  * If no valid record is available, returns NULL, or fails if emode is PANIC.
    3104                 :             :  * (emode must be either PANIC, LOG). In standby mode, retries until a valid
    3105                 :             :  * record is available.
    3106                 :             :  */
    3107                 :             : static XLogRecord *
    3108                 :     2967096 : ReadRecord(XLogPrefetcher *xlogprefetcher, int emode,
    3109                 :             :            bool fetching_ckpt, TimeLineID replayTLI)
    3110                 :             : {
    3111                 :             :     XLogRecord *record;
    3112                 :     2967096 :     XLogReaderState *xlogreader = XLogPrefetcherGetReader(xlogprefetcher);
    3113                 :     2967096 :     XLogPageReadPrivate *private = (XLogPageReadPrivate *) xlogreader->private_data;
    3114                 :             : 
    3115                 :             :     Assert(AmStartupProcess() || !IsUnderPostmaster);
    3116                 :             : 
    3117                 :             :     /* Pass through parameters to XLogPageRead */
    3118                 :     2967096 :     private->fetching_ckpt = fetching_ckpt;
    3119                 :     2967096 :     private->emode = emode;
    3120                 :     2967096 :     private->randAccess = !XLogRecPtrIsValid(xlogreader->ReadRecPtr);
    3121                 :     2967096 :     private->replayTLI = replayTLI;
    3122                 :             : 
    3123                 :             :     /* This is the first attempt to read this page. */
    3124                 :     2967096 :     lastSourceFailed = false;
    3125                 :             : 
    3126                 :             :     for (;;)
    3127                 :         168 :     {
    3128                 :             :         char       *errormsg;
    3129                 :             : 
    3130                 :     2967264 :         record = XLogPrefetcherReadRecord(xlogprefetcher, &errormsg);
    3131         [ +  + ]:     2967201 :         if (record == NULL)
    3132                 :             :         {
    3133                 :             :             /*
    3134                 :             :              * When we find that WAL ends in an incomplete record, keep track
    3135                 :             :              * of that record.  After recovery is done, we'll write a record
    3136                 :             :              * to indicate to downstream WAL readers that that portion is to
    3137                 :             :              * be ignored.
    3138                 :             :              *
    3139                 :             :              * However, when ArchiveRecoveryRequested = true, we're going to
    3140                 :             :              * switch to a new timeline at the end of recovery. We will only
    3141                 :             :              * copy WAL over to the new timeline up to the end of the last
    3142                 :             :              * complete record, so if we did this, we would later create an
    3143                 :             :              * overwrite contrecord in the wrong place, breaking everything.
    3144                 :             :              */
    3145         [ +  + ]:         332 :             if (!ArchiveRecoveryRequested &&
    3146         [ +  + ]:         110 :                 XLogRecPtrIsValid(xlogreader->abortedRecPtr))
    3147                 :             :             {
    3148                 :          11 :                 abortedRecPtr = xlogreader->abortedRecPtr;
    3149                 :          11 :                 missingContrecPtr = xlogreader->missingContrecPtr;
    3150                 :             :             }
    3151                 :             : 
    3152         [ +  + ]:         332 :             if (readFile >= 0)
    3153                 :             :             {
    3154                 :         305 :                 close(readFile);
    3155                 :         305 :                 readFile = -1;
    3156                 :             :             }
    3157                 :             : 
    3158                 :             :             /*
    3159                 :             :              * We only end up here without a message when XLogPageRead()
    3160                 :             :              * failed - in that case we already logged something. In
    3161                 :             :              * StandbyMode that only happens if we have been triggered, so we
    3162                 :             :              * shouldn't loop anymore in that case.
    3163                 :             :              */
    3164         [ +  + ]:         332 :             if (errormsg)
    3165         [ +  + ]:         305 :                 ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
    3166                 :             :                         (errmsg_internal("%s", errormsg) /* already translated */ ));
    3167                 :             :         }
    3168                 :             : 
    3169                 :             :         /*
    3170                 :             :          * Check page TLI is one of the expected values.
    3171                 :             :          */
    3172         [ -  + ]:     2966869 :         else if (!tliInHistory(xlogreader->latestPageTLI, expectedTLEs))
    3173                 :             :         {
    3174                 :             :             char        fname[MAXFNAMELEN];
    3175                 :             :             XLogSegNo   segno;
    3176                 :             :             int32       offset;
    3177                 :             : 
    3178                 :           0 :             XLByteToSeg(xlogreader->latestPagePtr, segno, wal_segment_size);
    3179                 :           0 :             offset = XLogSegmentOffset(xlogreader->latestPagePtr,
    3180                 :             :                                        wal_segment_size);
    3181                 :           0 :             XLogFileName(fname, xlogreader->seg.ws_tli, segno,
    3182                 :             :                          wal_segment_size);
    3183         [ #  # ]:           0 :             ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
    3184                 :             :                     errmsg("unexpected timeline ID %u in WAL segment %s, LSN %X/%08X, offset %u",
    3185                 :             :                            xlogreader->latestPageTLI,
    3186                 :             :                            fname,
    3187                 :             :                            LSN_FORMAT_ARGS(xlogreader->latestPagePtr),
    3188                 :             :                            offset));
    3189                 :           0 :             record = NULL;
    3190                 :             :         }
    3191                 :             : 
    3192         [ +  + ]:     2967201 :         if (record)
    3193                 :             :         {
    3194                 :             :             /* Great, got a record */
    3195                 :     2967033 :             return record;
    3196                 :             :         }
    3197                 :             :         else
    3198                 :             :         {
    3199                 :             :             /* No valid record available from this source */
    3200                 :         332 :             lastSourceFailed = true;
    3201                 :             : 
    3202                 :             :             /*
    3203                 :             :              * If archive recovery was requested, but we were still doing
    3204                 :             :              * crash recovery, switch to archive recovery and retry using the
    3205                 :             :              * offline archive. We have now replayed all the valid WAL in
    3206                 :             :              * pg_wal, so we are presumably now consistent.
    3207                 :             :              *
    3208                 :             :              * We require that there's at least some valid WAL present in
    3209                 :             :              * pg_wal, however (!fetching_ckpt).  We could recover using the
    3210                 :             :              * WAL from the archive, even if pg_wal is completely empty, but
    3211                 :             :              * we'd have no idea how far we'd have to replay to reach
    3212                 :             :              * consistency.  So err on the safe side and give up.
    3213                 :             :              */
    3214   [ +  +  +  + ]:         332 :             if (!InArchiveRecovery && ArchiveRecoveryRequested &&
    3215         [ +  - ]:           1 :                 !fetching_ckpt)
    3216                 :             :             {
    3217         [ -  + ]:           1 :                 ereport(DEBUG1,
    3218                 :             :                         (errmsg_internal("reached end of WAL in pg_wal, entering archive recovery")));
    3219                 :           1 :                 InArchiveRecovery = true;
    3220         [ +  - ]:           1 :                 if (StandbyModeRequested)
    3221                 :           1 :                     EnableStandbyMode();
    3222                 :             : 
    3223                 :           1 :                 SwitchIntoArchiveRecovery(xlogreader->EndRecPtr, replayTLI);
    3224                 :           1 :                 minRecoveryPoint = xlogreader->EndRecPtr;
    3225                 :           1 :                 minRecoveryPointTLI = replayTLI;
    3226                 :             : 
    3227                 :           1 :                 CheckRecoveryConsistency();
    3228                 :             : 
    3229                 :             :                 /*
    3230                 :             :                  * Before we retry, reset lastSourceFailed and currentSource
    3231                 :             :                  * so that we will check the archive next.
    3232                 :             :                  */
    3233                 :           1 :                 lastSourceFailed = false;
    3234                 :           1 :                 currentSource = XLOG_FROM_ANY;
    3235                 :             : 
    3236                 :         168 :                 continue;
    3237                 :             :             }
    3238                 :             : 
    3239                 :             :             /* In standby mode, loop back to retry. Otherwise, give up. */
    3240   [ +  +  +  + ]:         331 :             if (StandbyMode && !CheckForStandbyTrigger())
    3241                 :         167 :                 continue;
    3242                 :             :             else
    3243                 :         164 :                 return NULL;
    3244                 :             :         }
    3245                 :             :     }
    3246                 :             : }
    3247                 :             : 
    3248                 :             : /*
    3249                 :             :  * Read the XLOG page containing targetPagePtr into readBuf (if not read
    3250                 :             :  * already).  Returns number of bytes read, if the page is read successfully,
    3251                 :             :  * or XLREAD_FAIL in case of errors.  When errors occur, they are ereport'ed,
    3252                 :             :  * but only if they have not been previously reported.
    3253                 :             :  *
    3254                 :             :  * See XLogReaderRoutine.page_read for more details.
    3255                 :             :  *
    3256                 :             :  * While prefetching, xlogreader->nonblocking may be set.  In that case,
    3257                 :             :  * returns XLREAD_WOULDBLOCK if we'd otherwise have to wait for more WAL.
    3258                 :             :  *
    3259                 :             :  * This is responsible for restoring files from archive as needed, as well
    3260                 :             :  * as for waiting for the requested WAL record to arrive in standby mode.
    3261                 :             :  *
    3262                 :             :  * xlogreader->private_data->emode specifies the log level used for reporting
    3263                 :             :  * "file not found" or "end of WAL" situations in archive recovery, or in
    3264                 :             :  * standby mode when promotion is triggered. If set to WARNING or below,
    3265                 :             :  * XLogPageRead() returns XLREAD_FAIL in those situations, on higher log
    3266                 :             :  * levels the ereport() won't return.
    3267                 :             :  *
    3268                 :             :  * In standby mode, if after a successful return of XLogPageRead() the
    3269                 :             :  * caller finds the record it's interested in to be broken, it should
    3270                 :             :  * ereport the error with the level determined by
    3271                 :             :  * emode_for_corrupt_record(), and then set lastSourceFailed
    3272                 :             :  * and call XLogPageRead() again with the same arguments. This lets
    3273                 :             :  * XLogPageRead() to try fetching the record from another source, or to
    3274                 :             :  * sleep and retry.
    3275                 :             :  */
    3276                 :             : static int
    3277                 :     1519693 : XLogPageRead(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen,
    3278                 :             :              XLogRecPtr targetRecPtr, char *readBuf)
    3279                 :             : {
    3280                 :     1519693 :     XLogPageReadPrivate *private =
    3281                 :             :         (XLogPageReadPrivate *) xlogreader->private_data;
    3282                 :     1519693 :     int         emode = private->emode;
    3283                 :             :     uint32      targetPageOff;
    3284                 :             :     XLogSegNo   targetSegNo PG_USED_FOR_ASSERTS_ONLY;
    3285                 :             :     int         r;
    3286                 :             :     instr_time  io_start;
    3287                 :             : 
    3288                 :             :     Assert(AmStartupProcess() || !IsUnderPostmaster);
    3289                 :             : 
    3290                 :     1519693 :     XLByteToSeg(targetPagePtr, targetSegNo, wal_segment_size);
    3291                 :     1519693 :     targetPageOff = XLogSegmentOffset(targetPagePtr, wal_segment_size);
    3292                 :             : 
    3293                 :             :     /*
    3294                 :             :      * See if we need to switch to a new segment because the requested record
    3295                 :             :      * is not in the currently open one.
    3296                 :             :      */
    3297         [ +  + ]:     1519693 :     if (readFile >= 0 &&
    3298         [ +  + ]:     1517855 :         !XLByteInSeg(targetPagePtr, readSegNo, wal_segment_size))
    3299                 :             :     {
    3300                 :             :         /*
    3301                 :             :          * Request a restartpoint if we've replayed too much xlog since the
    3302                 :             :          * last one.
    3303                 :             :          */
    3304   [ +  +  +  - ]:        1475 :         if (ArchiveRecoveryRequested && IsUnderPostmaster)
    3305                 :             :         {
    3306         [ +  + ]:        1458 :             if (XLogCheckpointNeeded(readSegNo))
    3307                 :             :             {
    3308                 :        1315 :                 (void) GetRedoRecPtr();
    3309         [ +  + ]:        1315 :                 if (XLogCheckpointNeeded(readSegNo))
    3310                 :        1305 :                     RequestCheckpoint(CHECKPOINT_CAUSE_XLOG);
    3311                 :             :             }
    3312                 :             :         }
    3313                 :             : 
    3314                 :        1475 :         close(readFile);
    3315                 :        1475 :         readFile = -1;
    3316                 :        1475 :         readSource = XLOG_FROM_ANY;
    3317                 :             :     }
    3318                 :             : 
    3319                 :     1519693 :     XLByteToSeg(targetPagePtr, readSegNo, wal_segment_size);
    3320                 :             : 
    3321                 :     1519697 : retry:
    3322                 :             :     /* See if we need to retrieve more data */
    3323         [ +  + ]:     1519697 :     if (readFile < 0 ||
    3324         [ +  + ]:     1516380 :         (readSource == XLOG_FROM_STREAM &&
    3325         [ +  + ]:     1503268 :          flushedUpto < targetPagePtr + reqLen))
    3326                 :             :     {
    3327         [ +  + ]:       29234 :         if (readFile >= 0 &&
    3328         [ +  + ]:       25917 :             xlogreader->nonblocking &&
    3329         [ +  - ]:       12807 :             readSource == XLOG_FROM_STREAM &&
    3330         [ +  - ]:       12807 :             flushedUpto < targetPagePtr + reqLen)
    3331                 :       12807 :             return XLREAD_WOULDBLOCK;
    3332                 :             : 
    3333   [ +  +  +  - ]:       16364 :         switch (WaitForWALToBecomeAvailable(targetPagePtr + reqLen,
    3334                 :       16427 :                                             private->randAccess,
    3335                 :       16427 :                                             private->fetching_ckpt,
    3336                 :             :                                             targetRecPtr,
    3337                 :             :                                             private->replayTLI,
    3338                 :             :                                             xlogreader->EndRecPtr,
    3339                 :       16427 :                                             xlogreader->nonblocking))
    3340                 :             :         {
    3341                 :         395 :             case XLREAD_WOULDBLOCK:
    3342                 :         395 :                 return XLREAD_WOULDBLOCK;
    3343                 :          52 :             case XLREAD_FAIL:
    3344         [ -  + ]:          52 :                 if (readFile >= 0)
    3345                 :           0 :                     close(readFile);
    3346                 :          52 :                 readFile = -1;
    3347                 :          52 :                 readLen = 0;
    3348                 :          52 :                 readSource = XLOG_FROM_ANY;
    3349                 :          52 :                 return XLREAD_FAIL;
    3350                 :       15917 :             case XLREAD_SUCCESS:
    3351                 :       15917 :                 break;
    3352                 :             :         }
    3353                 :             :     }
    3354                 :             : 
    3355                 :             :     /*
    3356                 :             :      * At this point, we have the right segment open and if we're streaming we
    3357                 :             :      * know the requested record is in it.
    3358                 :             :      */
    3359                 :             :     Assert(readFile != -1);
    3360                 :             : 
    3361                 :             :     /*
    3362                 :             :      * If the current segment is being streamed from the primary, calculate
    3363                 :             :      * how much of the current page we have received already. We know the
    3364                 :             :      * requested record has been received, but this is for the benefit of
    3365                 :             :      * future calls, to allow quick exit at the top of this function.
    3366                 :             :      */
    3367         [ +  + ]:     1506380 :     if (readSource == XLOG_FROM_STREAM)
    3368                 :             :     {
    3369         [ +  + ]:     1491494 :         if (((targetPagePtr) / XLOG_BLCKSZ) != (flushedUpto / XLOG_BLCKSZ))
    3370                 :     1482777 :             readLen = XLOG_BLCKSZ;
    3371                 :             :         else
    3372                 :        8717 :             readLen = XLogSegmentOffset(flushedUpto, wal_segment_size) -
    3373                 :             :                 targetPageOff;
    3374                 :             :     }
    3375                 :             :     else
    3376                 :       14886 :         readLen = XLOG_BLCKSZ;
    3377                 :             : 
    3378                 :             :     /* Read the requested page */
    3379                 :     1506380 :     readOff = targetPageOff;
    3380                 :             : 
    3381                 :             :     /* Measure I/O timing when reading segment */
    3382                 :     1506380 :     io_start = pgstat_prepare_io_time(track_wal_io_timing);
    3383                 :             : 
    3384                 :     1506380 :     pgstat_report_wait_start(WAIT_EVENT_WAL_READ);
    3385                 :     1506380 :     r = pg_pread(readFile, readBuf, XLOG_BLCKSZ, (pgoff_t) readOff);
    3386         [ -  + ]:     1506380 :     if (r != XLOG_BLCKSZ)
    3387                 :             :     {
    3388                 :             :         char        fname[MAXFNAMELEN];
    3389                 :           0 :         int         save_errno = errno;
    3390                 :             : 
    3391                 :           0 :         pgstat_report_wait_end();
    3392                 :             : 
    3393                 :             :         /* Count I/O stats only for successful short reads */
    3394         [ #  # ]:           0 :         if (r > 0)
    3395                 :           0 :             pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL, IOOP_READ,
    3396                 :             :                                     io_start, 1, r);
    3397                 :             : 
    3398                 :           0 :         XLogFileName(fname, curFileTLI, readSegNo, wal_segment_size);
    3399         [ #  # ]:           0 :         if (r < 0)
    3400                 :             :         {
    3401                 :           0 :             errno = save_errno;
    3402         [ #  # ]:           0 :             ereport(emode_for_corrupt_record(emode, targetPagePtr + reqLen),
    3403                 :             :                     (errcode_for_file_access(),
    3404                 :             :                      errmsg("could not read from WAL segment %s, LSN %X/%08X, offset %u: %m",
    3405                 :             :                             fname, LSN_FORMAT_ARGS(targetPagePtr),
    3406                 :             :                             readOff)));
    3407                 :             :         }
    3408                 :             :         else
    3409         [ #  # ]:           0 :             ereport(emode_for_corrupt_record(emode, targetPagePtr + reqLen),
    3410                 :             :                     (errcode(ERRCODE_DATA_CORRUPTED),
    3411                 :             :                      errmsg("could not read from WAL segment %s, LSN %X/%08X, offset %u: read %d of %zu",
    3412                 :             :                             fname, LSN_FORMAT_ARGS(targetPagePtr),
    3413                 :             :                             readOff, r, (Size) XLOG_BLCKSZ)));
    3414                 :           0 :         goto next_record_is_invalid;
    3415                 :             :     }
    3416                 :     1506380 :     pgstat_report_wait_end();
    3417                 :             : 
    3418                 :     1506380 :     pgstat_count_io_op_time(IOOBJECT_WAL, IOCONTEXT_NORMAL, IOOP_READ,
    3419                 :             :                             io_start, 1, r);
    3420                 :             : 
    3421                 :             :     Assert(targetSegNo == readSegNo);
    3422                 :             :     Assert(targetPageOff == readOff);
    3423                 :             :     Assert(reqLen <= readLen);
    3424                 :             : 
    3425                 :     1506380 :     xlogreader->seg.ws_tli = curFileTLI;
    3426                 :             : 
    3427                 :             :     /*
    3428                 :             :      * Check the page header immediately, so that we can retry immediately if
    3429                 :             :      * it's not valid. This may seem unnecessary, because ReadPageInternal()
    3430                 :             :      * validates the page header anyway, and would propagate the failure up to
    3431                 :             :      * ReadRecord(), which would retry. However, there's a corner case with
    3432                 :             :      * continuation records, if a record is split across two pages such that
    3433                 :             :      * we would need to read the two pages from different sources across two
    3434                 :             :      * WAL segments.
    3435                 :             :      *
    3436                 :             :      * The first page is only available locally, in pg_wal, because it's
    3437                 :             :      * already been recycled on the primary. The second page, however, is not
    3438                 :             :      * present in pg_wal, and we should stream it from the primary. There is a
    3439                 :             :      * recycled WAL segment present in pg_wal, with garbage contents, however.
    3440                 :             :      * We would read the first page from the local WAL segment, but when
    3441                 :             :      * reading the second page, we would read the bogus, recycled, WAL
    3442                 :             :      * segment. If we didn't catch that case here, we would never recover,
    3443                 :             :      * because ReadRecord() would retry reading the whole record from the
    3444                 :             :      * beginning.
    3445                 :             :      *
    3446                 :             :      * Of course, this only catches errors in the page header, which is what
    3447                 :             :      * happens in the case of a recycled WAL segment. Other kinds of errors or
    3448                 :             :      * corruption still has the same problem. But this at least fixes the
    3449                 :             :      * common case, which can happen as part of normal operation.
    3450                 :             :      *
    3451                 :             :      * Validating the page header is cheap enough that doing it twice
    3452                 :             :      * shouldn't be a big deal from a performance point of view.
    3453                 :             :      *
    3454                 :             :      * When not in standby mode, an invalid page header should cause recovery
    3455                 :             :      * to end, not retry reading the page, so we don't need to validate the
    3456                 :             :      * page header here for the retry. Instead, ReadPageInternal() is
    3457                 :             :      * responsible for the validation.
    3458                 :             :      */
    3459         [ +  + ]:     1506380 :     if (StandbyMode &&
    3460         [ +  + ]:     1495912 :         (targetPagePtr % wal_segment_size) == 0 &&
    3461         [ +  + ]:        1491 :         !XLogReaderValidatePageHeader(xlogreader, targetPagePtr, readBuf))
    3462                 :             :     {
    3463                 :             :         /*
    3464                 :             :          * Emit this error right now then retry this page immediately. Use
    3465                 :             :          * errmsg_internal() because the message was already translated.
    3466                 :             :          */
    3467         [ +  - ]:           5 :         if (xlogreader->errormsg_buf[0])
    3468         [ +  + ]:           5 :             ereport(emode_for_corrupt_record(emode, xlogreader->EndRecPtr),
    3469                 :             :                     (errmsg_internal("%s", xlogreader->errormsg_buf)));
    3470                 :             : 
    3471                 :             :         /* reset any error XLogReaderValidatePageHeader() might have set */
    3472                 :           5 :         XLogReaderResetError(xlogreader);
    3473                 :           5 :         goto next_record_is_invalid;
    3474                 :             :     }
    3475                 :             : 
    3476                 :     1506375 :     return readLen;
    3477                 :             : 
    3478                 :           5 : next_record_is_invalid:
    3479                 :             : 
    3480                 :             :     /*
    3481                 :             :      * If we're reading ahead, give up fast.  Retries and error reporting will
    3482                 :             :      * be handled by a later read when recovery catches up to this point.
    3483                 :             :      */
    3484         [ +  + ]:           5 :     if (xlogreader->nonblocking)
    3485                 :           1 :         return XLREAD_WOULDBLOCK;
    3486                 :             : 
    3487                 :           4 :     lastSourceFailed = true;
    3488                 :             : 
    3489         [ +  - ]:           4 :     if (readFile >= 0)
    3490                 :           4 :         close(readFile);
    3491                 :           4 :     readFile = -1;
    3492                 :           4 :     readLen = 0;
    3493                 :           4 :     readSource = XLOG_FROM_ANY;
    3494                 :             : 
    3495                 :             :     /* In standby-mode, keep trying */
    3496         [ +  - ]:           4 :     if (StandbyMode)
    3497                 :           4 :         goto retry;
    3498                 :             :     else
    3499                 :           0 :         return XLREAD_FAIL;
    3500                 :             : }
    3501                 :             : 
    3502                 :             : /*
    3503                 :             :  * Open the WAL segment containing WAL location 'RecPtr'.
    3504                 :             :  *
    3505                 :             :  * The segment can be fetched via restore_command, or via walreceiver having
    3506                 :             :  * streamed the record, or it can already be present in pg_wal. Checking
    3507                 :             :  * pg_wal is mainly for crash recovery, but it will be polled in standby mode
    3508                 :             :  * too, in case someone copies a new segment directly to pg_wal. That is not
    3509                 :             :  * documented or recommended, though.
    3510                 :             :  *
    3511                 :             :  * If 'fetching_ckpt' is true, we're fetching a checkpoint record, and should
    3512                 :             :  * prepare to read WAL starting from RedoStartLSN after this.
    3513                 :             :  *
    3514                 :             :  * 'RecPtr' might not point to the beginning of the record we're interested
    3515                 :             :  * in, it might also point to the page or segment header. In that case,
    3516                 :             :  * 'tliRecPtr' is the position of the WAL record we're interested in. It is
    3517                 :             :  * used to decide which timeline to stream the requested WAL from.
    3518                 :             :  *
    3519                 :             :  * 'replayLSN' is the current replay LSN, so that if we scan for new
    3520                 :             :  * timelines, we can reject a switch to a timeline that branched off before
    3521                 :             :  * this point.
    3522                 :             :  *
    3523                 :             :  * If the record is not immediately available, the function returns XLREAD_FAIL
    3524                 :             :  * if we're not in standby mode. In standby mode, the function waits for it to
    3525                 :             :  * become available.
    3526                 :             :  *
    3527                 :             :  * When the requested record becomes available, the function opens the file
    3528                 :             :  * containing it (if not open already), and returns XLREAD_SUCCESS. When end
    3529                 :             :  * of standby mode is triggered by the user, and there is no more WAL
    3530                 :             :  * available, returns XLREAD_FAIL.
    3531                 :             :  *
    3532                 :             :  * If nonblocking is true, then give up immediately if we can't satisfy the
    3533                 :             :  * request, returning XLREAD_WOULDBLOCK instead of waiting.
    3534                 :             :  */
    3535                 :             : static XLogPageReadResult
    3536                 :       16427 : WaitForWALToBecomeAvailable(XLogRecPtr RecPtr, bool randAccess,
    3537                 :             :                             bool fetching_ckpt, XLogRecPtr tliRecPtr,
    3538                 :             :                             TimeLineID replayTLI, XLogRecPtr replayLSN,
    3539                 :             :                             bool nonblocking)
    3540                 :             : {
    3541                 :             :     static TimestampTz last_fail_time = 0;
    3542                 :             :     TimestampTz now;
    3543                 :       16427 :     bool        streaming_reply_sent = false;
    3544                 :             : 
    3545                 :             :     /*-------
    3546                 :             :      * Standby mode is implemented by a state machine:
    3547                 :             :      *
    3548                 :             :      * 1. Read from either archive or pg_wal (XLOG_FROM_ARCHIVE), or just
    3549                 :             :      *    pg_wal (XLOG_FROM_PG_WAL)
    3550                 :             :      * 2. Check for promotion trigger request
    3551                 :             :      * 3. Read from primary server via walreceiver (XLOG_FROM_STREAM)
    3552                 :             :      * 4. Rescan timelines
    3553                 :             :      * 5. Sleep wal_retrieve_retry_interval milliseconds, and loop back to 1.
    3554                 :             :      *
    3555                 :             :      * Failure to read from the current source advances the state machine to
    3556                 :             :      * the next state.
    3557                 :             :      *
    3558                 :             :      * 'currentSource' indicates the current state. There are no currentSource
    3559                 :             :      * values for "check trigger", "rescan timelines", and "sleep" states,
    3560                 :             :      * those actions are taken when reading from the previous source fails, as
    3561                 :             :      * part of advancing to the next state.
    3562                 :             :      *
    3563                 :             :      * If standby mode is turned off while reading WAL from stream, we move
    3564                 :             :      * to XLOG_FROM_ARCHIVE and reset lastSourceFailed, to force fetching
    3565                 :             :      * the files (which would be required at end of recovery, e.g., timeline
    3566                 :             :      * history file) from archive or pg_wal. We don't need to kill WAL receiver
    3567                 :             :      * here because it's already stopped when standby mode is turned off at
    3568                 :             :      * the end of recovery.
    3569                 :             :      *-------
    3570                 :             :      */
    3571         [ +  + ]:       16427 :     if (!InArchiveRecovery)
    3572                 :        1079 :         currentSource = XLOG_FROM_PG_WAL;
    3573         [ +  + ]:       15348 :     else if (currentSource == XLOG_FROM_ANY ||
    3574   [ +  +  -  + ]:       15214 :              (!StandbyMode && currentSource == XLOG_FROM_STREAM))
    3575                 :             :     {
    3576                 :         134 :         lastSourceFailed = false;
    3577                 :         134 :         currentSource = XLOG_FROM_ARCHIVE;
    3578                 :             :     }
    3579                 :             : 
    3580                 :             :     for (;;)
    3581                 :       14103 :     {
    3582                 :       30530 :         XLogSource  oldSource = currentSource;
    3583                 :       30530 :         bool        startWalReceiver = false;
    3584                 :             : 
    3585                 :             :         /*
    3586                 :             :          * First check if we failed to read from the current source, and
    3587                 :             :          * advance the state machine if so. The failure to read might've
    3588                 :             :          * happened outside this function, e.g when a CRC check fails on a
    3589                 :             :          * record, or within this loop.
    3590                 :             :          */
    3591         [ +  + ]:       30530 :         if (lastSourceFailed)
    3592                 :             :         {
    3593                 :             :             /*
    3594                 :             :              * Don't allow any retry loops to occur during nonblocking
    3595                 :             :              * readahead.  Let the caller process everything that has been
    3596                 :             :              * decoded already first.
    3597                 :             :              */
    3598         [ +  + ]:         614 :             if (nonblocking)
    3599                 :          89 :                 return XLREAD_WOULDBLOCK;
    3600                 :             : 
    3601      [ +  +  - ]:         525 :             switch (currentSource)
    3602                 :             :             {
    3603                 :         314 :                 case XLOG_FROM_ARCHIVE:
    3604                 :             :                 case XLOG_FROM_PG_WAL:
    3605                 :             : 
    3606                 :             :                     /*
    3607                 :             :                      * Check to see if promotion is requested. Note that we do
    3608                 :             :                      * this only after failure, so when you promote, we still
    3609                 :             :                      * finish replaying as much as we can from archive and
    3610                 :             :                      * pg_wal before failover.
    3611                 :             :                      */
    3612   [ +  +  +  + ]:         314 :                     if (StandbyMode && CheckForStandbyTrigger())
    3613                 :             :                     {
    3614                 :          22 :                         XLogShutdownWalRcv();
    3615                 :          22 :                         return XLREAD_FAIL;
    3616                 :             :                     }
    3617                 :             : 
    3618                 :             :                     /*
    3619                 :             :                      * Not in standby mode, and we've now tried the archive
    3620                 :             :                      * and pg_wal.
    3621                 :             :                      */
    3622         [ +  + ]:         292 :                     if (!StandbyMode)
    3623                 :          30 :                         return XLREAD_FAIL;
    3624                 :             : 
    3625                 :             :                     /*
    3626                 :             :                      * Move to XLOG_FROM_STREAM state, and set to start a
    3627                 :             :                      * walreceiver if necessary.
    3628                 :             :                      */
    3629                 :         262 :                     currentSource = XLOG_FROM_STREAM;
    3630                 :         262 :                     startWalReceiver = true;
    3631                 :         262 :                     break;
    3632                 :             : 
    3633                 :         211 :                 case XLOG_FROM_STREAM:
    3634                 :             : 
    3635                 :             :                     /*
    3636                 :             :                      * Failure while streaming. Most likely, we got here
    3637                 :             :                      * because streaming replication was terminated, or
    3638                 :             :                      * promotion was triggered. But we also get here if we
    3639                 :             :                      * find an invalid record in the WAL streamed from the
    3640                 :             :                      * primary, in which case something is seriously wrong.
    3641                 :             :                      * There's little chance that the problem will just go
    3642                 :             :                      * away, but PANIC is not good for availability either,
    3643                 :             :                      * especially in hot standby mode. So, we treat that the
    3644                 :             :                      * same as disconnection, and retry from archive/pg_wal
    3645                 :             :                      * again. The WAL in the archive should be identical to
    3646                 :             :                      * what was streamed, so it's unlikely that it helps, but
    3647                 :             :                      * one can hope...
    3648                 :             :                      */
    3649                 :             : 
    3650                 :             :                     /*
    3651                 :             :                      * We should be able to move to XLOG_FROM_STREAM only in
    3652                 :             :                      * standby mode.
    3653                 :             :                      */
    3654                 :             :                     Assert(StandbyMode);
    3655                 :             : 
    3656                 :             :                     /*
    3657                 :             :                      * Before we leave XLOG_FROM_STREAM state, make sure that
    3658                 :             :                      * walreceiver is not active, so that it won't overwrite
    3659                 :             :                      * WAL that we restore from archive.
    3660                 :             :                      *
    3661                 :             :                      * If walreceiver is actively streaming (or attempting to
    3662                 :             :                      * connect), we must shut it down. However, if it's
    3663                 :             :                      * already in WAITING state (e.g., due to timeline
    3664                 :             :                      * divergence), we only need to reset the install flag to
    3665                 :             :                      * allow archive restoration.
    3666                 :             :                      */
    3667         [ +  + ]:         211 :                     if (WalRcvStreaming())
    3668                 :          36 :                         XLogShutdownWalRcv();
    3669                 :             :                     else
    3670                 :             :                     {
    3671                 :             :                         /*
    3672                 :             :                          * WALRCV_STOPPING state is a transient state while
    3673                 :             :                          * the startup process is in ShutdownWalRcv().  It
    3674                 :             :                          * should never appear here since we would be waiting
    3675                 :             :                          * for the walreceiver to reach WALRCV_STOPPED in that
    3676                 :             :                          * case.
    3677                 :             :                          */
    3678                 :             :                         Assert(WalRcvGetState() != WALRCV_STOPPING);
    3679                 :         175 :                         ResetInstallXLogFileSegmentActive();
    3680                 :             :                     }
    3681                 :             : 
    3682                 :             :                     /*
    3683                 :             :                      * Before we sleep, re-scan for possible new timelines if
    3684                 :             :                      * we were requested to recover to the latest timeline.
    3685                 :             :                      */
    3686         [ +  - ]:         211 :                     if (recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_LATEST)
    3687                 :             :                     {
    3688         [ +  + ]:         211 :                         if (rescanLatestTimeLine(replayTLI, replayLSN))
    3689                 :             :                         {
    3690                 :           9 :                             currentSource = XLOG_FROM_ARCHIVE;
    3691                 :           9 :                             break;
    3692                 :             :                         }
    3693                 :             :                     }
    3694                 :             : 
    3695                 :             :                     /*
    3696                 :             :                      * XLOG_FROM_STREAM is the last state in our state
    3697                 :             :                      * machine, so we've exhausted all the options for
    3698                 :             :                      * obtaining the requested WAL. We're going to loop back
    3699                 :             :                      * and retry from the archive, but if it hasn't been long
    3700                 :             :                      * since last attempt, sleep wal_retrieve_retry_interval
    3701                 :             :                      * milliseconds to avoid busy-waiting.
    3702                 :             :                      */
    3703                 :         202 :                     now = GetCurrentTimestamp();
    3704         [ +  + ]:         202 :                     if (!TimestampDifferenceExceeds(last_fail_time, now,
    3705                 :             :                                                     wal_retrieve_retry_interval))
    3706                 :             :                     {
    3707                 :             :                         long        wait_time;
    3708                 :             : 
    3709                 :         220 :                         wait_time = wal_retrieve_retry_interval -
    3710                 :         110 :                             TimestampDifferenceMilliseconds(last_fail_time, now);
    3711                 :             : 
    3712         [ +  - ]:         110 :                         elog(LOG, "waiting for WAL to become available at %X/%08X",
    3713                 :             :                              LSN_FORMAT_ARGS(RecPtr));
    3714                 :             : 
    3715                 :             :                         /* Do background tasks that might benefit us later. */
    3716                 :         110 :                         KnownAssignedTransactionIdsIdleMaintenance();
    3717                 :             : 
    3718                 :         110 :                         (void) WaitLatch(&XLogRecoveryCtl->recoveryWakeupLatch,
    3719                 :             :                                          WL_LATCH_SET | WL_TIMEOUT |
    3720                 :             :                                          WL_EXIT_ON_PM_DEATH,
    3721                 :             :                                          wait_time,
    3722                 :             :                                          WAIT_EVENT_RECOVERY_RETRIEVE_RETRY_INTERVAL);
    3723                 :         110 :                         ResetLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
    3724                 :         110 :                         now = GetCurrentTimestamp();
    3725                 :             : 
    3726                 :             :                         /* Handle interrupt signals of startup process */
    3727                 :         110 :                         ProcessStartupProcInterrupts();
    3728                 :             :                     }
    3729                 :         188 :                     last_fail_time = now;
    3730                 :         188 :                     currentSource = XLOG_FROM_ARCHIVE;
    3731                 :         188 :                     break;
    3732                 :             : 
    3733                 :           0 :                 default:
    3734         [ #  # ]:           0 :                     elog(ERROR, "unexpected WAL source %d", currentSource);
    3735                 :             :             }
    3736                 :             :         }
    3737         [ +  + ]:       29916 :         else if (currentSource == XLOG_FROM_PG_WAL)
    3738                 :             :         {
    3739                 :             :             /*
    3740                 :             :              * We just successfully read a file in pg_wal. We prefer files in
    3741                 :             :              * the archive over ones in pg_wal, so try the next file again
    3742                 :             :              * from the archive first.
    3743                 :             :              */
    3744         [ -  + ]:        1073 :             if (InArchiveRecovery)
    3745                 :           0 :                 currentSource = XLOG_FROM_ARCHIVE;
    3746                 :             :         }
    3747                 :             : 
    3748         [ +  + ]:       30375 :         if (currentSource != oldSource)
    3749   [ +  +  +  - ]:         459 :             elog(DEBUG2, "switched WAL source from %s to %s after %s",
    3750                 :             :                  xlogSourceNames[oldSource], xlogSourceNames[currentSource],
    3751                 :             :                  lastSourceFailed ? "failure" : "success");
    3752                 :             : 
    3753                 :             :         /*
    3754                 :             :          * We've now handled possible failure. Try to read from the chosen
    3755                 :             :          * source.
    3756                 :             :          */
    3757                 :       30375 :         lastSourceFailed = false;
    3758                 :             : 
    3759      [ +  +  - ]:       30375 :         switch (currentSource)
    3760                 :             :         {
    3761                 :        1981 :             case XLOG_FROM_ARCHIVE:
    3762                 :             :             case XLOG_FROM_PG_WAL:
    3763                 :             : 
    3764                 :             :                 /*
    3765                 :             :                  * WAL receiver must not be running when reading WAL from
    3766                 :             :                  * archive or pg_wal.
    3767                 :             :                  */
    3768                 :             :                 Assert(!WalRcvStreaming());
    3769                 :             : 
    3770                 :             :                 /* Close any old file we might have open. */
    3771         [ +  + ]:        1981 :                 if (readFile >= 0)
    3772                 :             :                 {
    3773                 :         107 :                     close(readFile);
    3774                 :         107 :                     readFile = -1;
    3775                 :             :                 }
    3776                 :             :                 /* Reset curFileTLI if random fetch. */
    3777         [ +  + ]:        1981 :                 if (randAccess)
    3778                 :        1255 :                     curFileTLI = 0;
    3779                 :             : 
    3780                 :             :                 /*
    3781                 :             :                  * Try to restore the file from archive, or read an existing
    3782                 :             :                  * file from pg_wal.
    3783                 :             :                  */
    3784                 :        1981 :                 readFile = XLogFileReadAnyTLI(readSegNo,
    3785         [ +  + ]:        1981 :                                               currentSource == XLOG_FROM_ARCHIVE ? XLOG_FROM_ANY :
    3786                 :             :                                               currentSource);
    3787         [ +  + ]:        1981 :                 if (readFile >= 0)
    3788                 :        1774 :                     return XLREAD_SUCCESS;  /* success! */
    3789                 :             : 
    3790                 :             :                 /*
    3791                 :             :                  * Nope, not found in archive or pg_wal.
    3792                 :             :                  */
    3793                 :         207 :                 lastSourceFailed = true;
    3794                 :         207 :                 break;
    3795                 :             : 
    3796                 :       28394 :             case XLOG_FROM_STREAM:
    3797                 :             :                 {
    3798                 :             :                     bool        havedata;
    3799                 :             : 
    3800                 :             :                     /*
    3801                 :             :                      * We should be able to move to XLOG_FROM_STREAM only in
    3802                 :             :                      * standby mode.
    3803                 :             :                      */
    3804                 :             :                     Assert(StandbyMode);
    3805                 :             : 
    3806                 :             :                     /*
    3807                 :             :                      * First, shutdown walreceiver if its restart has been
    3808                 :             :                      * requested -- but no point if we're already slated for
    3809                 :             :                      * starting it.
    3810                 :             :                      */
    3811   [ +  +  +  - ]:       28394 :                     if (pendingWalRcvRestart && !startWalReceiver)
    3812                 :             :                     {
    3813                 :           8 :                         XLogShutdownWalRcv();
    3814                 :             : 
    3815                 :             :                         /*
    3816                 :             :                          * Re-scan for possible new timelines if we were
    3817                 :             :                          * requested to recover to the latest timeline.
    3818                 :             :                          */
    3819         [ +  - ]:           8 :                         if (recoveryTargetTimeLineGoal ==
    3820                 :             :                             RECOVERY_TARGET_TIMELINE_LATEST)
    3821                 :           8 :                             rescanLatestTimeLine(replayTLI, replayLSN);
    3822                 :             : 
    3823                 :           8 :                         startWalReceiver = true;
    3824                 :             :                     }
    3825                 :       28394 :                     pendingWalRcvRestart = false;
    3826                 :             : 
    3827                 :             :                     /*
    3828                 :             :                      * Launch walreceiver if needed.
    3829                 :             :                      *
    3830                 :             :                      * If fetching_ckpt is true, RecPtr points to the initial
    3831                 :             :                      * checkpoint location. In that case, we use RedoStartLSN
    3832                 :             :                      * as the streaming start position instead of RecPtr, so
    3833                 :             :                      * that when we later jump backwards to start redo at
    3834                 :             :                      * RedoStartLSN, we will have the logs streamed already.
    3835                 :             :                      */
    3836   [ +  +  +  - ]:       28394 :                     if (startWalReceiver &&
    3837         [ +  + ]:         270 :                         PrimaryConnInfo && strcmp(PrimaryConnInfo, "") != 0)
    3838                 :             :                     {
    3839                 :             :                         XLogRecPtr  ptr;
    3840                 :             :                         TimeLineID  tli;
    3841                 :             : 
    3842         [ -  + ]:         220 :                         if (fetching_ckpt)
    3843                 :             :                         {
    3844                 :           0 :                             ptr = RedoStartLSN;
    3845                 :           0 :                             tli = RedoStartTLI;
    3846                 :             :                         }
    3847                 :             :                         else
    3848                 :             :                         {
    3849                 :         220 :                             ptr = RecPtr;
    3850                 :             : 
    3851                 :             :                             /*
    3852                 :             :                              * Use the record begin position to determine the
    3853                 :             :                              * TLI, rather than the position we're reading.
    3854                 :             :                              */
    3855                 :         220 :                             tli = tliOfPointInHistory(tliRecPtr, expectedTLEs);
    3856                 :             : 
    3857   [ +  -  -  + ]:         220 :                             if (curFileTLI > 0 && tli < curFileTLI)
    3858         [ #  # ]:           0 :                                 elog(ERROR, "according to history file, WAL location %X/%08X belongs to timeline %u, but previous recovered WAL file came from timeline %u",
    3859                 :             :                                      LSN_FORMAT_ARGS(tliRecPtr),
    3860                 :             :                                      tli, curFileTLI);
    3861                 :             :                         }
    3862                 :         220 :                         curFileTLI = tli;
    3863                 :         220 :                         SetInstallXLogFileSegmentActive();
    3864                 :         220 :                         RequestXLogStreaming(tli, ptr, PrimaryConnInfo,
    3865                 :             :                                              PrimarySlotName,
    3866                 :             :                                              wal_receiver_create_temp_slot);
    3867                 :         220 :                         flushedUpto = InvalidXLogRecPtr;
    3868                 :             :                     }
    3869                 :             : 
    3870                 :             :                     /*
    3871                 :             :                      * Check if WAL receiver is active or wait to start up.
    3872                 :             :                      */
    3873         [ +  + ]:       28394 :                     if (!WalRcvStreaming())
    3874                 :             :                     {
    3875                 :         175 :                         lastSourceFailed = true;
    3876                 :         175 :                         break;
    3877                 :             :                     }
    3878                 :             : 
    3879                 :             :                     /*
    3880                 :             :                      * Walreceiver is active, so see if new data has arrived.
    3881                 :             :                      *
    3882                 :             :                      * We only advance XLogReceiptTime when we obtain fresh
    3883                 :             :                      * WAL from walreceiver and observe that we had already
    3884                 :             :                      * processed everything before the most recent "chunk"
    3885                 :             :                      * that it flushed to disk.  In steady state where we are
    3886                 :             :                      * keeping up with the incoming data, XLogReceiptTime will
    3887                 :             :                      * be updated on each cycle. When we are behind,
    3888                 :             :                      * XLogReceiptTime will not advance, so the grace time
    3889                 :             :                      * allotted to conflicting queries will decrease.
    3890                 :             :                      */
    3891         [ +  + ]:       28219 :                     if (RecPtr < flushedUpto)
    3892                 :        1776 :                         havedata = true;
    3893                 :             :                     else
    3894                 :             :                     {
    3895                 :             :                         XLogRecPtr  latestChunkStart;
    3896                 :             : 
    3897                 :       26443 :                         flushedUpto = GetWalRcvFlushRecPtr(&latestChunkStart, &receiveTLI);
    3898   [ +  +  +  - ]:       26443 :                         if (RecPtr < flushedUpto && receiveTLI == curFileTLI)
    3899                 :             :                         {
    3900                 :       13543 :                             havedata = true;
    3901         [ +  + ]:       13543 :                             if (latestChunkStart <= RecPtr)
    3902                 :             :                             {
    3903                 :        8901 :                                 XLogReceiptTime = GetCurrentTimestamp();
    3904                 :        8901 :                                 SetCurrentChunkStartTime(XLogReceiptTime);
    3905                 :             :                             }
    3906                 :             :                         }
    3907                 :             :                         else
    3908                 :       12900 :                             havedata = false;
    3909                 :             :                     }
    3910         [ +  + ]:       28219 :                     if (havedata)
    3911                 :             :                     {
    3912                 :             :                         /*
    3913                 :             :                          * Great, streamed far enough.  Open the file if it's
    3914                 :             :                          * not open already.  Also read the timeline history
    3915                 :             :                          * file if we haven't initialized timeline history
    3916                 :             :                          * yet; it should be streamed over and present in
    3917                 :             :                          * pg_wal by now.  Use XLOG_FROM_STREAM so that source
    3918                 :             :                          * info is set correctly and XLogReceiptTime isn't
    3919                 :             :                          * changed.
    3920                 :             :                          *
    3921                 :             :                          * NB: We must set readTimeLineHistory based on
    3922                 :             :                          * recoveryTargetTLI, not receiveTLI. Normally they'll
    3923                 :             :                          * be the same, but if recovery_target_timeline is
    3924                 :             :                          * 'latest' and archiving is configured, then it's
    3925                 :             :                          * possible that we managed to retrieve one or more
    3926                 :             :                          * new timeline history files from the archive,
    3927                 :             :                          * updating recoveryTargetTLI.
    3928                 :             :                          */
    3929         [ +  + ]:       15319 :                         if (readFile < 0)
    3930                 :             :                         {
    3931         [ -  + ]:        1176 :                             if (!expectedTLEs)
    3932                 :           0 :                                 expectedTLEs = readTimeLineHistory(recoveryTargetTLI);
    3933                 :        1176 :                             readFile = XLogFileRead(readSegNo, receiveTLI,
    3934                 :             :                                                     XLOG_FROM_STREAM, false);
    3935                 :             :                             Assert(readFile >= 0);
    3936                 :             :                         }
    3937                 :             :                         else
    3938                 :             :                         {
    3939                 :             :                             /* just make sure source info is correct... */
    3940                 :       14143 :                             readSource = XLOG_FROM_STREAM;
    3941                 :       14143 :                             XLogReceiptSource = XLOG_FROM_STREAM;
    3942                 :       14143 :                             return XLREAD_SUCCESS;
    3943                 :             :                         }
    3944                 :        1176 :                         break;
    3945                 :             :                     }
    3946                 :             : 
    3947                 :             :                     /* In nonblocking mode, return rather than sleeping. */
    3948         [ +  + ]:       12900 :                     if (nonblocking)
    3949                 :         306 :                         return XLREAD_WOULDBLOCK;
    3950                 :             : 
    3951                 :             :                     /*
    3952                 :             :                      * Data not here yet. Check for trigger, then wait for
    3953                 :             :                      * walreceiver to wake us up when new WAL arrives.
    3954                 :             :                      */
    3955         [ +  + ]:       12594 :                     if (CheckForStandbyTrigger())
    3956                 :             :                     {
    3957                 :             :                         /*
    3958                 :             :                          * Note that we don't return XLREAD_FAIL immediately
    3959                 :             :                          * here. After being triggered, we still want to
    3960                 :             :                          * replay all the WAL that was already streamed. It's
    3961                 :             :                          * in pg_wal now, so we just treat this as a failure,
    3962                 :             :                          * and the state machine will move on to replay the
    3963                 :             :                          * streamed WAL from pg_wal, and then recheck the
    3964                 :             :                          * trigger and exit replay.
    3965                 :             :                          */
    3966                 :          36 :                         lastSourceFailed = true;
    3967                 :          36 :                         break;
    3968                 :             :                     }
    3969                 :             : 
    3970                 :             :                     /*
    3971                 :             :                      * Since we have replayed everything we have received so
    3972                 :             :                      * far and are about to start waiting for more WAL, let's
    3973                 :             :                      * tell the upstream server our replay location now so
    3974                 :             :                      * that pg_stat_replication doesn't show stale
    3975                 :             :                      * information.
    3976                 :             :                      */
    3977         [ +  + ]:       12558 :                     if (!streaming_reply_sent)
    3978                 :             :                     {
    3979                 :       10698 :                         WalRcvRequestApplyReply();
    3980                 :       10698 :                         streaming_reply_sent = true;
    3981                 :             :                     }
    3982                 :             : 
    3983                 :             :                     /* Do any background tasks that might benefit us later. */
    3984                 :       12558 :                     KnownAssignedTransactionIdsIdleMaintenance();
    3985                 :             : 
    3986                 :             :                     /* Update pg_stat_recovery_prefetch before sleeping. */
    3987                 :       12558 :                     XLogPrefetcherComputeStats(xlogprefetcher);
    3988                 :             : 
    3989                 :             :                     /*
    3990                 :             :                      * Wait for more WAL to arrive, when we will be woken
    3991                 :             :                      * immediately by the WAL receiver.
    3992                 :             :                      */
    3993                 :       12558 :                     (void) WaitLatch(&XLogRecoveryCtl->recoveryWakeupLatch,
    3994                 :             :                                      WL_LATCH_SET | WL_EXIT_ON_PM_DEATH,
    3995                 :             :                                      -1L,
    3996                 :             :                                      WAIT_EVENT_RECOVERY_WAL_STREAM);
    3997                 :       12558 :                     ResetLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
    3998                 :       12558 :                     break;
    3999                 :             :                 }
    4000                 :             : 
    4001                 :           0 :             default:
    4002         [ #  # ]:           0 :                 elog(ERROR, "unexpected WAL source %d", currentSource);
    4003                 :             :         }
    4004                 :             : 
    4005                 :             :         /*
    4006                 :             :          * Check for recovery pause here so that we can confirm more quickly
    4007                 :             :          * that a requested pause has actually taken effect.
    4008                 :             :          */
    4009         [ +  + ]:       14152 :         if (((volatile XLogRecoveryCtlData *) XLogRecoveryCtl)->recoveryPauseState !=
    4010                 :             :             RECOVERY_NOT_PAUSED)
    4011                 :           7 :             recoveryPausesHere(false);
    4012                 :             : 
    4013                 :             :         /*
    4014                 :             :          * This possibly-long loop needs to handle interrupts of startup
    4015                 :             :          * process.
    4016                 :             :          */
    4017                 :       14152 :         ProcessStartupProcInterrupts();
    4018                 :             :     }
    4019                 :             : 
    4020                 :             :     return XLREAD_FAIL;         /* not reached */
    4021                 :             : }
    4022                 :             : 
    4023                 :             : 
    4024                 :             : /*
    4025                 :             :  * Determine what log level should be used to report a corrupt WAL record
    4026                 :             :  * in the current WAL page, previously read by XLogPageRead().
    4027                 :             :  *
    4028                 :             :  * 'emode' is the error mode that would be used to report a file-not-found
    4029                 :             :  * or legitimate end-of-WAL situation.   Generally, we use it as-is, but if
    4030                 :             :  * we're retrying the exact same record that we've tried previously, only
    4031                 :             :  * complain the first time to keep the noise down.  However, we only do when
    4032                 :             :  * reading from pg_wal, because we don't expect any invalid records in archive
    4033                 :             :  * or in records streamed from the primary. Files in the archive should be complete,
    4034                 :             :  * and we should never hit the end of WAL because we stop and wait for more WAL
    4035                 :             :  * to arrive before replaying it.
    4036                 :             :  *
    4037                 :             :  * NOTE: This function remembers the RecPtr value it was last called with,
    4038                 :             :  * to suppress repeated messages about the same record. Only call this when
    4039                 :             :  * you are about to ereport(), or you might cause a later message to be
    4040                 :             :  * erroneously suppressed.
    4041                 :             :  */
    4042                 :             : static int
    4043                 :         310 : emode_for_corrupt_record(int emode, XLogRecPtr RecPtr)
    4044                 :             : {
    4045                 :             :     static XLogRecPtr lastComplaint = InvalidXLogRecPtr;
    4046                 :             : 
    4047   [ +  +  +  - ]:         310 :     if (readSource == XLOG_FROM_PG_WAL && emode == LOG)
    4048                 :             :     {
    4049         [ +  + ]:         307 :         if (RecPtr == lastComplaint)
    4050                 :          93 :             emode = DEBUG1;
    4051                 :             :         else
    4052                 :         214 :             lastComplaint = RecPtr;
    4053                 :             :     }
    4054                 :         310 :     return emode;
    4055                 :             : }
    4056                 :             : 
    4057                 :             : 
    4058                 :             : /*
    4059                 :             :  * Subroutine to try to fetch and validate a prior checkpoint record.
    4060                 :             :  */
    4061                 :             : static XLogRecord *
    4062                 :        1089 : ReadCheckpointRecord(XLogPrefetcher *xlogprefetcher, XLogRecPtr RecPtr,
    4063                 :             :                      TimeLineID replayTLI)
    4064                 :             : {
    4065                 :             :     XLogRecord *record;
    4066                 :             :     uint8       info;
    4067                 :             : 
    4068                 :             :     Assert(xlogreader != NULL);
    4069                 :             : 
    4070         [ -  + ]:        1089 :     if (!XRecOffIsValid(RecPtr))
    4071                 :             :     {
    4072         [ #  # ]:           0 :         ereport(LOG,
    4073                 :             :                 (errmsg("invalid checkpoint location")));
    4074                 :           0 :         return NULL;
    4075                 :             :     }
    4076                 :             : 
    4077                 :        1089 :     XLogPrefetcherBeginRead(xlogprefetcher, RecPtr);
    4078                 :        1089 :     record = ReadRecord(xlogprefetcher, LOG, true, replayTLI);
    4079                 :             : 
    4080         [ +  + ]:        1089 :     if (record == NULL)
    4081                 :             :     {
    4082         [ +  - ]:           1 :         ereport(LOG,
    4083                 :             :                 (errmsg("invalid checkpoint record")));
    4084                 :           1 :         return NULL;
    4085                 :             :     }
    4086         [ -  + ]:        1088 :     if (record->xl_rmid != RM_XLOG_ID)
    4087                 :             :     {
    4088         [ #  # ]:           0 :         ereport(LOG,
    4089                 :             :                 (errmsg("invalid resource manager ID in checkpoint record")));
    4090                 :           0 :         return NULL;
    4091                 :             :     }
    4092                 :        1088 :     info = record->xl_info & ~XLR_INFO_MASK;
    4093   [ +  +  -  + ]:        1088 :     if (info != XLOG_CHECKPOINT_SHUTDOWN &&
    4094                 :             :         info != XLOG_CHECKPOINT_ONLINE)
    4095                 :             :     {
    4096         [ #  # ]:           0 :         ereport(LOG,
    4097                 :             :                 (errmsg("invalid xl_info in checkpoint record")));
    4098                 :           0 :         return NULL;
    4099                 :             :     }
    4100         [ -  + ]:        1088 :     if (record->xl_tot_len != SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(CheckPoint))
    4101                 :             :     {
    4102         [ #  # ]:           0 :         ereport(LOG,
    4103                 :             :                 (errmsg("invalid length of checkpoint record")));
    4104                 :           0 :         return NULL;
    4105                 :             :     }
    4106                 :        1088 :     return record;
    4107                 :             : }
    4108                 :             : 
    4109                 :             : /*
    4110                 :             :  * Scan for new timelines that might have appeared in the archive since we
    4111                 :             :  * started recovery.
    4112                 :             :  *
    4113                 :             :  * If there are any, the function changes recovery target TLI to the latest
    4114                 :             :  * one and returns 'true'.
    4115                 :             :  */
    4116                 :             : static bool
    4117                 :         219 : rescanLatestTimeLine(TimeLineID replayTLI, XLogRecPtr replayLSN)
    4118                 :             : {
    4119                 :             :     List       *newExpectedTLEs;
    4120                 :             :     bool        found;
    4121                 :             :     ListCell   *cell;
    4122                 :             :     TimeLineID  newtarget;
    4123                 :         219 :     TimeLineID  oldtarget = recoveryTargetTLI;
    4124                 :         219 :     TimeLineHistoryEntry *currentTle = NULL;
    4125                 :             : 
    4126                 :         219 :     newtarget = findNewestTimeLine(recoveryTargetTLI);
    4127         [ +  + ]:         219 :     if (newtarget == recoveryTargetTLI)
    4128                 :             :     {
    4129                 :             :         /* No new timelines found */
    4130                 :         210 :         return false;
    4131                 :             :     }
    4132                 :             : 
    4133                 :             :     /*
    4134                 :             :      * Determine the list of expected TLIs for the new TLI
    4135                 :             :      */
    4136                 :             : 
    4137                 :           9 :     newExpectedTLEs = readTimeLineHistory(newtarget);
    4138                 :             : 
    4139                 :             :     /*
    4140                 :             :      * If the current timeline is not part of the history of the new timeline,
    4141                 :             :      * we cannot proceed to it.
    4142                 :             :      */
    4143                 :           9 :     found = false;
    4144   [ +  -  +  -  :          18 :     foreach(cell, newExpectedTLEs)
                   +  - ]
    4145                 :             :     {
    4146                 :          18 :         currentTle = (TimeLineHistoryEntry *) lfirst(cell);
    4147                 :             : 
    4148         [ +  + ]:          18 :         if (currentTle->tli == recoveryTargetTLI)
    4149                 :             :         {
    4150                 :           9 :             found = true;
    4151                 :           9 :             break;
    4152                 :             :         }
    4153                 :             :     }
    4154         [ -  + ]:           9 :     if (!found)
    4155                 :             :     {
    4156         [ #  # ]:           0 :         ereport(LOG,
    4157                 :             :                 (errmsg("new timeline %u is not a child of database system timeline %u",
    4158                 :             :                         newtarget,
    4159                 :             :                         replayTLI)));
    4160                 :           0 :         return false;
    4161                 :             :     }
    4162                 :             : 
    4163                 :             :     /*
    4164                 :             :      * The current timeline was found in the history file, but check that the
    4165                 :             :      * next timeline was forked off from it *after* the current recovery
    4166                 :             :      * location.
    4167                 :             :      */
    4168         [ -  + ]:           9 :     if (currentTle->end < replayLSN)
    4169                 :             :     {
    4170         [ #  # ]:           0 :         ereport(LOG,
    4171                 :             :                 errmsg("new timeline %u forked off current database system timeline %u before current recovery point %X/%08X",
    4172                 :             :                        newtarget,
    4173                 :             :                        replayTLI,
    4174                 :             :                        LSN_FORMAT_ARGS(replayLSN)));
    4175                 :           0 :         return false;
    4176                 :             :     }
    4177                 :             : 
    4178                 :             :     /* The new timeline history seems valid. Switch target */
    4179                 :           9 :     recoveryTargetTLI = newtarget;
    4180                 :           9 :     list_free_deep(expectedTLEs);
    4181                 :           9 :     expectedTLEs = newExpectedTLEs;
    4182                 :             : 
    4183                 :             :     /*
    4184                 :             :      * As in StartupXLOG(), try to ensure we have all the history files
    4185                 :             :      * between the old target and new target in pg_wal.
    4186                 :             :      */
    4187                 :           9 :     restoreTimeLineHistoryFiles(oldtarget + 1, newtarget);
    4188                 :             : 
    4189         [ +  - ]:           9 :     ereport(LOG,
    4190                 :             :             (errmsg("new target timeline is %u",
    4191                 :             :                     recoveryTargetTLI)));
    4192                 :             : 
    4193                 :           9 :     return true;
    4194                 :             : }
    4195                 :             : 
    4196                 :             : 
    4197                 :             : /*
    4198                 :             :  * Open a logfile segment for reading (during recovery).
    4199                 :             :  *
    4200                 :             :  * If source == XLOG_FROM_ARCHIVE, the segment is retrieved from archive.
    4201                 :             :  * Otherwise, it's assumed to be already available in pg_wal.
    4202                 :             :  */
    4203                 :             : static int
    4204                 :        3726 : XLogFileRead(XLogSegNo segno, TimeLineID tli,
    4205                 :             :              XLogSource source, bool notfoundOk)
    4206                 :             : {
    4207                 :             :     char        xlogfname[MAXFNAMELEN];
    4208                 :             :     char        activitymsg[MAXFNAMELEN + 16];
    4209                 :             :     char        path[MAXPGPATH];
    4210                 :             :     int         fd;
    4211                 :             : 
    4212                 :        3726 :     XLogFileName(xlogfname, tli, segno, wal_segment_size);
    4213                 :             : 
    4214      [ +  +  - ]:        3726 :     switch (source)
    4215                 :             :     {
    4216                 :         921 :         case XLOG_FROM_ARCHIVE:
    4217                 :             :             /* Report recovery progress in PS display */
    4218                 :         921 :             snprintf(activitymsg, sizeof(activitymsg), "waiting for %s",
    4219                 :             :                      xlogfname);
    4220                 :         921 :             set_ps_display(activitymsg);
    4221                 :             : 
    4222         [ +  + ]:         921 :             if (!RestoreArchivedFile(path, xlogfname,
    4223                 :             :                                      "RECOVERYXLOG",
    4224                 :             :                                      wal_segment_size,
    4225                 :             :                                      InRedo))
    4226                 :         556 :                 return -1;
    4227                 :         365 :             break;
    4228                 :             : 
    4229                 :        2805 :         case XLOG_FROM_PG_WAL:
    4230                 :             :         case XLOG_FROM_STREAM:
    4231                 :        2805 :             XLogFilePath(path, tli, segno, wal_segment_size);
    4232                 :        2805 :             break;
    4233                 :             : 
    4234                 :           0 :         default:
    4235         [ #  # ]:           0 :             elog(ERROR, "invalid XLogFileRead source %d", source);
    4236                 :             :     }
    4237                 :             : 
    4238                 :             :     /*
    4239                 :             :      * If the segment was fetched from archival storage, replace the existing
    4240                 :             :      * xlog segment (if any) with the archival version.
    4241                 :             :      */
    4242         [ +  + ]:        3170 :     if (source == XLOG_FROM_ARCHIVE)
    4243                 :             :     {
    4244                 :             :         Assert(!IsInstallXLogFileSegmentActive());
    4245                 :         365 :         KeepFileRestoredFromArchive(path, xlogfname);
    4246                 :             : 
    4247                 :             :         /*
    4248                 :             :          * Set path to point at the new file in pg_wal.
    4249                 :             :          */
    4250                 :         365 :         snprintf(path, MAXPGPATH, XLOGDIR "/%s", xlogfname);
    4251                 :             :     }
    4252                 :             : 
    4253                 :        3170 :     fd = BasicOpenFile(path, O_RDONLY | PG_BINARY);
    4254         [ +  + ]:        3170 :     if (fd >= 0)
    4255                 :             :     {
    4256                 :             :         /* Success! */
    4257                 :        2950 :         curFileTLI = tli;
    4258                 :             : 
    4259                 :             :         /* Report recovery progress in PS display */
    4260                 :        2950 :         snprintf(activitymsg, sizeof(activitymsg), "recovering %s",
    4261                 :             :                  xlogfname);
    4262                 :        2950 :         set_ps_display(activitymsg);
    4263                 :             : 
    4264                 :             :         /* Track source of data in assorted state variables */
    4265                 :        2950 :         readSource = source;
    4266                 :        2950 :         XLogReceiptSource = source;
    4267                 :             :         /* In FROM_STREAM case, caller tracks receipt time, not me */
    4268         [ +  + ]:        2950 :         if (source != XLOG_FROM_STREAM)
    4269                 :        1774 :             XLogReceiptTime = GetCurrentTimestamp();
    4270                 :             : 
    4271                 :        2950 :         return fd;
    4272                 :             :     }
    4273   [ +  -  -  + ]:         220 :     if (errno != ENOENT || !notfoundOk) /* unexpected failure? */
    4274         [ #  # ]:           0 :         ereport(PANIC,
    4275                 :             :                 (errcode_for_file_access(),
    4276                 :             :                  errmsg("could not open file \"%s\": %m", path)));
    4277                 :         220 :     return -1;
    4278                 :             : }
    4279                 :             : 
    4280                 :             : /*
    4281                 :             :  * Open a logfile segment for reading (during recovery).
    4282                 :             :  *
    4283                 :             :  * This version searches for the segment with any TLI listed in expectedTLEs.
    4284                 :             :  */
    4285                 :             : static int
    4286                 :        1981 : XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source)
    4287                 :             : {
    4288                 :             :     char        path[MAXPGPATH];
    4289                 :             :     ListCell   *cell;
    4290                 :             :     int         fd;
    4291                 :             :     List       *tles;
    4292                 :             : 
    4293                 :             :     /*
    4294                 :             :      * Loop looking for a suitable timeline ID: we might need to read any of
    4295                 :             :      * the timelines listed in expectedTLEs.
    4296                 :             :      *
    4297                 :             :      * We expect curFileTLI on entry to be the TLI of the preceding file in
    4298                 :             :      * sequence, or 0 if there was no predecessor.  We do not allow curFileTLI
    4299                 :             :      * to go backwards; this prevents us from picking up the wrong file when a
    4300                 :             :      * parent timeline extends to higher segment numbers than the child we
    4301                 :             :      * want to read.
    4302                 :             :      *
    4303                 :             :      * If we haven't read the timeline history file yet, read it now, so that
    4304                 :             :      * we know which TLIs to scan.  We don't save the list in expectedTLEs,
    4305                 :             :      * however, unless we actually find a valid segment.  That way if there is
    4306                 :             :      * neither a timeline history file nor a WAL segment in the archive, and
    4307                 :             :      * streaming replication is set up, we'll read the timeline history file
    4308                 :             :      * streamed from the primary when we start streaming, instead of
    4309                 :             :      * recovering with a dummy history generated here.
    4310                 :             :      */
    4311         [ +  + ]:        1981 :     if (expectedTLEs)
    4312                 :         892 :         tles = expectedTLEs;
    4313                 :             :     else
    4314                 :        1089 :         tles = readTimeLineHistory(recoveryTargetTLI);
    4315                 :             : 
    4316   [ +  -  +  +  :        2208 :     foreach(cell, tles)
                   +  + ]
    4317                 :             :     {
    4318                 :        2007 :         TimeLineHistoryEntry *hent = (TimeLineHistoryEntry *) lfirst(cell);
    4319                 :        2007 :         TimeLineID  tli = hent->tli;
    4320                 :             : 
    4321         [ +  + ]:        2007 :         if (tli < curFileTLI)
    4322                 :           6 :             break;              /* don't bother looking at too-old TLIs */
    4323                 :             : 
    4324                 :             :         /*
    4325                 :             :          * Skip scanning the timeline ID that the logfile segment to read
    4326                 :             :          * doesn't belong to
    4327                 :             :          */
    4328         [ +  + ]:        2001 :         if (XLogRecPtrIsValid(hent->begin))
    4329                 :             :         {
    4330                 :          85 :             XLogSegNo   beginseg = 0;
    4331                 :             : 
    4332                 :          85 :             XLByteToSeg(hent->begin, beginseg, wal_segment_size);
    4333                 :             : 
    4334                 :             :             /*
    4335                 :             :              * The logfile segment that doesn't belong to the timeline is
    4336                 :             :              * older or newer than the segment that the timeline started or
    4337                 :             :              * ended at, respectively. It's sufficient to check only the
    4338                 :             :              * starting segment of the timeline here. Since the timelines are
    4339                 :             :              * scanned in descending order in this loop, any segments newer
    4340                 :             :              * than the ending segment should belong to newer timeline and
    4341                 :             :              * have already been read before. So it's not necessary to check
    4342                 :             :              * the ending segment of the timeline here.
    4343                 :             :              */
    4344         [ +  + ]:          85 :             if (segno < beginseg)
    4345                 :           7 :                 continue;
    4346                 :             :         }
    4347                 :             : 
    4348   [ +  +  -  + ]:        1994 :         if (source == XLOG_FROM_ANY || source == XLOG_FROM_ARCHIVE)
    4349                 :             :         {
    4350                 :         921 :             fd = XLogFileRead(segno, tli, XLOG_FROM_ARCHIVE, true);
    4351         [ +  + ]:         921 :             if (fd != -1)
    4352                 :             :             {
    4353         [ -  + ]:         365 :                 elog(DEBUG1, "got WAL segment from archive");
    4354         [ +  + ]:         365 :                 if (!expectedTLEs)
    4355                 :          19 :                     expectedTLEs = tles;
    4356                 :        1774 :                 return fd;
    4357                 :             :             }
    4358                 :             :         }
    4359                 :             : 
    4360   [ +  +  +  - ]:        1629 :         if (source == XLOG_FROM_ANY || source == XLOG_FROM_PG_WAL)
    4361                 :             :         {
    4362                 :        1629 :             fd = XLogFileRead(segno, tli, XLOG_FROM_PG_WAL, true);
    4363         [ +  + ]:        1629 :             if (fd != -1)
    4364                 :             :             {
    4365         [ +  + ]:        1409 :                 if (!expectedTLEs)
    4366                 :        1069 :                     expectedTLEs = tles;
    4367                 :        1409 :                 return fd;
    4368                 :             :             }
    4369                 :             :         }
    4370                 :             :     }
    4371                 :             : 
    4372                 :             :     /* Couldn't find it.  For simplicity, complain about front timeline */
    4373                 :         207 :     XLogFilePath(path, recoveryTargetTLI, segno, wal_segment_size);
    4374                 :         207 :     errno = ENOENT;
    4375         [ +  + ]:         207 :     ereport(DEBUG2,
    4376                 :             :             (errcode_for_file_access(),
    4377                 :             :              errmsg("could not open file \"%s\": %m", path)));
    4378                 :         207 :     return -1;
    4379                 :             : }
    4380                 :             : 
    4381                 :             : /*
    4382                 :             :  * Set flag to signal the walreceiver to restart.  (The startup process calls
    4383                 :             :  * this on noticing a relevant configuration change.)
    4384                 :             :  */
    4385                 :             : void
    4386                 :          13 : StartupRequestWalReceiverRestart(void)
    4387                 :             : {
    4388   [ +  -  +  + ]:          13 :     if (currentSource == XLOG_FROM_STREAM && WalRcvRunning())
    4389                 :             :     {
    4390         [ +  - ]:           8 :         ereport(LOG,
    4391                 :             :                 (errmsg("WAL receiver process shutdown requested")));
    4392                 :             : 
    4393                 :           8 :         pendingWalRcvRestart = true;
    4394                 :             :     }
    4395                 :          13 : }
    4396                 :             : 
    4397                 :             : 
    4398                 :             : /*
    4399                 :             :  * Has a standby promotion already been triggered?
    4400                 :             :  *
    4401                 :             :  * Unlike CheckForStandbyTrigger(), this works in any process
    4402                 :             :  * that's connected to shared memory.
    4403                 :             :  */
    4404                 :             : bool
    4405                 :          85 : PromoteIsTriggered(void)
    4406                 :             : {
    4407                 :             :     /*
    4408                 :             :      * We check shared state each time only until a standby promotion is
    4409                 :             :      * triggered. We can't trigger a promotion again, so there's no need to
    4410                 :             :      * keep checking after the shared variable has once been seen true.
    4411                 :             :      */
    4412         [ +  + ]:          85 :     if (LocalPromoteIsTriggered)
    4413                 :          56 :         return true;
    4414                 :             : 
    4415                 :          29 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4416                 :          29 :     LocalPromoteIsTriggered = XLogRecoveryCtl->SharedPromoteIsTriggered;
    4417                 :          29 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4418                 :             : 
    4419                 :          29 :     return LocalPromoteIsTriggered;
    4420                 :             : }
    4421                 :             : 
    4422                 :             : static void
    4423                 :          53 : SetPromoteIsTriggered(void)
    4424                 :             : {
    4425                 :          53 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4426                 :          53 :     XLogRecoveryCtl->SharedPromoteIsTriggered = true;
    4427                 :          53 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4428                 :             : 
    4429                 :             :     /*
    4430                 :             :      * Mark the recovery pause state as 'not paused' because the paused state
    4431                 :             :      * ends and promotion continues if a promotion is triggered while recovery
    4432                 :             :      * is paused. Otherwise pg_get_wal_replay_pause_state() can mistakenly
    4433                 :             :      * return 'paused' while a promotion is ongoing.
    4434                 :             :      */
    4435                 :          53 :     SetRecoveryPause(false);
    4436                 :             : 
    4437                 :          53 :     LocalPromoteIsTriggered = true;
    4438                 :          53 : }
    4439                 :             : 
    4440                 :             : /*
    4441                 :             :  * Check whether a promote request has arrived.
    4442                 :             :  */
    4443                 :             : static bool
    4444                 :       13200 : CheckForStandbyTrigger(void)
    4445                 :             : {
    4446         [ +  + ]:       13200 :     if (LocalPromoteIsTriggered)
    4447                 :          59 :         return true;
    4448                 :             : 
    4449   [ +  +  +  - ]:       13141 :     if (IsPromoteSignaled() && CheckPromoteSignal())
    4450                 :             :     {
    4451         [ +  - ]:          53 :         ereport(LOG, (errmsg("received promote request")));
    4452                 :          53 :         RemovePromoteSignalFiles();
    4453                 :          53 :         ResetPromoteSignaled();
    4454                 :          53 :         SetPromoteIsTriggered();
    4455                 :          53 :         return true;
    4456                 :             :     }
    4457                 :             : 
    4458                 :       13088 :     return false;
    4459                 :             : }
    4460                 :             : 
    4461                 :             : /*
    4462                 :             :  * Remove the files signaling a standby promotion request.
    4463                 :             :  */
    4464                 :             : void
    4465                 :        1047 : RemovePromoteSignalFiles(void)
    4466                 :             : {
    4467                 :        1047 :     unlink(PROMOTE_SIGNAL_FILE);
    4468                 :        1047 : }
    4469                 :             : 
    4470                 :             : /*
    4471                 :             :  * Check to see if a promote request has arrived.
    4472                 :             :  */
    4473                 :             : bool
    4474                 :         793 : CheckPromoteSignal(void)
    4475                 :             : {
    4476                 :             :     struct stat stat_buf;
    4477                 :             : 
    4478         [ +  + ]:         793 :     if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
    4479                 :         106 :         return true;
    4480                 :             : 
    4481                 :         687 :     return false;
    4482                 :             : }
    4483                 :             : 
    4484                 :             : /*
    4485                 :             :  * Wake up startup process to replay newly arrived WAL, or to notice that
    4486                 :             :  * failover has been requested.
    4487                 :             :  */
    4488                 :             : void
    4489                 :       48939 : WakeupRecovery(void)
    4490                 :             : {
    4491                 :       48939 :     SetLatch(&XLogRecoveryCtl->recoveryWakeupLatch);
    4492                 :       48939 : }
    4493                 :             : 
    4494                 :             : /*
    4495                 :             :  * Schedule a walreceiver wakeup in the main recovery loop.
    4496                 :             :  */
    4497                 :             : void
    4498                 :           2 : XLogRequestWalReceiverReply(void)
    4499                 :             : {
    4500                 :           2 :     doRequestWalReceiverReply = true;
    4501                 :           2 : }
    4502                 :             : 
    4503                 :             : /*
    4504                 :             :  * Is HotStandby active yet? This is only important in special backends
    4505                 :             :  * since normal backends won't ever be able to connect until this returns
    4506                 :             :  * true. Postmaster knows this by way of signal, not via shared memory.
    4507                 :             :  *
    4508                 :             :  * Unlike testing standbyState, this works in any process that's connected to
    4509                 :             :  * shared memory.  (And note that standbyState alone doesn't tell the truth
    4510                 :             :  * anyway.)
    4511                 :             :  */
    4512                 :             : bool
    4513                 :         170 : HotStandbyActive(void)
    4514                 :             : {
    4515                 :             :     /*
    4516                 :             :      * We check shared state each time only until Hot Standby is active. We
    4517                 :             :      * can't de-activate Hot Standby, so there's no need to keep checking
    4518                 :             :      * after the shared variable has once been seen true.
    4519                 :             :      */
    4520         [ +  + ]:         170 :     if (LocalHotStandbyActive)
    4521                 :          22 :         return true;
    4522                 :             :     else
    4523                 :             :     {
    4524                 :             :         /* spinlock is essential on machines with weak memory ordering! */
    4525                 :         148 :         SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4526                 :         148 :         LocalHotStandbyActive = XLogRecoveryCtl->SharedHotStandbyActive;
    4527                 :         148 :         SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4528                 :             : 
    4529                 :         148 :         return LocalHotStandbyActive;
    4530                 :             :     }
    4531                 :             : }
    4532                 :             : 
    4533                 :             : /*
    4534                 :             :  * Like HotStandbyActive(), but to be used only in WAL replay code,
    4535                 :             :  * where we don't need to ask any other process what the state is.
    4536                 :             :  */
    4537                 :             : static bool
    4538                 :           0 : HotStandbyActiveInReplay(void)
    4539                 :             : {
    4540                 :             :     Assert(AmStartupProcess() || !IsPostmasterEnvironment);
    4541                 :           0 :     return LocalHotStandbyActive;
    4542                 :             : }
    4543                 :             : 
    4544                 :             : /*
    4545                 :             :  * Get latest redo apply position.
    4546                 :             :  *
    4547                 :             :  * Exported to allow WALReceiver to read the pointer directly.
    4548                 :             :  */
    4549                 :             : XLogRecPtr
    4550                 :      119238 : GetXLogReplayRecPtr(TimeLineID *replayTLI)
    4551                 :             : {
    4552                 :             :     XLogRecPtr  recptr;
    4553                 :             :     TimeLineID  tli;
    4554                 :             : 
    4555                 :      119238 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4556                 :      119238 :     recptr = XLogRecoveryCtl->lastReplayedEndRecPtr;
    4557                 :      119238 :     tli = XLogRecoveryCtl->lastReplayedTLI;
    4558                 :      119238 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4559                 :             : 
    4560         [ +  + ]:      119238 :     if (replayTLI)
    4561                 :        2868 :         *replayTLI = tli;
    4562                 :      119238 :     return recptr;
    4563                 :             : }
    4564                 :             : 
    4565                 :             : 
    4566                 :             : /*
    4567                 :             :  * Get position of last applied, or the record being applied.
    4568                 :             :  *
    4569                 :             :  * This is different from GetXLogReplayRecPtr() in that if a WAL
    4570                 :             :  * record is currently being applied, this includes that record.
    4571                 :             :  */
    4572                 :             : XLogRecPtr
    4573                 :        6876 : GetCurrentReplayRecPtr(TimeLineID *replayEndTLI)
    4574                 :             : {
    4575                 :             :     XLogRecPtr  recptr;
    4576                 :             :     TimeLineID  tli;
    4577                 :             : 
    4578                 :        6876 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4579                 :        6876 :     recptr = XLogRecoveryCtl->replayEndRecPtr;
    4580                 :        6876 :     tli = XLogRecoveryCtl->replayEndTLI;
    4581                 :        6876 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4582                 :             : 
    4583         [ +  - ]:        6876 :     if (replayEndTLI)
    4584                 :        6876 :         *replayEndTLI = tli;
    4585                 :        6876 :     return recptr;
    4586                 :             : }
    4587                 :             : 
    4588                 :             : /*
    4589                 :             :  * Save timestamp of latest processed commit/abort record.
    4590                 :             :  *
    4591                 :             :  * We keep this in XLogRecoveryCtl, not a simple static variable, so that it can be
    4592                 :             :  * seen by processes other than the startup process.  Note in particular
    4593                 :             :  * that CreateRestartPoint is executed in the checkpointer.
    4594                 :             :  */
    4595                 :             : static void
    4596                 :       23943 : SetLatestXTime(TimestampTz xtime)
    4597                 :             : {
    4598                 :       23943 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4599                 :       23943 :     XLogRecoveryCtl->recoveryLastXTime = xtime;
    4600                 :       23943 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4601                 :       23943 : }
    4602                 :             : 
    4603                 :             : /*
    4604                 :             :  * Fetch timestamp of latest processed commit/abort record.
    4605                 :             :  */
    4606                 :             : TimestampTz
    4607                 :         373 : GetLatestXTime(void)
    4608                 :             : {
    4609                 :             :     TimestampTz xtime;
    4610                 :             : 
    4611                 :         373 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4612                 :         373 :     xtime = XLogRecoveryCtl->recoveryLastXTime;
    4613                 :         373 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4614                 :             : 
    4615                 :         373 :     return xtime;
    4616                 :             : }
    4617                 :             : 
    4618                 :             : /*
    4619                 :             :  * Save timestamp of the next chunk of WAL records to apply.
    4620                 :             :  *
    4621                 :             :  * We keep this in XLogRecoveryCtl, not a simple static variable, so that it can be
    4622                 :             :  * seen by all backends.
    4623                 :             :  */
    4624                 :             : static void
    4625                 :        8901 : SetCurrentChunkStartTime(TimestampTz xtime)
    4626                 :             : {
    4627                 :        8901 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4628                 :        8901 :     XLogRecoveryCtl->currentChunkStartTime = xtime;
    4629                 :        8901 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4630                 :        8901 : }
    4631                 :             : 
    4632                 :             : /*
    4633                 :             :  * Fetch timestamp of latest processed commit/abort record.
    4634                 :             :  * Startup process maintains an accurate local copy in XLogReceiptTime
    4635                 :             :  */
    4636                 :             : TimestampTz
    4637                 :         268 : GetCurrentChunkReplayStartTime(void)
    4638                 :             : {
    4639                 :             :     TimestampTz xtime;
    4640                 :             : 
    4641                 :         268 :     SpinLockAcquire(&XLogRecoveryCtl->info_lck);
    4642                 :         268 :     xtime = XLogRecoveryCtl->currentChunkStartTime;
    4643                 :         268 :     SpinLockRelease(&XLogRecoveryCtl->info_lck);
    4644                 :             : 
    4645                 :         268 :     return xtime;
    4646                 :             : }
    4647                 :             : 
    4648                 :             : /*
    4649                 :             :  * Returns time of receipt of current chunk of XLOG data, as well as
    4650                 :             :  * whether it was received from streaming replication or from archives.
    4651                 :             :  */
    4652                 :             : void
    4653                 :          28 : GetXLogReceiptTime(TimestampTz *rtime, bool *fromStream)
    4654                 :             : {
    4655                 :             :     /*
    4656                 :             :      * This must be executed in the startup process, since we don't export the
    4657                 :             :      * relevant state to shared memory.
    4658                 :             :      */
    4659                 :             :     Assert(InRecovery);
    4660                 :             : 
    4661                 :          28 :     *rtime = XLogReceiptTime;
    4662                 :          28 :     *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
    4663                 :          28 : }
    4664                 :             : 
    4665                 :             : /*
    4666                 :             :  * Note that text field supplied is a parameter name and does not require
    4667                 :             :  * translation
    4668                 :             :  */
    4669                 :             : void
    4670                 :         730 : RecoveryRequiresIntParameter(const char *param_name, int currValue, int minValue)
    4671                 :             : {
    4672         [ -  + ]:         730 :     if (currValue < minValue)
    4673                 :             :     {
    4674         [ #  # ]:           0 :         if (HotStandbyActiveInReplay())
    4675                 :             :         {
    4676                 :           0 :             bool        warned_for_promote = false;
    4677                 :             : 
    4678         [ #  # ]:           0 :             ereport(WARNING,
    4679                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4680                 :             :                      errmsg("hot standby is not possible because of insufficient parameter settings"),
    4681                 :             :                      errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
    4682                 :             :                                param_name,
    4683                 :             :                                currValue,
    4684                 :             :                                minValue)));
    4685                 :             : 
    4686                 :           0 :             SetRecoveryPause(true);
    4687                 :             : 
    4688         [ #  # ]:           0 :             ereport(LOG,
    4689                 :             :                     (errmsg("recovery has paused"),
    4690                 :             :                      errdetail("If recovery is unpaused, the server will shut down."),
    4691                 :             :                      errhint("You can then restart the server after making the necessary configuration changes.")));
    4692                 :             : 
    4693         [ #  # ]:           0 :             while (GetRecoveryPauseState() != RECOVERY_NOT_PAUSED)
    4694                 :             :             {
    4695                 :           0 :                 ProcessStartupProcInterrupts();
    4696                 :             : 
    4697         [ #  # ]:           0 :                 if (CheckForStandbyTrigger())
    4698                 :             :                 {
    4699         [ #  # ]:           0 :                     if (!warned_for_promote)
    4700         [ #  # ]:           0 :                         ereport(WARNING,
    4701                 :             :                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4702                 :             :                                  errmsg("promotion is not possible because of insufficient parameter settings"),
    4703                 :             : 
    4704                 :             :                         /*
    4705                 :             :                          * Repeat the detail from above so it's easy to find
    4706                 :             :                          * in the log.
    4707                 :             :                          */
    4708                 :             :                                  errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
    4709                 :             :                                            param_name,
    4710                 :             :                                            currValue,
    4711                 :             :                                            minValue),
    4712                 :             :                                  errhint("Restart the server after making the necessary configuration changes.")));
    4713                 :           0 :                     warned_for_promote = true;
    4714                 :             :                 }
    4715                 :             : 
    4716                 :             :                 /*
    4717                 :             :                  * If recovery pause is requested then set it paused.  While
    4718                 :             :                  * we are in the loop, user might resume and pause again so
    4719                 :             :                  * set this every time.
    4720                 :             :                  */
    4721                 :           0 :                 ConfirmRecoveryPaused();
    4722                 :             : 
    4723                 :             :                 /*
    4724                 :             :                  * We wait on a condition variable that will wake us as soon
    4725                 :             :                  * as the pause ends, but we use a timeout so we can check the
    4726                 :             :                  * above conditions periodically too.
    4727                 :             :                  */
    4728                 :           0 :                 ConditionVariableTimedSleep(&XLogRecoveryCtl->recoveryNotPausedCV, 1000,
    4729                 :             :                                             WAIT_EVENT_RECOVERY_PAUSE);
    4730                 :             :             }
    4731                 :           0 :             ConditionVariableCancelSleep();
    4732                 :             :         }
    4733                 :             : 
    4734         [ #  # ]:           0 :         ereport(FATAL,
    4735                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4736                 :             :                  errmsg("recovery aborted because of insufficient parameter settings"),
    4737                 :             :         /* Repeat the detail from above so it's easy to find in the log. */
    4738                 :             :                  errdetail("%s = %d is a lower setting than on the primary server, where its value was %d.",
    4739                 :             :                            param_name,
    4740                 :             :                            currValue,
    4741                 :             :                            minValue),
    4742                 :             :                  errhint("You can restart the server after making the necessary configuration changes.")));
    4743                 :             :     }
    4744                 :         730 : }
    4745                 :             : 
    4746                 :             : 
    4747                 :             : /*
    4748                 :             :  * GUC check_hook for primary_slot_name
    4749                 :             :  */
    4750                 :             : bool
    4751                 :        1479 : check_primary_slot_name(char **newval, void **extra, GucSource source)
    4752                 :             : {
    4753                 :             :     int         err_code;
    4754                 :        1479 :     char       *err_msg = NULL;
    4755                 :        1479 :     char       *err_hint = NULL;
    4756                 :             : 
    4757   [ +  -  +  + ]:        1479 :     if (*newval && strcmp(*newval, "") != 0 &&
    4758         [ -  + ]:         188 :         !ReplicationSlotValidateNameInternal(*newval, false, &err_code,
    4759                 :             :                                              &err_msg, &err_hint))
    4760                 :             :     {
    4761                 :           0 :         GUC_check_errcode(err_code);
    4762                 :           0 :         GUC_check_errdetail("%s", err_msg);
    4763         [ #  # ]:           0 :         if (err_hint != NULL)
    4764                 :           0 :             GUC_check_errhint("%s", err_hint);
    4765                 :           0 :         return false;
    4766                 :             :     }
    4767                 :             : 
    4768                 :        1479 :     return true;
    4769                 :             : }
    4770                 :             : 
    4771                 :             : /*
    4772                 :             :  * Recovery target settings: Only one of the several recovery_target* settings
    4773                 :             :  * may be set.  Setting a second one results in an error.  The global variable
    4774                 :             :  * recoveryTarget tracks which kind of recovery target was chosen.  Other
    4775                 :             :  * variables store the actual target value (for example a string or a xid).
    4776                 :             :  * The assign functions of the parameters check whether a competing parameter
    4777                 :             :  * was already set.  But we want to allow setting the same parameter multiple
    4778                 :             :  * times.  We also want to allow unsetting a parameter and setting a different
    4779                 :             :  * one, so we unset recoveryTarget when the parameter is set to an empty
    4780                 :             :  * string.
    4781                 :             :  *
    4782                 :             :  * XXX this code is broken by design.  Throwing an error from a GUC assign
    4783                 :             :  * hook breaks fundamental assumptions of guc.c.  So long as all the variables
    4784                 :             :  * for which this can happen are PGC_POSTMASTER, the consequences are limited,
    4785                 :             :  * since we'd just abort postmaster startup anyway.  Nonetheless it's likely
    4786                 :             :  * that we have odd behaviors such as unexpected GUC ordering dependencies.
    4787                 :             :  */
    4788                 :             : 
    4789                 :             : pg_noreturn static void
    4790                 :           1 : error_multiple_recovery_targets(void)
    4791                 :             : {
    4792         [ +  - ]:           1 :     ereport(ERROR,
    4793                 :             :             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4794                 :             :              errmsg("multiple recovery targets specified"),
    4795                 :             :              errdetail("At most one of \"recovery_target\", \"recovery_target_lsn\", \"recovery_target_name\", \"recovery_target_time\", \"recovery_target_xid\" may be set.")));
    4796                 :             : }
    4797                 :             : 
    4798                 :             : /*
    4799                 :             :  * GUC check_hook for recovery_target
    4800                 :             :  */
    4801                 :             : bool
    4802                 :        1292 : check_recovery_target(char **newval, void **extra, GucSource source)
    4803                 :             : {
    4804   [ +  +  -  + ]:        1292 :     if (strcmp(*newval, "immediate") != 0 && strcmp(*newval, "") != 0)
    4805                 :             :     {
    4806                 :           0 :         GUC_check_errdetail("The only allowed value is \"immediate\".");
    4807                 :           0 :         return false;
    4808                 :             :     }
    4809                 :        1292 :     return true;
    4810                 :             : }
    4811                 :             : 
    4812                 :             : /*
    4813                 :             :  * GUC assign_hook for recovery_target
    4814                 :             :  */
    4815                 :             : void
    4816                 :        1292 : assign_recovery_target(const char *newval, void *extra)
    4817                 :             : {
    4818         [ -  + ]:        1292 :     if (recoveryTarget != RECOVERY_TARGET_UNSET &&
    4819         [ #  # ]:           0 :         recoveryTarget != RECOVERY_TARGET_IMMEDIATE)
    4820                 :           0 :         error_multiple_recovery_targets();
    4821                 :             : 
    4822   [ +  -  +  + ]:        1292 :     if (newval && strcmp(newval, "") != 0)
    4823                 :           1 :         recoveryTarget = RECOVERY_TARGET_IMMEDIATE;
    4824                 :             :     else
    4825                 :        1291 :         recoveryTarget = RECOVERY_TARGET_UNSET;
    4826                 :        1292 : }
    4827                 :             : 
    4828                 :             : /*
    4829                 :             :  * GUC check_hook for recovery_target_lsn
    4830                 :             :  */
    4831                 :             : bool
    4832                 :        1298 : check_recovery_target_lsn(char **newval, void **extra, GucSource source)
    4833                 :             : {
    4834         [ +  + ]:        1298 :     if (strcmp(*newval, "") != 0)
    4835                 :             :     {
    4836                 :             :         XLogRecPtr  lsn;
    4837                 :             :         XLogRecPtr *myextra;
    4838                 :           8 :         ErrorSaveContext escontext = {T_ErrorSaveContext};
    4839                 :             : 
    4840                 :           8 :         lsn = pg_lsn_in_safe(*newval, (Node *) &escontext);
    4841         [ -  + ]:           8 :         if (escontext.error_occurred)
    4842                 :           0 :             return false;
    4843                 :             : 
    4844                 :           8 :         myextra = (XLogRecPtr *) guc_malloc(LOG, sizeof(XLogRecPtr));
    4845         [ -  + ]:           8 :         if (!myextra)
    4846                 :           0 :             return false;
    4847                 :           8 :         *myextra = lsn;
    4848                 :           8 :         *extra = myextra;
    4849                 :             :     }
    4850                 :        1298 :     return true;
    4851                 :             : }
    4852                 :             : 
    4853                 :             : /*
    4854                 :             :  * GUC assign_hook for recovery_target_lsn
    4855                 :             :  */
    4856                 :             : void
    4857                 :        1298 : assign_recovery_target_lsn(const char *newval, void *extra)
    4858                 :             : {
    4859         [ -  + ]:        1298 :     if (recoveryTarget != RECOVERY_TARGET_UNSET &&
    4860         [ #  # ]:           0 :         recoveryTarget != RECOVERY_TARGET_LSN)
    4861                 :           0 :         error_multiple_recovery_targets();
    4862                 :             : 
    4863   [ +  -  +  + ]:        1298 :     if (newval && strcmp(newval, "") != 0)
    4864                 :             :     {
    4865                 :           8 :         recoveryTarget = RECOVERY_TARGET_LSN;
    4866                 :           8 :         recoveryTargetLSN = *((XLogRecPtr *) extra);
    4867                 :             :     }
    4868                 :             :     else
    4869                 :        1290 :         recoveryTarget = RECOVERY_TARGET_UNSET;
    4870                 :        1298 : }
    4871                 :             : 
    4872                 :             : /*
    4873                 :             :  * GUC check_hook for recovery_target_name
    4874                 :             :  */
    4875                 :             : bool
    4876                 :        1298 : check_recovery_target_name(char **newval, void **extra, GucSource source)
    4877                 :             : {
    4878                 :             :     /* Use the value of newval directly */
    4879         [ -  + ]:        1298 :     if (strlen(*newval) >= MAXFNAMELEN)
    4880                 :             :     {
    4881                 :           0 :         GUC_check_errdetail("\"%s\" is too long (maximum %d characters).",
    4882                 :             :                             "recovery_target_name", MAXFNAMELEN - 1);
    4883                 :           0 :         return false;
    4884                 :             :     }
    4885                 :        1298 :     return true;
    4886                 :             : }
    4887                 :             : 
    4888                 :             : /*
    4889                 :             :  * GUC assign_hook for recovery_target_name
    4890                 :             :  */
    4891                 :             : void
    4892                 :        1298 : assign_recovery_target_name(const char *newval, void *extra)
    4893                 :             : {
    4894         [ -  + ]:        1298 :     if (recoveryTarget != RECOVERY_TARGET_UNSET &&
    4895         [ #  # ]:           0 :         recoveryTarget != RECOVERY_TARGET_NAME)
    4896                 :           0 :         error_multiple_recovery_targets();
    4897                 :             : 
    4898   [ +  -  +  + ]:        1298 :     if (newval && strcmp(newval, "") != 0)
    4899                 :             :     {
    4900                 :           6 :         recoveryTarget = RECOVERY_TARGET_NAME;
    4901                 :           6 :         recoveryTargetName = newval;
    4902                 :             :     }
    4903                 :             :     else
    4904                 :        1292 :         recoveryTarget = RECOVERY_TARGET_UNSET;
    4905                 :        1298 : }
    4906                 :             : 
    4907                 :             : /*
    4908                 :             :  * GUC check_hook for recovery_target_time
    4909                 :             :  *
    4910                 :             :  * The interpretation of the recovery_target_time string can depend on the
    4911                 :             :  * time zone setting, so we need to wait until after all GUC processing is
    4912                 :             :  * done before we can do the final parsing of the string.  This check function
    4913                 :             :  * only does a parsing pass to catch syntax errors, but we store the string
    4914                 :             :  * and parse it again when we need to use it.
    4915                 :             :  */
    4916                 :             : bool
    4917                 :        1294 : check_recovery_target_time(char **newval, void **extra, GucSource source)
    4918                 :             : {
    4919         [ +  + ]:        1294 :     if (strcmp(*newval, "") != 0)
    4920                 :             :     {
    4921                 :             :         /* reject some special values */
    4922         [ +  - ]:           3 :         if (strcmp(*newval, "now") == 0 ||
    4923         [ +  - ]:           3 :             strcmp(*newval, "today") == 0 ||
    4924         [ +  - ]:           3 :             strcmp(*newval, "tomorrow") == 0 ||
    4925         [ -  + ]:           3 :             strcmp(*newval, "yesterday") == 0)
    4926                 :             :         {
    4927                 :           0 :             return false;
    4928                 :             :         }
    4929                 :             : 
    4930                 :             :         /*
    4931                 :             :          * parse timestamp value (see also timestamptz_in())
    4932                 :             :          */
    4933                 :             :         {
    4934                 :           3 :             char       *str = *newval;
    4935                 :             :             fsec_t      fsec;
    4936                 :             :             struct pg_tm tt,
    4937                 :           3 :                        *tm = &tt;
    4938                 :             :             int         tz;
    4939                 :             :             int         dtype;
    4940                 :             :             int         nf;
    4941                 :             :             int         dterr;
    4942                 :             :             char       *field[MAXDATEFIELDS];
    4943                 :             :             int         ftype[MAXDATEFIELDS];
    4944                 :             :             char        workbuf[MAXDATELEN + MAXDATEFIELDS];
    4945                 :             :             DateTimeErrorExtra dtextra;
    4946                 :             :             TimestampTz timestamp;
    4947                 :             : 
    4948                 :           3 :             dterr = ParseDateTime(str, workbuf, sizeof(workbuf),
    4949                 :             :                                   field, ftype, MAXDATEFIELDS, &nf);
    4950         [ +  - ]:           3 :             if (dterr == 0)
    4951                 :           3 :                 dterr = DecodeDateTime(field, ftype, nf,
    4952                 :             :                                        &dtype, tm, &fsec, &tz, &dtextra);
    4953         [ -  + ]:           3 :             if (dterr != 0)
    4954                 :           0 :                 return false;
    4955         [ -  + ]:           3 :             if (dtype != DTK_DATE)
    4956                 :           0 :                 return false;
    4957                 :             : 
    4958         [ -  + ]:           3 :             if (tm2timestamp(tm, fsec, &tz, &timestamp) != 0)
    4959                 :             :             {
    4960                 :           0 :                 GUC_check_errdetail("Timestamp out of range: \"%s\".", str);
    4961                 :           0 :                 return false;
    4962                 :             :             }
    4963                 :             :         }
    4964                 :             :     }
    4965                 :        1294 :     return true;
    4966                 :             : }
    4967                 :             : 
    4968                 :             : /*
    4969                 :             :  * GUC assign_hook for recovery_target_time
    4970                 :             :  */
    4971                 :             : void
    4972                 :        1294 : assign_recovery_target_time(const char *newval, void *extra)
    4973                 :             : {
    4974         [ +  + ]:        1294 :     if (recoveryTarget != RECOVERY_TARGET_UNSET &&
    4975         [ +  - ]:           1 :         recoveryTarget != RECOVERY_TARGET_TIME)
    4976                 :           1 :         error_multiple_recovery_targets();
    4977                 :             : 
    4978   [ +  -  +  + ]:        1293 :     if (newval && strcmp(newval, "") != 0)
    4979                 :           2 :         recoveryTarget = RECOVERY_TARGET_TIME;
    4980                 :             :     else
    4981                 :        1291 :         recoveryTarget = RECOVERY_TARGET_UNSET;
    4982                 :        1293 : }
    4983                 :             : 
    4984                 :             : /*
    4985                 :             :  * GUC check_hook for recovery_target_timeline
    4986                 :             :  */
    4987                 :             : bool
    4988                 :        1295 : check_recovery_target_timeline(char **newval, void **extra, GucSource source)
    4989                 :             : {
    4990                 :             :     RecoveryTargetTimeLineGoal rttg;
    4991                 :             :     RecoveryTargetTimeLineGoal *myextra;
    4992                 :             : 
    4993         [ -  + ]:        1295 :     if (strcmp(*newval, "current") == 0)
    4994                 :           0 :         rttg = RECOVERY_TARGET_TIMELINE_CONTROLFILE;
    4995         [ +  + ]:        1295 :     else if (strcmp(*newval, "latest") == 0)
    4996                 :        1292 :         rttg = RECOVERY_TARGET_TIMELINE_LATEST;
    4997                 :             :     else
    4998                 :             :     {
    4999                 :             :         char       *endp;
    5000                 :             :         uint64      timeline;
    5001                 :             : 
    5002                 :           3 :         rttg = RECOVERY_TARGET_TIMELINE_NUMERIC;
    5003                 :             : 
    5004                 :           3 :         errno = 0;
    5005                 :           3 :         timeline = strtou64(*newval, &endp, 0);
    5006                 :             : 
    5007   [ +  +  +  -  :           3 :         if (*endp != '\0' || errno == EINVAL || errno == ERANGE)
                   -  + ]
    5008                 :             :         {
    5009                 :           1 :             GUC_check_errdetail("\"%s\" is not a valid number.",
    5010                 :             :                                 "recovery_target_timeline");
    5011                 :           3 :             return false;
    5012                 :             :         }
    5013                 :             : 
    5014   [ +  +  +  - ]:           2 :         if (timeline < 1 || timeline > PG_UINT32_MAX)
    5015                 :             :         {
    5016                 :           2 :             GUC_check_errdetail("\"%s\" must be between %u and %u.",
    5017                 :             :                                 "recovery_target_timeline", 1, PG_UINT32_MAX);
    5018                 :           2 :             return false;
    5019                 :             :         }
    5020                 :             :     }
    5021                 :             : 
    5022                 :        1292 :     myextra = (RecoveryTargetTimeLineGoal *) guc_malloc(LOG, sizeof(RecoveryTargetTimeLineGoal));
    5023         [ -  + ]:        1292 :     if (!myextra)
    5024                 :           0 :         return false;
    5025                 :        1292 :     *myextra = rttg;
    5026                 :        1292 :     *extra = myextra;
    5027                 :             : 
    5028                 :        1292 :     return true;
    5029                 :             : }
    5030                 :             : 
    5031                 :             : /*
    5032                 :             :  * GUC assign_hook for recovery_target_timeline
    5033                 :             :  */
    5034                 :             : void
    5035                 :        1292 : assign_recovery_target_timeline(const char *newval, void *extra)
    5036                 :             : {
    5037                 :        1292 :     recoveryTargetTimeLineGoal = *((RecoveryTargetTimeLineGoal *) extra);
    5038         [ -  + ]:        1292 :     if (recoveryTargetTimeLineGoal == RECOVERY_TARGET_TIMELINE_NUMERIC)
    5039                 :           0 :         recoveryTargetTLIRequested = (TimeLineID) strtoul(newval, NULL, 0);
    5040                 :             :     else
    5041                 :        1292 :         recoveryTargetTLIRequested = 0;
    5042                 :        1292 : }
    5043                 :             : 
    5044                 :             : /*
    5045                 :             :  * GUC check_hook for recovery_target_xid
    5046                 :             :  */
    5047                 :             : bool
    5048                 :        1292 : check_recovery_target_xid(char **newval, void **extra, GucSource source)
    5049                 :             : {
    5050         [ +  + ]:        1292 :     if (strcmp(*newval, "") != 0)
    5051                 :             :     {
    5052                 :             :         TransactionId xid;
    5053                 :             :         TransactionId *myextra;
    5054                 :             :         char       *endp;
    5055                 :             :         char       *val;
    5056                 :             : 
    5057                 :           1 :         errno = 0;
    5058                 :             : 
    5059                 :             :         /*
    5060                 :             :          * Consume leading whitespace to determine if number is negative
    5061                 :             :          */
    5062                 :           1 :         val = *newval;
    5063                 :             : 
    5064         [ -  + ]:           1 :         while (isspace((unsigned char) *val))
    5065                 :           0 :             val++;
    5066                 :             : 
    5067                 :             :         /*
    5068                 :             :          * This cast will remove the epoch, if any
    5069                 :             :          */
    5070                 :           1 :         xid = (TransactionId) strtou64(val, &endp, 0);
    5071                 :             : 
    5072   [ +  -  +  -  :           1 :         if (*endp != '\0' || errno == EINVAL || errno == ERANGE || *val == '-')
             +  -  -  + ]
    5073                 :             :         {
    5074                 :           0 :             GUC_check_errdetail("\"%s\" is not a valid number.",
    5075                 :             :                                 "recovery_target_xid");
    5076                 :           0 :             return false;
    5077                 :             :         }
    5078                 :             : 
    5079         [ -  + ]:           1 :         if (xid < FirstNormalTransactionId)
    5080                 :             :         {
    5081                 :           0 :             GUC_check_errdetail("\"%s\" without epoch must be greater than or equal to %u.",
    5082                 :             :                                 "recovery_target_xid",
    5083                 :             :                                 FirstNormalTransactionId);
    5084                 :           0 :             return false;
    5085                 :             :         }
    5086                 :             : 
    5087                 :           1 :         myextra = (TransactionId *) guc_malloc(LOG, sizeof(TransactionId));
    5088         [ -  + ]:           1 :         if (!myextra)
    5089                 :           0 :             return false;
    5090                 :           1 :         *myextra = xid;
    5091                 :           1 :         *extra = myextra;
    5092                 :             :     }
    5093                 :        1292 :     return true;
    5094                 :             : }
    5095                 :             : 
    5096                 :             : /*
    5097                 :             :  * GUC assign_hook for recovery_target_xid
    5098                 :             :  */
    5099                 :             : void
    5100                 :        1292 : assign_recovery_target_xid(const char *newval, void *extra)
    5101                 :             : {
    5102         [ -  + ]:        1292 :     if (recoveryTarget != RECOVERY_TARGET_UNSET &&
    5103         [ #  # ]:           0 :         recoveryTarget != RECOVERY_TARGET_XID)
    5104                 :           0 :         error_multiple_recovery_targets();
    5105                 :             : 
    5106   [ +  -  +  + ]:        1292 :     if (newval && strcmp(newval, "") != 0)
    5107                 :             :     {
    5108                 :           1 :         recoveryTarget = RECOVERY_TARGET_XID;
    5109                 :           1 :         recoveryTargetXid = *((TransactionId *) extra);
    5110                 :             :     }
    5111                 :             :     else
    5112                 :        1291 :         recoveryTarget = RECOVERY_TARGET_UNSET;
    5113                 :        1292 : }
        

Generated by: LCOV version 2.0-1