PostgreSQL Source Code  git master
xlog.h File Reference
#include "access/rmgr.h"
#include "access/xlogdefs.h"
#include "access/xloginsert.h"
#include "access/xlogreader.h"
#include "datatype/timestamp.h"
#include "lib/stringinfo.h"
#include "nodes/pg_list.h"
#include "storage/fd.h"
Include dependency graph for xlog.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  CheckpointStatsData
 

Macros

#define SYNC_METHOD_FSYNC   0
 
#define SYNC_METHOD_FDATASYNC   1
 
#define SYNC_METHOD_OPEN   2 /* for O_SYNC */
 
#define SYNC_METHOD_FSYNC_WRITETHROUGH   3
 
#define SYNC_METHOD_OPEN_DSYNC   4 /* for O_DSYNC */
 
#define XLogArchivingActive()   (AssertMacro(XLogArchiveMode == ARCHIVE_MODE_OFF || wal_level >= WAL_LEVEL_REPLICA), XLogArchiveMode > ARCHIVE_MODE_OFF)
 
#define XLogArchivingAlways()   (AssertMacro(XLogArchiveMode == ARCHIVE_MODE_OFF || wal_level >= WAL_LEVEL_REPLICA), XLogArchiveMode == ARCHIVE_MODE_ALWAYS)
 
#define XLogArchiveCommandSet()   (XLogArchiveCommand[0] != '\0')
 
#define XLogIsNeeded()   (wal_level >= WAL_LEVEL_REPLICA)
 
#define XLogHintBitIsNeeded()   (DataChecksumsEnabled() || wal_log_hints)
 
#define XLogStandbyInfoActive()   (wal_level >= WAL_LEVEL_REPLICA)
 
#define XLogLogicalInfoActive()   (wal_level >= WAL_LEVEL_LOGICAL)
 
#define CHECKPOINT_IS_SHUTDOWN   0x0001 /* Checkpoint is for shutdown */
 
#define CHECKPOINT_END_OF_RECOVERY
 
#define CHECKPOINT_IMMEDIATE   0x0004 /* Do it without delays */
 
#define CHECKPOINT_FORCE   0x0008 /* Force even if no activity */
 
#define CHECKPOINT_FLUSH_ALL
 
#define CHECKPOINT_WAIT   0x0020 /* Wait for completion */
 
#define CHECKPOINT_REQUESTED   0x0040 /* Checkpoint request has been made */
 
#define CHECKPOINT_CAUSE_XLOG   0x0080 /* XLOG consumption */
 
#define CHECKPOINT_CAUSE_TIME   0x0100 /* Elapsed time */
 
#define XLOG_INCLUDE_ORIGIN   0x01 /* include the replication origin */
 
#define XLOG_MARK_UNIMPORTANT   0x02 /* record not important for durability */
 
#define XLOG_INCLUDE_XID   0x04 /* WAL-internal message-passing hack */
 
#define RECOVERY_SIGNAL_FILE   "recovery.signal"
 
#define STANDBY_SIGNAL_FILE   "standby.signal"
 
#define BACKUP_LABEL_FILE   "backup_label"
 
#define BACKUP_LABEL_OLD   "backup_label.old"
 
#define TABLESPACE_MAP   "tablespace_map"
 
#define TABLESPACE_MAP_OLD   "tablespace_map.old"
 
#define PROMOTE_SIGNAL_FILE   "promote"
 

Typedefs

typedef enum ArchiveMode ArchiveMode
 
typedef enum WalLevel WalLevel
 
typedef enum WalCompression WalCompression
 
typedef enum RecoveryState RecoveryState
 
typedef enum RecoveryPauseState RecoveryPauseState
 
typedef struct CheckpointStatsData CheckpointStatsData
 
typedef enum WALAvailability WALAvailability
 
typedef enum SessionBackupState SessionBackupState
 

Enumerations

enum  RecoveryTargetType {
  RECOVERY_TARGET_UNSET, RECOVERY_TARGET_XID, RECOVERY_TARGET_TIME, RECOVERY_TARGET_NAME,
  RECOVERY_TARGET_LSN, RECOVERY_TARGET_IMMEDIATE
}
 
enum  RecoveryTargetTimeLineGoal { RECOVERY_TARGET_TIMELINE_CONTROLFILE, RECOVERY_TARGET_TIMELINE_LATEST, RECOVERY_TARGET_TIMELINE_NUMERIC }
 
enum  ArchiveMode { ARCHIVE_MODE_OFF = 0, ARCHIVE_MODE_ON, ARCHIVE_MODE_ALWAYS }
 
enum  WalLevel { WAL_LEVEL_MINIMAL = 0, WAL_LEVEL_REPLICA, WAL_LEVEL_LOGICAL }
 
enum  WalCompression { WAL_COMPRESSION_NONE = 0, WAL_COMPRESSION_PGLZ, WAL_COMPRESSION_LZ4 }
 
enum  RecoveryState { RECOVERY_STATE_CRASH = 0, RECOVERY_STATE_ARCHIVE, RECOVERY_STATE_DONE }
 
enum  RecoveryPauseState { RECOVERY_NOT_PAUSED, RECOVERY_PAUSE_REQUESTED, RECOVERY_PAUSED }
 
enum  WALAvailability {
  WALAVAIL_INVALID_LSN, WALAVAIL_RESERVED, WALAVAIL_EXTENDED, WALAVAIL_UNRESERVED,
  WALAVAIL_REMOVED
}
 
enum  SessionBackupState { SESSION_BACKUP_NONE, SESSION_BACKUP_EXCLUSIVE, SESSION_BACKUP_NON_EXCLUSIVE }
 

Functions

XLogRecPtr XLogInsertRecord (struct XLogRecData *rdata, XLogRecPtr fpw_lsn, uint8 flags, int num_fpi)
 
void XLogFlush (XLogRecPtr RecPtr)
 
bool XLogBackgroundFlush (void)
 
bool XLogNeedsFlush (XLogRecPtr RecPtr)
 
int XLogFileInit (XLogSegNo segno)
 
int XLogFileOpen (XLogSegNo segno)
 
void CheckXLogRemoved (XLogSegNo segno, TimeLineID tli)
 
XLogSegNo XLogGetLastRemovedSegno (void)
 
void XLogSetAsyncXactLSN (XLogRecPtr record)
 
void XLogSetReplicationSlotMinimumLSN (XLogRecPtr lsn)
 
void xlog_redo (XLogReaderState *record)
 
void xlog_desc (StringInfo buf, XLogReaderState *record)
 
const char * xlog_identify (uint8 info)
 
void issue_xlog_fsync (int fd, XLogSegNo segno)
 
bool RecoveryInProgress (void)
 
RecoveryState GetRecoveryState (void)
 
bool HotStandbyActive (void)
 
bool HotStandbyActiveInReplay (void)
 
bool XLogInsertAllowed (void)
 
void GetXLogReceiptTime (TimestampTz *rtime, bool *fromStream)
 
XLogRecPtr GetXLogReplayRecPtr (TimeLineID *replayTLI)
 
XLogRecPtr GetXLogInsertRecPtr (void)
 
XLogRecPtr GetXLogWriteRecPtr (void)
 
RecoveryPauseState GetRecoveryPauseState (void)
 
void SetRecoveryPause (bool recoveryPause)
 
TimestampTz GetLatestXTime (void)
 
TimestampTz GetCurrentChunkReplayStartTime (void)
 
void UpdateControlFile (void)
 
uint64 GetSystemIdentifier (void)
 
char * GetMockAuthenticationNonce (void)
 
bool DataChecksumsEnabled (void)
 
XLogRecPtr GetFakeLSNForUnloggedRel (void)
 
Size XLOGShmemSize (void)
 
void XLOGShmemInit (void)
 
void BootStrapXLOG (void)
 
void LocalProcessControlFile (bool reset)
 
void StartupXLOG (void)
 
void ShutdownXLOG (int code, Datum arg)
 
void InitXLOGAccess (void)
 
void CreateCheckPoint (int flags)
 
bool CreateRestartPoint (int flags)
 
WALAvailability GetWALAvailability (XLogRecPtr targetLSN)
 
XLogRecPtr CalculateMaxmumSafeLSN (void)
 
void XLogPutNextOid (Oid nextOid)
 
XLogRecPtr XLogRestorePoint (const char *rpName)
 
void UpdateFullPageWrites (void)
 
void GetFullPageWriteInfo (XLogRecPtr *RedoRecPtr_p, bool *doPageWrites_p)
 
XLogRecPtr GetRedoRecPtr (void)
 
XLogRecPtr GetInsertRecPtr (void)
 
XLogRecPtr GetFlushRecPtr (void)
 
XLogRecPtr GetLastImportantRecPtr (void)
 
void RemovePromoteSignalFiles (void)
 
bool PromoteIsTriggered (void)
 
bool CheckPromoteSignal (void)
 
void WakeupRecovery (void)
 
void SetWalWriterSleeping (bool sleeping)
 
void StartupRequestWalReceiverRestart (void)
 
void XLogRequestWalReceiverReply (void)
 
void assign_max_wal_size (int newval, void *extra)
 
void assign_checkpoint_completion_target (double newval, void *extra)
 
XLogRecPtr do_pg_start_backup (const char *backupidstr, bool fast, TimeLineID *starttli_p, StringInfo labelfile, List **tablespaces, StringInfo tblspcmapfile)
 
XLogRecPtr do_pg_stop_backup (char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
 
void do_pg_abort_backup (int code, Datum arg)
 
void register_persistent_abort_backup_handler (void)
 
SessionBackupState get_backup_status (void)
 

Variables

int sync_method
 
PGDLLIMPORT TimeLineID ThisTimeLineID
 
XLogRecPtr ProcLastRecPtr
 
XLogRecPtr XactLastRecEnd
 
PGDLLIMPORT XLogRecPtr XactLastCommitEnd
 
bool reachedConsistency
 
int wal_segment_size
 
int min_wal_size_mb
 
int max_wal_size_mb
 
int wal_keep_size_mb
 
int max_slot_wal_keep_size_mb
 
int XLOGbuffers
 
int XLogArchiveTimeout
 
int wal_retrieve_retry_interval
 
char * XLogArchiveCommand
 
bool EnableHotStandby
 
bool fullPageWrites
 
bool wal_log_hints
 
int wal_compression
 
bool wal_init_zero
 
bool wal_recycle
 
boolwal_consistency_checking
 
char * wal_consistency_checking_string
 
bool log_checkpoints
 
char * recoveryRestoreCommand
 
char * recoveryEndCommand
 
char * archiveCleanupCommand
 
bool recoveryTargetInclusive
 
int recoveryTargetAction
 
int recovery_min_apply_delay
 
char * PrimaryConnInfo
 
char * PrimarySlotName
 
bool wal_receiver_create_temp_slot
 
bool track_wal_io_timing
 
TransactionId recoveryTargetXid
 
char * recovery_target_time_string
 
const char * recoveryTargetName
 
XLogRecPtr recoveryTargetLSN
 
RecoveryTargetType recoveryTarget
 
char * PromoteTriggerFile
 
RecoveryTargetTimeLineGoal recoveryTargetTimeLineGoal
 
TimeLineID recoveryTargetTLIRequested
 
TimeLineID recoveryTargetTLI
 
int CheckPointSegments
 
bool StandbyModeRequested
 
bool StandbyMode
 
int XLogArchiveMode
 
PGDLLIMPORT int wal_level
 
CheckpointStatsData CheckpointStats
 

Macro Definition Documentation

◆ BACKUP_LABEL_FILE

#define BACKUP_LABEL_FILE   "backup_label"

◆ BACKUP_LABEL_OLD

#define BACKUP_LABEL_OLD   "backup_label.old"

Definition at line 364 of file xlog.h.

Referenced by CancelBackup(), and StartupXLOG().

◆ CHECKPOINT_CAUSE_TIME

#define CHECKPOINT_CAUSE_TIME   0x0100 /* Elapsed time */

Definition at line 208 of file xlog.h.

Referenced by CheckpointerMain(), and LogCheckpointStart().

◆ CHECKPOINT_CAUSE_XLOG

#define CHECKPOINT_CAUSE_XLOG   0x0080 /* XLOG consumption */

Definition at line 207 of file xlog.h.

Referenced by CheckpointerMain(), LogCheckpointStart(), XLogPageRead(), and XLogWrite().

◆ CHECKPOINT_END_OF_RECOVERY

#define CHECKPOINT_END_OF_RECOVERY
Value:
0x0002 /* Like shutdown checkpoint, but
* issued at end of WAL recovery */

Definition at line 197 of file xlog.h.

Referenced by BufferSync(), CheckpointerMain(), CreateCheckPoint(), LogCheckpointStart(), PerformRecoveryXLogAction(), and update_checkpoint_display().

◆ CHECKPOINT_FLUSH_ALL

#define CHECKPOINT_FLUSH_ALL
Value:
0x0010 /* Flush all pages, including those
* belonging to unlogged tables */

Definition at line 201 of file xlog.h.

Referenced by BufferSync(), createdb(), LogCheckpointStart(), and movedb().

◆ CHECKPOINT_FORCE

#define CHECKPOINT_FORCE   0x0008 /* Force even if no activity */

◆ CHECKPOINT_IMMEDIATE

◆ CHECKPOINT_IS_SHUTDOWN

#define CHECKPOINT_IS_SHUTDOWN   0x0001 /* Checkpoint is for shutdown */

◆ CHECKPOINT_REQUESTED

#define CHECKPOINT_REQUESTED   0x0040 /* Checkpoint request has been made */

Definition at line 205 of file xlog.h.

Referenced by RequestCheckpoint().

◆ CHECKPOINT_WAIT

#define CHECKPOINT_WAIT   0x0020 /* Wait for completion */

◆ PROMOTE_SIGNAL_FILE

#define PROMOTE_SIGNAL_FILE   "promote"

Definition at line 370 of file xlog.h.

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

◆ RECOVERY_SIGNAL_FILE

#define RECOVERY_SIGNAL_FILE   "recovery.signal"

Definition at line 361 of file xlog.h.

Referenced by exitArchiveRecovery(), and readRecoverySignalFile().

◆ STANDBY_SIGNAL_FILE

#define STANDBY_SIGNAL_FILE   "standby.signal"

Definition at line 362 of file xlog.h.

Referenced by exitArchiveRecovery(), and readRecoverySignalFile().

◆ SYNC_METHOD_FDATASYNC

#define SYNC_METHOD_FDATASYNC   1

Definition at line 26 of file xlog.h.

Referenced by get_sync_bit(), and issue_xlog_fsync().

◆ SYNC_METHOD_FSYNC

#define SYNC_METHOD_FSYNC   0

Definition at line 25 of file xlog.h.

Referenced by get_sync_bit(), and issue_xlog_fsync().

◆ SYNC_METHOD_FSYNC_WRITETHROUGH

#define SYNC_METHOD_FSYNC_WRITETHROUGH   3

Definition at line 28 of file xlog.h.

Referenced by get_sync_bit(), issue_xlog_fsync(), and pg_fsync().

◆ SYNC_METHOD_OPEN

#define SYNC_METHOD_OPEN   2 /* for O_SYNC */

Definition at line 27 of file xlog.h.

Referenced by get_sync_bit(), issue_xlog_fsync(), and XLogWrite().

◆ SYNC_METHOD_OPEN_DSYNC

#define SYNC_METHOD_OPEN_DSYNC   4 /* for O_DSYNC */

Definition at line 29 of file xlog.h.

Referenced by get_sync_bit(), issue_xlog_fsync(), and XLogWrite().

◆ TABLESPACE_MAP

#define TABLESPACE_MAP   "tablespace_map"

◆ TABLESPACE_MAP_OLD

#define TABLESPACE_MAP_OLD   "tablespace_map.old"

Definition at line 367 of file xlog.h.

Referenced by CancelBackup(), and StartupXLOG().

◆ XLOG_INCLUDE_ORIGIN

#define XLOG_INCLUDE_ORIGIN   0x01 /* include the replication origin */

◆ XLOG_INCLUDE_XID

#define XLOG_INCLUDE_XID   0x04 /* WAL-internal message-passing hack */

Definition at line 215 of file xlog.h.

Referenced by XLogRecordAssemble(), and XLogResetInsertion().

◆ XLOG_MARK_UNIMPORTANT

#define XLOG_MARK_UNIMPORTANT   0x02 /* record not important for durability */

◆ XLogArchiveCommandSet

#define XLogArchiveCommandSet ( )    (XLogArchiveCommand[0] != '\0')

Definition at line 160 of file xlog.h.

Referenced by pgarch_ArchiverCopyLoop(), and ShutdownXLOG().

◆ XLogArchivingActive

◆ XLogArchivingAlways

Definition at line 158 of file xlog.h.

Referenced by do_pg_stop_backup(), sigusr1_handler(), and XLogArchiveCheckDone().

◆ XLogHintBitIsNeeded

◆ XLogIsNeeded

◆ XLogLogicalInfoActive

◆ XLogStandbyInfoActive

Typedef Documentation

◆ ArchiveMode

typedef enum ArchiveMode ArchiveMode

◆ CheckpointStatsData

◆ RecoveryPauseState

◆ RecoveryState

◆ SessionBackupState

◆ WALAvailability

◆ WalCompression

◆ WalLevel

typedef enum WalLevel WalLevel

Enumeration Type Documentation

◆ ArchiveMode

Enumerator
ARCHIVE_MODE_OFF 
ARCHIVE_MODE_ON 
ARCHIVE_MODE_ALWAYS 

Definition at line 112 of file xlog.h.

113 {
114  ARCHIVE_MODE_OFF = 0, /* disabled */
115  ARCHIVE_MODE_ON, /* enabled while server is running normally */
116  ARCHIVE_MODE_ALWAYS /* enabled always (even during recovery) */
117 } ArchiveMode;
ArchiveMode
Definition: xlog.h:112

◆ RecoveryPauseState

Enumerator
RECOVERY_NOT_PAUSED 
RECOVERY_PAUSE_REQUESTED 
RECOVERY_PAUSED 

Definition at line 145 of file xlog.h.

146 {
147  RECOVERY_NOT_PAUSED, /* pause not requested */
148  RECOVERY_PAUSE_REQUESTED, /* pause requested, but not yet paused */
149  RECOVERY_PAUSED /* recovery is paused */
RecoveryPauseState
Definition: xlog.h:145

◆ RecoveryState

Enumerator
RECOVERY_STATE_CRASH 
RECOVERY_STATE_ARCHIVE 
RECOVERY_STATE_DONE 

Definition at line 137 of file xlog.h.

138 {
139  RECOVERY_STATE_CRASH = 0, /* crash recovery */
140  RECOVERY_STATE_ARCHIVE, /* archive recovery */
141  RECOVERY_STATE_DONE /* currently in production */
142 } RecoveryState;
RecoveryState
Definition: xlog.h:137

◆ RecoveryTargetTimeLineGoal

Enumerator
RECOVERY_TARGET_TIMELINE_CONTROLFILE 
RECOVERY_TARGET_TIMELINE_LATEST 
RECOVERY_TARGET_TIMELINE_NUMERIC 

Definition at line 51 of file xlog.h.

◆ RecoveryTargetType

Enumerator
RECOVERY_TARGET_UNSET 
RECOVERY_TARGET_XID 
RECOVERY_TARGET_TIME 
RECOVERY_TARGET_NAME 
RECOVERY_TARGET_LSN 
RECOVERY_TARGET_IMMEDIATE 

Definition at line 38 of file xlog.h.

◆ SessionBackupState

Enumerator
SESSION_BACKUP_NONE 
SESSION_BACKUP_EXCLUSIVE 
SESSION_BACKUP_NON_EXCLUSIVE 

Definition at line 344 of file xlog.h.

◆ WALAvailability

Enumerator
WALAVAIL_INVALID_LSN 
WALAVAIL_RESERVED 
WALAVAIL_EXTENDED 
WALAVAIL_UNRESERVED 
WALAVAIL_REMOVED 

Definition at line 246 of file xlog.h.

247 {
248  WALAVAIL_INVALID_LSN, /* parameter error */
249  WALAVAIL_RESERVED, /* WAL segment is within max_wal_size */
250  WALAVAIL_EXTENDED, /* WAL segment is reserved by a slot or
251  * wal_keep_size */
252  WALAVAIL_UNRESERVED, /* no longer reserved, but not removed yet */
253  WALAVAIL_REMOVED /* WAL segment has been removed */
WALAvailability
Definition: xlog.h:246

◆ WalCompression

Enumerator
WAL_COMPRESSION_NONE 
WAL_COMPRESSION_PGLZ 
WAL_COMPRESSION_LZ4 

Definition at line 129 of file xlog.h.

◆ WalLevel

enum WalLevel
Enumerator
WAL_LEVEL_MINIMAL 
WAL_LEVEL_REPLICA 
WAL_LEVEL_LOGICAL 

Definition at line 121 of file xlog.h.

Function Documentation

◆ assign_checkpoint_completion_target()

void assign_checkpoint_completion_target ( double  newval,
void *  extra 
)

Definition at line 2354 of file xlog.c.

References CalculateCheckpointSegments(), CheckPointCompletionTarget, and newval.

2355 {
2358 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2318
#define newval
double CheckPointCompletionTarget
Definition: checkpointer.c:145

◆ assign_max_wal_size()

void assign_max_wal_size ( int  newval,
void *  extra 
)

Definition at line 2347 of file xlog.c.

References CalculateCheckpointSegments(), max_wal_size_mb, and newval.

2348 {
2351 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2318
int max_wal_size_mb
Definition: xlog.c:91
#define newval

◆ BootStrapXLOG()

void BootStrapXLOG ( void  )

Definition at line 5283 of file xlog.c.

References AdvanceOldestClogXid(), Assert, BootStrapCLOG(), BootStrapCommitTs(), BootStrapMultiXact(), BootStrapSUBTRANS(), ControlFileData::checkPoint, ControlFileData::checkPointCopy, close, COMP_CRC32C, ereport, errcode_for_file_access(), errmsg(), FIN_CRC32C, FirstGenbkiObjectId, FirstMultiXactId, FirstNormalTransactionId, CheckPoint::fullPageWrites, fullPageWrites, FullTransactionIdFromEpochAndXid(), gettimeofday(), INIT_CRC32C, InitControlFile(), XLogCtlData::InstallXLogFileSegmentActive, InvalidTransactionId, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MultiXactSetNextMXact(), CheckPoint::newestCommitTsXid, CheckPoint::nextMulti, CheckPoint::nextMultiOffset, CheckPoint::nextOid, VariableCacheData::nextOid, CheckPoint::nextXid, VariableCacheData::nextXid, offsetof, VariableCacheData::oidCount, CheckPoint::oldestActiveXid, CheckPoint::oldestCommitTsXid, CheckPoint::oldestMulti, CheckPoint::oldestMultiDB, CheckPoint::oldestXid, CheckPoint::oldestXidDB, openLogFile, palloc(), PANIC, pfree(), pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), CheckPoint::PrevTimeLineID, ReadControlFile(), CheckPoint::redo, SetCommitTsLimit(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemVariableCache, SizeOfXLogLongPHD, SizeOfXLogRecord, SizeOfXLogRecordDataHeaderShort, CheckPoint::ThisTimeLineID, ThisTimeLineID, CheckPoint::time, ControlFileData::time, TYPEALIGN, WAIT_EVENT_WAL_BOOTSTRAP_SYNC, WAIT_EVENT_WAL_BOOTSTRAP_WRITE, wal_segment_size, write, WriteControlFile(), XLogRecord::xl_info, XLogRecord::xl_prev, XLogRecord::xl_rmid, XLogRecord::xl_tot_len, XLogRecord::xl_xid, XLOG_CHECKPOINT_SHUTDOWN, XLOG_PAGE_MAGIC, XLogFileInit(), XLogPageHeaderData::xlp_info, XLP_LONG_HEADER, XLogPageHeaderData::xlp_magic, XLogPageHeaderData::xlp_pageaddr, XLogLongPageHeaderData::xlp_seg_size, XLogLongPageHeaderData::xlp_sysid, XLogPageHeaderData::xlp_tli, XLogLongPageHeaderData::xlp_xlog_blcksz, and XLR_BLOCK_ID_DATA_SHORT.

Referenced by BootstrapModeMain().

5284 {
5285  CheckPoint checkPoint;
5286  char *buffer;
5287  XLogPageHeader page;
5288  XLogLongPageHeader longpage;
5289  XLogRecord *record;
5290  char *recptr;
5291  uint64 sysidentifier;
5292  struct timeval tv;
5293  pg_crc32c crc;
5294 
5295  /* allow ordinary WAL segment creation, like StartupXLOG() would */
5296  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
5298  LWLockRelease(ControlFileLock);
5299 
5300  /*
5301  * Select a hopefully-unique system identifier code for this installation.
5302  * We use the result of gettimeofday(), including the fractional seconds
5303  * field, as being about as unique as we can easily get. (Think not to
5304  * use random(), since it hasn't been seeded and there's no portable way
5305  * to seed it other than the system clock value...) The upper half of the
5306  * uint64 value is just the tv_sec part, while the lower half contains the
5307  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5308  * PID for a little extra uniqueness. A person knowing this encoding can
5309  * determine the initialization time of the installation, which could
5310  * perhaps be useful sometimes.
5311  */
5312  gettimeofday(&tv, NULL);
5313  sysidentifier = ((uint64) tv.tv_sec) << 32;
5314  sysidentifier |= ((uint64) tv.tv_usec) << 12;
5315  sysidentifier |= getpid() & 0xFFF;
5316 
5317  /* First timeline ID is always 1 */
5318  ThisTimeLineID = 1;
5319 
5320  /* page buffer must be aligned suitably for O_DIRECT */
5321  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5322  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5323  memset(page, 0, XLOG_BLCKSZ);
5324 
5325  /*
5326  * Set up information for the initial checkpoint record
5327  *
5328  * The initial checkpoint record is written to the beginning of the WAL
5329  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5330  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5331  */
5332  checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5333  checkPoint.ThisTimeLineID = ThisTimeLineID;
5334  checkPoint.PrevTimeLineID = ThisTimeLineID;
5335  checkPoint.fullPageWrites = fullPageWrites;
5336  checkPoint.nextXid =
5338  checkPoint.nextOid = FirstGenbkiObjectId;
5339  checkPoint.nextMulti = FirstMultiXactId;
5340  checkPoint.nextMultiOffset = 0;
5341  checkPoint.oldestXid = FirstNormalTransactionId;
5342  checkPoint.oldestXidDB = TemplateDbOid;
5343  checkPoint.oldestMulti = FirstMultiXactId;
5344  checkPoint.oldestMultiDB = TemplateDbOid;
5347  checkPoint.time = (pg_time_t) time(NULL);
5349 
5350  ShmemVariableCache->nextXid = checkPoint.nextXid;
5351  ShmemVariableCache->nextOid = checkPoint.nextOid;
5353  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5354  AdvanceOldestClogXid(checkPoint.oldestXid);
5355  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5356  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5358 
5359  /* Set up the XLOG page header */
5360  page->xlp_magic = XLOG_PAGE_MAGIC;
5361  page->xlp_info = XLP_LONG_HEADER;
5362  page->xlp_tli = ThisTimeLineID;
5364  longpage = (XLogLongPageHeader) page;
5365  longpage->xlp_sysid = sysidentifier;
5366  longpage->xlp_seg_size = wal_segment_size;
5367  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5368 
5369  /* Insert the initial checkpoint record */
5370  recptr = ((char *) page + SizeOfXLogLongPHD);
5371  record = (XLogRecord *) recptr;
5372  record->xl_prev = 0;
5373  record->xl_xid = InvalidTransactionId;
5374  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5376  record->xl_rmid = RM_XLOG_ID;
5377  recptr += SizeOfXLogRecord;
5378  /* fill the XLogRecordDataHeaderShort struct */
5379  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5380  *(recptr++) = sizeof(checkPoint);
5381  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5382  recptr += sizeof(checkPoint);
5383  Assert(recptr - (char *) record == record->xl_tot_len);
5384 
5385  INIT_CRC32C(crc);
5386  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5387  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5388  FIN_CRC32C(crc);
5389  record->xl_crc = crc;
5390 
5391  /* Create first XLOG segment file */
5393 
5394  /*
5395  * We needn't bother with Reserve/ReleaseExternalFD here, since we'll
5396  * close the file again in a moment.
5397  */
5398 
5399  /* Write the first page with the initial record */
5400  errno = 0;
5402  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5403  {
5404  /* if write didn't set errno, assume problem is no disk space */
5405  if (errno == 0)
5406  errno = ENOSPC;
5407  ereport(PANIC,
5409  errmsg("could not write bootstrap write-ahead log file: %m")));
5410  }
5412 
5414  if (pg_fsync(openLogFile) != 0)
5415  ereport(PANIC,
5417  errmsg("could not fsync bootstrap write-ahead log file: %m")));
5419 
5420  if (close(openLogFile) != 0)
5421  ereport(PANIC,
5423  errmsg("could not close bootstrap write-ahead log file: %m")));
5424 
5425  openLogFile = -1;
5426 
5427  /* Now create pg_control */
5428  InitControlFile(sysidentifier);
5429  ControlFile->time = checkPoint.time;
5430  ControlFile->checkPoint = checkPoint.redo;
5431  ControlFile->checkPointCopy = checkPoint;
5432 
5433  /* some additional ControlFile fields are set in WriteControlFile() */
5434  WriteControlFile();
5435 
5436  /* Bootstrap the commit log, too */
5437  BootStrapCLOG();
5441 
5442  pfree(buffer);
5443 
5444  /*
5445  * Force control file to be read - in contrast to normal processing we'd
5446  * otherwise never run the checks and GUC related initializations therein.
5447  */
5448  ReadControlFile();
5449 }
static void WriteControlFile(void)
Definition: xlog.c:4698
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:104
int64 pg_time_t
Definition: pgtime.h:23
static void pgstat_report_wait_end(void)
Definition: wait_event.h:274
int wal_segment_size
Definition: xlog.c:119
pg_time_t time
Definition: pg_control.h:130
void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact)
Definition: commit_ts.c:877
uint32 oidCount
Definition: transam.h:215
#define write(a, b, c)
Definition: win32.h:14
#define SizeOfXLogRecordDataHeaderShort
Definition: xlogrecord.h:204
uint32 pg_crc32c
Definition: pg_crc32c.h:38
TransactionId oldestActiveXid
Definition: pg_control.h:63
void BootStrapMultiXact(void)
Definition: multixact.c:1894
MultiXactId oldestMulti
Definition: pg_control.h:49
TimeLineID PrevTimeLineID
Definition: pg_control.h:40
static void InitControlFile(uint64 sysidentifier)
Definition: xlog.c:4663
int XLogFileInit(XLogSegNo logsegno)
Definition: xlog.c:3472
RmgrId xl_rmid
Definition: xlogrecord.h:47
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:54
CheckPoint checkPointCopy
Definition: pg_control.h:133
TransactionId oldestXid
Definition: pg_control.h:47
FullTransactionId nextXid
Definition: transam.h:220
pg_time_t time
Definition: pg_control.h:51
#define PANIC
Definition: elog.h:50
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:71
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
bool fullPageWrites
Definition: xlog.c:99
void BootStrapSUBTRANS(void)
Definition: subtrans.c:211
MultiXactOffset nextMultiOffset
Definition: pg_control.h:46
void AdvanceOldestClogXid(TransactionId oldest_datfrozenxid)
Definition: varsup.c:328
TransactionId oldestCommitTsXid
Definition: pg_control.h:52
void pfree(void *pointer)
Definition: mcxt.c:1169
#define FirstNormalTransactionId
Definition: transam.h:34
uint32 xl_tot_len
Definition: xlogrecord.h:43
#define XLOG_PAGE_MAGIC
Definition: xlog_internal.h:34
static void ReadControlFile(void)
Definition: xlog.c:4789
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
int errcode_for_file_access(void)
Definition: elog.c:721
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
#define FirstMultiXactId
Definition: multixact.h:25
bool InstallXLogFileSegmentActive
Definition: xlog.c:663
TimeLineID xlp_tli
Definition: xlog_internal.h:40
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:258
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
TransactionId newestCommitTsXid
Definition: pg_control.h:54
Oid oldestMultiDB
Definition: pg_control.h:50
static int openLogFile
Definition: xlog.c:807
static ControlFileData * ControlFile
Definition: xlog.c:746
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2213
TimeLineID ThisTimeLineID
Definition: xlog.c:194
Oid nextOid
Definition: pg_control.h:44
#define ereport(elevel,...)
Definition: elog.h:157
#define TYPEALIGN(ALIGNVAL, LEN)
Definition: c.h:750
bool fullPageWrites
Definition: pg_control.h:42
void BootStrapCLOG(void)
Definition: clog.c:712
#define Assert(condition)
Definition: c.h:804
#define XLP_LONG_HEADER
Definition: xlog_internal.h:76
Oid oldestXidDB
Definition: pg_control.h:48
void SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
Definition: varsup.c:345
uint8 xl_info
Definition: xlogrecord.h:46
MultiXactId nextMulti
Definition: pg_control.h:45
static XLogCtlData * XLogCtl
Definition: xlog.c:738
static FullTransactionId FullTransactionIdFromEpochAndXid(uint32 epoch, TransactionId xid)
Definition: transam.h:71
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:228
TransactionId xl_xid
Definition: xlogrecord.h:44
#define FirstGenbkiObjectId
Definition: transam.h:195
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
int pg_fsync(int fd)
Definition: fd.c:357
#define close(a)
Definition: win32.h:12
void BootStrapCommitTs(void)
Definition: commit_ts.c:570
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
XLogRecPtr checkPoint
Definition: pg_control.h:131
XLogRecPtr redo
Definition: pg_control.h:37
#define offsetof(type, field)
Definition: c.h:727
FullTransactionId nextXid
Definition: pg_control.h:43
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:69
void MultiXactSetNextMXact(MultiXactId nextMulti, MultiXactOffset nextMultiOffset)
Definition: multixact.c:2179

◆ CalculateMaxmumSafeLSN()

XLogRecPtr CalculateMaxmumSafeLSN ( void  )

◆ CheckPromoteSignal()

bool CheckPromoteSignal ( void  )

Definition at line 13153 of file xlog.c.

References PROMOTE_SIGNAL_FILE, and stat.

Referenced by CheckForStandbyTrigger(), and sigusr1_handler().

13154 {
13155  struct stat stat_buf;
13156 
13157  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
13158  return true;
13159 
13160  return false;
13161 }
#define PROMOTE_SIGNAL_FILE
Definition: xlog.h:370
#define stat
Definition: win32_port.h:283

◆ CheckXLogRemoved()

void CheckXLogRemoved ( XLogSegNo  segno,
TimeLineID  tli 
)

Definition at line 3999 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 logical_read_xlog_page(), perform_base_backup(), and XLogSendPhysical().

4000 {
4001  int save_errno = errno;
4002  XLogSegNo lastRemovedSegNo;
4003 
4005  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
4007 
4008  if (segno <= lastRemovedSegNo)
4009  {
4010  char filename[MAXFNAMELEN];
4011 
4012  XLogFileName(filename, tli, segno, wal_segment_size);
4013  errno = save_errno;
4014  ereport(ERROR,
4016  errmsg("requested WAL segment %s has already been removed",
4017  filename)));
4018  }
4019  errno = save_errno;
4020 }
int wal_segment_size
Definition: xlog.c:119
slock_t info_lck
Definition: xlog.c:735
XLogSegNo lastRemovedSegNo
Definition: xlog.c:597
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define ERROR
Definition: elog.h:46
uint64 XLogSegNo
Definition: xlogdefs.h:48
int errcode_for_file_access(void)
Definition: elog.c:721
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
#define ereport(elevel,...)
Definition: elog.h:157
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static XLogCtlData * XLogCtl
Definition: xlog.c:738
static char * filename
Definition: pg_dumpall.c:92
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ CreateCheckPoint()

void CreateCheckPoint ( int  flags)

Definition at line 9010 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::ckptFullXid, XLogCtlInsert::CurrBytePos, DB_SHUTDOWNED, DB_SHUTDOWNING, DEBUG1, elog, END_CRIT_SECTION, ereport, errmsg(), errmsg_internal(), ERROR, CheckPoint::fullPageWrites, XLogCtlInsert::fullPageWrites, GetCurrentTimestamp(), GetLastImportantRecPtr(), GetOldestActiveTransactionId(), GetOldestTransactionIdConsideredRunning(), GetVirtualXIDsDelayingChkpt(), HaveVirtualXIDsDelayingChkpt(), XLogCtlData::info_lck, InitXLogInsert(), Insert(), XLogCtlData::Insert, INSERT_FREESPACE, InvalidateObsoleteReplicationSlots(), 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, VariableCacheData::oidCount, CheckPoint::oldestActiveXid, CheckPoint::oldestCommitTsXid, VariableCacheData::oldestCommitTsXid, CheckPoint::oldestMulti, CheckPoint::oldestMultiDB, CheckPoint::oldestXid, VariableCacheData::oldestXid, CheckPoint::oldestXidDB, VariableCacheData::oldestXidDB, PANIC, pfree(), pg_usleep(), PreallocXlogFiles(), CheckPoint::PrevTimeLineID, XLogCtlData::PrevTimeLineID, ProcLastRecPtr, RecoveryInProgress(), CheckPoint::redo, RedoRecPtr, XLogCtlInsert::RedoRecPtr, XLogCtlData::RedoRecPtr, RemoveOldXlogFiles(), ShmemVariableCache, SizeOfXLogLongPHD, SizeOfXLogShortPHD, SpinLockAcquire, SpinLockRelease, START_CRIT_SECTION, ControlFileData::state, SyncPostCheckpoint(), SyncPreCheckpoint(), CheckPoint::ThisTimeLineID, ThisTimeLineID, CheckPoint::time, ControlFileData::time, TruncateSUBTRANS(), XLogCtlData::ulsn_lck, ControlFileData::unloggedLSN, XLogCtlData::unloggedLSN, update_checkpoint_display(), 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(), and ShutdownXLOG().

9011 {
9012  bool shutdown;
9013  CheckPoint checkPoint;
9014  XLogRecPtr recptr;
9015  XLogSegNo _logSegNo;
9017  uint32 freespace;
9018  XLogRecPtr PriorRedoPtr;
9019  XLogRecPtr curInsert;
9020  XLogRecPtr last_important_lsn;
9021  VirtualTransactionId *vxids;
9022  int nvxids;
9023 
9024  /*
9025  * An end-of-recovery checkpoint is really a shutdown checkpoint, just
9026  * issued at a different time.
9027  */
9029  shutdown = true;
9030  else
9031  shutdown = false;
9032 
9033  /* sanity check */
9034  if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
9035  elog(ERROR, "can't create a checkpoint during recovery");
9036 
9037  /*
9038  * Initialize InitXLogInsert working areas before entering the critical
9039  * section. Normally, this is done by the first call to
9040  * RecoveryInProgress() or LocalSetXLogInsertAllowed(), but when creating
9041  * an end-of-recovery checkpoint, the LocalSetXLogInsertAllowed call is
9042  * done below in a critical section, and InitXLogInsert cannot be called
9043  * in a critical section.
9044  */
9045  InitXLogInsert();
9046 
9047  /*
9048  * Prepare to accumulate statistics.
9049  *
9050  * Note: because it is possible for log_checkpoints to change while a
9051  * checkpoint proceeds, we always accumulate stats, even if
9052  * log_checkpoints is currently off.
9053  */
9054  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
9056 
9057  /*
9058  * Use a critical section to force system panic if we have trouble.
9059  */
9061 
9062  if (shutdown)
9063  {
9064  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9066  ControlFile->time = (pg_time_t) time(NULL);
9068  LWLockRelease(ControlFileLock);
9069  }
9070 
9071  /*
9072  * Let smgr prepare for checkpoint; this has to happen before we determine
9073  * the REDO pointer. Note that smgr must not do anything that'd have to
9074  * be undone if we decide no checkpoint is needed.
9075  */
9077 
9078  /* Begin filling in the checkpoint WAL record */
9079  MemSet(&checkPoint, 0, sizeof(checkPoint));
9080  checkPoint.time = (pg_time_t) time(NULL);
9081 
9082  /*
9083  * For Hot Standby, derive the oldestActiveXid before we fix the redo
9084  * pointer. This allows us to begin accumulating changes to assemble our
9085  * starting snapshot of locks and transactions.
9086  */
9087  if (!shutdown && XLogStandbyInfoActive())
9089  else
9091 
9092  /*
9093  * Get location of last important record before acquiring insert locks (as
9094  * GetLastImportantRecPtr() also locks WAL locks).
9095  */
9096  last_important_lsn = GetLastImportantRecPtr();
9097 
9098  /*
9099  * We must block concurrent insertions while examining insert state to
9100  * determine the checkpoint REDO pointer.
9101  */
9103  curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
9104 
9105  /*
9106  * If this isn't a shutdown or forced checkpoint, and if there has been no
9107  * WAL activity requiring a checkpoint, skip it. The idea here is to
9108  * avoid inserting duplicate checkpoints when the system is idle.
9109  */
9110  if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
9111  CHECKPOINT_FORCE)) == 0)
9112  {
9113  if (last_important_lsn == ControlFile->checkPoint)
9114  {
9116  END_CRIT_SECTION();
9117  ereport(DEBUG1,
9118  (errmsg_internal("checkpoint skipped because system is idle")));
9119  return;
9120  }
9121  }
9122 
9123  /*
9124  * An end-of-recovery checkpoint is created before anyone is allowed to
9125  * write WAL. To allow us to write the checkpoint record, temporarily
9126  * enable XLogInsertAllowed. (This also ensures ThisTimeLineID is
9127  * initialized, which we need here and in AdvanceXLInsertBuffer.)
9128  */
9129  if (flags & CHECKPOINT_END_OF_RECOVERY)
9131 
9132  checkPoint.ThisTimeLineID = ThisTimeLineID;
9133  if (flags & CHECKPOINT_END_OF_RECOVERY)
9134  checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
9135  else
9136  checkPoint.PrevTimeLineID = ThisTimeLineID;
9137 
9138  checkPoint.fullPageWrites = Insert->fullPageWrites;
9139 
9140  /*
9141  * Compute new REDO record ptr = location of next XLOG record.
9142  *
9143  * NB: this is NOT necessarily where the checkpoint record itself will be,
9144  * since other backends may insert more XLOG records while we're off doing
9145  * the buffer flush work. Those XLOG records are logically after the
9146  * checkpoint, even though physically before it. Got that?
9147  */
9148  freespace = INSERT_FREESPACE(curInsert);
9149  if (freespace == 0)
9150  {
9151  if (XLogSegmentOffset(curInsert, wal_segment_size) == 0)
9152  curInsert += SizeOfXLogLongPHD;
9153  else
9154  curInsert += SizeOfXLogShortPHD;
9155  }
9156  checkPoint.redo = curInsert;
9157 
9158  /*
9159  * Here we update the shared RedoRecPtr for future XLogInsert calls; this
9160  * must be done while holding all the insertion locks.
9161  *
9162  * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
9163  * pointing past where it really needs to point. This is okay; the only
9164  * consequence is that XLogInsert might back up whole buffers that it
9165  * didn't really need to. We can't postpone advancing RedoRecPtr because
9166  * XLogInserts that happen while we are dumping buffers must assume that
9167  * their buffer changes are not included in the checkpoint.
9168  */
9169  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
9170 
9171  /*
9172  * Now we can release the WAL insertion locks, allowing other xacts to
9173  * proceed while we are flushing disk buffers.
9174  */
9176 
9177  /* Update the info_lck-protected copy of RedoRecPtr as well */
9179  XLogCtl->RedoRecPtr = checkPoint.redo;
9181 
9182  /*
9183  * If enabled, log checkpoint start. We postpone this until now so as not
9184  * to log anything if we decided to skip the checkpoint.
9185  */
9186  if (log_checkpoints)
9187  LogCheckpointStart(flags, false);
9188 
9189  /* Update the process title */
9190  update_checkpoint_display(flags, false, false);
9191 
9192  TRACE_POSTGRESQL_CHECKPOINT_START(flags);
9193 
9194  /*
9195  * Get the other info we need for the checkpoint record.
9196  *
9197  * We don't need to save oldestClogXid in the checkpoint, it only matters
9198  * for the short period in which clog is being truncated, and if we crash
9199  * during that we'll redo the clog truncation and fix up oldestClogXid
9200  * there.
9201  */
9202  LWLockAcquire(XidGenLock, LW_SHARED);
9203  checkPoint.nextXid = ShmemVariableCache->nextXid;
9204  checkPoint.oldestXid = ShmemVariableCache->oldestXid;
9206  LWLockRelease(XidGenLock);
9207 
9208  LWLockAcquire(CommitTsLock, LW_SHARED);
9211  LWLockRelease(CommitTsLock);
9212 
9213  LWLockAcquire(OidGenLock, LW_SHARED);
9214  checkPoint.nextOid = ShmemVariableCache->nextOid;
9215  if (!shutdown)
9216  checkPoint.nextOid += ShmemVariableCache->oidCount;
9217  LWLockRelease(OidGenLock);
9218 
9219  MultiXactGetCheckptMulti(shutdown,
9220  &checkPoint.nextMulti,
9221  &checkPoint.nextMultiOffset,
9222  &checkPoint.oldestMulti,
9223  &checkPoint.oldestMultiDB);
9224 
9225  /*
9226  * Having constructed the checkpoint record, ensure all shmem disk buffers
9227  * and commit-log buffers are flushed to disk.
9228  *
9229  * This I/O could fail for various reasons. If so, we will fail to
9230  * complete the checkpoint, but there is no reason to force a system
9231  * panic. Accordingly, exit critical section while doing it.
9232  */
9233  END_CRIT_SECTION();
9234 
9235  /*
9236  * In some cases there are groups of actions that must all occur on one
9237  * side or the other of a checkpoint record. Before flushing the
9238  * checkpoint record we must explicitly wait for any backend currently
9239  * performing those groups of actions.
9240  *
9241  * One example is end of transaction, so we must wait for any transactions
9242  * that are currently in commit critical sections. If an xact inserted
9243  * its commit record into XLOG just before the REDO point, then a crash
9244  * restart from the REDO point would not replay that record, which means
9245  * that our flushing had better include the xact's update of pg_xact. So
9246  * we wait till he's out of his commit critical section before proceeding.
9247  * See notes in RecordTransactionCommit().
9248  *
9249  * Because we've already released the insertion locks, this test is a bit
9250  * fuzzy: it is possible that we will wait for xacts we didn't really need
9251  * to wait for. But the delay should be short and it seems better to make
9252  * checkpoint take a bit longer than to hold off insertions longer than
9253  * necessary. (In fact, the whole reason we have this issue is that xact.c
9254  * does commit record XLOG insertion and clog update as two separate steps
9255  * protected by different locks, but again that seems best on grounds of
9256  * minimizing lock contention.)
9257  *
9258  * A transaction that has not yet set delayChkpt when we look cannot be at
9259  * risk, since he's not inserted his commit record yet; and one that's
9260  * already cleared it is not at risk either, since he's done fixing clog
9261  * and we will correctly flush the update below. So we cannot miss any
9262  * xacts we need to wait for.
9263  */
9264  vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
9265  if (nvxids > 0)
9266  {
9267  do
9268  {
9269  pg_usleep(10000L); /* wait for 10 msec */
9270  } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
9271  }
9272  pfree(vxids);
9273 
9274  CheckPointGuts(checkPoint.redo, flags);
9275 
9276  /*
9277  * Take a snapshot of running transactions and write this to WAL. This
9278  * allows us to reconstruct the state of running transactions during
9279  * archive recovery, if required. Skip, if this info disabled.
9280  *
9281  * If we are shutting down, or Startup process is completing crash
9282  * recovery we don't need to write running xact data.
9283  */
9284  if (!shutdown && XLogStandbyInfoActive())
9286 
9288 
9289  /*
9290  * Now insert the checkpoint record into XLOG.
9291  */
9292  XLogBeginInsert();
9293  XLogRegisterData((char *) (&checkPoint), sizeof(checkPoint));
9294  recptr = XLogInsert(RM_XLOG_ID,
9295  shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
9297 
9298  XLogFlush(recptr);
9299 
9300  /*
9301  * We mustn't write any new WAL after a shutdown checkpoint, or it will be
9302  * overwritten at next startup. No-one should even try, this just allows
9303  * sanity-checking. In the case of an end-of-recovery checkpoint, we want
9304  * to just temporarily disable writing until the system has exited
9305  * recovery.
9306  */
9307  if (shutdown)
9308  {
9309  if (flags & CHECKPOINT_END_OF_RECOVERY)
9310  LocalXLogInsertAllowed = -1; /* return to "check" state */
9311  else
9312  LocalXLogInsertAllowed = 0; /* never again write WAL */
9313  }
9314 
9315  /*
9316  * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
9317  * = end of actual checkpoint record.
9318  */
9319  if (shutdown && checkPoint.redo != ProcLastRecPtr)
9320  ereport(PANIC,
9321  (errmsg("concurrent write-ahead log activity while database system is shutting down")));
9322 
9323  /*
9324  * Remember the prior checkpoint's redo ptr for
9325  * UpdateCheckPointDistanceEstimate()
9326  */
9327  PriorRedoPtr = ControlFile->checkPointCopy.redo;
9328 
9329  /*
9330  * Update the control file.
9331  */
9332  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9333  if (shutdown)
9336  ControlFile->checkPointCopy = checkPoint;
9337  ControlFile->time = (pg_time_t) time(NULL);
9338  /* crash recovery should always recover to the end of WAL */
9341 
9342  /*
9343  * Persist unloggedLSN value. It's reset on crash recovery, so this goes
9344  * unused on non-shutdown checkpoints, but seems useful to store it always
9345  * for debugging purposes.
9346  */
9350 
9352  LWLockRelease(ControlFileLock);
9353 
9354  /* Update shared-memory copy of checkpoint XID/epoch */
9356  XLogCtl->ckptFullXid = checkPoint.nextXid;
9358 
9359  /*
9360  * We are now done with critical updates; no need for system panic if we
9361  * have trouble while fooling with old log segments.
9362  */
9363  END_CRIT_SECTION();
9364 
9365  /*
9366  * Let smgr do post-checkpoint cleanup (eg, deleting old files).
9367  */
9369 
9370  /*
9371  * Update the average distance between checkpoints if the prior checkpoint
9372  * exists.
9373  */
9374  if (PriorRedoPtr != InvalidXLogRecPtr)
9376 
9377  /*
9378  * Delete old log files, those no longer needed for last checkpoint to
9379  * prevent the disk holding the xlog from growing full.
9380  */
9382  KeepLogSeg(recptr, &_logSegNo);
9383  if (InvalidateObsoleteReplicationSlots(_logSegNo))
9384  {
9385  /*
9386  * Some slots have been invalidated; recalculate the old-segment
9387  * horizon, starting again from RedoRecPtr.
9388  */
9390  KeepLogSeg(recptr, &_logSegNo);
9391  }
9392  _logSegNo--;
9393  RemoveOldXlogFiles(_logSegNo, RedoRecPtr, recptr);
9394 
9395  /*
9396  * Make more log segments if needed. (Do this after recycling old log
9397  * segments, since that may supply some of the needed files.)
9398  */
9399  if (!shutdown)
9400  PreallocXlogFiles(recptr);
9401 
9402  /*
9403  * Truncate pg_subtrans if possible. We can throw away all data before
9404  * the oldest XMIN of any running transaction. No future transaction will
9405  * attempt to reference any pg_subtrans entry older than that (see Asserts
9406  * in subtrans.c). During recovery, though, we mustn't do this because
9407  * StartupSUBTRANS hasn't been called yet.
9408  */
9409  if (!RecoveryInProgress())
9411 
9412  /* Real work is done; log and update stats. */
9413  LogCheckpointEnd(false);
9414 
9415  /* Reset the process title */
9416  update_checkpoint_display(flags, false, true);
9417 
9418  TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
9419  NBuffers,
9423 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8698
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8915
static int LocalXLogInsertAllowed
Definition: xlog.c:248
bool log_checkpoints
Definition: xlog.c:106
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
int wal_segment_size
Definition: xlog.c:119
pg_time_t time
Definition: pg_control.h:130
#define XLOG_CHECKPOINT_ONLINE
Definition: pg_control.h:68
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:169
uint32 oidCount
Definition: transam.h:215
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:2009
XLogRecPtr unloggedLSN
Definition: xlog.c:600
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:352
TransactionId oldestActiveXid
Definition: pg_control.h:63
void InitXLogInsert(void)
Definition: xloginsert.c:1251
TimestampTz ckpt_start_t
Definition: xlog.h:221
slock_t info_lck
Definition: xlog.c:735
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids)
Definition: procarray.c:3043
MultiXactId oldestMulti
Definition: pg_control.h:49
TimeLineID PrevTimeLineID
Definition: xlog.c:641
TimeLineID PrevTimeLineID
Definition: pg_control.h:40
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
int ckpt_segs_recycled
Definition: xlog.h:231
TransactionId oldestXid
Definition: transam.h:222
#define MemSet(start, val, len)
Definition: c.h:1008
void MultiXactGetCheckptMulti(bool is_shutdown, MultiXactId *nextMulti, MultiXactOffset *nextMultiOffset, MultiXactId *oldestMulti, Oid *oldestMultiDB)
Definition: multixact.c:2133
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:9530
CheckPoint checkPointCopy
Definition: pg_control.h:133
XLogCtlInsert Insert
Definition: xlog.c:588
TransactionId oldestXid
Definition: pg_control.h:47
bool RecoveryInProgress(void)
Definition: xlog.c:8328
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:338
FullTransactionId nextXid
Definition: transam.h:220
pg_time_t time
Definition: pg_control.h:51
#define PANIC
Definition: elog.h:50
bool fullPageWrites
Definition: xlog.c:563
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2887
static void update_checkpoint_display(int flags, bool restartpoint, bool reset)
Definition: xlog.c:8953
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#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:4989
TransactionId oldestCommitTsXid
Definition: pg_control.h:52
void pfree(void *pointer)
Definition: mcxt.c:1169
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1220
#define ERROR
Definition: elog.h:46
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8823
bool InvalidateObsoleteReplicationSlots(XLogSegNo oldestSegno)
Definition: slot.c:1317
static XLogRecPtr RedoRecPtr
Definition: xlog.c:366
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
XLogRecPtr unloggedLSN
Definition: pg_control.h:135
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3962
uint64 XLogSegNo
Definition: xlogdefs.h:48
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:197
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
uint64 CurrBytePos
Definition: xlog.c:538
unsigned int uint32
Definition: c.h:441
XLogRecPtr RedoRecPtr
Definition: xlog.c:592
int ckpt_segs_removed
Definition: xlog.h:230
#define CHECKPOINT_FORCE
Definition: xlog.h:200
#define INSERT_FREESPACE(endptr)
Definition: xlog.c:752
TransactionId oldestCommitTsXid
Definition: transam.h:232
static void Insert(File file)
Definition: fd.c:1302
int ckpt_bufs_written
Definition: xlog.h:227
static void LocalSetXLogInsertAllowed(void)
Definition: xlog.c:8472
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:340
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:434
TransactionId newestCommitTsXid
Definition: pg_control.h:54
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9963
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
Oid oldestMultiDB
Definition: pg_control.h:50
FullTransactionId ckptFullXid
Definition: xlog.c:593
#define XLogStandbyInfoActive()
Definition: xlog.h:180
static ControlFileData * ControlFile
Definition: xlog.c:746
TimeLineID ThisTimeLineID
Definition: xlog.c:194
Oid nextOid
Definition: pg_control.h:44
#define ereport(elevel,...)
Definition: elog.h:157
bool fullPageWrites
Definition: pg_control.h:42
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
uint64 XLogRecPtr
Definition: xlogdefs.h:21
Oid oldestXidDB
Definition: pg_control.h:48
TransactionId newestCommitTsXid
Definition: transam.h:233
CheckpointStatsData CheckpointStats
Definition: xlog.c:188
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:52
MultiXactId nextMulti
Definition: pg_control.h:45
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:738
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
TransactionId GetOldestTransactionIdConsideredRunning(void)
Definition: procarray.c:2034
int ckpt_segs_added
Definition: xlog.h:229
slock_t ulsn_lck
Definition: xlog.c:601
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr)
Definition: xlog.c:4097
void SyncPostCheckpoint(void)
Definition: sync.c:195
TransactionId GetOldestActiveTransactionId(void)
Definition: procarray.c:2882
int NBuffers
Definition: globals.c:135
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids)
Definition: procarray.c:3087
void XLogBeginInsert(void)
Definition: xloginsert.c:135
XLogRecPtr RedoRecPtr
Definition: xlog.c:561
XLogRecPtr checkPoint
Definition: pg_control.h:131
XLogRecPtr redo
Definition: pg_control.h:37
static void LogCheckpointStart(int flags, bool restartpoint)
Definition: xlog.c:8791
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:196
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:168
void SyncPreCheckpoint(void)
Definition: sync.c:180
FullTransactionId nextXid
Definition: pg_control.h:43
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:69
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ CreateRestartPoint()

bool CreateRestartPoint ( int  flags)

Definition at line 9611 of file xlog.c.

References 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(), errmsg_internal(), ExecuteRecoveryCommand(), GetCurrentTimestamp(), GetLatestXTime(), GetOldestTransactionIdConsideredRunning(), GetWalRcvFlushRecPtr(), GetXLogReplayRecPtr(), XLogCtlData::info_lck, XLogCtlData::Insert, InvalidateObsoleteReplicationSlots(), InvalidXLogRecPtr, KeepLogSeg(), XLogCtlData::lastCheckPoint, XLogCtlData::lastCheckPointEndPtr, XLogCtlData::lastCheckPointRecPtr, LOG, log_checkpoints, LogCheckpointEnd(), LogCheckpointStart(), LSN_FORMAT_ARGS, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MemSet, ControlFileData::minRecoveryPoint, minRecoveryPoint, ControlFileData::minRecoveryPointTLI, minRecoveryPointTLI, PreallocXlogFiles(), RecoveryInProgress(), CheckPoint::redo, RedoRecPtr, XLogCtlInsert::RedoRecPtr, XLogCtlData::RedoRecPtr, RemoveOldXlogFiles(), SpinLockAcquire, SpinLockRelease, ControlFileData::state, CheckPoint::ThisTimeLineID, ThisTimeLineID, ControlFileData::time, timestamptz_to_str(), TruncateSUBTRANS(), update_checkpoint_display(), UpdateCheckPointDistanceEstimate(), UpdateControlFile(), UpdateMinRecoveryPoint(), wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), XLByteToSeg, and XLogRecPtrIsInvalid.

Referenced by CheckpointerMain(), and ShutdownXLOG().

9612 {
9613  XLogRecPtr lastCheckPointRecPtr;
9614  XLogRecPtr lastCheckPointEndPtr;
9615  CheckPoint lastCheckPoint;
9616  XLogRecPtr PriorRedoPtr;
9617  XLogRecPtr receivePtr;
9618  XLogRecPtr replayPtr;
9619  TimeLineID replayTLI;
9620  XLogRecPtr endptr;
9621  XLogSegNo _logSegNo;
9622  TimestampTz xtime;
9623 
9624  /* Get a local copy of the last safe checkpoint record. */
9626  lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
9627  lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
9628  lastCheckPoint = XLogCtl->lastCheckPoint;
9630 
9631  /*
9632  * Check that we're still in recovery mode. It's ok if we exit recovery
9633  * mode after this check, the restart point is valid anyway.
9634  */
9635  if (!RecoveryInProgress())
9636  {
9637  ereport(DEBUG2,
9638  (errmsg_internal("skipping restartpoint, recovery has already ended")));
9639  return false;
9640  }
9641 
9642  /*
9643  * If the last checkpoint record we've replayed is already our last
9644  * restartpoint, we can't perform a new restart point. We still update
9645  * minRecoveryPoint in that case, so that if this is a shutdown restart
9646  * point, we won't start up earlier than before. That's not strictly
9647  * necessary, but when hot standby is enabled, it would be rather weird if
9648  * the database opened up for read-only connections at a point-in-time
9649  * before the last shutdown. Such time travel is still possible in case of
9650  * immediate shutdown, though.
9651  *
9652  * We don't explicitly advance minRecoveryPoint when we do create a
9653  * restartpoint. It's assumed that flushing the buffers will do that as a
9654  * side-effect.
9655  */
9656  if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
9657  lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
9658  {
9659  ereport(DEBUG2,
9660  (errmsg_internal("skipping restartpoint, already performed at %X/%X",
9661  LSN_FORMAT_ARGS(lastCheckPoint.redo))));
9662 
9664  if (flags & CHECKPOINT_IS_SHUTDOWN)
9665  {
9666  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9668  ControlFile->time = (pg_time_t) time(NULL);
9670  LWLockRelease(ControlFileLock);
9671  }
9672  return false;
9673  }
9674 
9675  /*
9676  * Update the shared RedoRecPtr so that the startup process can calculate
9677  * the number of segments replayed since last restartpoint, and request a
9678  * restartpoint if it exceeds CheckPointSegments.
9679  *
9680  * Like in CreateCheckPoint(), hold off insertions to update it, although
9681  * during recovery this is just pro forma, because no WAL insertions are
9682  * happening.
9683  */
9685  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
9687 
9688  /* Also update the info_lck-protected copy */
9690  XLogCtl->RedoRecPtr = lastCheckPoint.redo;
9692 
9693  /*
9694  * Prepare to accumulate statistics.
9695  *
9696  * Note: because it is possible for log_checkpoints to change while a
9697  * checkpoint proceeds, we always accumulate stats, even if
9698  * log_checkpoints is currently off.
9699  */
9700  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
9702 
9703  if (log_checkpoints)
9704  LogCheckpointStart(flags, true);
9705 
9706  /* Update the process title */
9707  update_checkpoint_display(flags, true, false);
9708 
9709  CheckPointGuts(lastCheckPoint.redo, flags);
9710 
9711  /*
9712  * Remember the prior checkpoint's redo ptr for
9713  * UpdateCheckPointDistanceEstimate()
9714  */
9715  PriorRedoPtr = ControlFile->checkPointCopy.redo;
9716 
9717  /*
9718  * Update pg_control, using current time. Check that it still shows
9719  * DB_IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
9720  * this is a quick hack to make sure nothing really bad happens if somehow
9721  * we get here after the end-of-recovery checkpoint.
9722  */
9723  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9725  ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
9726  {
9727  ControlFile->checkPoint = lastCheckPointRecPtr;
9728  ControlFile->checkPointCopy = lastCheckPoint;
9729  ControlFile->time = (pg_time_t) time(NULL);
9730 
9731  /*
9732  * Ensure minRecoveryPoint is past the checkpoint record. Normally,
9733  * this will have happened already while writing out dirty buffers,
9734  * but not necessarily - e.g. because no buffers were dirtied. We do
9735  * this because a non-exclusive base backup uses minRecoveryPoint to
9736  * determine which WAL files must be included in the backup, and the
9737  * file (or files) containing the checkpoint record must be included,
9738  * at a minimum. Note that for an ordinary restart of recovery there's
9739  * no value in having the minimum recovery point any earlier than this
9740  * anyway, because redo will begin just after the checkpoint record.
9741  */
9742  if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
9743  {
9744  ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
9746 
9747  /* update local copy */
9750  }
9751  if (flags & CHECKPOINT_IS_SHUTDOWN)
9754  }
9755  LWLockRelease(ControlFileLock);
9756 
9757  /*
9758  * Update the average distance between checkpoints/restartpoints if the
9759  * prior checkpoint exists.
9760  */
9761  if (PriorRedoPtr != InvalidXLogRecPtr)
9763 
9764  /*
9765  * Delete old log files, those no longer needed for last restartpoint to
9766  * prevent the disk holding the xlog from growing full.
9767  */
9769 
9770  /*
9771  * Retreat _logSegNo using the current end of xlog replayed or received,
9772  * whichever is later.
9773  */
9774  receivePtr = GetWalRcvFlushRecPtr(NULL, NULL);
9775  replayPtr = GetXLogReplayRecPtr(&replayTLI);
9776  endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
9777  KeepLogSeg(endptr, &_logSegNo);
9778  if (InvalidateObsoleteReplicationSlots(_logSegNo))
9779  {
9780  /*
9781  * Some slots have been invalidated; recalculate the old-segment
9782  * horizon, starting again from RedoRecPtr.
9783  */
9785  KeepLogSeg(endptr, &_logSegNo);
9786  }
9787  _logSegNo--;
9788 
9789  /*
9790  * Try to recycle segments on a useful timeline. If we've been promoted
9791  * since the beginning of this restartpoint, use the new timeline chosen
9792  * at end of recovery (RecoveryInProgress() sets ThisTimeLineID in that
9793  * case). If we're still in recovery, use the timeline we're currently
9794  * replaying.
9795  *
9796  * There is no guarantee that the WAL segments will be useful on the
9797  * current timeline; if recovery proceeds to a new timeline right after
9798  * this, the pre-allocated WAL segments on this timeline will not be used,
9799  * and will go wasted until recycled on the next restartpoint. We'll live
9800  * with that.
9801  */
9802  if (RecoveryInProgress())
9803  ThisTimeLineID = replayTLI;
9804 
9805  RemoveOldXlogFiles(_logSegNo, RedoRecPtr, endptr);
9806 
9807  /*
9808  * Make more log segments if needed. (Do this after recycling old log
9809  * segments, since that may supply some of the needed files.)
9810  */
9811  PreallocXlogFiles(endptr);
9812 
9813  /*
9814  * ThisTimeLineID is normally not set when we're still in recovery.
9815  * However, recycling/preallocating segments above needed ThisTimeLineID
9816  * to determine which timeline to install the segments on. Reset it now,
9817  * to restore the normal state of affairs for debugging purposes.
9818  */
9819  if (RecoveryInProgress())
9820  ThisTimeLineID = 0;
9821 
9822  /*
9823  * Truncate pg_subtrans if possible. We can throw away all data before
9824  * the oldest XMIN of any running transaction. No future transaction will
9825  * attempt to reference any pg_subtrans entry older than that (see Asserts
9826  * in subtrans.c). When hot standby is disabled, though, we mustn't do
9827  * this because StartupSUBTRANS hasn't been called yet.
9828  */
9829  if (EnableHotStandby)
9831 
9832  /* Real work is done; log and update stats. */
9833  LogCheckpointEnd(true);
9834 
9835  /* Reset the process title */
9836  update_checkpoint_display(flags, true, true);
9837 
9838  xtime = GetLatestXTime();
9840  (errmsg("recovery restart point at %X/%X",
9841  LSN_FORMAT_ARGS(lastCheckPoint.redo)),
9842  xtime ? errdetail("Last completed transaction was at log time %s.",
9843  timestamptz_to_str(xtime)) : 0));
9844 
9845  /*
9846  * Finally, execute archive_cleanup_command, if any.
9847  */
9848  if (archiveCleanupCommand && strcmp(archiveCleanupCommand, "") != 0)
9850  "archive_cleanup_command",
9851  false);
9852 
9853  return true;
9854 }
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8915
bool log_checkpoints
Definition: xlog.c:106
void ExecuteRecoveryCommand(const char *command, const char *commandName, bool failOnSignal)
Definition: xlogarchive.c:287
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TimeLineID
Definition: xlogdefs.h:59
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
int wal_segment_size
Definition: xlog.c:119
pg_time_t time
Definition: pg_control.h:130
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:169
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
Definition: xlog.c:2803
TimestampTz ckpt_start_t
Definition: xlog.h:221
slock_t info_lck
Definition: xlog.c:735
#define MemSet(start, val, len)
Definition: c.h:1008
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:9530
TimestampTz GetLatestXTime(void)
Definition: xlog.c:6426
CheckPoint checkPointCopy
Definition: pg_control.h:133
XLogCtlInsert Insert
Definition: xlog.c:588
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8328
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:338
XLogRecPtr lastCheckPointRecPtr
Definition: xlog.c:703
static void update_checkpoint_display(int flags, bool restartpoint, bool reset)
Definition: xlog.c:8953
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
void UpdateControlFile(void)
Definition: xlog.c:4989
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8823
bool InvalidateObsoleteReplicationSlots(XLogSegNo oldestSegno)
Definition: slot.c:1317
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11927
#define DEBUG2
Definition: elog.h:24
static XLogRecPtr RedoRecPtr
Definition: xlog.c:366
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3962
uint64 XLogSegNo
Definition: xlogdefs.h:48
int errdetail(const char *fmt,...)
Definition: elog.c:1042
XLogRecPtr RedoRecPtr
Definition: xlog.c:592
CheckPoint lastCheckPoint
Definition: xlog.c:705
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define SpinLockRelease(lock)
Definition: spin.h:64
static TimeLineID minRecoveryPointTLI
Definition: xlog.c:869
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9963
static ControlFileData * ControlFile
Definition: xlog.c:746
TimeLineID ThisTimeLineID
Definition: xlog.c:194
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
uint64 XLogRecPtr
Definition: xlogdefs.h:21
CheckpointStatsData CheckpointStats
Definition: xlog.c:188
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:738
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
TransactionId GetOldestTransactionIdConsideredRunning(void)
Definition: procarray.c:2034
XLogRecPtr GetWalRcvFlushRecPtr(XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI)
bool EnableHotStandby
Definition: xlog.c:98
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr)
Definition: xlog.c:4097
XLogRecPtr RedoRecPtr
Definition: xlog.c:561
XLogRecPtr lastCheckPointEndPtr
Definition: xlog.c:704
XLogRecPtr checkPoint
Definition: pg_control.h:131
XLogRecPtr redo
Definition: pg_control.h:37
static void LogCheckpointStart(int flags, bool restartpoint)
Definition: xlog.c:8791
char * archiveCleanupCommand
Definition: xlog.c:274
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:196
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:168
static XLogRecPtr minRecoveryPoint
Definition: xlog.c:868
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1774
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ DataChecksumsEnabled()

bool DataChecksumsEnabled ( void  )

Definition at line 5018 of file xlog.c.

References Assert, and ControlFileData::data_checksum_version.

Referenced by PageIsVerifiedExtended(), PageSetChecksumCopy(), PageSetChecksumInplace(), pg_stat_get_db_checksum_failures(), pg_stat_get_db_checksum_last_failure(), ReadControlFile(), and sendFile().

5019 {
5020  Assert(ControlFile != NULL);
5021  return (ControlFile->data_checksum_version > 0);
5022 }
uint32 data_checksum_version
Definition: pg_control.h:222
static ControlFileData * ControlFile
Definition: xlog.c:746
#define Assert(condition)
Definition: c.h:804

◆ do_pg_abort_backup()

void do_pg_abort_backup ( int  code,
Datum  arg 
)

Definition at line 11879 of file xlog.c.

References Assert, DatumGetBool, ereport, errmsg(), EXCLUSIVE_BACKUP_NONE, XLogCtlInsert::exclusiveBackupState, XLogCtlInsert::forcePageWrites, XLogCtlData::Insert, XLogCtlInsert::nonExclusiveBackups, SESSION_BACKUP_NON_EXCLUSIVE, sessionBackupState, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), and WARNING.

Referenced by perform_base_backup(), and register_persistent_abort_backup_handler().

11880 {
11881  bool emit_warning = DatumGetBool(arg);
11882 
11883  /*
11884  * Quick exit if session is not keeping around a non-exclusive backup
11885  * already started.
11886  */
11888  return;
11889 
11893 
11896  {
11897  XLogCtl->Insert.forcePageWrites = false;
11898  }
11900 
11901  if (emit_warning)
11902  ereport(WARNING,
11903  (errmsg("aborting backup due to backend exiting before pg_stop_backup was called")));
11904 }
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
static SessionBackupState sessionBackupState
Definition: xlog.c:522
XLogCtlInsert Insert
Definition: xlog.c:588
bool forcePageWrites
Definition: xlog.c:562
#define DatumGetBool(X)
Definition: postgres.h:437
#define WARNING
Definition: elog.h:40
int nonExclusiveBackups
Definition: xlog.c:574
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:573
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:738
int errmsg(const char *fmt,...)
Definition: elog.c:909
void * arg

◆ do_pg_start_backup()

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

Definition at line 10946 of file xlog.c.

References AllocateDir(), 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, FreeDir(), FreeFile(), CheckPoint::fullPageWrites, XLogCtlData::info_lck, initStringInfo(), XLogCtlData::Insert, IS_DIR_SEP, lappend(), XLogCtlInsert::lastBackupStart, XLogCtlData::lastFpwDisableRecPtr, StringInfoData::len, log_timezone, LSN_FORMAT_ARGS, LW_SHARED, LWLockAcquire(), LWLockRelease(), makeStringInfo(), MAXFNAMELEN, MAXPGPATH, XLogCtlInsert::nonExclusiveBackups, tablespaceinfo::oid, palloc(), tablespaceinfo::path, pfree(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_fsync(), pg_localtime(), pg_start_backup_callback(), pg_strftime(), pstrdup(), ReadDir(), readlink, RecoveryInProgress(), CheckPoint::redo, relpath, RequestCheckpoint(), RequestXLogSwitch(), tablespaceinfo::rpath, SESSION_BACKUP_EXCLUSIVE, SESSION_BACKUP_NON_EXCLUSIVE, sessionBackupState, tablespaceinfo::size, snprintf, SpinLockAcquire, SpinLockRelease, stat, TABLESPACE_MAP, CheckPoint::ThisTimeLineID, wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), WARNING, XLByteToSeg, XLogFileName, and XLogIsNeeded.

Referenced by perform_base_backup(), and pg_start_backup().

10949 {
10950  bool exclusive = (labelfile == NULL);
10951  bool backup_started_in_recovery = false;
10952  XLogRecPtr checkpointloc;
10953  XLogRecPtr startpoint;
10954  TimeLineID starttli;
10955  pg_time_t stamp_time;
10956  char strfbuf[128];
10957  char xlogfilename[MAXFNAMELEN];
10958  XLogSegNo _logSegNo;
10959  struct stat stat_buf;
10960  FILE *fp;
10961 
10962  backup_started_in_recovery = RecoveryInProgress();
10963 
10964  /*
10965  * Currently only non-exclusive backup can be taken during recovery.
10966  */
10967  if (backup_started_in_recovery && exclusive)
10968  ereport(ERROR,
10969  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10970  errmsg("recovery is in progress"),
10971  errhint("WAL control functions cannot be executed during recovery.")));
10972 
10973  /*
10974  * During recovery, we don't need to check WAL level. Because, if WAL
10975  * level is not sufficient, it's impossible to get here during recovery.
10976  */
10977  if (!backup_started_in_recovery && !XLogIsNeeded())
10978  ereport(ERROR,
10979  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10980  errmsg("WAL level not sufficient for making an online backup"),
10981  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
10982 
10983  if (strlen(backupidstr) > MAXPGPATH)
10984  ereport(ERROR,
10985  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10986  errmsg("backup label too long (max %d bytes)",
10987  MAXPGPATH)));
10988 
10989  /*
10990  * Mark backup active in shared memory. We must do full-page WAL writes
10991  * during an on-line backup even if not doing so at other times, because
10992  * it's quite possible for the backup dump to obtain a "torn" (partially
10993  * written) copy of a database page if it reads the page concurrently with
10994  * our write to the same page. This can be fixed as long as the first
10995  * write to the page in the WAL sequence is a full-page write. Hence, we
10996  * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
10997  * are no dirty pages in shared memory that might get dumped while the
10998  * backup is in progress without having a corresponding WAL record. (Once
10999  * the backup is complete, we need not force full-page writes anymore,
11000  * since we expect that any pages not modified during the backup interval
11001  * must have been correctly captured by the backup.)
11002  *
11003  * Note that forcePageWrites has no effect during an online backup from
11004  * the standby.
11005  *
11006  * We must hold all the insertion locks to change the value of
11007  * forcePageWrites, to ensure adequate interlocking against
11008  * XLogInsertRecord().
11009  */
11011  if (exclusive)
11012  {
11013  /*
11014  * At first, mark that we're now starting an exclusive backup, to
11015  * ensure that there are no other sessions currently running
11016  * pg_start_backup() or pg_stop_backup().
11017  */
11019  {
11021  ereport(ERROR,
11022  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11023  errmsg("a backup is already in progress"),
11024  errhint("Run pg_stop_backup() and try again.")));
11025  }
11027  }
11028  else
11030  XLogCtl->Insert.forcePageWrites = true;
11032 
11033  /* Ensure we release forcePageWrites if fail below */
11035  {
11036  bool gotUniqueStartpoint = false;
11037  DIR *tblspcdir;
11038  struct dirent *de;
11039  tablespaceinfo *ti;
11040  int datadirpathlen;
11041 
11042  /*
11043  * Force an XLOG file switch before the checkpoint, to ensure that the
11044  * WAL segment the checkpoint is written to doesn't contain pages with
11045  * old timeline IDs. That would otherwise happen if you called
11046  * pg_start_backup() right after restoring from a PITR archive: the
11047  * first WAL segment containing the startup checkpoint has pages in
11048  * the beginning with the old timeline ID. That can cause trouble at
11049  * recovery: we won't have a history file covering the old timeline if
11050  * pg_wal directory was not included in the base backup and the WAL
11051  * archive was cleared too before starting the backup.
11052  *
11053  * This also ensures that we have emitted a WAL page header that has
11054  * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
11055  * Therefore, if a WAL archiver (such as pglesslog) is trying to
11056  * compress out removable backup blocks, it won't remove any that
11057  * occur after this point.
11058  *
11059  * During recovery, we skip forcing XLOG file switch, which means that
11060  * the backup taken during recovery is not available for the special
11061  * recovery case described above.
11062  */
11063  if (!backup_started_in_recovery)
11064  RequestXLogSwitch(false);
11065 
11066  do
11067  {
11068  bool checkpointfpw;
11069 
11070  /*
11071  * Force a CHECKPOINT. Aside from being necessary to prevent torn
11072  * page problems, this guarantees that two successive backup runs
11073  * will have different checkpoint positions and hence different
11074  * history file names, even if nothing happened in between.
11075  *
11076  * During recovery, establish a restartpoint if possible. We use
11077  * the last restartpoint as the backup starting checkpoint. This
11078  * means that two successive backup runs can have same checkpoint
11079  * positions.
11080  *
11081  * Since the fact that we are executing do_pg_start_backup()
11082  * during recovery means that checkpointer is running, we can use
11083  * RequestCheckpoint() to establish a restartpoint.
11084  *
11085  * We use CHECKPOINT_IMMEDIATE only if requested by user (via
11086  * passing fast = true). Otherwise this can take awhile.
11087  */
11089  (fast ? CHECKPOINT_IMMEDIATE : 0));
11090 
11091  /*
11092  * Now we need to fetch the checkpoint record location, and also
11093  * its REDO pointer. The oldest point in WAL that would be needed
11094  * to restore starting from the checkpoint is precisely the REDO
11095  * pointer.
11096  */
11097  LWLockAcquire(ControlFileLock, LW_SHARED);
11098  checkpointloc = ControlFile->checkPoint;
11099  startpoint = ControlFile->checkPointCopy.redo;
11101  checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
11102  LWLockRelease(ControlFileLock);
11103 
11104  if (backup_started_in_recovery)
11105  {
11106  XLogRecPtr recptr;
11107 
11108  /*
11109  * Check to see if all WAL replayed during online backup
11110  * (i.e., since last restartpoint used as backup starting
11111  * checkpoint) contain full-page writes.
11112  */
11114  recptr = XLogCtl->lastFpwDisableRecPtr;
11116 
11117  if (!checkpointfpw || startpoint <= recptr)
11118  ereport(ERROR,
11119  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11120  errmsg("WAL generated with full_page_writes=off was replayed "
11121  "since last restartpoint"),
11122  errhint("This means that the backup being taken on the standby "
11123  "is corrupt and should not be used. "
11124  "Enable full_page_writes and run CHECKPOINT on the primary, "
11125  "and then try an online backup again.")));
11126 
11127  /*
11128  * During recovery, since we don't use the end-of-backup WAL
11129  * record and don't write the backup history file, the
11130  * starting WAL location doesn't need to be unique. This means
11131  * that two base backups started at the same time might use
11132  * the same checkpoint as starting locations.
11133  */
11134  gotUniqueStartpoint = true;
11135  }
11136 
11137  /*
11138  * If two base backups are started at the same time (in WAL sender
11139  * processes), we need to make sure that they use different
11140  * checkpoints as starting locations, because we use the starting
11141  * WAL location as a unique identifier for the base backup in the
11142  * end-of-backup WAL record and when we write the backup history
11143  * file. Perhaps it would be better generate a separate unique ID
11144  * for each backup instead of forcing another checkpoint, but
11145  * taking a checkpoint right after another is not that expensive
11146  * either because only few buffers have been dirtied yet.
11147  */
11149  if (XLogCtl->Insert.lastBackupStart < startpoint)
11150  {
11151  XLogCtl->Insert.lastBackupStart = startpoint;
11152  gotUniqueStartpoint = true;
11153  }
11155  } while (!gotUniqueStartpoint);
11156 
11157  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
11158  XLogFileName(xlogfilename, starttli, _logSegNo, wal_segment_size);
11159 
11160  /*
11161  * Construct tablespace_map file. If caller isn't interested in this,
11162  * we make a local StringInfo.
11163  */
11164  if (tblspcmapfile == NULL)
11165  tblspcmapfile = makeStringInfo();
11166 
11167  datadirpathlen = strlen(DataDir);
11168 
11169  /* Collect information about all tablespaces */
11170  tblspcdir = AllocateDir("pg_tblspc");
11171  while ((de = ReadDir(tblspcdir, "pg_tblspc")) != NULL)
11172  {
11173  char fullpath[MAXPGPATH + 10];
11174  char linkpath[MAXPGPATH];
11175  char *relpath = NULL;
11176  int rllen;
11177  StringInfoData escapedpath;
11178  char *s;
11179 
11180  /* Skip anything that doesn't look like a tablespace */
11181  if (strspn(de->d_name, "0123456789") != strlen(de->d_name))
11182  continue;
11183 
11184  snprintf(fullpath, sizeof(fullpath), "pg_tblspc/%s", de->d_name);
11185 
11186 #if defined(HAVE_READLINK) || defined(WIN32)
11187  rllen = readlink(fullpath, linkpath, sizeof(linkpath));
11188  if (rllen < 0)
11189  {
11190  ereport(WARNING,
11191  (errmsg("could not read symbolic link \"%s\": %m",
11192  fullpath)));
11193  continue;
11194  }
11195  else if (rllen >= sizeof(linkpath))
11196  {
11197  ereport(WARNING,
11198  (errmsg("symbolic link \"%s\" target is too long",
11199  fullpath)));
11200  continue;
11201  }
11202  linkpath[rllen] = '\0';
11203 
11204  /*
11205  * Build a backslash-escaped version of the link path to include
11206  * in the tablespace map file.
11207  */
11208  initStringInfo(&escapedpath);
11209  for (s = linkpath; *s; s++)
11210  {
11211  if (*s == '\n' || *s == '\r' || *s == '\\')
11212  appendStringInfoChar(&escapedpath, '\\');
11213  appendStringInfoChar(&escapedpath, *s);
11214  }
11215 
11216  /*
11217  * Relpath holds the relative path of the tablespace directory
11218  * when it's located within PGDATA, or NULL if it's located
11219  * elsewhere.
11220  */
11221  if (rllen > datadirpathlen &&
11222  strncmp(linkpath, DataDir, datadirpathlen) == 0 &&
11223  IS_DIR_SEP(linkpath[datadirpathlen]))
11224  relpath = linkpath + datadirpathlen + 1;
11225 
11226  ti = palloc(sizeof(tablespaceinfo));
11227  ti->oid = pstrdup(de->d_name);
11228  ti->path = pstrdup(linkpath);
11229  ti->rpath = relpath ? pstrdup(relpath) : NULL;
11230  ti->size = -1;
11231 
11232  if (tablespaces)
11233  *tablespaces = lappend(*tablespaces, ti);
11234 
11235  appendStringInfo(tblspcmapfile, "%s %s\n",
11236  ti->oid, escapedpath.data);
11237 
11238  pfree(escapedpath.data);
11239 #else
11240 
11241  /*
11242  * If the platform does not have symbolic links, it should not be
11243  * possible to have tablespaces - clearly somebody else created
11244  * them. Warn about it and ignore.
11245  */
11246  ereport(WARNING,
11247  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11248  errmsg("tablespaces are not supported on this platform")));
11249 #endif
11250  }
11251  FreeDir(tblspcdir);
11252 
11253  /*
11254  * Construct backup label file. If caller isn't interested in this,
11255  * we make a local StringInfo.
11256  */
11257  if (labelfile == NULL)
11258  labelfile = makeStringInfo();
11259 
11260  /* Use the log timezone here, not the session timezone */
11261  stamp_time = (pg_time_t) time(NULL);
11262  pg_strftime(strfbuf, sizeof(strfbuf),
11263  "%Y-%m-%d %H:%M:%S %Z",
11264  pg_localtime(&stamp_time, log_timezone));
11265  appendStringInfo(labelfile, "START WAL LOCATION: %X/%X (file %s)\n",
11266  LSN_FORMAT_ARGS(startpoint), xlogfilename);
11267  appendStringInfo(labelfile, "CHECKPOINT LOCATION: %X/%X\n",
11268  LSN_FORMAT_ARGS(checkpointloc));
11269  appendStringInfo(labelfile, "BACKUP METHOD: %s\n",
11270  exclusive ? "pg_start_backup" : "streamed");
11271  appendStringInfo(labelfile, "BACKUP FROM: %s\n",
11272  backup_started_in_recovery ? "standby" : "primary");
11273  appendStringInfo(labelfile, "START TIME: %s\n", strfbuf);
11274  appendStringInfo(labelfile, "LABEL: %s\n", backupidstr);
11275  appendStringInfo(labelfile, "START TIMELINE: %u\n", starttli);
11276 
11277  /*
11278  * Okay, write the file, or return its contents to caller.
11279  */
11280  if (exclusive)
11281  {
11282  /*
11283  * Check for existing backup label --- implies a backup is already
11284  * running. (XXX given that we checked exclusiveBackupState
11285  * above, maybe it would be OK to just unlink any such label
11286  * file?)
11287  */
11288  if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
11289  {
11290  if (errno != ENOENT)
11291  ereport(ERROR,
11293  errmsg("could not stat file \"%s\": %m",
11294  BACKUP_LABEL_FILE)));
11295  }
11296  else
11297  ereport(ERROR,
11298  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11299  errmsg("a backup is already in progress"),
11300  errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
11301  BACKUP_LABEL_FILE)));
11302 
11303  fp = AllocateFile(BACKUP_LABEL_FILE, "w");
11304 
11305  if (!fp)
11306  ereport(ERROR,
11308  errmsg("could not create file \"%s\": %m",
11309  BACKUP_LABEL_FILE)));
11310  if (fwrite(labelfile->data, labelfile->len, 1, fp) != 1 ||
11311  fflush(fp) != 0 ||
11312  pg_fsync(fileno(fp)) != 0 ||
11313  ferror(fp) ||
11314  FreeFile(fp))
11315  ereport(ERROR,
11317  errmsg("could not write file \"%s\": %m",
11318  BACKUP_LABEL_FILE)));
11319  /* Allocated locally for exclusive backups, so free separately */
11320  pfree(labelfile->data);
11321  pfree(labelfile);
11322 
11323  /* Write backup tablespace_map file. */
11324  if (tblspcmapfile->len > 0)
11325  {
11326  if (stat(TABLESPACE_MAP, &stat_buf) != 0)
11327  {
11328  if (errno != ENOENT)
11329  ereport(ERROR,
11331  errmsg("could not stat file \"%s\": %m",
11332  TABLESPACE_MAP)));
11333  }
11334  else
11335  ereport(ERROR,
11336  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11337  errmsg("a backup is already in progress"),
11338  errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
11339  TABLESPACE_MAP)));
11340 
11341  fp = AllocateFile(TABLESPACE_MAP, "w");
11342 
11343  if (!fp)
11344  ereport(ERROR,
11346  errmsg("could not create file \"%s\": %m",
11347  TABLESPACE_MAP)));
11348  if (fwrite(tblspcmapfile->data, tblspcmapfile->len, 1, fp) != 1 ||
11349  fflush(fp) != 0 ||
11350  pg_fsync(fileno(fp)) != 0 ||
11351  ferror(fp) ||
11352  FreeFile(fp))
11353  ereport(ERROR,
11355  errmsg("could not write file \"%s\": %m",
11356  TABLESPACE_MAP)));
11357  }
11358 
11359  /* Allocated locally for exclusive backups, so free separately */
11360  pfree(tblspcmapfile->data);
11361  pfree(tblspcmapfile);
11362  }
11363  }
11365 
11366  /*
11367  * Mark that start phase has correctly finished for an exclusive backup.
11368  * Session-level locks are updated as well to reflect that state.
11369  *
11370  * Note that CHECK_FOR_INTERRUPTS() must not occur while updating backup
11371  * counters and session-level lock. Otherwise they can be updated
11372  * inconsistently, and which might cause do_pg_abort_backup() to fail.
11373  */
11374  if (exclusive)
11375  {
11378 
11379  /* Set session-level lock */
11382  }
11383  else
11385 
11386  /*
11387  * We're done. As a convenience, return the starting WAL location.
11388  */
11389  if (starttli_p)
11390  *starttli_p = starttli;
11391  return startpoint;
11392 }
size_t pg_strftime(char *s, size_t max, const char *format, const struct pg_tm *tm)
Definition: strftime.c:128
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:10056
int errhint(const char *fmt,...)
Definition: elog.c:1156
uint32 TimeLineID
Definition: xlogdefs.h:59
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
int wal_segment_size
Definition: xlog.c:119
XLogRecPtr lastFpwDisableRecPtr
Definition: xlog.c:733
static SessionBackupState sessionBackupState
Definition: xlog.c:522
XLogRecPtr lastBackupStart
Definition: xlog.c:575
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define XLogIsNeeded()
Definition: xlog.h:166
char * rpath
Definition: basebackup.h:32
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
slock_t info_lck
Definition: xlog.c:735
int errcode(int sqlerrcode)
Definition: elog.c:698
CheckPoint checkPointCopy
Definition: pg_control.h:133
XLogCtlInsert Insert
Definition: xlog.c:588
bool RecoveryInProgress(void)
Definition: xlog.c:8328
static bool backup_started_in_recovery
Definition: basebackup.c:88
Definition: dirent.h:9
#define IS_DIR_SEP(ch)
Definition: port.h:84
pg_tz * log_timezone
Definition: pgtz.c:31
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define TABLESPACE_MAP
Definition: xlog.h:366
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool forcePageWrites
Definition: xlog.c:562
Definition: dirent.c:25
#define ERROR
Definition: elog.h:46
#define MAXPGPATH
uint64 XLogSegNo
Definition: xlogdefs.h:48
#define readlink(path, buf, size)
Definition: win32_port.h:236
int errcode_for_file_access(void)
Definition: elog.c:721
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2459
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2720
#define CHECKPOINT_FORCE
Definition: xlog.h:200
List * lappend(List *list, void *datum)
Definition: list.c:336
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define WARNING
Definition: elog.h:40
int nonExclusiveBackups
Definition: xlog.c:574
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
static void pg_start_backup_callback(int code, Datum arg)
Definition: xlog.c:11396
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:573
uintptr_t Datum
Definition: postgres.h:411
static ControlFileData * ControlFile
Definition: xlog.c:746
#define BoolGetDatum(X)
Definition: postgres.h:446
#define ereport(elevel,...)
Definition: elog.h:157
bool fullPageWrites
Definition: pg_control.h:42
#define CHECKPOINT_WAIT
Definition: xlog.h:204
uint64 XLogRecPtr
Definition: xlogdefs.h:21
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2786
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:738
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
#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:1342
int FreeFile(FILE *file)
Definition: fd.c:2658
void * palloc(Size size)
Definition: mcxt.c:1062
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:199
#define relpath(rnode, forknum)
Definition: relpath.h:87
char * DataDir
Definition: globals.c:65
#define BACKUP_LABEL_FILE
Definition: xlog.h:363
int pg_fsync(int fd)
Definition: fd.c:357
char d_name[MAX_PATH]
Definition: dirent.h:15
#define snprintf
Definition: port.h:217
XLogRecPtr checkPoint
Definition: pg_control.h:131
XLogRecPtr redo
Definition: pg_control.h:37
int FreeDir(DIR *dir)
Definition: fd.c:2838
#define stat
Definition: win32_port.h:283
void RequestCheckpoint(int flags)
Definition: checkpointer.c:920
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ do_pg_stop_backup()

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

Definition at line 11464 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, fprintf, FreeFile(), XLogCtlData::info_lck, XLogCtlData::Insert, XLogCtlData::lastFpwDisableRecPtr, log_timezone, LSN_FORMAT_ARGS, LW_SHARED, LWLockAcquire(), LWLockRelease(), MAXFNAMELEN, MAXPGPATH, ControlFileData::minRecoveryPoint, ControlFileData::minRecoveryPointTLI, MyLatch, XLogCtlInsert::nonExclusiveBackups, NOTICE, palloc(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_localtime(), pg_stop_backup_callback(), pg_strftime(), RecoveryInProgress(), remaining, RequestXLogSwitch(), ResetLatch(), SESSION_BACKUP_NONE, sessionBackupState, SpinLockAcquire, SpinLockRelease, stat::st_size, stat, TABLESPACE_MAP, ThisTimeLineID, WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE, WaitLatch(), wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), WARNING, WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_TIMEOUT, 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().

11465 {
11466  bool exclusive = (labelfile == NULL);
11467  bool backup_started_in_recovery = false;
11468  XLogRecPtr startpoint;
11469  XLogRecPtr stoppoint;
11470  TimeLineID stoptli;
11471  pg_time_t stamp_time;
11472  char strfbuf[128];
11473  char histfilepath[MAXPGPATH];
11474  char startxlogfilename[MAXFNAMELEN];
11475  char stopxlogfilename[MAXFNAMELEN];
11476  char lastxlogfilename[MAXFNAMELEN];
11477  char histfilename[MAXFNAMELEN];
11478  char backupfrom[20];
11479  XLogSegNo _logSegNo;
11480  FILE *lfp;
11481  FILE *fp;
11482  char ch;
11483  int seconds_before_warning;
11484  int waits = 0;
11485  bool reported_waiting = false;
11486  char *remaining;
11487  char *ptr;
11488  uint32 hi,
11489  lo;
11490 
11491  backup_started_in_recovery = RecoveryInProgress();
11492 
11493  /*
11494  * Currently only non-exclusive backup can be taken during recovery.
11495  */
11496  if (backup_started_in_recovery && exclusive)
11497  ereport(ERROR,
11498  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11499  errmsg("recovery is in progress"),
11500  errhint("WAL control functions cannot be executed during recovery.")));
11501 
11502  /*
11503  * During recovery, we don't need to check WAL level. Because, if WAL
11504  * level is not sufficient, it's impossible to get here during recovery.
11505  */
11506  if (!backup_started_in_recovery && !XLogIsNeeded())
11507  ereport(ERROR,
11508  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11509  errmsg("WAL level not sufficient for making an online backup"),
11510  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
11511 
11512  if (exclusive)
11513  {
11514  /*
11515  * At first, mark that we're now stopping an exclusive backup, to
11516  * ensure that there are no other sessions currently running
11517  * pg_start_backup() or pg_stop_backup().
11518  */
11521  {
11523  ereport(ERROR,
11524  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11525  errmsg("exclusive backup not in progress")));
11526  }
11529 
11530  /*
11531  * Remove backup_label. In case of failure, the state for an exclusive
11532  * backup is switched back to in-progress.
11533  */
11535  {
11536  /*
11537  * Read the existing label file into memory.
11538  */
11539  struct stat statbuf;
11540  int r;
11541 
11542  if (stat(BACKUP_LABEL_FILE, &statbuf))
11543  {
11544  /* should not happen per the upper checks */
11545  if (errno != ENOENT)
11546  ereport(ERROR,
11548  errmsg("could not stat file \"%s\": %m",
11549  BACKUP_LABEL_FILE)));
11550  ereport(ERROR,
11551  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11552  errmsg("a backup is not in progress")));
11553  }
11554 
11555  lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
11556  if (!lfp)
11557  {
11558  ereport(ERROR,
11560  errmsg("could not read file \"%s\": %m",
11561  BACKUP_LABEL_FILE)));
11562  }
11563  labelfile = palloc(statbuf.st_size + 1);
11564  r = fread(labelfile, statbuf.st_size, 1, lfp);
11565  labelfile[statbuf.st_size] = '\0';
11566 
11567  /*
11568  * Close and remove the backup label file
11569  */
11570  if (r != 1 || ferror(lfp) || FreeFile(lfp))
11571  ereport(ERROR,
11573  errmsg("could not read file \"%s\": %m",
11574  BACKUP_LABEL_FILE)));
11576 
11577  /*
11578  * Remove tablespace_map file if present, it is created only if
11579  * there are tablespaces.
11580  */
11582  }
11584  }
11585 
11586  /*
11587  * OK to update backup counters, forcePageWrites and session-level lock.
11588  *
11589  * Note that CHECK_FOR_INTERRUPTS() must not occur while updating them.
11590  * Otherwise they can be updated inconsistently, and which might cause
11591  * do_pg_abort_backup() to fail.
11592  */
11594  if (exclusive)
11595  {
11597  }
11598  else
11599  {
11600  /*
11601  * The user-visible pg_start/stop_backup() functions that operate on
11602  * exclusive backups can be called at any time, but for non-exclusive
11603  * backups, it is expected that each do_pg_start_backup() call is
11604  * matched by exactly one do_pg_stop_backup() call.
11605  */
11608  }
11609 
11612  {
11613  XLogCtl->Insert.forcePageWrites = false;
11614  }
11615 
11616  /*
11617  * Clean up session-level lock.
11618  *
11619  * You might think that WALInsertLockRelease() can be called before
11620  * cleaning up session-level lock because session-level lock doesn't need
11621  * to be protected with WAL insertion lock. But since
11622  * CHECK_FOR_INTERRUPTS() can occur in it, session-level lock must be
11623  * cleaned up before it.
11624  */
11626 
11628 
11629  /*
11630  * Read and parse the START WAL LOCATION line (this code is pretty crude,
11631  * but we are not expecting any variability in the file format).
11632  */
11633  if (sscanf(labelfile, "START WAL LOCATION: %X/%X (file %24s)%c",
11634  &hi, &lo, startxlogfilename,
11635  &ch) != 4 || ch != '\n')
11636  ereport(ERROR,
11637  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11638  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
11639  startpoint = ((uint64) hi) << 32 | lo;
11640  remaining = strchr(labelfile, '\n') + 1; /* %n is not portable enough */
11641 
11642  /*
11643  * Parse the BACKUP FROM line. If we are taking an online backup from the
11644  * standby, we confirm that the standby has not been promoted during the
11645  * backup.
11646  */
11647  ptr = strstr(remaining, "BACKUP FROM:");
11648  if (!ptr || sscanf(ptr, "BACKUP FROM: %19s\n", backupfrom) != 1)
11649  ereport(ERROR,
11650  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11651  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
11652  if (strcmp(backupfrom, "standby") == 0 && !backup_started_in_recovery)
11653  ereport(ERROR,
11654  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11655  errmsg("the standby was promoted during online backup"),
11656  errhint("This means that the backup being taken is corrupt "
11657  "and should not be used. "
11658  "Try taking another online backup.")));
11659 
11660  /*
11661  * During recovery, we don't write an end-of-backup record. We assume that
11662  * pg_control was backed up last and its minimum recovery point can be
11663  * available as the backup end location. Since we don't have an
11664  * end-of-backup record, we use the pg_control value to check whether
11665  * we've reached the end of backup when starting recovery from this
11666  * backup. We have no way of checking if pg_control wasn't backed up last
11667  * however.
11668  *
11669  * We don't force a switch to new WAL file but it is still possible to
11670  * wait for all the required files to be archived if waitforarchive is
11671  * true. This is okay if we use the backup to start a standby and fetch
11672  * the missing WAL using streaming replication. But in the case of an
11673  * archive recovery, a user should set waitforarchive to true and wait for
11674  * them to be archived to ensure that all the required files are
11675  * available.
11676  *
11677  * We return the current minimum recovery point as the backup end
11678  * location. Note that it can be greater than the exact backup end
11679  * location if the minimum recovery point is updated after the backup of
11680  * pg_control. This is harmless for current uses.
11681  *
11682  * XXX currently a backup history file is for informational and debug
11683  * purposes only. It's not essential for an online backup. Furthermore,
11684  * even if it's created, it will not be archived during recovery because
11685  * an archiver is not invoked. So it doesn't seem worthwhile to write a
11686  * backup history file during recovery.
11687  */
11688  if (backup_started_in_recovery)
11689  {
11690  XLogRecPtr recptr;
11691 
11692  /*
11693  * Check to see if all WAL replayed during online backup contain
11694  * full-page writes.
11695  */
11697  recptr = XLogCtl->lastFpwDisableRecPtr;
11699 
11700  if (startpoint <= recptr)
11701  ereport(ERROR,
11702  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11703  errmsg("WAL generated with full_page_writes=off was replayed "
11704  "during online backup"),
11705  errhint("This means that the backup being taken on the standby "
11706  "is corrupt and should not be used. "
11707  "Enable full_page_writes and run CHECKPOINT on the primary, "
11708  "and then try an online backup again.")));
11709 
11710 
11711  LWLockAcquire(ControlFileLock, LW_SHARED);
11712  stoppoint = ControlFile->minRecoveryPoint;
11713  stoptli = ControlFile->minRecoveryPointTLI;
11714  LWLockRelease(ControlFileLock);
11715  }
11716  else
11717  {
11718  /*
11719  * Write the backup-end xlog record
11720  */
11721  XLogBeginInsert();
11722  XLogRegisterData((char *) (&startpoint), sizeof(startpoint));
11723  stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END);
11724  stoptli = ThisTimeLineID;
11725 
11726  /*
11727  * Force a switch to a new xlog segment file, so that the backup is
11728  * valid as soon as archiver moves out the current segment file.
11729  */
11730  RequestXLogSwitch(false);
11731 
11732  XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
11733  XLogFileName(stopxlogfilename, stoptli, _logSegNo, wal_segment_size);
11734 
11735  /* Use the log timezone here, not the session timezone */
11736  stamp_time = (pg_time_t) time(NULL);
11737  pg_strftime(strfbuf, sizeof(strfbuf),
11738  "%Y-%m-%d %H:%M:%S %Z",
11739  pg_localtime(&stamp_time, log_timezone));
11740 
11741  /*
11742  * Write the backup history file
11743  */
11744  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
11745  BackupHistoryFilePath(histfilepath, stoptli, _logSegNo,
11746  startpoint, wal_segment_size);
11747  fp = AllocateFile(histfilepath, "w");
11748  if (!fp)
11749  ereport(ERROR,
11751  errmsg("could not create file \"%s\": %m",
11752  histfilepath)));
11753  fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
11754  LSN_FORMAT_ARGS(startpoint), startxlogfilename);
11755  fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
11756  LSN_FORMAT_ARGS(stoppoint), stopxlogfilename);
11757 
11758  /*
11759  * Transfer remaining lines including label and start timeline to
11760  * history file.
11761  */
11762  fprintf(fp, "%s", remaining);
11763  fprintf(fp, "STOP TIME: %s\n", strfbuf);
11764  fprintf(fp, "STOP TIMELINE: %u\n", stoptli);
11765  if (fflush(fp) || ferror(fp) || FreeFile(fp))
11766  ereport(ERROR,
11768  errmsg("could not write file \"%s\": %m",
11769  histfilepath)));
11770 
11771  /*
11772  * Clean out any no-longer-needed history files. As a side effect,
11773  * this will post a .ready file for the newly created history file,
11774  * notifying the archiver that history file may be archived
11775  * immediately.
11776  */
11778  }
11779 
11780  /*
11781  * If archiving is enabled, wait for all the required WAL files to be
11782  * archived before returning. If archiving isn't enabled, the required WAL
11783  * needs to be transported via streaming replication (hopefully with
11784  * wal_keep_size set high enough), or some more exotic mechanism like
11785  * polling and copying files from pg_wal with script. We have no knowledge
11786  * of those mechanisms, so it's up to the user to ensure that he gets all
11787  * the required WAL.
11788  *
11789  * We wait until both the last WAL file filled during backup and the
11790  * history file have been archived, and assume that the alphabetic sorting
11791  * property of the WAL files ensures any earlier WAL files are safely
11792  * archived as well.
11793  *
11794  * We wait forever, since archive_command is supposed to work and we
11795  * assume the admin wanted his backup to work completely. If you don't
11796  * wish to wait, then either waitforarchive should be passed in as false,
11797  * or you can set statement_timeout. Also, some notices are issued to
11798  * clue in anyone who might be doing this interactively.
11799  */
11800 
11801  if (waitforarchive &&
11802  ((!backup_started_in_recovery && XLogArchivingActive()) ||
11803  (backup_started_in_recovery && XLogArchivingAlways())))
11804  {
11805  XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
11806  XLogFileName(lastxlogfilename, stoptli, _logSegNo, wal_segment_size);
11807 
11808  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
11809  BackupHistoryFileName(histfilename, stoptli, _logSegNo,
11810  startpoint, wal_segment_size);
11811 
11812  seconds_before_warning = 60;
11813  waits = 0;
11814 
11815  while (XLogArchiveIsBusy(lastxlogfilename) ||
11816  XLogArchiveIsBusy(histfilename))
11817  {
11819 
11820  if (!reported_waiting && waits > 5)
11821  {
11822  ereport(NOTICE,
11823  (errmsg("base backup done, waiting for required WAL segments to be archived")));
11824  reported_waiting = true;
11825  }
11826 
11827  (void) WaitLatch(MyLatch,
11829  1000L,
11832 
11833  if (++waits >= seconds_before_warning)
11834  {
11835  seconds_before_warning *= 2; /* This wraps in >10 years... */
11836  ereport(WARNING,
11837  (errmsg("still waiting for all required WAL segments to be archived (%d seconds elapsed)",
11838  waits),
11839  errhint("Check that your archive_command is executing properly. "
11840  "You can safely cancel this backup, "
11841  "but the database backup will not be usable without all the WAL segments.")));
11842  }
11843  }
11844 
11845  ereport(NOTICE,
11846  (errmsg("all required WAL segments have been archived")));
11847  }
11848  else if (waitforarchive)
11849  ereport(NOTICE,
11850  (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
11851 
11852  /*
11853  * We're done. As a convenience, return the ending WAL location.
11854  */
11855  if (stoptli_p)
11856  *stoptli_p = stoptli;
11857  return stoppoint;
11858 }
int remaining
Definition: informix.c:667
size_t pg_strftime(char *s, size_t max, const char *format, const struct pg_tm *tm)
Definition: strftime.c:128
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:10056
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1156
uint32 TimeLineID
Definition: xlogdefs.h:59
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
#define WL_TIMEOUT
Definition: latch.h:128
int wal_segment_size
Definition: xlog.c:119
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:169
XLogRecPtr lastFpwDisableRecPtr
Definition: xlog.c:733
static SessionBackupState sessionBackupState
Definition: xlog.c:522
#define XLByteToPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogIsNeeded()
Definition: xlog.h:166
slock_t info_lck
Definition: xlog.c:735
int errcode(int sqlerrcode)
Definition: elog.c:698
XLogCtlInsert Insert
Definition: xlog.c:588
#define BackupHistoryFileName(fname, tli, logSegNo, startpoint, wal_segsz_bytes)
bool RecoveryInProgress(void)
Definition: xlog.c:8328
static bool backup_started_in_recovery
Definition: basebackup.c:88
#define fprintf
Definition: port.h:221
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
pg_tz * log_timezone
Definition: pgtz.c:31
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define TABLESPACE_MAP
Definition: xlog.h:366
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
#define XLogArchivingAlways()
Definition: xlog.h:158
bool forcePageWrites
Definition: xlog.c:562
#define ERROR
Definition: elog.h:46
static void CleanupBackupHistory(void)
Definition: xlog.c:4364
#define MAXPGPATH
uint64 XLogSegNo
Definition: xlogdefs.h:48
int errcode_for_file_access(void)
Definition: elog.c:721
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2459
unsigned int uint32
Definition: c.h:441
#define XLOG_BACKUP_END
Definition: pg_control.h:72
#define WARNING
Definition: elog.h:40
int nonExclusiveBackups
Definition: xlog.c:574
#define MAXFNAMELEN
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:340
#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:434
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:573
uintptr_t Datum
Definition: postgres.h:411
static ControlFileData * ControlFile
Definition: xlog.c:746
#define BoolGetDatum(X)
Definition: postgres.h:446
TimeLineID ThisTimeLineID
Definition: xlog.c:194
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
bool XLogArchiveIsBusy(const char *xlog)
Definition: xlogarchive.c:626
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
#define XLogArchivingActive()
Definition: xlog.h:155
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:738
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
static void pg_stop_backup_callback(int code, Datum arg)
Definition: xlog.c:11425
#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:1342
int durable_unlink(const char *fname, int elevel)
Definition: fd.c:787
int FreeFile(FILE *file)
Definition: fd.c:2658
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
struct Latch * MyLatch
Definition: globals.c:57
#define BACKUP_LABEL_FILE
Definition: xlog.h:363
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
void XLogBeginInsert(void)
Definition: xloginsert.c:135
#define WL_LATCH_SET
Definition: latch.h:125
#define stat
Definition: win32_port.h:283
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:168
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ get_backup_status()

SessionBackupState get_backup_status ( void  )

Definition at line 11443 of file xlog.c.

References sessionBackupState.

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

11444 {
11445  return sessionBackupState;
11446 }
static SessionBackupState sessionBackupState
Definition: xlog.c:522

◆ GetCurrentChunkReplayStartTime()

TimestampTz GetCurrentChunkReplayStartTime ( void  )

Definition at line 6456 of file xlog.c.

References XLogCtlData::currentChunkStartTime, XLogCtlData::info_lck, SpinLockAcquire, and SpinLockRelease.

Referenced by GetReplicationApplyDelay().

6457 {
6458  TimestampTz xtime;
6459 
6461  xtime = XLogCtl->currentChunkStartTime;
6463 
6464  return xtime;
6465 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738
TimestampTz currentChunkStartTime
Definition: xlog.c:724

◆ GetFakeLSNForUnloggedRel()

XLogRecPtr GetFakeLSNForUnloggedRel ( void  )

Definition at line 5034 of file xlog.c.

References SpinLockAcquire, SpinLockRelease, XLogCtlData::ulsn_lck, and XLogCtlData::unloggedLSN.

Referenced by gistGetFakeLSN().

5035 {
5036  XLogRecPtr nextUnloggedLSN;
5037 
5038  /* increment the unloggedLSN counter, need SpinLock */
5040  nextUnloggedLSN = XLogCtl->unloggedLSN++;
5042 
5043  return nextUnloggedLSN;
5044 }
XLogRecPtr unloggedLSN
Definition: xlog.c:600
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:738
slock_t ulsn_lck
Definition: xlog.c:601

◆ GetFlushRecPtr()

XLogRecPtr GetFlushRecPtr ( void  )

Definition at line 8680 of file xlog.c.

References XLogwrtResult::Flush, XLogCtlData::info_lck, XLogCtlData::LogwrtResult, SpinLockAcquire, and SpinLockRelease.

Referenced by get_flush_position(), IdentifySystem(), pg_current_wal_flush_lsn(), pg_logical_slot_get_changes_guts(), pg_replication_slot_advance(), read_local_xlog_page(), StartReplication(), WalSndWaitForWal(), XLogSendLogical(), and XLogSendPhysical().

8681 {
8685 
8686  return LogwrtResult.Flush;
8687 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:784
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:611
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738
XLogRecPtr Flush
Definition: xlog.c:436

◆ GetFullPageWriteInfo()

void GetFullPageWriteInfo ( XLogRecPtr RedoRecPtr_p,
bool doPageWrites_p 
)

Definition at line 8649 of file xlog.c.

References doPageWrites, and RedoRecPtr.

Referenced by XLogCheckBufferNeedsBackup(), and XLogInsert().

8650 {
8651  *RedoRecPtr_p = RedoRecPtr;
8652  *doPageWrites_p = doPageWrites;
8653 }
static bool doPageWrites
Definition: xlog.c:373
static XLogRecPtr RedoRecPtr
Definition: xlog.c:366

◆ GetInsertRecPtr()

XLogRecPtr GetInsertRecPtr ( void  )

Definition at line 8664 of file xlog.c.

References XLogCtlData::info_lck, XLogCtlData::LogwrtRqst, SpinLockAcquire, SpinLockRelease, and XLogwrtRqst::Write.

Referenced by CheckpointerMain(), gistvacuumscan(), and IsCheckpointOnSchedule().

8665 {
8666  XLogRecPtr recptr;
8667 
8669  recptr = XLogCtl->LogwrtRqst.Write;
8671 
8672  return recptr;
8673 }
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr Write
Definition: xlog.c:429
XLogwrtRqst LogwrtRqst
Definition: xlog.c:591
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:738

◆ GetLastImportantRecPtr()

XLogRecPtr GetLastImportantRecPtr ( void  )

Definition at line 8698 of file xlog.c.

References i, InvalidXLogRecPtr, WALInsertLockPadded::l, WALInsertLock::lastImportantAt, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), and NUM_XLOGINSERT_LOCKS.

Referenced by BackgroundWriterMain(), CheckArchiveTimeout(), and CreateCheckPoint().

8699 {
8701  int i;
8702 
8703  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
8704  {
8705  XLogRecPtr last_important;
8706 
8707  /*
8708  * Need to take a lock to prevent torn reads of the LSN, which are
8709  * possible on some of the supported platforms. WAL insert locks only
8710  * support exclusive mode, so we have to use that.
8711  */
8713  last_important = WALInsertLocks[i].l.lastImportantAt;
8714  LWLockRelease(&WALInsertLocks[i].l.lock);
8715 
8716  if (res < last_important)
8717  res = last_important;
8718  }
8719 
8720  return res;
8721 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogRecPtr lastImportantAt
Definition: xlog.c:479
#define NUM_XLOGINSERT_LOCKS
Definition: xlog.c:126
WALInsertLock l
Definition: xlog.c:491
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
uint64 XLogRecPtr
Definition: xlogdefs.h:21
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int i
static WALInsertLockPadded * WALInsertLocks
Definition: xlog.c:741

◆ GetLatestXTime()

TimestampTz GetLatestXTime ( void  )

Definition at line 6426 of file xlog.c.

References XLogCtlData::info_lck, XLogCtlData::recoveryLastXTime, SpinLockAcquire, and SpinLockRelease.

Referenced by CreateRestartPoint(), pg_last_xact_replay_timestamp(), and StartupXLOG().

6427 {
6428  TimestampTz xtime;
6429 
6431  xtime = XLogCtl->recoveryLastXTime;
6433 
6434  return xtime;
6435 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz recoveryLastXTime
Definition: xlog.c:718
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738

◆ GetMockAuthenticationNonce()

char* GetMockAuthenticationNonce ( void  )

Definition at line 5008 of file xlog.c.

References Assert, and ControlFileData::mock_authentication_nonce.

Referenced by scram_mock_salt().

5009 {
5010  Assert(ControlFile != NULL);
5012 }
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:229
static ControlFileData * ControlFile
Definition: xlog.c:746
#define Assert(condition)
Definition: c.h:804

◆ GetRecoveryPauseState()

RecoveryPauseState GetRecoveryPauseState ( void  )

Definition at line 6257 of file xlog.c.

References XLogCtlData::info_lck, XLogCtlData::recoveryPauseState, SpinLockAcquire, and SpinLockRelease.

Referenced by pg_get_wal_replay_pause_state(), pg_is_wal_replay_paused(), recoveryPausesHere(), and RecoveryRequiresIntParameter().

6258 {
6260 
6262  state = XLogCtl->recoveryPauseState;
6264 
6265  return state;
6266 }
RecoveryPauseState recoveryPauseState
Definition: xlog.c:726
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
RecoveryPauseState
Definition: xlog.h:145
#define SpinLockRelease(lock)
Definition: spin.h:64
Definition: regguts.h:317
static XLogCtlData * XLogCtl
Definition: xlog.c:738

◆ GetRecoveryState()

RecoveryState GetRecoveryState ( void  )

Definition at line 8381 of file xlog.c.

References XLogCtlData::info_lck, XLogCtlData::SharedRecoveryState, SpinLockAcquire, and SpinLockRelease.

Referenced by XLogArchiveCheckDone().

8382 {
8383  RecoveryState retval;
8384 
8386  retval = XLogCtl->SharedRecoveryState;
8388 
8389  return retval;
8390 }
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
RecoveryState SharedRecoveryState
Definition: xlog.c:647
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738
RecoveryState
Definition: xlog.h:137

◆ GetRedoRecPtr()

XLogRecPtr GetRedoRecPtr ( void  )

Definition at line 8620 of file xlog.c.

References XLogCtlData::info_lck, RedoRecPtr, XLogCtlData::RedoRecPtr, SpinLockAcquire, and SpinLockRelease.

Referenced by CheckPointLogicalRewriteHeap(), CheckPointSnapBuild(), InitXLOGAccess(), nextval_internal(), ReplicationSlotReserveWal(), XLogPageRead(), XLogSaveBufferForHint(), and XLogWrite().

8621 {
8622  XLogRecPtr ptr;
8623 
8624  /*
8625  * The possibly not up-to-date copy in XlogCtl is enough. Even if we
8626  * grabbed a WAL insertion lock to read the authoritative value in
8627  * Insert->RedoRecPtr, someone might update it just after we've released
8628  * the lock.
8629  */
8631  ptr = XLogCtl->RedoRecPtr;
8633 
8634  if (RedoRecPtr < ptr)
8635  RedoRecPtr = ptr;
8636 
8637  return RedoRecPtr;
8638 }
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
static XLogRecPtr RedoRecPtr
Definition: xlog.c:366
XLogRecPtr RedoRecPtr
Definition: xlog.c:592
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:738

◆ GetSystemIdentifier()

uint64 GetSystemIdentifier ( void  )

Definition at line 4998 of file xlog.c.

References Assert, and ControlFileData::system_identifier.

Referenced by IdentifySystem(), ReplicationSlotNameForTablesync(), and WalReceiverMain().

4999 {
5000  Assert(ControlFile != NULL);
5002 }
uint64 system_identifier
Definition: pg_control.h:108
static ControlFileData * ControlFile
Definition: xlog.c:746
#define Assert(condition)
Definition: c.h:804

◆ GetWALAvailability()

WALAvailability GetWALAvailability ( XLogRecPtr  targetLSN)

Definition at line 9879 of file xlog.c.

References ConvertToXSegs, GetXLogWriteRecPtr(), KeepLogSeg(), max_wal_size_mb, wal_segment_size, WALAVAIL_EXTENDED, WALAVAIL_INVALID_LSN, WALAVAIL_REMOVED, WALAVAIL_RESERVED, WALAVAIL_UNRESERVED, XLByteToSeg, XLogGetLastRemovedSegno(), and XLogRecPtrIsInvalid.

Referenced by pg_get_replication_slots().

9880 {
9881  XLogRecPtr currpos; /* current write LSN */
9882  XLogSegNo currSeg; /* segid of currpos */
9883  XLogSegNo targetSeg; /* segid of targetLSN */
9884  XLogSegNo oldestSeg; /* actual oldest segid */
9885  XLogSegNo oldestSegMaxWalSize; /* oldest segid kept by max_wal_size */
9886  XLogSegNo oldestSlotSeg; /* oldest segid kept by slot */
9887  uint64 keepSegs;
9888 
9889  /*
9890  * slot does not reserve WAL. Either deactivated, or has never been active
9891  */
9892  if (XLogRecPtrIsInvalid(targetLSN))
9893  return WALAVAIL_INVALID_LSN;
9894 
9895  /*
9896  * Calculate the oldest segment currently reserved by all slots,
9897  * considering wal_keep_size and max_slot_wal_keep_size. Initialize
9898  * oldestSlotSeg to the current segment.
9899  */
9900  currpos = GetXLogWriteRecPtr();
9901  XLByteToSeg(currpos, oldestSlotSeg, wal_segment_size);
9902  KeepLogSeg(currpos, &oldestSlotSeg);
9903 
9904  /*
9905  * Find the oldest extant segment file. We get 1 until checkpoint removes
9906  * the first WAL segment file since startup, which causes the status being
9907  * wrong under certain abnormal conditions but that doesn't actually harm.
9908  */
9909  oldestSeg = XLogGetLastRemovedSegno() + 1;
9910 
9911  /* calculate oldest segment by max_wal_size */
9912  XLByteToSeg(currpos, currSeg, wal_segment_size);
9914 
9915  if (currSeg > keepSegs)
9916  oldestSegMaxWalSize = currSeg - keepSegs;
9917  else
9918  oldestSegMaxWalSize = 1;
9919 
9920  /* the segment we care about */
9921  XLByteToSeg(targetLSN, targetSeg, wal_segment_size);
9922 
9923  /*
9924  * No point in returning reserved or extended status values if the
9925  * targetSeg is known to be lost.
9926  */
9927  if (targetSeg >= oldestSlotSeg)
9928  {
9929  /* show "reserved" when targetSeg is within max_wal_size */
9930  if (targetSeg >= oldestSegMaxWalSize)
9931  return WALAVAIL_RESERVED;
9932 
9933  /* being retained by slots exceeding max_wal_size */
9934  return WALAVAIL_EXTENDED;
9935  }
9936 
9937  /* WAL segments are no longer retained but haven't been removed yet */
9938  if (targetSeg >= oldestSeg)
9939  return WALAVAIL_UNRESERVED;
9940 
9941  /* Definitely lost */
9942  return WALAVAIL_REMOVED;
9943 }
#define ConvertToXSegs(x, segsize)
Definition: xlog.c:775
int wal_segment_size
Definition: xlog.c:119
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:4030
int max_wal_size_mb
Definition: xlog.c:91
uint64 XLogSegNo
Definition: xlogdefs.h:48
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9963
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:11962
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ GetXLogInsertRecPtr()

XLogRecPtr GetXLogInsertRecPtr ( void  )

Definition at line 11946 of file xlog.c.

References XLogCtlInsert::CurrBytePos, Insert(), XLogCtlData::Insert, XLogCtlInsert::insertpos_lck, SpinLockAcquire, SpinLockRelease, and XLogBytePosToRecPtr().

Referenced by GetSnapshotDataInitOldSnapshot(), gistGetFakeLSN(), logical_begin_heap_rewrite(), pg_current_wal_insert_lsn(), and ReplicationSlotReserveWal().

11947 {
11949  uint64 current_bytepos;
11950 
11951  SpinLockAcquire(&Insert->insertpos_lck);
11952  current_bytepos = Insert->CurrBytePos;
11953  SpinLockRelease(&Insert->insertpos_lck);
11954 
11955  return XLogBytePosToRecPtr(current_bytepos);
11956 }
slock_t insertpos_lck
Definition: xlog.c:529
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:2009
XLogCtlInsert Insert
Definition: xlog.c:588
#define SpinLockAcquire(lock)
Definition: spin.h:62
uint64 CurrBytePos
Definition: xlog.c:538
static void Insert(File file)
Definition: fd.c:1302
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738

◆ GetXLogReceiptTime()

void GetXLogReceiptTime ( TimestampTz rtime,
bool fromStream 
)

Definition at line 6472 of file xlog.c.

References Assert, InRecovery, XLOG_FROM_STREAM, XLogReceiptSource, and XLogReceiptTime.

Referenced by GetStandbyLimitTime().

6473 {
6474  /*
6475  * This must be executed in the startup process, since we don't export the
6476  * relevant state to shared memory.
6477  */
6478  Assert(InRecovery);
6479 
6480  *rtime = XLogReceiptTime;
6481  *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
6482 }
static XLogSource XLogReceiptSource
Definition: xlog.c:855
bool InRecovery
Definition: xlogutils.c:52
static TimestampTz XLogReceiptTime
Definition: xlog.c:854
#define Assert(condition)
Definition: c.h:804

◆ GetXLogReplayRecPtr()

XLogRecPtr GetXLogReplayRecPtr ( TimeLineID replayTLI)

Definition at line 11927 of file xlog.c.

References XLogCtlData::info_lck, XLogCtlData::lastReplayedEndRecPtr, XLogCtlData::lastReplayedTLI, SpinLockAcquire, and SpinLockRelease.

Referenced by CheckpointerMain(), CreateRestartPoint(), GetReplicationApplyDelay(), GetStandbyFlushRecPtr(), IsCheckpointOnSchedule(), pg_last_wal_replay_lsn(), pg_logical_slot_get_changes_guts(), pg_replication_slot_advance(), read_local_xlog_page(), WalReceiverMain(), WalSndWaitForWal(), and XLogWalRcvSendReply().

11928 {
11929  XLogRecPtr recptr;
11930  TimeLineID tli;
11931 
11933  recptr = XLogCtl->lastReplayedEndRecPtr;
11934  tli = XLogCtl->lastReplayedTLI;
11936 
11937  if (replayTLI)
11938  *replayTLI = tli;
11939  return recptr;
11940 }
uint32 TimeLineID
Definition: xlogdefs.h:59
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:738
TimeLineID lastReplayedTLI
Definition: xlog.c:714
XLogRecPtr lastReplayedEndRecPtr
Definition: xlog.c:713

◆ GetXLogWriteRecPtr()

XLogRecPtr GetXLogWriteRecPtr ( void  )

Definition at line 11962 of file xlog.c.

References XLogCtlData::info_lck, XLogCtlData::LogwrtResult, SpinLockAcquire, SpinLockRelease, and XLogwrtResult::Write.

Referenced by GetWALAvailability(), pg_attribute_noreturn(), pg_current_wal_lsn(), and pg_get_replication_slots().

11963 {
11967 
11968  return LogwrtResult.Write;
11969 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:784
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:611
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738
XLogRecPtr Write
Definition: xlog.c:435

◆ HotStandbyActive()

bool HotStandbyActive ( void  )

Definition at line 8402 of file xlog.c.

References XLogCtlData::info_lck, LocalHotStandbyActive, XLogCtlData::SharedHotStandbyActive, SpinLockAcquire, and SpinLockRelease.

Referenced by XLogWalRcvSendHSFeedback().

8403 {
8404  /*
8405  * We check shared state each time only until Hot Standby is active. We
8406  * can't de-activate Hot Standby, so there's no need to keep checking
8407  * after the shared variable has once been seen true.
8408  */
8410  return true;
8411  else
8412  {
8413  /* spinlock is essential on machines with weak memory ordering! */
8417 
8418  return LocalHotStandbyActive;
8419  }
8420 }
bool SharedHotStandbyActive
Definition: xlog.c:653
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool LocalHotStandbyActive
Definition: xlog.c:230
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738

◆ HotStandbyActiveInReplay()

bool HotStandbyActiveInReplay ( void  )

Definition at line 8427 of file xlog.c.

References AmStartupProcess, Assert, IsPostmasterEnvironment, and LocalHotStandbyActive.

8428 {
8430  return LocalHotStandbyActive;
8431 }
#define AmStartupProcess()
Definition: miscadmin.h:444
bool IsPostmasterEnvironment
Definition: globals.c:111
static bool LocalHotStandbyActive
Definition: xlog.c:230
#define Assert(condition)
Definition: c.h:804

◆ InitXLOGAccess()

void InitXLOGAccess ( void  )

Definition at line 8594 of file xlog.c.

References Assert, doPageWrites, XLogCtlInsert::forcePageWrites, XLogCtlInsert::fullPageWrites, GetRedoRecPtr(), InitXLogInsert(), Insert(), XLogCtlData::Insert, IsBootstrapProcessingMode, ThisTimeLineID, XLogCtlData::ThisTimeLineID, wal_segment_size, and ControlFileData::xlog_seg_size.

Referenced by AuxiliaryProcessMain(), LocalSetXLogInsertAllowed(), and RecoveryInProgress().

8595 {
8597 
8598  /* ThisTimeLineID doesn't change so we need no lock to copy it */
8601 
8602  /* set wal_segment_size */
8604 
8605  /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
8606  (void) GetRedoRecPtr();
8607  /* Also update our copy of doPageWrites. */
8608  doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);
8609 
8610  /* Also initialize the working areas for constructing WAL records */
8611  InitXLogInsert();
8612 }
int wal_segment_size
Definition: xlog.c:119
void InitXLogInsert(void)
Definition: xloginsert.c:1251
TimeLineID ThisTimeLineID
Definition: xlog.c:640
XLogCtlInsert Insert
Definition: xlog.c:588
bool fullPageWrites
Definition: xlog.c:563
uint32 xlog_seg_size
Definition: pg_control.h:211
static bool doPageWrites
Definition: xlog.c:373
bool forcePageWrites
Definition: xlog.c:562
static void Insert(File file)
Definition: fd.c:1302
static ControlFileData * ControlFile
Definition: xlog.c:746
TimeLineID ThisTimeLineID
Definition: xlog.c:194
#define Assert(condition)
Definition: c.h:804
static XLogCtlData * XLogCtl
Definition: xlog.c:738
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:8620
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:406

◆ issue_xlog_fsync()

void issue_xlog_fsync ( int  fd,
XLogSegNo  segno 
)

Definition at line 10826 of file xlog.c.

References _, Assert, duration, elog, enableFsync, ereport, errcode_for_file_access(), errmsg(), INSTR_TIME_GET_MICROSEC, INSTR_TIME_SET_CURRENT, INSTR_TIME_SUBTRACT, PgStat_MsgWal::m_wal_sync, PgStat_MsgWal::m_wal_sync_time, MAXFNAMELEN, PANIC, pg_fdatasync(), pg_fsync_no_writethrough(), pg_fsync_writethrough(), pgstat_report_wait_end(), pgstat_report_wait_start(), sync_method, SYNC_METHOD_FDATASYNC, SYNC_METHOD_FSYNC, SYNC_METHOD_FSYNC_WRITETHROUGH, SYNC_METHOD_OPEN, SYNC_METHOD_OPEN_DSYNC, ThisTimeLineID, track_wal_io_timing, WAIT_EVENT_WAL_SYNC, wal_segment_size, WalStats, and XLogFileName.

Referenced by XLogWalRcvFlush(), and XLogWrite().

10827 {
10828  char *msg = NULL;
10829  instr_time start;
10830 
10831  /*
10832  * Quick exit if fsync is disabled or write() has already synced the WAL
10833  * file.
10834  */
10835  if (!enableFsync ||
10838  return;
10839 
10840  /* Measure I/O timing to sync the WAL file */
10841  if (track_wal_io_timing)
10842  INSTR_TIME_SET_CURRENT(start);
10843 
10845  switch (sync_method)
10846  {
10847  case SYNC_METHOD_FSYNC:
10848  if (pg_fsync_no_writethrough(fd) != 0)
10849  msg = _("could not fsync file \"%s\": %m");
10850  break;
10851 #ifdef HAVE_FSYNC_WRITETHROUGH
10853  if (pg_fsync_writethrough(fd) != 0)
10854  msg = _("could not fsync write-through file \"%s\": %m");
10855  break;
10856 #endif
10857 #ifdef HAVE_FDATASYNC
10858  case SYNC_METHOD_FDATASYNC:
10859  if (pg_fdatasync(fd) != 0)
10860  msg = _("could not fdatasync file \"%s\": %m");
10861  break;
10862 #endif
10863  case SYNC_METHOD_OPEN:
10865  /* not reachable */
10866  Assert(false);
10867  break;
10868  default:
10869  elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
10870  break;
10871  }
10872 
10873  /* PANIC if failed to fsync */
10874  if (msg)
10875  {
10876  char xlogfname[MAXFNAMELEN];
10877  int save_errno = errno;
10878 
10879  XLogFileName(xlogfname, ThisTimeLineID, segno,
10881  errno = save_errno;
10882  ereport(PANIC,
10884  errmsg(msg, xlogfname)));
10885  }
10886 
10888 
10889  /*
10890  * Increment the I/O timing and the number of times WAL files were synced.
10891  */
10892  if (track_wal_io_timing)
10893  {
10895 
10896  INSTR_TIME_SET_CURRENT(duration);
10897  INSTR_TIME_SUBTRACT(duration, start);
10899  }
10900 
10901  WalStats.m_wal_sync++;
10902 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:274
int pg_fdatasync(int fd)
Definition: fd.c:447
int wal_segment_size
Definition: xlog.c:119
#define SYNC_METHOD_FSYNC_WRITETHROUGH
Definition: xlog.h:28
int pg_fsync_writethrough(int fd)
Definition: fd.c:424
struct timeval instr_time
Definition: instr_time.h:150
PgStat_Counter m_wal_sync
Definition: pgstat.h:494
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:412
#define PANIC
Definition: elog.h:50
static int fd(const char *x, int i)
Definition: preproc-init.c:105
PgStat_Counter m_wal_sync_time
Definition: pgstat.h:497
int duration
Definition: pgbench.c:184
#define SYNC_METHOD_OPEN_DSYNC
Definition: xlog.h:29
bool track_wal_io_timing
Definition: xlog.c:113
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
int errcode_for_file_access(void)
Definition: elog.c:721
#define SYNC_METHOD_FSYNC
Definition: xlog.h:25
#define SYNC_METHOD_OPEN
Definition: xlog.h:27
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:258
#define MAXFNAMELEN
PgStat_MsgWal WalStats
Definition: pgstat.c:133
TimeLineID ThisTimeLineID
Definition: xlog.c:194
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
#define INSTR_TIME_GET_MICROSEC(t)
Definition: instr_time.h:205
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
int sync_method
Definition: xlog.c:107
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
bool enableFsync
Definition: globals.c:122
#define SYNC_METHOD_FDATASYNC
Definition: xlog.h:26
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define _(x)
Definition: elog.c:89

◆ LocalProcessControlFile()

void LocalProcessControlFile ( bool  reset)

Definition at line 5118 of file xlog.c.

References Assert, palloc(), and ReadControlFile().

Referenced by BackendRun(), PostgresSingleUserMain(), PostmasterMain(), and PostmasterStateMachine().

5119 {
5120  Assert(reset || ControlFile == NULL);
5121  ControlFile = palloc(sizeof(ControlFileData));
5122  ReadControlFile();
5123 }
void reset(void)
Definition: sql-declare.c:600
static void ReadControlFile(void)
Definition: xlog.c:4789
static ControlFileData * ControlFile
Definition: xlog.c:746
#define Assert(condition)
Definition: c.h:804
void * palloc(Size size)
Definition: mcxt.c:1062

◆ PromoteIsTriggered()

bool PromoteIsTriggered ( void  )

Definition at line 13064 of file xlog.c.

References XLogCtlData::info_lck, LocalPromoteIsTriggered, XLogCtlData::SharedPromoteIsTriggered, SpinLockAcquire, and SpinLockRelease.

Referenced by pg_wal_replay_pause(), and pg_wal_replay_resume().

13065 {
13066  /*
13067  * We check shared state each time only until a standby promotion is
13068  * triggered. We can't trigger a promotion again, so there's no need to
13069  * keep checking after the shared variable has once been seen true.
13070  */
13072  return true;
13073 
13077 
13078  return LocalPromoteIsTriggered;
13079 }
slock_t info_lck
Definition: xlog.c:735
static bool LocalPromoteIsTriggered
Definition: xlog.c:236
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738
bool SharedPromoteIsTriggered
Definition: xlog.c:669

◆ RecoveryInProgress()

bool RecoveryInProgress ( void  )

Definition at line 8328 of file xlog.c.

References InitXLOGAccess(), LocalRecoveryInProgress, pg_memory_barrier, RECOVERY_STATE_DONE, XLogCtlData::SharedRecoveryState, and XLogCtl.

Referenced by BackgroundWriterMain(), BeginReportingGUCOptions(), brin_desummarize_range(), brin_summarize_range(), btree_index_mainfork_expected(), check_transaction_read_only(), check_XactIsoLevel(), CheckArchiveTimeout(), CheckLogicalDecodingRequirements(), CheckpointerMain(), ComputeXidHorizons(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateOverwriteContrecordRecord(), CreateRestartPoint(), do_pg_start_backup(), do_pg_stop_backup(), error_commit_ts_disabled(), get_relation_info(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestSafeDecodingTransactionId(), GetRunningTransactionData(), GetSerializableTransactionSnapshot(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), gin_clean_pending_list(), GlobalVisHorizonKindForRel(), heap_force_common(), heap_page_prune_opt(), IdentifySystem(), InitPostgres(), InitTempTableNamespace(), IsCheckpointOnSchedule(), LockAcquireExtended(), MaintainLatestCompletedXid(), MarkBufferDirtyHint(), perform_base_backup(), pg_create_restore_point(), pg_current_wal_flush_lsn(), pg_current_wal_insert_lsn(), pg_current_wal_lsn(), pg_get_wal_replay_pause_state(), pg_is_in_recovery(), pg_is_wal_replay_paused(), pg_logical_slot_get_changes_guts(), pg_promote(), pg_replication_slot_advance(), pg_switch_wal(), pg_wal_replay_pause(), pg_wal_replay_resume(), pg_walfile_name(), pg_walfile_name_offset(), PrepareRedoAdd(), PrepareRedoRemove(), PreventCommandDuringRecovery(), ProcSendSignal(), ProcSleep(), read_local_xlog_page(), ReplicationSlotReserveWal(), replorigin_check_prerequisites(), ReportChangedGUCOptions(), sendDir(), SerialSetActiveSerXmin(), show_in_hot_standby(), ShutdownXLOG(), SnapBuildWaitSnapshot(), standard_ProcessUtility(), StartLogicalReplication(), StartReplication(), StartTransaction(), TransactionIdIsInProgress(), TruncateMultiXact(), UpdateFullPageWrites(), verify_heapam(), WalReceiverMain(), WalSndWaitForWal(), XLogBackgroundFlush(), XLogInsertAllowed(), XLogNeedsFlush(), and XLogSendPhysical().

8329 {
8330  /*
8331  * We check shared state each time only until we leave recovery mode. We
8332  * can't re-enter recovery, so there's no need to keep checking after the
8333  * shared variable has once been seen false.
8334  */
8336  return false;
8337  else
8338  {
8339  /*
8340  * use volatile pointer to make sure we make a fresh read of the
8341  * shared variable.
8342  */
8343  volatile XLogCtlData *xlogctl = XLogCtl;
8344 
8346 
8347  /*
8348  * Initialize TimeLineID and RedoRecPtr when we discover that recovery
8349  * is finished. InitPostgres() relies upon this behaviour to ensure
8350  * that InitXLOGAccess() is called at backend startup. (If you change
8351  * this, see also LocalSetXLogInsertAllowed.)
8352  */
8354  {
8355  /*
8356  * If we just exited recovery, make sure we read TimeLineID and
8357  * RedoRecPtr after SharedRecoveryState (for machines with weak
8358  * memory ordering).
8359  */
8361  InitXLOGAccess();
8362  }
8363 
8364  /*
8365  * Note: We don't need a memory barrier when we're still in recovery.
8366  * We might exit recovery immediately after return, so the caller
8367  * can't rely on 'true' meaning that we're still in recovery anyway.
8368  */
8369 
8370  return LocalRecoveryInProgress;
8371  }
8372 }
void InitXLOGAccess(void)
Definition: xlog.c:8594
RecoveryState SharedRecoveryState
Definition: xlog.c:647
#define pg_memory_barrier()
Definition: atomics.h:145
static XLogCtlData * XLogCtl
Definition: xlog.c:738
static bool LocalRecoveryInProgress
Definition: xlog.c:224

◆ register_persistent_abort_backup_handler()

void register_persistent_abort_backup_handler ( void  )

Definition at line 11911 of file xlog.c.

References before_shmem_exit(), DatumGetBool, and do_pg_abort_backup().

Referenced by pg_start_backup().

11912 {
11913  static bool already_done = false;
11914 
11915  if (already_done)
11916  return;
11918  already_done = true;
11919 }
void do_pg_abort_backup(int code, Datum arg)
Definition: xlog.c:11879
#define DatumGetBool(X)
Definition: postgres.h:437
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333

◆ RemovePromoteSignalFiles()

void RemovePromoteSignalFiles ( void  )

Definition at line 13144 of file xlog.c.

References PROMOTE_SIGNAL_FILE.

Referenced by CheckForStandbyTrigger(), and PostmasterMain().

13145 {
13146  unlink(PROMOTE_SIGNAL_FILE);
13147 }
#define PROMOTE_SIGNAL_FILE
Definition: xlog.h:370

◆ SetRecoveryPause()

void SetRecoveryPause ( bool  recoveryPause)

Definition at line 6277 of file xlog.c.

References ConditionVariableBroadcast(), XLogCtlData::info_lck, RECOVERY_NOT_PAUSED, RECOVERY_PAUSE_REQUESTED, XLogCtlData::recoveryNotPausedCV, XLogCtlData::recoveryPauseState, SpinLockAcquire, and SpinLockRelease.

Referenced by pg_wal_replay_pause(), pg_wal_replay_resume(), RecoveryRequiresIntParameter(), SetPromoteIsTriggered(), and StartupXLOG().

6278 {
6280 
6281  if (!recoveryPause)
6285 
6287 
6288  if (!recoveryPause)
6290 }
RecoveryPauseState recoveryPauseState
Definition: xlog.c:726
slock_t info_lck
Definition: xlog.c:735
void ConditionVariableBroadcast(ConditionVariable *cv)
#define SpinLockAcquire(lock)
Definition: spin.h:62
ConditionVariable recoveryNotPausedCV
Definition: xlog.c:727
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:738

◆ SetWalWriterSleeping()

void SetWalWriterSleeping ( bool  sleeping)

Definition at line 13177 of file xlog.c.

References XLogCtlData::info_lck, SpinLockAcquire, SpinLockRelease, and XLogCtlData::WalWriterSleeping.

Referenced by WalWriterMain().

13178 {
13180  XLogCtl->WalWriterSleeping = sleeping;
13182 }
slock_t info_lck
Definition: xlog.c:735
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool WalWriterSleeping
Definition: xlog.c:676
static XLogCtlData * XLogCtl
Definition: xlog.c:738

◆ ShutdownXLOG()

void ShutdownXLOG ( int  code,
Datum  arg 
)

Definition at line 8744 of file xlog.c.

References Assert, AuxProcessResourceOwner, CHECKPOINT_IMMEDIATE, CHECKPOINT_IS_SHUTDOWN, CreateCheckPoint(), CreateRestartPoint(), CurrentResourceOwner, ereport, errmsg(), IsPostmasterEnvironment, LOG, NOTICE, RecoveryInProgress(), RequestXLogSwitch(), WalSndInitStopping(), WalSndWaitStopping(), XLogArchiveCommandSet, and XLogArchivingActive.

Referenced by HandleCheckpointerInterrupts(), and InitPostgres().

8745 {
8746  /*
8747  * We should have an aux process resource owner to use, and we should not
8748  * be in a transaction that's installed some other resowner.
8749  */
8751  Assert(CurrentResourceOwner == NULL ||
8754 
8755  /* Don't be chatty in standalone mode */
8757  (errmsg("shutting down")));
8758 
8759  /*
8760  * Signal walsenders to move to stopping state.
8761  */
8763 
8764  /*
8765  * Wait for WAL senders to be in stopping state. This prevents commands
8766  * from writing new WAL.
8767  */
8769 
8770  if (RecoveryInProgress())
8772  else
8773  {
8774  /*
8775  * If archiving is enabled, rotate the last XLOG file so that all the
8776  * remaining records are archived (postmaster wakes up the archiver
8777  * process one more time at the end of shutdown). The checkpoint
8778  * record will go to the next XLOG file and won't be archived (yet).
8779  */
8781  RequestXLogSwitch(false);
8782 
8784  }
8785 }
bool IsPostmasterEnvironment
Definition: globals.c:111
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:10056
void CreateCheckPoint(int flags)
Definition: xlog.c:9010
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
bool CreateRestartPoint(int flags)
Definition: xlog.c:9611
#define XLogArchiveCommandSet()
Definition: xlog.h:160
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8328
ResourceOwner AuxProcessResourceOwner
Definition: resowner.c:149
void WalSndWaitStopping(void)
Definition: walsender.c:3195
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
void WalSndInitStopping(void)
Definition: walsender.c:3169
#define Assert(condition)
Definition: c.h:804
#define XLogArchivingActive()
Definition: xlog.h:155
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:199
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:196

◆ StartupRequestWalReceiverRestart()

void StartupRequestWalReceiverRestart ( void  )

Definition at line 13002 of file xlog.c.

References currentSource, ereport, errmsg(), LOG, pendingWalRcvRestart, WalRcvRunning(), and XLOG_FROM_STREAM.

Referenced by StartupRereadConfig().

13003 {
13005  {
13006  ereport(LOG,
13007  (errmsg("WAL receiver process shutdown requested")));
13008 
13009  pendingWalRcvRestart = true;
13010  }
13011 }
#define LOG
Definition: elog.h:26
static bool pendingWalRcvRestart
Definition: xlog.c:837
#define ereport(elevel,...)
Definition: elog.h:157
static XLogSource currentSource
Definition: xlog.c:835
int errmsg(const char *fmt,...)
Definition: elog.c:909
bool WalRcvRunning(void)

◆ StartupXLOG()

void StartupXLOG ( void  )

Definition at line 6617 of file xlog.c.

References abortedRecPtr, AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AllowCascadeReplication, appendStringInfo(), appendStringInfoString(), ArchiveRecoveryRequested, ErrorContextCallback::arg, Assert, AuxProcessResourceOwner, BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, ControlFileData::backupEndPoint, ControlFileData::backupEndRequired, ControlFileData::backupStartPoint, buf, ErrorContextCallback::callback, ControlFileData::checkPoint, CHECKPOINT_FORCE, ControlFileData::checkPointCopy, CheckRecoveryConsistency(), CheckRequiredParameterValues(), checkTimeLineSwitch(), checkXLogConsistency(), XLogCtlData::ckptFullXid, CleanupAfterArchiveRecovery(), close, CompleteCommitTsInitialization(), CreateOverwriteContrecordRecord(), XLogCtlInsert::CurrBytePos, XLogCtlData::currentChunkStartTime, CurrentResourceOwner, StringInfoData::data, DataDir, DB_IN_ARCHIVE_RECOVERY, DB_IN_CRASH_RECOVERY, DB_IN_PRODUCTION, DB_SHUTDOWNED, DB_SHUTDOWNED_IN_RECOVERY, DB_SHUTDOWNING, DEBUG1, DEBUG2, DEBUG3, DeleteAllExportedSnapshotFiles(), DisownLatch(), doPageWrites, doRequestWalReceiverReply, durable_rename(), elog, EnableHotStandby, EndRecPtr, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), errmsg_internal(), ERROR, error_context_stack, exitArchiveRecovery(), FATAL, findNewestTimeLine(), FirstNormalUnloggedLSN, XLogwrtRqst::Flush, XLogwrtResult::Flush, CheckPoint::fullPageWrites, XLogCtlInsert::fullPageWrites, FullTransactionIdRetreat(), GetCurrentTimestamp(), GetLatestXTime(), getRecoveryStopReason(), HandleStartupProcInterrupts(), InArchiveRecovery, XLogCtlData::info_lck, XLogCtlData::InitializedUpTo, InitRecoveryTransactionEnvironment(), initStringInfo(), InRecovery, InRedo, Insert(), XLogCtlData::Insert, XLogCtlData::InstallXLogFileSegmentActive, InvalidXLogRecPtr, IsPostmasterEnvironment, IsUnderPostmaster, lastFullPageWrites, LastRec, XLogCtlData::lastReplayedEndRecPtr, XLogCtlData::lastReplayedTLI, XLogCtlData::lastSegSwitchLSN, XLogCtlData::lastSegSwitchTime, RunningTransactionsData::latestCompletedXid, VariableCacheData::latestCompletedXid, lfirst, LocalSetXLogInsertAllowed(), LocalXLogInsertAllowed, LOG, XLogCtlData::LogwrtResult, LogwrtResult, XLogCtlData::LogwrtRqst, LSN_FORMAT_ARGS, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXPGPATH, MemSet, ControlFileData::minRecoveryPoint, minRecoveryPoint, ControlFileData::minRecoveryPointTLI, minRecoveryPointTLI, missingContrecPtr, MultiXactSetNextMXact(), CheckPoint::newestCommitTsXid, CheckPoint::nextMulti, CheckPoint::nextMultiOffset, CheckPoint::nextOid, VariableCacheData::nextOid, CheckPoint::nextXid, RunningTransactionsData::nextXid, VariableCacheData::nextXid, NIL, NOTICE, tablespaceinfo::oid, VariableCacheData::oidCount, CheckPoint::oldestActiveXid, CheckPoint::oldestCommitTsXid, CheckPoint::oldestMulti, CheckPoint::oldestMultiDB, RunningTransactionsData::oldestRunningXid, CheckPoint::oldestXid, CheckPoint::oldestXidDB, OwnLatch(), XLogCtlData::pages, palloc(), PANIC, tablespaceinfo::path, PerformRecoveryXLogAction(), pfree(), pg_rusage_init(), pg_rusage_show(), pg_usleep(), pgstat_reset_all(), PMSIGNAL_RECOVERY_STARTED, PreallocXlogFiles(), PrescanPreparedTransactions(), XLogCtlInsert::PrevBytePos, ErrorContextCallback::previous, CheckPoint::PrevTimeLineID, xl_end_of_recovery::PrevTimeLineID, XLogCtlData::PrevTimeLineID, primary_image_masked, proc_exit(), ProcArrayApplyRecoveryInfo(), ProcArrayInitRecovery(), psprintf(), PublishStartupProcessInformation(), reachedConsistency, read_backup_label(), read_tablespace_map(), XLogReaderState::readBuf, ReadCheckpointRecord(), readFile, readOff, ReadRecord(), readRecoverySignalFile(), ReadRecPtr, RecordKnownAssignedTransactionIds(), RecoverPreparedTransactions(), RECOVERY_NOT_PAUSED, RECOVERY_STATE_ARCHIVE, RECOVERY_STATE_CRASH, RECOVERY_STATE_DONE, RECOVERY_TARGET_ACTION_PAUSE, RECOVERY_TARGET_ACTION_PROMOTE, RECOVERY_TARGET_ACTION_SHUTDOWN, RECOVERY_TARGET_IMMEDIATE, RECOVERY_TARGET_LSN, RECOVERY_TARGET_NAME, RECOVERY_TARGET_TIME, RECOVERY_TARGET_UNSET, RECOVERY_TARGET_XID, recoveryApplyDelay(), XLogCtlData::recoveryLastXTime, recoveryPausesHere(), XLogCtlData::recoveryPauseState, recoveryStopsAfter(), recoveryStopsBefore(), recoveryTarget, recoveryTargetAction, recoveryTargetLSN, recoveryTargetName, recoveryTargetTime, recoveryTargetTLI, recoveryTargetXid, XLogCtlData::recoveryWakeupLatch, CheckPoint::redo, RedoRecPtr, XLogCtlInsert::RedoRecPtr, XLogCtlData::RedoRecPtr, RedoStartLSN, RelationCacheInitFileRemove(), remove_tablespace_symlink(), RemoveNonParentXlogFiles(), RemoveTempXlogFiles(), replay_image_masked, XLogCtlData::replayEndRecPtr, XLogCtlData::replayEndTLI, RequestCheckpoint(), ResetUnloggedRelations(), restoreTimeLineHistoryFiles(), restoreTwoPhaseData(), RmgrData::rm_cleanup, RM_MAX_ID, RmgrData::rm_redo, rm_redo_error_callback(), RmgrData::rm_startup, RmgrTable, XLogReaderState::seg, SendPostmasterSignal(), SetCommitTsLimit(), SetMultiXactIdLimit(), SetRecoveryPause(), SetTransactionIdLimit(), XLogCtlData::SharedRecoveryState, ShmemVariableCache, ShutdownRecoveryTransactionEnvironment(), snprintf, SpinLockAcquire, SpinLockRelease, STANDBY_DISABLED, STANDBY_INITIALIZED, StandbyMode, StandbyModeRequested, StandbyRecoverPreparedTransactions(), standbyState, StartupCLOG(), StartupCommitTs(), StartupMultiXact(), StartupReorderBuffer(), StartupReplicationOrigin(), StartupReplicationSlots(), StartupSUBTRANS(), stat, ControlFileData::state, str_time(), RunningTransactionsData::subxcnt, RunningTransactionsData::subxid_overflow, symlink, SyncDataDirectory(), ControlFileData::system_identifier, XLogReaderState::system_identifier, TABLESPACE_MAP, TABLESPACE_MAP_OLD, CheckPoint::ThisTimeLineID, ThisTimeLineID, xl_end_of_recovery::ThisTimeLineID, XLogCtlData::ThisTimeLineID, CheckPoint::time, ControlFileData::time, timestamptz_to_str(), tliOfPointInHistory(), tliSwitchPoint(), trace_recovery_messages, ControlFileData::track_commit_timestamp, TransactionIdIsNormal, TransactionIdIsValid, TransactionIdRetreat, TrimCLOG(), TrimMultiXact(), U64FromFullTransactionId, UINT64_FORMAT, UNLOGGED_RELATION_CLEANUP, UNLOGGED_RELATION_INIT, ControlFileData::unloggedLSN, XLogCtlData::unloggedLSN, UpdateControlFile(), UpdateFullPageWrites(), validateRecoveryParameters(), ValidateXLOGDirectoryStructure(), wal_segment_close(), wal_segment_size, WalRcvForceReply(), WalRcvStreaming(), WalSndWakeup(), XLogwrtRqst::Write, XLogwrtResult::Write, writeTimeLineHistory(), WALOpenSegment::ws_tli, RunningTransactionsData::xcnt, XidFromFullTransactionId, RunningTransactionsData::xids, XLogRecord::xl_info, XLogRecord::xl_rmid, XL_ROUTINE, XLogRecord::xl_xid, XLogCtlData::xlblocks, XLOG_CHECKPOINT_SHUTDOWN, XLOG_END_OF_RECOVERY, xlog_outdesc(), XLogBeginRead(), XLOGDIR, XLogPageRead(), xlogreader, XLogReaderAllocate(), XLogReaderFree(), XLogReceiptTime, XLogRecGetData, XLogRecPtrIsInvalid, XLogRecPtrToBufIdx, XLogRecPtrToBytePos(), XLogReportParameters(), XLogSegmentOffset, XLogShutdownWalRcv(), XLR_CHECK_CONSISTENCY, XLR_INFO_MASK, and XRecOffIsValid.

Referenced by InitPostgres(), and StartupProcessMain().

6618 {
6620  CheckPoint checkPoint;
6621  bool wasShutdown;
6622  bool reachedRecoveryTarget = false;
6623  bool haveBackupLabel = false;
6624  bool haveTblspcMap = false;
6625  XLogRecPtr RecPtr,
6626  checkPointLoc,
6627  EndOfLog;
6628  TimeLineID EndOfLogTLI;
6629  TimeLineID PrevTimeLineID;
6630  XLogRecord *record;
6631  TransactionId oldestActiveXID;
6632  bool backupEndRequired = false;
6633  bool backupFromStandby = false;
6634  DBState dbstate_at_startup;
6636  XLogPageReadPrivate private;
6637  bool promoted = false;
6638  struct stat st;
6639 
6640  /*
6641  * We should have an aux process resource owner to use, and we should not
6642  * be in a transaction that's installed some other resowner.
6643  */
6645  Assert(CurrentResourceOwner == NULL ||
6648 
6649  /*
6650  * Check that contents look valid.
6651  */
6653  ereport(FATAL,
6654  (errmsg("control file contains invalid checkpoint location")));
6655 
6656  switch (ControlFile->state)
6657  {
6658  case DB_SHUTDOWNED:
6659 
6660  /*
6661  * This is the expected case, so don't be chatty in standalone
6662  * mode
6663  */
6665  (errmsg("database system was shut down at %s",
6666  str_time(ControlFile->time))));
6667  break;
6668 
6670  ereport(LOG,
6671  (errmsg("database system was shut down in recovery at %s",
6672  str_time(ControlFile->time))));
6673  break;
6674 
6675  case DB_SHUTDOWNING:
6676  ereport(LOG,
6677  (errmsg("database system shutdown was interrupted; last known up at %s",
6678  str_time(ControlFile->time))));
6679  break;
6680 
6681  case DB_IN_CRASH_RECOVERY:
6682  ereport(LOG,
6683  (errmsg("database system was interrupted while in recovery at %s",
6685  errhint("This probably means that some data is corrupted and"
6686  " you will have to use the last backup for recovery.")));
6687  break;
6688 
6690  ereport(LOG,
6691  (errmsg("database system was interrupted while in recovery at log time %s",
6693  errhint("If this has occurred more than once some data might be corrupted"
6694  " and you might need to choose an earlier recovery target.")));
6695  break;
6696 
6697  case DB_IN_PRODUCTION:
6698  ereport(LOG,
6699  (errmsg("database system was interrupted; last known up at %s",
6700  str_time(ControlFile->time))));
6701  break;
6702 
6703  default:
6704  ereport(FATAL,
6705  (errmsg("control file contains invalid database cluster state")));
6706  }
6707 
6708  /* This is just to allow attaching to startup process with a debugger */
6709 #ifdef XLOG_REPLAY_DELAY
6711  pg_usleep(60000000L);
6712 #endif
6713 
6714  /*
6715  * Verify that pg_wal and pg_wal/archive_status exist. In cases where
6716  * someone has performed a copy for PITR, these directories may have been
6717  * excluded and need to be re-created.
6718  */
6720 
6721  /*----------
6722  * If we previously crashed, perform a couple of actions:
6723  *
6724  * - The pg_wal directory may still include some temporary WAL segments
6725  * used when creating a new segment, so perform some clean up to not
6726  * bloat this path. This is done first as there is no point to sync
6727  * this temporary data.
6728  *
6729  * - There might be data which we had written, intending to fsync it, but
6730  * which we had not actually fsync'd yet. Therefore, a power failure in
6731  * the near future might cause earlier unflushed writes to be lost, even
6732  * though more recent data written to disk from here on would be
6733  * persisted. To avoid that, fsync the entire data directory.
6734  */
6735  if (ControlFile->state != DB_SHUTDOWNED &&
6737  {
6740  }
6741 
6742  /*
6743  * Initialize on the assumption we want to recover to the latest timeline
6744  * that's active according to pg_control.
6745  */
6749  else
6751 
6752  /*
6753  * Check for signal files, and if so set up state for offline recovery
6754  */
6757 
6759  {
6761  ereport(LOG,
6762  (errmsg("entering standby mode")));
6763  else if (recoveryTarget == RECOVERY_TARGET_XID)
6764  ereport(LOG,
6765  (errmsg("starting point-in-time recovery to XID %u",
6766  recoveryTargetXid)));