PostgreSQL Source Code  git master
xlog.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <math.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include "access/clog.h"
#include "access/commit_ts.h"
#include "access/multixact.h"
#include "access/rewriteheap.h"
#include "access/subtrans.h"
#include "access/timeline.h"
#include "access/transam.h"
#include "access/tuptoaster.h"
#include "access/twophase.h"
#include "access/xact.h"
#include "access/xlog_internal.h"
#include "access/xloginsert.h"
#include "access/xlogreader.h"
#include "access/xlogutils.h"
#include "catalog/catversion.h"
#include "catalog/pg_control.h"
#include "catalog/pg_database.h"
#include "commands/tablespace.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "port/atomics.h"
#include "postmaster/bgwriter.h"
#include "postmaster/walwriter.h"
#include "postmaster/startup.h"
#include "replication/basebackup.h"
#include "replication/logical.h"
#include "replication/slot.h"
#include "replication/origin.h"
#include "replication/snapbuild.h"
#include "replication/walreceiver.h"
#include "replication/walsender.h"
#include "storage/bufmgr.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/large_object.h"
#include "storage/latch.h"
#include "storage/pmsignal.h"
#include "storage/predicate.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/reinit.h"
#include "storage/smgr.h"
#include "storage/spin.h"
#include "utils/backend_random.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/ps_status.h"
#include "utils/relmapper.h"
#include "utils/snapmgr.h"
#include "utils/timestamp.h"
#include "pg_trace.h"
Include dependency graph for xlog.c:

Go to the source code of this file.

Data Structures

struct  XLogwrtRqst
 
struct  XLogwrtResult
 
struct  WALInsertLock
 
union  WALInsertLockPadded
 
struct  XLogCtlInsert
 
struct  XLogCtlData
 
struct  XLogPageReadPrivate
 

Macros

#define RECOVERY_COMMAND_FILE   "recovery.conf"
 
#define RECOVERY_COMMAND_DONE   "recovery.done"
 
#define PROMOTE_SIGNAL_FILE   "promote"
 
#define FALLBACK_PROMOTE_SIGNAL_FILE   "fallback_promote"
 
#define NUM_XLOGINSERT_LOCKS   8
 
#define INSERT_FREESPACE(endptr)   (((endptr) % XLOG_BLCKSZ == 0) ? 0 : (XLOG_BLCKSZ - (endptr) % XLOG_BLCKSZ))
 
#define NextBufIdx(idx)   (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
 
#define XLogRecPtrToBufIdx(recptr)   (((recptr) / XLOG_BLCKSZ) % (XLogCtl->XLogCacheBlck + 1))
 
#define UsableBytesInPage   (XLOG_BLCKSZ - SizeOfXLogShortPHD)
 
#define ConvertToXSegs(x, segsize)   (x / ((segsize) / (1024 * 1024)))
 
#define RecoveryRequiresIntParameter(param_name, currValue, minValue)
 

Typedefs

typedef struct XLogwrtRqst XLogwrtRqst
 
typedef struct XLogwrtResult XLogwrtResult
 
typedef union WALInsertLockPadded WALInsertLockPadded
 
typedef enum ExclusiveBackupState ExclusiveBackupState
 
typedef struct XLogCtlInsert XLogCtlInsert
 
typedef struct XLogCtlData XLogCtlData
 
typedef struct XLogPageReadPrivate XLogPageReadPrivate
 

Enumerations

enum  ExclusiveBackupState { EXCLUSIVE_BACKUP_NONE = 0, EXCLUSIVE_BACKUP_STARTING, EXCLUSIVE_BACKUP_IN_PROGRESS, EXCLUSIVE_BACKUP_STOPPING }
 
enum  XLogSource { XLOG_FROM_ANY = 0, XLOG_FROM_ARCHIVE, XLOG_FROM_PG_WAL, XLOG_FROM_STREAM }
 

Functions

static void readRecoveryCommandFile (void)
 
static void exitArchiveRecovery (TimeLineID endTLI, XLogRecPtr endOfLog)
 
static bool recoveryStopsBefore (XLogReaderState *record)
 
static bool recoveryStopsAfter (XLogReaderState *record)
 
static void recoveryPausesHere (void)
 
static bool recoveryApplyDelay (XLogReaderState *record)
 
static void SetLatestXTime (TimestampTz xtime)
 
static void SetCurrentChunkStartTime (TimestampTz xtime)
 
static void CheckRequiredParameterValues (void)
 
static void XLogReportParameters (void)
 
static void checkTimeLineSwitch (XLogRecPtr lsn, TimeLineID newTLI, TimeLineID prevTLI)
 
static void LocalSetXLogInsertAllowed (void)
 
static void CreateEndOfRecoveryRecord (void)
 
static void CheckPointGuts (XLogRecPtr checkPointRedo, int flags)
 
static void KeepLogSeg (XLogRecPtr recptr, XLogSegNo *logSegNo)
 
static XLogRecPtr XLogGetReplicationSlotMinimumLSN (void)
 
static void AdvanceXLInsertBuffer (XLogRecPtr upto, bool opportunistic)
 
static bool XLogCheckpointNeeded (XLogSegNo new_segno)
 
static void XLogWrite (XLogwrtRqst WriteRqst, bool flexible)
 
static bool InstallXLogFileSegment (XLogSegNo *segno, char *tmppath, bool find_free, XLogSegNo max_segno, bool use_lock)
 
static int XLogFileRead (XLogSegNo segno, int emode, TimeLineID tli, int source, bool notfoundOk)
 
static int XLogFileReadAnyTLI (XLogSegNo segno, int emode, int source)
 
static int XLogPageRead (XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf, TimeLineID *readTLI)
 
static bool WaitForWALToBecomeAvailable (XLogRecPtr RecPtr, bool randAccess, bool fetching_ckpt, XLogRecPtr tliRecPtr)
 
static int emode_for_corrupt_record (int emode, XLogRecPtr RecPtr)
 
static void XLogFileClose (void)
 
static void PreallocXlogFiles (XLogRecPtr endptr)
 
static void RemoveOldXlogFiles (XLogSegNo segno, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
 
static void RemoveXlogFile (const char *segname, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
 
static void UpdateLastRemovedPtr (char *filename)
 
static void ValidateXLOGDirectoryStructure (void)
 
static void CleanupBackupHistory (void)
 
static void UpdateMinRecoveryPoint (XLogRecPtr lsn, bool force)
 
static XLogRecordReadRecord (XLogReaderState *xlogreader, XLogRecPtr RecPtr, int emode, bool fetching_ckpt)
 
static void CheckRecoveryConsistency (void)
 
static XLogRecordReadCheckpointRecord (XLogReaderState *xlogreader, XLogRecPtr RecPtr, int whichChkpti, bool report)
 
static bool rescanLatestTimeLine (void)
 
static void WriteControlFile (void)
 
static void ReadControlFile (void)
 
static char * str_time (pg_time_t tnow)
 
static bool CheckForStandbyTrigger (void)
 
static void xlog_outdesc (StringInfo buf, XLogReaderState *record)
 
static void pg_start_backup_callback (int code, Datum arg)
 
static void pg_stop_backup_callback (int code, Datum arg)
 
static bool read_backup_label (XLogRecPtr *checkPointLoc, bool *backupEndRequired, bool *backupFromStandby)
 
static bool read_tablespace_map (List **tablespaces)
 
static void rm_redo_error_callback (void *arg)
 
static int get_sync_bit (int method)
 
static void CopyXLogRecordToWAL (int write_len, bool isLogSwitch, XLogRecData *rdata, XLogRecPtr StartPos, XLogRecPtr EndPos)
 
static void ReserveXLogInsertLocation (int size, XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
 
static bool ReserveXLogSwitch (XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
 
static XLogRecPtr WaitXLogInsertionsToFinish (XLogRecPtr upto)
 
static char * GetXLogBuffer (XLogRecPtr ptr)
 
static XLogRecPtr XLogBytePosToRecPtr (uint64 bytepos)
 
static XLogRecPtr XLogBytePosToEndRecPtr (uint64 bytepos)
 
static uint64 XLogRecPtrToBytePos (XLogRecPtr ptr)
 
static void checkXLogConsistency (XLogReaderState *record)
 
static void WALInsertLockAcquire (void)
 
static void WALInsertLockAcquireExclusive (void)
 
static void WALInsertLockRelease (void)
 
static void WALInsertLockUpdateInsertingAt (XLogRecPtr insertingAt)
 
XLogRecPtr XLogInsertRecord (XLogRecData *rdata, XLogRecPtr fpw_lsn, uint8 flags)
 
static void CalculateCheckpointSegments (void)
 
void assign_max_wal_size (int newval, void *extra)
 
void assign_checkpoint_completion_target (double newval, void *extra)
 
static XLogSegNo XLOGfileslop (XLogRecPtr PriorRedoPtr)
 
void XLogSetAsyncXactLSN (XLogRecPtr asyncXactLSN)
 
void XLogSetReplicationSlotMinimumLSN (XLogRecPtr lsn)
 
void XLogFlush (XLogRecPtr record)
 
bool XLogBackgroundFlush (void)
 
bool XLogNeedsFlush (XLogRecPtr record)
 
int XLogFileInit (XLogSegNo logsegno, bool *use_existent, bool use_lock)
 
static void XLogFileCopy (XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno, int upto)
 
int XLogFileOpen (XLogSegNo segno)
 
void CheckXLogRemoved (XLogSegNo segno, TimeLineID tli)
 
XLogSegNo XLogGetLastRemovedSegno (void)
 
static void RemoveNonParentXlogFiles (XLogRecPtr switchpoint, TimeLineID newTLI)
 
void UpdateControlFile (void)
 
uint64 GetSystemIdentifier (void)
 
char * GetMockAuthenticationNonce (void)
 
bool DataChecksumsEnabled (void)
 
XLogRecPtr GetFakeLSNForUnloggedRel (void)
 
static int XLOGChooseNumBuffers (void)
 
bool check_wal_buffers (int *newval, void **extra, GucSource source)
 
void LocalProcessControlFile (bool reset)
 
Size XLOGShmemSize (void)
 
void XLOGShmemInit (void)
 
void BootStrapXLOG (void)
 
static bool getRecordTimestamp (XLogReaderState *record, TimestampTz *recordXtime)
 
bool RecoveryIsPaused (void)
 
void SetRecoveryPause (bool recoveryPause)
 
TimestampTz GetLatestXTime (void)
 
TimestampTz GetCurrentChunkReplayStartTime (void)
 
void GetXLogReceiptTime (TimestampTz *rtime, bool *fromStream)
 
void StartupXLOG (void)
 
bool RecoveryInProgress (void)
 
bool HotStandbyActive (void)
 
bool HotStandbyActiveInReplay (void)
 
bool XLogInsertAllowed (void)
 
void InitXLOGAccess (void)
 
XLogRecPtr GetRedoRecPtr (void)
 
void GetFullPageWriteInfo (XLogRecPtr *RedoRecPtr_p, bool *doPageWrites_p)
 
XLogRecPtr GetInsertRecPtr (void)
 
XLogRecPtr GetFlushRecPtr (void)
 
XLogRecPtr GetLastImportantRecPtr (void)
 
pg_time_t GetLastSegSwitchData (XLogRecPtr *lastSwitchLSN)
 
void GetNextXidAndEpoch (TransactionId *xid, uint32 *epoch)
 
void ShutdownXLOG (int code, Datum arg)
 
static void LogCheckpointStart (int flags, bool restartpoint)
 
static void LogCheckpointEnd (bool restartpoint)
 
static void UpdateCheckPointDistanceEstimate (uint64 nbytes)
 
void CreateCheckPoint (int flags)
 
static void RecoveryRestartPoint (const CheckPoint *checkPoint)
 
bool CreateRestartPoint (int flags)
 
void XLogPutNextOid (Oid nextOid)
 
XLogRecPtr RequestXLogSwitch (bool mark_unimportant)
 
XLogRecPtr XLogRestorePoint (const char *rpName)
 
void UpdateFullPageWrites (void)
 
void xlog_redo (XLogReaderState *record)
 
void assign_xlog_sync_method (int new_sync_method, void *extra)
 
void issue_xlog_fsync (int fd, XLogSegNo segno)
 
char * XLogFileNameP (TimeLineID tli, XLogSegNo segno)
 
XLogRecPtr do_pg_start_backup (const char *backupidstr, bool fast, TimeLineID *starttli_p, StringInfo labelfile, DIR *tblspcdir, List **tablespaces, StringInfo tblspcmapfile, bool infotbssize, bool needtblspcmapfile)
 
SessionBackupState get_backup_status (void)
 
XLogRecPtr do_pg_stop_backup (char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
 
void do_pg_abort_backup (void)
 
XLogRecPtr GetXLogReplayRecPtr (TimeLineID *replayTLI)
 
XLogRecPtr GetXLogInsertRecPtr (void)
 
XLogRecPtr GetXLogWriteRecPtr (void)
 
void GetOldestRestartPoint (XLogRecPtr *oldrecptr, TimeLineID *oldtli)
 
bool BackupInProgress (void)
 
void CancelBackup (void)
 
void RemovePromoteSignalFiles (void)
 
bool CheckPromoteSignal (void)
 
void WakeupRecovery (void)
 
void SetWalWriterSleeping (bool sleeping)
 
void XLogRequestWalReceiverReply (void)
 

Variables

uint32 bootstrap_data_checksum_version
 
int max_wal_size_mb = 1024
 
int min_wal_size_mb = 80
 
int wal_keep_segments = 0
 
int XLOGbuffers = -1
 
int XLogArchiveTimeout = 0
 
int XLogArchiveMode = ARCHIVE_MODE_OFF
 
char * XLogArchiveCommand = NULL
 
bool EnableHotStandby = false
 
bool fullPageWrites = true
 
bool wal_log_hints = false
 
bool wal_compression = false
 
char * wal_consistency_checking_string = NULL
 
boolwal_consistency_checking = NULL
 
bool log_checkpoints = false
 
int sync_method = DEFAULT_SYNC_METHOD
 
int wal_level = WAL_LEVEL_MINIMAL
 
int CommitDelay = 0
 
int CommitSiblings = 5
 
int wal_retrieve_retry_interval = 5000
 
int wal_segment_size = DEFAULT_XLOG_SEG_SIZE
 
int CheckPointSegments
 
static double CheckPointDistanceEstimate = 0
 
static double PrevCheckPointDistance = 0
 
const struct config_enum_entry sync_method_options []
 
const struct config_enum_entry archive_mode_options []
 
CheckpointStatsData CheckpointStats
 
TimeLineID ThisTimeLineID = 0
 
bool InRecovery = false
 
HotStandbyState standbyState = STANDBY_DISABLED
 
static XLogRecPtr LastRec
 
static XLogRecPtr receivedUpto = 0
 
static TimeLineID receiveTLI = 0
 
static bool lastFullPageWrites
 
static bool LocalRecoveryInProgress = true
 
static bool LocalHotStandbyActive = false
 
static int LocalXLogInsertAllowed = -1
 
bool ArchiveRecoveryRequested = false
 
bool InArchiveRecovery = false
 
static bool restoredFromArchive = false
 
static char * replay_image_masked = NULL
 
static char * master_image_masked = NULL
 
char * recoveryRestoreCommand = NULL
 
static char * recoveryEndCommand = NULL
 
static char * archiveCleanupCommand = NULL
 
static RecoveryTargetType recoveryTarget = RECOVERY_TARGET_UNSET
 
static bool recoveryTargetInclusive = true
 
static RecoveryTargetAction recoveryTargetAction = RECOVERY_TARGET_ACTION_PAUSE
 
static TransactionId recoveryTargetXid
 
static TimestampTz recoveryTargetTime
 
static char * recoveryTargetName
 
static XLogRecPtr recoveryTargetLSN
 
static int recovery_min_apply_delay = 0
 
static TimestampTz recoveryDelayUntilTime
 
static bool StandbyModeRequested = false
 
static char * PrimaryConnInfo = NULL
 
static char * PrimarySlotName = NULL
 
static char * TriggerFile = NULL
 
bool StandbyMode = false
 
static bool fast_promote = false
 
static TransactionId recoveryStopXid
 
static TimestampTz recoveryStopTime
 
static XLogRecPtr recoveryStopLSN
 
static char recoveryStopName [MAXFNAMELEN]
 
static bool recoveryStopAfter
 
static TimeLineID recoveryTargetTLI
 
static bool recoveryTargetIsLatest = false
 
static ListexpectedTLEs
 
static TimeLineID curFileTLI
 
XLogRecPtr ProcLastRecPtr = InvalidXLogRecPtr
 
XLogRecPtr XactLastRecEnd = InvalidXLogRecPtr
 
XLogRecPtr XactLastCommitEnd = InvalidXLogRecPtr
 
static XLogRecPtr RedoRecPtr
 
static bool doPageWrites
 
static bool doRequestWalReceiverReply
 
static XLogRecPtr RedoStartLSN = InvalidXLogRecPtr
 
static SessionBackupState sessionBackupState = SESSION_BACKUP_NONE
 
static XLogCtlDataXLogCtl = NULL
 
static WALInsertLockPaddedWALInsertLocks = NULL
 
static ControlFileDataControlFile = NULL
 
static int UsableBytesInSegment
 
static XLogwrtResult LogwrtResult = {0, 0}
 
static const char * xlogSourceNames [] = {"any", "archive", "pg_wal", "stream"}
 
static int openLogFile = -1
 
static XLogSegNo openLogSegNo = 0
 
static uint32 openLogOff = 0
 
static int readFile = -1
 
static XLogSegNo readSegNo = 0
 
static uint32 readOff = 0
 
static uint32 readLen = 0
 
static XLogSource readSource = 0
 
static XLogSource currentSource = 0
 
static bool lastSourceFailed = false
 
static TimestampTz XLogReceiptTime = 0
 
static XLogSource XLogReceiptSource = 0
 
static XLogRecPtr ReadRecPtr
 
static XLogRecPtr EndRecPtr
 
static XLogRecPtr minRecoveryPoint
 
static TimeLineID minRecoveryPointTLI
 
static bool updateMinRecoveryPoint = true
 
bool reachedConsistency = false
 
static bool InRedo = false
 
static bool bgwriterLaunched = false
 
static int MyLockNo = 0
 
static bool holdingAllLocks = false
 

Macro Definition Documentation

◆ ConvertToXSegs

#define ConvertToXSegs (   x,
  segsize 
)    (x / ((segsize) / (1024 * 1024)))

Definition at line 741 of file xlog.c.

Referenced by CalculateCheckpointSegments(), ReadControlFile(), and XLOGfileslop().

◆ FALLBACK_PROMOTE_SIGNAL_FILE

#define FALLBACK_PROMOTE_SIGNAL_FILE   "fallback_promote"

Definition at line 85 of file xlog.c.

Referenced by CheckForStandbyTrigger(), CheckPromoteSignal(), and RemovePromoteSignalFiles().

◆ INSERT_FREESPACE

#define INSERT_FREESPACE (   endptr)    (((endptr) % XLOG_BLCKSZ == 0) ? 0 : (XLOG_BLCKSZ - (endptr) % XLOG_BLCKSZ))

Definition at line 721 of file xlog.c.

Referenced by CopyXLogRecordToWAL(), and CreateCheckPoint().

◆ NextBufIdx

#define NextBufIdx (   idx)    (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))

Definition at line 725 of file xlog.c.

Referenced by XLogWrite().

◆ NUM_XLOGINSERT_LOCKS

◆ PROMOTE_SIGNAL_FILE

#define PROMOTE_SIGNAL_FILE   "promote"

Definition at line 84 of file xlog.c.

Referenced by CheckForStandbyTrigger(), CheckPromoteSignal(), and RemovePromoteSignalFiles().

◆ RECOVERY_COMMAND_DONE

#define RECOVERY_COMMAND_DONE   "recovery.done"

Definition at line 83 of file xlog.c.

Referenced by exitArchiveRecovery().

◆ RECOVERY_COMMAND_FILE

#define RECOVERY_COMMAND_FILE   "recovery.conf"

Definition at line 82 of file xlog.c.

Referenced by exitArchiveRecovery(), and readRecoveryCommandFile().

◆ RecoveryRequiresIntParameter

#define RecoveryRequiresIntParameter (   param_name,
  currValue,
  minValue 
)
Value:
do { \
if ((currValue) < (minValue)) \
ereport(ERROR, \
(errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
errmsg("hot standby is not possible because " \
"%s = %d is a lower setting than on the master server " \
"(its value was %d)", \
param_name, \
currValue, \
minValue))); \
} while(0)
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
int errmsg(const char *fmt,...)
Definition: elog.c:797

Definition at line 6198 of file xlog.c.

Referenced by CheckRequiredParameterValues().

◆ UsableBytesInPage

#define UsableBytesInPage   (XLOG_BLCKSZ - SizeOfXLogShortPHD)

◆ XLogRecPtrToBufIdx

#define XLogRecPtrToBufIdx (   recptr)    (((recptr) / XLOG_BLCKSZ) % (XLogCtl->XLogCacheBlck + 1))

Definition at line 732 of file xlog.c.

Referenced by AdvanceXLInsertBuffer(), GetXLogBuffer(), StartupXLOG(), and XLogWrite().

Typedef Documentation

◆ ExclusiveBackupState

◆ WALInsertLockPadded

◆ XLogCtlData

◆ XLogCtlInsert

◆ XLogPageReadPrivate

◆ XLogwrtResult

◆ XLogwrtRqst

Enumeration Type Documentation

◆ ExclusiveBackupState

Enumerator
EXCLUSIVE_BACKUP_NONE 
EXCLUSIVE_BACKUP_STARTING 
EXCLUSIVE_BACKUP_IN_PROGRESS 
EXCLUSIVE_BACKUP_STOPPING 

Definition at line 500 of file xlog.c.

◆ XLogSource

enum XLogSource
Enumerator
XLOG_FROM_ANY 
XLOG_FROM_ARCHIVE 
XLOG_FROM_PG_WAL 
XLOG_FROM_STREAM 

Definition at line 757 of file xlog.c.

758 {
759  XLOG_FROM_ANY = 0, /* request to read WAL from any source */
760  XLOG_FROM_ARCHIVE, /* restored using restore_command */
761  XLOG_FROM_PG_WAL, /* existing file in pg_wal */
762  XLOG_FROM_STREAM /* streamed from master */
763 } XLogSource;
XLogSource
Definition: xlog.c:757

Function Documentation

◆ AdvanceXLInsertBuffer()

static void AdvanceXLInsertBuffer ( XLogRecPtr  upto,
bool  opportunistic 
)
static

Definition at line 2047 of file xlog.c.

References Assert, DEBUG1, elog, XLogwrtRqst::Flush, XLogCtlInsert::forcePageWrites, XLogCtlData::info_lck, XLogCtlData::InitializedUpTo, Insert(), XLogCtlData::Insert, InvalidXLogRecPtr, XLogCtlData::LogwrtResult, XLogCtlData::LogwrtRqst, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MemSet, XLogCtlData::pages, pg_write_barrier, SpinLockAcquire, SpinLockRelease, ControlFileData::system_identifier, ThisTimeLineID, WaitXLogInsertionsToFinish(), wal_segment_size, XLogwrtRqst::Write, XLogwrtResult::Write, XLogCtlData::xlblocks, XLOG_PAGE_MAGIC, XLogRecPtrToBufIdx, XLogSegmentOffset, XLogWrite(), XLP_BKP_REMOVABLE, XLP_LONG_HEADER, XLogLongPageHeaderData::xlp_seg_size, XLogLongPageHeaderData::xlp_sysid, and XLogLongPageHeaderData::xlp_xlog_blcksz.

Referenced by CopyXLogRecordToWAL(), GetXLogBuffer(), and XLogBackgroundFlush().

2048 {
2050  int nextidx;
2051  XLogRecPtr OldPageRqstPtr;
2052  XLogwrtRqst WriteRqst;
2053  XLogRecPtr NewPageEndPtr = InvalidXLogRecPtr;
2054  XLogRecPtr NewPageBeginPtr;
2055  XLogPageHeader NewPage;
2056  int npages = 0;
2057 
2058  LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2059 
2060  /*
2061  * Now that we have the lock, check if someone initialized the page
2062  * already.
2063  */
2064  while (upto >= XLogCtl->InitializedUpTo || opportunistic)
2065  {
2067 
2068  /*
2069  * Get ending-offset of the buffer page we need to replace (this may
2070  * be zero if the buffer hasn't been used yet). Fall through if it's
2071  * already written out.
2072  */
2073  OldPageRqstPtr = XLogCtl->xlblocks[nextidx];
2074  if (LogwrtResult.Write < OldPageRqstPtr)
2075  {
2076  /*
2077  * Nope, got work to do. If we just want to pre-initialize as much
2078  * as we can without flushing, give up now.
2079  */
2080  if (opportunistic)
2081  break;
2082 
2083  /* Before waiting, get info_lck and update LogwrtResult */
2085  if (XLogCtl->LogwrtRqst.Write < OldPageRqstPtr)
2086  XLogCtl->LogwrtRqst.Write = OldPageRqstPtr;
2089 
2090  /*
2091  * Now that we have an up-to-date LogwrtResult value, see if we
2092  * still need to write it or if someone else already did.
2093  */
2094  if (LogwrtResult.Write < OldPageRqstPtr)
2095  {
2096  /*
2097  * Must acquire write lock. Release WALBufMappingLock first,
2098  * to make sure that all insertions that we need to wait for
2099  * can finish (up to this same position). Otherwise we risk
2100  * deadlock.
2101  */
2102  LWLockRelease(WALBufMappingLock);
2103 
2104  WaitXLogInsertionsToFinish(OldPageRqstPtr);
2105 
2106  LWLockAcquire(WALWriteLock, LW_EXCLUSIVE);
2107 
2109  if (LogwrtResult.Write >= OldPageRqstPtr)
2110  {
2111  /* OK, someone wrote it already */
2112  LWLockRelease(WALWriteLock);
2113  }
2114  else
2115  {
2116  /* Have to write it ourselves */
2117  TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2118  WriteRqst.Write = OldPageRqstPtr;
2119  WriteRqst.Flush = 0;
2120  XLogWrite(WriteRqst, false);
2121  LWLockRelease(WALWriteLock);
2122  TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
2123  }
2124  /* Re-acquire WALBufMappingLock and retry */
2125  LWLockAcquire(WALBufMappingLock, LW_EXCLUSIVE);
2126  continue;
2127  }
2128  }
2129 
2130  /*
2131  * Now the next buffer slot is free and we can set it up to be the
2132  * next output page.
2133  */
2134  NewPageBeginPtr = XLogCtl->InitializedUpTo;
2135  NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2136 
2137  Assert(XLogRecPtrToBufIdx(NewPageBeginPtr) == nextidx);
2138 
2139  NewPage = (XLogPageHeader) (XLogCtl->pages + nextidx * (Size) XLOG_BLCKSZ);
2140 
2141  /*
2142  * Be sure to re-zero the buffer so that bytes beyond what we've
2143  * written will look like zeroes and not valid XLOG records...
2144  */
2145  MemSet((char *) NewPage, 0, XLOG_BLCKSZ);
2146 
2147  /*
2148  * Fill the new page's header
2149  */
2150  NewPage->xlp_magic = XLOG_PAGE_MAGIC;
2151 
2152  /* NewPage->xlp_info = 0; */ /* done by memset */
2153  NewPage->xlp_tli = ThisTimeLineID;
2154  NewPage->xlp_pageaddr = NewPageBeginPtr;
2155 
2156  /* NewPage->xlp_rem_len = 0; */ /* done by memset */
2157 
2158  /*
2159  * If online backup is not in progress, mark the header to indicate
2160  * that* WAL records beginning in this page have removable backup
2161  * blocks. This allows the WAL archiver to know whether it is safe to
2162  * compress archived WAL data by transforming full-block records into
2163  * the non-full-block format. It is sufficient to record this at the
2164  * page level because we force a page switch (in fact a segment
2165  * switch) when starting a backup, so the flag will be off before any
2166  * records can be written during the backup. At the end of a backup,
2167  * the last page will be marked as all unsafe when perhaps only part
2168  * is unsafe, but at worst the archiver would miss the opportunity to
2169  * compress a few records.
2170  */
2171  if (!Insert->forcePageWrites)
2172  NewPage->xlp_info |= XLP_BKP_REMOVABLE;
2173 
2174  /*
2175  * If first page of an XLOG segment file, make it a long header.
2176  */
2177  if ((XLogSegmentOffset(NewPage->xlp_pageaddr, wal_segment_size)) == 0)
2178  {
2179  XLogLongPageHeader NewLongPage = (XLogLongPageHeader) NewPage;
2180 
2181  NewLongPage->xlp_sysid = ControlFile->system_identifier;
2182  NewLongPage->xlp_seg_size = wal_segment_size;
2183  NewLongPage->xlp_xlog_blcksz = XLOG_BLCKSZ;
2184  NewPage->xlp_info |= XLP_LONG_HEADER;
2185  }
2186 
2187  /*
2188  * Make sure the initialization of the page becomes visible to others
2189  * before the xlblocks update. GetXLogBuffer() reads xlblocks without
2190  * holding a lock.
2191  */
2192  pg_write_barrier();
2193 
2194  *((volatile XLogRecPtr *) &XLogCtl->xlblocks[nextidx]) = NewPageEndPtr;
2195 
2196  XLogCtl->InitializedUpTo = NewPageEndPtr;
2197 
2198  npages++;
2199  }
2200  LWLockRelease(WALBufMappingLock);
2201 
2202 #ifdef WAL_DEBUG
2203  if (XLOG_DEBUG && npages > 0)
2204  {
2205  elog(DEBUG1, "initialized %d pages, up to %X/%X",
2206  npages, (uint32) (NewPageEndPtr >> 32), (uint32) NewPageEndPtr);
2207  }
2208 #endif
2209 }
XLogRecPtr InitializedUpTo
Definition: xlog.c:613
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
int wal_segment_size
Definition: xlog.c:113
XLogRecPtr * xlblocks
Definition: xlog.c:621
static XLogwrtResult LogwrtResult
Definition: xlog.c:751
slock_t info_lck
Definition: xlog.c:704
#define MemSet(start, val, len)
Definition: c.h:853
static XLogRecPtr WaitXLogInsertionsToFinish(XLogRecPtr upto)
Definition: xlog.c:1710
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:57
XLogCtlInsert Insert
Definition: xlog.c:577
XLogRecPtr Flush
Definition: xlog.c:420
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:74
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define XLP_BKP_REMOVABLE
Definition: xlog_internal.h:81
bool forcePageWrites
Definition: xlog.c:551
uint64 system_identifier
Definition: pg_control.h:106
#define XLOG_PAGE_MAGIC
Definition: xlog_internal.h:34
XLogwrtResult LogwrtResult
Definition: xlog.c:601
unsigned int uint32
Definition: c.h:296
static void Insert(File file)
Definition: fd.c:1059
TimeLineID xlp_tli
Definition: xlog_internal.h:40
static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible)
Definition: xlog.c:2337
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr Write
Definition: xlog.c:419
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
static ControlFileData * ControlFile
Definition: xlog.c:715
XLogwrtRqst LogwrtRqst
Definition: xlog.c:580
TimeLineID ThisTimeLineID
Definition: xlog.c:181
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:670
#define XLP_LONG_HEADER
Definition: xlog_internal.h:79
size_t Size
Definition: c.h:404
static XLogCtlData * XLogCtl
Definition: xlog.c:707
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
#define XLogRecPtrToBufIdx(recptr)
Definition: xlog.c:732
XLogRecPtr Write
Definition: xlog.c:425
#define pg_write_barrier()
Definition: atomics.h:162
#define elog
Definition: elog.h:219
char * pages
Definition: xlog.c:620

◆ assign_checkpoint_completion_target()

void assign_checkpoint_completion_target ( double  newval,
void *  extra 
)

Definition at line 2252 of file xlog.c.

References CalculateCheckpointSegments(), CheckPointCompletionTarget, and newval.

2253 {
2256 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2216
#define newval
double CheckPointCompletionTarget
Definition: checkpointer.c:147

◆ assign_max_wal_size()

void assign_max_wal_size ( int  newval,
void *  extra 
)

Definition at line 2245 of file xlog.c.

References CalculateCheckpointSegments(), max_wal_size_mb, and newval.

2246 {
2249 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2216
int max_wal_size_mb
Definition: xlog.c:89
#define newval

◆ assign_xlog_sync_method()

void assign_xlog_sync_method ( int  new_sync_method,
void *  extra 
)

Definition at line 10090 of file xlog.c.

References ereport, errcode_for_file_access(), errmsg(), get_sync_bit(), openLogFile, openLogSegNo, PANIC, pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), sync_method, ThisTimeLineID, WAIT_EVENT_WAL_SYNC_METHOD_ASSIGN, XLogFileClose(), and XLogFileNameP().

10091 {
10092  if (sync_method != new_sync_method)
10093  {
10094  /*
10095  * To ensure that no blocks escape unsynced, force an fsync on the
10096  * currently open log segment (if any). Also, if the open flag is
10097  * changing, close the log file so it will be reopened (with new flag
10098  * bit) at next use.
10099  */
10100  if (openLogFile >= 0)
10101  {
10103  if (pg_fsync(openLogFile) != 0)
10104  ereport(PANIC,
10106  errmsg("could not fsync log segment %s: %m",
10109  if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
10110  XLogFileClose();
10111  }
10112  }
10113 }
static int get_sync_bit(int method)
Definition: xlog.c:10034
#define PANIC
Definition: elog.h:53
static XLogSegNo openLogSegNo
Definition: xlog.c:775
static void XLogFileClose(void)
Definition: xlog.c:3707
char * XLogFileNameP(TimeLineID tli, XLogSegNo segno)
Definition: xlog.c:10166
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
#define ereport(elevel, rest)
Definition: elog.h:122
static int openLogFile
Definition: xlog.c:774
TimeLineID ThisTimeLineID
Definition: xlog.c:181
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
int sync_method
Definition: xlog.c:103
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync(int fd)
Definition: fd.c:338

◆ BackupInProgress()

bool BackupInProgress ( void  )

Definition at line 11384 of file xlog.c.

References BACKUP_LABEL_FILE, and stat.

Referenced by pg_is_in_backup(), and PostmasterStateMachine().

11385 {
11386  struct stat stat_buf;
11387 
11388  return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
11389 }
struct stat stat_buf
Definition: pg_standby.c:103
#define stat(a, b)
Definition: win32_port.h:266
#define BACKUP_LABEL_FILE
Definition: xlog.h:322

◆ BootStrapXLOG()

void BootStrapXLOG ( void  )

Definition at line 5003 of file xlog.c.

References AdvanceOldestClogXid(), Assert, bootstrap_data_checksum_version, BootStrapCLOG(), BootStrapCommitTs(), BootStrapMultiXact(), BootStrapSUBTRANS(), buffer, ControlFileData::checkPoint, ControlFileData::checkPointCopy, close, COMP_CRC32C, ControlFileData::data_checksum_version, DB_SHUTDOWNED, ereport, errcode(), errcode_for_file_access(), errmsg(), FIN_CRC32C, FirstBootstrapObjectId, FirstMultiXactId, FirstNormalTransactionId, CheckPoint::fullPageWrites, fullPageWrites, gettimeofday(), INIT_CRC32C, InvalidTransactionId, max_locks_per_xact, ControlFileData::max_locks_per_xact, max_prepared_xacts, ControlFileData::max_prepared_xacts, max_worker_processes, ControlFileData::max_worker_processes, MaxConnections, ControlFileData::MaxConnections, MOCK_AUTH_NONCE_LEN, ControlFileData::mock_authentication_nonce, MultiXactSetNextMXact(), CheckPoint::newestCommitTsXid, CheckPoint::nextMulti, CheckPoint::nextMultiOffset, CheckPoint::nextOid, VariableCacheData::nextOid, CheckPoint::nextXid, VariableCacheData::nextXid, CheckPoint::nextXidEpoch, offsetof, VariableCacheData::oidCount, CheckPoint::oldestActiveXid, CheckPoint::oldestCommitTsXid, CheckPoint::oldestMulti, CheckPoint::oldestMultiDB, CheckPoint::oldestXid, CheckPoint::oldestXidDB, openLogFile, palloc(), PANIC, pfree(), pg_backend_random(), pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), CheckPoint::PrevTimeLineID, ReadControlFile(), CheckPoint::redo, SetCommitTsLimit(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemVariableCache, SizeOfXLogLongPHD, SizeOfXLogRecord, SizeOfXLogRecordDataHeaderShort, ControlFileData::state, ControlFileData::system_identifier, TemplateDbOid, CheckPoint::ThisTimeLineID, ThisTimeLineID, CheckPoint::time, ControlFileData::time, track_commit_timestamp, ControlFileData::track_commit_timestamp, TYPEALIGN, ControlFileData::unloggedLSN, WAIT_EVENT_WAL_BOOTSTRAP_SYNC, WAIT_EVENT_WAL_BOOTSTRAP_WRITE, wal_level, ControlFileData::wal_level, wal_log_hints, ControlFileData::wal_log_hints, wal_segment_size, write, WriteControlFile(), XLogRecord::xl_info, XLogRecord::xl_prev, XLogRecord::xl_rmid, XLogRecord::xl_tot_len, XLogRecord::xl_xid, XLOG_CHECKPOINT_SHUTDOWN, XLOG_PAGE_MAGIC, XLogFileInit(), XLogPageHeaderData::xlp_info, XLP_LONG_HEADER, XLogPageHeaderData::xlp_magic, XLogPageHeaderData::xlp_pageaddr, XLogLongPageHeaderData::xlp_seg_size, XLogLongPageHeaderData::xlp_sysid, XLogPageHeaderData::xlp_tli, XLogLongPageHeaderData::xlp_xlog_blcksz, and XLR_BLOCK_ID_DATA_SHORT.

Referenced by AuxiliaryProcessMain().

5004 {
5005  CheckPoint checkPoint;
5006  char *buffer;
5007  XLogPageHeader page;
5008  XLogLongPageHeader longpage;
5009  XLogRecord *record;
5010  char *recptr;
5011  bool use_existent;
5012  uint64 sysidentifier;
5013  char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
5014  struct timeval tv;
5015  pg_crc32c crc;
5016 
5017  /*
5018  * Select a hopefully-unique system identifier code for this installation.
5019  * We use the result of gettimeofday(), including the fractional seconds
5020  * field, as being about as unique as we can easily get. (Think not to
5021  * use random(), since it hasn't been seeded and there's no portable way
5022  * to seed it other than the system clock value...) The upper half of the
5023  * uint64 value is just the tv_sec part, while the lower half contains the
5024  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5025  * PID for a little extra uniqueness. A person knowing this encoding can
5026  * determine the initialization time of the installation, which could
5027  * perhaps be useful sometimes.
5028  */
5029  gettimeofday(&tv, NULL);
5030  sysidentifier = ((uint64) tv.tv_sec) << 32;
5031  sysidentifier |= ((uint64) tv.tv_usec) << 12;
5032  sysidentifier |= getpid() & 0xFFF;
5033 
5034  /*
5035  * Generate a random nonce. This is used for authentication requests that
5036  * will fail because the user does not exist. The nonce is used to create
5037  * a genuine-looking password challenge for the non-existent user, in lieu
5038  * of an actual stored password.
5039  */
5040  if (!pg_backend_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
5041  ereport(PANIC,
5042  (errcode(ERRCODE_INTERNAL_ERROR),
5043  errmsg("could not generate secret authorization token")));
5044 
5045  /* First timeline ID is always 1 */
5046  ThisTimeLineID = 1;
5047 
5048  /* page buffer must be aligned suitably for O_DIRECT */
5049  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5050  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5051  memset(page, 0, XLOG_BLCKSZ);
5052 
5053  /*
5054  * Set up information for the initial checkpoint record
5055  *
5056  * The initial checkpoint record is written to the beginning of the WAL
5057  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5058  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5059  */
5060  checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5061  checkPoint.ThisTimeLineID = ThisTimeLineID;
5062  checkPoint.PrevTimeLineID = ThisTimeLineID;
5063  checkPoint.fullPageWrites = fullPageWrites;
5064  checkPoint.nextXidEpoch = 0;
5065  checkPoint.nextXid = FirstNormalTransactionId;
5066  checkPoint.nextOid = FirstBootstrapObjectId;
5067  checkPoint.nextMulti = FirstMultiXactId;
5068  checkPoint.nextMultiOffset = 0;
5069  checkPoint.oldestXid = FirstNormalTransactionId;
5070  checkPoint.oldestXidDB = TemplateDbOid;
5071  checkPoint.oldestMulti = FirstMultiXactId;
5072  checkPoint.oldestMultiDB = TemplateDbOid;
5075  checkPoint.time = (pg_time_t) time(NULL);
5077 
5078  ShmemVariableCache->nextXid = checkPoint.nextXid;
5079  ShmemVariableCache->nextOid = checkPoint.nextOid;
5081  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5082  AdvanceOldestClogXid(checkPoint.oldestXid);
5083  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5084  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5086 
5087  /* Set up the XLOG page header */
5088  page->xlp_magic = XLOG_PAGE_MAGIC;
5089  page->xlp_info = XLP_LONG_HEADER;
5090  page->xlp_tli = ThisTimeLineID;
5092  longpage = (XLogLongPageHeader) page;
5093  longpage->xlp_sysid = sysidentifier;
5094  longpage->xlp_seg_size = wal_segment_size;
5095  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5096 
5097  /* Insert the initial checkpoint record */
5098  recptr = ((char *) page + SizeOfXLogLongPHD);
5099  record = (XLogRecord *) recptr;
5100  record->xl_prev = 0;
5101  record->xl_xid = InvalidTransactionId;
5102  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5104  record->xl_rmid = RM_XLOG_ID;
5105  recptr += SizeOfXLogRecord;
5106  /* fill the XLogRecordDataHeaderShort struct */
5107  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5108  *(recptr++) = sizeof(checkPoint);
5109  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5110  recptr += sizeof(checkPoint);
5111  Assert(recptr - (char *) record == record->xl_tot_len);
5112 
5113  INIT_CRC32C(crc);
5114  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5115  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5116  FIN_CRC32C(crc);
5117  record->xl_crc = crc;
5118 
5119  /* Create first XLOG segment file */
5120  use_existent = false;
5121  openLogFile = XLogFileInit(1, &use_existent, false);
5122 
5123  /* Write the first page with the initial record */
5124  errno = 0;
5126  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5127  {
5128  /* if write didn't set errno, assume problem is no disk space */
5129  if (errno == 0)
5130  errno = ENOSPC;
5131  ereport(PANIC,
5133  errmsg("could not write bootstrap write-ahead log file: %m")));
5134  }
5136 
5138  if (pg_fsync(openLogFile) != 0)
5139  ereport(PANIC,
5141  errmsg("could not fsync bootstrap write-ahead log file: %m")));
5143 
5144  if (close(openLogFile))
5145  ereport(PANIC,
5147  errmsg("could not close bootstrap write-ahead log file: %m")));
5148 
5149  openLogFile = -1;
5150 
5151  /* Now create pg_control */
5152 
5153  memset(ControlFile, 0, sizeof(ControlFileData));
5154  /* Initialize pg_control status fields */
5155  ControlFile->system_identifier = sysidentifier;
5156  memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
5158  ControlFile->time = checkPoint.time;
5159  ControlFile->checkPoint = checkPoint.redo;
5160  ControlFile->checkPointCopy = checkPoint;
5161  ControlFile->unloggedLSN = 1;
5162 
5163  /* Set important parameter values for use when replaying WAL */
5172 
5173  /* some additional ControlFile fields are set in WriteControlFile() */
5174 
5175  WriteControlFile();
5176 
5177  /* Bootstrap the commit log, too */
5178  BootStrapCLOG();
5182 
5183  pfree(buffer);
5184 
5185  /*
5186  * Force control file to be read - in contrast to normal processing we'd
5187  * otherwise never run the checks and GUC related initializations therein.
5188  */
5189  ReadControlFile();
5190 }
static void WriteControlFile(void)
Definition: xlog.c:4382
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
int max_locks_per_xact
Definition: pg_control.h:181
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
int max_prepared_xacts
Definition: pg_control.h:180
int64 pg_time_t
Definition: pgtime.h:23
int wal_segment_size
Definition: xlog.c:113
pg_time_t time
Definition: pg_control.h:128
void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact)
Definition: commit_ts.c:849
uint32 oidCount
Definition: transam.h:112
#define write(a, b, c)
Definition: win32.h:14
#define SizeOfXLogRecordDataHeaderShort
Definition: xlogrecord.h:201
int max_worker_processes
Definition: pg_control.h:179
uint32 pg_crc32c
Definition: pg_crc32c.h:38
TransactionId oldestActiveXid
Definition: pg_control.h:63
int wal_level
Definition: xlog.c:104
int XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
Definition: xlog.c:3160
void BootStrapMultiXact(void)
Definition: multixact.c:1866
MultiXactId oldestMulti
Definition: pg_control.h:49
TimeLineID PrevTimeLineID
Definition: pg_control.h:39
int errcode(int sqlerrcode)
Definition: elog.c:575
RmgrId xl_rmid
Definition: xlogrecord.h:47
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:57
CheckPoint checkPointCopy
Definition: pg_control.h:131
TransactionId oldestXid
Definition: pg_control.h:47
TransactionId nextXid
Definition: pg_control.h:43
pg_time_t time
Definition: pg_control.h:51
#define PANIC
Definition: elog.h:53
uint32 bootstrap_data_checksum_version
Definition: bootstrap.c:50
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:74
#define MOCK_AUTH_NONCE_LEN
Definition: pg_control.h:27
bool fullPageWrites
Definition: xlog.c:97
void BootStrapSUBTRANS(void)
Definition: subtrans.c:212
MultiXactOffset nextMultiOffset
Definition: pg_control.h:46
void AdvanceOldestClogXid(TransactionId oldest_datfrozenxid)
Definition: varsup.c:271
TransactionId oldestCommitTsXid
Definition: pg_control.h:52
void pfree(void *pointer)
Definition: mcxt.c:949
#define FirstNormalTransactionId
Definition: transam.h:34
int max_prepared_xacts
Definition: twophase.c:117
uint64 system_identifier
Definition: pg_control.h:106
uint32 xl_tot_len
Definition: xlogrecord.h:43
#define XLOG_PAGE_MAGIC
Definition: xlog_internal.h:34
TransactionId nextXid
Definition: transam.h:117
static void ReadControlFile(void)
Definition: xlog.c:4471
uint32 nextXidEpoch
Definition: pg_control.h:42
bool track_commit_timestamp
Definition: commit_ts.c:103
#define TemplateDbOid
Definition: pg_database.h:80
uint32 data_checksum_version
Definition: pg_control.h:221
bool pg_backend_random(char *dst, int len)
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
XLogRecPtr unloggedLSN
Definition: pg_control.h:133
int errcode_for_file_access(void)
Definition: elog.c:598
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
#define FirstBootstrapObjectId
Definition: transam.h:93
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1244
#define FirstMultiXactId
Definition: multixact.h:24
#define ereport(elevel, rest)
Definition: elog.h:122
int max_locks_per_xact
Definition: lock.c:54
TimeLineID xlp_tli
Definition: xlog_internal.h:40
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
TransactionId newestCommitTsXid
Definition: pg_control.h:54
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:228
int MaxConnections
Definition: globals.c:123
Oid oldestMultiDB
Definition: pg_control.h:50
static int openLogFile
Definition: xlog.c:774
static ControlFileData * ControlFile
Definition: xlog.c:715
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2194
TimeLineID ThisTimeLineID
Definition: xlog.c:181
Oid nextOid
Definition: pg_control.h:44
#define TYPEALIGN(ALIGNVAL, LEN)
Definition: c.h:616
bool fullPageWrites
Definition: pg_control.h:41
bool wal_log_hints
Definition: xlog.c:98
void BootStrapCLOG(void)
Definition: clog.c:712
bool track_commit_timestamp
Definition: pg_control.h:182
#define Assert(condition)
Definition: c.h:670
#define XLP_LONG_HEADER
Definition: xlog_internal.h:79
Oid oldestXidDB
Definition: pg_control.h:48
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1220
void SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
Definition: varsup.c:288
uint8 xl_info
Definition: xlogrecord.h:46
MultiXactId nextMulti
Definition: pg_control.h:45
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:224
TransactionId xl_xid
Definition: xlogrecord.h:44
TimeLineID ThisTimeLineID
Definition: pg_control.h:38
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
int max_worker_processes
Definition: globals.c:124
int pg_fsync(int fd)
Definition: fd.c:338
#define close(a)
Definition: win32.h:12
void BootStrapCommitTs(void)
Definition: commit_ts.c:523
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:73
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:78
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:36
#define offsetof(type, field)
Definition: c.h:593
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:72
void MultiXactSetNextMXact(MultiXactId nextMulti, MultiXactOffset nextMultiOffset)
Definition: multixact.c:2160

◆ CalculateCheckpointSegments()

static void CalculateCheckpointSegments ( void  )
static

Definition at line 2216 of file xlog.c.

References CheckPointCompletionTarget, CheckPointSegments, ConvertToXSegs, max_wal_size_mb, and wal_segment_size.

Referenced by assign_checkpoint_completion_target(), assign_max_wal_size(), and ReadControlFile().

2217 {
2218  double target;
2219 
2220  /*-------
2221  * Calculate the distance at which to trigger a checkpoint, to avoid
2222  * exceeding max_wal_size_mb. This is based on two assumptions:
2223  *
2224  * a) we keep WAL for only one checkpoint cycle (prior to PG11 we kept
2225  * WAL for two checkpoint cycles to allow us to recover from the
2226  * secondary checkpoint if the first checkpoint failed, though we
2227  * only did this on the master anyway, not on standby. Keeping just
2228  * one checkpoint simplifies processing and reduces disk space in
2229  * many smaller databases.)
2230  * b) during checkpoint, we consume checkpoint_completion_target *
2231  * number of segments consumed between checkpoints.
2232  *-------
2233  */
2234  target = (double) ConvertToXSegs(max_wal_size_mb, wal_segment_size) /
2236 
2237  /* round down */
2238  CheckPointSegments = (int) target;
2239 
2240  if (CheckPointSegments < 1)
2241  CheckPointSegments = 1;
2242 }
#define ConvertToXSegs(x, segsize)
Definition: xlog.c:741
int wal_segment_size
Definition: xlog.c:113
int max_wal_size_mb
Definition: xlog.c:89
int CheckPointSegments
Definition: xlog.c:126
double CheckPointCompletionTarget
Definition: checkpointer.c:147

◆ CancelBackup()

void CancelBackup ( void  )

Definition at line 11404 of file xlog.c.

References BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, DEBUG1, durable_rename(), ereport, errcode_for_file_access(), errdetail(), errmsg(), LOG, stat, TABLESPACE_MAP, TABLESPACE_MAP_OLD, and WARNING.

Referenced by PostmasterStateMachine().

11405 {
11406  struct stat stat_buf;
11407 
11408  /* if the backup_label file is not there, return */
11409  if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
11410  return;
11411 
11412  /* remove leftover file from previously canceled backup if it exists */
11413  unlink(BACKUP_LABEL_OLD);
11414 
11416  {
11417  ereport(WARNING,
11419  errmsg("online backup mode was not canceled"),
11420  errdetail("File \"%s\" could not be renamed to \"%s\": %m.",
11422  return;
11423  }
11424 
11425  /* if the tablespace_map file is not there, return */
11426  if (stat(TABLESPACE_MAP, &stat_buf) < 0)
11427  {
11428  ereport(LOG,
11429  (errmsg("online backup mode canceled"),
11430  errdetail("File \"%s\" was renamed to \"%s\".",
11432  return;
11433  }
11434 
11435  /* remove leftover file from previously canceled backup if it exists */
11436  unlink(TABLESPACE_MAP_OLD);
11437 
11439  {
11440  ereport(LOG,
11441  (errmsg("online backup mode canceled"),
11442  errdetail("Files \"%s\" and \"%s\" were renamed to "
11443  "\"%s\" and \"%s\", respectively.",
11446  }
11447  else
11448  {
11449  ereport(WARNING,
11451  errmsg("online backup mode canceled"),
11452  errdetail("File \"%s\" was renamed to \"%s\", but "
11453  "file \"%s\" could not be renamed to \"%s\": %m.",
11456  }
11457 }
#define DEBUG1
Definition: elog.h:25
#define LOG
Definition: elog.h:26
#define BACKUP_LABEL_OLD
Definition: xlog.h:323
#define TABLESPACE_MAP
Definition: xlog.h:325
struct stat stat_buf
Definition: pg_standby.c:103
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:598
#define WARNING
Definition: elog.h:40
#define stat(a, b)
Definition: win32_port.h:266
#define TABLESPACE_MAP_OLD
Definition: xlog.h:326
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define BACKUP_LABEL_FILE
Definition: xlog.h:322

◆ check_wal_buffers()

bool check_wal_buffers ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 4794 of file xlog.c.

References XLOGbuffers, and XLOGChooseNumBuffers().

4795 {
4796  /*
4797  * -1 indicates a request for auto-tune.
4798  */
4799  if (*newval == -1)
4800  {
4801  /*
4802  * If we haven't yet changed the boot_val default of -1, just let it
4803  * be. We'll fix it when XLOGShmemSize is called.
4804  */
4805  if (XLOGbuffers == -1)
4806  return true;
4807 
4808  /* Otherwise, substitute the auto-tune value */
4810  }
4811 
4812  /*
4813  * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
4814  * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
4815  * the case, we just silently treat such values as a request for the
4816  * minimum. (We could throw an error instead, but that doesn't seem very
4817  * helpful.)
4818  */
4819  if (*newval < 4)
4820  *newval = 4;
4821 
4822  return true;
4823 }
static int XLOGChooseNumBuffers(void)
Definition: xlog.c:4778
#define newval
int XLOGbuffers
Definition: xlog.c:92

◆ CheckForStandbyTrigger()

static bool CheckForStandbyTrigger ( void  )
static

Definition at line 12050 of file xlog.c.

References ereport, errcode_for_file_access(), errmsg(), ERROR, FALLBACK_PROMOTE_SIGNAL_FILE, fast_promote, IsPromoteTriggered(), LOG, PROMOTE_SIGNAL_FILE, ResetPromoteTriggered(), stat, and TriggerFile.

Referenced by ReadRecord(), recoveryApplyDelay(), and WaitForWALToBecomeAvailable().

12051 {
12052  struct stat stat_buf;
12053  static bool triggered = false;
12054 
12055  if (triggered)
12056  return true;
12057 
12058  if (IsPromoteTriggered())
12059  {
12060  /*
12061  * In 9.1 and 9.2 the postmaster unlinked the promote file inside the
12062  * signal handler. It now leaves the file in place and lets the
12063  * Startup process do the unlink. This allows Startup to know whether
12064  * it should create a full checkpoint before starting up (fallback
12065  * mode). Fast promotion takes precedence.
12066  */
12067  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
12068  {
12069  unlink(PROMOTE_SIGNAL_FILE);
12071  fast_promote = true;
12072  }
12073  else if (stat(FALLBACK_PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
12074  {
12076  fast_promote = false;
12077  }
12078 
12079  ereport(LOG, (errmsg("received promote request")));
12080 
12082  triggered = true;
12083  return true;
12084  }
12085 
12086  if (TriggerFile == NULL)
12087  return false;
12088 
12089  if (stat(TriggerFile, &stat_buf) == 0)
12090  {
12091  ereport(LOG,
12092  (errmsg("trigger file found: %s", TriggerFile)));
12093  unlink(TriggerFile);
12094  triggered = true;
12095  fast_promote = true;
12096  return true;
12097  }
12098  else if (errno != ENOENT)
12099  ereport(ERROR,
12101  errmsg("could not stat trigger file \"%s\": %m",
12102  TriggerFile)));
12103 
12104  return false;
12105 }
void ResetPromoteTriggered(void)
Definition: startup.c:253
#define FALLBACK_PROMOTE_SIGNAL_FILE
Definition: xlog.c:85
#define LOG
Definition: elog.h:26
static char * TriggerFile
Definition: xlog.c:276
#define ERROR
Definition: elog.h:43
struct stat stat_buf
Definition: pg_standby.c:103
#define PROMOTE_SIGNAL_FILE
Definition: xlog.c:84
int errcode_for_file_access(void)
Definition: elog.c:598
bool IsPromoteTriggered(void)
Definition: startup.c:247
#define ereport(elevel, rest)
Definition: elog.h:122
#define stat(a, b)
Definition: win32_port.h:266
int errmsg(const char *fmt,...)
Definition: elog.c:797
static bool fast_promote
Definition: xlog.c:282

◆ CheckPointGuts()

static void CheckPointGuts ( XLogRecPtr  checkPointRedo,
int  flags 
)
static

Definition at line 9042 of file xlog.c.

References CheckPointBuffers(), CheckPointCLOG(), CheckPointCommitTs(), CheckPointLogicalRewriteHeap(), CheckPointMultiXact(), CheckPointPredicate(), CheckPointRelationMap(), CheckPointReplicationOrigin(), CheckPointReplicationSlots(), CheckPointSnapBuild(), CheckPointSUBTRANS(), and CheckPointTwoPhase().

Referenced by CreateCheckPoint(), and CreateRestartPoint().

9043 {
9044  CheckPointCLOG();
9053  CheckPointBuffers(flags); /* performs all required fsyncs */
9055  /* We deliberately delay 2PC checkpointing as long as possible */
9056  CheckPointTwoPhase(checkPointRedo);
9057 }
void CheckPointBuffers(int flags)
Definition: bufmgr.c:2574
void CheckPointLogicalRewriteHeap(void)
Definition: rewriteheap.c:1198
void CheckPointReplicationOrigin(void)
Definition: origin.c:528
void CheckPointSnapBuild(void)
Definition: snapbuild.c:1861
void CheckPointCLOG(void)
Definition: clog.c:842
void CheckPointMultiXact(void)
Definition: multixact.c:2140
void CheckPointCommitTs(void)
Definition: commit_ts.c:761
void CheckPointSUBTRANS(void)
Definition: subtrans.c:300
void CheckPointRelationMap(void)
Definition: relmapper.c:524
void CheckPointPredicate(void)
Definition: predicate.c:1043
void CheckPointTwoPhase(XLogRecPtr redo_horizon)
Definition: twophase.c:1651
void CheckPointReplicationSlots(void)
Definition: slot.c:1055

◆ CheckPromoteSignal()

bool CheckPromoteSignal ( void  )

Definition at line 12122 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, PROMOTE_SIGNAL_FILE, and stat.

Referenced by sigusr1_handler().

12123 {
12124  struct stat stat_buf;
12125 
12126  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0 ||
12128  return true;
12129 
12130  return false;
12131 }
#define FALLBACK_PROMOTE_SIGNAL_FILE
Definition: xlog.c:85
struct stat stat_buf
Definition: pg_standby.c:103
#define PROMOTE_SIGNAL_FILE
Definition: xlog.c:84
#define stat(a, b)
Definition: win32_port.h:266

◆ CheckRecoveryConsistency()

static void CheckRecoveryConsistency ( void  )
static

Definition at line 7830 of file xlog.c.

References ControlFileData::backupEndPoint, ControlFileData::backupEndRequired, ControlFileData::backupStartPoint, DEBUG1, elog, ereport, errmsg(), XLogCtlData::info_lck, InvalidXLogRecPtr, IsUnderPostmaster, XLogCtlData::lastReplayedEndRecPtr, LocalHotStandbyActive, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ControlFileData::minRecoveryPoint, minRecoveryPoint, PMSIGNAL_BEGIN_HOT_STANDBY, reachedConsistency, SendPostmasterSignal(), XLogCtlData::SharedHotStandbyActive, SpinLockAcquire, SpinLockRelease, STANDBY_SNAPSHOT_READY, standbyState, UpdateControlFile(), XLogCheckInvalidPages(), and XLogRecPtrIsInvalid.

Referenced by ReadRecord(), and StartupXLOG().

7831 {
7832  XLogRecPtr lastReplayedEndRecPtr;
7833 
7834  /*
7835  * During crash recovery, we don't reach a consistent state until we've
7836  * replayed all the WAL.
7837  */
7839  return;
7840 
7841  /*
7842  * assume that we are called in the startup process, and hence don't need
7843  * a lock to read lastReplayedEndRecPtr
7844  */
7845  lastReplayedEndRecPtr = XLogCtl->lastReplayedEndRecPtr;
7846 
7847  /*
7848  * Have we reached the point where our base backup was completed?
7849  */
7851  ControlFile->backupEndPoint <= lastReplayedEndRecPtr)
7852  {
7853  /*
7854  * We have reached the end of base backup, as indicated by pg_control.
7855  * The data on disk is now consistent. Reset backupStartPoint and
7856  * backupEndPoint, and update minRecoveryPoint to make sure we don't
7857  * allow starting up at an earlier point even if recovery is stopped
7858  * and restarted soon after this.
7859  */
7860  elog(DEBUG1, "end of backup reached");
7861 
7862  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7863 
7864  if (ControlFile->minRecoveryPoint < lastReplayedEndRecPtr)
7865  ControlFile->minRecoveryPoint = lastReplayedEndRecPtr;
7866 
7869  ControlFile->backupEndRequired = false;
7871 
7872  LWLockRelease(ControlFileLock);
7873  }
7874 
7875  /*
7876  * Have we passed our safe starting point? Note that minRecoveryPoint is
7877  * known to be incorrectly set if ControlFile->backupEndRequired, until
7878  * the XLOG_BACKUP_RECORD arrives to advise us of the correct
7879  * minRecoveryPoint. All we know prior to that is that we're not
7880  * consistent yet.
7881  */
7883  minRecoveryPoint <= lastReplayedEndRecPtr &&
7885  {
7886  /*
7887  * Check to see if the XLOG sequence contained any unresolved
7888  * references to uninitialized pages.
7889  */
7891 
7892  reachedConsistency = true;
7893  ereport(LOG,
7894  (errmsg("consistent recovery state reached at %X/%X",
7895  (uint32) (lastReplayedEndRecPtr >> 32),
7896  (uint32) lastReplayedEndRecPtr)));
7897  }
7898 
7899  /*
7900  * Have we got a valid starting snapshot that will allow queries to be
7901  * run? If so, we can tell postmaster that the database is consistent now,
7902  * enabling connections.
7903  */
7908  {
7912 
7913  LocalHotStandbyActive = true;
7914 
7916  }
7917 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
void XLogCheckInvalidPages(void)
Definition: xlogutils.c:221
bool SharedHotStandbyActive
Definition: xlog.c:649
slock_t info_lck
Definition: xlog.c:704
#define LOG
Definition: elog.h:26
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
bool backupEndRequired
Definition: pg_control.h:170
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool LocalHotStandbyActive
Definition: xlog.c:223
void UpdateControlFile(void)
Definition: xlog.c:4670
bool IsUnderPostmaster
Definition: globals.c:101
unsigned int uint32
Definition: c.h:296
#define ereport(elevel, rest)
Definition: elog.h:122
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define SpinLockRelease(lock)
Definition: spin.h:64
static ControlFileData * ControlFile
Definition: xlog.c:715
XLogRecPtr backupEndPoint
Definition: pg_control.h:169
bool reachedConsistency
Definition: xlog.c:834
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:707
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
int errmsg(const char *fmt,...)
Definition: elog.c:797
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:113
#define elog
Definition: elog.h:219
HotStandbyState standbyState
Definition: xlog.c:197
XLogRecPtr backupStartPoint
Definition: pg_control.h:168
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
static XLogRecPtr minRecoveryPoint
Definition: xlog.c:824
XLogRecPtr lastReplayedEndRecPtr
Definition: xlog.c:683

◆ CheckRequiredParameterValues()

static void CheckRequiredParameterValues ( void  )
static

Definition at line 6220 of file xlog.c.

References ArchiveRecoveryRequested, EnableHotStandby, ereport, errhint(), errmsg(), ERROR, max_locks_per_xact, ControlFileData::max_locks_per_xact, max_prepared_xacts, ControlFileData::max_prepared_xacts, max_worker_processes, ControlFileData::max_worker_processes, MaxConnections, ControlFileData::MaxConnections, RecoveryRequiresIntParameter, ControlFileData::wal_level, WAL_LEVEL_MINIMAL, WAL_LEVEL_REPLICA, and WARNING.

Referenced by StartupXLOG(), and xlog_redo().

6221 {
6222  /*
6223  * For archive recovery, the WAL must be generated with at least 'replica'
6224  * wal_level.
6225  */
6227  {
6228  ereport(WARNING,
6229  (errmsg("WAL was generated with wal_level=minimal, data may be missing"),
6230  errhint("This happens if you temporarily set wal_level=minimal without taking a new base backup.")));
6231  }
6232 
6233  /*
6234  * For Hot Standby, the WAL must be generated with 'replica' mode, and we
6235  * must have at least as many backend slots as the primary.
6236  */
6238  {
6240  ereport(ERROR,
6241  (errmsg("hot standby is not possible because wal_level was not set to \"replica\" or higher on the master server"),
6242  errhint("Either set wal_level to \"replica\" on the master, or turn off hot_standby here.")));
6243 
6244  /* We ignore autovacuum_max_workers when we make this test. */
6245  RecoveryRequiresIntParameter("max_connections",
6248  RecoveryRequiresIntParameter("max_worker_processes",
6251  RecoveryRequiresIntParameter("max_prepared_transactions",
6254  RecoveryRequiresIntParameter("max_locks_per_transaction",
6257  }
6258 }
bool ArchiveRecoveryRequested
Definition: xlog.c:248
int max_locks_per_xact
Definition: pg_control.h:181
int errhint(const char *fmt,...)
Definition: elog.c:987
int max_prepared_xacts
Definition: pg_control.h:180
int max_worker_processes
Definition: pg_control.h:179
#define ERROR
Definition: elog.h:43
int max_prepared_xacts
Definition: twophase.c:117
#define ereport(elevel, rest)
Definition: elog.h:122
int max_locks_per_xact
Definition: lock.c:54
#define WARNING
Definition: elog.h:40
int MaxConnections
Definition: globals.c:123
static ControlFileData * ControlFile
Definition: xlog.c:715
bool EnableHotStandby
Definition: xlog.c:96
int errmsg(const char *fmt,...)
Definition: elog.c:797
int max_worker_processes
Definition: globals.c:124
#define RecoveryRequiresIntParameter(param_name, currValue, minValue)
Definition: xlog.c:6198

◆ checkTimeLineSwitch()

static void checkTimeLineSwitch ( XLogRecPtr  lsn,
TimeLineID  newTLI,
TimeLineID  prevTLI 
)
static

Definition at line 9598 of file xlog.c.

References ereport, errmsg(), minRecoveryPoint, minRecoveryPointTLI, PANIC, ThisTimeLineID, tliInHistory(), and XLogRecPtrIsInvalid.

Referenced by StartupXLOG().

9599 {
9600  /* Check that the record agrees on what the current (old) timeline is */
9601  if (prevTLI != ThisTimeLineID)
9602  ereport(PANIC,
9603  (errmsg("unexpected previous timeline ID %u (current timeline ID %u) in checkpoint record",
9604  prevTLI, ThisTimeLineID)));
9605 
9606  /*
9607  * The new timeline better be in the list of timelines we expect to see,
9608  * according to the timeline history. It should also not decrease.
9609  */
9610  if (newTLI < ThisTimeLineID || !tliInHistory(newTLI, expectedTLEs))
9611  ereport(PANIC,
9612  (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
9613  newTLI, ThisTimeLineID)));
9614 
9615  /*
9616  * If we have not yet reached min recovery point, and we're about to
9617  * switch to a timeline greater than the timeline of the min recovery
9618  * point: trouble. After switching to the new timeline, we could not
9619  * possibly visit the min recovery point on the correct timeline anymore.
9620  * This can happen if there is a newer timeline in the archive that
9621  * branched before the timeline the min recovery point is on, and you
9622  * attempt to do PITR to the new timeline.
9623  */
9625  lsn < minRecoveryPoint &&
9626  newTLI > minRecoveryPointTLI)
9627  ereport(PANIC,
9628  (errmsg("unexpected timeline ID %u in checkpoint record, before reaching minimum recovery point %X/%X on timeline %u",
9629  newTLI,
9630  (uint32) (minRecoveryPoint >> 32),
9633 
9634  /* Looks good */
9635 }
static List * expectedTLEs
Definition: xlog.c:320
#define PANIC
Definition: elog.h:53
unsigned int uint32
Definition: c.h:296
#define ereport(elevel, rest)
Definition: elog.h:122
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
static TimeLineID minRecoveryPointTLI
Definition: xlog.c:826
TimeLineID ThisTimeLineID
Definition: xlog.c:181
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool tliInHistory(TimeLineID tli, List *expectedTLEs)
Definition: timeline.c:515
static XLogRecPtr minRecoveryPoint
Definition: xlog.c:824

◆ checkXLogConsistency()

static void checkXLogConsistency ( XLogReaderState record)
static

Definition at line 1349 of file xlog.c.

References Assert, buf, BUFFER_LOCK_EXCLUSIVE, BufferGetPage, BufferIsValid, RelFileNode::dbNode, elog, XLogReaderState::EndRecPtr, ERROR, FATAL, LockBuffer(), master_image_masked, XLogReaderState::max_block_id, PageGetLSN, RBM_NORMAL_NO_LOG, RelFileNode::relNode, replay_image_masked, RestoreBlockImage(), RmgrData::rm_mask, RmgrTable, RelFileNode::spcNode, UnlockReleaseBuffer(), XLogReadBufferExtended(), XLogRecBlockImageApply, XLogRecGetBlockTag(), XLogRecGetInfo, XLogRecGetRmid, XLogRecHasAnyBlockRefs, XLogRecHasBlockImage, and XLR_CHECK_CONSISTENCY.

Referenced by StartupXLOG().

1350 {
1351  RmgrId rmid = XLogRecGetRmid(record);
1352  RelFileNode rnode;
1353  ForkNumber forknum;
1354  BlockNumber blkno;
1355  int block_id;
1356 
1357  /* Records with no backup blocks have no need for consistency checks. */
1358  if (!XLogRecHasAnyBlockRefs(record))
1359  return;
1360 
1361  Assert((XLogRecGetInfo(record) & XLR_CHECK_CONSISTENCY) != 0);
1362 
1363  for (block_id = 0; block_id <= record->max_block_id; block_id++)
1364  {
1365  Buffer buf;
1366  Page page;
1367 
1368  if (!XLogRecGetBlockTag(record, block_id, &rnode, &forknum, &blkno))
1369  {
1370  /*
1371  * WAL record doesn't contain a block reference with the given id.
1372  * Do nothing.
1373  */
1374  continue;
1375  }
1376 
1377  Assert(XLogRecHasBlockImage(record, block_id));
1378 
1379  if (XLogRecBlockImageApply(record, block_id))
1380  {
1381  /*
1382  * WAL record has already applied the page, so bypass the
1383  * consistency check as that would result in comparing the full
1384  * page stored in the record with itself.
1385  */
1386  continue;
1387  }
1388 
1389  /*
1390  * Read the contents from the current buffer and store it in a
1391  * temporary page.
1392  */
1393  buf = XLogReadBufferExtended(rnode, forknum, blkno,
1395  if (!BufferIsValid(buf))
1396  continue;
1397 
1399  page = BufferGetPage(buf);
1400 
1401  /*
1402  * Take a copy of the local page where WAL has been applied to have a
1403  * comparison base before masking it...
1404  */
1405  memcpy(replay_image_masked, page, BLCKSZ);
1406 
1407  /* No need for this page anymore now that a copy is in. */
1408  UnlockReleaseBuffer(buf);
1409 
1410  /*
1411  * If the block LSN is already ahead of this WAL record, we can't
1412  * expect contents to match. This can happen if recovery is
1413  * restarted.
1414  */
1415  if (PageGetLSN(replay_image_masked) > record->EndRecPtr)
1416  continue;
1417 
1418  /*
1419  * Read the contents from the backup copy, stored in WAL record and
1420  * store it in a temporary page. There is no need to allocate a new
1421  * page here, a local buffer is fine to hold its contents and a mask
1422  * can be directly applied on it.
1423  */
1424  if (!RestoreBlockImage(record, block_id, master_image_masked))
1425  elog(ERROR, "failed to restore block image");
1426 
1427  /*
1428  * If masking function is defined, mask both the master and replay
1429  * images
1430  */
1431  if (RmgrTable[rmid].rm_mask != NULL)
1432  {
1433  RmgrTable[rmid].rm_mask(replay_image_masked, blkno);
1434  RmgrTable[rmid].rm_mask(master_image_masked, blkno);
1435  }
1436 
1437  /* Time to compare the master and replay images. */
1438  if (memcmp(replay_image_masked, master_image_masked, BLCKSZ) != 0)
1439  {
1440  elog(FATAL,
1441  "inconsistent page found, rel %u/%u/%u, forknum %u, blkno %u",
1442  rnode.spcNode, rnode.dbNode, rnode.relNode,
1443  forknum, blkno);
1444  }
1445  }
1446 }
#define XLogRecHasBlockImage(decoder, block_id)
Definition: xlogreader.h:231
Buffer XLogReadBufferExtended(RelFileNode rnode, ForkNumber forknum, BlockNumber blkno, ReadBufferMode mode)
Definition: xlogutils.c:438
const RmgrData RmgrTable[RM_MAX_ID+1]
Definition: rmgr.c:36
uint32 BlockNumber
Definition: block.h:31
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
#define XLR_CHECK_CONSISTENCY
Definition: xlogrecord.h:80
XLogRecPtr EndRecPtr
Definition: xlogreader.h:120
static char * replay_image_masked
Definition: xlog.c:255
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
static char * buf
Definition: pg_test_fsync.c:67
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:222
ForkNumber
Definition: relpath.h:24
void(* rm_mask)(char *pagedata, BlockNumber blkno)
bool XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
Definition: xlogreader.c:1309
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
uint8 RmgrId
Definition: rmgr.h:11
#define Assert(condition)
Definition: c.h:670
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
bool RestoreBlockImage(XLogReaderState *record, uint8 block_id, char *page)
Definition: xlogreader.c:1362
#define PageGetLSN(page)
Definition: bufpage.h:362
#define XLogRecHasAnyBlockRefs(decoder)
Definition: xlogreader.h:228
#define elog
Definition: elog.h:219
#define XLogRecBlockImageApply(decoder, block_id)
Definition: xlogreader.h:233
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:74
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:223
static char * master_image_masked
Definition: xlog.c:256

◆ CheckXLogRemoved()

void CheckXLogRemoved ( XLogSegNo  segno,
TimeLineID  tli 
)

Definition at line 3769 of file xlog.c.

References ereport, errcode_for_file_access(), errmsg(), ERROR, filename, XLogCtlData::info_lck, XLogCtlData::lastRemovedSegNo, MAXFNAMELEN, SpinLockAcquire, SpinLockRelease, wal_segment_size, and XLogFileName.

Referenced by perform_base_backup(), and XLogRead().

3770 {
3771  XLogSegNo lastRemovedSegNo;
3772 
3774  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3776 
3777  if (segno <= lastRemovedSegNo)
3778  {
3779  char filename[MAXFNAMELEN];
3780 
3781  XLogFileName(filename, tli, segno, wal_segment_size);
3782  ereport(ERROR,
3784  errmsg("requested WAL segment %s has already been removed",
3785  filename)));
3786  }
3787 }
int wal_segment_size
Definition: xlog.c:113
slock_t info_lck
Definition: xlog.c:704
XLogSegNo lastRemovedSegNo
Definition: xlog.c:587
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define ERROR
Definition: elog.h:43
uint64 XLogSegNo
Definition: xlogdefs.h:34
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static XLogCtlData * XLogCtl
Definition: xlog.c:707
static char * filename
Definition: pg_dumpall.c:90
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ CleanupBackupHistory()

static void CleanupBackupHistory ( void  )
static

Definition at line 4104 of file xlog.c.

References AllocateDir(), dirent::d_name, DEBUG2, elog, ereport, errcode_for_file_access(), errmsg(), ERROR, FreeDir(), IsBackupHistoryFileName, MAXPGPATH, ReadDir(), snprintf(), XLogArchiveCheckDone(), XLogArchiveCleanup(), and XLOGDIR.

Referenced by do_pg_stop_backup().

4105 {
4106  DIR *xldir;
4107  struct dirent *xlde;
4108  char path[MAXPGPATH + sizeof(XLOGDIR)];
4109 
4110  xldir = AllocateDir(XLOGDIR);
4111  if (xldir == NULL)
4112  ereport(ERROR,
4114  errmsg("could not open write-ahead log directory \"%s\": %m",
4115  XLOGDIR)));
4116 
4117  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4118  {
4119  if (IsBackupHistoryFileName(xlde->d_name))
4120  {
4121  if (XLogArchiveCheckDone(xlde->d_name))
4122  {
4123  elog(DEBUG2, "removing WAL backup history file \"%s\"",
4124  xlde->d_name);
4125  snprintf(path, sizeof(path), XLOGDIR "/%s", xlde->d_name);
4126  unlink(path);
4127  XLogArchiveCleanup(xlde->d_name);
4128  }
4129  }
4130  }
4131 
4132  FreeDir(xldir);
4133 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
Definition: dirent.h:9
void XLogArchiveCleanup(const char *xlog)
Definition: xlogarchive.c:752
Definition: dirent.c:25
#define ERROR
Definition: elog.h:43
bool XLogArchiveCheckDone(const char *xlog)
Definition: xlogarchive.c:619
#define MAXPGPATH
#define DEBUG2
Definition: elog.h:24
int errcode_for_file_access(void)
Definition: elog.c:598
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2373
#define ereport(elevel, rest)
Definition: elog.h:122
#define IsBackupHistoryFileName(fname)
#define XLOGDIR
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2439
int errmsg(const char *fmt,...)
Definition: elog.c:797
char d_name[MAX_PATH]
Definition: dirent.h:14
#define elog
Definition: elog.h:219
int FreeDir(DIR *dir)
Definition: fd.c:2482

◆ CopyXLogRecordToWAL()

static void CopyXLogRecordToWAL ( int  write_len,
bool  isLogSwitch,
XLogRecData rdata,
XLogRecPtr  StartPos,
XLogRecPtr  EndPos 
)
static

Definition at line 1453 of file xlog.c.

References AdvanceXLInsertBuffer(), Assert, XLogRecData::data, elog, GetXLogBuffer(), INSERT_FREESPACE, XLogRecData::len, MAXALIGN64, XLogRecData::next, PANIC, SizeOfXLogLongPHD, SizeOfXLogRecord, SizeOfXLogShortPHD, wal_segment_size, WALInsertLockUpdateInsertingAt(), XLogSegmentOffset, XLP_FIRST_IS_CONTRECORD, XLogPageHeaderData::xlp_info, and XLogPageHeaderData::xlp_rem_len.

Referenced by XLogInsertRecord().

1455 {
1456  char *currpos;
1457  int freespace;
1458  int written;
1459  XLogRecPtr CurrPos;
1460  XLogPageHeader pagehdr;
1461 
1462  /*
1463  * Get a pointer to the right place in the right WAL buffer to start
1464  * inserting to.
1465  */
1466  CurrPos = StartPos;
1467  currpos = GetXLogBuffer(CurrPos);
1468  freespace = INSERT_FREESPACE(CurrPos);
1469 
1470  /*
1471  * there should be enough space for at least the first field (xl_tot_len)
1472  * on this page.
1473  */
1474  Assert(freespace >= sizeof(uint32));
1475 
1476  /* Copy record data */
1477  written = 0;
1478  while (rdata != NULL)
1479  {
1480  char *rdata_data = rdata->data;
1481  int rdata_len = rdata->len;
1482 
1483  while (rdata_len > freespace)
1484  {
1485  /*
1486  * Write what fits on this page, and continue on the next page.
1487  */
1488  Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || freespace == 0);
1489  memcpy(currpos, rdata_data, freespace);
1490  rdata_data += freespace;
1491  rdata_len -= freespace;
1492  written += freespace;
1493  CurrPos += freespace;
1494 
1495  /*
1496  * Get pointer to beginning of next page, and set the xlp_rem_len
1497  * in the page header. Set XLP_FIRST_IS_CONTRECORD.
1498  *
1499  * It's safe to set the contrecord flag and xlp_rem_len without a
1500  * lock on the page. All the other flags were already set when the
1501  * page was initialized, in AdvanceXLInsertBuffer, and we're the
1502  * only backend that needs to set the contrecord flag.
1503  */
1504  currpos = GetXLogBuffer(CurrPos);
1505  pagehdr = (XLogPageHeader) currpos;
1506  pagehdr->xlp_rem_len = write_len - written;
1507  pagehdr->xlp_info |= XLP_FIRST_IS_CONTRECORD;
1508 
1509  /* skip over the page header */
1510  if (XLogSegmentOffset(CurrPos, wal_segment_size) == 0)
1511  {
1512  CurrPos += SizeOfXLogLongPHD;
1513  currpos += SizeOfXLogLongPHD;
1514  }
1515  else
1516  {
1517  CurrPos += SizeOfXLogShortPHD;
1518  currpos += SizeOfXLogShortPHD;
1519  }
1520  freespace = INSERT_FREESPACE(CurrPos);
1521  }
1522 
1523  Assert(CurrPos % XLOG_BLCKSZ >= SizeOfXLogShortPHD || rdata_len == 0);
1524  memcpy(currpos, rdata_data, rdata_len);
1525  currpos += rdata_len;
1526  CurrPos += rdata_len;
1527  freespace -= rdata_len;
1528  written += rdata_len;
1529 
1530  rdata = rdata->next;
1531  }
1532  Assert(written == write_len);
1533 
1534  /*
1535  * If this was an xlog-switch, it's not enough to write the switch record,
1536  * we also have to consume all the remaining space in the WAL segment. We
1537  * have already reserved it for us, but we still need to make sure it's
1538  * allocated and zeroed in the WAL buffers so that when the caller (or
1539  * someone else) does XLogWrite(), it can really write out all the zeros.
1540  */
1541  if (isLogSwitch && XLogSegmentOffset(CurrPos, wal_segment_size) != 0)
1542  {
1543  /* An xlog-switch record doesn't contain any data besides the header */
1544  Assert(write_len == SizeOfXLogRecord);
1545 
1546  /*
1547  * We do this one page at a time, to make sure we don't deadlock
1548  * against ourselves if wal_buffers < wal_segment_size.
1549  */
1550  Assert(XLogSegmentOffset(EndPos, wal_segment_size) == 0);
1551 
1552  /* Use up all the remaining space on the first page */
1553  CurrPos += freespace;
1554 
1555  while (CurrPos < EndPos)
1556  {
1557  /* initialize the next page (if not initialized already) */
1559  AdvanceXLInsertBuffer(CurrPos, false);
1560  CurrPos += XLOG_BLCKSZ;
1561  }
1562  }
1563  else
1564  {
1565  /* Align the end position, so that the next record starts aligned */
1566  CurrPos = MAXALIGN64(CurrPos);
1567  }
1568 
1569  if (CurrPos != EndPos)
1570  elog(PANIC, "space reserved for WAL record does not match what was written");
1571 }
int wal_segment_size
Definition: xlog.c:113
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:57
#define PANIC
Definition: elog.h:53
static char * GetXLogBuffer(XLogRecPtr ptr)
Definition: xlog.c:1809
#define MAXALIGN64(LEN)
Definition: c.h:648
static void WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt)
Definition: xlog.c:1677
unsigned int uint32
Definition: c.h:296
#define INSERT_FREESPACE(endptr)
Definition: xlog.c:721
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:670
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:55
#define XLP_FIRST_IS_CONTRECORD
Definition: xlog_internal.h:77
struct XLogRecData * next
#define elog
Definition: elog.h:219
static void AdvanceXLInsertBuffer(XLogRecPtr upto, bool opportunistic)
Definition: xlog.c:2047
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:72

◆ CreateCheckPoint()

void CreateCheckPoint ( int  flags)

Definition at line 8567 of file xlog.c.

References ControlFileData::checkPoint, CHECKPOINT_END_OF_RECOVERY, CHECKPOINT_FORCE, CHECKPOINT_IS_SHUTDOWN, ControlFileData::checkPointCopy, CheckPointGuts(), CheckpointStatsData::ckpt_bufs_written, CheckpointStatsData::ckpt_segs_added, CheckpointStatsData::ckpt_segs_recycled, CheckpointStatsData::ckpt_segs_removed, CheckpointStatsData::ckpt_start_t, XLogCtlData::ckptXid, XLogCtlData::ckptXidEpoch, XLogCtlInsert::CurrBytePos, DB_SHUTDOWNED, DB_SHUTDOWNING, DEBUG1, elog, END_CRIT_SECTION, ereport, errmsg(), ERROR, CheckPoint::fullPageWrites, XLogCtlInsert::fullPageWrites, GetCurrentTimestamp(), GetLastImportantRecPtr(), GetOldestActiveTransactionId(), GetOldestXmin(), GetVirtualXIDsDelayingChkpt(), HaveVirtualXIDsDelayingChkpt(), XLogCtlData::info_lck, InitXLogInsert(), Insert(), XLogCtlData::Insert, INSERT_FREESPACE, InvalidTransactionId, InvalidXLogRecPtr, KeepLogSeg(), LocalSetXLogInsertAllowed(), LocalXLogInsertAllowed, log_checkpoints, LogCheckpointEnd(), LogCheckpointStart(), LogStandbySnapshot(), LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MemSet, ControlFileData::minRecoveryPoint, ControlFileData::minRecoveryPointTLI, MultiXactGetCheckptMulti(), NBuffers, CheckPoint::newestCommitTsXid, VariableCacheData::newestCommitTsXid, CheckPoint::nextMulti, CheckPoint::nextMultiOffset, CheckPoint::nextOid, VariableCacheData::nextOid, CheckPoint::nextXid, VariableCacheData::nextXid, CheckPoint::nextXidEpoch, VariableCacheData::oidCount, CheckPoint::oldestActiveXid, CheckPoint::oldestCommitTsXid, VariableCacheData::oldestCommitTsXid, CheckPoint::oldestMulti, CheckPoint::oldestMultiDB, CheckPoint::oldestXid, VariableCacheData::oldestXid, CheckPoint::oldestXidDB, VariableCacheData::oldestXidDB, PANIC, pfree(), pg_usleep(), PreallocXlogFiles(), CheckPoint::PrevTimeLineID, XLogCtlData::PrevTimeLineID, PROCARRAY_FLAGS_DEFAULT, ProcLastRecPtr, RecoveryInProgress(), CheckPoint::redo, RedoRecPtr, XLogCtlInsert::RedoRecPtr, XLogCtlData::RedoRecPtr, RemoveOldXlogFiles(), ShmemVariableCache, SizeOfXLogLongPHD, SizeOfXLogShortPHD, smgrpostckpt(), smgrpreckpt(), SpinLockAcquire, SpinLockRelease, START_CRIT_SECTION, ControlFileData::state, CheckPoint::ThisTimeLineID, ThisTimeLineID, CheckPoint::time, ControlFileData::time, TruncateSUBTRANS(), XLogCtlData::ulsn_lck, ControlFileData::unloggedLSN, XLogCtlData::unloggedLSN, UpdateCheckPointDistanceEstimate(), UpdateControlFile(), wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), XLByteToSeg, XLOG_CHECKPOINT_ONLINE, XLOG_CHECKPOINT_SHUTDOWN, XLogBeginInsert(), XLogBytePosToRecPtr(), XLogFlush(), XLogInsert(), XLogRegisterData(), XLogSegmentOffset, and XLogStandbyInfoActive.

Referenced by CheckpointerMain(), RequestCheckpoint(), ShutdownXLOG(), and StartupXLOG().

8568 {
8569  bool shutdown;
8570  CheckPoint checkPoint;
8571  XLogRecPtr recptr;
8573  uint32 freespace;
8574  XLogRecPtr PriorRedoPtr;
8575  XLogRecPtr curInsert;
8576  XLogRecPtr last_important_lsn;
8577  VirtualTransactionId *vxids;
8578  int nvxids;
8579 
8580  /*
8581  * An end-of-recovery checkpoint is really a shutdown checkpoint, just
8582  * issued at a different time.
8583  */
8585  shutdown = true;
8586  else
8587  shutdown = false;
8588 
8589  /* sanity check */
8590  if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
8591  elog(ERROR, "can't create a checkpoint during recovery");
8592 
8593  /*
8594  * Initialize InitXLogInsert working areas before entering the critical
8595  * section. Normally, this is done by the first call to
8596  * RecoveryInProgress() or LocalSetXLogInsertAllowed(), but when creating
8597  * an end-of-recovery checkpoint, the LocalSetXLogInsertAllowed call is
8598  * done below in a critical section, and InitXLogInsert cannot be called
8599  * in a critical section.
8600  */
8601  InitXLogInsert();
8602 
8603  /*
8604  * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
8605  * (This is just pro forma, since in the present system structure there is
8606  * only one process that is allowed to issue checkpoints at any given
8607  * time.)
8608  */
8609  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
8610 
8611  /*
8612  * Prepare to accumulate statistics.
8613  *
8614  * Note: because it is possible for log_checkpoints to change while a
8615  * checkpoint proceeds, we always accumulate stats, even if
8616  * log_checkpoints is currently off.
8617  */
8618  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
8620 
8621  /*
8622  * Use a critical section to force system panic if we have trouble.
8623  */
8625 
8626  if (shutdown)
8627  {
8628  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8630  ControlFile->time = (pg_time_t) time(NULL);
8632  LWLockRelease(ControlFileLock);
8633  }
8634 
8635  /*
8636  * Let smgr prepare for checkpoint; this has to happen before we determine
8637  * the REDO pointer. Note that smgr must not do anything that'd have to
8638  * be undone if we decide no checkpoint is needed.
8639  */
8640  smgrpreckpt();
8641 
8642  /* Begin filling in the checkpoint WAL record */
8643  MemSet(&checkPoint, 0, sizeof(checkPoint));
8644  checkPoint.time = (pg_time_t) time(NULL);
8645 
8646  /*
8647  * For Hot Standby, derive the oldestActiveXid before we fix the redo
8648  * pointer. This allows us to begin accumulating changes to assemble our
8649  * starting snapshot of locks and transactions.
8650  */
8651  if (!shutdown && XLogStandbyInfoActive())
8653  else
8655 
8656  /*
8657  * Get location of last important record before acquiring insert locks (as
8658  * GetLastImportantRecPtr() also locks WAL locks).
8659  */
8660  last_important_lsn = GetLastImportantRecPtr();
8661 
8662  /*
8663  * We must block concurrent insertions while examining insert state to
8664  * determine the checkpoint REDO pointer.
8665  */
8667  curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
8668 
8669  /*
8670  * If this isn't a shutdown or forced checkpoint, and if there has been no
8671  * WAL activity requiring a checkpoint, skip it. The idea here is to
8672  * avoid inserting duplicate checkpoints when the system is idle.
8673  */
8674  if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
8675  CHECKPOINT_FORCE)) == 0)
8676  {
8677  if (last_important_lsn == ControlFile->checkPoint)
8678  {
8680  LWLockRelease(CheckpointLock);
8681  END_CRIT_SECTION();
8682  ereport(DEBUG1,
8683  (errmsg("checkpoint skipped because system is idle")));
8684  return;
8685  }
8686  }
8687 
8688  /*
8689  * An end-of-recovery checkpoint is created before anyone is allowed to
8690  * write WAL. To allow us to write the checkpoint record, temporarily
8691  * enable XLogInsertAllowed. (This also ensures ThisTimeLineID is
8692  * initialized, which we need here and in AdvanceXLInsertBuffer.)
8693  */
8694  if (flags & CHECKPOINT_END_OF_RECOVERY)
8696 
8697  checkPoint.ThisTimeLineID = ThisTimeLineID;
8698  if (flags & CHECKPOINT_END_OF_RECOVERY)
8699  checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8700  else
8701  checkPoint.PrevTimeLineID = ThisTimeLineID;
8702 
8703  checkPoint.fullPageWrites = Insert->fullPageWrites;
8704 
8705  /*
8706  * Compute new REDO record ptr = location of next XLOG record.
8707  *
8708  * NB: this is NOT necessarily where the checkpoint record itself will be,
8709  * since other backends may insert more XLOG records while we're off doing
8710  * the buffer flush work. Those XLOG records are logically after the
8711  * checkpoint, even though physically before it. Got that?
8712  */
8713  freespace = INSERT_FREESPACE(curInsert);
8714  if (freespace == 0)
8715  {
8716  if (XLogSegmentOffset(curInsert, wal_segment_size) == 0)
8717  curInsert += SizeOfXLogLongPHD;
8718  else
8719  curInsert += SizeOfXLogShortPHD;
8720  }
8721  checkPoint.redo = curInsert;
8722 
8723  /*
8724  * Here we update the shared RedoRecPtr for future XLogInsert calls; this
8725  * must be done while holding all the insertion locks.
8726  *
8727  * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
8728  * pointing past where it really needs to point. This is okay; the only
8729  * consequence is that XLogInsert might back up whole buffers that it
8730  * didn't really need to. We can't postpone advancing RedoRecPtr because
8731  * XLogInserts that happen while we are dumping buffers must assume that
8732  * their buffer changes are not included in the checkpoint.
8733  */
8734  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
8735 
8736  /*
8737  * Now we can release the WAL insertion locks, allowing other xacts to
8738  * proceed while we are flushing disk buffers.
8739  */
8741 
8742  /* Update the info_lck-protected copy of RedoRecPtr as well */
8744  XLogCtl->RedoRecPtr = checkPoint.redo;
8746 
8747  /*
8748  * If enabled, log checkpoint start. We postpone this until now so as not
8749  * to log anything if we decided to skip the checkpoint.
8750  */
8751  if (log_checkpoints)
8752  LogCheckpointStart(flags, false);
8753 
8754  TRACE_POSTGRESQL_CHECKPOINT_START(flags);
8755 
8756  /*
8757  * Get the other info we need for the checkpoint record.
8758  *
8759  * We don't need to save oldestClogXid in the checkpoint, it only matters
8760  * for the short period in which clog is being truncated, and if we crash
8761  * during that we'll redo the clog truncation and fix up oldestClogXid
8762  * there.
8763  */
8764  LWLockAcquire(XidGenLock, LW_SHARED);
8765  checkPoint.nextXid = ShmemVariableCache->nextXid;
8766  checkPoint.oldestXid = ShmemVariableCache->oldestXid;
8768  LWLockRelease(XidGenLock);
8769 
8770  LWLockAcquire(CommitTsLock, LW_SHARED);
8773  LWLockRelease(CommitTsLock);
8774 
8775  /* Increase XID epoch if we've wrapped around since last checkpoint */
8777  if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
8778  checkPoint.nextXidEpoch++;
8779 
8780  LWLockAcquire(OidGenLock, LW_SHARED);
8781  checkPoint.nextOid = ShmemVariableCache->nextOid;
8782  if (!shutdown)
8783  checkPoint.nextOid += ShmemVariableCache->oidCount;
8784  LWLockRelease(OidGenLock);
8785 
8786  MultiXactGetCheckptMulti(shutdown,
8787  &checkPoint.nextMulti,
8788  &checkPoint.nextMultiOffset,
8789  &checkPoint.oldestMulti,
8790  &checkPoint.oldestMultiDB);
8791 
8792  /*
8793  * Having constructed the checkpoint record, ensure all shmem disk buffers
8794  * and commit-log buffers are flushed to disk.
8795  *
8796  * This I/O could fail for various reasons. If so, we will fail to
8797  * complete the checkpoint, but there is no reason to force a system
8798  * panic. Accordingly, exit critical section while doing it.
8799  */
8800  END_CRIT_SECTION();
8801 
8802  /*
8803  * In some cases there are groups of actions that must all occur on one
8804  * side or the other of a checkpoint record. Before flushing the
8805  * checkpoint record we must explicitly wait for any backend currently
8806  * performing those groups of actions.
8807  *
8808  * One example is end of transaction, so we must wait for any transactions
8809  * that are currently in commit critical sections. If an xact inserted
8810  * its commit record into XLOG just before the REDO point, then a crash
8811  * restart from the REDO point would not replay that record, which means
8812  * that our flushing had better include the xact's update of pg_xact. So
8813  * we wait till he's out of his commit critical section before proceeding.
8814  * See notes in RecordTransactionCommit().
8815  *
8816  * Because we've already released the insertion locks, this test is a bit
8817  * fuzzy: it is possible that we will wait for xacts we didn't really need
8818  * to wait for. But the delay should be short and it seems better to make
8819  * checkpoint take a bit longer than to hold off insertions longer than
8820  * necessary. (In fact, the whole reason we have this issue is that xact.c
8821  * does commit record XLOG insertion and clog update as two separate steps
8822  * protected by different locks, but again that seems best on grounds of
8823  * minimizing lock contention.)
8824  *
8825  * A transaction that has not yet set delayChkpt when we look cannot be at
8826  * risk, since he's not inserted his commit record yet; and one that's
8827  * already cleared it is not at risk either, since he's done fixing clog
8828  * and we will correctly flush the update below. So we cannot miss any
8829  * xacts we need to wait for.
8830  */
8831  vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
8832  if (nvxids > 0)
8833  {
8834  do
8835  {
8836  pg_usleep(10000L); /* wait for 10 msec */
8837  } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
8838  }
8839  pfree(vxids);
8840 
8841  CheckPointGuts(checkPoint.redo, flags);
8842 
8843  /*
8844  * Take a snapshot of running transactions and write this to WAL. This
8845  * allows us to reconstruct the state of running transactions during
8846  * archive recovery, if required. Skip, if this info disabled.
8847  *
8848  * If we are shutting down, or Startup process is completing crash
8849  * recovery we don't need to write running xact data.
8850  */
8851  if (!shutdown && XLogStandbyInfoActive())
8853 
8855 
8856  /*
8857  * Now insert the checkpoint record into XLOG.
8858  */
8859  XLogBeginInsert();
8860  XLogRegisterData((char *) (&checkPoint), sizeof(checkPoint));
8861  recptr = XLogInsert(RM_XLOG_ID,
8862  shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
8864 
8865  XLogFlush(recptr);
8866 
8867  /*
8868  * We mustn't write any new WAL after a shutdown checkpoint, or it will be
8869  * overwritten at next startup. No-one should even try, this just allows
8870  * sanity-checking. In the case of an end-of-recovery checkpoint, we want
8871  * to just temporarily disable writing until the system has exited
8872  * recovery.
8873  */
8874  if (shutdown)
8875  {
8876  if (flags & CHECKPOINT_END_OF_RECOVERY)
8877  LocalXLogInsertAllowed = -1; /* return to "check" state */
8878  else
8879  LocalXLogInsertAllowed = 0; /* never again write WAL */
8880  }
8881 
8882  /*
8883  * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
8884  * = end of actual checkpoint record.
8885  */
8886  if (shutdown && checkPoint.redo != ProcLastRecPtr)
8887  ereport(PANIC,
8888  (errmsg("concurrent write-ahead log activity while database system is shutting down")));
8889 
8890  /*
8891  * Remember the prior checkpoint's redo ptr for UpdateCheckPointDistanceEstimate()
8892  */
8893  PriorRedoPtr = ControlFile->checkPointCopy.redo;
8894 
8895  /*
8896  * Update the control file.
8897  */
8898  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8899  if (shutdown)
8902  ControlFile->checkPointCopy = checkPoint;
8903  ControlFile->time = (pg_time_t) time(NULL);
8904  /* crash recovery should always recover to the end of WAL */
8907 
8908  /*
8909  * Persist unloggedLSN value. It's reset on crash recovery, so this goes
8910  * unused on non-shutdown checkpoints, but seems useful to store it always
8911  * for debugging purposes.
8912  */
8916 
8918  LWLockRelease(ControlFileLock);
8919 
8920  /* Update shared-memory copy of checkpoint XID/epoch */
8922  XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
8923  XLogCtl->ckptXid = checkPoint.nextXid;
8925 
8926  /*
8927  * We are now done with critical updates; no need for system panic if we
8928  * have trouble while fooling with old log segments.
8929  */
8930  END_CRIT_SECTION();
8931 
8932  /*
8933  * Let smgr do post-checkpoint cleanup (eg, deleting old files).
8934  */
8935  smgrpostckpt();
8936 
8937  /*
8938  * Delete old log files and recycle them
8939  */
8940  if (PriorRedoPtr != InvalidXLogRecPtr)
8941  {
8942  XLogSegNo _logSegNo;
8943 
8944  /* Update the average distance between checkpoints. */
8946 
8947  /* Trim from the last checkpoint, not the last - 1 */
8949  KeepLogSeg(recptr, &_logSegNo);
8950  _logSegNo--;
8951  RemoveOldXlogFiles(_logSegNo, PriorRedoPtr, recptr);
8952  }
8953 
8954  /*
8955  * Make more log segments if needed. (Do this after recycling old log
8956  * segments, since that may supply some of the needed files.)
8957  */
8958  if (!shutdown)
8959  PreallocXlogFiles(recptr);
8960 
8961  /*
8962  * Truncate pg_subtrans if possible. We can throw away all data before
8963  * the oldest XMIN of any running transaction. No future transaction will
8964  * attempt to reference any pg_subtrans entry older than that (see Asserts
8965  * in subtrans.c). During recovery, though, we mustn't do this because
8966  * StartupSUBTRANS hasn't been called yet.
8967  */
8968  if (!RecoveryInProgress())
8970 
8971  /* Real work is done, but log and update stats before releasing lock. */
8972  LogCheckpointEnd(false);
8973 
8974  TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
8975  NBuffers,
8979 
8980  LWLockRelease(CheckpointLock);
8981 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8279
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8505
static int LocalXLogInsertAllowed
Definition: xlog.c:235
bool log_checkpoints
Definition: xlog.c:102
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
int64 pg_time_t
Definition: pgtime.h:23
TransactionId ckptXid
Definition: xlog.c:583
static void WALInsertLockRelease(void)
Definition: xlog.c:1651
int wal_segment_size
Definition: xlog.c:113
pg_time_t time
Definition: pg_control.h:128
#define XLOG_CHECKPOINT_ONLINE
Definition: pg_control.h:68
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
uint32 oidCount
Definition: transam.h:112
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:1920
XLogRecPtr unloggedLSN
Definition: xlog.c:590
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:338
TransactionId oldestActiveXid
Definition: pg_control.h:63
void InitXLogInsert(void)
Definition: xloginsert.c:1028
TimestampTz ckpt_start_t
Definition: xlog.h:199
slock_t info_lck
Definition: xlog.c:704
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids)
Definition: procarray.c:2254
MultiXactId oldestMulti
Definition: pg_control.h:49
TimeLineID PrevTimeLineID
Definition: xlog.c:631
TimeLineID PrevTimeLineID
Definition: pg_control.h:39
#define START_CRIT_SECTION()
Definition: miscadmin.h:131
int ckpt_segs_recycled
Definition: xlog.h:209
TransactionId oldestXid
Definition: transam.h:119
#define MemSet(start, val, len)
Definition: c.h:853
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
Definition: xlog.c:3834
void MultiXactGetCheckptMulti(bool is_shutdown, MultiXactId *nextMulti, MultiXactOffset *nextMultiOffset, MultiXactId *oldestMulti, Oid *oldestMultiDB)
Definition: multixact.c:2118
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:9042
CheckPoint checkPointCopy
Definition: pg_control.h:131
XLogCtlInsert Insert
Definition: xlog.c:577
TransactionId oldestXid
Definition: pg_control.h:47
bool RecoveryInProgress(void)
Definition: xlog.c:7929
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:354
uint32 ckptXidEpoch
Definition: xlog.c:582
TransactionId nextXid
Definition: pg_control.h:43
pg_time_t time
Definition: pg_control.h:51
#define PANIC
Definition: elog.h:53
bool fullPageWrites
Definition: xlog.c:552
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2763
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
MultiXactOffset nextMultiOffset
Definition: pg_control.h:46
void UpdateControlFile(void)
Definition: xlog.c:4670
TransactionId oldestCommitTsXid
Definition: pg_control.h:52
void pfree(void *pointer)
Definition: mcxt.c:949
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:909
#define ERROR
Definition: elog.h:43
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8420
TransactionId nextXid
Definition: transam.h:117
uint32 nextXidEpoch
Definition: pg_control.h:42
static XLogRecPtr RedoRecPtr
Definition: xlog.c:352
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
XLogRecPtr unloggedLSN
Definition: pg_control.h:133
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3741
uint64 XLogSegNo
Definition: xlogdefs.h:34
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:177
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
uint64 CurrBytePos
Definition: xlog.c:528
unsigned int uint32
Definition: c.h:296
XLogRecPtr RedoRecPtr
Definition: xlog.c:581
int ckpt_segs_removed
Definition: xlog.h:208
#define CHECKPOINT_FORCE
Definition: xlog.h:180
#define INSERT_FREESPACE(endptr)
Definition: xlog.c:721
#define ereport(elevel, rest)
Definition: elog.h:122
TransactionId oldestCommitTsXid
Definition: transam.h:129
static void Insert(File file)
Definition: fd.c:1059
int ckpt_bufs_written
Definition: xlog.h:205
static void LocalSetXLogInsertAllowed(void)
Definition: xlog.c:8055
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
TransactionId newestCommitTsXid
Definition: pg_control.h:54
#define PROCARRAY_FLAGS_DEFAULT
Definition: procarray.h:50
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9364
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
Oid oldestMultiDB
Definition: pg_control.h:50
#define XLogStandbyInfoActive()
Definition: xlog.h:160
static ControlFileData * ControlFile
Definition: xlog.c:715
TimeLineID ThisTimeLineID
Definition: xlog.c:181
Oid nextOid
Definition: pg_control.h:44
bool fullPageWrites
Definition: pg_control.h:41
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1315
void smgrpreckpt(void)
Definition: smgr.c:744
uint64 XLogRecPtr
Definition: xlogdefs.h:21
Oid oldestXidDB
Definition: pg_control.h:48
TransactionId newestCommitTsXid
Definition: transam.h:130
CheckpointStatsData CheckpointStats
Definition: xlog.c:175
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:55
MultiXactId nextMulti
Definition: pg_control.h:45
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1622
static XLogCtlData * XLogCtl
Definition: xlog.c:707
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
int ckpt_segs_added
Definition: xlog.h:207
slock_t ulsn_lck
Definition: xlog.c:591
TimeLineID ThisTimeLineID
Definition: pg_control.h:38
int errmsg(const char *fmt,...)
Definition: elog.c:797
TransactionId GetOldestActiveTransactionId(void)
Definition: procarray.c:2092
int NBuffers
Definition: globals.c:122
#define elog
Definition: elog.h:219
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids)
Definition: procarray.c:2299
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr RedoRecPtr
Definition: xlog.c:550
void smgrpostckpt(void)
Definition: smgr.c:774
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:36
static void LogCheckpointStart(int flags, bool restartpoint)
Definition: xlog.c:8402
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:176
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:72
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ CreateEndOfRecoveryRecord()

static void CreateEndOfRecoveryRecord ( void  )
static

Definition at line 8993 of file xlog.c.

References elog, END_CRIT_SECTION, xl_end_of_recovery::end_time, ERROR, GetCurrentTimestamp(), LocalSetXLogInsertAllowed(), LocalXLogInsertAllowed, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ControlFileData::minRecoveryPoint, ControlFileData::minRecoveryPointTLI, xl_end_of_recovery::PrevTimeLineID, XLogCtlData::PrevTimeLineID, RecoveryInProgress(), START_CRIT_SECTION, ThisTimeLineID, xl_end_of_recovery::ThisTimeLineID, ControlFileData::time, UpdateControlFile(), WALInsertLockAcquireExclusive(), WALInsertLockRelease(), XLOG_END_OF_RECOVERY, XLogBeginInsert(), XLogFlush(), XLogInsert(), and XLogRegisterData().

Referenced by StartupXLOG().

8994 {
8995  xl_end_of_recovery xlrec;
8996  XLogRecPtr recptr;
8997 
8998  /* sanity check */
8999  if (!RecoveryInProgress())
9000  elog(ERROR, "can only be used to end recovery");
9001 
9002  xlrec.end_time = GetCurrentTimestamp();
9003 
9008 
9010 
9012 
9013  XLogBeginInsert();
9014  XLogRegisterData((char *) &xlrec, sizeof(xl_end_of_recovery));
9015  recptr = XLogInsert(RM_XLOG_ID, XLOG_END_OF_RECOVERY);
9016 
9017  XLogFlush(recptr);
9018 
9019  /*
9020  * Update the control file so that crash recovery can follow the timeline
9021  * changes to this point.
9022  */
9023  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9024  ControlFile->time = (pg_time_t) time(NULL);
9025  ControlFile->minRecoveryPoint = recptr;
9028  LWLockRelease(ControlFileLock);
9029 
9030  END_CRIT_SECTION();
9031 
9032  LocalXLogInsertAllowed = -1; /* return to "check" state */
9033 }
static int LocalXLogInsertAllowed
Definition: xlog.c:235
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1651
pg_time_t time
Definition: pg_control.h:128
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
TimeLineID PrevTimeLineID
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
TimeLineID PrevTimeLineID
Definition: xlog.c:631
#define START_CRIT_SECTION()
Definition: miscadmin.h:131
bool RecoveryInProgress(void)
Definition: xlog.c:7929
#define XLOG_END_OF_RECOVERY
Definition: pg_control.h:76
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2763
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void UpdateControlFile(void)
Definition: xlog.c:4670
#define ERROR
Definition: elog.h:43
static void LocalSetXLogInsertAllowed(void)
Definition: xlog.c:8055
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
static ControlFileData * ControlFile
Definition: xlog.c:715
TimeLineID ThisTimeLineID
Definition: xlog.c:181
TimestampTz end_time
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1622
static XLogCtlData * XLogCtl
Definition: xlog.c:707
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
TimeLineID ThisTimeLineID
#define elog
Definition: elog.h:219
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166

◆ CreateRestartPoint()

bool CreateRestartPoint ( int  flags)

Definition at line 9112 of file xlog.c.

References XLogCtlData::archiveCleanupCommand, ControlFileData::checkPoint, CHECKPOINT_IS_SHUTDOWN, ControlFileData::checkPointCopy, CheckPointGuts(), CheckpointStatsData::ckpt_start_t, DB_IN_ARCHIVE_RECOVERY, DB_SHUTDOWNED_IN_RECOVERY, DEBUG2, EnableHotStandby, ereport, errdetail(), errmsg(), ExecuteRecoveryCommand(), GetCurrentTimestamp(), GetLatestXTime(), GetOldestXmin(), GetWalRcvWriteRecPtr(), GetXLogReplayRecPtr(), XLogCtlData::info_lck, XLogCtlData::Insert, InvalidXLogRecPtr, KeepLogSeg(), XLogCtlData::lastCheckPoint, XLogCtlData::lastCheckPointEndPtr, XLogCtlData::lastCheckPointRecPtr, LOG, log_checkpoints, LogCheckpointEnd(), LogCheckpointStart(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MemSet, ControlFileData::minRecoveryPoint, minRecoveryPoint, ControlFileData::minRecoveryPointTLI, minRecoveryPointTLI, PreallocXlogFiles(), PROCARRAY_FLAGS_DEFAULT, RecoveryInProgress(), CheckPoint::redo, RedoRecPtr, XLogCtlInsert::RedoRecPtr, XLogCtlData::RedoRecPtr, RemoveOldXlogFiles(), SpinLockAcquire, SpinLockRelease, ControlFileData::state, CheckPoint::ThisTimeLineID, ThisTimeLineID, ControlFileData::time, timestamptz_to_str(), TruncateSUBTRANS(), UpdateCheckPointDistanceEstimate(), UpdateControlFile(), UpdateMinRecoveryPoint(), wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), XLByteToSeg, and XLogRecPtrIsInvalid.

Referenced by CheckpointerMain(), and ShutdownXLOG().

9113 {
9114  XLogRecPtr lastCheckPointRecPtr;
9115  XLogRecPtr lastCheckPointEndPtr;
9116  CheckPoint lastCheckPoint;
9117  XLogRecPtr PriorRedoPtr;
9118  TimestampTz xtime;
9119 
9120  /*
9121  * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
9122  * happens at a time.
9123  */
9124  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
9125 
9126  /* Get a local copy of the last safe checkpoint record. */
9128  lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
9129  lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
9130  lastCheckPoint = XLogCtl->lastCheckPoint;
9132 
9133  /*
9134  * Check that we're still in recovery mode. It's ok if we exit recovery
9135  * mode after this check, the restart point is valid anyway.
9136  */
9137  if (!RecoveryInProgress())
9138  {
9139  ereport(DEBUG2,
9140  (errmsg("skipping restartpoint, recovery has already ended")));
9141  LWLockRelease(CheckpointLock);
9142  return false;
9143  }
9144 
9145  /*
9146  * If the last checkpoint record we've replayed is already our last
9147  * restartpoint, we can't perform a new restart point. We still update
9148  * minRecoveryPoint in that case, so that if this is a shutdown restart
9149  * point, we won't start up earlier than before. That's not strictly
9150  * necessary, but when hot standby is enabled, it would be rather weird if
9151  * the database opened up for read-only connections at a point-in-time
9152  * before the last shutdown. Such time travel is still possible in case of
9153  * immediate shutdown, though.
9154  *
9155  * We don't explicitly advance minRecoveryPoint when we do create a
9156  * restartpoint. It's assumed that flushing the buffers will do that as a
9157  * side-effect.
9158  */
9159  if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
9160  lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
9161  {
9162  ereport(DEBUG2,
9163  (errmsg("skipping restartpoint, already performed at %X/%X",
9164  (uint32) (lastCheckPoint.redo >> 32),
9165  (uint32) lastCheckPoint.redo)));
9166 
9168  if (flags & CHECKPOINT_IS_SHUTDOWN)
9169  {
9170  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9172  ControlFile->time = (pg_time_t) time(NULL);
9174  LWLockRelease(ControlFileLock);
9175  }
9176  LWLockRelease(CheckpointLock);
9177  return false;
9178  }
9179 
9180  /*
9181  * Update the shared RedoRecPtr so that the startup process can calculate
9182  * the number of segments replayed since last restartpoint, and request a
9183  * restartpoint if it exceeds CheckPointSegments.
9184  *
9185  * Like in CreateCheckPoint(), hold off insertions to update it, although
9186  * during recovery this is just pro forma, because no WAL insertions are
9187  * happening.
9188  */
9190  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
9192 
9193  /* Also update the info_lck-protected copy */
9195  XLogCtl->RedoRecPtr = lastCheckPoint.redo;
9197 
9198  /*
9199  * Prepare to accumulate statistics.
9200  *
9201  * Note: because it is possible for log_checkpoints to change while a
9202  * checkpoint proceeds, we always accumulate stats, even if
9203  * log_checkpoints is currently off.
9204  */
9205  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
9207 
9208  if (log_checkpoints)
9209  LogCheckpointStart(flags, true);
9210 
9211  CheckPointGuts(lastCheckPoint.redo, flags);
9212 
9213  /*
9214  * Remember the prior checkpoint's redo ptr for UpdateCheckPointDistanceEstimate()
9215  */
9216  PriorRedoPtr = ControlFile->checkPointCopy.redo;
9217 
9218  /*
9219  * Update pg_control, using current time. Check that it still shows
9220  * IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
9221  * this is a quick hack to make sure nothing really bad happens if somehow
9222  * we get here after the end-of-recovery checkpoint.
9223  */
9224  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9226  ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
9227  {
9228  ControlFile->checkPoint = lastCheckPointRecPtr;
9229  ControlFile->checkPointCopy = lastCheckPoint;
9230  ControlFile->time = (pg_time_t) time(NULL);
9231 
9232  /*
9233  * Ensure minRecoveryPoint is past the checkpoint record. Normally,
9234  * this will have happened already while writing out dirty buffers,
9235  * but not necessarily - e.g. because no buffers were dirtied. We do
9236  * this because a non-exclusive base backup uses minRecoveryPoint to
9237  * determine which WAL files must be included in the backup, and the
9238  * file (or files) containing the checkpoint record must be included,
9239  * at a minimum. Note that for an ordinary restart of recovery there's
9240  * no value in having the minimum recovery point any earlier than this
9241  * anyway, because redo will begin just after the checkpoint record.
9242  */
9243  if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
9244  {
9245  ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
9247 
9248  /* update local copy */
9251  }
9252  if (flags & CHECKPOINT_IS_SHUTDOWN)
9255  }
9256  LWLockRelease(ControlFileLock);
9257 
9258  /*
9259  * Delete old log files (those no longer needed even for previous
9260  * checkpoint/restartpoint) to prevent the disk holding the xlog from
9261  * growing full.
9262  */
9263  if (PriorRedoPtr != InvalidXLogRecPtr)
9264  {
9265  XLogRecPtr receivePtr;
9266  XLogRecPtr replayPtr;
9267  TimeLineID replayTLI;
9268  XLogRecPtr endptr;
9269  XLogSegNo _logSegNo;
9270 
9271  /* Update the average distance between checkpoints/restartpoints. */
9273 
9274  XLByteToSeg(PriorRedoPtr, _logSegNo, wal_segment_size);
9275 
9276  /*
9277  * Get the current end of xlog replayed or received, whichever is
9278  * later.
9279  */
9280  receivePtr = GetWalRcvWriteRecPtr(NULL, NULL);
9281  replayPtr = GetXLogReplayRecPtr(&replayTLI);
9282  endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
9283 
9284  KeepLogSeg(endptr, &_logSegNo);
9285  _logSegNo--;
9286 
9287  /*
9288  * Try to recycle segments on a useful timeline. If we've been
9289  * promoted since the beginning of this restartpoint, use the new
9290  * timeline chosen at end of recovery (RecoveryInProgress() sets
9291  * ThisTimeLineID in that case). If we're still in recovery, use the
9292  * timeline we're currently replaying.
9293  *
9294  * There is no guarantee that the WAL segments will be useful on the
9295  * current timeline; if recovery proceeds to a new timeline right
9296  * after this, the pre-allocated WAL segments on this timeline will
9297  * not be used, and will go wasted until recycled on the next
9298  * restartpoint. We'll live with that.
9299  */
9300  if (RecoveryInProgress())
9301  ThisTimeLineID = replayTLI;
9302 
9303  RemoveOldXlogFiles(_logSegNo, PriorRedoPtr, endptr);
9304 
9305  /*
9306  * Make more log segments if needed. (Do this after recycling old log
9307  * segments, since that may supply some of the needed files.)
9308  */
9309  PreallocXlogFiles(endptr);
9310 
9311  /*
9312  * ThisTimeLineID is normally not set when we're still in recovery.
9313  * However, recycling/preallocating segments above needed
9314  * ThisTimeLineID to determine which timeline to install the segments
9315  * on. Reset it now, to restore the normal state of affairs for
9316  * debugging purposes.
9317  */
9318  if (RecoveryInProgress())
9319  ThisTimeLineID = 0;
9320  }
9321 
9322  /*
9323  * Truncate pg_subtrans if possible. We can throw away all data before
9324  * the oldest XMIN of any running transaction. No future transaction will
9325  * attempt to reference any pg_subtrans entry older than that (see Asserts
9326  * in subtrans.c). When hot standby is disabled, though, we mustn't do
9327  * this because StartupSUBTRANS hasn't been called yet.
9328  */
9329  if (EnableHotStandby)
9331 
9332  /* Real work is done, but log and update before releasing lock. */
9333  LogCheckpointEnd(true);
9334 
9335  xtime = GetLatestXTime();
9337  (errmsg("recovery restart point at %X/%X",
9338  (uint32) (lastCheckPoint.redo >> 32), (uint32) lastCheckPoint.redo),
9339  xtime ? errdetail("last completed transaction was at log time %s",
9340  timestamptz_to_str(xtime)) : 0));
9341 
9342  LWLockRelease(CheckpointLock);
9343 
9344  /*
9345  * Finally, execute archive_cleanup_command, if any.
9346  */
9349  "archive_cleanup_command",
9350  false);
9351 
9352  return true;
9353 }
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8505
bool log_checkpoints
Definition: xlog.c:102
void ExecuteRecoveryCommand(const char *command, const char *commandName, bool failOnSignal)
Definition: xlogarchive.c:330
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TimeLineID
Definition: xlogdefs.h:45
int64 pg_time_t
Definition: pgtime.h:23
XLogRecPtr GetWalRcvWriteRecPtr(XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI)
static void WALInsertLockRelease(void)
Definition: xlog.c:1651
int wal_segment_size
Definition: xlog.c:113
pg_time_t time
Definition: pg_control.h:128
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
Definition: xlog.c:2688
TimestampTz ckpt_start_t
Definition: xlog.h:199
slock_t info_lck
Definition: xlog.c:704
#define MemSet(start, val, len)
Definition: c.h:853
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
Definition: xlog.c:3834
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:9042
TimestampTz GetLatestXTime(void)
Definition: xlog.c:6136
CheckPoint checkPointCopy
Definition: pg_control.h:131
XLogCtlInsert Insert
Definition: xlog.c:577
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:7929
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:354
XLogRecPtr lastCheckPointRecPtr
Definition: xlog.c:673
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define SpinLockAcquire(lock)
Definition: spin.h:62
void UpdateControlFile(void)
Definition: xlog.c:4670
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8420
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11128
#define DEBUG2
Definition: elog.h:24
static XLogRecPtr RedoRecPtr
Definition: xlog.c:352
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3741
uint64 XLogSegNo
Definition: xlogdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:873
unsigned int uint32
Definition: c.h:296
XLogRecPtr RedoRecPtr
Definition: xlog.c:581
#define ereport(elevel, rest)
Definition: elog.h:122
CheckPoint lastCheckPoint
Definition: xlog.c:675
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define SpinLockRelease(lock)
Definition: spin.h:64
static TimeLineID minRecoveryPointTLI
Definition: xlog.c:826
#define PROCARRAY_FLAGS_DEFAULT
Definition: procarray.h:50
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9364
static ControlFileData * ControlFile
Definition: xlog.c:715
TimeLineID ThisTimeLineID
Definition: xlog.c:181
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1315
uint64 XLogRecPtr
Definition: xlogdefs.h:21
CheckpointStatsData CheckpointStats
Definition: xlog.c:175
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1622
static XLogCtlData * XLogCtl
Definition: xlog.c:707
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
char archiveCleanupCommand[MAXPGPATH]
Definition: xlog.c:637
bool EnableHotStandby
Definition: xlog.c:96
TimeLineID ThisTimeLineID
Definition: pg_control.h:38
int errmsg(const char *fmt,...)
Definition: elog.c:797
XLogRecPtr RedoRecPtr
Definition: xlog.c:550
XLogRecPtr lastCheckPointEndPtr
Definition: xlog.c:674
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:36
static void LogCheckpointStart(int flags, bool restartpoint)
Definition: xlog.c:8402
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:176
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
static XLogRecPtr minRecoveryPoint
Definition: xlog.c:824
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1710
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ DataChecksumsEnabled()

bool DataChecksumsEnabled ( void  )

Definition at line 4738 of file xlog.c.

References Assert, and ControlFileData::data_checksum_version.

Referenced by PageIsVerified(), PageSetChecksumCopy(), PageSetChecksumInplace(), and ReadControlFile().

4739 {
4740  Assert(ControlFile != NULL);
4741  return (ControlFile->data_checksum_version > 0);
4742 }
uint32 data_checksum_version
Definition: pg_control.h:221
static ControlFileData * ControlFile
Definition: xlog.c:715
#define Assert(condition)
Definition: c.h:670

◆ do_pg_abort_backup()

void do_pg_abort_backup ( void  )

Definition at line 11108 of file xlog.c.

References Assert, EXCLUSIVE_BACKUP_NONE, XLogCtlInsert::exclusiveBackupState, XLogCtlInsert::forcePageWrites, XLogCtlData::Insert, XLogCtlInsert::nonExclusiveBackups, WALInsertLockAcquireExclusive(), and WALInsertLockRelease().

Referenced by base_backup_cleanup(), and nonexclusive_base_backup_cleanup().

11109 {
11113 
11116  {
11117  XLogCtl->Insert.forcePageWrites = false;
11118  }
11120 }
static void WALInsertLockRelease(void)
Definition: xlog.c:1651
XLogCtlInsert Insert
Definition: xlog.c:577
bool forcePageWrites
Definition: xlog.c:551
int nonExclusiveBackups
Definition: xlog.c:563
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:562
#define Assert(condition)
Definition: c.h:670
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1622
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ do_pg_start_backup()

XLogRecPtr do_pg_start_backup ( const char *  backupidstr,
bool  fast,
TimeLineID starttli_p,
StringInfo  labelfile,
DIR tblspcdir,
List **  tablespaces,
StringInfo  tblspcmapfile,
bool  infotbssize,
bool  needtblspcmapfile 
)

Definition at line 10213 of file xlog.c.

References AllocateFile(), appendStringInfo(), appendStringInfoChar(), BACKUP_LABEL_FILE, backup_started_in_recovery, BoolGetDatum, ControlFileData::checkPoint, CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, ControlFileData::checkPointCopy, dirent::d_name, StringInfoData::data, DataDir, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, EXCLUSIVE_BACKUP_IN_PROGRESS, EXCLUSIVE_BACKUP_NONE, EXCLUSIVE_BACKUP_STARTING, XLogCtlInsert::exclusiveBackupState, XLogCtlInsert::forcePageWrites, FreeFile(), CheckPoint::fullPageWrites, XLogCtlData::info_lck, initStringInfo(), XLogCtlData::Insert, IS_DIR_SEP, lappend(), XLogCtlInsert::lastBackupStart, XLogCtlData::lastFpwDisableRecPtr, StringInfoData::len, log_timezone, LW_SHARED, LWLockAcquire(), LWLockRelease(), makeStringInfo(), MAXFNAMELEN, MAXPGPATH, XLogCtlInsert::nonExclusiveBackups, tablespaceinfo::oid, palloc(), tablespaceinfo::path, pfree(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_fsync(), pg_localtime(), pg_start_backup_callback(), pg_strftime(), pstrdup(), ReadDir(), readlink, RecoveryInProgress(), CheckPoint::redo, relpath, RequestCheckpoint(), RequestXLogSwitch(), tablespaceinfo::rpath, sendTablespace(), SESSION_BACKUP_EXCLUSIVE, SESSION_BACKUP_NON_EXCLUSIVE, sessionBackupState, tablespaceinfo::size, snprintf(), SpinLockAcquire, SpinLockRelease, stat, TABLESPACE_MAP, CheckPoint::ThisTimeLineID, wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), WARNING, XLByteToSeg, XLogFileName, and XLogIsNeeded.

Referenced by perform_base_backup(), and pg_start_backup().

10217 {
10218  bool exclusive = (labelfile == NULL);
10219  bool backup_started_in_recovery = false;
10220  XLogRecPtr checkpointloc;
10221  XLogRecPtr startpoint;
10222  TimeLineID starttli;
10223  pg_time_t stamp_time;
10224  char strfbuf[128];
10225  char xlogfilename[MAXFNAMELEN];
10226  XLogSegNo _logSegNo;
10227  struct stat stat_buf;
10228  FILE *fp;
10229 
10230  backup_started_in_recovery = RecoveryInProgress();
10231 
10232  /*
10233  * Currently only non-exclusive backup can be taken during recovery.
10234  */
10235  if (backup_started_in_recovery && exclusive)
10236  ereport(ERROR,
10237  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10238  errmsg("recovery is in progress"),
10239  errhint("WAL control functions cannot be executed during recovery.")));
10240 
10241  /*
10242  * During recovery, we don't need to check WAL level. Because, if WAL
10243  * level is not sufficient, it's impossible to get here during recovery.
10244  */
10245  if (!backup_started_in_recovery && !XLogIsNeeded())
10246  ereport(ERROR,
10247  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10248  errmsg("WAL level not sufficient for making an online backup"),
10249  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
10250 
10251  if (strlen(backupidstr) > MAXPGPATH)
10252  ereport(ERROR,
10253  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10254  errmsg("backup label too long (max %d bytes)",
10255  MAXPGPATH)));
10256 
10257  /*
10258  * Mark backup active in shared memory. We must do full-page WAL writes
10259  * during an on-line backup even if not doing so at other times, because
10260  * it's quite possible for the backup dump to obtain a "torn" (partially
10261  * written) copy of a database page if it reads the page concurrently with
10262  * our write to the same page. This can be fixed as long as the first
10263  * write to the page in the WAL sequence is a full-page write. Hence, we
10264  * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
10265  * are no dirty pages in shared memory that might get dumped while the
10266  * backup is in progress without having a corresponding WAL record. (Once
10267  * the backup is complete, we need not force full-page writes anymore,
10268  * since we expect that any pages not modified during the backup interval
10269  * must have been correctly captured by the backup.)
10270  *
10271  * Note that forcePageWrites has no effect during an online backup from
10272  * the standby.
10273  *
10274  * We must hold all the insertion locks to change the value of
10275  * forcePageWrites, to ensure adequate interlocking against
10276  * XLogInsertRecord().
10277  */
10279  if (exclusive)
10280  {
10281  /*
10282  * At first, mark that we're now starting an exclusive backup, to
10283  * ensure that there are no other sessions currently running
10284  * pg_start_backup() or pg_stop_backup().
10285  */
10287  {
10289  ereport(ERROR,
10290  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10291  errmsg("a backup is already in progress"),
10292  errhint("Run pg_stop_backup() and try again.")));
10293  }
10295  }
10296  else
10298  XLogCtl->Insert.forcePageWrites = true;
10300 
10301  /* Ensure we release forcePageWrites if fail below */
10303  {
10304  bool gotUniqueStartpoint = false;
10305  struct dirent *de;
10306  tablespaceinfo *ti;
10307  int datadirpathlen;
10308 
10309  /*
10310  * Force an XLOG file switch before the checkpoint, to ensure that the
10311  * WAL segment the checkpoint is written to doesn't contain pages with
10312  * old timeline IDs. That would otherwise happen if you called
10313  * pg_start_backup() right after restoring from a PITR archive: the
10314  * first WAL segment containing the startup checkpoint has pages in
10315  * the beginning with the old timeline ID. That can cause trouble at
10316  * recovery: we won't have a history file covering the old timeline if
10317  * pg_wal directory was not included in the base backup and the WAL
10318  * archive was cleared too before starting the backup.
10319  *
10320  * This also ensures that we have emitted a WAL page header that has
10321  * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
10322  * Therefore, if a WAL archiver (such as pglesslog) is trying to
10323  * compress out removable backup blocks, it won't remove any that
10324  * occur after this point.
10325  *
10326  * During recovery, we skip forcing XLOG file switch, which means that
10327  * the backup taken during recovery is not available for the special
10328  * recovery case described above.
10329  */
10330  if (!backup_started_in_recovery)
10331  RequestXLogSwitch(false);
10332 
10333  do
10334  {
10335  bool checkpointfpw;
10336 
10337  /*
10338  * Force a CHECKPOINT. Aside from being necessary to prevent torn
10339  * page problems, this guarantees that two successive backup runs
10340  * will have different checkpoint positions and hence different
10341  * history file names, even if nothing happened in between.
10342  *
10343  * During recovery, establish a restartpoint if possible. We use
10344  * the last restartpoint as the backup starting checkpoint. This
10345  * means that two successive backup runs can have same checkpoint
10346  * positions.
10347  *
10348  * Since the fact that we are executing do_pg_start_backup()
10349  * during recovery means that checkpointer is running, we can use
10350  * RequestCheckpoint() to establish a restartpoint.
10351  *
10352  * We use CHECKPOINT_IMMEDIATE only if requested by user (via
10353  * passing fast = true). Otherwise this can take awhile.
10354  */
10356  (fast ? CHECKPOINT_IMMEDIATE : 0));
10357 
10358  /*
10359  * Now we need to fetch the checkpoint record location, and also
10360  * its REDO pointer. The oldest point in WAL that would be needed
10361  * to restore starting from the checkpoint is precisely the REDO
10362  * pointer.
10363  */
10364  LWLockAcquire(ControlFileLock, LW_SHARED);
10365  checkpointloc = ControlFile->checkPoint;
10366  startpoint = ControlFile->checkPointCopy.redo;
10368  checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
10369  LWLockRelease(ControlFileLock);
10370 
10371  if (backup_started_in_recovery)
10372  {
10373  XLogRecPtr recptr;
10374 
10375  /*
10376  * Check to see if all WAL replayed during online backup
10377  * (i.e., since last restartpoint used as backup starting
10378  * checkpoint) contain full-page writes.
10379  */
10381  recptr = XLogCtl->lastFpwDisableRecPtr;
10383 
10384  if (!checkpointfpw || startpoint <= recptr)
10385  ereport(ERROR,
10386  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10387  errmsg("WAL generated with full_page_writes=off was replayed "
10388  "since last restartpoint"),
10389  errhint("This means that the backup being taken on the standby "
10390  "is corrupt and should not be used. "
10391  "Enable full_page_writes and run CHECKPOINT on the master, "
10392  "and then try an online backup again.")));
10393 
10394  /*
10395  * During recovery, since we don't use the end-of-backup WAL
10396  * record and don't write the backup history file, the
10397  * starting WAL location doesn't need to be unique. This means
10398  * that two base backups started at the same time might use
10399  * the same checkpoint as starting locations.
10400  */
10401  gotUniqueStartpoint = true;
10402  }
10403 
10404  /*
10405  * If two base backups are started at the same time (in WAL sender
10406  * processes), we need to make sure that they use different
10407  * checkpoints as starting locations, because we use the starting
10408  * WAL location as a unique identifier for the base backup in the
10409  * end-of-backup WAL record and when we write the backup history
10410  * file. Perhaps it would be better generate a separate unique ID
10411  * for each backup instead of forcing another checkpoint, but
10412  * taking a checkpoint right after another is not that expensive
10413  * either because only few buffers have been dirtied yet.
10414  */
10416  if (XLogCtl->Insert.lastBackupStart < startpoint)
10417  {
10418  XLogCtl->Insert.lastBackupStart = startpoint;
10419  gotUniqueStartpoint = true;
10420  }
10422  } while (!gotUniqueStartpoint);
10423 
10424  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
10425  XLogFileName(xlogfilename, starttli, _logSegNo, wal_segment_size);
10426 
10427  /*
10428  * Construct tablespace_map file
10429  */
10430  if (exclusive)
10431  tblspcmapfile = makeStringInfo();
10432 
10433  datadirpathlen = strlen(DataDir);
10434 
10435  /* Collect information about all tablespaces */
10436  while ((de = ReadDir(tblspcdir, "pg_tblspc")) != NULL)
10437  {
10438  char fullpath[MAXPGPATH + 10];
10439  char linkpath[MAXPGPATH];
10440  char *relpath = NULL;
10441  int rllen;
10442  StringInfoData buflinkpath;
10443  char *s = linkpath;
10444 
10445  /* Skip special stuff */
10446  if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
10447  continue;
10448 
10449  snprintf(fullpath, sizeof(fullpath), "pg_tblspc/%s", de->d_name);
10450 
10451 #if defined(HAVE_READLINK) || defined(WIN32)
10452  rllen = readlink(fullpath, linkpath, sizeof(linkpath));
10453  if (rllen < 0)
10454  {
10455  ereport(WARNING,
10456  (errmsg("could not read symbolic link \"%s\": %m",
10457  fullpath)));
10458  continue;
10459  }
10460  else if (rllen >= sizeof(linkpath))
10461  {
10462  ereport(WARNING,
10463  (errmsg("symbolic link \"%s\" target is too long",
10464  fullpath)));
10465  continue;
10466  }
10467  linkpath[rllen] = '\0';
10468 
10469  /*
10470  * Add the escape character '\\' before newline in a string to
10471  * ensure that we can distinguish between the newline in the
10472  * tablespace path and end of line while reading tablespace_map
10473  * file during archive recovery.
10474  */
10475  initStringInfo(&buflinkpath);
10476 
10477  while (*s)
10478  {
10479  if ((*s == '\n' || *s == '\r') && needtblspcmapfile)
10480  appendStringInfoChar(&buflinkpath, '\\');
10481  appendStringInfoChar(&buflinkpath, *s++);
10482  }
10483 
10484 
10485  /*
10486  * Relpath holds the relative path of the tablespace directory
10487  * when it's located within PGDATA, or NULL if it's located
10488  * elsewhere.
10489  */
10490  if (rllen > datadirpathlen &&
10491  strncmp(linkpath, DataDir, datadirpathlen) == 0 &&
10492  IS_DIR_SEP(linkpath[datadirpathlen]))
10493  relpath = linkpath + datadirpathlen + 1;
10494 
10495  ti = palloc(sizeof(tablespaceinfo));
10496  ti->oid = pstrdup(de->d_name);
10497  ti->path = pstrdup(buflinkpath.data);
10498  ti->rpath = relpath ? pstrdup(relpath) : NULL;
10499  ti->size = infotbssize ? sendTablespace(fullpath, true) : -1;
10500 
10501  if (tablespaces)
10502  *tablespaces = lappend(*tablespaces, ti);
10503 
10504  appendStringInfo(tblspcmapfile, "%s %s\n", ti->oid, ti->path);
10505 
10506  pfree(buflinkpath.data);
10507 #else
10508 
10509  /*
10510  * If the platform does not have symbolic links, it should not be
10511  * possible to have tablespaces - clearly somebody else created
10512  * them. Warn about it and ignore.
10513  */
10514  ereport(WARNING,
10515  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10516  errmsg("tablespaces are not supported on this platform")));
10517 #endif
10518  }
10519 
10520  /*
10521  * Construct backup label file
10522  */
10523  if (exclusive)
10524  labelfile = makeStringInfo();
10525 
10526  /* Use the log timezone here, not the session timezone */
10527  stamp_time = (pg_time_t) time(NULL);
10528  pg_strftime(strfbuf, sizeof(strfbuf),
10529  "%Y-%m-%d %H:%M:%S %Z",
10530  pg_localtime(&stamp_time, log_timezone));
10531  appendStringInfo(labelfile, "START WAL LOCATION: %X/%X (file %s)\n",
10532  (uint32) (startpoint >> 32), (uint32) startpoint, xlogfilename);
10533  appendStringInfo(labelfile, "CHECKPOINT LOCATION: %X/%X\n",
10534  (uint32) (checkpointloc >> 32), (uint32) checkpointloc);
10535  appendStringInfo(labelfile, "BACKUP METHOD: %s\n",
10536  exclusive ? "pg_start_backup" : "streamed");
10537  appendStringInfo(labelfile, "BACKUP FROM: %s\n",
10538  backup_started_in_recovery ? "standby" : "master");
10539  appendStringInfo(labelfile, "START TIME: %s\n", strfbuf);
10540  appendStringInfo(labelfile, "LABEL: %s\n", backupidstr);
10541 
10542  /*
10543  * Okay, write the file, or return its contents to caller.
10544  */
10545  if (exclusive)
10546  {
10547  /*
10548  * Check for existing backup label --- implies a backup is already
10549  * running. (XXX given that we checked exclusiveBackupState
10550  * above, maybe it would be OK to just unlink any such label
10551  * file?)
10552  */
10553  if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
10554  {
10555  if (errno != ENOENT)
10556  ereport(ERROR,
10558  errmsg("could not stat file \"%s\": %m",
10559  BACKUP_LABEL_FILE)));
10560  }
10561  else
10562  ereport(ERROR,
10563  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10564  errmsg("a backup is already in progress"),
10565  errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
10566  BACKUP_LABEL_FILE)));
10567 
10568  fp = AllocateFile(BACKUP_LABEL_FILE, "w");
10569 
10570  if (!fp)
10571  ereport(ERROR,
10573  errmsg("could not create file \"%s\": %m",
10574  BACKUP_LABEL_FILE)));
10575  if (fwrite(labelfile->data, labelfile->len, 1, fp) != 1 ||
10576  fflush(fp) != 0 ||
10577  pg_fsync(fileno(fp)) != 0 ||
10578  ferror(fp) ||
10579  FreeFile(fp))
10580  ereport(ERROR,
10582  errmsg("could not write file \"%s\": %m",
10583  BACKUP_LABEL_FILE)));
10584  /* Allocated locally for exclusive backups, so free separately */
10585  pfree(labelfile->data);
10586  pfree(labelfile);
10587 
10588  /* Write backup tablespace_map file. */
10589  if (tblspcmapfile->len > 0)
10590  {
10591  if (stat(TABLESPACE_MAP, &stat_buf) != 0)
10592  {
10593  if (errno != ENOENT)
10594  ereport(ERROR,
10596  errmsg("could not stat file \"%s\": %m",
10597  TABLESPACE_MAP)));
10598  }
10599  else
10600  ereport(ERROR,
10601  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10602  errmsg("a backup is already in progress"),
10603  errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
10604  TABLESPACE_MAP)));
10605 
10606  fp = AllocateFile(TABLESPACE_MAP, "w");
10607 
10608  if (!fp)
10609  ereport(ERROR,
10611  errmsg("could not create file \"%s\": %m",
10612  TABLESPACE_MAP)));
10613  if (fwrite(tblspcmapfile->data, tblspcmapfile->len, 1, fp) != 1 ||
10614  fflush(fp) != 0 ||
10615  pg_fsync(fileno(fp)) != 0 ||
10616  ferror(fp) ||
10617  FreeFile(fp))
10618  ereport(ERROR,
10620  errmsg("could not write file \"%s\": %m",
10621  TABLESPACE_MAP)));
10622  }
10623 
10624  /* Allocated locally for exclusive backups, so free separately */
10625  pfree(tblspcmapfile->data);
10626  pfree(tblspcmapfile);
10627  }
10628  }
10630 
10631  /*
10632  * Mark that start phase has correctly finished for an exclusive backup.
10633  * Session-level locks are updated as well to reflect that state.
10634  */
10635  if (exclusive)
10636  {
10641  }
10642  else
10644 
10645  /*
10646  * We're done. As a convenience, return the starting WAL location.
10647  */
10648  if (starttli_p)
10649  *starttli_p = starttli;
10650  return startpoint;
10651 }
size_t pg_strftime(char *s, size_t max, const char *format, const struct pg_tm *tm)
Definition: strftime.c:122
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9441
int errhint(const char *fmt,...)
Definition: elog.c:987
uint32 TimeLineID
Definition: xlogdefs.h:45
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1651
int wal_segment_size
Definition: xlog.c:113
XLogRecPtr lastFpwDisableRecPtr
Definition: xlog.c:702
static SessionBackupState sessionBackupState
Definition: xlog.c:512
XLogRecPtr lastBackupStart
Definition: xlog.c:564
char * pstrdup(const char *in)
Definition: mcxt.c:1076
#define XLogIsNeeded()
Definition: xlog.h:146
char * rpath
Definition: basebackup.h:28
StringInfo makeStringInfo(void)
Definition: stringinfo.c:28
slock_t info_lck
Definition: xlog.c:704
int errcode(int sqlerrcode)
Definition: elog.c:575
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
CheckPoint checkPointCopy
Definition: pg_control.h:131
XLogCtlInsert Insert
Definition: xlog.c:577
bool RecoveryInProgress(void)
Definition: xlog.c:7929
static bool backup_started_in_recovery
Definition: basebackup.c:74
Definition: dirent.h:9
#define IS_DIR_SEP(ch)
Definition: port.h:84
pg_tz * log_timezone
Definition: pgtz.c:31
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define TABLESPACE_MAP
Definition: xlog.h:325
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
void pfree(void *pointer)
Definition: mcxt.c:949
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
bool forcePageWrites
Definition: xlog.c:551
#define ERROR
Definition: elog.h:43
struct stat stat_buf
Definition: pg_standby.c:103
#define MAXPGPATH
uint64 XLogSegNo
Definition: xlogdefs.h:34
#define readlink(path, buf, size)
Definition: win32_port.h:233
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2123
unsigned int uint32
Definition: c.h:296
int64 sendTablespace(char *path, bool sizeonly)
Definition: basebackup.c:914
#define CHECKPOINT_FORCE
Definition: xlog.h:180
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define WARNING
Definition: elog.h:40
int nonExclusiveBackups
Definition: xlog.c:563
#define stat(a, b)
Definition: win32_port.h:266
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
static void pg_start_backup_callback(int code, Datum arg)
Definition: xlog.c:10655
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:562
uintptr_t Datum
Definition: postgres.h:372
static ControlFileData * ControlFile
Definition: xlog.c:715
#define BoolGetDatum(X)
Definition: postgres.h:408
bool fullPageWrites
Definition: pg_control.h:41
#define CHECKPOINT_WAIT
Definition: xlog.h:184
uint64 XLogRecPtr
Definition: xlogdefs.h:21
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2439
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1622
static XLogCtlData * XLogCtl
Definition: xlog.c:707
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
Definition: localtime.c:1314
int FreeFile(FILE *file)
Definition: fd.c:2315
void * palloc(Size size)
Definition: mcxt.c:848
TimeLineID ThisTimeLineID
Definition: pg_control.h:38
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:179
#define relpath(rnode, forknum)
Definition: relpath.h:71
char * DataDir
Definition: globals.c:60
#define BACKUP_LABEL_FILE
Definition: xlog.h:322
int pg_fsync(int fd)
Definition: fd.c:338
char d_name[MAX_PATH]
Definition: dirent.h:14
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:36
void RequestCheckpoint(int flags)
Definition: checkpointer.c:967
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ do_pg_stop_backup()

XLogRecPtr do_pg_stop_backup ( char *  labelfile,
bool  waitforarchive,
TimeLineID stoptli_p 
)

Definition at line 10721 of file xlog.c.

References AllocateFile(), Assert, BACKUP_LABEL_FILE, backup_started_in_recovery, BackupHistoryFileName, BackupHistoryFilePath, BoolGetDatum, CHECK_FOR_INTERRUPTS, CleanupBackupHistory(), DEBUG1, durable_unlink(), ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, EXCLUSIVE_BACKUP_IN_PROGRESS, EXCLUSIVE_BACKUP_NONE, EXCLUSIVE_BACKUP_STOPPING, XLogCtlInsert::exclusiveBackupState, XLogCtlInsert::forcePageWrites, FreeFile(), XLogCtlData::info_lck, XLogCtlData::Insert, XLogCtlData::lastFpwDisableRecPtr, log_timezone, LW_SHARED, LWLockAcquire(), LWLockRelease(), MAXFNAMELEN, MAXPGPATH, ControlFileData::minRecoveryPoint, ControlFileData::minRecoveryPointTLI, XLogCtlInsert::nonExclusiveBackups, NOTICE, palloc(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_localtime(), pg_stop_backup_callback(), pg_strftime(), pg_usleep(), RecoveryInProgress(), remaining, RequestXLogSwitch(), SESSION_BACKUP_NONE, sessionBackupState, SpinLockAcquire, SpinLockRelease, stat, TABLESPACE_MAP, ThisTimeLineID, wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), WARNING, XLByteToPrevSeg, XLByteToSeg, XLOG_BACKUP_END, XLogArchiveIsBusy(), XLogArchivingActive, XLogArchivingAlways, XLogBeginInsert(), XLogFileName, XLogInsert(), XLogIsNeeded, and XLogRegisterData().

Referenced by perform_base_backup(), pg_stop_backup(), and pg_stop_backup_v2().

10722 {
10723  bool exclusive = (labelfile == NULL);
10724  bool backup_started_in_recovery = false;
10725  XLogRecPtr startpoint;
10726  XLogRecPtr stoppoint;
10727  TimeLineID stoptli;
10728  pg_time_t stamp_time;
10729  char strfbuf[128];
10730  char histfilepath[MAXPGPATH];
10731  char startxlogfilename[MAXFNAMELEN];
10732  char stopxlogfilename[MAXFNAMELEN];
10733  char lastxlogfilename[MAXFNAMELEN];
10734  char histfilename[MAXFNAMELEN];
10735  char backupfrom[20];
10736  XLogSegNo _logSegNo;
10737  FILE *lfp;
10738  FILE *fp;
10739  char ch;
10740  int seconds_before_warning;
10741  int waits = 0;
10742  bool reported_waiting = false;
10743  char *remaining;
10744  char *ptr;
10745  uint32 hi,
10746  lo;
10747 
10748  backup_started_in_recovery = RecoveryInProgress();
10749 
10750  /*
10751  * Currently only non-exclusive backup can be taken during recovery.
10752  */
10753  if (backup_started_in_recovery && exclusive)
10754  ereport(ERROR,
10755  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10756  errmsg("recovery is in progress"),
10757  errhint("WAL control functions cannot be executed during recovery.")));
10758 
10759  /*
10760  * During recovery, we don't need to check WAL level. Because, if WAL
10761  * level is not sufficient, it's impossible to get here during recovery.
10762  */
10763  if (!backup_started_in_recovery && !XLogIsNeeded())
10764  ereport(ERROR,
10765  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10766  errmsg("WAL level not sufficient for making an online backup"),
10767  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
10768 
10769  if (exclusive)
10770  {
10771  /*
10772  * At first, mark that we're now stopping an exclusive backup, to
10773  * ensure that there are no other sessions currently running
10774  * pg_start_backup() or pg_stop_backup().
10775  */
10778  {
10780  ereport(ERROR,
10781  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10782  errmsg("exclusive backup not in progress")));
10783  }
10786 
10787  /*
10788  * Remove backup_label. In case of failure, the state for an exclusive
10789  * backup is switched back to in-progress.
10790  */
10792  {
10793  /*
10794  * Read the existing label file into memory.
10795  */
10796  struct stat statbuf;
10797  int r;
10798 
10799  if (stat(BACKUP_LABEL_FILE, &statbuf))
10800  {
10801  /* should not happen per the upper checks */
10802  if (errno != ENOENT)
10803  ereport(ERROR,
10805  errmsg("could not stat file \"%s\": %m",
10806  BACKUP_LABEL_FILE)));
10807  ereport(ERROR,
10808  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10809  errmsg("a backup is not in progress")));
10810  }
10811 
10812  lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
10813  if (!lfp)
10814  {
10815  ereport(ERROR,
10817  errmsg("could not read file \"%s\": %m",
10818  BACKUP_LABEL_FILE)));
10819  }
10820  labelfile = palloc(statbuf.st_size + 1);
10821  r = fread(labelfile, statbuf.st_size, 1, lfp);
10822  labelfile[statbuf.st_size] = '\0';
10823 
10824  /*
10825  * Close and remove the backup label file
10826  */
10827  if (r != 1 || ferror(lfp) || FreeFile(lfp))
10828  ereport(ERROR,
10830  errmsg("could not read file \"%s\": %m",
10831  BACKUP_LABEL_FILE)));
10833 
10834  /*
10835  * Remove tablespace_map file if present, it is created only if
10836  * there are tablespaces.
10837  */
10839  }
10841  }
10842 
10843  /*
10844  * OK to update backup counters and forcePageWrites
10845  */
10847  if (exclusive)
10848  {
10850  }
10851  else
10852  {
10853  /*
10854  * The user-visible pg_start/stop_backup() functions that operate on
10855  * exclusive backups can be called at any time, but for non-exclusive
10856  * backups, it is expected that each do_pg_start_backup() call is
10857  * matched by exactly one do_pg_stop_backup() call.
10858  */
10861  }
10862 
10865  {
10866  XLogCtl->Insert.forcePageWrites = false;
10867  }
10869 
10870  /* Clean up session-level lock */
10872 
10873  /*
10874  * Read and parse the START WAL LOCATION line (this code is pretty crude,
10875  * but we are not expecting any variability in the file format).
10876  */
10877  if (sscanf(labelfile, "START WAL LOCATION: %X/%X (file %24s)%c",
10878  &hi, &lo, startxlogfilename,
10879  &ch) != 4 || ch != '\n')
10880  ereport(ERROR,
10881  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10882  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10883  startpoint = ((uint64) hi) << 32 | lo;
10884  remaining = strchr(labelfile, '\n') + 1; /* %n is not portable enough */
10885 
10886  /*
10887  * Parse the BACKUP FROM line. If we are taking an online backup from the
10888  * standby, we confirm that the standby has not been promoted during the
10889  * backup.
10890  */
10891  ptr = strstr(remaining, "BACKUP FROM:");
10892  if (!ptr || sscanf(ptr, "BACKUP FROM: %19s\n", backupfrom) != 1)
10893  ereport(ERROR,
10894  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10895  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10896  if (strcmp(backupfrom, "standby") == 0 && !backup_started_in_recovery)
10897  ereport(ERROR,
10898  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10899  errmsg("the standby was promoted during online backup"),
10900  errhint("This means that the backup being taken is corrupt "
10901  "and should not be used. "
10902  "Try taking another online backup.")));
10903 
10904  /*
10905  * During recovery, we don't write an end-of-backup record. We assume that
10906  * pg_control was backed up last and its minimum recovery point can be
10907  * available as the backup end location. Since we don't have an
10908  * end-of-backup record, we use the pg_control value to check whether
10909  * we've reached the end of backup when starting recovery from this
10910  * backup. We have no way of checking if pg_control wasn't backed up last
10911  * however.
10912  *
10913  * We don't force a switch to new WAL file but it is still possible to
10914  * wait for all the required files to be archived if waitforarchive is
10915  * true. This is okay if we use the backup to start a standby and fetch
10916  * the missing WAL using streaming replication. But in the case of an
10917  * archive recovery, a user should set waitforarchive to true and wait for
10918  * them to be archived to ensure that all the required files are
10919  * available.
10920  *
10921  * We return the current minimum recovery point as the backup end
10922  * location. Note that it can be greater than the exact backup end
10923  * location if the minimum recovery point is updated after the backup of
10924  * pg_control. This is harmless for current uses.
10925  *
10926  * XXX currently a backup history file is for informational and debug
10927  * purposes only. It's not essential for an online backup. Furthermore,
10928  * even if it's created, it will not be archived during recovery because
10929  * an archiver is not invoked. So it doesn't seem worthwhile to write a
10930  * backup history file during recovery.
10931  */
10932  if (backup_started_in_recovery)
10933  {
10934  XLogRecPtr recptr;
10935 
10936  /*
10937  * Check to see if all WAL replayed during online backup contain
10938  * full-page writes.
10939  */
10941  recptr = XLogCtl->lastFpwDisableRecPtr;
10943 
10944  if (startpoint <= recptr)
10945  ereport(ERROR,
10946  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10947  errmsg("WAL generated with full_page_writes=off was replayed "
10948  "during online backup"),
10949  errhint("This means that the backup being taken on the standby "
10950  "is corrupt and should not be used. "
10951  "Enable full_page_writes and run CHECKPOINT on the master, "
10952  "and then try an online backup again.")));
10953 
10954 
10955  LWLockAcquire(ControlFileLock, LW_SHARED);
10956  stoppoint = ControlFile->minRecoveryPoint;
10957  stoptli = ControlFile->minRecoveryPointTLI;
10958  LWLockRelease(ControlFileLock);
10959  }
10960  else
10961  {
10962  /*
10963  * Write the backup-end xlog record
10964  */
10965  XLogBeginInsert();
10966  XLogRegisterData((char *) (&startpoint), sizeof(startpoint));
10967  stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END);
10968  stoptli = ThisTimeLineID;
10969 
10970  /*
10971  * Force a switch to a new xlog segment file, so that the backup is
10972  * valid as soon as archiver moves out the current segment file.
10973  */
10974  RequestXLogSwitch(false);
10975 
10976  XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
10977  XLogFileName(stopxlogfilename, stoptli, _logSegNo, wal_segment_size);
10978 
10979  /* Use the log timezone here, not the session timezone */
10980  stamp_time = (pg_time_t) time(NULL);
10981  pg_strftime(strfbuf, sizeof(strfbuf),
10982  "%Y-%m-%d %H:%M:%S %Z",
10983  pg_localtime(&stamp_time, log_timezone));
10984 
10985  /*
10986  * Write the backup history file
10987  */
10988  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
10989  BackupHistoryFilePath(histfilepath, stoptli, _logSegNo,
10990  startpoint, wal_segment_size);
10991  fp = AllocateFile(histfilepath, "w");
10992  if (!fp)
10993  ereport(ERROR,
10995  errmsg("could not create file \"%s\": %m",
10996  histfilepath)));
10997  fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
10998  (uint32) (startpoint >> 32), (uint32) startpoint, startxlogfilename);
10999  fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
11000  (uint32) (stoppoint >> 32), (uint32) stoppoint, stopxlogfilename);
11001  /* transfer remaining lines from label to history file */
11002  fprintf(fp, "%s", remaining);
11003  fprintf(fp, "STOP TIME: %s\n", strfbuf);
11004  if (fflush(fp) || ferror(fp) || FreeFile(fp))
11005  ereport(ERROR,
11007  errmsg("could not write file \"%s\": %m",
11008  histfilepath)));
11009 
11010  /*
11011  * Clean out any no-longer-needed history files. As a side effect,
11012  * this will post a .ready file for the newly created history file,
11013  * notifying the archiver that history file may be archived
11014  * immediately.
11015  */
11017  }
11018 
11019  /*
11020  * If archiving is enabled, wait for all the required WAL files to be
11021  * archived before returning. If archiving isn't enabled, the required WAL
11022  * needs to be transported via streaming replication (hopefully with
11023  * wal_keep_segments set high enough), or some more exotic mechanism like
11024  * polling and copying files from pg_wal with script. We have no knowledge
11025  * of those mechanisms, so it's up to the user to ensure that he gets all
11026  * the required WAL.
11027  *
11028  * We wait until both the last WAL file filled during backup and the
11029  * history file have been archived, and assume that the alphabetic sorting
11030  * property of the WAL files ensures any earlier WAL files are safely
11031  * archived as well.
11032  *
11033  * We wait forever, since archive_command is supposed to work and we
11034  * assume the admin wanted his backup to work completely. If you don't
11035  * wish to wait, then either waitforarchive should be passed in as false,
11036  * or you can set statement_timeout. Also, some notices are issued to
11037  * clue in anyone who might be doing this interactively.
11038  */
11039 
11040  if (waitforarchive &&
11041  ((!backup_started_in_recovery && XLogArchivingActive()) ||
11042  (backup_started_in_recovery && XLogArchivingAlways())))
11043  {
11044  XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
11045  XLogFileName(lastxlogfilename, stoptli, _logSegNo, wal_segment_size);
11046 
11047  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
11048  BackupHistoryFileName(histfilename, stoptli, _logSegNo,
11049  startpoint, wal_segment_size);
11050 
11051  seconds_before_warning = 60;
11052  waits = 0;
11053 
11054  while (XLogArchiveIsBusy(lastxlogfilename) ||
11055  XLogArchiveIsBusy(histfilename))
11056  {
11058 
11059  if (!reported_waiting && waits > 5)
11060  {
11061  ereport(NOTICE,
11062  (errmsg("pg_stop_backup cleanup done, waiting for required WAL segments to be archived")));
11063  reported_waiting = true;
11064  }
11065 
11066  pg_usleep(1000000L);
11067 
11068  if (++waits >= seconds_before_warning)
11069  {
11070  seconds_before_warning *= 2; /* This wraps in >10 years... */
11071  ereport(WARNING,
11072  (errmsg("pg_stop_backup still waiting for all required WAL segments to be archived (%d seconds elapsed)",
11073  waits),
11074  errhint("Check that your archive_command is executing properly. "
11075  "pg_stop_backup can be canceled safely, "
11076  "but the database backup will not be usable without all the WAL segments.")));
11077  }
11078  }
11079 
11080  ereport(NOTICE,
11081  (errmsg("pg_stop_backup complete, all required WAL segments have been archived")));
11082  }
11083  else if (waitforarchive)
11084  ereport(NOTICE,
11085  (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
11086 
11087  /*
11088  * We're done. As a convenience, return the ending WAL location.
11089  */
11090  if (stoptli_p)
11091  *stoptli_p = stoptli;
11092  return stoppoint;
11093 }
int remaining
Definition: informix.c:692
size_t pg_strftime(char *s, size_t max, const char *format, const struct pg_tm *tm)
Definition: strftime.c:122
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9441
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:987
uint32 TimeLineID
Definition: xlogdefs.h:45
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1651
int wal_segment_size
Definition: xlog.c:113
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
XLogRecPtr lastFpwDisableRecPtr
Definition: xlog.c:702
static SessionBackupState sessionBackupState
Definition: xlog.c:512
#define XLByteToPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogIsNeeded()
Definition: xlog.h:146
slock_t info_lck
Definition: xlog.c:704
int errcode(int sqlerrcode)
Definition: elog.c:575
XLogCtlInsert Insert
Definition: xlog.c:577
#define BackupHistoryFileName(fname, tli, logSegNo, startpoint, wal_segsz_bytes)
bool RecoveryInProgress(void)
Definition: xlog.c:7929
static bool backup_started_in_recovery
Definition: basebackup.c:74
pg_tz * log_timezone
Definition: pgtz.c:31
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define TABLESPACE_MAP
Definition: xlog.h:325
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
#define XLogArchivingAlways()
Definition: xlog.h:138
bool forcePageWrites
Definition: xlog.c:551
#define ERROR
Definition: elog.h:43
static void CleanupBackupHistory(void)
Definition: xlog.c:4104
#define MAXPGPATH
uint64 XLogSegNo
Definition: xlogdefs.h:34
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2123
unsigned int uint32
Definition: c.h:296
#define ereport(elevel, rest)
Definition: elog.h:122
#define XLOG_BACKUP_END
Definition: pg_control.h:72
#define WARNING
Definition: elog.h:40
int nonExclusiveBackups
Definition: xlog.c:563
#define stat(a, b)
Definition: win32_port.h:266
#define MAXFNAMELEN
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
#define SpinLockRelease(lock)
Definition: spin.h:64
#define BackupHistoryFilePath(path, tli, logSegNo, startpoint, wal_segsz_bytes)
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:562
uintptr_t Datum
Definition: postgres.h:372
static ControlFileData * ControlFile
Definition: xlog.c:715
#define BoolGetDatum(X)
Definition: postgres.h:408
TimeLineID ThisTimeLineID
Definition: xlog.c:181
#define NOTICE
Definition: elog.h:37
bool XLogArchiveIsBusy(const char *xlog)
Definition: xlogarchive.c:659
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:670
#define XLogArchivingActive()
Definition: xlog.h:135
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1622
static XLogCtlData * XLogCtl
Definition: xlog.c:707
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
static void pg_stop_backup_callback(int code, Datum arg)
Definition: xlog.c:10684
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
Definition: localtime.c:1314
int durable_unlink(const char *fname, int elevel)
Definition: fd.c:681
int FreeFile(FILE *file)
Definition: fd.c:2315
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define BACKUP_LABEL_FILE
Definition: xlog.h:322
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ emode_for_corrupt_record()

static int emode_for_corrupt_record ( int  emode,
XLogRecPtr  RecPtr 
)
static

Definition at line 12031 of file xlog.c.

References DEBUG1, LOG, readSource, and XLOG_FROM_PG_WAL.

Referenced by ReadRecord(), and XLogPageRead().

12032 {
12033  static XLogRecPtr lastComplaint = 0;
12034 
12035  if (readSource == XLOG_FROM_PG_WAL && emode == LOG)
12036  {
12037  if (RecPtr == lastComplaint)
12038  emode = DEBUG1;
12039  else
12040  lastComplaint = RecPtr;
12041  }
12042  return emode;
12043 }
#define DEBUG1
Definition: elog.h:25
static XLogSource readSource
Definition: xlog.c:790
#define LOG
Definition: elog.h:26
uint64 XLogRecPtr
Definition: xlogdefs.h:21

◆ exitArchiveRecovery()

static void exitArchiveRecovery ( TimeLineID  endTLI,
XLogRecPtr  endOfLog 
)
static

Definition at line 5540 of file xlog.c.

References Assert, close, durable_rename(), ereport, errcode_for_file_access(), errmsg(), ERROR, FATAL, fd(), InArchiveRecovery, InvalidXLogRecPtr, LOG, MAXFNAMELEN, MAXPGPATH, readFile, RECOVERY_COMMAND_DONE, RECOVERY_COMMAND_FILE, snprintf(), ThisTimeLineID, UpdateMinRecoveryPoint(), wal_segment_size, XLByteToPrevSeg, XLByteToSeg, XLogArchiveCleanup(), XLOGDIR, XLogFileCopy(), XLogFileInit(), XLogFileName, XLogFileNameP(), and XLogSegmentOffset.

Referenced by StartupXLOG().

5541 {
5542  char recoveryPath[MAXPGPATH];
5543  char xlogfname[MAXFNAMELEN];
5544  XLogSegNo endLogSegNo;
5545  XLogSegNo startLogSegNo;
5546 
5547  /* we always switch to a new timeline after archive recovery */
5548  Assert(endTLI != ThisTimeLineID);
5549 
5550  /*
5551  * We are no longer in archive recovery state.
5552  */
5553  InArchiveRecovery = false;
5554 
5555  /*
5556  * Update min recovery point one last time.
5557  */
5559 
5560  /*
5561  * If the ending log segment is still open, close it (to avoid problems on
5562  * Windows with trying to rename or delete an open file).
5563  */
5564  if (readFile >= 0)
5565  {
5566  close(readFile);
5567  readFile = -1;
5568  }
5569 
5570  /*
5571  * Calculate the last segment on the old timeline, and the first segment
5572  * on the new timeline. If the switch happens in the middle of a segment,
5573  * they are the same, but if the switch happens exactly at a segment
5574  * boundary, startLogSegNo will be endLogSegNo + 1.
5575  */
5576  XLByteToPrevSeg(endOfLog, endLogSegNo, wal_segment_size);
5577  XLByteToSeg(endOfLog, startLogSegNo, wal_segment_size);
5578 
5579  /*
5580  * Initialize the starting WAL segment for the new timeline. If the switch
5581  * happens in the middle of a segment, copy data from the last WAL segment
5582  * of the old timeline up to the switch point, to the starting WAL segment
5583  * on the new timeline.
5584  */
5585  if (endLogSegNo == startLogSegNo)
5586  {
5587  /*
5588  * Make a copy of the file on the new timeline.
5589  *
5590  * Writing WAL isn't allowed yet, so there are no locking
5591  * considerations. But we should be just as tense as XLogFileInit to
5592  * avoid emplacing a bogus file.
5593  */
5594  XLogFileCopy(endLogSegNo, endTLI, endLogSegNo,
5595  XLogSegmentOffset(endOfLog, wal_segment_size));
5596  }
5597  else
5598  {
5599  /*
5600  * The switch happened at a segment boundary, so just create the next
5601  * segment on the new timeline.
5602  */
5603  bool use_existent = true;
5604  int fd;
5605 
5606  fd = XLogFileInit(startLogSegNo, &use_existent, true);
5607 
5608  if (close(fd))
5609  ereport(ERROR,
5611  errmsg("could not close log file %s: %m",
5612  XLogFileNameP(ThisTimeLineID, startLogSegNo))));
5613  }
5614 
5615  /*
5616  * Let's just make real sure there are not .ready or .done flags posted
5617  * for the new segment.
5618  */
5619  XLogFileName(xlogfname, ThisTimeLineID, startLogSegNo, wal_segment_size);
5620  XLogArchiveCleanup(xlogfname);
5621 
5622  /*
5623  * Since there might be a partial WAL segment named RECOVERYXLOG, get rid
5624  * of it.
5625  */
5626  snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
5627  unlink(recoveryPath); /* ignore any error */
5628 
5629  /* Get rid of any remaining recovered timeline-history file, too */
5630  snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
5631  unlink(recoveryPath); /* ignore any error */
5632 
5633  /*
5634  * Rename the config file out of the way, so that we don't accidentally
5635  * re-enter archive recovery mode in a subsequent crash.
5636  */
5637  unlink(RECOVERY_COMMAND_DONE);
5639 
5640  ereport(LOG,
5641  (errmsg("archive recovery complete")));
5642 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
int wal_segment_size
Definition: xlog.c:113
#define XLByteToPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)