PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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

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

Definition at line 741 of file xlog.c.

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

#define FALLBACK_PROMOTE_SIGNAL_FILE   "fallback_promote"

Definition at line 85 of file xlog.c.

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

#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().

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

Definition at line 725 of file xlog.c.

Referenced by XLogWrite().

#define PROMOTE_SIGNAL_FILE   "promote"

Definition at line 84 of file xlog.c.

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

#define RECOVERY_COMMAND_DONE   "recovery.done"

Definition at line 83 of file xlog.c.

Referenced by exitArchiveRecovery().

#define RECOVERY_COMMAND_FILE   "recovery.conf"

Definition at line 82 of file xlog.c.

Referenced by exitArchiveRecovery(), and readRecoveryCommandFile().

#define RecoveryRequiresIntParameter (   param_name,
  currValue,
  minValue 
)
Value:
do { \
if ((currValue) < (minValue)) \
(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
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797

Definition at line 6216 of file xlog.c.

Referenced by CheckRequiredParameterValues().

#define UsableBytesInPage   (XLOG_BLCKSZ - SizeOfXLogShortPHD)
#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

Enumeration Type Documentation

Enumerator
EXCLUSIVE_BACKUP_NONE 
EXCLUSIVE_BACKUP_STARTING 
EXCLUSIVE_BACKUP_IN_PROGRESS 
EXCLUSIVE_BACKUP_STOPPING 

Definition at line 500 of file xlog.c.

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

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, XLogPageHeaderData::xlp_info, XLP_LONG_HEADER, XLogPageHeaderData::xlp_magic, XLogPageHeaderData::xlp_pageaddr, XLogLongPageHeaderData::xlp_seg_size, XLogLongPageHeaderData::xlp_sysid, XLogPageHeaderData::xlp_tli, 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:846
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:258
static void Insert(File file)
Definition: fd.c:1044
TimeLineID xlp_tli
Definition: xlog_internal.h:40
static void XLogWrite(XLogwrtRqst WriteRqst, bool flexible)
Definition: xlog.c:2347
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:664
#define XLP_LONG_HEADER
Definition: xlog_internal.h:79
size_t Size
Definition: c.h:350
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
void assign_checkpoint_completion_target ( double  newval,
void *  extra 
)

Definition at line 2247 of file xlog.c.

References CalculateCheckpointSegments(), CheckPointCompletionTarget, and newval.

2248 {
2251 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2216
#define newval
double CheckPointCompletionTarget
Definition: checkpointer.c:147
void assign_max_wal_size ( int  newval,
void *  extra 
)

Definition at line 2240 of file xlog.c.

References CalculateCheckpointSegments(), max_wal_size_mb, and newval.

2241 {
2244 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2216
int max_wal_size_mb
Definition: xlog.c:89
#define newval
void assign_xlog_sync_method ( int  new_sync_method,
void *  extra 
)

Definition at line 10147 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().

10148 {
10149  if (sync_method != new_sync_method)
10150  {
10151  /*
10152  * To ensure that no blocks escape unsynced, force an fsync on the
10153  * currently open log segment (if any). Also, if the open flag is
10154  * changing, close the log file so it will be reopened (with new flag
10155  * bit) at next use.
10156  */
10157  if (openLogFile >= 0)
10158  {
10160  if (pg_fsync(openLogFile) != 0)
10161  ereport(PANIC,
10163  errmsg("could not fsync log segment %s: %m",
10166  if (get_sync_bit(sync_method) != get_sync_bit(new_sync_method))
10167  XLogFileClose();
10168  }
10169  }
10170 }
static int get_sync_bit(int method)
Definition: xlog.c:10091
#define PANIC
Definition: elog.h:53
static XLogSegNo openLogSegNo
Definition: xlog.c:775
static void XLogFileClose(void)
Definition: xlog.c:3722
char * XLogFileNameP(TimeLineID tli, XLogSegNo segno)
Definition: xlog.c:10223
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:333
bool BackupInProgress ( void  )

Definition at line 11441 of file xlog.c.

References BACKUP_LABEL_FILE.

Referenced by pg_is_in_backup(), and PostmasterStateMachine().

11442 {
11443  struct stat stat_buf;
11444 
11445  return (stat(BACKUP_LABEL_FILE, &stat_buf) == 0);
11446 }
struct stat stat_buf
Definition: pg_standby.c:103
#define BACKUP_LABEL_FILE
Definition: xlog.h:322
void BootStrapXLOG ( void  )

Definition at line 5021 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_crc, 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().

5022 {
5023  CheckPoint checkPoint;
5024  char *buffer;
5025  XLogPageHeader page;
5026  XLogLongPageHeader longpage;
5027  XLogRecord *record;
5028  char *recptr;
5029  bool use_existent;
5030  uint64 sysidentifier;
5031  char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
5032  struct timeval tv;
5033  pg_crc32c crc;
5034 
5035  /*
5036  * Select a hopefully-unique system identifier code for this installation.
5037  * We use the result of gettimeofday(), including the fractional seconds
5038  * field, as being about as unique as we can easily get. (Think not to
5039  * use random(), since it hasn't been seeded and there's no portable way
5040  * to seed it other than the system clock value...) The upper half of the
5041  * uint64 value is just the tv_sec part, while the lower half contains the
5042  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5043  * PID for a little extra uniqueness. A person knowing this encoding can
5044  * determine the initialization time of the installation, which could
5045  * perhaps be useful sometimes.
5046  */
5047  gettimeofday(&tv, NULL);
5048  sysidentifier = ((uint64) tv.tv_sec) << 32;
5049  sysidentifier |= ((uint64) tv.tv_usec) << 12;
5050  sysidentifier |= getpid() & 0xFFF;
5051 
5052  /*
5053  * Generate a random nonce. This is used for authentication requests that
5054  * will fail because the user does not exist. The nonce is used to create
5055  * a genuine-looking password challenge for the non-existent user, in lieu
5056  * of an actual stored password.
5057  */
5058  if (!pg_backend_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
5059  ereport(PANIC,
5060  (errcode(ERRCODE_INTERNAL_ERROR),
5061  errmsg("could not generate secret authorization token")));
5062 
5063  /* First timeline ID is always 1 */
5064  ThisTimeLineID = 1;
5065 
5066  /* page buffer must be aligned suitably for O_DIRECT */
5067  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5068  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5069  memset(page, 0, XLOG_BLCKSZ);
5070 
5071  /*
5072  * Set up information for the initial checkpoint record
5073  *
5074  * The initial checkpoint record is written to the beginning of the WAL
5075  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5076  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5077  */
5078  checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5079  checkPoint.ThisTimeLineID = ThisTimeLineID;
5080  checkPoint.PrevTimeLineID = ThisTimeLineID;
5081  checkPoint.fullPageWrites = fullPageWrites;
5082  checkPoint.nextXidEpoch = 0;
5083  checkPoint.nextXid = FirstNormalTransactionId;
5084  checkPoint.nextOid = FirstBootstrapObjectId;
5085  checkPoint.nextMulti = FirstMultiXactId;
5086  checkPoint.nextMultiOffset = 0;
5087  checkPoint.oldestXid = FirstNormalTransactionId;
5088  checkPoint.oldestXidDB = TemplateDbOid;
5089  checkPoint.oldestMulti = FirstMultiXactId;
5090  checkPoint.oldestMultiDB = TemplateDbOid;
5093  checkPoint.time = (pg_time_t) time(NULL);
5095 
5096  ShmemVariableCache->nextXid = checkPoint.nextXid;
5097  ShmemVariableCache->nextOid = checkPoint.nextOid;
5099  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5100  AdvanceOldestClogXid(checkPoint.oldestXid);
5101  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5102  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5104 
5105  /* Set up the XLOG page header */
5106  page->xlp_magic = XLOG_PAGE_MAGIC;
5107  page->xlp_info = XLP_LONG_HEADER;
5108  page->xlp_tli = ThisTimeLineID;
5110  longpage = (XLogLongPageHeader) page;
5111  longpage->xlp_sysid = sysidentifier;
5112  longpage->xlp_seg_size = wal_segment_size;
5113  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5114 
5115  /* Insert the initial checkpoint record */
5116  recptr = ((char *) page + SizeOfXLogLongPHD);
5117  record = (XLogRecord *) recptr;
5118  record->xl_prev = 0;
5119  record->xl_xid = InvalidTransactionId;
5120  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5122  record->xl_rmid = RM_XLOG_ID;
5123  recptr += SizeOfXLogRecord;
5124  /* fill the XLogRecordDataHeaderShort struct */
5125  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5126  *(recptr++) = sizeof(checkPoint);
5127  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5128  recptr += sizeof(checkPoint);
5129  Assert(recptr - (char *) record == record->xl_tot_len);
5130 
5131  INIT_CRC32C(crc);
5132  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5133  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5134  FIN_CRC32C(crc);
5135  record->xl_crc = crc;
5136 
5137  /* Create first XLOG segment file */
5138  use_existent = false;
5139  openLogFile = XLogFileInit(1, &use_existent, false);
5140 
5141  /* Write the first page with the initial record */
5142  errno = 0;
5144  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5145  {
5146  /* if write didn't set errno, assume problem is no disk space */
5147  if (errno == 0)
5148  errno = ENOSPC;
5149  ereport(PANIC,
5151  errmsg("could not write bootstrap write-ahead log file: %m")));
5152  }
5154 
5156  if (pg_fsync(openLogFile) != 0)
5157  ereport(PANIC,
5159  errmsg("could not fsync bootstrap write-ahead log file: %m")));
5161 
5162  if (close(openLogFile))
5163  ereport(PANIC,
5165  errmsg("could not close bootstrap write-ahead log file: %m")));
5166 
5167  openLogFile = -1;
5168 
5169  /* Now create pg_control */
5170 
5171  memset(ControlFile, 0, sizeof(ControlFileData));
5172  /* Initialize pg_control status fields */
5173  ControlFile->system_identifier = sysidentifier;
5174  memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
5176  ControlFile->time = checkPoint.time;
5177  ControlFile->checkPoint = checkPoint.redo;
5178  ControlFile->checkPointCopy = checkPoint;
5179  ControlFile->unloggedLSN = 1;
5180 
5181  /* Set important parameter values for use when replaying WAL */
5190 
5191  /* some additional ControlFile fields are set in WriteControlFile() */
5192 
5193  WriteControlFile();
5194 
5195  /* Bootstrap the commit log, too */
5196  BootStrapCLOG();
5200 
5201  pfree(buffer);
5202 
5203  /*
5204  * Force control file to be read - in contrast to normal processing we'd
5205  * otherwise never run the checks and GUC related initializations therein.
5206  */
5207  ReadControlFile();
5208 }
static void WriteControlFile(void)
Definition: xlog.c:4397
#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:182
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
int max_prepared_xacts
Definition: pg_control.h:181
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:180
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:3170
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:132
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:4487
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:222
bool pg_backend_random(char *dst, int len)
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
XLogRecPtr unloggedLSN
Definition: pg_control.h:134
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:229
int MaxConnections
Definition: globals.c:124
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:569
bool fullPageWrites
Definition: pg_control.h:41
bool wal_log_hints
Definition: xlog.c:98
void BootStrapCLOG(void)
Definition: clog.c:706
bool track_commit_timestamp
Definition: pg_control.h:183
#define Assert(condition)
Definition: c.h:664
#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
pg_crc32c xl_crc
Definition: xlogrecord.h:49
#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:125
int pg_fsync(int fd)
Definition: fd.c:333
#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:549
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:72
void MultiXactSetNextMXact(MultiXactId nextMulti, MultiXactOffset nextMultiOffset)
Definition: multixact.c:2160
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 two checkpoint cycles, back to the "prev" checkpoint.
2225  * b) during checkpoint, we consume checkpoint_completion_target *
2226  * number of segments consumed between checkpoints.
2227  *-------
2228  */
2229  target = (double) ConvertToXSegs(max_wal_size_mb, wal_segment_size) /
2231 
2232  /* round down */
2233  CheckPointSegments = (int) target;
2234 
2235  if (CheckPointSegments < 1)
2236  CheckPointSegments = 1;
2237 }
#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
void CancelBackup ( void  )

Definition at line 11461 of file xlog.c.

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

Referenced by PostmasterStateMachine().

11462 {
11463  struct stat stat_buf;
11464 
11465  /* if the backup_label file is not there, return */
11466  if (stat(BACKUP_LABEL_FILE, &stat_buf) < 0)
11467  return;
11468 
11469  /* remove leftover file from previously canceled backup if it exists */
11471 
11473  {
11474  ereport(WARNING,
11476  errmsg("online backup mode was not canceled"),
11477  errdetail("File \"%s\" could not be renamed to \"%s\": %m.",
11479  return;
11480  }
11481 
11482  /* if the tablespace_map file is not there, return */
11483  if (stat(TABLESPACE_MAP, &stat_buf) < 0)
11484  {
11485  ereport(LOG,
11486  (errmsg("online backup mode canceled"),
11487  errdetail("File \"%s\" was renamed to \"%s\".",
11489  return;
11490  }
11491 
11492  /* remove leftover file from previously canceled backup if it exists */
11494 
11496  {
11497  ereport(LOG,
11498  (errmsg("online backup mode canceled"),
11499  errdetail("Files \"%s\" and \"%s\" were renamed to "
11500  "\"%s\" and \"%s\", respectively.",
11503  }
11504  else
11505  {
11506  ereport(WARNING,
11508  errmsg("online backup mode canceled"),
11509  errdetail("File \"%s\" was renamed to \"%s\", but "
11510  "file \"%s\" could not be renamed to \"%s\": %m.",
11513  }
11514 }
#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
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:593
#define WARNING
Definition: elog.h:40
#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
bool check_wal_buffers ( int *  newval,
void **  extra,
GucSource  source 
)

Definition at line 4812 of file xlog.c.

References XLOGbuffers, and XLOGChooseNumBuffers().

4813 {
4814  /*
4815  * -1 indicates a request for auto-tune.
4816  */
4817  if (*newval == -1)
4818  {
4819  /*
4820  * If we haven't yet changed the boot_val default of -1, just let it
4821  * be. We'll fix it when XLOGShmemSize is called.
4822  */
4823  if (XLOGbuffers == -1)
4824  return true;
4825 
4826  /* Otherwise, substitute the auto-tune value */
4828  }
4829 
4830  /*
4831  * We clamp manually-set values to at least 4 blocks. Prior to PostgreSQL
4832  * 9.1, a minimum of 4 was enforced by guc.c, but since that is no longer
4833  * the case, we just silently treat such values as a request for the
4834  * minimum. (We could throw an error instead, but that doesn't seem very
4835  * helpful.)
4836  */
4837  if (*newval < 4)
4838  *newval = 4;
4839 
4840  return true;
4841 }
static int XLOGChooseNumBuffers(void)
Definition: xlog.c:4796
#define newval
int XLOGbuffers
Definition: xlog.c:92
static bool CheckForStandbyTrigger ( void  )
static

Definition at line 12107 of file xlog.c.

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

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

12108 {
12109  struct stat stat_buf;
12110  static bool triggered = false;
12111 
12112  if (triggered)
12113  return true;
12114 
12115  if (IsPromoteTriggered())
12116  {
12117  /*
12118  * In 9.1 and 9.2 the postmaster unlinked the promote file inside the
12119  * signal handler. It now leaves the file in place and lets the
12120  * Startup process do the unlink. This allows Startup to know whether
12121  * it should create a full checkpoint before starting up (fallback
12122  * mode). Fast promotion takes precedence.
12123  */
12124  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
12125  {
12128  fast_promote = true;
12129  }
12130  else if (stat(FALLBACK_PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
12131  {
12133  fast_promote = false;
12134  }
12135 
12136  ereport(LOG, (errmsg("received promote request")));
12137 
12139  triggered = true;
12140  return true;
12141  }
12142 
12143  if (TriggerFile == NULL)
12144  return false;
12145 
12146  if (stat(TriggerFile, &stat_buf) == 0)
12147  {
12148  ereport(LOG,
12149  (errmsg("trigger file found: %s", TriggerFile)));
12151  triggered = true;
12152  fast_promote = true;
12153  return true;
12154  }
12155  else if (errno != ENOENT)
12156  ereport(ERROR,
12158  errmsg("could not stat trigger file \"%s\": %m",
12159  TriggerFile)));
12160 
12161  return false;
12162 }
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
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
static bool fast_promote
Definition: xlog.c:282
static void CheckPointGuts ( XLogRecPtr  checkPointRedo,
int  flags 
)
static

Definition at line 9097 of file xlog.c.

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

Referenced by CreateCheckPoint(), and CreateRestartPoint().

9098 {
9099  CheckPointCLOG();
9108  CheckPointBuffers(flags); /* performs all required fsyncs */
9110  /* We deliberately delay 2PC checkpointing as long as possible */
9111  CheckPointTwoPhase(checkPointRedo);
9112 }
void CheckPointBuffers(int flags)
Definition: bufmgr.c:2574
void CheckPointLogicalRewriteHeap(void)
Definition: rewriteheap.c:1200
void CheckPointReplicationOrigin(void)
Definition: origin.c:524
void CheckPointSnapBuild(void)
Definition: snapbuild.c:1862
void CheckPointCLOG(void)
Definition: clog.c:836
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:1652
void CheckPointReplicationSlots(void)
Definition: slot.c:1055
bool CheckPromoteSignal ( void  )

Definition at line 12179 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, and PROMOTE_SIGNAL_FILE.

Referenced by sigusr1_handler().

12180 {
12181  struct stat stat_buf;
12182 
12183  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0 ||
12185  return true;
12186 
12187  return false;
12188 }
#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
static void CheckRecoveryConsistency ( void  )
static

Definition at line 7863 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().

7864 {
7865  XLogRecPtr lastReplayedEndRecPtr;
7866 
7867  /*
7868  * During crash recovery, we don't reach a consistent state until we've
7869  * replayed all the WAL.
7870  */
7872  return;
7873 
7874  /*
7875  * assume that we are called in the startup process, and hence don't need
7876  * a lock to read lastReplayedEndRecPtr
7877  */
7878  lastReplayedEndRecPtr = XLogCtl->lastReplayedEndRecPtr;
7879 
7880  /*
7881  * Have we reached the point where our base backup was completed?
7882  */
7884  ControlFile->backupEndPoint <= lastReplayedEndRecPtr)
7885  {
7886  /*
7887  * We have reached the end of base backup, as indicated by pg_control.
7888  * The data on disk is now consistent. Reset backupStartPoint and
7889  * backupEndPoint, and update minRecoveryPoint to make sure we don't
7890  * allow starting up at an earlier point even if recovery is stopped
7891  * and restarted soon after this.
7892  */
7893  elog(DEBUG1, "end of backup reached");
7894 
7895  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
7896 
7897  if (ControlFile->minRecoveryPoint < lastReplayedEndRecPtr)
7898  ControlFile->minRecoveryPoint = lastReplayedEndRecPtr;
7899 
7902  ControlFile->backupEndRequired = false;
7904 
7905  LWLockRelease(ControlFileLock);
7906  }
7907 
7908  /*
7909  * Have we passed our safe starting point? Note that minRecoveryPoint is
7910  * known to be incorrectly set if ControlFile->backupEndRequired, until
7911  * the XLOG_BACKUP_RECORD arrives to advise us of the correct
7912  * minRecoveryPoint. All we know prior to that is that we're not
7913  * consistent yet.
7914  */
7916  minRecoveryPoint <= lastReplayedEndRecPtr &&
7918  {
7919  /*
7920  * Check to see if the XLOG sequence contained any unresolved
7921  * references to uninitialized pages.
7922  */
7924 
7925  reachedConsistency = true;
7926  ereport(LOG,
7927  (errmsg("consistent recovery state reached at %X/%X",
7928  (uint32) (lastReplayedEndRecPtr >> 32),
7929  (uint32) lastReplayedEndRecPtr)));
7930  }
7931 
7932  /*
7933  * Have we got a valid starting snapshot that will allow queries to be
7934  * run? If so, we can tell postmaster that the database is consistent now,
7935  * enabling connections.
7936  */
7941  {
7945 
7946  LocalHotStandbyActive = true;
7947 
7949  }
7950 }
#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:171
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool LocalHotStandbyActive
Definition: xlog.c:223
void UpdateControlFile(void)
Definition: xlog.c:4687
bool IsUnderPostmaster
Definition: globals.c:101
unsigned int uint32
Definition: c.h:258
#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:170
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:169
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:167
static XLogRecPtr minRecoveryPoint
Definition: xlog.c:824
XLogRecPtr lastReplayedEndRecPtr
Definition: xlog.c:683
static void CheckRequiredParameterValues ( void  )
static

Definition at line 6238 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().

6239 {
6240  /*
6241  * For archive recovery, the WAL must be generated with at least 'replica'
6242  * wal_level.
6243  */
6245  {
6246  ereport(WARNING,
6247  (errmsg("WAL was generated with wal_level=minimal, data may be missing"),
6248  errhint("This happens if you temporarily set wal_level=minimal without taking a new base backup.")));
6249  }
6250 
6251  /*
6252  * For Hot Standby, the WAL must be generated with 'replica' mode, and we
6253  * must have at least as many backend slots as the primary.
6254  */
6256  {
6258  ereport(ERROR,
6259  (errmsg("hot standby is not possible because wal_level was not set to \"replica\" or higher on the master server"),
6260  errhint("Either set wal_level to \"replica\" on the master, or turn off hot_standby here.")));
6261 
6262  /* We ignore autovacuum_max_workers when we make this test. */
6263  RecoveryRequiresIntParameter("max_connections",
6266  RecoveryRequiresIntParameter("max_worker_processes",
6269  RecoveryRequiresIntParameter("max_prepared_transactions",
6272  RecoveryRequiresIntParameter("max_locks_per_transaction",
6275  }
6276 }
bool ArchiveRecoveryRequested
Definition: xlog.c:248
int max_locks_per_xact
Definition: pg_control.h:182
int errhint(const char *fmt,...)
Definition: elog.c:987
int max_prepared_xacts
Definition: pg_control.h:181
int max_worker_processes
Definition: pg_control.h:180
#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:124
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:125
#define RecoveryRequiresIntParameter(param_name, currValue, minValue)
Definition: xlog.c:6216
static void checkTimeLineSwitch ( XLogRecPtr  lsn,
TimeLineID  newTLI,
TimeLineID  prevTLI 
)
static

Definition at line 9655 of file xlog.c.

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

Referenced by StartupXLOG().

9656 {
9657  /* Check that the record agrees on what the current (old) timeline is */
9658  if (prevTLI != ThisTimeLineID)
9659  ereport(PANIC,
9660  (errmsg("unexpected previous timeline ID %u (current timeline ID %u) in checkpoint record",
9661  prevTLI, ThisTimeLineID)));
9662 
9663  /*
9664  * The new timeline better be in the list of timelines we expect to see,
9665  * according to the timeline history. It should also not decrease.
9666  */
9667  if (newTLI < ThisTimeLineID || !tliInHistory(newTLI, expectedTLEs))
9668  ereport(PANIC,
9669  (errmsg("unexpected timeline ID %u (after %u) in checkpoint record",
9670  newTLI, ThisTimeLineID)));
9671 
9672  /*
9673  * If we have not yet reached min recovery point, and we're about to
9674  * switch to a timeline greater than the timeline of the min recovery
9675  * point: trouble. After switching to the new timeline, we could not
9676  * possibly visit the min recovery point on the correct timeline anymore.
9677  * This can happen if there is a newer timeline in the archive that
9678  * branched before the timeline the min recovery point is on, and you
9679  * attempt to do PITR to the new timeline.
9680  */
9682  lsn < minRecoveryPoint &&
9683  newTLI > minRecoveryPointTLI)
9684  ereport(PANIC,
9685  (errmsg("unexpected timeline ID %u in checkpoint record, before reaching minimum recovery point %X/%X on timeline %u",
9686  newTLI,
9687  (uint32) (minRecoveryPoint >> 32),
9690 
9691  /* Looks good */
9692 }
static List * expectedTLEs
Definition: xlog.c:320
#define PANIC
Definition: elog.h:53
unsigned int uint32
Definition: c.h:258
#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:517
static XLogRecPtr minRecoveryPoint
Definition: xlog.c:824
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 }
void(* rm_mask)(char *pagedata, BlockNumber blkno)
#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
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:664
#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
void CheckXLogRemoved ( XLogSegNo  segno,
TimeLineID  tli 
)

Definition at line 3784 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().

3785 {
3786  XLogSegNo lastRemovedSegNo;
3787 
3789  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3791 
3792  if (segno <= lastRemovedSegNo)
3793  {
3794  char filename[MAXFNAMELEN];
3795 
3796  XLogFileName(filename, tli, segno, wal_segment_size);
3797  ereport(ERROR,
3799  errmsg("requested WAL segment %s has already been removed",
3800  filename)));
3801  }
3802 }
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
static void CleanupBackupHistory ( void  )
static

Definition at line 4119 of file xlog.c.

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

Referenced by do_pg_stop_backup().

4120 {
4121  DIR *xldir;
4122  struct dirent *xlde;
4123  char path[MAXPGPATH + sizeof(XLOGDIR)];
4124 
4125  xldir = AllocateDir(XLOGDIR);
4126  if (xldir == NULL)
4127  ereport(ERROR,
4129  errmsg("could not open write-ahead log directory \"%s\": %m",
4130  XLOGDIR)));
4131 
4132  while ((xlde = ReadDir(xldir, XLOGDIR)) != NULL)
4133  {
4134  if (IsBackupHistoryFileName(xlde->d_name))
4135  {
4136  if (XLogArchiveCheckDone(xlde->d_name))
4137  {
4138  elog(DEBUG2, "removing WAL backup history file \"%s\"",
4139  xlde->d_name);
4140  snprintf(path, sizeof(path), XLOGDIR "/%s", xlde->d_name);
4141  unlink(path);
4142  XLogArchiveCleanup(xlde->d_name);
4143  }
4144  }
4145  }
4146 
4147  FreeDir(xldir);
4148 }
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:2335
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
#define IsBackupHistoryFileName(fname)
#define XLOGDIR
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2401
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:2444
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:601
static void WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt)
Definition: xlog.c:1677
unsigned int uint32
Definition: c.h:258
#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:664
#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
void CreateCheckPoint ( int  flags)

Definition at line 8620 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(), ControlFileData::prevCheckPoint, 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().

8621 {
8622  bool shutdown;
8623  CheckPoint checkPoint;
8624  XLogRecPtr recptr;
8626  uint32 freespace;
8627  XLogRecPtr PriorRedoPtr;
8628  XLogRecPtr curInsert;
8629  XLogRecPtr last_important_lsn;
8630  VirtualTransactionId *vxids;
8631  int nvxids;
8632 
8633  /*
8634  * An end-of-recovery checkpoint is really a shutdown checkpoint, just
8635  * issued at a different time.
8636  */
8638  shutdown = true;
8639  else
8640  shutdown = false;
8641 
8642  /* sanity check */
8643  if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
8644  elog(ERROR, "can't create a checkpoint during recovery");
8645 
8646  /*
8647  * Initialize InitXLogInsert working areas before entering the critical
8648  * section. Normally, this is done by the first call to
8649  * RecoveryInProgress() or LocalSetXLogInsertAllowed(), but when creating
8650  * an end-of-recovery checkpoint, the LocalSetXLogInsertAllowed call is
8651  * done below in a critical section, and InitXLogInsert cannot be called
8652  * in a critical section.
8653  */
8654  InitXLogInsert();
8655 
8656  /*
8657  * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
8658  * (This is just pro forma, since in the present system structure there is
8659  * only one process that is allowed to issue checkpoints at any given
8660  * time.)
8661  */
8662  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
8663 
8664  /*
8665  * Prepare to accumulate statistics.
8666  *
8667  * Note: because it is possible for log_checkpoints to change while a
8668  * checkpoint proceeds, we always accumulate stats, even if
8669  * log_checkpoints is currently off.
8670  */
8671  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
8673 
8674  /*
8675  * Use a critical section to force system panic if we have trouble.
8676  */
8678 
8679  if (shutdown)
8680  {
8681  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8683  ControlFile->time = (pg_time_t) time(NULL);
8685  LWLockRelease(ControlFileLock);
8686  }
8687 
8688  /*
8689  * Let smgr prepare for checkpoint; this has to happen before we determine
8690  * the REDO pointer. Note that smgr must not do anything that'd have to
8691  * be undone if we decide no checkpoint is needed.
8692  */
8693  smgrpreckpt();
8694 
8695  /* Begin filling in the checkpoint WAL record */
8696  MemSet(&checkPoint, 0, sizeof(checkPoint));
8697  checkPoint.time = (pg_time_t) time(NULL);
8698 
8699  /*
8700  * For Hot Standby, derive the oldestActiveXid before we fix the redo
8701  * pointer. This allows us to begin accumulating changes to assemble our
8702  * starting snapshot of locks and transactions.
8703  */
8704  if (!shutdown && XLogStandbyInfoActive())
8706  else
8708 
8709  /*
8710  * Get location of last important record before acquiring insert locks (as
8711  * GetLastImportantRecPtr() also locks WAL locks).
8712  */
8713  last_important_lsn = GetLastImportantRecPtr();
8714 
8715  /*
8716  * We must block concurrent insertions while examining insert state to
8717  * determine the checkpoint REDO pointer.
8718  */
8720  curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
8721 
8722  /*
8723  * If this isn't a shutdown or forced checkpoint, and if there has been no
8724  * WAL activity requiring a checkpoint, skip it. The idea here is to
8725  * avoid inserting duplicate checkpoints when the system is idle.
8726  */
8727  if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
8728  CHECKPOINT_FORCE)) == 0)
8729  {
8730  if (last_important_lsn == ControlFile->checkPoint)
8731  {
8733  LWLockRelease(CheckpointLock);
8734  END_CRIT_SECTION();
8735  ereport(DEBUG1,
8736  (errmsg("checkpoint skipped because system is idle")));
8737  return;
8738  }
8739  }
8740 
8741  /*
8742  * An end-of-recovery checkpoint is created before anyone is allowed to
8743  * write WAL. To allow us to write the checkpoint record, temporarily
8744  * enable XLogInsertAllowed. (This also ensures ThisTimeLineID is
8745  * initialized, which we need here and in AdvanceXLInsertBuffer.)
8746  */
8747  if (flags & CHECKPOINT_END_OF_RECOVERY)
8749 
8750  checkPoint.ThisTimeLineID = ThisTimeLineID;
8751  if (flags & CHECKPOINT_END_OF_RECOVERY)
8752  checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8753  else
8754  checkPoint.PrevTimeLineID = ThisTimeLineID;
8755 
8756  checkPoint.fullPageWrites = Insert->fullPageWrites;
8757 
8758  /*
8759  * Compute new REDO record ptr = location of next XLOG record.
8760  *
8761  * NB: this is NOT necessarily where the checkpoint record itself will be,
8762  * since other backends may insert more XLOG records while we're off doing
8763  * the buffer flush work. Those XLOG records are logically after the
8764  * checkpoint, even though physically before it. Got that?
8765  */
8766  freespace = INSERT_FREESPACE(curInsert);
8767  if (freespace == 0)
8768  {
8769  if (XLogSegmentOffset(curInsert, wal_segment_size) == 0)
8770  curInsert += SizeOfXLogLongPHD;
8771  else
8772  curInsert += SizeOfXLogShortPHD;
8773  }
8774  checkPoint.redo = curInsert;
8775 
8776  /*
8777  * Here we update the shared RedoRecPtr for future XLogInsert calls; this
8778  * must be done while holding all the insertion locks.
8779  *
8780  * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
8781  * pointing past where it really needs to point. This is okay; the only
8782  * consequence is that XLogInsert might back up whole buffers that it
8783  * didn't really need to. We can't postpone advancing RedoRecPtr because
8784  * XLogInserts that happen while we are dumping buffers must assume that
8785  * their buffer changes are not included in the checkpoint.
8786  */
8787  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
8788 
8789  /*
8790  * Now we can release the WAL insertion locks, allowing other xacts to
8791  * proceed while we are flushing disk buffers.
8792  */
8794 
8795  /* Update the info_lck-protected copy of RedoRecPtr as well */
8797  XLogCtl->RedoRecPtr = checkPoint.redo;
8799 
8800  /*
8801  * If enabled, log checkpoint start. We postpone this until now so as not
8802  * to log anything if we decided to skip the checkpoint.
8803  */
8804  if (log_checkpoints)
8805  LogCheckpointStart(flags, false);
8806 
8807  TRACE_POSTGRESQL_CHECKPOINT_START(flags);
8808 
8809  /*
8810  * Get the other info we need for the checkpoint record.
8811  *
8812  * We don't need to save oldestClogXid in the checkpoint, it only matters
8813  * for the short period in which clog is being truncated, and if we crash
8814  * during that we'll redo the clog truncation and fix up oldestClogXid
8815  * there.
8816  */
8817  LWLockAcquire(XidGenLock, LW_SHARED);
8818  checkPoint.nextXid = ShmemVariableCache->nextXid;
8819  checkPoint.oldestXid = ShmemVariableCache->oldestXid;
8821  LWLockRelease(XidGenLock);
8822 
8823  LWLockAcquire(CommitTsLock, LW_SHARED);
8826  LWLockRelease(CommitTsLock);
8827 
8828  /* Increase XID epoch if we've wrapped around since last checkpoint */
8830  if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
8831  checkPoint.nextXidEpoch++;
8832 
8833  LWLockAcquire(OidGenLock, LW_SHARED);
8834  checkPoint.nextOid = ShmemVariableCache->nextOid;
8835  if (!shutdown)
8836  checkPoint.nextOid += ShmemVariableCache->oidCount;
8837  LWLockRelease(OidGenLock);
8838 
8839  MultiXactGetCheckptMulti(shutdown,
8840  &checkPoint.nextMulti,
8841  &checkPoint.nextMultiOffset,
8842  &checkPoint.oldestMulti,
8843  &checkPoint.oldestMultiDB);
8844 
8845  /*
8846  * Having constructed the checkpoint record, ensure all shmem disk buffers
8847  * and commit-log buffers are flushed to disk.
8848  *
8849  * This I/O could fail for various reasons. If so, we will fail to
8850  * complete the checkpoint, but there is no reason to force a system
8851  * panic. Accordingly, exit critical section while doing it.
8852  */
8853  END_CRIT_SECTION();
8854 
8855  /*
8856  * In some cases there are groups of actions that must all occur on one
8857  * side or the other of a checkpoint record. Before flushing the
8858  * checkpoint record we must explicitly wait for any backend currently
8859  * performing those groups of actions.
8860  *
8861  * One example is end of transaction, so we must wait for any transactions
8862  * that are currently in commit critical sections. If an xact inserted
8863  * its commit record into XLOG just before the REDO point, then a crash
8864  * restart from the REDO point would not replay that record, which means
8865  * that our flushing had better include the xact's update of pg_xact. So
8866  * we wait till he's out of his commit critical section before proceeding.
8867  * See notes in RecordTransactionCommit().
8868  *
8869  * Because we've already released the insertion locks, this test is a bit
8870  * fuzzy: it is possible that we will wait for xacts we didn't really need
8871  * to wait for. But the delay should be short and it seems better to make
8872  * checkpoint take a bit longer than to hold off insertions longer than
8873  * necessary. (In fact, the whole reason we have this issue is that xact.c
8874  * does commit record XLOG insertion and clog update as two separate steps
8875  * protected by different locks, but again that seems best on grounds of
8876  * minimizing lock contention.)
8877  *
8878  * A transaction that has not yet set delayChkpt when we look cannot be at
8879  * risk, since he's not inserted his commit record yet; and one that's
8880  * already cleared it is not at risk either, since he's done fixing clog
8881  * and we will correctly flush the update below. So we cannot miss any
8882  * xacts we need to wait for.
8883  */
8884  vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
8885  if (nvxids > 0)
8886  {
8887  do
8888  {
8889  pg_usleep(10000L); /* wait for 10 msec */
8890  } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
8891  }
8892  pfree(vxids);
8893 
8894  CheckPointGuts(checkPoint.redo, flags);
8895 
8896  /*
8897  * Take a snapshot of running transactions and write this to WAL. This
8898  * allows us to reconstruct the state of running transactions during
8899  * archive recovery, if required. Skip, if this info disabled.
8900  *
8901  * If we are shutting down, or Startup process is completing crash
8902  * recovery we don't need to write running xact data.
8903  */
8904  if (!shutdown && XLogStandbyInfoActive())
8906 
8908 
8909  /*
8910  * Now insert the checkpoint record into XLOG.
8911  */
8912  XLogBeginInsert();
8913  XLogRegisterData((char *) (&checkPoint), sizeof(checkPoint));
8914  recptr = XLogInsert(RM_XLOG_ID,
8915  shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
8917 
8918  XLogFlush(recptr);
8919 
8920  /*
8921  * We mustn't write any new WAL after a shutdown checkpoint, or it will be
8922  * overwritten at next startup. No-one should even try, this just allows
8923  * sanity-checking. In the case of an end-of-recovery checkpoint, we want
8924  * to just temporarily disable writing until the system has exited
8925  * recovery.
8926  */
8927  if (shutdown)
8928  {
8929  if (flags & CHECKPOINT_END_OF_RECOVERY)
8930  LocalXLogInsertAllowed = -1; /* return to "check" state */
8931  else
8932  LocalXLogInsertAllowed = 0; /* never again write WAL */
8933  }
8934 
8935  /*
8936  * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
8937  * = end of actual checkpoint record.
8938  */
8939  if (shutdown && checkPoint.redo != ProcLastRecPtr)
8940  ereport(PANIC,
8941  (errmsg("concurrent write-ahead log activity while database system is shutting down")));
8942 
8943  /*
8944  * Remember the prior checkpoint's redo pointer, used later to determine
8945  * the point where the log can be truncated.
8946  */
8947  PriorRedoPtr = ControlFile->checkPointCopy.redo;
8948 
8949  /*
8950  * Update the control file.
8951  */
8952  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8953  if (shutdown)
8957  ControlFile->checkPointCopy = checkPoint;
8958  ControlFile->time = (pg_time_t) time(NULL);
8959  /* crash recovery should always recover to the end of WAL */
8962 
8963  /*
8964  * Persist unloggedLSN value. It's reset on crash recovery, so this goes
8965  * unused on non-shutdown checkpoints, but seems useful to store it always
8966  * for debugging purposes.
8967  */
8971 
8973  LWLockRelease(ControlFileLock);
8974 
8975  /* Update shared-memory copy of checkpoint XID/epoch */
8977  XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
8978  XLogCtl->ckptXid = checkPoint.nextXid;
8980 
8981  /*
8982  * We are now done with critical updates; no need for system panic if we
8983  * have trouble while fooling with old log segments.
8984  */
8985  END_CRIT_SECTION();
8986 
8987  /*
8988  * Let smgr do post-checkpoint cleanup (eg, deleting old files).
8989  */
8990  smgrpostckpt();
8991 
8992  /*
8993  * Delete old log files (those no longer needed even for previous
8994  * checkpoint or the standbys in XLOG streaming).
8995  */
8996  if (PriorRedoPtr != InvalidXLogRecPtr)
8997  {
8998  XLogSegNo _logSegNo;
8999 
9000  /* Update the average distance between checkpoints. */
9002 
9003  XLByteToSeg(PriorRedoPtr, _logSegNo, wal_segment_size);
9004  KeepLogSeg(recptr, &_logSegNo);
9005  _logSegNo--;
9006  RemoveOldXlogFiles(_logSegNo, PriorRedoPtr, recptr);
9007  }
9008 
9009  /*
9010  * Make more log segments if needed. (Do this after recycling old log
9011  * segments, since that may supply some of the needed files.)
9012  */
9013  if (!shutdown)
9014  PreallocXlogFiles(recptr);
9015 
9016  /*
9017  * Truncate pg_subtrans if possible. We can throw away all data before
9018  * the oldest XMIN of any running transaction. No future transaction will
9019  * attempt to reference any pg_subtrans entry older than that (see Asserts
9020  * in subtrans.c). During recovery, though, we mustn't do this because
9021  * StartupSUBTRANS hasn't been called yet.
9022  */
9023  if (!RecoveryInProgress())
9025 
9026  /* Real work is done, but log and update stats before releasing lock. */
9027  LogCheckpointEnd(false);
9028 
9029  TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
9030  NBuffers,
9034 
9035  LWLockRelease(CheckpointLock);
9036 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8332
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8558
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:168
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:846
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
Definition: xlog.c:3849
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:9097
CheckPoint checkPointCopy
Definition: pg_control.h:132
XLogCtlInsert Insert
Definition: xlog.c:577
TransactionId oldestXid
Definition: pg_control.h:47
bool RecoveryInProgress(void)
Definition: xlog.c:7962
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:2773
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:4687
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:8473
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:134
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3756
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:258
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:1044
int ckpt_bufs_written
Definition: xlog.h:205
static void LocalSetXLogInsertAllowed(void)
Definition: xlog.c:8088
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:9421
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
Oid oldestMultiDB
Definition: pg_control.h:50
#define XLogStandbyInfoActive()
Definition: xlog.h:160
XLogRecPtr prevCheckPoint
Definition: pg_control.h:130
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:123
#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:8455
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:176
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:167
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:72
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
static void CreateEndOfRecoveryRecord ( void  )
static

Definition at line 9048 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().

9049 {
9050  xl_end_of_recovery xlrec;
9051  XLogRecPtr recptr;
9052 
9053  /* sanity check */
9054  if (!RecoveryInProgress())
9055  elog(ERROR, "can only be used to end recovery");
9056 
9057  xlrec.end_time = GetCurrentTimestamp();
9058 
9063 
9065 
9067 
9068  XLogBeginInsert();
9069  XLogRegisterData((char *) &xlrec, sizeof(xl_end_of_recovery));
9070  recptr = XLogInsert(RM_XLOG_ID, XLOG_END_OF_RECOVERY);
9071 
9072  XLogFlush(recptr);
9073 
9074  /*
9075  * Update the control file so that crash recovery can follow the timeline
9076  * changes to this point.
9077  */
9078  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9079  ControlFile->time = (pg_time_t) time(NULL);
9080  ControlFile->minRecoveryPoint = recptr;
9083  LWLockRelease(ControlFileLock);
9084 
9085  END_CRIT_SECTION();
9086 
9087  LocalXLogInsertAllowed = -1; /* return to "check" state */
9088 }
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:168
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:7962
#define XLOG_END_OF_RECOVERY
Definition: pg_control.h:76
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2773
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void UpdateControlFile(void)
Definition: xlog.c:4687
#define ERROR
Definition: elog.h:43
static void LocalSetXLogInsertAllowed(void)
Definition: xlog.c:8088
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:167
bool CreateRestartPoint ( int  flags)

Definition at line 9167 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(), ControlFileData::prevCheckPoint, 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().

9168 {
9169  XLogRecPtr lastCheckPointRecPtr;
9170  XLogRecPtr lastCheckPointEndPtr;
9171  CheckPoint lastCheckPoint;
9172  XLogRecPtr PriorRedoPtr;
9173  TimestampTz xtime;
9174 
9175  /*
9176  * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
9177  * happens at a time.
9178  */
9179  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
9180 
9181  /* Get a local copy of the last safe checkpoint record. */
9183  lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
9184  lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
9185  lastCheckPoint = XLogCtl->lastCheckPoint;
9187 
9188  /*
9189  * Check that we're still in recovery mode. It's ok if we exit recovery
9190  * mode after this check, the restart point is valid anyway.
9191  */
9192  if (!RecoveryInProgress())
9193  {
9194  ereport(DEBUG2,
9195  (errmsg("skipping restartpoint, recovery has already ended")));
9196  LWLockRelease(CheckpointLock);
9197  return false;
9198  }
9199 
9200  /*
9201  * If the last checkpoint record we've replayed is already our last
9202  * restartpoint, we can't perform a new restart point. We still update
9203  * minRecoveryPoint in that case, so that if this is a shutdown restart
9204  * point, we won't start up earlier than before. That's not strictly
9205  * necessary, but when hot standby is enabled, it would be rather weird if
9206  * the database opened up for read-only connections at a point-in-time
9207  * before the last shutdown. Such time travel is still possible in case of
9208  * immediate shutdown, though.
9209  *
9210  * We don't explicitly advance minRecoveryPoint when we do create a
9211  * restartpoint. It's assumed that flushing the buffers will do that as a
9212  * side-effect.
9213  */
9214  if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
9215  lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
9216  {
9217  ereport(DEBUG2,
9218  (errmsg("skipping restartpoint, already performed at %X/%X",
9219  (uint32) (lastCheckPoint.redo >> 32),
9220  (uint32) lastCheckPoint.redo)));
9221 
9223  if (flags & CHECKPOINT_IS_SHUTDOWN)
9224  {
9225  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9227  ControlFile->time = (pg_time_t) time(NULL);
9229  LWLockRelease(ControlFileLock);
9230  }
9231  LWLockRelease(CheckpointLock);
9232  return false;
9233  }
9234 
9235  /*
9236  * Update the shared RedoRecPtr so that the startup process can calculate
9237  * the number of segments replayed since last restartpoint, and request a
9238  * restartpoint if it exceeds CheckPointSegments.
9239  *
9240  * Like in CreateCheckPoint(), hold off insertions to update it, although
9241  * during recovery this is just pro forma, because no WAL insertions are
9242  * happening.
9243  */
9245  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
9247 
9248  /* Also update the info_lck-protected copy */
9250  XLogCtl->RedoRecPtr = lastCheckPoint.redo;
9252 
9253  /*
9254  * Prepare to accumulate statistics.
9255  *
9256  * Note: because it is possible for log_checkpoints to change while a
9257  * checkpoint proceeds, we always accumulate stats, even if
9258  * log_checkpoints is currently off.
9259  */
9260  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
9262 
9263  if (log_checkpoints)
9264  LogCheckpointStart(flags, true);
9265 
9266  CheckPointGuts(lastCheckPoint.redo, flags);
9267 
9268  /*
9269  * Remember the prior checkpoint's redo pointer, used later to determine
9270  * the point at which we can truncate the log.
9271  */
9272  PriorRedoPtr = ControlFile->checkPointCopy.redo;
9273 
9274  /*
9275  * Update pg_control, using current time. Check that it still shows
9276  * IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
9277  * this is a quick hack to make sure nothing really bad happens if somehow
9278  * we get here after the end-of-recovery checkpoint.
9279  */
9280  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9282  ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
9283  {
9285  ControlFile->checkPoint = lastCheckPointRecPtr;
9286  ControlFile->checkPointCopy = lastCheckPoint;
9287  ControlFile->time = (pg_time_t) time(NULL);
9288 
9289  /*
9290  * Ensure minRecoveryPoint is past the checkpoint record. Normally,
9291  * this will have happened already while writing out dirty buffers,
9292  * but not necessarily - e.g. because no buffers were dirtied. We do
9293  * this because a non-exclusive base backup uses minRecoveryPoint to
9294  * determine which WAL files must be included in the backup, and the
9295  * file (or files) containing the checkpoint record must be included,
9296  * at a minimum. Note that for an ordinary restart of recovery there's
9297  * no value in having the minimum recovery point any earlier than this
9298  * anyway, because redo will begin just after the checkpoint record.
9299  */
9300  if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
9301  {
9302  ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
9304 
9305  /* update local copy */
9308  }
9309  if (flags & CHECKPOINT_IS_SHUTDOWN)
9312  }
9313  LWLockRelease(ControlFileLock);
9314 
9315  /*
9316  * Delete old log files (those no longer needed even for previous
9317  * checkpoint/restartpoint) to prevent the disk holding the xlog from
9318  * growing full.
9319  */
9320  if (PriorRedoPtr != InvalidXLogRecPtr)
9321  {
9322  XLogRecPtr receivePtr;
9323  XLogRecPtr replayPtr;
9324  TimeLineID replayTLI;
9325  XLogRecPtr endptr;
9326  XLogSegNo _logSegNo;
9327 
9328  /* Update the average distance between checkpoints/restartpoints. */
9330 
9331  XLByteToSeg(PriorRedoPtr, _logSegNo, wal_segment_size);
9332 
9333  /*
9334  * Get the current end of xlog replayed or received, whichever is
9335  * later.
9336  */
9337  receivePtr = GetWalRcvWriteRecPtr(NULL, NULL);
9338  replayPtr = GetXLogReplayRecPtr(&replayTLI);
9339  endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
9340 
9341  KeepLogSeg(endptr, &_logSegNo);
9342  _logSegNo--;
9343 
9344  /*
9345  * Try to recycle segments on a useful timeline. If we've been
9346  * promoted since the beginning of this restartpoint, use the new
9347  * timeline chosen at end of recovery (RecoveryInProgress() sets
9348  * ThisTimeLineID in that case). If we're still in recovery, use the
9349  * timeline we're currently replaying.
9350  *
9351  * There is no guarantee that the WAL segments will be useful on the
9352  * current timeline; if recovery proceeds to a new timeline right
9353  * after this, the pre-allocated WAL segments on this timeline will
9354  * not be used, and will go wasted until recycled on the next
9355  * restartpoint. We'll live with that.
9356  */
9357  if (RecoveryInProgress())
9358  ThisTimeLineID = replayTLI;
9359 
9360  RemoveOldXlogFiles(_logSegNo, PriorRedoPtr, endptr);
9361 
9362  /*
9363  * Make more log segments if needed. (Do this after recycling old log
9364  * segments, since that may supply some of the needed files.)
9365  */
9366  PreallocXlogFiles(endptr);
9367 
9368  /*
9369  * ThisTimeLineID is normally not set when we're still in recovery.
9370  * However, recycling/preallocating segments above needed
9371  * ThisTimeLineID to determine which timeline to install the segments
9372  * on. Reset it now, to restore the normal state of affairs for
9373  * debugging purposes.
9374  */
9375  if (RecoveryInProgress())
9376  ThisTimeLineID = 0;
9377  }
9378 
9379  /*
9380  * Truncate pg_subtrans if possible. We can throw away all data before
9381  * the oldest XMIN of any running transaction. No future transaction will
9382  * attempt to reference any pg_subtrans entry older than that (see Asserts
9383  * in subtrans.c). When hot standby is disabled, though, we mustn't do
9384  * this because StartupSUBTRANS hasn't been called yet.
9385  */
9386  if (EnableHotStandby)
9388 
9389  /* Real work is done, but log and update before releasing lock. */
9390  LogCheckpointEnd(true);
9391 
9392  xtime = GetLatestXTime();
9394  (errmsg("recovery restart point at %X/%X",
9395  (uint32) (lastCheckPoint.redo >> 32), (uint32) lastCheckPoint.redo),
9396  xtime ? errdetail("last completed transaction was at log time %s",
9397  timestamptz_to_str(xtime)) : 0));
9398 
9399  LWLockRelease(CheckpointLock);
9400 
9401  /*
9402  * Finally, execute archive_cleanup_command, if any.
9403  */
9406  "archive_cleanup_command",
9407  false);
9408 
9409  return true;
9410 }
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8558
bool log_checkpoints
Definition: xlog.c:102
#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:168
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
Definition: xlog.c:2698
TimestampTz ckpt_start_t
Definition: xlog.h:199
slock_t info_lck
Definition: xlog.c:704
#define MemSet(start, val, len)
Definition: c.h:846
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
Definition: xlog.c:3849
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:9097
TimestampTz GetLatestXTime(void)
Definition: xlog.c:6154
CheckPoint checkPointCopy
Definition: pg_control.h:132
XLogCtlInsert Insert
Definition: xlog.c:577
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:7962
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:4687
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8473
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11185
#define DEBUG2
Definition: elog.h:24
static XLogRecPtr RedoRecPtr
Definition: xlog.c:352
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3756
uint64 XLogSegNo
Definition: xlogdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:873
unsigned int uint32
Definition: c.h:258
XLogRecPtr RedoRecPtr
Definition: xlog.c:581
#define ereport(elevel, rest)
Definition: elog.h:122
CheckPoint lastCheckPoint
Definition: xlog.c:675
void ExecuteRecoveryCommand(char *command, char *commandName, bool failOnSignal)
Definition: xlogarchive.c:330
#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:9421
XLogRecPtr prevCheckPoint
Definition: pg_control.h:130
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:8455
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:176
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:167
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)
bool DataChecksumsEnabled ( void  )

Definition at line 4756 of file xlog.c.

References Assert, and ControlFileData::data_checksum_version.

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

4757 {
4758  Assert(ControlFile != NULL);
4759  return (ControlFile->data_checksum_version > 0);
4760 }
uint32 data_checksum_version
Definition: pg_control.h:222
static ControlFileData * ControlFile
Definition: xlog.c:715
#define Assert(condition)
Definition: c.h:664
void do_pg_abort_backup ( void  )

Definition at line 11165 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().

11166 {
11170 
11173  {
11174  XLogCtl->Insert.forcePageWrites = false;
11175  }
11177 }
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:664
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1622
static XLogCtlData * XLogCtl
Definition: xlog.c:707
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 10270 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(), RecoveryInProgress(), CheckPoint::redo, relpath, RequestCheckpoint(), RequestXLogSwitch(), tablespaceinfo::rpath, sendTablespace(), SESSION_BACKUP_EXCLUSIVE, SESSION_BACKUP_NON_EXCLUSIVE, sessionBackupState, tablespaceinfo::size, snprintf(), SpinLockAcquire, SpinLockRelease, TABLESPACE_MAP, CheckPoint::ThisTimeLineID, wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), WARNING, XLByteToSeg, XLogFileName, and XLogIsNeeded.

Referenced by perform_base_backup(), and pg_start_backup().

10274 {
10275  bool exclusive = (labelfile == NULL);
10276  bool backup_started_in_recovery = false;
10277  XLogRecPtr checkpointloc;
10278  XLogRecPtr startpoint;
10279  TimeLineID starttli;
10280  pg_time_t stamp_time;
10281  char strfbuf[128];
10282  char xlogfilename[MAXFNAMELEN];
10283  XLogSegNo _logSegNo;
10284  struct stat stat_buf;
10285  FILE *fp;
10286 
10287  backup_started_in_recovery = RecoveryInProgress();
10288 
10289  /*
10290  * Currently only non-exclusive backup can be taken during recovery.
10291  */
10292  if (backup_started_in_recovery && exclusive)
10293  ereport(ERROR,
10294  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10295  errmsg("recovery is in progress"),
10296  errhint("WAL control functions cannot be executed during recovery.")));
10297 
10298  /*
10299  * During recovery, we don't need to check WAL level. Because, if WAL
10300  * level is not sufficient, it's impossible to get here during recovery.
10301  */
10302  if (!backup_started_in_recovery && !XLogIsNeeded())
10303  ereport(ERROR,
10304  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10305  errmsg("WAL level not sufficient for making an online backup"),
10306  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
10307 
10308  if (strlen(backupidstr) > MAXPGPATH)
10309  ereport(ERROR,
10310  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10311  errmsg("backup label too long (max %d bytes)",
10312  MAXPGPATH)));
10313 
10314  /*
10315  * Mark backup active in shared memory. We must do full-page WAL writes
10316  * during an on-line backup even if not doing so at other times, because
10317  * it's quite possible for the backup dump to obtain a "torn" (partially
10318  * written) copy of a database page if it reads the page concurrently with
10319  * our write to the same page. This can be fixed as long as the first
10320  * write to the page in the WAL sequence is a full-page write. Hence, we
10321  * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
10322  * are no dirty pages in shared memory that might get dumped while the
10323  * backup is in progress without having a corresponding WAL record. (Once
10324  * the backup is complete, we need not force full-page writes anymore,
10325  * since we expect that any pages not modified during the backup interval
10326  * must have been correctly captured by the backup.)
10327  *
10328  * Note that forcePageWrites has no effect during an online backup from
10329  * the standby.
10330  *
10331  * We must hold all the insertion locks to change the value of
10332  * forcePageWrites, to ensure adequate interlocking against
10333  * XLogInsertRecord().
10334  */
10336  if (exclusive)
10337  {
10338  /*
10339  * At first, mark that we're now starting an exclusive backup, to
10340  * ensure that there are no other sessions currently running
10341  * pg_start_backup() or pg_stop_backup().
10342  */
10344  {
10346  ereport(ERROR,
10347  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10348  errmsg("a backup is already in progress"),
10349  errhint("Run pg_stop_backup() and try again.")));
10350  }
10352  }
10353  else
10355  XLogCtl->Insert.forcePageWrites = true;
10357 
10358  /* Ensure we release forcePageWrites if fail below */
10360  {
10361  bool gotUniqueStartpoint = false;
10362  struct dirent *de;
10363  tablespaceinfo *ti;
10364  int datadirpathlen;
10365 
10366  /*
10367  * Force an XLOG file switch before the checkpoint, to ensure that the
10368  * WAL segment the checkpoint is written to doesn't contain pages with
10369  * old timeline IDs. That would otherwise happen if you called
10370  * pg_start_backup() right after restoring from a PITR archive: the
10371  * first WAL segment containing the startup checkpoint has pages in
10372  * the beginning with the old timeline ID. That can cause trouble at
10373  * recovery: we won't have a history file covering the old timeline if
10374  * pg_wal directory was not included in the base backup and the WAL
10375  * archive was cleared too before starting the backup.
10376  *
10377  * This also ensures that we have emitted a WAL page header that has
10378  * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
10379  * Therefore, if a WAL archiver (such as pglesslog) is trying to
10380  * compress out removable backup blocks, it won't remove any that
10381  * occur after this point.
10382  *
10383  * During recovery, we skip forcing XLOG file switch, which means that
10384  * the backup taken during recovery is not available for the special
10385  * recovery case described above.
10386  */
10387  if (!backup_started_in_recovery)
10388  RequestXLogSwitch(false);
10389 
10390  do
10391  {
10392  bool checkpointfpw;
10393 
10394  /*
10395  * Force a CHECKPOINT. Aside from being necessary to prevent torn
10396  * page problems, this guarantees that two successive backup runs
10397  * will have different checkpoint positions and hence different
10398  * history file names, even if nothing happened in between.
10399  *
10400  * During recovery, establish a restartpoint if possible. We use
10401  * the last restartpoint as the backup starting checkpoint. This
10402  * means that two successive backup runs can have same checkpoint
10403  * positions.
10404  *
10405  * Since the fact that we are executing do_pg_start_backup()
10406  * during recovery means that checkpointer is running, we can use
10407  * RequestCheckpoint() to establish a restartpoint.
10408  *
10409  * We use CHECKPOINT_IMMEDIATE only if requested by user (via
10410  * passing fast = true). Otherwise this can take awhile.
10411  */
10413  (fast ? CHECKPOINT_IMMEDIATE : 0));
10414 
10415  /*
10416  * Now we need to fetch the checkpoint record location, and also
10417  * its REDO pointer. The oldest point in WAL that would be needed
10418  * to restore starting from the checkpoint is precisely the REDO
10419  * pointer.
10420  */
10421  LWLockAcquire(ControlFileLock, LW_SHARED);
10422  checkpointloc = ControlFile->checkPoint;
10423  startpoint = ControlFile->checkPointCopy.redo;
10425  checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
10426  LWLockRelease(ControlFileLock);
10427 
10428  if (backup_started_in_recovery)
10429  {
10430  XLogRecPtr recptr;
10431 
10432  /*
10433  * Check to see if all WAL replayed during online backup
10434  * (i.e., since last restartpoint used as backup starting
10435  * checkpoint) contain full-page writes.
10436  */
10438  recptr = XLogCtl->lastFpwDisableRecPtr;
10440 
10441  if (!checkpointfpw || startpoint <= recptr)
10442  ereport(ERROR,
10443  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10444  errmsg("WAL generated with full_page_writes=off was replayed "
10445  "since last restartpoint"),
10446  errhint("This means that the backup being taken on the standby "
10447  "is corrupt and should not be used. "
10448  "Enable full_page_writes and run CHECKPOINT on the master, "
10449  "and then try an online backup again.")));
10450 
10451  /*
10452  * During recovery, since we don't use the end-of-backup WAL
10453  * record and don't write the backup history file, the
10454  * starting WAL location doesn't need to be unique. This means
10455  * that two base backups started at the same time might use
10456  * the same checkpoint as starting locations.
10457  */
10458  gotUniqueStartpoint = true;
10459  }
10460 
10461  /*
10462  * If two base backups are started at the same time (in WAL sender
10463  * processes), we need to make sure that they use different
10464  * checkpoints as starting locations, because we use the starting
10465  * WAL location as a unique identifier for the base backup in the
10466  * end-of-backup WAL record and when we write the backup history
10467  * file. Perhaps it would be better generate a separate unique ID
10468  * for each backup instead of forcing another checkpoint, but
10469  * taking a checkpoint right after another is not that expensive
10470  * either because only few buffers have been dirtied yet.
10471  */
10473  if (XLogCtl->Insert.lastBackupStart < startpoint)
10474  {
10475  XLogCtl->Insert.lastBackupStart = startpoint;
10476  gotUniqueStartpoint = true;
10477  }
10479  } while (!gotUniqueStartpoint);
10480 
10481  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
10482  XLogFileName(xlogfilename, starttli, _logSegNo, wal_segment_size);
10483 
10484  /*
10485  * Construct tablespace_map file
10486  */
10487  if (exclusive)
10488  tblspcmapfile = makeStringInfo();
10489 
10490  datadirpathlen = strlen(DataDir);
10491 
10492  /* Collect information about all tablespaces */
10493  while ((de = ReadDir(tblspcdir, "pg_tblspc")) != NULL)
10494  {
10495  char fullpath[MAXPGPATH + 10];
10496  char linkpath[MAXPGPATH];
10497  char *relpath = NULL;
10498  int rllen;
10499  StringInfoData buflinkpath;
10500  char *s = linkpath;
10501 
10502  /* Skip special stuff */
10503  if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
10504  continue;
10505 
10506  snprintf(fullpath, sizeof(fullpath), "pg_tblspc/%s", de->d_name);
10507 
10508 #if defined(HAVE_READLINK) || defined(WIN32)
10509  rllen = readlink(fullpath, linkpath, sizeof(linkpath));
10510  if (rllen < 0)
10511  {
10512  ereport(WARNING,
10513  (errmsg("could not read symbolic link \"%s\": %m",
10514  fullpath)));
10515  continue;
10516  }
10517  else if (rllen >= sizeof(linkpath))
10518  {
10519  ereport(WARNING,
10520  (errmsg("symbolic link \"%s\" target is too long",
10521  fullpath)));
10522  continue;
10523  }
10524  linkpath[rllen] = '\0';
10525 
10526  /*
10527  * Add the escape character '\\' before newline in a string to
10528  * ensure that we can distinguish between the newline in the
10529  * tablespace path and end of line while reading tablespace_map
10530  * file during archive recovery.
10531  */
10532  initStringInfo(&buflinkpath);
10533 
10534  while (*s)
10535  {
10536  if ((*s == '\n' || *s == '\r') && needtblspcmapfile)
10537  appendStringInfoChar(&buflinkpath, '\\');
10538  appendStringInfoChar(&buflinkpath, *s++);
10539  }
10540 
10541 
10542  /*
10543  * Relpath holds the relative path of the tablespace directory
10544  * when it's located within PGDATA, or NULL if it's located
10545  * elsewhere.
10546  */
10547  if (rllen > datadirpathlen &&
10548  strncmp(linkpath, DataDir, datadirpathlen) == 0 &&
10549  IS_DIR_SEP(linkpath[datadirpathlen]))
10550  relpath = linkpath + datadirpathlen + 1;
10551 
10552  ti = palloc(sizeof(tablespaceinfo));
10553  ti->oid = pstrdup(de->d_name);
10554  ti->path = pstrdup(buflinkpath.data);
10555  ti->rpath = relpath ? pstrdup(relpath) : NULL;
10556  ti->size = infotbssize ? sendTablespace(fullpath, true) : -1;
10557 
10558  if (tablespaces)
10559  *tablespaces = lappend(*tablespaces, ti);
10560 
10561  appendStringInfo(tblspcmapfile, "%s %s\n", ti->oid, ti->path);
10562 
10563  pfree(buflinkpath.data);
10564 #else
10565 
10566  /*
10567  * If the platform does not have symbolic links, it should not be
10568  * possible to have tablespaces - clearly somebody else created
10569  * them. Warn about it and ignore.
10570  */
10571  ereport(WARNING,
10572  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10573  errmsg("tablespaces are not supported on this platform")));
10574 #endif
10575  }
10576 
10577  /*
10578  * Construct backup label file
10579  */
10580  if (exclusive)
10581  labelfile = makeStringInfo();
10582 
10583  /* Use the log timezone here, not the session timezone */
10584  stamp_time = (pg_time_t) time(NULL);
10585  pg_strftime(strfbuf, sizeof(strfbuf),
10586  "%Y-%m-%d %H:%M:%S %Z",
10587  pg_localtime(&stamp_time, log_timezone));
10588  appendStringInfo(labelfile, "START WAL LOCATION: %X/%X (file %s)\n",
10589  (uint32) (startpoint >> 32), (uint32) startpoint, xlogfilename);
10590  appendStringInfo(labelfile, "CHECKPOINT LOCATION: %X/%X\n",
10591  (uint32) (checkpointloc >> 32), (uint32) checkpointloc);
10592  appendStringInfo(labelfile, "BACKUP METHOD: %s\n",
10593  exclusive ? "pg_start_backup" : "streamed");
10594  appendStringInfo(labelfile, "BACKUP FROM: %s\n",
10595  backup_started_in_recovery ? "standby" : "master");
10596  appendStringInfo(labelfile, "START TIME: %s\n", strfbuf);
10597  appendStringInfo(labelfile, "LABEL: %s\n", backupidstr);
10598 
10599  /*
10600  * Okay, write the file, or return its contents to caller.
10601  */
10602  if (exclusive)
10603  {
10604  /*
10605  * Check for existing backup label --- implies a backup is already
10606  * running. (XXX given that we checked exclusiveBackupState
10607  * above, maybe it would be OK to just unlink any such label
10608  * file?)
10609  */
10610  if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
10611  {
10612  if (errno != ENOENT)
10613  ereport(ERROR,
10615  errmsg("could not stat file \"%s\": %m",
10616  BACKUP_LABEL_FILE)));
10617  }
10618  else
10619  ereport(ERROR,
10620  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10621  errmsg("a backup is already in progress"),
10622  errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
10623  BACKUP_LABEL_FILE)));
10624 
10625  fp = AllocateFile(BACKUP_LABEL_FILE, "w");
10626 
10627  if (!fp)
10628  ereport(ERROR,
10630  errmsg("could not create file \"%s\": %m",
10631  BACKUP_LABEL_FILE)));
10632  if (fwrite(labelfile->data, labelfile->len, 1, fp) != 1 ||
10633  fflush(fp) != 0 ||
10634  pg_fsync(fileno(fp)) != 0 ||
10635  ferror(fp) ||
10636  FreeFile(fp))
10637  ereport(ERROR,
10639  errmsg("could not write file \"%s\": %m",
10640  BACKUP_LABEL_FILE)));
10641  /* Allocated locally for exclusive backups, so free separately */
10642  pfree(labelfile->data);
10643  pfree(labelfile);
10644 
10645  /* Write backup tablespace_map file. */
10646  if (tblspcmapfile->len > 0)
10647  {
10648  if (stat(TABLESPACE_MAP, &stat_buf) != 0)
10649  {
10650  if (errno != ENOENT)
10651  ereport(ERROR,
10653  errmsg("could not stat file \"%s\": %m",
10654  TABLESPACE_MAP)));
10655  }
10656  else
10657  ereport(ERROR,
10658  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10659  errmsg("a backup is already in progress"),
10660  errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
10661  TABLESPACE_MAP)));
10662 
10663  fp = AllocateFile(TABLESPACE_MAP, "w");
10664 
10665  if (!fp)
10666  ereport(ERROR,
10668  errmsg("could not create file \"%s\": %m",
10669  TABLESPACE_MAP)));
10670  if (fwrite(tblspcmapfile->data, tblspcmapfile->len, 1, fp) != 1 ||
10671  fflush(fp) != 0 ||
10672  pg_fsync(fileno(fp)) != 0 ||
10673  ferror(fp) ||
10674  FreeFile(fp))
10675  ereport(ERROR,
10677  errmsg("could not write file \"%s\": %m",
10678  TABLESPACE_MAP)));
10679  }
10680 
10681  /* Allocated locally for exclusive backups, so free separately */
10682  pfree(tblspcmapfile->data);
10683  pfree(tblspcmapfile);
10684  }
10685  }
10687 
10688  /*
10689  * Mark that start phase has correctly finished for an exclusive backup.
10690  * Session-level locks are updated as well to reflect that state.
10691  */
10692  if (exclusive)
10693  {
10698  }
10699  else
10701 
10702  /*
10703  * We're done. As a convenience, return the starting WAL location.
10704  */
10705  if (starttli_p)
10706  *starttli_p = starttli;
10707  return startpoint;
10708 }
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:9498
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:132
XLogCtlInsert Insert
Definition: xlog.c:577
bool RecoveryInProgress(void)
Definition: xlog.c:7962
static bool backup_started_in_recovery
Definition: basebackup.c:73
Definition: dirent.h:9
#define IS_DIR_SEP(ch)
Definition: port.h:75
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
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2094
unsigned int uint32
Definition: c.h:258
int64 sendTablespace(char *path, bool sizeonly)
Definition: basebackup.c:910
#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 MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
static void pg_start_backup_callback(int code, Datum arg)
Definition: xlog.c:10712
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:2401
#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:2277
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:333
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)
XLogRecPtr do_pg_stop_backup ( char *  labelfile,
bool  waitforarchive,
TimeLineID stoptli_p 
)

Definition at line 10778 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, 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().

10779 {
10780  bool exclusive = (labelfile == NULL);
10781  bool backup_started_in_recovery = false;
10782  XLogRecPtr startpoint;
10783  XLogRecPtr stoppoint;
10784  TimeLineID stoptli;
10785  pg_time_t stamp_time;
10786  char strfbuf[128];
10787  char histfilepath[MAXPGPATH];
10788  char startxlogfilename[MAXFNAMELEN];
10789  char stopxlogfilename[MAXFNAMELEN];
10790  char lastxlogfilename[MAXFNAMELEN];
10791  char histfilename[MAXFNAMELEN];
10792  char backupfrom[20];
10793  XLogSegNo _logSegNo;
10794  FILE *lfp;
10795  FILE *fp;
10796  char ch;
10797  int seconds_before_warning;
10798  int waits = 0;
10799  bool reported_waiting = false;
10800  char *remaining;
10801  char *ptr;
10802  uint32 hi,
10803  lo;
10804 
10805  backup_started_in_recovery = RecoveryInProgress();
10806 
10807  /*
10808  * Currently only non-exclusive backup can be taken during recovery.
10809  */
10810  if (backup_started_in_recovery && exclusive)
10811  ereport(ERROR,
10812  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10813  errmsg("recovery is in progress"),
10814  errhint("WAL control functions cannot be executed during recovery.")));
10815 
10816  /*
10817  * During recovery, we don't need to check WAL level. Because, if WAL
10818  * level is not sufficient, it's impossible to get here during recovery.
10819  */
10820  if (!backup_started_in_recovery && !XLogIsNeeded())
10821  ereport(ERROR,
10822  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10823  errmsg("WAL level not sufficient for making an online backup"),
10824  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
10825 
10826  if (exclusive)
10827  {
10828  /*
10829  * At first, mark that we're now stopping an exclusive backup, to
10830  * ensure that there are no other sessions currently running
10831  * pg_start_backup() or pg_stop_backup().
10832  */
10835  {
10837  ereport(ERROR,
10838  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10839  errmsg("exclusive backup not in progress")));
10840  }
10843 
10844  /*
10845  * Remove backup_label. In case of failure, the state for an exclusive
10846  * backup is switched back to in-progress.
10847  */
10849  {
10850  /*
10851  * Read the existing label file into memory.
10852  */
10853  struct stat statbuf;
10854  int r;
10855 
10856  if (stat(BACKUP_LABEL_FILE, &statbuf))
10857  {
10858  /* should not happen per the upper checks */
10859  if (errno != ENOENT)
10860  ereport(ERROR,
10862  errmsg("could not stat file \"%s\": %m",
10863  BACKUP_LABEL_FILE)));
10864  ereport(ERROR,
10865  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10866  errmsg("a backup is not in progress")));
10867  }
10868 
10869  lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
10870  if (!lfp)
10871  {
10872  ereport(ERROR,
10874  errmsg("could not read file \"%s\": %m",
10875  BACKUP_LABEL_FILE)));
10876  }
10877  labelfile = palloc(statbuf.st_size + 1);
10878  r = fread(labelfile, statbuf.st_size, 1, lfp);
10879  labelfile[statbuf.st_size] = '\0';
10880 
10881  /*
10882  * Close and remove the backup label file
10883  */
10884  if (r != 1 || ferror(lfp) || FreeFile(lfp))
10885  ereport(ERROR,
10887  errmsg("could not read file \"%s\": %m",
10888  BACKUP_LABEL_FILE)));
10890 
10891  /*
10892  * Remove tablespace_map file if present, it is created only if
10893  * there are tablespaces.
10894  */
10896  }
10898  }
10899 
10900  /*
10901  * OK to update backup counters and forcePageWrites
10902  */
10904  if (exclusive)
10905  {
10907  }
10908  else
10909  {
10910  /*
10911  * The user-visible pg_start/stop_backup() functions that operate on
10912  * exclusive backups can be called at any time, but for non-exclusive
10913  * backups, it is expected that each do_pg_start_backup() call is
10914  * matched by exactly one do_pg_stop_backup() call.
10915  */
10918  }
10919 
10922  {
10923  XLogCtl->Insert.forcePageWrites = false;
10924  }
10926 
10927  /* Clean up session-level lock */
10929 
10930  /*
10931  * Read and parse the START WAL LOCATION line (this code is pretty crude,
10932  * but we are not expecting any variability in the file format).
10933  */
10934  if (sscanf(labelfile, "START WAL LOCATION: %X/%X (file %24s)%c",
10935  &hi, &lo, startxlogfilename,
10936  &ch) != 4 || ch != '\n')
10937  ereport(ERROR,
10938  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10939  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10940  startpoint = ((uint64) hi) << 32 | lo;
10941  remaining = strchr(labelfile, '\n') + 1; /* %n is not portable enough */
10942 
10943  /*
10944  * Parse the BACKUP FROM line. If we are taking an online backup from the
10945  * standby, we confirm that the standby has not been promoted during the
10946  * backup.
10947  */
10948  ptr = strstr(remaining, "BACKUP FROM:");
10949  if (!ptr || sscanf(ptr, "BACKUP FROM: %19s\n", backupfrom) != 1)
10950  ereport(ERROR,
10951  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10952  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
10953  if (strcmp(backupfrom, "standby") == 0 && !backup_started_in_recovery)
10954  ereport(ERROR,
10955  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10956  errmsg("the standby was promoted during online backup"),
10957  errhint("This means that the backup being taken is corrupt "
10958  "and should not be used. "
10959  "Try taking another online backup.")));
10960 
10961  /*
10962  * During recovery, we don't write an end-of-backup record. We assume that
10963  * pg_control was backed up last and its minimum recovery point can be
10964  * available as the backup end location. Since we don't have an
10965  * end-of-backup record, we use the pg_control value to check whether
10966  * we've reached the end of backup when starting recovery from this
10967  * backup. We have no way of checking if pg_control wasn't backed up last
10968  * however.
10969  *
10970  * We don't force a switch to new WAL file but it is still possible to
10971  * wait for all the required files to be archived if waitforarchive is
10972  * true. This is okay if we use the backup to start a standby and fetch
10973  * the missing WAL using streaming replication. But in the case of an
10974  * archive recovery, a user should set waitforarchive to true and wait for
10975  * them to be archived to ensure that all the required files are
10976  * available.
10977  *
10978  * We return the current minimum recovery point as the backup end
10979  * location. Note that it can be greater than the exact backup end
10980  * location if the minimum recovery point is updated after the backup of
10981  * pg_control. This is harmless for current uses.
10982  *
10983  * XXX currently a backup history file is for informational and debug
10984  * purposes only. It's not essential for an online backup. Furthermore,
10985  * even if it's created, it will not be archived during recovery because
10986  * an archiver is not invoked. So it doesn't seem worthwhile to write a
10987  * backup history file during recovery.
10988  */
10989  if (backup_started_in_recovery)
10990  {
10991  XLogRecPtr recptr;
10992 
10993  /*
10994  * Check to see if all WAL replayed during online backup contain
10995  * full-page writes.
10996  */
10998  recptr = XLogCtl->lastFpwDisableRecPtr;
11000 
11001  if (startpoint <= recptr)
11002  ereport(ERROR,
11003  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11004  errmsg("WAL generated with full_page_writes=off was replayed "
11005  "during online backup"),
11006  errhint("This means that the backup being taken on the standby "
11007  "is corrupt and should not be used. "
11008  "Enable full_page_writes and run CHECKPOINT on the master, "
11009  "and then try an online backup again.")));
11010 
11011 
11012  LWLockAcquire(ControlFileLock, LW_SHARED);
11013  stoppoint = ControlFile->minRecoveryPoint;
11014  stoptli = ControlFile->minRecoveryPointTLI;
11015  LWLockRelease(ControlFileLock);
11016  }
11017  else
11018  {
11019  /*
11020  * Write the backup-end xlog record
11021  */
11022  XLogBeginInsert();
11023  XLogRegisterData((char *) (&startpoint), sizeof(startpoint));
11024  stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END);
11025  stoptli = ThisTimeLineID;
11026 
11027  /*
11028  * Force a switch to a new xlog segment file, so that the backup is
11029  * valid as soon as archiver moves out the current segment file.
11030  */
11031  RequestXLogSwitch(false);
11032 
11033  XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
11034  XLogFileName(stopxlogfilename, stoptli, _logSegNo, wal_segment_size);
11035 
11036  /* Use the log timezone here, not the session timezone */
11037  stamp_time = (pg_time_t) time(NULL);
11038  pg_strftime(strfbuf, sizeof(strfbuf),
11039  "%Y-%m-%d %H:%M:%S %Z",
11040  pg_localtime(&stamp_time, log_timezone));
11041 
11042  /*
11043  * Write the backup history file
11044  */
11045  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
11046  BackupHistoryFilePath(histfilepath, stoptli, _logSegNo,
11047  startpoint, wal_segment_size);
11048  fp = AllocateFile(histfilepath, "w");
11049  if (!fp)
11050  ereport(ERROR,
11052  errmsg("could not create file \"%s\": %m",
11053  histfilepath)));
11054  fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
11055  (uint32) (startpoint >> 32), (uint32) startpoint, startxlogfilename);
11056  fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
11057  (uint32) (stoppoint >> 32), (uint32) stoppoint, stopxlogfilename);
11058  /* transfer remaining lines from label to history file */
11059  fprintf(fp, "%s", remaining);
11060  fprintf(fp, "STOP TIME: %s\n", strfbuf);
11061  if (fflush(fp) || ferror(fp) || FreeFile(fp))
11062  ereport(ERROR,
11064  errmsg("could not write file \"%s\": %m",
11065  histfilepath)));
11066 
11067  /*
11068  * Clean out any no-longer-needed history files. As a side effect,
11069  * this will post a .ready file for the newly created history file,
11070  * notifying the archiver that history file may be archived
11071  * immediately.
11072  */
11074  }
11075 
11076  /*
11077  * If archiving is enabled, wait for all the required WAL files to be
11078  * archived before returning. If archiving isn't enabled, the required WAL
11079  * needs to be transported via streaming replication (hopefully with
11080  * wal_keep_segments set high enough), or some more exotic mechanism like
11081  * polling and copying files from pg_wal with script. We have no knowledge
11082  * of those mechanisms, so it's up to the user to ensure that he gets all
11083  * the required WAL.
11084  *
11085  * We wait until both the last WAL file filled during backup and the
11086  * history file have been archived, and assume that the alphabetic sorting
11087  * property of the WAL files ensures any earlier WAL files are safely
11088  * archived as well.
11089  *
11090  * We wait forever, since archive_command is supposed to work and we
11091  * assume the admin wanted his backup to work completely. If you don't
11092  * wish to wait, then either waitforarchive should be passed in as false,
11093  * or you can set statement_timeout. Also, some notices are issued to
11094  * clue in anyone who might be doing this interactively.
11095  */
11096 
11097  if (waitforarchive &&
11098  ((!backup_started_in_recovery && XLogArchivingActive()) ||
11099  (backup_started_in_recovery && XLogArchivingAlways())))
11100  {
11101  XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
11102  XLogFileName(lastxlogfilename, stoptli, _logSegNo, wal_segment_size);
11103 
11104  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
11105  BackupHistoryFileName(histfilename, stoptli, _logSegNo,
11106  startpoint, wal_segment_size);
11107 
11108  seconds_before_warning = 60;
11109  waits = 0;
11110 
11111  while (XLogArchiveIsBusy(lastxlogfilename) ||
11112  XLogArchiveIsBusy(histfilename))
11113  {
11115 
11116  if (!reported_waiting && waits > 5)
11117  {
11118  ereport(NOTICE,
11119  (errmsg("pg_stop_backup cleanup done, waiting for required WAL segments to be archived")));
11120  reported_waiting = true;
11121  }
11122 
11123  pg_usleep(1000000L);
11124 
11125  if (++waits >= seconds_before_warning)
11126  {
11127  seconds_before_warning *= 2; /* This wraps in >10 years... */
11128  ereport(WARNING,
11129  (errmsg("pg_stop_backup still waiting for all required WAL segments to be archived (%d seconds elapsed)",
11130  waits),
11131  errhint("Check that your archive_command is executing properly. "
11132  "pg_stop_backup can be canceled safely, "
11133  "but the database backup will not be usable without all the WAL segments.")));
11134  }
11135  }
11136 
11137  ereport(NOTICE,
11138  (errmsg("pg_stop_backup complete, all required WAL segments have been archived")));
11139  }
11140  else if (waitforarchive)
11141  ereport(NOTICE,
11142  (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
11143 
11144  /*
11145  * We're done. As a convenience, return the ending WAL location.
11146  */
11147  if (stoptli_p)
11148  *stoptli_p = stoptli;
11149  return stoppoint;
11150 }
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:9498
#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:168
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:7962
static bool backup_started_in_recovery
Definition: basebackup.c:73
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:4119
#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:2094
unsigned int uint32
Definition: c.h:258
#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 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:664
#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:10741
#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:676
int FreeFile(FILE *file)
Definition: fd.c:2277
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:167
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
static int emode_for_corrupt_record ( int  emode,
XLogRecPtr  RecPtr 
)
static

Definition at line 12088 of file xlog.c.

References DEBUG1, LOG, readSource, and XLOG_FROM_PG_WAL.

Referenced by ReadRecord(), and XLogPageRead().

12089 {
12090  static XLogRecPtr lastComplaint = 0;
12091 
12092  if (readSource == XLOG_FROM_PG_WAL && emode == LOG)
12093  {
12094  if (RecPtr == lastComplaint)
12095  emode = DEBUG1;
12096  else
12097  lastComplaint = RecPtr;
12098  }
12099  return emode;
12100 }
#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
static void exitArchiveRecovery ( TimeLineID  endTLI,
XLogRecPtr  endOfLog 
)
static

Definition at line 5558 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, unlink(), UpdateMinRecoveryPoint(), wal_segment_size, XLByteToPrevSeg, XLByteToSeg, XLogArchiveCleanup(), XLOGDIR, XLogFileCopy(), XLogFileInit(), XLogFileName, XLogFileNameP(), and XLogSegmentOffset.

Referenced by StartupXLOG().

5559 {
5560  char recoveryPath[MAXPGPATH];
5561  char xlogfname[MAXFNAMELEN];
5562  XLogSegNo endLogSegNo;
5563  XLogSegNo startLogSegNo;
5564 
5565  /* we always switch to a new timeline after archive recovery */
5566  Assert(endTLI != ThisTimeLineID);
5567 
5568  /*
5569  * We are no longer in archive recovery state.
5570  */
5571  InArchiveRecovery = false;
5572 
5573  /*
5574  * Update min recovery point one last time.
5575  */
5577 
5578  /*
5579  * If the ending log segment is still open, close it (to avoid problems on
5580  * Windows with trying to rename or delete an open file).
5581  */
5582  if (readFile >= 0)
5583  {
5584  close(readFile);
5585  readFile = -1;
5586  }
5587 
5588  /*
5589  * Calculate the last segment on the old timeline, and the first segment
5590  * on the new timeline. If the switch happens in the middle of a segment,
5591  * they are the same, but if the switch happens exactly at a segment
5592  * boundary, startLogSegNo will be endLogSegNo + 1.
5593  */
5594  XLByteToPrevSeg(endOfLog, endLogSegNo, wal_segment_size);
5595  XLByteToSeg(endOfLog, startLogSegNo, wal_segment_size);
5596 
5597  /*
5598  * Initialize the starting WAL segment for the new timeline. If the switch
5599  * happens in the middle of a segment, copy data from the last WAL segment
5600  * of the old timeline up to the switch point, to the starting WAL segment
5601  * on the new timeline.
5602  */
5603  if (endLogSegNo == startLogSegNo)
5604  {
5605  /*
5606  * Make a copy of the file on the new timeline.
5607  *
5608  * Writing WAL isn't allowed yet, so there are no locking
5609  * considerations. But we should be just as tense as XLogFileInit to
5610  * avoid emplacing a bogus file.
5611  */
5612  XLogFileCopy(endLogSegNo, endTLI, endLogSegNo,
5613  XLogSegmentOffset(endOfLog, wal_segment_size));
5614  }
5615  else
5616  {
5617  /*
5618  * The switch happened at a segment boundary, so just create the next
5619  * segment on the new timeline.
5620  */
5621  bool use_existent = true;
5622  int fd;
5623 
5624  fd = XLogFileInit(startLogSegNo, &use_existent, true);
5625 
5626  if (close(fd))
5627  ereport(ERROR,
5629  errmsg("could not close log file %s: %m",
5630  XLogFileNameP(ThisTimeLineID, startLogSegNo))));
5631  }
5632 
5633  /*
5634  * Let's just make real sure there are not .ready or .done flags posted
5635  * for the new segment.
5636  */
5637  XLogFileName(xlogfname, ThisTimeLineID, startLogSegNo, wal_segment_size);
5638  XLogArchiveCleanup(xlogfname);
5639 
5640  /*
5641  * Since there might be a partial WAL segment named RECOVERYXLOG, get rid
5642  * of it.
5643  */
5644  snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYXLOG");
5645  unlink(recoveryPath); /* ignore any error */
5646 
5647  /* Get rid of any remaining recovered timeline-history file, too */
5648  snprintf(recoveryPath, MAXPGPATH, XLOGDIR "/RECOVERYHISTORY");
5649  unlink(recoveryPath); /* ignore any error */
5650 
5651  /*
5652  * Rename the config file out of the way, so that we don't accidentally
5653  * re-enter archive recovery mode in a subsequent crash.
5654  */
5657 
5658  ereport(LOG,
5659  (errmsg("archive recovery complete")));
5660 }
#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)
Definition: xlog.c:2698
int XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
Definition: xlog.c:3170
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define RECOVERY_COMMAND_FILE
Definition: xlog.c:82
static void XLogFileCopy(XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno, int upto)
Definition: xlog.c:3339
#define LOG
Definition: elog.h:26
#define RECOVERY_COMMAND_DONE
Definition: xlog.c:83
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void XLogArchiveCleanup(const char *xlog)