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 InHotStandby   (standbyState >= STANDBY_SNAPSHOT_PENDING)
 
#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 /* include XID of top-level xact */
 
#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 RecoveryState RecoveryState
 
typedef struct CheckpointStatsData CheckpointStatsData
 
typedef enum WALAvailability WALAvailability
 
typedef enum SessionBackupState SessionBackupState
 

Enumerations

enum  HotStandbyState { STANDBY_DISABLED, STANDBY_INITIALIZED, STANDBY_SNAPSHOT_PENDING, STANDBY_SNAPSHOT_READY }
 
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  RecoveryState { RECOVERY_STATE_CRASH = 0, RECOVERY_STATE_ARCHIVE, RECOVERY_STATE_DONE }
 
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, bool *use_existent, bool use_lock)
 
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)
 
bool RecoveryIsPaused (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, bool needtblspcmapfile)
 
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
 
bool InRecovery
 
HotStandbyState standbyState
 
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
 
bool 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
 
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 390 of file xlog.h.

Referenced by CancelBackup(), and StartupXLOG().

◆ CHECKPOINT_CAUSE_TIME

#define CHECKPOINT_CAUSE_TIME   0x0100 /* Elapsed time */

Definition at line 233 of file xlog.h.

Referenced by CheckpointerMain(), and LogCheckpointStart().

◆ CHECKPOINT_CAUSE_XLOG

#define CHECKPOINT_CAUSE_XLOG   0x0080 /* XLOG consumption */

Definition at line 232 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 222 of file xlog.h.

Referenced by BufferSync(), CheckpointerMain(), CreateCheckPoint(), LogCheckpointStart(), StartupXLOG(), 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 226 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 230 of file xlog.h.

Referenced by RequestCheckpoint().

◆ CHECKPOINT_WAIT

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

◆ InHotStandby

◆ PROMOTE_SIGNAL_FILE

#define PROMOTE_SIGNAL_FILE   "promote"

Definition at line 396 of file xlog.h.

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

◆ RECOVERY_SIGNAL_FILE

#define RECOVERY_SIGNAL_FILE   "recovery.signal"

Definition at line 387 of file xlog.h.

Referenced by exitArchiveRecovery(), and readRecoverySignalFile().

◆ STANDBY_SIGNAL_FILE

#define STANDBY_SIGNAL_FILE   "standby.signal"

Definition at line 388 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 393 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 /* include XID of top-level xact */

Definition at line 240 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 185 of file xlog.h.

Referenced by pgarch_ArchiverCopyLoop(), and ShutdownXLOG().

◆ XLogArchivingActive

◆ XLogArchivingAlways

Definition at line 183 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

◆ RecoveryState

◆ SessionBackupState

◆ WALAvailability

◆ WalLevel

typedef enum WalLevel WalLevel

Enumeration Type Documentation

◆ ArchiveMode

Enumerator
ARCHIVE_MODE_OFF 
ARCHIVE_MODE_ON 
ARCHIVE_MODE_ALWAYS 

Definition at line 153 of file xlog.h.

154 {
155  ARCHIVE_MODE_OFF = 0, /* disabled */
156  ARCHIVE_MODE_ON, /* enabled while server is running normally */
157  ARCHIVE_MODE_ALWAYS /* enabled always (even during recovery) */
158 } ArchiveMode;
ArchiveMode
Definition: xlog.h:153

◆ HotStandbyState

Enumerator
STANDBY_DISABLED 
STANDBY_INITIALIZED 
STANDBY_SNAPSHOT_PENDING 
STANDBY_SNAPSHOT_READY 

Definition at line 64 of file xlog.h.

◆ RecoveryState

Enumerator
RECOVERY_STATE_CRASH 
RECOVERY_STATE_ARCHIVE 
RECOVERY_STATE_DONE 

Definition at line 170 of file xlog.h.

171 {
172  RECOVERY_STATE_CRASH = 0, /* crash recovery */
173  RECOVERY_STATE_ARCHIVE, /* archive recovery */
174  RECOVERY_STATE_DONE /* currently in production */
175 } RecoveryState;
RecoveryState
Definition: xlog.h:170

◆ RecoveryTargetTimeLineGoal

Enumerator
RECOVERY_TARGET_TIMELINE_CONTROLFILE 
RECOVERY_TARGET_TIMELINE_LATEST 
RECOVERY_TARGET_TIMELINE_NUMERIC 

Definition at line 93 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 80 of file xlog.h.

◆ SessionBackupState

Enumerator
SESSION_BACKUP_NONE 
SESSION_BACKUP_EXCLUSIVE 
SESSION_BACKUP_NON_EXCLUSIVE 

Definition at line 369 of file xlog.h.

◆ WALAvailability

Enumerator
WALAVAIL_INVALID_LSN 
WALAVAIL_RESERVED 
WALAVAIL_EXTENDED 
WALAVAIL_UNRESERVED 
WALAVAIL_REMOVED 

Definition at line 271 of file xlog.h.

272 {
273  WALAVAIL_INVALID_LSN, /* parameter error */
274  WALAVAIL_RESERVED, /* WAL segment is within max_wal_size */
275  WALAVAIL_EXTENDED, /* WAL segment is reserved by a slot or
276  * wal_keep_size */
277  WALAVAIL_UNRESERVED, /* no longer reserved, but not removed yet */
278  WALAVAIL_REMOVED /* WAL segment has been removed */
WALAvailability
Definition: xlog.h:271

◆ WalLevel

enum WalLevel
Enumerator
WAL_LEVEL_MINIMAL 
WAL_LEVEL_REPLICA 
WAL_LEVEL_LOGICAL 

Definition at line 162 of file xlog.h.

Function Documentation

◆ assign_checkpoint_completion_target()

void assign_checkpoint_completion_target ( double  newval,
void *  extra 
)

Definition at line 2343 of file xlog.c.

References CalculateCheckpointSegments(), CheckPointCompletionTarget, and newval.

2344 {
2347 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2307
#define newval
double CheckPointCompletionTarget
Definition: checkpointer.c:148

◆ assign_max_wal_size()

void assign_max_wal_size ( int  newval,
void *  extra 
)

Definition at line 2336 of file xlog.c.

References CalculateCheckpointSegments(), max_wal_size_mb, and newval.

2337 {
2340 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2307
int max_wal_size_mb
Definition: xlog.c:91
#define newval

◆ BootStrapXLOG()

void BootStrapXLOG ( void  )

Definition at line 5224 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, FirstBootstrapObjectId, FirstMultiXactId, FirstNormalTransactionId, CheckPoint::fullPageWrites, fullPageWrites, FullTransactionIdFromEpochAndXid(), gettimeofday(), INIT_CRC32C, InitControlFile(), InvalidTransactionId, 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 AuxiliaryProcessMain().

5225 {
5226  CheckPoint checkPoint;
5227  char *buffer;
5228  XLogPageHeader page;
5229  XLogLongPageHeader longpage;
5230  XLogRecord *record;
5231  char *recptr;
5232  bool use_existent;
5233  uint64 sysidentifier;
5234  struct timeval tv;
5235  pg_crc32c crc;
5236 
5237  /*
5238  * Select a hopefully-unique system identifier code for this installation.
5239  * We use the result of gettimeofday(), including the fractional seconds
5240  * field, as being about as unique as we can easily get. (Think not to
5241  * use random(), since it hasn't been seeded and there's no portable way
5242  * to seed it other than the system clock value...) The upper half of the
5243  * uint64 value is just the tv_sec part, while the lower half contains the
5244  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
5245  * PID for a little extra uniqueness. A person knowing this encoding can
5246  * determine the initialization time of the installation, which could
5247  * perhaps be useful sometimes.
5248  */
5249  gettimeofday(&tv, NULL);
5250  sysidentifier = ((uint64) tv.tv_sec) << 32;
5251  sysidentifier |= ((uint64) tv.tv_usec) << 12;
5252  sysidentifier |= getpid() & 0xFFF;
5253 
5254  /* First timeline ID is always 1 */
5255  ThisTimeLineID = 1;
5256 
5257  /* page buffer must be aligned suitably for O_DIRECT */
5258  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5259  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
5260  memset(page, 0, XLOG_BLCKSZ);
5261 
5262  /*
5263  * Set up information for the initial checkpoint record
5264  *
5265  * The initial checkpoint record is written to the beginning of the WAL
5266  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5267  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5268  */
5269  checkPoint.redo = wal_segment_size + SizeOfXLogLongPHD;
5270  checkPoint.ThisTimeLineID = ThisTimeLineID;
5271  checkPoint.PrevTimeLineID = ThisTimeLineID;
5272  checkPoint.fullPageWrites = fullPageWrites;
5273  checkPoint.nextXid =
5275  checkPoint.nextOid = FirstBootstrapObjectId;
5276  checkPoint.nextMulti = FirstMultiXactId;
5277  checkPoint.nextMultiOffset = 0;
5278  checkPoint.oldestXid = FirstNormalTransactionId;
5279  checkPoint.oldestXidDB = TemplateDbOid;
5280  checkPoint.oldestMulti = FirstMultiXactId;
5281  checkPoint.oldestMultiDB = TemplateDbOid;
5284  checkPoint.time = (pg_time_t) time(NULL);
5286 
5287  ShmemVariableCache->nextXid = checkPoint.nextXid;
5288  ShmemVariableCache->nextOid = checkPoint.nextOid;
5290  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5291  AdvanceOldestClogXid(checkPoint.oldestXid);
5292  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5293  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5295 
5296  /* Set up the XLOG page header */
5297  page->xlp_magic = XLOG_PAGE_MAGIC;
5298  page->xlp_info = XLP_LONG_HEADER;
5299  page->xlp_tli = ThisTimeLineID;
5301  longpage = (XLogLongPageHeader) page;
5302  longpage->xlp_sysid = sysidentifier;
5303  longpage->xlp_seg_size = wal_segment_size;
5304  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5305 
5306  /* Insert the initial checkpoint record */
5307  recptr = ((char *) page + SizeOfXLogLongPHD);
5308  record = (XLogRecord *) recptr;
5309  record->xl_prev = 0;
5310  record->xl_xid = InvalidTransactionId;
5311  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5313  record->xl_rmid = RM_XLOG_ID;
5314  recptr += SizeOfXLogRecord;
5315  /* fill the XLogRecordDataHeaderShort struct */
5316  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5317  *(recptr++) = sizeof(checkPoint);
5318  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5319  recptr += sizeof(checkPoint);
5320  Assert(recptr - (char *) record == record->xl_tot_len);
5321 
5322  INIT_CRC32C(crc);
5323  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5324  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5325  FIN_CRC32C(crc);
5326  record->xl_crc = crc;
5327 
5328  /* Create first XLOG segment file */
5329  use_existent = false;
5330  openLogFile = XLogFileInit(1, &use_existent, false);
5331 
5332  /*
5333  * We needn't bother with Reserve/ReleaseExternalFD here, since we'll
5334  * close the file again in a moment.
5335  */
5336 
5337  /* Write the first page with the initial record */
5338  errno = 0;
5340  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5341  {
5342  /* if write didn't set errno, assume problem is no disk space */
5343  if (errno == 0)
5344  errno = ENOSPC;
5345  ereport(PANIC,
5347  errmsg("could not write bootstrap write-ahead log file: %m")));
5348  }
5350 
5352  if (pg_fsync(openLogFile) != 0)
5353  ereport(PANIC,
5355  errmsg("could not fsync bootstrap write-ahead log file: %m")));
5357 
5358  if (close(openLogFile) != 0)
5359  ereport(PANIC,
5361  errmsg("could not close bootstrap write-ahead log file: %m")));
5362 
5363  openLogFile = -1;
5364 
5365  /* Now create pg_control */
5366  InitControlFile(sysidentifier);
5367  ControlFile->time = checkPoint.time;
5368  ControlFile->checkPoint = checkPoint.redo;
5369  ControlFile->checkPointCopy = checkPoint;
5370 
5371  /* some additional ControlFile fields are set in WriteControlFile() */
5372  WriteControlFile();
5373 
5374  /* Bootstrap the commit log, too */
5375  BootStrapCLOG();
5379 
5380  pfree(buffer);
5381 
5382  /*
5383  * Force control file to be read - in contrast to normal processing we'd
5384  * otherwise never run the checks and GUC related initializations therein.
5385  */
5386  ReadControlFile();
5387 }
static void WriteControlFile(void)
Definition: xlog.c:4641
#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
int wal_segment_size
Definition: xlog.c:118
pg_time_t time
Definition: pg_control.h:128
void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact)
Definition: commit_ts.c:893
uint32 oidCount
Definition: transam.h:208
#define write(a, b, c)
Definition: win32.h:14
#define SizeOfXLogRecordDataHeaderShort
Definition: xlogrecord.h:200
uint32 pg_crc32c
Definition: pg_crc32c.h:38
TransactionId oldestActiveXid
Definition: pg_control.h:63
int XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
Definition: xlog.c:3267
void BootStrapMultiXact(void)
Definition: multixact.c:1891
MultiXactId oldestMulti
Definition: pg_control.h:49
TimeLineID PrevTimeLineID
Definition: pg_control.h:40
static void InitControlFile(uint64 sysidentifier)
Definition: xlog.c:4606
RmgrId xl_rmid
Definition: xlogrecord.h:47
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:54
CheckPoint checkPointCopy
Definition: pg_control.h:131
TransactionId oldestXid
Definition: pg_control.h:47
FullTransactionId nextXid
Definition: transam.h:213
pg_time_t time
Definition: pg_control.h:51
#define PANIC
Definition: elog.h:55
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:71
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:1057
#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:4732
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
int errcode_for_file_access(void)
Definition: elog.c:727
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
#define FirstBootstrapObjectId
Definition: transam.h:189
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1512
#define FirstMultiXactId
Definition: multixact.h:25
TimeLineID xlp_tli
Definition: xlog_internal.h:40
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
TransactionId newestCommitTsXid
Definition: pg_control.h:54
Oid oldestMultiDB
Definition: pg_control.h:50
static int openLogFile
Definition: xlog.c:809
static ControlFileData * ControlFile
Definition: xlog.c:748
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2210
TimeLineID ThisTimeLineID
Definition: xlog.c:193
Oid nextOid
Definition: pg_control.h:44
#define ereport(elevel,...)
Definition: elog.h:155
#define TYPEALIGN(ALIGNVAL, LEN)
Definition: c.h:738
bool fullPageWrites
Definition: pg_control.h:42
void BootStrapCLOG(void)
Definition: clog.c:707
#define Assert(condition)
Definition: c.h:792
#define XLP_LONG_HEADER
Definition: xlog_internal.h:76
Oid oldestXidDB
Definition: pg_control.h:48
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1488
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 FullTransactionId FullTransactionIdFromEpochAndXid(uint32 epoch, TransactionId xid)
Definition: transam.h:71
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:223
TransactionId xl_xid
Definition: xlogrecord.h:44
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:915
int pg_fsync(int fd)
Definition: fd.c:347
#define close(a)
Definition: win32.h:12
void BootStrapCommitTs(void)
Definition: commit_ts.c:586
#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:129
XLogRecPtr redo
Definition: pg_control.h:37
#define offsetof(type, field)
Definition: c.h:715
FullTransactionId nextXid
Definition: pg_control.h:43
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:69
void MultiXactSetNextMXact(MultiXactId nextMulti, MultiXactOffset nextMultiOffset)
Definition: multixact.c:2176

◆ CalculateMaxmumSafeLSN()

XLogRecPtr CalculateMaxmumSafeLSN ( void  )

◆ CheckPromoteSignal()

bool CheckPromoteSignal ( void  )

Definition at line 12798 of file xlog.c.

References PROMOTE_SIGNAL_FILE, and stat.

Referenced by CheckForStandbyTrigger(), and sigusr1_handler().

12799 {
12800  struct stat stat_buf;
12801 
12802  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0)
12803  return true;
12804 
12805  return false;
12806 }
#define PROMOTE_SIGNAL_FILE
Definition: xlog.h:396
struct stat stat_buf
Definition: pg_standby.c:100
#define stat
Definition: win32_port.h:275

◆ CheckXLogRemoved()

void CheckXLogRemoved ( XLogSegNo  segno,
TimeLineID  tli 
)

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

3957 {
3958  int save_errno = errno;
3959  XLogSegNo lastRemovedSegNo;
3960 
3962  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3964 
3965  if (segno <= lastRemovedSegNo)
3966  {
3967  char filename[MAXFNAMELEN];
3968 
3969  XLogFileName(filename, tli, segno, wal_segment_size);
3970  errno = save_errno;
3971  ereport(ERROR,
3973  errmsg("requested WAL segment %s has already been removed",
3974  filename)));
3975  }
3976  errno = save_errno;
3977 }
int wal_segment_size
Definition: xlog.c:118
slock_t info_lck
Definition: xlog.c:737
XLogSegNo lastRemovedSegNo
Definition: xlog.c:610
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define ERROR
Definition: elog.h:45
uint64 XLogSegNo
Definition: xlogdefs.h:41
int errcode_for_file_access(void)
Definition: elog.c:727
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
#define ereport(elevel,...)
Definition: elog.h:155
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static XLogCtlData * XLogCtl
Definition: xlog.c:740
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ CreateCheckPoint()

void CreateCheckPoint ( int  flags)

Definition at line 8830 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(), 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(), ShutdownXLOG(), and StartupXLOG().

8831 {
8832  bool shutdown;
8833  CheckPoint checkPoint;
8834  XLogRecPtr recptr;
8835  XLogSegNo _logSegNo;
8837  uint32 freespace;
8838  XLogRecPtr PriorRedoPtr;
8839  XLogRecPtr curInsert;
8840  XLogRecPtr last_important_lsn;
8841  VirtualTransactionId *vxids;
8842  int nvxids;
8843 
8844  /*
8845  * An end-of-recovery checkpoint is really a shutdown checkpoint, just
8846  * issued at a different time.
8847  */
8849  shutdown = true;
8850  else
8851  shutdown = false;
8852 
8853  /* sanity check */
8854  if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
8855  elog(ERROR, "can't create a checkpoint during recovery");
8856 
8857  /*
8858  * Initialize InitXLogInsert working areas before entering the critical
8859  * section. Normally, this is done by the first call to
8860  * RecoveryInProgress() or LocalSetXLogInsertAllowed(), but when creating
8861  * an end-of-recovery checkpoint, the LocalSetXLogInsertAllowed call is
8862  * done below in a critical section, and InitXLogInsert cannot be called
8863  * in a critical section.
8864  */
8865  InitXLogInsert();
8866 
8867  /*
8868  * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
8869  * (This is just pro forma, since in the present system structure there is
8870  * only one process that is allowed to issue checkpoints at any given
8871  * time.)
8872  */
8873  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
8874 
8875  /*
8876  * Prepare to accumulate statistics.
8877  *
8878  * Note: because it is possible for log_checkpoints to change while a
8879  * checkpoint proceeds, we always accumulate stats, even if
8880  * log_checkpoints is currently off.
8881  */
8882  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
8884 
8885  /*
8886  * Use a critical section to force system panic if we have trouble.
8887  */
8889 
8890  if (shutdown)
8891  {
8892  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8894  ControlFile->time = (pg_time_t) time(NULL);
8896  LWLockRelease(ControlFileLock);
8897  }
8898 
8899  /*
8900  * Let smgr prepare for checkpoint; this has to happen before we determine
8901  * the REDO pointer. Note that smgr must not do anything that'd have to
8902  * be undone if we decide no checkpoint is needed.
8903  */
8905 
8906  /* Begin filling in the checkpoint WAL record */
8907  MemSet(&checkPoint, 0, sizeof(checkPoint));
8908  checkPoint.time = (pg_time_t) time(NULL);
8909 
8910  /*
8911  * For Hot Standby, derive the oldestActiveXid before we fix the redo
8912  * pointer. This allows us to begin accumulating changes to assemble our
8913  * starting snapshot of locks and transactions.
8914  */
8915  if (!shutdown && XLogStandbyInfoActive())
8917  else
8919 
8920  /*
8921  * Get location of last important record before acquiring insert locks (as
8922  * GetLastImportantRecPtr() also locks WAL locks).
8923  */
8924  last_important_lsn = GetLastImportantRecPtr();
8925 
8926  /*
8927  * We must block concurrent insertions while examining insert state to
8928  * determine the checkpoint REDO pointer.
8929  */
8931  curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
8932 
8933  /*
8934  * If this isn't a shutdown or forced checkpoint, and if there has been no
8935  * WAL activity requiring a checkpoint, skip it. The idea here is to
8936  * avoid inserting duplicate checkpoints when the system is idle.
8937  */
8938  if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
8939  CHECKPOINT_FORCE)) == 0)
8940  {
8941  if (last_important_lsn == ControlFile->checkPoint)
8942  {
8944  LWLockRelease(CheckpointLock);
8945  END_CRIT_SECTION();
8946  ereport(DEBUG1,
8947  (errmsg("checkpoint skipped because system is idle")));
8948  return;
8949  }
8950  }
8951 
8952  /*
8953  * An end-of-recovery checkpoint is created before anyone is allowed to
8954  * write WAL. To allow us to write the checkpoint record, temporarily
8955  * enable XLogInsertAllowed. (This also ensures ThisTimeLineID is
8956  * initialized, which we need here and in AdvanceXLInsertBuffer.)
8957  */
8958  if (flags & CHECKPOINT_END_OF_RECOVERY)
8960 
8961  checkPoint.ThisTimeLineID = ThisTimeLineID;
8962  if (flags & CHECKPOINT_END_OF_RECOVERY)
8963  checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8964  else
8965  checkPoint.PrevTimeLineID = ThisTimeLineID;
8966 
8967  checkPoint.fullPageWrites = Insert->fullPageWrites;
8968 
8969  /*
8970  * Compute new REDO record ptr = location of next XLOG record.
8971  *
8972  * NB: this is NOT necessarily where the checkpoint record itself will be,
8973  * since other backends may insert more XLOG records while we're off doing
8974  * the buffer flush work. Those XLOG records are logically after the
8975  * checkpoint, even though physically before it. Got that?
8976  */
8977  freespace = INSERT_FREESPACE(curInsert);
8978  if (freespace == 0)
8979  {
8980  if (XLogSegmentOffset(curInsert, wal_segment_size) == 0)
8981  curInsert += SizeOfXLogLongPHD;
8982  else
8983  curInsert += SizeOfXLogShortPHD;
8984  }
8985  checkPoint.redo = curInsert;
8986 
8987  /*
8988  * Here we update the shared RedoRecPtr for future XLogInsert calls; this
8989  * must be done while holding all the insertion locks.
8990  *
8991  * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
8992  * pointing past where it really needs to point. This is okay; the only
8993  * consequence is that XLogInsert might back up whole buffers that it
8994  * didn't really need to. We can't postpone advancing RedoRecPtr because
8995  * XLogInserts that happen while we are dumping buffers must assume that
8996  * their buffer changes are not included in the checkpoint.
8997  */
8998  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
8999 
9000  /*
9001  * Now we can release the WAL insertion locks, allowing other xacts to
9002  * proceed while we are flushing disk buffers.
9003  */
9005 
9006  /* Update the info_lck-protected copy of RedoRecPtr as well */
9008  XLogCtl->RedoRecPtr = checkPoint.redo;
9010 
9011  /*
9012  * If enabled, log checkpoint start. We postpone this until now so as not
9013  * to log anything if we decided to skip the checkpoint.
9014  */
9015  if (log_checkpoints)
9016  LogCheckpointStart(flags, false);
9017 
9018  /* Update the process title */
9019  update_checkpoint_display(flags, false, false);
9020 
9021  TRACE_POSTGRESQL_CHECKPOINT_START(flags);
9022 
9023  /*
9024  * Get the other info we need for the checkpoint record.
9025  *
9026  * We don't need to save oldestClogXid in the checkpoint, it only matters
9027  * for the short period in which clog is being truncated, and if we crash
9028  * during that we'll redo the clog truncation and fix up oldestClogXid
9029  * there.
9030  */
9031  LWLockAcquire(XidGenLock, LW_SHARED);
9032  checkPoint.nextXid = ShmemVariableCache->nextXid;
9033  checkPoint.oldestXid = ShmemVariableCache->oldestXid;
9035  LWLockRelease(XidGenLock);
9036 
9037  LWLockAcquire(CommitTsLock, LW_SHARED);
9040  LWLockRelease(CommitTsLock);
9041 
9042  LWLockAcquire(OidGenLock, LW_SHARED);
9043  checkPoint.nextOid = ShmemVariableCache->nextOid;
9044  if (!shutdown)
9045  checkPoint.nextOid += ShmemVariableCache->oidCount;
9046  LWLockRelease(OidGenLock);
9047 
9048  MultiXactGetCheckptMulti(shutdown,
9049  &checkPoint.nextMulti,
9050  &checkPoint.nextMultiOffset,
9051  &checkPoint.oldestMulti,
9052  &checkPoint.oldestMultiDB);
9053 
9054  /*
9055  * Having constructed the checkpoint record, ensure all shmem disk buffers
9056  * and commit-log buffers are flushed to disk.
9057  *
9058  * This I/O could fail for various reasons. If so, we will fail to
9059  * complete the checkpoint, but there is no reason to force a system
9060  * panic. Accordingly, exit critical section while doing it.
9061  */
9062  END_CRIT_SECTION();
9063 
9064  /*
9065  * In some cases there are groups of actions that must all occur on one
9066  * side or the other of a checkpoint record. Before flushing the
9067  * checkpoint record we must explicitly wait for any backend currently
9068  * performing those groups of actions.
9069  *
9070  * One example is end of transaction, so we must wait for any transactions
9071  * that are currently in commit critical sections. If an xact inserted
9072  * its commit record into XLOG just before the REDO point, then a crash
9073  * restart from the REDO point would not replay that record, which means
9074  * that our flushing had better include the xact's update of pg_xact. So
9075  * we wait till he's out of his commit critical section before proceeding.
9076  * See notes in RecordTransactionCommit().
9077  *
9078  * Because we've already released the insertion locks, this test is a bit
9079  * fuzzy: it is possible that we will wait for xacts we didn't really need
9080  * to wait for. But the delay should be short and it seems better to make
9081  * checkpoint take a bit longer than to hold off insertions longer than
9082  * necessary. (In fact, the whole reason we have this issue is that xact.c
9083  * does commit record XLOG insertion and clog update as two separate steps
9084  * protected by different locks, but again that seems best on grounds of
9085  * minimizing lock contention.)
9086  *
9087  * A transaction that has not yet set delayChkpt when we look cannot be at
9088  * risk, since he's not inserted his commit record yet; and one that's
9089  * already cleared it is not at risk either, since he's done fixing clog
9090  * and we will correctly flush the update below. So we cannot miss any
9091  * xacts we need to wait for.
9092  */
9093  vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
9094  if (nvxids > 0)
9095  {
9096  do
9097  {
9098  pg_usleep(10000L); /* wait for 10 msec */
9099  } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
9100  }
9101  pfree(vxids);
9102 
9103  CheckPointGuts(checkPoint.redo, flags);
9104 
9105  /*
9106  * Take a snapshot of running transactions and write this to WAL. This
9107  * allows us to reconstruct the state of running transactions during
9108  * archive recovery, if required. Skip, if this info disabled.
9109  *
9110  * If we are shutting down, or Startup process is completing crash
9111  * recovery we don't need to write running xact data.
9112  */
9113  if (!shutdown && XLogStandbyInfoActive())
9115 
9117 
9118  /*
9119  * Now insert the checkpoint record into XLOG.
9120  */
9121  XLogBeginInsert();
9122  XLogRegisterData((char *) (&checkPoint), sizeof(checkPoint));
9123  recptr = XLogInsert(RM_XLOG_ID,
9124  shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
9126 
9127  XLogFlush(recptr);
9128 
9129  /*
9130  * We mustn't write any new WAL after a shutdown checkpoint, or it will be
9131  * overwritten at next startup. No-one should even try, this just allows
9132  * sanity-checking. In the case of an end-of-recovery checkpoint, we want
9133  * to just temporarily disable writing until the system has exited
9134  * recovery.
9135  */
9136  if (shutdown)
9137  {
9138  if (flags & CHECKPOINT_END_OF_RECOVERY)
9139  LocalXLogInsertAllowed = -1; /* return to "check" state */
9140  else
9141  LocalXLogInsertAllowed = 0; /* never again write WAL */
9142  }
9143 
9144  /*
9145  * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
9146  * = end of actual checkpoint record.
9147  */
9148  if (shutdown && checkPoint.redo != ProcLastRecPtr)
9149  ereport(PANIC,
9150  (errmsg("concurrent write-ahead log activity while database system is shutting down")));
9151 
9152  /*
9153  * Remember the prior checkpoint's redo ptr for
9154  * UpdateCheckPointDistanceEstimate()
9155  */
9156  PriorRedoPtr = ControlFile->checkPointCopy.redo;
9157 
9158  /*
9159  * Update the control file.
9160  */
9161  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9162  if (shutdown)
9165  ControlFile->checkPointCopy = checkPoint;
9166  ControlFile->time = (pg_time_t) time(NULL);
9167  /* crash recovery should always recover to the end of WAL */
9170 
9171  /*
9172  * Persist unloggedLSN value. It's reset on crash recovery, so this goes
9173  * unused on non-shutdown checkpoints, but seems useful to store it always
9174  * for debugging purposes.
9175  */
9179 
9181  LWLockRelease(ControlFileLock);
9182 
9183  /* Update shared-memory copy of checkpoint XID/epoch */
9185  XLogCtl->ckptFullXid = checkPoint.nextXid;
9187 
9188  /*
9189  * We are now done with critical updates; no need for system panic if we
9190  * have trouble while fooling with old log segments.
9191  */
9192  END_CRIT_SECTION();
9193 
9194  /*
9195  * Let smgr do post-checkpoint cleanup (eg, deleting old files).
9196  */
9198 
9199  /*
9200  * Update the average distance between checkpoints if the prior checkpoint
9201  * exists.
9202  */
9203  if (PriorRedoPtr != InvalidXLogRecPtr)
9205 
9206  /*
9207  * Delete old log files, those no longer needed for last checkpoint to
9208  * prevent the disk holding the xlog from growing full.
9209  */
9211  KeepLogSeg(recptr, &_logSegNo);
9213  _logSegNo--;
9214  RemoveOldXlogFiles(_logSegNo, RedoRecPtr, recptr);
9215 
9216  /*
9217  * Make more log segments if needed. (Do this after recycling old log
9218  * segments, since that may supply some of the needed files.)
9219  */
9220  if (!shutdown)
9221  PreallocXlogFiles(recptr);
9222 
9223  /*
9224  * Truncate pg_subtrans if possible. We can throw away all data before
9225  * the oldest XMIN of any running transaction. No future transaction will
9226  * attempt to reference any pg_subtrans entry older than that (see Asserts
9227  * in subtrans.c). During recovery, though, we mustn't do this because
9228  * StartupSUBTRANS hasn't been called yet.
9229  */
9230  if (!RecoveryInProgress())
9232 
9233  /* Real work is done, but log and update stats before releasing lock. */
9234  LogCheckpointEnd(false);
9235 
9236  /* Reset the process title */
9237  update_checkpoint_display(flags, false, true);
9238 
9239  TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
9240  NBuffers,
9244 
9245  LWLockRelease(CheckpointLock);
9246 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8518
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8735
static int LocalXLogInsertAllowed
Definition: xlog.c:254
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:118
pg_time_t time
Definition: pg_control.h:128
#define XLOG_CHECKPOINT_ONLINE
Definition: pg_control.h:68
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
uint32 oidCount
Definition: transam.h:208
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:2010
XLogRecPtr unloggedLSN
Definition: xlog.c:613
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:361
TransactionId oldestActiveXid
Definition: pg_control.h:63
void InitXLogInsert(void)
Definition: xloginsert.c:1197
TimestampTz ckpt_start_t
Definition: xlog.h:246
slock_t info_lck
Definition: xlog.c:737
#define END_CRIT_SECTION()
Definition: miscadmin.h:135
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids)
Definition: procarray.c:2946
MultiXactId oldestMulti
Definition: pg_control.h:49
TimeLineID PrevTimeLineID
Definition: xlog.c:654
TimeLineID PrevTimeLineID
Definition: pg_control.h:40
#define START_CRIT_SECTION()
Definition: miscadmin.h:133
int ckpt_segs_recycled
Definition: xlog.h:256
TransactionId oldestXid
Definition: transam.h:215
#define MemSet(start, val, len)
Definition: c.h:996
void MultiXactGetCheckptMulti(bool is_shutdown, MultiXactId *nextMulti, MultiXactOffset *nextMultiOffset, MultiXactId *oldestMulti, Oid *oldestMultiDB)
Definition: multixact.c:2130
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:9307
CheckPoint checkPointCopy
Definition: pg_control.h:131
XLogCtlInsert Insert
Definition: xlog.c:601
TransactionId oldestXid
Definition: pg_control.h:47
bool RecoveryInProgress(void)
Definition: xlog.c:8148
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:338
FullTransactionId nextXid
Definition: transam.h:213
pg_time_t time
Definition: pg_control.h:51
#define PANIC
Definition: elog.h:55
bool fullPageWrites
Definition: xlog.c:576
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2860
static void update_checkpoint_display(int flags, bool restartpoint, bool reset)
Definition: xlog.c:8773
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
#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:4932
TransactionId oldestCommitTsXid
Definition: pg_control.h:52
void pfree(void *pointer)
Definition: mcxt.c:1057
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1155
#define ERROR
Definition: elog.h:45
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8643
static XLogRecPtr RedoRecPtr
Definition: xlog.c:375
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
XLogRecPtr unloggedLSN
Definition: pg_control.h:133
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3923
uint64 XLogSegNo
Definition: xlogdefs.h:41
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:222
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
uint64 CurrBytePos
Definition: xlog.c:551
unsigned int uint32
Definition: c.h:429
XLogRecPtr RedoRecPtr
Definition: xlog.c:605
int ckpt_segs_removed
Definition: xlog.h:255
#define CHECKPOINT_FORCE
Definition: xlog.h:225
#define INSERT_FREESPACE(endptr)
Definition: xlog.c:754
TransactionId oldestCommitTsXid
Definition: transam.h:225
static void Insert(File file)
Definition: fd.c:1203
int ckpt_bufs_written
Definition: xlog.h:252
static void LocalSetXLogInsertAllowed(void)
Definition: xlog.c:8292
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:330
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:422
TransactionId newestCommitTsXid
Definition: pg_control.h:54
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9738
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
Oid oldestMultiDB
Definition: pg_control.h:50
FullTransactionId ckptFullXid
Definition: xlog.c:606
#define XLogStandbyInfoActive()
Definition: xlog.h:205
static ControlFileData * ControlFile
Definition: xlog.c:748
TimeLineID ThisTimeLineID
Definition: xlog.c:193
Oid nextOid
Definition: pg_control.h:44
#define ereport(elevel,...)
Definition: elog.h:155
bool fullPageWrites
Definition: pg_control.h:42
uint64 XLogRecPtr
Definition: xlogdefs.h:21
Oid oldestXidDB
Definition: pg_control.h:48
TransactionId newestCommitTsXid
Definition: transam.h:226
CheckpointStatsData CheckpointStats
Definition: xlog.c:187
#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:740
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1206
TransactionId GetOldestTransactionIdConsideredRunning(void)
Definition: procarray.c:1937
int ckpt_segs_added
Definition: xlog.h:254
slock_t ulsn_lck
Definition: xlog.c:614
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
int errmsg(const char *fmt,...)
Definition: elog.c:915
void InvalidateObsoleteReplicationSlots(XLogSegNo oldestSegno)
Definition: slot.c:1155
#define elog(elevel,...)
Definition: elog.h:228
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr)
Definition: xlog.c:4054
void SyncPostCheckpoint(void)
Definition: sync.c:195
TransactionId GetOldestActiveTransactionId(void)
Definition: procarray.c:2785
int NBuffers
Definition: globals.c:133
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids)
Definition: procarray.c:2990
void XLogBeginInsert(void)
Definition: xloginsert.c:123
XLogRecPtr RedoRecPtr
Definition: xlog.c:574
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:37
static void LogCheckpointStart(int flags, bool restartpoint)
Definition: xlog.c:8611
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:221
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
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 9389 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(), 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(), 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().

9390 {
9391  XLogRecPtr lastCheckPointRecPtr;
9392  XLogRecPtr lastCheckPointEndPtr;
9393  CheckPoint lastCheckPoint;
9394  XLogRecPtr PriorRedoPtr;
9395  XLogRecPtr receivePtr;
9396  XLogRecPtr replayPtr;
9397  TimeLineID replayTLI;
9398  XLogRecPtr endptr;
9399  XLogSegNo _logSegNo;
9400  TimestampTz xtime;
9401 
9402  /*
9403  * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
9404  * happens at a time.
9405  */
9406  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
9407 
9408  /* Get a local copy of the last safe checkpoint record. */
9410  lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
9411  lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
9412  lastCheckPoint = XLogCtl->lastCheckPoint;
9414 
9415  /*
9416  * Check that we're still in recovery mode. It's ok if we exit recovery
9417  * mode after this check, the restart point is valid anyway.
9418  */
9419  if (!RecoveryInProgress())
9420  {
9421  ereport(DEBUG2,
9422  (errmsg("skipping restartpoint, recovery has already ended")));
9423  LWLockRelease(CheckpointLock);
9424  return false;
9425  }
9426 
9427  /*
9428  * If the last checkpoint record we've replayed is already our last
9429  * restartpoint, we can't perform a new restart point. We still update
9430  * minRecoveryPoint in that case, so that if this is a shutdown restart
9431  * point, we won't start up earlier than before. That's not strictly
9432  * necessary, but when hot standby is enabled, it would be rather weird if
9433  * the database opened up for read-only connections at a point-in-time
9434  * before the last shutdown. Such time travel is still possible in case of
9435  * immediate shutdown, though.
9436  *
9437  * We don't explicitly advance minRecoveryPoint when we do create a
9438  * restartpoint. It's assumed that flushing the buffers will do that as a
9439  * side-effect.
9440  */
9441  if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
9442  lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
9443  {
9444  ereport(DEBUG2,
9445  (errmsg("skipping restartpoint, already performed at %X/%X",
9446  (uint32) (lastCheckPoint.redo >> 32),
9447  (uint32) lastCheckPoint.redo)));
9448 
9450  if (flags & CHECKPOINT_IS_SHUTDOWN)
9451  {
9452  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9454  ControlFile->time = (pg_time_t) time(NULL);
9456  LWLockRelease(ControlFileLock);
9457  }
9458  LWLockRelease(CheckpointLock);
9459  return false;
9460  }
9461 
9462  /*
9463  * Update the shared RedoRecPtr so that the startup process can calculate
9464  * the number of segments replayed since last restartpoint, and request a
9465  * restartpoint if it exceeds CheckPointSegments.
9466  *
9467  * Like in CreateCheckPoint(), hold off insertions to update it, although
9468  * during recovery this is just pro forma, because no WAL insertions are
9469  * happening.
9470  */
9472  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
9474 
9475  /* Also update the info_lck-protected copy */
9477  XLogCtl->RedoRecPtr = lastCheckPoint.redo;
9479 
9480  /*
9481  * Prepare to accumulate statistics.
9482  *
9483  * Note: because it is possible for log_checkpoints to change while a
9484  * checkpoint proceeds, we always accumulate stats, even if
9485  * log_checkpoints is currently off.
9486  */
9487  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
9489 
9490  if (log_checkpoints)
9491  LogCheckpointStart(flags, true);
9492 
9493  /* Update the process title */
9494  update_checkpoint_display(flags, true, false);
9495 
9496  CheckPointGuts(lastCheckPoint.redo, flags);
9497 
9498  /*
9499  * Remember the prior checkpoint's redo ptr for
9500  * UpdateCheckPointDistanceEstimate()
9501  */
9502  PriorRedoPtr = ControlFile->checkPointCopy.redo;
9503 
9504  /*
9505  * Update pg_control, using current time. Check that it still shows
9506  * DB_IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
9507  * this is a quick hack to make sure nothing really bad happens if somehow
9508  * we get here after the end-of-recovery checkpoint.
9509  */
9510  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9512  ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
9513  {
9514  ControlFile->checkPoint = lastCheckPointRecPtr;
9515  ControlFile->checkPointCopy = lastCheckPoint;
9516  ControlFile->time = (pg_time_t) time(NULL);
9517 
9518  /*
9519  * Ensure minRecoveryPoint is past the checkpoint record. Normally,
9520  * this will have happened already while writing out dirty buffers,
9521  * but not necessarily - e.g. because no buffers were dirtied. We do
9522  * this because a non-exclusive base backup uses minRecoveryPoint to
9523  * determine which WAL files must be included in the backup, and the
9524  * file (or files) containing the checkpoint record must be included,
9525  * at a minimum. Note that for an ordinary restart of recovery there's
9526  * no value in having the minimum recovery point any earlier than this
9527  * anyway, because redo will begin just after the checkpoint record.
9528  */
9529  if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
9530  {
9531  ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
9533 
9534  /* update local copy */
9537  }
9538  if (flags & CHECKPOINT_IS_SHUTDOWN)
9541  }
9542  LWLockRelease(ControlFileLock);
9543 
9544  /*
9545  * Update the average distance between checkpoints/restartpoints if the
9546  * prior checkpoint exists.
9547  */
9548  if (PriorRedoPtr != InvalidXLogRecPtr)
9550 
9551  /*
9552  * Delete old log files, those no longer needed for last restartpoint to
9553  * prevent the disk holding the xlog from growing full.
9554  */
9556 
9557  /*
9558  * Retreat _logSegNo using the current end of xlog replayed or received,
9559  * whichever is later.
9560  */
9561  receivePtr = GetWalRcvFlushRecPtr(NULL, NULL);
9562  replayPtr = GetXLogReplayRecPtr(&replayTLI);
9563  endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
9564  KeepLogSeg(endptr, &_logSegNo);
9566  _logSegNo--;
9567 
9568  /*
9569  * Try to recycle segments on a useful timeline. If we've been promoted
9570  * since the beginning of this restartpoint, use the new timeline chosen
9571  * at end of recovery (RecoveryInProgress() sets ThisTimeLineID in that
9572  * case). If we're still in recovery, use the timeline we're currently
9573  * replaying.
9574  *
9575  * There is no guarantee that the WAL segments will be useful on the
9576  * current timeline; if recovery proceeds to a new timeline right after
9577  * this, the pre-allocated WAL segments on this timeline will not be used,
9578  * and will go wasted until recycled on the next restartpoint. We'll live
9579  * with that.
9580  */
9581  if (RecoveryInProgress())
9582  ThisTimeLineID = replayTLI;
9583 
9584  RemoveOldXlogFiles(_logSegNo, RedoRecPtr, endptr);
9585 
9586  /*
9587  * Make more log segments if needed. (Do this after recycling old log
9588  * segments, since that may supply some of the needed files.)
9589  */
9590  PreallocXlogFiles(endptr);
9591 
9592  /*
9593  * ThisTimeLineID is normally not set when we're still in recovery.
9594  * However, recycling/preallocating segments above needed ThisTimeLineID
9595  * to determine which timeline to install the segments on. Reset it now,
9596  * to restore the normal state of affairs for debugging purposes.
9597  */
9598  if (RecoveryInProgress())
9599  ThisTimeLineID = 0;
9600 
9601  /*
9602  * Truncate pg_subtrans if possible. We can throw away all data before
9603  * the oldest XMIN of any running transaction. No future transaction will
9604  * attempt to reference any pg_subtrans entry older than that (see Asserts
9605  * in subtrans.c). When hot standby is disabled, though, we mustn't do
9606  * this because StartupSUBTRANS hasn't been called yet.
9607  */
9608  if (EnableHotStandby)
9610 
9611  /* Real work is done, but log and update before releasing lock. */
9612  LogCheckpointEnd(true);
9613 
9614  /* Reset the process title */
9615  update_checkpoint_display(flags, true, true);
9616 
9617  xtime = GetLatestXTime();
9619  (errmsg("recovery restart point at %X/%X",
9620  (uint32) (lastCheckPoint.redo >> 32), (uint32) lastCheckPoint.redo),
9621  xtime ? errdetail("Last completed transaction was at log time %s.",
9622  timestamptz_to_str(xtime)) : 0));
9623 
9624  LWLockRelease(CheckpointLock);
9625 
9626  /*
9627  * Finally, execute archive_cleanup_command, if any.
9628  */
9629  if (archiveCleanupCommand && strcmp(archiveCleanupCommand, "") != 0)
9631  "archive_cleanup_command",
9632  false);
9633 
9634  return true;
9635 }
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8735
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:52
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
int wal_segment_size
Definition: xlog.c:118
pg_time_t time
Definition: pg_control.h:128
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
Definition: xlog.c:2773
TimestampTz ckpt_start_t
Definition: xlog.h:246
slock_t info_lck
Definition: xlog.c:737
#define MemSet(start, val, len)
Definition: c.h:996
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:9307
TimestampTz GetLatestXTime(void)
Definition: xlog.c:6198
CheckPoint checkPointCopy
Definition: pg_control.h:131
XLogCtlInsert Insert
Definition: xlog.c:601
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8148
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:338
XLogRecPtr lastCheckPointRecPtr
Definition: xlog.c:706
static void update_checkpoint_display(int flags, bool restartpoint, bool reset)
Definition: xlog.c:8773
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
#define SpinLockAcquire(lock)
Definition: spin.h:62
void UpdateControlFile(void)
Definition: xlog.c:4932
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8643
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11638
#define DEBUG2
Definition: elog.h:24
static XLogRecPtr RedoRecPtr
Definition: xlog.c:375
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3923
uint64 XLogSegNo
Definition: xlogdefs.h:41
int errdetail(const char *fmt,...)
Definition: elog.c:1048
unsigned int uint32
Definition: c.h:429
XLogRecPtr RedoRecPtr
Definition: xlog.c:605
CheckPoint lastCheckPoint
Definition: xlog.c:708
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define SpinLockRelease(lock)
Definition: spin.h:64
static TimeLineID minRecoveryPointTLI
Definition: xlog.c:873
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9738
static ControlFileData * ControlFile
Definition: xlog.c:748
TimeLineID ThisTimeLineID
Definition: xlog.c:193
#define ereport(elevel,...)
Definition: elog.h:155
uint64 XLogRecPtr
Definition: xlogdefs.h:21
CheckpointStatsData CheckpointStats
Definition: xlog.c:187
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:740
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1206
TransactionId GetOldestTransactionIdConsideredRunning(void)
Definition: procarray.c:1937
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:915
void InvalidateObsoleteReplicationSlots(XLogSegNo oldestSegno)
Definition: slot.c:1155
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr)
Definition: xlog.c:4054
XLogRecPtr RedoRecPtr
Definition: xlog.c:574
XLogRecPtr lastCheckPointEndPtr
Definition: xlog.c:707
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:37
static void LogCheckpointStart(int flags, bool restartpoint)
Definition: xlog.c:8611
char * archiveCleanupCommand
Definition: xlog.c:283
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:221
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
static XLogRecPtr minRecoveryPoint
Definition: xlog.c:872
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1772
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ DataChecksumsEnabled()

bool DataChecksumsEnabled ( void  )

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

4962 {
4963  Assert(ControlFile != NULL);
4964  return (ControlFile->data_checksum_version > 0);
4965 }
uint32 data_checksum_version
Definition: pg_control.h:220
static ControlFileData * ControlFile
Definition: xlog.c:748
#define Assert(condition)
Definition: c.h:792

◆ do_pg_abort_backup()

void do_pg_abort_backup ( int  code,
Datum  arg 
)

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

11591 {
11592  bool emit_warning = DatumGetBool(arg);
11593 
11594  /*
11595  * Quick exit if session is not keeping around a non-exclusive backup
11596  * already started.
11597  */
11599  return;
11600 
11604 
11607  {
11608  XLogCtl->Insert.forcePageWrites = false;
11609  }
11611 
11612  if (emit_warning)
11613  ereport(WARNING,
11614  (errmsg("aborting backup due to backend exiting before pg_stop_backup was called")));
11615 }
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
static SessionBackupState sessionBackupState
Definition: xlog.c:535
XLogCtlInsert Insert
Definition: xlog.c:601
bool forcePageWrites
Definition: xlog.c:575
#define DatumGetBool(X)
Definition: postgres.h:393
#define WARNING
Definition: elog.h:40
int nonExclusiveBackups
Definition: xlog.c:587
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:586
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:792
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:740
int errmsg(const char *fmt,...)
Definition: elog.c:915
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,
bool  needtblspcmapfile 
)

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

10662 {
10663  bool exclusive = (labelfile == NULL);
10664  bool backup_started_in_recovery = false;
10665  XLogRecPtr checkpointloc;
10666  XLogRecPtr startpoint;
10667  TimeLineID starttli;
10668  pg_time_t stamp_time;
10669  char strfbuf[128];
10670  char xlogfilename[MAXFNAMELEN];
10671  XLogSegNo _logSegNo;
10672  struct stat stat_buf;
10673  FILE *fp;
10674 
10675  backup_started_in_recovery = RecoveryInProgress();
10676 
10677  /*
10678  * Currently only non-exclusive backup can be taken during recovery.
10679  */
10680  if (backup_started_in_recovery && exclusive)
10681  ereport(ERROR,
10682  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10683  errmsg("recovery is in progress"),
10684  errhint("WAL control functions cannot be executed during recovery.")));
10685 
10686  /*
10687  * During recovery, we don't need to check WAL level. Because, if WAL
10688  * level is not sufficient, it's impossible to get here during recovery.
10689  */
10690  if (!backup_started_in_recovery && !XLogIsNeeded())
10691  ereport(ERROR,
10692  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10693  errmsg("WAL level not sufficient for making an online backup"),
10694  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
10695 
10696  if (strlen(backupidstr) > MAXPGPATH)
10697  ereport(ERROR,
10698  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
10699  errmsg("backup label too long (max %d bytes)",
10700  MAXPGPATH)));
10701 
10702  /*
10703  * Mark backup active in shared memory. We must do full-page WAL writes
10704  * during an on-line backup even if not doing so at other times, because
10705  * it's quite possible for the backup dump to obtain a "torn" (partially
10706  * written) copy of a database page if it reads the page concurrently with
10707  * our write to the same page. This can be fixed as long as the first
10708  * write to the page in the WAL sequence is a full-page write. Hence, we
10709  * turn on forcePageWrites and then force a CHECKPOINT, to ensure there
10710  * are no dirty pages in shared memory that might get dumped while the
10711  * backup is in progress without having a corresponding WAL record. (Once
10712  * the backup is complete, we need not force full-page writes anymore,
10713  * since we expect that any pages not modified during the backup interval
10714  * must have been correctly captured by the backup.)
10715  *
10716  * Note that forcePageWrites has no effect during an online backup from
10717  * the standby.
10718  *
10719  * We must hold all the insertion locks to change the value of
10720  * forcePageWrites, to ensure adequate interlocking against
10721  * XLogInsertRecord().
10722  */
10724  if (exclusive)
10725  {
10726  /*
10727  * At first, mark that we're now starting an exclusive backup, to
10728  * ensure that there are no other sessions currently running
10729  * pg_start_backup() or pg_stop_backup().
10730  */
10732  {
10734  ereport(ERROR,
10735  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10736  errmsg("a backup is already in progress"),
10737  errhint("Run pg_stop_backup() and try again.")));
10738  }
10740  }
10741  else
10743  XLogCtl->Insert.forcePageWrites = true;
10745 
10746  /* Ensure we release forcePageWrites if fail below */
10748  {
10749  bool gotUniqueStartpoint = false;
10750  DIR *tblspcdir;
10751  struct dirent *de;
10752  tablespaceinfo *ti;
10753  int datadirpathlen;
10754 
10755  /*
10756  * Force an XLOG file switch before the checkpoint, to ensure that the
10757  * WAL segment the checkpoint is written to doesn't contain pages with
10758  * old timeline IDs. That would otherwise happen if you called
10759  * pg_start_backup() right after restoring from a PITR archive: the
10760  * first WAL segment containing the startup checkpoint has pages in
10761  * the beginning with the old timeline ID. That can cause trouble at
10762  * recovery: we won't have a history file covering the old timeline if
10763  * pg_wal directory was not included in the base backup and the WAL
10764  * archive was cleared too before starting the backup.
10765  *
10766  * This also ensures that we have emitted a WAL page header that has
10767  * XLP_BKP_REMOVABLE off before we emit the checkpoint record.
10768  * Therefore, if a WAL archiver (such as pglesslog) is trying to
10769  * compress out removable backup blocks, it won't remove any that
10770  * occur after this point.
10771  *
10772  * During recovery, we skip forcing XLOG file switch, which means that
10773  * the backup taken during recovery is not available for the special
10774  * recovery case described above.
10775  */
10776  if (!backup_started_in_recovery)
10777  RequestXLogSwitch(false);
10778 
10779  do
10780  {
10781  bool checkpointfpw;
10782 
10783  /*
10784  * Force a CHECKPOINT. Aside from being necessary to prevent torn
10785  * page problems, this guarantees that two successive backup runs
10786  * will have different checkpoint positions and hence different
10787  * history file names, even if nothing happened in between.
10788  *
10789  * During recovery, establish a restartpoint if possible. We use
10790  * the last restartpoint as the backup starting checkpoint. This
10791  * means that two successive backup runs can have same checkpoint
10792  * positions.
10793  *
10794  * Since the fact that we are executing do_pg_start_backup()
10795  * during recovery means that checkpointer is running, we can use
10796  * RequestCheckpoint() to establish a restartpoint.
10797  *
10798  * We use CHECKPOINT_IMMEDIATE only if requested by user (via
10799  * passing fast = true). Otherwise this can take awhile.
10800  */
10802  (fast ? CHECKPOINT_IMMEDIATE : 0));
10803 
10804  /*
10805  * Now we need to fetch the checkpoint record location, and also
10806  * its REDO pointer. The oldest point in WAL that would be needed
10807  * to restore starting from the checkpoint is precisely the REDO
10808  * pointer.
10809  */
10810  LWLockAcquire(ControlFileLock, LW_SHARED);
10811  checkpointloc = ControlFile->checkPoint;
10812  startpoint = ControlFile->checkPointCopy.redo;
10814  checkpointfpw = ControlFile->checkPointCopy.fullPageWrites;
10815  LWLockRelease(ControlFileLock);
10816 
10817  if (backup_started_in_recovery)
10818  {
10819  XLogRecPtr recptr;
10820 
10821  /*
10822  * Check to see if all WAL replayed during online backup
10823  * (i.e., since last restartpoint used as backup starting
10824  * checkpoint) contain full-page writes.
10825  */
10827  recptr = XLogCtl->lastFpwDisableRecPtr;
10829 
10830  if (!checkpointfpw || startpoint <= recptr)
10831  ereport(ERROR,
10832  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
10833  errmsg("WAL generated with full_page_writes=off was replayed "
10834  "since last restartpoint"),
10835  errhint("This means that the backup being taken on the standby "
10836  "is corrupt and should not be used. "
10837  "Enable full_page_writes and run CHECKPOINT on the primary, "
10838  "and then try an online backup again.")));
10839 
10840  /*
10841  * During recovery, since we don't use the end-of-backup WAL
10842  * record and don't write the backup history file, the
10843  * starting WAL location doesn't need to be unique. This means
10844  * that two base backups started at the same time might use
10845  * the same checkpoint as starting locations.
10846  */
10847  gotUniqueStartpoint = true;
10848  }
10849 
10850  /*
10851  * If two base backups are started at the same time (in WAL sender
10852  * processes), we need to make sure that they use different
10853  * checkpoints as starting locations, because we use the starting
10854  * WAL location as a unique identifier for the base backup in the
10855  * end-of-backup WAL record and when we write the backup history
10856  * file. Perhaps it would be better generate a separate unique ID
10857  * for each backup instead of forcing another checkpoint, but
10858  * taking a checkpoint right after another is not that expensive
10859  * either because only few buffers have been dirtied yet.
10860  */
10862  if (XLogCtl->Insert.lastBackupStart < startpoint)
10863  {
10864  XLogCtl->Insert.lastBackupStart = startpoint;
10865  gotUniqueStartpoint = true;
10866  }
10868  } while (!gotUniqueStartpoint);
10869 
10870  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
10871  XLogFileName(xlogfilename, starttli, _logSegNo, wal_segment_size);
10872 
10873  /*
10874  * Construct tablespace_map file
10875  */
10876  if (exclusive)
10877  tblspcmapfile = makeStringInfo();
10878 
10879  datadirpathlen = strlen(DataDir);
10880 
10881  /* Collect information about all tablespaces */
10882  tblspcdir = AllocateDir("pg_tblspc");
10883  while ((de = ReadDir(tblspcdir, "pg_tblspc")) != NULL)
10884  {
10885  char fullpath[MAXPGPATH + 10];
10886  char linkpath[MAXPGPATH];
10887  char *relpath = NULL;
10888  int rllen;
10889  StringInfoData buflinkpath;
10890  char *s = linkpath;
10891 
10892  /* Skip special stuff */
10893  if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
10894  continue;
10895 
10896  snprintf(fullpath, sizeof(fullpath), "pg_tblspc/%s", de->d_name);
10897 
10898 #if defined(HAVE_READLINK) || defined(WIN32)
10899  rllen = readlink(fullpath, linkpath, sizeof(linkpath));
10900  if (rllen < 0)
10901  {
10902  ereport(WARNING,
10903  (errmsg("could not read symbolic link \"%s\": %m",
10904  fullpath)));
10905  continue;
10906  }
10907  else if (rllen >= sizeof(linkpath))
10908  {
10909  ereport(WARNING,
10910  (errmsg("symbolic link \"%s\" target is too long",
10911  fullpath)));
10912  continue;
10913  }
10914  linkpath[rllen] = '\0';
10915 
10916  /*
10917  * Add the escape character '\\' before newline in a string to
10918  * ensure that we can distinguish between the newline in the
10919  * tablespace path and end of line while reading tablespace_map
10920  * file during archive recovery.
10921  */
10922  initStringInfo(&buflinkpath);
10923 
10924  while (*s)
10925  {
10926  if ((*s == '\n' || *s == '\r') && needtblspcmapfile)
10927  appendStringInfoChar(&buflinkpath, '\\');
10928  appendStringInfoChar(&buflinkpath, *s++);
10929  }
10930 
10931  /*
10932  * Relpath holds the relative path of the tablespace directory
10933  * when it's located within PGDATA, or NULL if it's located
10934  * elsewhere.
10935  */
10936  if (rllen > datadirpathlen &&
10937  strncmp(linkpath, DataDir, datadirpathlen) == 0 &&
10938  IS_DIR_SEP(linkpath[datadirpathlen]))
10939  relpath = linkpath + datadirpathlen + 1;
10940 
10941  ti = palloc(sizeof(tablespaceinfo));
10942  ti->oid = pstrdup(de->d_name);
10943  ti->path = pstrdup(buflinkpath.data);
10944  ti->rpath = relpath ? pstrdup(relpath) : NULL;
10945  ti->size = -1;
10946 
10947  if (tablespaces)
10948  *tablespaces = lappend(*tablespaces, ti);
10949 
10950  appendStringInfo(tblspcmapfile, "%s %s\n", ti->oid, ti->path);
10951 
10952  pfree(buflinkpath.data);
10953 #else
10954 
10955  /*
10956  * If the platform does not have symbolic links, it should not be
10957  * possible to have tablespaces - clearly somebody else created
10958  * them. Warn about it and ignore.
10959  */
10960  ereport(WARNING,
10961  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
10962  errmsg("tablespaces are not supported on this platform")));
10963 #endif
10964  }
10965  FreeDir(tblspcdir);
10966 
10967  /*
10968  * Construct backup label file
10969  */
10970  if (exclusive)
10971  labelfile = makeStringInfo();
10972 
10973  /* Use the log timezone here, not the session timezone */
10974  stamp_time = (pg_time_t) time(NULL);
10975  pg_strftime(strfbuf, sizeof(strfbuf),
10976  "%Y-%m-%d %H:%M:%S %Z",
10977  pg_localtime(&stamp_time, log_timezone));
10978  appendStringInfo(labelfile, "START WAL LOCATION: %X/%X (file %s)\n",
10979  (uint32) (startpoint >> 32), (uint32) startpoint, xlogfilename);
10980  appendStringInfo(labelfile, "CHECKPOINT LOCATION: %X/%X\n",
10981  (uint32) (checkpointloc >> 32), (uint32) checkpointloc);
10982  appendStringInfo(labelfile, "BACKUP METHOD: %s\n",
10983  exclusive ? "pg_start_backup" : "streamed");
10984  appendStringInfo(labelfile, "BACKUP FROM: %s\n",
10985  backup_started_in_recovery ? "standby" : "primary");
10986  appendStringInfo(labelfile, "START TIME: %s\n", strfbuf);
10987  appendStringInfo(labelfile, "LABEL: %s\n", backupidstr);
10988  appendStringInfo(labelfile, "START TIMELINE: %u\n", starttli);
10989 
10990  /*
10991  * Okay, write the file, or return its contents to caller.
10992  */
10993  if (exclusive)
10994  {
10995  /*
10996  * Check for existing backup label --- implies a backup is already
10997  * running. (XXX given that we checked exclusiveBackupState
10998  * above, maybe it would be OK to just unlink any such label
10999  * file?)
11000  */
11001  if (stat(BACKUP_LABEL_FILE, &stat_buf) != 0)
11002  {
11003  if (errno != ENOENT)
11004  ereport(ERROR,
11006  errmsg("could not stat file \"%s\": %m",
11007  BACKUP_LABEL_FILE)));
11008  }
11009  else
11010  ereport(ERROR,
11011  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11012  errmsg("a backup is already in progress"),
11013  errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
11014  BACKUP_LABEL_FILE)));
11015 
11016  fp = AllocateFile(BACKUP_LABEL_FILE, "w");
11017 
11018  if (!fp)
11019  ereport(ERROR,
11021  errmsg("could not create file \"%s\": %m",
11022  BACKUP_LABEL_FILE)));
11023  if (fwrite(labelfile->data, labelfile->len, 1, fp) != 1 ||
11024  fflush(fp) != 0 ||
11025  pg_fsync(fileno(fp)) != 0 ||
11026  ferror(fp) ||
11027  FreeFile(fp))
11028  ereport(ERROR,
11030  errmsg("could not write file \"%s\": %m",
11031  BACKUP_LABEL_FILE)));
11032  /* Allocated locally for exclusive backups, so free separately */
11033  pfree(labelfile->data);
11034  pfree(labelfile);
11035 
11036  /* Write backup tablespace_map file. */
11037  if (tblspcmapfile->len > 0)
11038  {
11039  if (stat(TABLESPACE_MAP, &stat_buf) != 0)
11040  {
11041  if (errno != ENOENT)
11042  ereport(ERROR,
11044  errmsg("could not stat file \"%s\": %m",
11045  TABLESPACE_MAP)));
11046  }
11047  else
11048  ereport(ERROR,
11049  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11050  errmsg("a backup is already in progress"),
11051  errhint("If you're sure there is no backup in progress, remove file \"%s\" and try again.",
11052  TABLESPACE_MAP)));
11053 
11054  fp = AllocateFile(TABLESPACE_MAP, "w");
11055 
11056  if (!fp)
11057  ereport(ERROR,
11059  errmsg("could not create file \"%s\": %m",
11060  TABLESPACE_MAP)));
11061  if (fwrite(tblspcmapfile->data, tblspcmapfile->len, 1, fp) != 1 ||
11062  fflush(fp) != 0 ||
11063  pg_fsync(fileno(fp)) != 0 ||
11064  ferror(fp) ||
11065  FreeFile(fp))
11066  ereport(ERROR,
11068  errmsg("could not write file \"%s\": %m",
11069  TABLESPACE_MAP)));
11070  }
11071 
11072  /* Allocated locally for exclusive backups, so free separately */
11073  pfree(tblspcmapfile->data);
11074  pfree(tblspcmapfile);
11075  }
11076  }
11078 
11079  /*
11080  * Mark that start phase has correctly finished for an exclusive backup.
11081  * Session-level locks are updated as well to reflect that state.
11082  *
11083  * Note that CHECK_FOR_INTERRUPTS() must not occur while updating backup
11084  * counters and session-level lock. Otherwise they can be updated
11085  * inconsistently, and which might cause do_pg_abort_backup() to fail.
11086  */
11087  if (exclusive)
11088  {
11091 
11092  /* Set session-level lock */
11095  }
11096  else
11098 
11099  /*
11100  * We're done. As a convenience, return the starting WAL location.
11101  */
11102  if (starttli_p)
11103  *starttli_p = starttli;
11104  return startpoint;
11105 }
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:9831
int errhint(const char *fmt,...)
Definition: elog.c:1162
uint32 TimeLineID
Definition: xlogdefs.h:52
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
int wal_segment_size
Definition: xlog.c:118
XLogRecPtr lastFpwDisableRecPtr
Definition: xlog.c:735
static SessionBackupState sessionBackupState
Definition: xlog.c:535
XLogRecPtr lastBackupStart
Definition: xlog.c:588
char * pstrdup(const char *in)
Definition: mcxt.c:1187
#define XLogIsNeeded()
Definition: xlog.h:191
char * rpath
Definition: basebackup.h:27
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
slock_t info_lck
Definition: xlog.c:737
int errcode(int sqlerrcode)
Definition: elog.c:704
CheckPoint checkPointCopy
Definition: pg_control.h:131
XLogCtlInsert Insert
Definition: xlog.c:601
bool RecoveryInProgress(void)
Definition: xlog.c:8148
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:1808
#define TABLESPACE_MAP
Definition: xlog.h:392
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
void pfree(void *pointer)
Definition: mcxt.c:1057
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
bool forcePageWrites
Definition: xlog.c:575
Definition: dirent.c:25
#define ERROR
Definition: elog.h:45
struct stat stat_buf
Definition: pg_standby.c:100
#define MAXPGPATH
uint64 XLogSegNo
Definition: xlogdefs.h:41
#define readlink(path, buf, size)
Definition: win32_port.h:228
int errcode_for_file_access(void)
Definition: elog.c:727
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2354
unsigned int uint32
Definition: c.h:429
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2615
#define CHECKPOINT_FORCE
Definition: xlog.h:225
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:587
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
static void pg_start_backup_callback(int code, Datum arg)
Definition: xlog.c:11109
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:586
uintptr_t Datum
Definition: postgres.h:367
static ControlFileData * ControlFile
Definition: xlog.c:748
#define BoolGetDatum(X)
Definition: postgres.h:402
#define ereport(elevel,...)
Definition: elog.h:155
bool fullPageWrites
Definition: pg_control.h:42
#define CHECKPOINT_WAIT
Definition: xlog.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2681
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:740
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1206
#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:2553
void * palloc(Size size)
Definition: mcxt.c:950
TimeLineID ThisTimeLineID
Definition: pg_control.h:39
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:224
#define relpath(rnode, forknum)
Definition: relpath.h:87
char * DataDir
Definition: globals.c:63
#define BACKUP_LABEL_FILE
Definition: xlog.h:389
int pg_fsync(int fd)
Definition: fd.c:347
char d_name[MAX_PATH]
Definition: dirent.h:15
#define snprintf
Definition: port.h:215
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:37
int FreeDir(DIR *dir)
Definition: fd.c:2733
#define stat
Definition: win32_port.h:275
void RequestCheckpoint(int flags)
Definition: checkpointer.c:916
#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 11177 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, LW_SHARED, LWLockAcquire(), LWLockRelease(), MAXFNAMELEN, MAXPGPATH, ControlFileData::minRecoveryPoint, ControlFileData::minRecoveryPointTLI, XLogCtlInsert::nonExclusiveBackups, NOTICE, palloc(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_localtime(), pg_stop_backup_callback(), pg_strftime(), pg_usleep(), pgstat_report_wait_end(), pgstat_report_wait_start(), RecoveryInProgress(), remaining, RequestXLogSwitch(), SESSION_BACKUP_NONE, sessionBackupState, SpinLockAcquire, SpinLockRelease, stat::st_size, stat, TABLESPACE_MAP, ThisTimeLineID, WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE, wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), WARNING, XLByteToPrevSeg, XLByteToSeg, XLOG_BACKUP_END, XLogArchiveIsBusy(), XLogArchivingActive, XLogArchivingAlways, XLogBeginInsert(), XLogFileName, XLogInsert(), XLogIsNeeded, and XLogRegisterData().

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

11178 {
11179  bool exclusive = (labelfile == NULL);
11180  bool backup_started_in_recovery = false;
11181  XLogRecPtr startpoint;
11182  XLogRecPtr stoppoint;
11183  TimeLineID stoptli;
11184  pg_time_t stamp_time;
11185  char strfbuf[128];
11186  char histfilepath[MAXPGPATH];
11187  char startxlogfilename[MAXFNAMELEN];
11188  char stopxlogfilename[MAXFNAMELEN];
11189  char lastxlogfilename[MAXFNAMELEN];
11190  char histfilename[MAXFNAMELEN];
11191  char backupfrom[20];
11192  XLogSegNo _logSegNo;
11193  FILE *lfp;
11194  FILE *fp;
11195  char ch;
11196  int seconds_before_warning;
11197  int waits = 0;
11198  bool reported_waiting = false;
11199  char *remaining;
11200  char *ptr;
11201  uint32 hi,
11202  lo;
11203 
11204  backup_started_in_recovery = RecoveryInProgress();
11205 
11206  /*
11207  * Currently only non-exclusive backup can be taken during recovery.
11208  */
11209  if (backup_started_in_recovery && exclusive)
11210  ereport(ERROR,
11211  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11212  errmsg("recovery is in progress"),
11213  errhint("WAL control functions cannot be executed during recovery.")));
11214 
11215  /*
11216  * During recovery, we don't need to check WAL level. Because, if WAL
11217  * level is not sufficient, it's impossible to get here during recovery.
11218  */
11219  if (!backup_started_in_recovery && !XLogIsNeeded())
11220  ereport(ERROR,
11221  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11222  errmsg("WAL level not sufficient for making an online backup"),
11223  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
11224 
11225  if (exclusive)
11226  {
11227  /*
11228  * At first, mark that we're now stopping an exclusive backup, to
11229  * ensure that there are no other sessions currently running
11230  * pg_start_backup() or pg_stop_backup().
11231  */
11234  {
11236  ereport(ERROR,
11237  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11238  errmsg("exclusive backup not in progress")));
11239  }
11242 
11243  /*
11244  * Remove backup_label. In case of failure, the state for an exclusive
11245  * backup is switched back to in-progress.
11246  */
11248  {
11249  /*
11250  * Read the existing label file into memory.
11251  */
11252  struct stat statbuf;
11253  int r;
11254 
11255  if (stat(BACKUP_LABEL_FILE, &statbuf))
11256  {
11257  /* should not happen per the upper checks */
11258  if (errno != ENOENT)
11259  ereport(ERROR,
11261  errmsg("could not stat file \"%s\": %m",
11262  BACKUP_LABEL_FILE)));
11263  ereport(ERROR,
11264  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11265  errmsg("a backup is not in progress")));
11266  }
11267 
11268  lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
11269  if (!lfp)
11270  {
11271  ereport(ERROR,
11273  errmsg("could not read file \"%s\": %m",
11274  BACKUP_LABEL_FILE)));
11275  }
11276  labelfile = palloc(statbuf.st_size + 1);
11277  r = fread(labelfile, statbuf.st_size, 1, lfp);
11278  labelfile[statbuf.st_size] = '\0';
11279 
11280  /*
11281  * Close and remove the backup label file
11282  */
11283  if (r != 1 || ferror(lfp) || FreeFile(lfp))
11284  ereport(ERROR,
11286  errmsg("could not read file \"%s\": %m",
11287  BACKUP_LABEL_FILE)));
11289 
11290  /*
11291  * Remove tablespace_map file if present, it is created only if
11292  * there are tablespaces.
11293  */
11295  }
11297  }
11298 
11299  /*
11300  * OK to update backup counters, forcePageWrites and session-level lock.
11301  *
11302  * Note that CHECK_FOR_INTERRUPTS() must not occur while updating them.
11303  * Otherwise they can be updated inconsistently, and which might cause
11304  * do_pg_abort_backup() to fail.
11305  */
11307  if (exclusive)
11308  {
11310  }
11311  else
11312  {
11313  /*
11314  * The user-visible pg_start/stop_backup() functions that operate on
11315  * exclusive backups can be called at any time, but for non-exclusive
11316  * backups, it is expected that each do_pg_start_backup() call is
11317  * matched by exactly one do_pg_stop_backup() call.
11318  */
11321  }
11322 
11325  {
11326  XLogCtl->Insert.forcePageWrites = false;
11327  }
11328 
11329  /*
11330  * Clean up session-level lock.
11331  *
11332  * You might think that WALInsertLockRelease() can be called before
11333  * cleaning up session-level lock because session-level lock doesn't need
11334  * to be protected with WAL insertion lock. But since
11335  * CHECK_FOR_INTERRUPTS() can occur in it, session-level lock must be
11336  * cleaned up before it.
11337  */
11339 
11341 
11342  /*
11343  * Read and parse the START WAL LOCATION line (this code is pretty crude,
11344  * but we are not expecting any variability in the file format).
11345  */
11346  if (sscanf(labelfile, "START WAL LOCATION: %X/%X (file %24s)%c",
11347  &hi, &lo, startxlogfilename,
11348  &ch) != 4 || ch != '\n')
11349  ereport(ERROR,
11350  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11351  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
11352  startpoint = ((uint64) hi) << 32 | lo;
11353  remaining = strchr(labelfile, '\n') + 1; /* %n is not portable enough */
11354 
11355  /*
11356  * Parse the BACKUP FROM line. If we are taking an online backup from the
11357  * standby, we confirm that the standby has not been promoted during the
11358  * backup.
11359  */
11360  ptr = strstr(remaining, "BACKUP FROM:");
11361  if (!ptr || sscanf(ptr, "BACKUP FROM: %19s\n", backupfrom) != 1)
11362  ereport(ERROR,
11363  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11364  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
11365  if (strcmp(backupfrom, "standby") == 0 && !backup_started_in_recovery)
11366  ereport(ERROR,
11367  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11368  errmsg("the standby was promoted during online backup"),
11369  errhint("This means that the backup being taken is corrupt "
11370  "and should not be used. "
11371  "Try taking another online backup.")));
11372 
11373  /*
11374  * During recovery, we don't write an end-of-backup record. We assume that
11375  * pg_control was backed up last and its minimum recovery point can be
11376  * available as the backup end location. Since we don't have an
11377  * end-of-backup record, we use the pg_control value to check whether
11378  * we've reached the end of backup when starting recovery from this
11379  * backup. We have no way of checking if pg_control wasn't backed up last
11380  * however.
11381  *
11382  * We don't force a switch to new WAL file but it is still possible to
11383  * wait for all the required files to be archived if waitforarchive is
11384  * true. This is okay if we use the backup to start a standby and fetch
11385  * the missing WAL using streaming replication. But in the case of an
11386  * archive recovery, a user should set waitforarchive to true and wait for
11387  * them to be archived to ensure that all the required files are
11388  * available.
11389  *
11390  * We return the current minimum recovery point as the backup end
11391  * location. Note that it can be greater than the exact backup end
11392  * location if the minimum recovery point is updated after the backup of
11393  * pg_control. This is harmless for current uses.
11394  *
11395  * XXX currently a backup history file is for informational and debug
11396  * purposes only. It's not essential for an online backup. Furthermore,
11397  * even if it's created, it will not be archived during recovery because
11398  * an archiver is not invoked. So it doesn't seem worthwhile to write a
11399  * backup history file during recovery.
11400  */
11401  if (backup_started_in_recovery)
11402  {
11403  XLogRecPtr recptr;
11404 
11405  /*
11406  * Check to see if all WAL replayed during online backup contain
11407  * full-page writes.
11408  */
11410  recptr = XLogCtl->lastFpwDisableRecPtr;
11412 
11413  if (startpoint <= recptr)
11414  ereport(ERROR,
11415  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
11416  errmsg("WAL generated with full_page_writes=off was replayed "
11417  "during online backup"),
11418  errhint("This means that the backup being taken on the standby "
11419  "is corrupt and should not be used. "
11420  "Enable full_page_writes and run CHECKPOINT on the primary, "
11421  "and then try an online backup again.")));
11422 
11423 
11424  LWLockAcquire(ControlFileLock, LW_SHARED);
11425  stoppoint = ControlFile->minRecoveryPoint;
11426  stoptli = ControlFile->minRecoveryPointTLI;
11427  LWLockRelease(ControlFileLock);
11428  }
11429  else
11430  {
11431  /*
11432  * Write the backup-end xlog record
11433  */
11434  XLogBeginInsert();
11435  XLogRegisterData((char *) (&startpoint), sizeof(startpoint));
11436  stoppoint = XLogInsert(RM_XLOG_ID, XLOG_BACKUP_END);
11437  stoptli = ThisTimeLineID;
11438 
11439  /*
11440  * Force a switch to a new xlog segment file, so that the backup is
11441  * valid as soon as archiver moves out the current segment file.
11442  */
11443  RequestXLogSwitch(false);
11444 
11445  XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
11446  XLogFileName(stopxlogfilename, stoptli, _logSegNo, wal_segment_size);
11447 
11448  /* Use the log timezone here, not the session timezone */
11449  stamp_time = (pg_time_t) time(NULL);
11450  pg_strftime(strfbuf, sizeof(strfbuf),
11451  "%Y-%m-%d %H:%M:%S %Z",
11452  pg_localtime(&stamp_time, log_timezone));
11453 
11454  /*
11455  * Write the backup history file
11456  */
11457  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
11458  BackupHistoryFilePath(histfilepath, stoptli, _logSegNo,
11459  startpoint, wal_segment_size);
11460  fp = AllocateFile(histfilepath, "w");
11461  if (!fp)
11462  ereport(ERROR,
11464  errmsg("could not create file \"%s\": %m",
11465  histfilepath)));
11466  fprintf(fp, "START WAL LOCATION: %X/%X (file %s)\n",
11467  (uint32) (startpoint >> 32), (uint32) startpoint, startxlogfilename);
11468  fprintf(fp, "STOP WAL LOCATION: %X/%X (file %s)\n",
11469  (uint32) (stoppoint >> 32), (uint32) stoppoint, stopxlogfilename);
11470 
11471  /*
11472  * Transfer remaining lines including label and start timeline to
11473  * history file.
11474  */
11475  fprintf(fp, "%s", remaining);
11476  fprintf(fp, "STOP TIME: %s\n", strfbuf);
11477  fprintf(fp, "STOP TIMELINE: %u\n", stoptli);
11478  if (fflush(fp) || ferror(fp) || FreeFile(fp))
11479  ereport(ERROR,
11481  errmsg("could not write file \"%s\": %m",
11482  histfilepath)));
11483 
11484  /*
11485  * Clean out any no-longer-needed history files. As a side effect,
11486  * this will post a .ready file for the newly created history file,
11487  * notifying the archiver that history file may be archived
11488  * immediately.
11489  */
11491  }
11492 
11493  /*
11494  * If archiving is enabled, wait for all the required WAL files to be
11495  * archived before returning. If archiving isn't enabled, the required WAL
11496  * needs to be transported via streaming replication (hopefully with
11497  * wal_keep_size set high enough), or some more exotic mechanism like
11498  * polling and copying files from pg_wal with script. We have no knowledge
11499  * of those mechanisms, so it's up to the user to ensure that he gets all
11500  * the required WAL.
11501  *
11502  * We wait until both the last WAL file filled during backup and the
11503  * history file have been archived, and assume that the alphabetic sorting
11504  * property of the WAL files ensures any earlier WAL files are safely
11505  * archived as well.
11506  *
11507  * We wait forever, since archive_command is supposed to work and we
11508  * assume the admin wanted his backup to work completely. If you don't
11509  * wish to wait, then either waitforarchive should be passed in as false,
11510  * or you can set statement_timeout. Also, some notices are issued to
11511  * clue in anyone who might be doing this interactively.
11512  */
11513 
11514  if (waitforarchive &&
11515  ((!backup_started_in_recovery && XLogArchivingActive()) ||
11516  (backup_started_in_recovery && XLogArchivingAlways())))
11517  {
11518  XLByteToPrevSeg(stoppoint, _logSegNo, wal_segment_size);
11519  XLogFileName(lastxlogfilename, stoptli, _logSegNo, wal_segment_size);
11520 
11521  XLByteToSeg(startpoint, _logSegNo, wal_segment_size);
11522  BackupHistoryFileName(histfilename, stoptli, _logSegNo,
11523  startpoint, wal_segment_size);
11524 
11525  seconds_before_warning = 60;
11526  waits = 0;
11527 
11528  while (XLogArchiveIsBusy(lastxlogfilename) ||
11529  XLogArchiveIsBusy(histfilename))
11530  {
11532 
11533  if (!reported_waiting && waits > 5)
11534  {
11535  ereport(NOTICE,
11536  (errmsg("base backup done, waiting for required WAL segments to be archived")));
11537  reported_waiting = true;
11538  }
11539 
11541  pg_usleep(1000000L);
11543 
11544  if (++waits >= seconds_before_warning)
11545  {
11546  seconds_before_warning *= 2; /* This wraps in >10 years... */
11547  ereport(WARNING,
11548  (errmsg("still waiting for all required WAL segments to be archived (%d seconds elapsed)",
11549  waits),
11550  errhint("Check that your archive_command is executing properly. "
11551  "You can safely cancel this backup, "
11552  "but the database backup will not be usable without all the WAL segments.")));
11553  }
11554  }
11555 
11556  ereport(NOTICE,
11557  (errmsg("all required WAL segments have been archived")));
11558  }
11559  else if (waitforarchive)
11560  ereport(NOTICE,
11561  (errmsg("WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
11562 
11563  /*
11564  * We're done. As a convenience, return the ending WAL location.
11565  */
11566  if (stoptli_p)
11567  *stoptli_p = stoptli;
11568  return stoppoint;
11569 }
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:9831
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1162
uint32 TimeLineID
Definition: xlogdefs.h:52
int64 pg_time_t
Definition: pgtime.h:23
static void WALInsertLockRelease(void)
Definition: xlog.c:1740
int wal_segment_size
Definition: xlog.c:118
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:167
XLogRecPtr lastFpwDisableRecPtr
Definition: xlog.c:735
static SessionBackupState sessionBackupState
Definition: xlog.c:535
#define XLByteToPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogIsNeeded()
Definition: xlog.h:191
slock_t info_lck
Definition: xlog.c:737
int errcode(int sqlerrcode)
Definition: elog.c:704
XLogCtlInsert Insert
Definition: xlog.c:601
#define BackupHistoryFileName(fname, tli, logSegNo, startpoint, wal_segsz_bytes)
bool RecoveryInProgress(void)
Definition: xlog.c:8148
static bool backup_started_in_recovery
Definition: basebackup.c:88
#define fprintf
Definition: port.h:219
pg_tz * log_timezone
Definition: pgtz.c:31
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
#define TABLESPACE_MAP
Definition: xlog.h:392
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
#define XLogArchivingAlways()
Definition: xlog.h:183
bool forcePageWrites
Definition: xlog.c:575
#define ERROR
Definition: elog.h:45
static void CleanupBackupHistory(void)
Definition: xlog.c:4320
#define MAXPGPATH
uint64 XLogSegNo
Definition: xlogdefs.h:41
int errcode_for_file_access(void)
Definition: elog.c:727
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2354
unsigned int uint32
Definition: c.h:429
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1512
#define XLOG_BACKUP_END
Definition: pg_control.h:72
#define WARNING
Definition: elog.h:40
int nonExclusiveBackups
Definition: xlog.c:587
#define MAXFNAMELEN
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:330
#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:422
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:586
uintptr_t Datum
Definition: postgres.h:367
static ControlFileData * ControlFile
Definition: xlog.c:748
#define BoolGetDatum(X)
Definition: postgres.h:402
TimeLineID ThisTimeLineID
Definition: xlog.c:193
#define ereport(elevel,...)
Definition: elog.h:155
#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:792
#define XLogArchivingActive()
Definition: xlog.h:180
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1488
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1711
static XLogCtlData * XLogCtl
Definition: xlog.c:740
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1206
static void pg_stop_backup_callback(int code, Datum arg)
Definition: xlog.c:11138
#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:777
int FreeFile(FILE *file)
Definition: fd.c:2553
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define BACKUP_LABEL_FILE
Definition: xlog.h:389
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
void XLogBeginInsert(void)
Definition: xloginsert.c:123
#define stat
Definition: win32_port.h:275
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:166
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ get_backup_status()

SessionBackupState get_backup_status ( void  )

Definition at line 11156 of file xlog.c.

References sessionBackupState.

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

11157 {
11158  return sessionBackupState;
11159 }
static SessionBackupState sessionBackupState
Definition: xlog.c:535

◆ GetCurrentChunkReplayStartTime()

TimestampTz GetCurrentChunkReplayStartTime ( void  )

Definition at line 6228 of file xlog.c.

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

Referenced by GetReplicationApplyDelay().

6229 {
6230  TimestampTz xtime;
6231 
6233  xtime = XLogCtl->currentChunkStartTime;
6235 
6236  return xtime;
6237 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:740
TimestampTz currentChunkStartTime
Definition: xlog.c:727

◆ GetFakeLSNForUnloggedRel()

XLogRecPtr GetFakeLSNForUnloggedRel ( void  )

Definition at line 4977 of file xlog.c.

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

Referenced by gistGetFakeLSN().

4978 {
4979  XLogRecPtr nextUnloggedLSN;
4980 
4981  /* increment the unloggedLSN counter, need SpinLock */
4983  nextUnloggedLSN = XLogCtl->unloggedLSN++;
4985 
4986  return nextUnloggedLSN;
4987 }
XLogRecPtr unloggedLSN
Definition: xlog.c:613
#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:740
slock_t ulsn_lck
Definition: xlog.c:614

◆ GetFlushRecPtr()

XLogRecPtr GetFlushRecPtr ( void  )

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

8501 {
8505 
8506  return LogwrtResult.Flush;
8507 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:786
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:624
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:740
XLogRecPtr Flush
Definition: xlog.c:449

◆ GetFullPageWriteInfo()

void GetFullPageWriteInfo ( XLogRecPtr RedoRecPtr_p,
bool doPageWrites_p 
)

Definition at line 8469 of file xlog.c.

References doPageWrites, and RedoRecPtr.

Referenced by XLogCheckBufferNeedsBackup(), and XLogInsert().

8470 {
8471  *RedoRecPtr_p = RedoRecPtr;
8472  *doPageWrites_p = doPageWrites;
8473 }
static bool doPageWrites
Definition: xlog.c:382
static XLogRecPtr RedoRecPtr
Definition: xlog.c:375

◆ GetInsertRecPtr()

XLogRecPtr GetInsertRecPtr ( void  )

Definition at line 8484 of file xlog.c.

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

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

8485 {
8486  XLogRecPtr recptr;
8487 
8489  recptr = XLogCtl->LogwrtRqst.Write;
8491 
8492  return recptr;
8493 }
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr Write
Definition: xlog.c:442
XLogwrtRqst LogwrtRqst
Definition: xlog.c:604
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:740

◆ GetLastImportantRecPtr()

XLogRecPtr GetLastImportantRecPtr ( void  )

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

8519 {
8521  int i;
8522 
8523  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
8524  {
8525  XLogRecPtr last_important;
8526 
8527  /*
8528  * Need to take a lock to prevent torn reads of the LSN, which are
8529  * possible on some of the supported platforms. WAL insert locks only
8530  * support exclusive mode, so we have to use that.
8531  */
8533  last_important = WALInsertLocks[i].l.lastImportantAt;
8534  LWLockRelease(&WALInsertLocks[i].l.lock);
8535 
8536  if (res < last_important)
8537  res = last_important;
8538  }
8539 
8540  return res;
8541 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogRecPtr lastImportantAt
Definition: xlog.c:492
#define NUM_XLOGINSERT_LOCKS
Definition: xlog.c:125
WALInsertLock l
Definition: xlog.c:504
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
uint64 XLogRecPtr
Definition: xlogdefs.h:21
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1206
int i
static WALInsertLockPadded * WALInsertLocks
Definition: xlog.c:743

◆ GetLatestXTime()

TimestampTz GetLatestXTime ( void  )

Definition at line 6198 of file xlog.c.

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

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

6199 {
6200  TimestampTz xtime;
6201 
6203  xtime = XLogCtl->recoveryLastXTime;
6205 
6206  return xtime;
6207 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz recoveryLastXTime
Definition: xlog.c:721
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:740

◆ GetMockAuthenticationNonce()

char* GetMockAuthenticationNonce ( void  )

Definition at line 4951 of file xlog.c.

References Assert, and ControlFileData::mock_authentication_nonce.

Referenced by scram_mock_salt().

4952 {
4953  Assert(ControlFile != NULL);
4955 }
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:227
static ControlFileData * ControlFile
Definition: xlog.c:748
#define Assert(condition)
Definition: c.h:792

◆ GetRecoveryState()

RecoveryState GetRecoveryState ( void  )

Definition at line 8201 of file xlog.c.

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

Referenced by XLogArchiveCheckDone().

8202 {
8203  RecoveryState retval;
8204 
8206  retval = XLogCtl->SharedRecoveryState;
8208 
8209  return retval;
8210 }
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
RecoveryState SharedRecoveryState
Definition: xlog.c:660
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:740
RecoveryState
Definition: xlog.h:170

◆ GetRedoRecPtr()

XLogRecPtr GetRedoRecPtr ( void  )

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

8441 {
8442  XLogRecPtr ptr;
8443 
8444  /*
8445  * The possibly not up-to-date copy in XlogCtl is enough. Even if we
8446  * grabbed a WAL insertion lock to read the authoritative value in
8447  * Insert->RedoRecPtr, someone might update it just after we've released
8448  * the lock.
8449  */
8451  ptr = XLogCtl->RedoRecPtr;
8453 
8454  if (RedoRecPtr < ptr)
8455  RedoRecPtr = ptr;
8456 
8457  return RedoRecPtr;
8458 }
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
static XLogRecPtr RedoRecPtr
Definition: xlog.c:375
XLogRecPtr RedoRecPtr
Definition: xlog.c:605
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:740

◆ GetSystemIdentifier()

uint64 GetSystemIdentifier ( void  )

Definition at line 4941 of file xlog.c.

References Assert, and ControlFileData::system_identifier.

Referenced by IdentifySystem(), and WalReceiverMain().

4942 {
4943  Assert(ControlFile != NULL);
4945 }
uint64 system_identifier
Definition: pg_control.h:106
static ControlFileData * ControlFile
Definition: xlog.c:748
#define Assert(condition)
Definition: c.h:792

◆ GetWALAvailability()

WALAvailability GetWALAvailability ( XLogRecPtr  targetLSN)

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

9661 {
9662  XLogRecPtr currpos; /* current write LSN */
9663  XLogSegNo currSeg; /* segid of currpos */
9664  XLogSegNo targetSeg; /* segid of targetLSN */
9665  XLogSegNo oldestSeg; /* actual oldest segid */
9666  XLogSegNo oldestSegMaxWalSize; /* oldest segid kept by max_wal_size */
9667  XLogSegNo oldestSlotSeg; /* oldest segid kept by slot */
9668  uint64 keepSegs;
9669 
9670  /*
9671  * slot does not reserve WAL. Either deactivated, or has never been active
9672  */
9673  if (XLogRecPtrIsInvalid(targetLSN))
9674  return WALAVAIL_INVALID_LSN;
9675 
9676  /*
9677  * Calculate the oldest segment currently reserved by all slots,
9678  * considering wal_keep_size and max_slot_wal_keep_size. Initialize
9679  * oldestSlotSeg to the current segment.
9680  */
9681  currpos = GetXLogWriteRecPtr();
9682  XLByteToSeg(currpos, oldestSlotSeg, wal_segment_size);
9683  KeepLogSeg(currpos, &oldestSlotSeg);
9684 
9685  /*
9686  * Find the oldest extant segment file. We get 1 until checkpoint removes
9687  * the first WAL segment file since startup, which causes the status being
9688  * wrong under certain abnormal conditions but that doesn't actually harm.
9689  */
9690  oldestSeg = XLogGetLastRemovedSegno() + 1;
9691 
9692  /* calculate oldest segment by max_wal_size */
9693  XLByteToSeg(currpos, currSeg, wal_segment_size);
9695 
9696  if (currSeg > keepSegs)
9697  oldestSegMaxWalSize = currSeg - keepSegs;
9698  else
9699  oldestSegMaxWalSize = 1;
9700 
9701  /* the segment we care about */
9702  XLByteToSeg(targetLSN, targetSeg, wal_segment_size);
9703 
9704  /*
9705  * No point in returning reserved or extended status values if the
9706  * targetSeg is known to be lost.
9707  */
9708  if (targetSeg >= oldestSlotSeg)
9709  {
9710  /* show "reserved" when targetSeg is within max_wal_size */
9711  if (targetSeg >= oldestSegMaxWalSize)
9712  return WALAVAIL_RESERVED;
9713 
9714  /* being retained by slots exceeding max_wal_size */
9715  return WALAVAIL_EXTENDED;
9716  }
9717 
9718  /* WAL segments are no longer retained but haven't been removed yet */
9719  if (targetSeg >= oldestSeg)
9720  return WALAVAIL_UNRESERVED;
9721 
9722  /* Definitely lost */
9723  return WALAVAIL_REMOVED;
9724 }
#define ConvertToXSegs(x, segsize)
Definition: xlog.c:777
int wal_segment_size
Definition: xlog.c:118
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3987
int max_wal_size_mb
Definition: xlog.c:91
uint64 XLogSegNo
Definition: xlogdefs.h:41
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9738
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:11673
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ GetXLogInsertRecPtr()

XLogRecPtr GetXLogInsertRecPtr ( void  )

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

11658 {
11660  uint64 current_bytepos;
11661 
11662  SpinLockAcquire(&Insert->insertpos_lck);
11663  current_bytepos = Insert->CurrBytePos;
11664  SpinLockRelease(&Insert->insertpos_lck);
11665 
11666  return XLogBytePosToRecPtr(current_bytepos);
11667 }
slock_t insertpos_lck
Definition: xlog.c:542
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:2010
XLogCtlInsert Insert
Definition: xlog.c:601
#define SpinLockAcquire(lock)
Definition: spin.h:62
uint64 CurrBytePos
Definition: xlog.c:551
static void Insert(File file)
Definition: fd.c:1203
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:740

◆ GetXLogReceiptTime()

void GetXLogReceiptTime ( TimestampTz rtime,
bool fromStream 
)

Definition at line 6244 of file xlog.c.

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

Referenced by GetStandbyLimitTime().

6245 {
6246  /*
6247  * This must be executed in the startup process, since we don't export the
6248  * relevant state to shared memory.
6249  */
6250  Assert(InRecovery);
6251 
6252  *rtime = XLogReceiptTime;
6253  *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
6254 }
static XLogSource XLogReceiptSource
Definition: xlog.c:859
bool InRecovery
Definition: xlog.c:206
static TimestampTz XLogReceiptTime
Definition: xlog.c:858
#define Assert(condition)
Definition: c.h:792

◆ GetXLogReplayRecPtr()

XLogRecPtr GetXLogReplayRecPtr ( TimeLineID replayTLI)

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

11639 {
11640  XLogRecPtr recptr;
11641  TimeLineID tli;
11642 
11644  recptr = XLogCtl->lastReplayedEndRecPtr;
11645  tli = XLogCtl->lastReplayedTLI;
11647 
11648  if (replayTLI)
11649  *replayTLI = tli;
11650  return recptr;
11651 }
uint32 TimeLineID
Definition: xlogdefs.h:52
slock_t info_lck
Definition: xlog.c:737
#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:740
TimeLineID lastReplayedTLI
Definition: xlog.c:717
XLogRecPtr lastReplayedEndRecPtr
Definition: xlog.c:716

◆ GetXLogWriteRecPtr()

XLogRecPtr GetXLogWriteRecPtr ( void  )

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

11674 {
11678 
11679  return LogwrtResult.Write;
11680 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:786
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:624
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:740
XLogRecPtr Write
Definition: xlog.c:448

◆ HotStandbyActive()

bool HotStandbyActive ( void  )

Definition at line 8222 of file xlog.c.

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

Referenced by XLogWalRcvSendHSFeedback().

8223 {
8224  /*
8225  * We check shared state each time only until Hot Standby is active. We
8226  * can't de-activate Hot Standby, so there's no need to keep checking
8227  * after the shared variable has once been seen true.
8228  */
8230  return true;
8231  else
8232  {
8233  /* spinlock is essential on machines with weak memory ordering! */
8237 
8238  return LocalHotStandbyActive;
8239  }
8240 }
bool SharedHotStandbyActive
Definition: xlog.c:666
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool LocalHotStandbyActive
Definition: xlog.c:236
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:740

◆ HotStandbyActiveInReplay()

bool HotStandbyActiveInReplay ( void  )

Definition at line 8247 of file xlog.c.

References AmStartupProcess, Assert, IsPostmasterEnvironment, and LocalHotStandbyActive.

8248 {
8250  return LocalHotStandbyActive;
8251 }
#define AmStartupProcess()
Definition: miscadmin.h:432
bool IsPostmasterEnvironment
Definition: globals.c:109
static bool LocalHotStandbyActive
Definition: xlog.c:236
#define Assert(condition)
Definition: c.h:792

◆ InitXLOGAccess()

void InitXLOGAccess ( void  )

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

8415 {
8417 
8418  /* ThisTimeLineID doesn't change so we need no lock to copy it */
8421 
8422  /* set wal_segment_size */
8424 
8425  /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
8426  (void) GetRedoRecPtr();
8427  /* Also update our copy of doPageWrites. */
8428  doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);
8429 
8430  /* Also initialize the working areas for constructing WAL records */
8431  InitXLogInsert();
8432 }
int wal_segment_size
Definition: xlog.c:118
void InitXLogInsert(void)
Definition: xloginsert.c:1197
TimeLineID ThisTimeLineID
Definition: xlog.c:653
XLogCtlInsert Insert
Definition: xlog.c:601
bool fullPageWrites
Definition: xlog.c:576
uint32 xlog_seg_size
Definition: pg_control.h:209
static bool doPageWrites
Definition: xlog.c:382
bool forcePageWrites
Definition: xlog.c:575
static void Insert(File file)
Definition: fd.c:1203
static ControlFileData * ControlFile
Definition: xlog.c:748
TimeLineID ThisTimeLineID
Definition: xlog.c:193
#define Assert(condition)
Definition: c.h:792
static XLogCtlData * XLogCtl
Definition: xlog.c:740
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:8440
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:394

◆ issue_xlog_fsync()

void issue_xlog_fsync ( int  fd,
XLogSegNo  segno 
)

Definition at line 10566 of file xlog.c.

References _, elog, ereport, errcode_for_file_access(), errmsg(), 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, WAIT_EVENT_WAL_SYNC, wal_segment_size, and XLogFileName.

Referenced by XLogWalRcvFlush(), and XLogWrite().

10567 {
10568  char *msg = NULL;
10569 
10571  switch (sync_method)
10572  {
10573  case SYNC_METHOD_FSYNC:
10574  if (pg_fsync_no_writethrough(fd) != 0)
10575  msg = _("could not fsync file \"%s\": %m");
10576  break;
10577 #ifdef HAVE_FSYNC_WRITETHROUGH
10579  if (pg_fsync_writethrough(fd) != 0)
10580  msg = _("could not fsync write-through file \"%s\": %m");
10581  break;
10582 #endif
10583 #ifdef HAVE_FDATASYNC
10584  case SYNC_METHOD_FDATASYNC:
10585  if (pg_fdatasync(fd) != 0)
10586  msg = _("could not fdatasync file \"%s\": %m");
10587  break;
10588 #endif
10589  case SYNC_METHOD_OPEN:
10591  /* write synced it already */
10592  break;
10593  default:
10594  elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
10595  break;
10596  }
10597 
10598  /* PANIC if failed to fsync */
10599  if (msg)
10600  {
10601  char xlogfname[MAXFNAMELEN];
10602  int save_errno = errno;
10603 
10604  XLogFileName(xlogfname, ThisTimeLineID, segno,
10606  errno = save_errno;
10607  ereport(PANIC,
10609  errmsg(msg, xlogfname)));
10610  }
10611 
10613 }
int pg_fdatasync(int fd)
Definition: fd.c:437
int wal_segment_size
Definition: xlog.c:118
#define SYNC_METHOD_FSYNC_WRITETHROUGH
Definition: xlog.h:28
int pg_fsync_writethrough(int fd)
Definition: fd.c:414
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:402
#define PANIC
Definition: elog.h:55
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define SYNC_METHOD_OPEN_DSYNC
Definition: xlog.h:29
int errcode_for_file_access(void)
Definition: elog.c:727
#define SYNC_METHOD_FSYNC
Definition: xlog.h:25
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1512
#define SYNC_METHOD_OPEN
Definition: xlog.h:27
#define MAXFNAMELEN
TimeLineID ThisTimeLineID
Definition: xlog.c:193
#define ereport(elevel,...)
Definition: elog.h:155
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1488
int sync_method
Definition: xlog.c:107
#define SYNC_METHOD_FDATASYNC
Definition: xlog.h:26
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define elog(elevel,...)
Definition: elog.h:228
#define _(x)
Definition: elog.c:89

◆ LocalProcessControlFile()

void LocalProcessControlFile ( bool  reset)

Definition at line 5061 of file xlog.c.

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

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

5062 {
5063  Assert(reset || ControlFile == NULL);
5064  ControlFile = palloc(sizeof(ControlFileData));
5065  ReadControlFile();
5066 }
static void ReadControlFile(void)
Definition: xlog.c:4732
static ControlFileData * ControlFile
Definition: xlog.c:748
#define Assert(condition)
Definition: c.h:792
void * palloc(Size size)
Definition: mcxt.c:950

◆ PromoteIsTriggered()

bool PromoteIsTriggered ( void  )

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

12718 {
12719  /*
12720  * We check shared state each time only until a standby promotion is
12721  * triggered. We can't trigger a promotion again, so there's no need to
12722  * keep checking after the shared variable has once been seen true.
12723  */
12725  return true;
12726 
12730 
12731  return LocalPromoteIsTriggered;
12732 }
slock_t info_lck
Definition: xlog.c:737
static bool LocalPromoteIsTriggered
Definition: xlog.c:242
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:740
bool SharedPromoteIsTriggered
Definition: xlog.c:672

◆ RecoveryInProgress()

bool RecoveryInProgress ( void  )

Definition at line 8148 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(), 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(), GlobalVisTestFor(), 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_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(), StartTransaction(), TransactionIdIsInProgress(), TruncateMultiXact(), UpdateFullPageWrites(), WalReceiverMain(), WalSndWaitForWal(), XLogBackgroundFlush(), XLogInsertAllowed(), XLogNeedsFlush(), and XLogSendPhysical().

8149 {
8150  /*
8151  * We check shared state each time only until we leave recovery mode. We
8152  * can't re-enter recovery, so there's no need to keep checking after the
8153  * shared variable has once been seen false.
8154  */
8156  return false;
8157  else
8158  {
8159  /*
8160  * use volatile pointer to make sure we make a fresh read of the
8161  * shared variable.
8162  */
8163  volatile XLogCtlData *xlogctl = XLogCtl;
8164 
8166 
8167  /*
8168  * Initialize TimeLineID and RedoRecPtr when we discover that recovery
8169  * is finished. InitPostgres() relies upon this behaviour to ensure
8170  * that InitXLOGAccess() is called at backend startup. (If you change
8171  * this, see also LocalSetXLogInsertAllowed.)
8172  */
8174  {
8175  /*
8176  * If we just exited recovery, make sure we read TimeLineID and
8177  * RedoRecPtr after SharedRecoveryState (for machines with weak
8178  * memory ordering).
8179  */
8181  InitXLOGAccess();
8182  }
8183 
8184  /*
8185  * Note: We don't need a memory barrier when we're still in recovery.
8186  * We might exit recovery immediately after return, so the caller
8187  * can't rely on 'true' meaning that we're still in recovery anyway.
8188  */
8189 
8190  return LocalRecoveryInProgress;
8191  }
8192 }
void InitXLOGAccess(void)
Definition: xlog.c:8414
RecoveryState SharedRecoveryState
Definition: xlog.c:660
#define pg_memory_barrier()
Definition: atomics.h:145
static XLogCtlData * XLogCtl
Definition: xlog.c:740
static bool LocalRecoveryInProgress
Definition: xlog.c:230

◆ RecoveryIsPaused()

bool RecoveryIsPaused ( void  )

Definition at line 6068 of file xlog.c.

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

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

6069 {
6070  bool recoveryPause;
6071 
6073  recoveryPause = XLogCtl->recoveryPause;
6075 
6076  return recoveryPause;
6077 }
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:729
static XLogCtlData * XLogCtl
Definition: xlog.c:740

◆ register_persistent_abort_backup_handler()

void register_persistent_abort_backup_handler ( void  )

Definition at line 11622 of file xlog.c.

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

Referenced by pg_start_backup().

11623 {
11624  static bool already_done = false;
11625 
11626  if (already_done)
11627  return;
11629  already_done = true;
11630 }
void do_pg_abort_backup(int code, Datum arg)
Definition: xlog.c:11590
#define DatumGetBool(X)
Definition: postgres.h:393
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333

◆ RemovePromoteSignalFiles()

void RemovePromoteSignalFiles ( void  )

Definition at line 12789 of file xlog.c.

References PROMOTE_SIGNAL_FILE.

Referenced by CheckForStandbyTrigger(), and PostmasterMain().

12790 {
12791  unlink(PROMOTE_SIGNAL_FILE);
12792 }
#define PROMOTE_SIGNAL_FILE
Definition: xlog.h:396

◆ SetRecoveryPause()

void SetRecoveryPause ( bool  recoveryPause)

Definition at line 6080 of file xlog.c.

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

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

6081 {
6083  XLogCtl->recoveryPause = recoveryPause;
6085 }
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:729
static XLogCtlData * XLogCtl
Definition: xlog.c:740

◆ SetWalWriterSleeping()

void SetWalWriterSleeping ( bool  sleeping)

Definition at line 12822 of file xlog.c.

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

Referenced by WalWriterMain().

12823 {
12825  XLogCtl->WalWriterSleeping = sleeping;
12827 }
slock_t info_lck
Definition: xlog.c:737
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool WalWriterSleeping
Definition: xlog.c:679
static XLogCtlData * XLogCtl
Definition: xlog.c:740

◆ ShutdownXLOG()

void ShutdownXLOG ( int  code,
Datum  arg 
)

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

8565 {
8566  /*
8567  * We should have an aux process resource owner to use, and we should not
8568  * be in a transaction that's installed some other resowner.
8569  */
8571  Assert(CurrentResourceOwner == NULL ||
8574 
8575  /* Don't be chatty in standalone mode */
8577  (errmsg("shutting down")));
8578 
8579  /*
8580  * Signal walsenders to move to stopping state.
8581  */
8583 
8584  /*
8585  * Wait for WAL senders to be in stopping state. This prevents commands
8586  * from writing new WAL.
8587  */
8589 
8590  if (RecoveryInProgress())
8592  else
8593  {
8594  /*
8595  * If archiving is enabled, rotate the last XLOG file so that all the
8596  * remaining records are archived (postmaster wakes up the archiver
8597  * process one more time at the end of shutdown). The checkpoint
8598  * record will go to the next XLOG file and won't be archived (yet).
8599  */
8601  RequestXLogSwitch(false);
8602 
8604  }
8605 }
bool IsPostmasterEnvironment
Definition: globals.c:109
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9831
void CreateCheckPoint(int flags)
Definition: xlog.c:8830
ResourceOwner CurrentResourceOwner
Definition: resowner.c:144
bool CreateRestartPoint(int flags)
Definition: xlog.c:9389
#define XLogArchiveCommandSet()
Definition: xlog.h:185
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8148
ResourceOwner AuxProcessResourceOwner
Definition: resowner.c:147
void WalSndWaitStopping(void)
Definition: walsender.c:3163
#define ereport(elevel,...)
Definition: elog.h:155
#define NOTICE
Definition: elog.h:37
void WalSndInitStopping(void)
Definition: walsender.c:3137
#define Assert(condition)
Definition: c.h:792
#define XLogArchivingActive()
Definition: xlog.h:180
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:224
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:221

◆ StartupRequestWalReceiverRestart()

void StartupRequestWalReceiverRestart ( void  )

Definition at line 12666 of file xlog.c.

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

Referenced by StartupRereadConfig().

12667 {
12669  {
12670  ereport(LOG,
12671  (errmsg("WAL receiver process shutdown requested")));
12672 
12673  pendingWalRcvRestart = true;
12674  }
12675 }
#define LOG
Definition: elog.h:26
static bool pendingWalRcvRestart
Definition: xlog.c:841
#define ereport(elevel,...)
Definition: elog.h:155
static XLogSource currentSource
Definition: xlog.c:839
int errmsg(const char *fmt,...)
Definition: elog.c:915
bool WalRcvRunning(void)

◆ StartupXLOG()

void StartupXLOG ( void  )

Definition at line 6377 of file xlog.c.

References AdvanceNextFullTransactionIdPastXid(), AdvanceOldestClogXid(), AllowCascadeReplication, appendStringInfo(), appendStringInfoString(), ArchiveRecoveryRequested, ErrorContextCallback::arg, Assert, AuxProcessResourceOwner, BACKUP_LABEL_FILE, BACKUP_LABEL_OLD, ControlFileData::backupEndPoint, ControlFileData::backupEndRequired, ControlFileData::backupStartPoint, bgwriterLaunched, buf, ErrorContextCallback::callback, ControlFileData::checkPoint, CHECKPOINT_END_OF_RECOVERY, CHECKPOINT_FORCE, CHECKPOINT_IMMEDIATE, CHECKPOINT_WAIT, ControlFileData::checkPointCopy, CheckRecoveryConsistency(), CheckRequiredParameterValues(), checkTimeLineSwitch(), checkXLogConsistency(), XLogCtlData::ckptFullXid, close, CompleteCommitTsInitialization(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), 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, EnableSyncRequestForwarding(), EndRecPtr, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), errmsg_internal(), ERROR, error_context_stack, ExecuteRecoveryCommand(), exitArchiveRecovery(), FATAL, findNewestTimeLine(), FirstNormalUnloggedLSN, XLogwrtRqst::Flush, XLogwrtResult::Flush, CheckPoint::fullPageWrites, XLogCtlInsert::fullPageWrites, FullTransactionIdRetreat(), GetCurrentTimestamp(), GetLatestXTime(), HandleStartupProcInterrupts(), InArchiveRecovery, XLogCtlData::info_lck, XLogCtlData::InitializedUpTo, InitRecoveryTransactionEnvironment(), initStringInfo(), InRecovery, InRedo, Insert(), XLogCtlData::Insert, InvalidXLogRecPtr, IsPostmasterEnvironment, IsUnderPostmaster, lastFullPageWrites, LastRec, XLogCtlData::lastReplayedEndRecPtr, XLogCtlData::lastReplayedTLI, XLogCtlData::lastSegSwitchLSN, XLogCtlData::lastSegSwitchTime, RunningTransactionsData::latestCompletedXid, VariableCacheData::latestCompletedXid, lfirst, LocalPromoteIsTriggered, LocalSetXLogInsertAllowed(), LocalXLogInsertAllowed, LOG, XLogCtlData::LogwrtResult, LogwrtResult, XLogCtlData::LogwrtRqst, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXFNAMELEN, MAXPGPATH, MemSet, ControlFileData::minRecoveryPoint, minRecoveryPoint, ControlFileData::minRecoveryPointTLI, minRecoveryPointTLI, 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, 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_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(), recoveryEndCommand, XLogCtlData::recoveryLastXTime, XLogCtlData::recoveryPause, recoveryPausesHere(), recoveryStopAfter, recoveryStopLSN, recoveryStopName, recoveryStopsAfter(), recoveryStopsBefore(), recoveryStopTime, recoveryStopXid, 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(), ShutdownWalRcv(), 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, XLByteToPrevSeg, XLOG_CHECKPOINT_SHUTDOWN, XLOG_END_OF_RECOVERY, xlog_outdesc(), XLogArchiveCleanup(), XLogArchiveIsReadyOrDone(), XLogArchiveNotify(), XLogArchivingActive, XLogBeginRead(), XLOGDIR, XLogFileName, XLogFilePath, XLogPageRead(), xlogreader, XLogReaderAllocate(), XLogReaderFree(), XLogReceiptTime, XLogRecGetData, XLogRecPtrIsInvalid, XLogRecPtrToBufIdx, XLogRecPtrToBytePos(), XLogReportParameters(), XLogSegmentOffset, XLR_CHECK_CONSISTENCY, XLR_INFO_MASK, and XRecOffIsValid.

Referenced by InitPostgres(), and StartupProcessMain().

6378 {
6380  CheckPoint checkPoint;
6381  bool wasShutdown;
6382  bool reachedRecoveryTarget = false;
6383  bool haveBackupLabel = false;
6384  bool haveTblspcMap = false;
6385  XLogRecPtr RecPtr,
6386  checkPointLoc,
6387  EndOfLog;
6388  TimeLineID EndOfLogTLI;
6389  TimeLineID PrevTimeLineID;
6390  XLogRecord *record;
6391  TransactionId oldestActiveXID;
6392  bool backupEndRequired = false;
6393  bool backupFromStandby = false;
6394  DBState dbstate_at_startup;
6396  XLogPageReadPrivate private;
6397  bool promoted = false;
6398  struct stat st;
6399 
6400  /*
6401  * We should have an aux process resource owner to use, and we should not
6402  * be in a transaction that's installed some other resowner.
6403  */
6405  Assert(CurrentResourceOwner == NULL ||
6408 
6409  /*
6410  * Check that contents look valid.
6411  */
6413  ereport(FATAL,
6414  (errmsg("control file contains invalid checkpoint location")));
6415 
6416  switch (ControlFile->state)
6417  {
6418  case DB_SHUTDOWNED:
6419 
6420  /*
6421  * This is the expected case, so don't be chatty in standalone
6422  * mode
6423  */
6425  (errmsg("database system was shut down at %s",
6426  str_time(ControlFile->time))));
6427  break;
6428 
6430  ereport(LOG,
6431  (errmsg("database system was shut down in recovery at %s",
6432  str_time(ControlFile->time))));
6433  break;
6434 
6435  case DB_SHUTDOWNING:
6436  ereport(LOG,
6437  (errmsg("database system shutdown was interrupted; last known up at %s",
6438  str_time(ControlFile->time))));
6439  break;
6440 
6441  case DB_IN_CRASH_RECOVERY:
6442  ereport(LOG,
6443  (errmsg("database system was interrupted while in recovery at %s",
6445  errhint("This probably means that some data is corrupted and"
6446  " you will have to use the last backup for recovery.")));
6447  break;
6448 
6450  ereport(LOG,
6451  (errmsg("database system was interrupted while in recovery at log time %s",
6453  errhint("If this has occurred more than once some data might be corrupted"
6454  " and you might need to choose an earlier recovery target.")));
6455  break;
6456 
6457  case DB_IN_PRODUCTION:
6458  ereport(LOG,
6459  (errmsg("database system was interrupted; last known up at %s",
6460  str_time(ControlFile->time))));
6461  break;
6462 
6463  default:
6464  ereport(FATAL,
6465  (errmsg("control file contains invalid database cluster state")));
6466  }
6467 
6468  /* This is just to allow attaching to startup process with a debugger */
6469 #ifdef XLOG_REPLAY_DELAY
6471  pg_usleep(60000000L);
6472 #endif
6473 
6474  /*
6475  * Verify that pg_wal and pg_wal/archive_status exist. In cases where
6476  * someone has performed a copy for PITR, these directories may have been
6477  * excluded and need to be re-created.
6478  */
6480 
6481  /*----------
6482  * If we previously crashed, perform a couple of actions:
6483  *
6484  * - The pg_wal directory may still include some temporary WAL segments
6485  * used when creating a new segment, so perform some clean up to not
6486  * bloat this path. This is done first as there is no point to sync
6487  * this temporary data.
6488  *
6489  * - There might be data which we had written, intending to fsync it, but
6490  * which we had not actually fsync'd yet. Therefore, a power failure in
6491  * the near future might cause earlier unflushed writes to be lost, even
6492  * though more recent data written to disk from here on would be
6493  * persisted. To avoid that, fsync the entire data directory.
6494  */
6495  if (ControlFile->state != DB_SHUTDOWNED &&
6497  {
6500  }
6501 
6502  /*
6503  * Initialize on the assumption we want to recover to the latest timeline
6504  * that's active according to pg_control.
6505  */
6509  else
6511 
6512  /*
6513  * Check for signal files, and if so set up state for offline recovery
6514  */
6517 
6519  {
6521  ereport(LOG,
6522  (errmsg("entering standby mode")));
6523  else if (recoveryTarget == RECOVERY_TARGET_XID)
6524  ereport(LOG,
6525  (errmsg("starting point-in-time recovery to XID %u",
6526  recoveryTargetXid)));
6528  ereport(LOG,
6529  (errmsg("starting point-in-time recovery to %s",
6532  ereport(LOG,
6533  (errmsg("starting point-in-time recovery to \"%s\"",
6534  recoveryTargetName)));
6535  else if (recoveryTarget == RECOVERY_TARGET_LSN)
6536  ereport(LOG,
6537  (errmsg("starting point-in-time recovery to WAL location (LSN) \"%X/%X\"",
6538  (uint32) (recoveryTargetLSN >> 32),
6541  ereport(LOG,
6542  (errmsg("starting point-in-time recovery to earliest consistent point")));
6543  else
6544  ereport(LOG,
6545  (errmsg("starting archive recovery")));
6546  }
6547 
6548  /*
6549  * Take ownership of the wakeup latch if we're going to sleep during
6550  * recovery.
6551  */
6554 
6555  /* Set up XLOG reader facility */
6556  MemSet(&private, 0, sizeof(XLogPageReadPrivate));
6557  xlogreader =
6559  XL_ROUTINE(.page_read = &XLogPageRead,
6560  .segment_open = NULL,
6561  .segment_close = wal_segment_close),
6562  &private);
6563  if (!xlogreader)
6564  ereport(ERROR,
6565  (errcode(ERRCODE_OUT_OF_MEMORY),
6566  errmsg("out of memory"),
6567  errdetail("Failed while allocating a WAL reading processor.")));
6569 
6570  /*
6571  * Allocate two page buffers dedicated to WAL consistency checks. We do
6572  * it this way, rather than just making static arrays, for two reasons:
6573  * (1) no need to waste the storage in most instantiations of the backend;
6574  * (2) a static char array isn't guaranteed to have any particular
6575  * alignment, whereas palloc() will provide MAXALIGN'd storage.
6576  */
6577  replay_image_masked = (char *) palloc(BLCKSZ);
6578  primary_image_masked = (char *) palloc(BLCKSZ);
6579 
6580  if (read_backup_label(&checkPointLoc, &backupEndRequired,
6581  &backupFromStandby))
6582  {
6583  List *tablespaces = NIL;
6584 
6585  /*
6586  * Archive recovery was requested, and thanks to the backup label
6587  * file, we know how far we need to replay to reach consistency. Enter
6588  * archive recovery directly.
6589  */
6590  InArchiveRecovery = true;
6592  StandbyMode = true;
6593 
6594  /*
6595  * When a backup_label file is present, we want to roll forward from
6596  * the checkpoint it identifies, rather than using pg_control.
6597  */
6598  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 0, true);
6599  if (record != NULL)
6600  {
6601  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
6602  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
6603  ereport(DEBUG1,
6604  (errmsg("checkpoint record is at %X/%X",
6605  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6606  InRecovery = true; /* force recovery even if SHUTDOWNED */
6607 
6608  /*
6609  * Make sure that REDO location exists. This may not be the case
6610  * if there was a crash during an online backup, which left a
6611  * backup_label around that references a WAL segment that's
6612  * already been archived.
6613  */
6614  if (checkPoint.redo < checkPointLoc)
6615  {
6616  XLogBeginRead(xlogreader, checkPoint.redo);
6617  if (!ReadRecord(xlogreader,