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_CAUSE_XLOG   0x0040 /* XLOG consumption */
 
#define CHECKPOINT_CAUSE_TIME   0x0080 /* Elapsed time */
 
#define XLOG_INCLUDE_ORIGIN   0x01 /* include the replication origin */
 
#define XLOG_MARK_UNIMPORTANT   0x02 /* record not important for durability */
 
#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"
 

Typedefs

typedef enum ArchiveMode ArchiveMode
 
typedef enum WalLevel WalLevel
 
typedef struct CheckpointStatsData CheckpointStatsData
 
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  ArchiveMode { ARCHIVE_MODE_OFF = 0, ARCHIVE_MODE_ON, ARCHIVE_MODE_ALWAYS }
 
enum  WalLevel { WAL_LEVEL_MINIMAL = 0, WAL_LEVEL_REPLICA, WAL_LEVEL_LOGICAL }
 
enum  SessionBackupState { SESSION_BACKUP_NONE, SESSION_BACKUP_EXCLUSIVE, SESSION_BACKUP_NON_EXCLUSIVE }
 

Functions

XLogRecPtr XLogInsertRecord (struct XLogRecData *rdata, XLogRecPtr fpw_lsn, uint8 flags)
 
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)
 
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)
 
char * XLogFileNameP (TimeLineID tli, XLogSegNo segno)
 
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)
 
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 GetNextXidAndEpoch (TransactionId *xid, uint32 *epoch)
 
void RemovePromoteSignalFiles (void)
 
bool CheckPromoteSignal (void)
 
void WakeupRecovery (void)
 
void SetWalWriterSleeping (bool sleeping)
 
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 infotbssize, bool needtblspcmapfile)
 
XLogRecPtr do_pg_stop_backup (char *labelfile, bool waitforarchive, TimeLineID *stoptli_p)
 
void do_pg_abort_backup (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_segments
 
int XLOGbuffers
 
int XLogArchiveTimeout
 
int wal_retrieve_retry_interval
 
char * XLogArchiveCommand
 
bool EnableHotStandby
 
bool fullPageWrites
 
bool wal_log_hints
 
bool wal_compression
 
boolwal_consistency_checking
 
char * wal_consistency_checking_string
 
bool log_checkpoints
 
int CheckPointSegments
 
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 323 of file xlog.h.

Referenced by CancelBackup(), and StartupXLOG().

◆ CHECKPOINT_CAUSE_TIME

#define CHECKPOINT_CAUSE_TIME   0x0080 /* Elapsed time */

Definition at line 187 of file xlog.h.

Referenced by CheckpointerMain(), and LogCheckpointStart().

◆ CHECKPOINT_CAUSE_XLOG

#define CHECKPOINT_CAUSE_XLOG   0x0040 /* XLOG consumption */

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

Referenced by BufferSync(), CheckpointerMain(), CreateCheckPoint(), LogCheckpointStart(), and StartupXLOG().

◆ CHECKPOINT_FLUSH_ALL

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

Definition at line 181 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_WAIT

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

◆ InHotStandby

◆ 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 326 of file xlog.h.

Referenced by CancelBackup(), and StartupXLOG().

◆ XLOG_INCLUDE_ORIGIN

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

◆ XLOG_MARK_UNIMPORTANT

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

◆ XLogArchiveCommandSet

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

Definition at line 140 of file xlog.h.

Referenced by pgarch_ArchiverCopyLoop(), and ShutdownXLOG().

◆ XLogArchivingActive

◆ XLogArchivingAlways

Definition at line 138 of file xlog.h.

Referenced by do_pg_stop_backup(), and sigusr1_handler().

◆ XLogHintBitIsNeeded

◆ XLogIsNeeded

◆ XLogLogicalInfoActive

#define XLogLogicalInfoActive ( )    (wal_level >= WAL_LEVEL_LOGICAL)

◆ XLogStandbyInfoActive

Typedef Documentation

◆ ArchiveMode

◆ CheckpointStatsData

◆ SessionBackupState

◆ WalLevel

Enumeration Type Documentation

◆ ArchiveMode

Enumerator
ARCHIVE_MODE_OFF 
ARCHIVE_MODE_ON 
ARCHIVE_MODE_ALWAYS 

Definition at line 116 of file xlog.h.

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

◆ HotStandbyState

Enumerator
STANDBY_DISABLED 
STANDBY_INITIALIZED 
STANDBY_SNAPSHOT_PENDING 
STANDBY_SNAPSHOT_READY 

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

◆ WalLevel

enum WalLevel
Enumerator
WAL_LEVEL_MINIMAL 
WAL_LEVEL_REPLICA 
WAL_LEVEL_LOGICAL 

Definition at line 125 of file xlog.h.

Function Documentation

◆ assign_checkpoint_completion_target()

void assign_checkpoint_completion_target ( double  newval,
void *  extra 
)

Definition at line 2272 of file xlog.c.

References CalculateCheckpointSegments(), CheckPointCompletionTarget, and newval.

2273 {
2276 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2236
#define newval
double CheckPointCompletionTarget
Definition: checkpointer.c:147

◆ assign_max_wal_size()

void assign_max_wal_size ( int  newval,
void *  extra 
)

Definition at line 2265 of file xlog.c.

References CalculateCheckpointSegments(), max_wal_size_mb, and newval.

2266 {
2269 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2236
int max_wal_size_mb
Definition: xlog.c:89
#define newval

◆ BootStrapXLOG()

void BootStrapXLOG ( void  )

Definition at line 5026 of file xlog.c.

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

Referenced by AuxiliaryProcessMain().

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

◆ CheckPromoteSignal()

bool CheckPromoteSignal ( void  )

Definition at line 12268 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, PROMOTE_SIGNAL_FILE, and stat.

Referenced by sigusr1_handler().

12269 {
12270  struct stat stat_buf;
12271 
12272  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0 ||
12274  return true;
12275 
12276  return false;
12277 }
#define FALLBACK_PROMOTE_SIGNAL_FILE
Definition: xlog.c:85
struct stat stat_buf
Definition: pg_standby.c:103
#define PROMOTE_SIGNAL_FILE
Definition: xlog.c:84
#define stat(a, b)
Definition: win32_port.h:266

◆ CheckXLogRemoved()

void CheckXLogRemoved ( XLogSegNo  segno,
TimeLineID  tli 
)

Definition at line 3794 of file xlog.c.

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

Referenced by perform_base_backup(), and XLogRead().

3795 {
3796  int save_errno = errno;
3797  XLogSegNo lastRemovedSegNo;
3798 
3800  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3802 
3803  if (segno <= lastRemovedSegNo)
3804  {
3805  char filename[MAXFNAMELEN];
3806 
3807  XLogFileName(filename, tli, segno, wal_segment_size);
3808  errno = save_errno;
3809  ereport(ERROR,
3811  errmsg("requested WAL segment %s has already been removed",
3812  filename)));
3813  }
3814  errno = save_errno;
3815 }
int wal_segment_size
Definition: xlog.c:113
slock_t info_lck
Definition: xlog.c:704
XLogSegNo lastRemovedSegNo
Definition: xlog.c:587
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define ERROR
Definition: elog.h:43
uint64 XLogSegNo
Definition: xlogdefs.h:34
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static XLogCtlData * XLogCtl
Definition: xlog.c:707
static char * filename
Definition: pg_dumpall.c:87
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ CreateCheckPoint()

void CreateCheckPoint ( int  flags)

Definition at line 8587 of file xlog.c.

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

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

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

◆ CreateRestartPoint()

bool CreateRestartPoint ( int  flags)

Definition at line 9133 of file xlog.c.

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

Referenced by CheckpointerMain(), and ShutdownXLOG().

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

◆ DataChecksumsEnabled()

bool DataChecksumsEnabled ( void  )

Definition at line 4761 of file xlog.c.

References Assert, and ControlFileData::data_checksum_version.

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

4762 {
4763  Assert(ControlFile != NULL);
4764  return (ControlFile->data_checksum_version > 0);
4765 }
uint32 data_checksum_version
Definition: pg_control.h:221
static ControlFileData * ControlFile
Definition: xlog.c:715
#define Assert(condition)
Definition: c.h:699

◆ do_pg_abort_backup()

void do_pg_abort_backup ( void  )

Definition at line 11166 of file xlog.c.

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

Referenced by base_backup_cleanup(), and nonexclusive_base_backup_cleanup().

11167 {
11168  /*
11169  * Quick exit if session is not keeping around a non-exclusive backup
11170  * already started.
11171  */
11173  return;
11174 
11179 
11182  {
11183  XLogCtl->Insert.forcePageWrites = false;
11184  }
11186 }
static void WALInsertLockRelease(void)
Definition: xlog.c:1671
static SessionBackupState sessionBackupState
Definition: xlog.c:512
XLogCtlInsert Insert
Definition: xlog.c:577
bool forcePageWrites
Definition: xlog.c:551
int nonExclusiveBackups
Definition: xlog.c:563
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:562
#define Assert(condition)
Definition: c.h:699
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1642
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ do_pg_start_backup()

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

Definition at line 10244 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, sendTablespace(), SESSION_BACKUP_EXCLUSIVE, SESSION_BACKUP_NON_EXCLUSIVE, sessionBackupState, tablespaceinfo::size, snprintf(), SpinLockAcquire, SpinLockRelease, stat, TABLESPACE_MAP, CheckPoint::ThisTimeLineID, wal_segment_size, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), WARNING, XLByteToSeg, XLogFileName, and XLogIsNeeded.

Referenced by perform_base_backup(), and pg_start_backup().

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

◆ do_pg_stop_backup()

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

Definition at line 10761 of file xlog.c.

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

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

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

◆ get_backup_status()

SessionBackupState get_backup_status ( void  )

Definition at line 10742 of file xlog.c.

References sessionBackupState.

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

10743 {
10744  return sessionBackupState;
10745 }
static SessionBackupState sessionBackupState
Definition: xlog.c:512

◆ GetCurrentChunkReplayStartTime()

TimestampTz GetCurrentChunkReplayStartTime ( void  )

Definition at line 6189 of file xlog.c.

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

Referenced by GetReplicationApplyDelay().

6190 {
6191  TimestampTz xtime;
6192 
6194  xtime = XLogCtl->currentChunkStartTime;
6196 
6197  return xtime;
6198 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
TimestampTz currentChunkStartTime
Definition: xlog.c:694

◆ GetFakeLSNForUnloggedRel()

XLogRecPtr GetFakeLSNForUnloggedRel ( void  )

Definition at line 4777 of file xlog.c.

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

Referenced by gistGetFakeLSN().

4778 {
4779  XLogRecPtr nextUnloggedLSN;
4780 
4781  /* increment the unloggedLSN counter, need SpinLock */
4783  nextUnloggedLSN = XLogCtl->unloggedLSN++;
4785 
4786  return nextUnloggedLSN;
4787 }
XLogRecPtr unloggedLSN
Definition: xlog.c:590
#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:707
slock_t ulsn_lck
Definition: xlog.c:591

◆ GetFlushRecPtr()

XLogRecPtr GetFlushRecPtr ( void  )

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

8282 {
8286 
8287  return LogwrtResult.Flush;
8288 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:751
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:601
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
XLogRecPtr Flush
Definition: xlog.c:426

◆ GetFullPageWriteInfo()

void GetFullPageWriteInfo ( XLogRecPtr RedoRecPtr_p,
bool doPageWrites_p 
)

Definition at line 8250 of file xlog.c.

References doPageWrites, and RedoRecPtr.

Referenced by XLogCheckBufferNeedsBackup(), and XLogInsert().

8251 {
8252  *RedoRecPtr_p = RedoRecPtr;
8253  *doPageWrites_p = doPageWrites;
8254 }
static bool doPageWrites
Definition: xlog.c:359
static XLogRecPtr RedoRecPtr
Definition: xlog.c:352

◆ GetInsertRecPtr()

XLogRecPtr GetInsertRecPtr ( void  )

Definition at line 8265 of file xlog.c.

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

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

8266 {
8267  XLogRecPtr recptr;
8268 
8270  recptr = XLogCtl->LogwrtRqst.Write;
8272 
8273  return recptr;
8274 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr Write
Definition: xlog.c:419
XLogwrtRqst LogwrtRqst
Definition: xlog.c:580
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ GetLastImportantRecPtr()

XLogRecPtr GetLastImportantRecPtr ( void  )

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

8300 {
8302  int i;
8303 
8304  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
8305  {
8306  XLogRecPtr last_important;
8307 
8308  /*
8309  * Need to take a lock to prevent torn reads of the LSN, which are
8310  * possible on some of the supported platforms. WAL insert locks only
8311  * support exclusive mode, so we have to use that.
8312  */
8314  last_important = WALInsertLocks[i].l.lastImportantAt;
8315  LWLockRelease(&WALInsertLocks[i].l.lock);
8316 
8317  if (res < last_important)
8318  res = last_important;
8319  }
8320 
8321  return res;
8322 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogRecPtr lastImportantAt
Definition: xlog.c:469
#define NUM_XLOGINSERT_LOCKS
Definition: xlog.c:120
WALInsertLock l
Definition: xlog.c:481
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1725
uint64 XLogRecPtr
Definition: xlogdefs.h:21
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1121
int i
static WALInsertLockPadded * WALInsertLocks
Definition: xlog.c:710

◆ GetLatestXTime()

TimestampTz GetLatestXTime ( void  )

Definition at line 6159 of file xlog.c.

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

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

6160 {
6161  TimestampTz xtime;
6162 
6164  xtime = XLogCtl->recoveryLastXTime;
6166 
6167  return xtime;
6168 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz recoveryLastXTime
Definition: xlog.c:688
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ GetMockAuthenticationNonce()

char* GetMockAuthenticationNonce ( void  )

Definition at line 4751 of file xlog.c.

References Assert, and ControlFileData::mock_authentication_nonce.

Referenced by scram_mock_salt().

4752 {
4753  Assert(ControlFile != NULL);
4755 }
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:228
static ControlFileData * ControlFile
Definition: xlog.c:715
#define Assert(condition)
Definition: c.h:699

◆ GetNextXidAndEpoch()

void GetNextXidAndEpoch ( TransactionId xid,
uint32 epoch 
)

Definition at line 8350 of file xlog.c.

References XLogCtlData::ckptXid, XLogCtlData::ckptXidEpoch, XLogCtlData::info_lck, ReadNewTransactionId(), SpinLockAcquire, and SpinLockRelease.

Referenced by load_xid_epoch(), TransactionIdInRecentPast(), and XLogWalRcvSendHSFeedback().

8351 {
8352  uint32 ckptXidEpoch;
8353  TransactionId ckptXid;
8354  TransactionId nextXid;
8355 
8356  /* Must read checkpoint info first, else have race condition */
8358  ckptXidEpoch = XLogCtl->ckptXidEpoch;
8359  ckptXid = XLogCtl->ckptXid;
8361 
8362  /* Now fetch current nextXid */
8363  nextXid = ReadNewTransactionId();
8364 
8365  /*
8366  * nextXid is certainly logically later than ckptXid. So if it's
8367  * numerically less, it must have wrapped into the next epoch.
8368  */
8369  if (nextXid < ckptXid)
8370  ckptXidEpoch++;
8371 
8372  *xid = nextXid;
8373  *epoch = ckptXidEpoch;
8374 }
TransactionId ckptXid
Definition: xlog.c:583
uint32 TransactionId
Definition: c.h:474
slock_t info_lck
Definition: xlog.c:704
uint32 ckptXidEpoch
Definition: xlog.c:582
#define SpinLockAcquire(lock)
Definition: spin.h:62
TransactionId ReadNewTransactionId(void)
Definition: varsup.c:250
unsigned int uint32
Definition: c.h:325
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
static const unsigned __int64 epoch
Definition: gettimeofday.c:34

◆ GetRedoRecPtr()

XLogRecPtr GetRedoRecPtr ( void  )

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

8223 {
8224  XLogRecPtr ptr;
8225 
8226  /*
8227  * The possibly not up-to-date copy in XlogCtl is enough. Even if we
8228  * grabbed a WAL insertion lock to read the master copy, someone might
8229  * update it just after we've released the lock.
8230  */
8232  ptr = XLogCtl->RedoRecPtr;
8234 
8235  if (RedoRecPtr < ptr)
8236  RedoRecPtr = ptr;
8237 
8238  return RedoRecPtr;
8239 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
static XLogRecPtr RedoRecPtr
Definition: xlog.c:352
XLogRecPtr RedoRecPtr
Definition: xlog.c:581
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ GetSystemIdentifier()

uint64 GetSystemIdentifier ( void  )

Definition at line 4741 of file xlog.c.

References Assert, and ControlFileData::system_identifier.

Referenced by IdentifySystem(), and WalReceiverMain().

4742 {
4743  Assert(ControlFile != NULL);
4745 }
uint64 system_identifier
Definition: pg_control.h:106
static ControlFileData * ControlFile
Definition: xlog.c:715
#define Assert(condition)
Definition: c.h:699

◆ GetXLogInsertRecPtr()

XLogRecPtr GetXLogInsertRecPtr ( void  )

Definition at line 11213 of file xlog.c.

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

Referenced by GetSnapshotData(), logical_begin_heap_rewrite(), pg_current_wal_insert_lsn(), and ReplicationSlotReserveWal().

11214 {
11216  uint64 current_bytepos;
11217 
11218  SpinLockAcquire(&Insert->insertpos_lck);
11219  current_bytepos = Insert->CurrBytePos;
11220  SpinLockRelease(&Insert->insertpos_lck);
11221 
11222  return XLogBytePosToRecPtr(current_bytepos);
11223 }
slock_t insertpos_lck
Definition: xlog.c:519
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:1940
XLogCtlInsert Insert
Definition: xlog.c:577
#define SpinLockAcquire(lock)
Definition: spin.h:62
uint64 CurrBytePos
Definition: xlog.c:528
static void Insert(File file)
Definition: fd.c:1062
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ GetXLogReceiptTime()

void GetXLogReceiptTime ( TimestampTz rtime,
bool fromStream 
)

Definition at line 6205 of file xlog.c.

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

Referenced by GetStandbyLimitTime().

6206 {
6207  /*
6208  * This must be executed in the startup process, since we don't export the
6209  * relevant state to shared memory.
6210  */
6211  Assert(InRecovery);
6212 
6213  *rtime = XLogReceiptTime;
6214  *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
6215 }
static XLogSource XLogReceiptSource
Definition: xlog.c:818
bool InRecovery
Definition: xlog.c:194
static TimestampTz XLogReceiptTime
Definition: xlog.c:817
#define Assert(condition)
Definition: c.h:699

◆ GetXLogReplayRecPtr()

XLogRecPtr GetXLogReplayRecPtr ( TimeLineID replayTLI)

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

11195 {
11196  XLogRecPtr recptr;
11197  TimeLineID tli;
11198 
11200  recptr = XLogCtl->lastReplayedEndRecPtr;
11201  tli = XLogCtl->lastReplayedTLI;
11203 
11204  if (replayTLI)
11205  *replayTLI = tli;
11206  return recptr;
11207 }
uint32 TimeLineID
Definition: xlogdefs.h:45
slock_t info_lck
Definition: xlog.c:704
#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:707
TimeLineID lastReplayedTLI
Definition: xlog.c:684
XLogRecPtr lastReplayedEndRecPtr
Definition: xlog.c:683

◆ GetXLogWriteRecPtr()

XLogRecPtr GetXLogWriteRecPtr ( void  )

Definition at line 11229 of file xlog.c.

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

Referenced by pg_attribute_noreturn(), and pg_current_wal_lsn().

11230 {
11234 
11235  return LogwrtResult.Write;
11236 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:751
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:601
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
XLogRecPtr Write
Definition: xlog.c:425

◆ HotStandbyActive()

bool HotStandbyActive ( void  )

Definition at line 8005 of file xlog.c.

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

Referenced by XLogWalRcvSendHSFeedback().

8006 {
8007  /*
8008  * We check shared state each time only until Hot Standby is active. We
8009  * can't de-activate Hot Standby, so there's no need to keep checking
8010  * after the shared variable has once been seen true.
8011  */
8013  return true;
8014  else
8015  {
8016  /* spinlock is essential on machines with weak memory ordering! */
8020 
8021  return LocalHotStandbyActive;
8022  }
8023 }
bool SharedHotStandbyActive
Definition: xlog.c:649
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool LocalHotStandbyActive
Definition: xlog.c:223
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ HotStandbyActiveInReplay()

bool HotStandbyActiveInReplay ( void  )

Definition at line 8030 of file xlog.c.

References AmStartupProcess, Assert, IsPostmasterEnvironment, and LocalHotStandbyActive.

Referenced by btree_xlog_vacuum().

8031 {
8033  return LocalHotStandbyActive;
8034 }
#define AmStartupProcess()
Definition: miscadmin.h:410
bool IsPostmasterEnvironment
Definition: globals.c:107
static bool LocalHotStandbyActive
Definition: xlog.c:223
#define Assert(condition)
Definition: c.h:699

◆ InitXLOGAccess()

void InitXLOGAccess ( void  )

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

8197 {
8199 
8200  /* ThisTimeLineID doesn't change so we need no lock to copy it */
8203 
8204  /* set wal_segment_size */
8206 
8207  /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
8208  (void) GetRedoRecPtr();
8209  /* Also update our copy of doPageWrites. */
8210  doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);
8211 
8212  /* Also initialize the working areas for constructing WAL records */
8213  InitXLogInsert();
8214 }
int wal_segment_size
Definition: xlog.c:113
void InitXLogInsert(void)
Definition: xloginsert.c:1028
TimeLineID ThisTimeLineID
Definition: xlog.c:630
XLogCtlInsert Insert
Definition: xlog.c:577
bool fullPageWrites
Definition: xlog.c:552
uint32 xlog_seg_size
Definition: pg_control.h:208
static bool doPageWrites
Definition: xlog.c:359
bool forcePageWrites
Definition: xlog.c:551
static void Insert(File file)
Definition: fd.c:1062
static ControlFileData * ControlFile
Definition: xlog.c:715
TimeLineID ThisTimeLineID
Definition: xlog.c:181
#define Assert(condition)
Definition: c.h:699
static XLogCtlData * XLogCtl
Definition: xlog.c:707
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:8222
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:372

◆ issue_xlog_fsync()

void issue_xlog_fsync ( int  fd,
XLogSegNo  segno 
)

Definition at line 10154 of file xlog.c.

References elog, ereport, errcode_for_file_access(), errmsg(), PANIC, pg_fdatasync(), pg_fsync_no_writethrough(), pg_fsync_writethrough(), sync_method, SYNC_METHOD_FDATASYNC, SYNC_METHOD_FSYNC, SYNC_METHOD_FSYNC_WRITETHROUGH, SYNC_METHOD_OPEN, SYNC_METHOD_OPEN_DSYNC, ThisTimeLineID, and XLogFileNameP().

Referenced by XLogWalRcvFlush(), and XLogWrite().

10155 {
10156  switch (sync_method)
10157  {
10158  case SYNC_METHOD_FSYNC:
10159  if (pg_fsync_no_writethrough(fd) != 0)
10160  ereport(PANIC,
10162  errmsg("could not fsync log file %s: %m",
10163  XLogFileNameP(ThisTimeLineID, segno))));
10164  break;
10165 #ifdef HAVE_FSYNC_WRITETHROUGH
10167  if (pg_fsync_writethrough(fd) != 0)
10168  ereport(PANIC,
10170  errmsg("could not fsync write-through log file %s: %m",
10171  XLogFileNameP(ThisTimeLineID, segno))));
10172  break;
10173 #endif
10174 #ifdef HAVE_FDATASYNC
10175  case SYNC_METHOD_FDATASYNC:
10176  if (pg_fdatasync(fd) != 0)
10177  ereport(PANIC,
10179  errmsg("could not fdatasync log file %s: %m",
10180  XLogFileNameP(ThisTimeLineID, segno))));
10181  break;
10182 #endif
10183  case SYNC_METHOD_OPEN:
10185  /* write synced it already */
10186  break;
10187  default:
10188  elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
10189  break;
10190  }
10191 }
int pg_fdatasync(int fd)
Definition: fd.c:393
#define SYNC_METHOD_FSYNC_WRITETHROUGH
Definition: xlog.h:28
int pg_fsync_writethrough(int fd)
Definition: fd.c:370
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:358
#define PANIC
Definition: elog.h:53
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define SYNC_METHOD_OPEN_DSYNC
Definition: xlog.h:29
char * XLogFileNameP(TimeLineID tli, XLogSegNo segno)
Definition: xlog.c:10197
int errcode_for_file_access(void)
Definition: elog.c:598
#define SYNC_METHOD_FSYNC
Definition: xlog.h:25
#define ereport(elevel, rest)
Definition: elog.h:122
#define SYNC_METHOD_OPEN
Definition: xlog.h:27
TimeLineID ThisTimeLineID
Definition: xlog.c:181
int sync_method
Definition: xlog.c:103
#define SYNC_METHOD_FDATASYNC
Definition: xlog.h:26
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219

◆ LocalProcessControlFile()

void LocalProcessControlFile ( bool  reset)

Definition at line 4861 of file xlog.c.

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

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

4862 {
4863  Assert(reset || ControlFile == NULL);
4864  ControlFile = palloc(sizeof(ControlFileData));
4865  ReadControlFile();
4866 }
static void ReadControlFile(void)
Definition: xlog.c:4484
static ControlFileData * ControlFile
Definition: xlog.c:715
#define Assert(condition)
Definition: c.h:699
void * palloc(Size size)
Definition: mcxt.c:924

◆ RecoveryInProgress()

bool RecoveryInProgress ( void  )

Definition at line 7949 of file xlog.c.

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

Referenced by BackgroundWriterMain(), brin_desummarize_range(), brin_summarize_range(), check_transaction_read_only(), check_XactIsoLevel(), CheckArchiveTimeout(), CheckLogicalDecodingRequirements(), CheckpointerMain(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), CreateRestartPoint(), do_pg_start_backup(), do_pg_stop_backup(), error_commit_ts_disabled(), get_relation_info(), GetNewMultiXactId(), GetNewObjectId(), GetNewTransactionId(), GetOldestActiveTransactionId(), GetOldestSafeDecodingTransactionId(), GetOldestXmin(), GetRunningTransactionData(), GetSerializableTransactionSnapshot(), GetSerializableTransactionSnapshotInt(), GetSnapshotData(), gin_clean_pending_list(), heap_page_prune_opt(), IdentifySystem(), InitPostgres(), InitTempTableNamespace(), IsCheckpointOnSchedule(), LockAcquireExtended(), MarkBufferDirtyHint(), OldSerXidSetActiveSerXmin(), 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_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(), sendDir(), ShutdownXLOG(), SnapBuildWaitSnapshot(), standard_ProcessUtility(), StartLogicalReplication(), StartTransaction(), TransactionIdIsInProgress(), TruncateMultiXact(), UpdateFullPageWrites(), WalReceiverMain(), WalSndWaitForWal(), XLogBackgroundFlush(), XLogInsertAllowed(), XLogNeedsFlush(), and XLogSendPhysical().

7950 {
7951  /*
7952  * We check shared state each time only until we leave recovery mode. We
7953  * can't re-enter recovery, so there's no need to keep checking after the
7954  * shared variable has once been seen false.
7955  */
7957  return false;
7958  else
7959  {
7960  /*
7961  * use volatile pointer to make sure we make a fresh read of the
7962  * shared variable.
7963  */
7964  volatile XLogCtlData *xlogctl = XLogCtl;
7965 
7967 
7968  /*
7969  * Initialize TimeLineID and RedoRecPtr when we discover that recovery
7970  * is finished. InitPostgres() relies upon this behaviour to ensure
7971  * that InitXLOGAccess() is called at backend startup. (If you change
7972  * this, see also LocalSetXLogInsertAllowed.)
7973  */
7975  {
7976  /*
7977  * If we just exited recovery, make sure we read TimeLineID and
7978  * RedoRecPtr after SharedRecoveryInProgress (for machines with
7979  * weak memory ordering).
7980  */
7982  InitXLOGAccess();
7983  }
7984 
7985  /*
7986  * Note: We don't need a memory barrier when we're still in recovery.
7987  * We might exit recovery immediately after return, so the caller
7988  * can't rely on 'true' meaning that we're still in recovery anyway.
7989  */
7990 
7991  return LocalRecoveryInProgress;
7992  }
7993 }
void InitXLOGAccess(void)
Definition: xlog.c:8196
bool SharedRecoveryInProgress
Definition: xlog.c:643
#define pg_memory_barrier()
Definition: atomics.h:148
static XLogCtlData * XLogCtl
Definition: xlog.c:707
static bool LocalRecoveryInProgress
Definition: xlog.c:217

◆ RecoveryIsPaused()

bool RecoveryIsPaused ( void  )

Definition at line 6028 of file xlog.c.

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

Referenced by pg_is_wal_replay_paused(), and recoveryPausesHere().

6029 {
6030  bool recoveryPause;
6031 
6033  recoveryPause = XLogCtl->recoveryPause;
6035 
6036  return recoveryPause;
6037 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:696
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ RemovePromoteSignalFiles()

void RemovePromoteSignalFiles ( void  )

Definition at line 12257 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, and PROMOTE_SIGNAL_FILE.

Referenced by PostmasterMain().

12258 {
12259  unlink(PROMOTE_SIGNAL_FILE);
12261 }
#define FALLBACK_PROMOTE_SIGNAL_FILE
Definition: xlog.c:85
#define PROMOTE_SIGNAL_FILE
Definition: xlog.c:84

◆ SetRecoveryPause()

void SetRecoveryPause ( bool  recoveryPause)

Definition at line 6040 of file xlog.c.

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

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

6041 {
6043  XLogCtl->recoveryPause = recoveryPause;
6045 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:696
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ SetWalWriterSleeping()

void SetWalWriterSleeping ( bool  sleeping)

Definition at line 12293 of file xlog.c.

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

Referenced by WalWriterMain().

12294 {
12296  XLogCtl->WalWriterSleeping = sleeping;
12298 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool WalWriterSleeping
Definition: xlog.c:656
static XLogCtlData * XLogCtl
Definition: xlog.c:707

◆ ShutdownXLOG()

void ShutdownXLOG ( int  code,
Datum  arg 
)

Definition at line 8380 of file xlog.c.

References CHECKPOINT_IMMEDIATE, CHECKPOINT_IS_SHUTDOWN, CreateCheckPoint(), CreateRestartPoint(), ereport, errmsg(), IsPostmasterEnvironment, LOG, NOTICE, RecoveryInProgress(), RequestXLogSwitch(), ShutdownCLOG(), ShutdownCommitTs(), ShutdownMultiXact(), ShutdownSUBTRANS(), WalSndInitStopping(), WalSndWaitStopping(), XLogArchiveCommandSet, and XLogArchivingActive.

Referenced by CheckpointerMain(), and InitPostgres().

8381 {
8382  /* Don't be chatty in standalone mode */
8384  (errmsg("shutting down")));
8385 
8386  /*
8387  * Signal walsenders to move to stopping state.
8388  */
8390 
8391  /*
8392  * Wait for WAL senders to be in stopping state. This prevents commands
8393  * from writing new WAL.
8394  */
8396 
8397  if (RecoveryInProgress())
8399  else
8400  {
8401  /*
8402  * If archiving is enabled, rotate the last XLOG file so that all the
8403  * remaining records are archived (postmaster wakes up the archiver
8404  * process one more time at the end of shutdown). The checkpoint
8405  * record will go to the next XLOG file and won't be archived (yet).
8406  */
8408  RequestXLogSwitch(false);
8409 
8411  }
8412  ShutdownCLOG();
8413  ShutdownCommitTs();
8414  ShutdownSUBTRANS();
8416 }
bool IsPostmasterEnvironment
Definition: globals.c:107
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9463
void ShutdownSUBTRANS(void)
Definition: subtrans.c:283
void CreateCheckPoint(int flags)
Definition: xlog.c:8587
void ShutdownCLOG(void)
Definition: clog.c:823
bool CreateRestartPoint(int flags)
Definition: xlog.c:9133
#define XLogArchiveCommandSet()
Definition: xlog.h:140
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:7949
void WalSndWaitStopping(void)
Definition: walsender.c:3075
void ShutdownMultiXact(void)
Definition: multixact.c:2105
#define ereport(elevel, rest)
Definition: elog.h:122
#define NOTICE
Definition: elog.h:37
void WalSndInitStopping(void)
Definition: walsender.c:3049
void ShutdownCommitTs(void)
Definition: commit_ts.c:745
#define XLogArchivingActive()
Definition: xlog.h:135
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:179
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:176

◆ StartupXLOG()

void StartupXLOG ( void  )

Definition at line 6287 of file xlog.c.

References AdvanceOldestClogXid(), AllowCascadeReplication, appendStringInfo(), appendStringInfoString(), archiveCleanupCommand, XLogCtlData::archiveCleanupCommand, ArchiveRecoveryRequested, ErrorContextCallback::arg, Assert, 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::ckptXid, XLogCtlData::ckptXidEpoch, close, CompleteCommitTsInitialization(), CreateCheckPoint(), CreateEndOfRecoveryRecord(), XLogCtlInsert::CurrBytePos, XLogCtlData::currentChunkStartTime, StringInfoData::data, DataDir, DB_IN_ARCHIVE_RECOVERY, DB_IN_CRASH_RECOVERY, DB_IN_PRODUCTION, DB_SHUTDOWNED, DB_SHUTDOWNED_IN_RECOVERY, DB_SHUTDOWNING, DEBUG1, DEBUG2, DEBUG3, DeleteAllExportedSnapshotFiles(), DisownLatch(), doPageWrites, doRequestWalReceiverReply, durable_rename(), elog, EnableHotStandby, EndRecPtr, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), errmsg_internal(), ERROR, error_context_stack, ExecuteRecoveryCommand(), exitArchiveRecovery(), fast_promote, FATAL, findNewestTimeLine(), XLogwrtRqst::Flush, XLogwrtResult::Flush, CheckPoint::fullPageWrites, XLogCtlInsert::fullPageWrites, 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, LocalSetXLogInsertAllowed(), LocalXLogInsertAllowed, LOG, XLogCtlData::LogwrtResult, LogwrtResult, XLogCtlData::LogwrtRqst, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), master_image_masked, 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, CheckPoint::nextXidEpoch, 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_usleep(), pgstat_reset_all(), PMSIGNAL_RECOVERY_STARTED, PreallocXlogFiles(), PrescanPreparedTransactions(), XLogCtlInsert::PrevBytePos, ErrorContextCallback::previous, CheckPoint::PrevTimeLineID, xl_end_of_recovery::PrevTimeLineID, XLogCtlData::PrevTimeLineID, proc_exit(), ProcArrayApplyRecoveryInfo(), ProcArrayInitRecovery(), psprintf(), PublishStartupProcessInformation(), reachedConsistency, read_backup_label(), read_tablespace_map(), XLogReaderState::readBuf, ReadCheckpointRecord(), readFile, readOff, XLogReaderState::readPageTLI, ReadRecord(), readRecoveryCommandFile(), ReadRecPtr, RecordKnownAssignedTransactionIds(), RecoverPreparedTransactions(), 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_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(), 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, SendPostmasterSignal(), SetCommitTsLimit(), SetForwardFsyncRequests(), SetMultiXactIdLimit(), SetRecoveryPause(), SetTransactionIdLimit(), XLogCtlData::SharedRecoveryInProgress, 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(), strlcpy(), 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, track_commit_timestamp, ControlFileData::track_commit_timestamp, TransactionIdAdvance, TransactionIdFollowsOrEquals(), TransactionIdIsNormal, TransactionIdIsValid, TransactionIdRetreat, TrimCLOG(), TrimMultiXact(), UNLOGGED_RELATION_CLEANUP, UNLOGGED_RELATION_INIT, ControlFileData::unloggedLSN, XLogCtlData::unloggedLSN, UpdateControlFile(), UpdateFullPageWrites(), ValidateXLOGDirectoryStructure(), wal_segment_size, WalRcvForceReply(), WalSndWakeup(), XLogwrtRqst::Write, XLogwrtResult::Write, writeTimeLineHistory(), RunningTransactionsData::xcnt, RunningTransactionsData::xids, XLogRecord::xl_info, XLogRecord::xl_rmid, XLogRecord::xl_xid, XLogCtlData::xlblocks, XLByteToPrevSeg, XLOG_CHECKPOINT_SHUTDOWN, XLOG_END_OF_RECOVERY, xlog_outdesc(), XLogArchiveCleanup(), XLogArchiveIsReadyOrDone(), XLogArchiveNotify(), XLogArchivingActive, XLogFileName, XLogFilePath, XLogPageRead(), XLogReaderAllocate(), XLogReaderFree(), XLogReceiptTime, XLogRecGetData, XLogRecPtrIsInvalid, XLogRecPtrToBufIdx, XLogRecPtrToBytePos(), XLogReportParameters(), XLogSegmentOffset, XLR_CHECK_CONSISTENCY, XLR_INFO_MASK, and XRecOffIsValid.

Referenced by InitPostgres(), and StartupProcessMain().

6288 {
6290  CheckPoint checkPoint;
6291  bool wasShutdown;
6292  bool reachedStopPoint = false;
6293  bool haveBackupLabel = false;
6294  bool haveTblspcMap = false;
6295  XLogRecPtr RecPtr,
6296  checkPointLoc,
6297  EndOfLog;
6298  TimeLineID EndOfLogTLI;
6299  TimeLineID PrevTimeLineID;
6300  XLogRecord *record;
6301  TransactionId oldestActiveXID;
6302  bool backupEndRequired = false;
6303  bool backupFromStandby = false;
6304  DBState dbstate_at_startup;
6305  XLogReaderState *xlogreader;
6306  XLogPageReadPrivate private;
6307  bool fast_promoted = false;
6308  struct stat st;
6309 
6310  /*
6311  * Verify XLOG status looks valid.
6312  */
6313  if (ControlFile->state < DB_SHUTDOWNED ||
6316  ereport(FATAL,
6317  (errmsg("control file contains invalid data")));
6318 
6320  {
6321  /* This is the expected case, so don't be chatty in standalone mode */
6323  (errmsg("database system was shut down at %s",
6324  str_time(ControlFile->time))));
6325  }
6327  ereport(LOG,
6328  (errmsg("database system was shut down in recovery at %s",
6329  str_time(ControlFile->time))));
6330  else if (ControlFile->state == DB_SHUTDOWNING)
6331  ereport(LOG,
6332  (errmsg("database system shutdown was interrupted; last known up at %s",
6333  str_time(ControlFile->time))));
6334  else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
6335  ereport(LOG,
6336  (errmsg("database system was interrupted while in recovery at %s",
6338  errhint("This probably means that some data is corrupted and"
6339  " you will have to use the last backup for recovery.")));
6341  ereport(LOG,
6342  (errmsg("database system was interrupted while in recovery at log time %s",
6344  errhint("If this has occurred more than once some data might be corrupted"
6345  " and you might need to choose an earlier recovery target.")));
6346  else if (ControlFile->state == DB_IN_PRODUCTION)
6347  ereport(LOG,
6348  (errmsg("database system was interrupted; last known up at %s",
6349  str_time(ControlFile->time))));
6350 
6351  /* This is just to allow attaching to startup process with a debugger */
6352 #ifdef XLOG_REPLAY_DELAY
6354  pg_usleep(60000000L);
6355 #endif
6356 
6357  /*
6358  * Verify that pg_wal and pg_wal/archive_status exist. In cases where
6359  * someone has performed a copy for PITR, these directories may have been
6360  * excluded and need to be re-created.
6361  */
6363 
6364  /*
6365  * If we previously crashed, there might be data which we had written,
6366  * intending to fsync it, but which we had not actually fsync'd yet.
6367  * Therefore, a power failure in the near future might cause earlier
6368  * unflushed writes to be lost, even though more recent data written to
6369  * disk from here on would be persisted. To avoid that, fsync the entire
6370  * data directory.
6371  */
6372  if (ControlFile->state != DB_SHUTDOWNED &&
6375 
6376  /*
6377  * Initialize on the assumption we want to recover to the latest timeline
6378  * that's active according to pg_control.
6379  */
6383  else
6385 
6386  /*
6387  * Check for recovery control file, and if so set up state for offline
6388  * recovery
6389  */
6391 
6392  /*
6393  * Save archive_cleanup_command in shared memory so that other processes
6394  * can see it.
6395  */
6398  sizeof(XLogCtl->archiveCleanupCommand));
6399 
6401  {
6403  ereport(LOG,
6404  (errmsg("entering standby mode")));
6405  else if (recoveryTarget == RECOVERY_TARGET_XID)
6406  ereport(LOG,
6407  (errmsg("starting point-in-time recovery to XID %u",
6408  recoveryTargetXid)));
6410  ereport(LOG,
6411  (errmsg("starting point-in-time recovery to %s",
6414  ereport(LOG,
6415  (errmsg("starting point-in-time recovery to \"%s\"",
6416  recoveryTargetName)));
6417  else if (recoveryTarget == RECOVERY_TARGET_LSN)
6418  ereport(LOG,
6419  (errmsg("starting point-in-time recovery to WAL location (LSN) \"%X/%X\"",
6420  (uint32) (recoveryTargetLSN >> 32),
6423  ereport(LOG,
6424  (errmsg("starting point-in-time recovery to earliest consistent point")));
6425  else
6426  ereport(LOG,
6427  (errmsg("starting archive recovery")));
6428  }
6429 
6430  /*
6431  * Take ownership of the wakeup latch if we're going to sleep during
6432  * recovery.
6433  */
6436 
6437  /* Set up XLOG reader facility */
6438  MemSet(&private, 0, sizeof(XLogPageReadPrivate));
6439  xlogreader = XLogReaderAllocate(wal_segment_size, &XLogPageRead, &private);
6440  if (!xlogreader)
6441  ereport(ERROR,
6442  (errcode(ERRCODE_OUT_OF_MEMORY),
6443  errmsg("out of memory"),
6444  errdetail("Failed while allocating a WAL reading processor.")));
6446 
6447  /*
6448  * Allocate pages dedicated to WAL consistency checks, those had better be
6449  * aligned.
6450  */
6451  replay_image_masked = (char *) palloc(BLCKSZ);
6452  master_image_masked = (char *) palloc(BLCKSZ);
6453 
6454  if (read_backup_label(&checkPointLoc, &backupEndRequired,
6455  &backupFromStandby))
6456  {
6457  List *tablespaces = NIL;
6458 
6459  /*
6460  * Archive recovery was requested, and thanks to the backup label
6461  * file, we know how far we need to replay to reach consistency. Enter
6462  * archive recovery directly.
6463  */
6464  InArchiveRecovery = true;
6466  StandbyMode = true;
6467 
6468  /*
6469  * When a backup_label file is present, we want to roll forward from
6470  * the checkpoint it identifies, rather than using pg_control.
6471  */
6472  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 0, true);
6473  if (record != NULL)
6474  {
6475  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
6476  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
6477  ereport(DEBUG1,
6478  (errmsg("checkpoint record is at %X/%X",
6479  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6480  InRecovery = true; /* force recovery even if SHUTDOWNED */
6481 
6482  /*
6483  * Make sure that REDO location exists. This may not be the case
6484  * if there was a crash during an online backup, which left a
6485  * backup_label around that references a WAL segment that's
6486  * already been archived.
6487  */
6488  if (checkPoint.redo < checkPointLoc)
6489  {
6490  if (!ReadRecord(xlogreader, checkPoint.redo, LOG, false))
6491  ereport(FATAL,
6492  (errmsg("could not find redo location referenced by checkpoint record"),
6493  errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6494  }
6495  }
6496  else
6497  {
6498  ereport(FATAL,
6499  (errmsg("could not locate required checkpoint record"),
6500  errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6501  wasShutdown = false; /* keep compiler quiet */
6502  }
6503 
6504  /* read the tablespace_map file if present and create symlinks. */
6505  if (read_tablespace_map(&tablespaces))
6506  {
6507  ListCell *lc;
6508 
6509  foreach(lc, tablespaces)
6510  {
6511  tablespaceinfo *ti = lfirst(lc);
6512  char *linkloc;
6513 
6514  linkloc = psprintf("pg_tblspc/%s", ti->oid);
6515 
6516  /*
6517  * Remove the existing symlink if any and Create the symlink
6518  * under PGDATA.
6519  */
6520  remove_tablespace_symlink(linkloc);
6521 
6522  if (symlink(ti->path, linkloc) < 0)
6523  ereport(ERROR,
6525  errmsg("could not create symbolic link \"%s\": %m",
6526  linkloc)));
6527 
6528  pfree(ti->oid);
6529  pfree(ti->path);
6530  pfree(ti);
6531  }
6532 
6533  /* set flag to delete it later */
6534  haveTblspcMap = true;
6535  }
6536 
6537  /* set flag to delete it later */
6538  haveBackupLabel = true;
6539  }
6540  else
6541  {
6542  /*
6543  * If tablespace_map file is present without backup_label file, there
6544  * is no use of such file. There is no harm in retaining it, but it
6545  * is better to get rid of the map file so that we don't have any
6546  * redundant file in data directory and it will avoid any sort of
6547  * confusion. It seems prudent though to just rename the file out of
6548  * the way rather than delete it completely, also we ignore any error
6549  * that occurs in rename operation as even if map file is present
6550  * without backup_label file, it is harmless.
6551  */
6552  if (stat(TABLESPACE_MAP, &st) == 0)
6553  {
6554  unlink(TABLESPACE_MAP_OLD);
6556  ereport(LOG,
6557  (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
6559  errdetail("File \"%s\" was renamed to \"%s\".",
6561  else
6562  ereport(LOG,
6563  (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
6565  errdetail("Could not rename file \"%s\" to \"%s\": %m.",
6567  }
6568 
6569  /*
6570  * It's possible that archive recovery was requested, but we don't
6571  * know how far we need to replay the WAL before we reach consistency.
6572  * This can happen for example if a base backup is taken from a
6573  * running server using an atomic filesystem snapshot, without calling
6574  * pg_start/stop_backup. Or if you just kill a running master server
6575  * and put it into archive recovery by creating a recovery.conf file.
6576  *
6577  * Our strategy in that case is to perform crash recovery first,
6578  * replaying all the WAL present in pg_wal, and only enter archive
6579  * recovery after that.
6580  *
6581  * But usually we already know how far we need to replay the WAL (up
6582  * to minRecoveryPoint, up to backupEndPoint, or until we see an
6583  * end-of-backup record), and we can enter archive recovery directly.
6584  */
6590  {
6591  InArchiveRecovery = true;
6593  StandbyMode = true;
6594  }
6595 
6596  /* Get the last valid checkpoint record. */
6597  checkPointLoc = ControlFile->checkPoint;
6599  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 1, true);
6600  if (record != NULL)
6601  {
6602  ereport(DEBUG1,
6603  (errmsg("checkpoint record is at %X/%X",
6604  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6605  }
6606  else
6607  {
6608  /*
6609  * We used to attempt to go back to a secondary checkpoint record
6610  * here, but only when not in standby_mode. We now just fail if we
6611  * can't read the last checkpoint because this allows us to
6612  * simplify processing around checkpoints.
6613  */
6614  ereport(PANIC,
6615  (errmsg("could not locate a valid checkpoint record")));
6616  }
6617  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
6618  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
6619  }
6620 
6621  /*
6622  * Clear out any old relcache cache files. This is *necessary* if we do
6623  * any WAL replay, since that would probably result in the cache files
6624  * being out of sync with database reality. In theory we could leave them
6625  * in place if the database had been cleanly shut down, but it seems
6626  * safest to just remove them always and let them be rebuilt during the
6627  * first backend startup. These files needs to be removed from all
6628  * directories including pg_tblspc, however the symlinks are created only
6629  * after reading tablespace_map file in case of archive recovery from
6630  * backup, so needs to clear old relcache files here after creating
6631  * symlinks.
6632  */
6634 
6635  /*
6636  * If the location of the checkpoint record is not on the expected
6637  * timeline in the history of the requested timeline, we cannot proceed:
6638  * the backup is not part of the history of the requested timeline.
6639  */
6640  Assert(expectedTLEs); /* was initialized by reading checkpoint
6641  * record */
6642  if (tliOfPointInHistory(checkPointLoc, expectedTLEs) !=
6643  checkPoint.ThisTimeLineID)
6644  {
6645  XLogRecPtr switchpoint;
6646 
6647  /*
6648  * tliSwitchPoint will throw an error if the checkpoint's timeline is
6649  * not in expectedTLEs at all.
6650  */
6652  ereport(FATAL,
6653  (errmsg("requested timeline %u is not a child of this server's history",
6655  errdetail("Latest checkpoint is at %X/%X on timeline %u, but in the history of the requested timeline, the server forked off from that timeline at %X/%X.",
6656  (uint32) (ControlFile->checkPoint >> 32),
6659  (uint32) (switchpoint >> 32),
6660  (uint32) switchpoint)));
6661  }
6662 
6663  /*
6664  * The min recovery point should be part of the requested timeline's
6665  * history, too.
6666  */
6670  ereport(FATAL,
6671  (errmsg("requested timeline %u does not contain minimum recovery point %X/%X on timeline %u",
6673  (uint32) (ControlFile->minRecoveryPoint >> 32),
6676 
6677  LastRec = RecPtr = checkPointLoc;
6678 
6679  ereport(DEBUG1,
6680  (errmsg_internal("redo record is at %X/%X; shutdown %s",
6681  (uint32) (checkPoint.redo >> 32), (uint32) checkPoint.redo,
6682  wasShutdown ? "true" : "false")));
6683  ereport(DEBUG1,
6684  (errmsg_internal("next transaction ID: %u:%u; next OID: %u",
6685  checkPoint.nextXidEpoch, checkPoint.nextXid,
6686  checkPoint.nextOid)));
6687  ereport(DEBUG1,
6688  (errmsg_internal("next MultiXactId: %u; next MultiXactOffset: %u",
6689  checkPoint.nextMulti, checkPoint.nextMultiOffset)));
6690  ereport(DEBUG1,
6691  (errmsg_internal("oldest unfrozen transaction ID: %u, in database %u",
6692  checkPoint.oldestXid, checkPoint.oldestXidDB)));
6693  ereport(DEBUG1,
6694  (errmsg_internal("oldest MultiXactId: %u, in database %u",
6695  checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
6696  ereport(DEBUG1,
6697  (errmsg_internal("commit timestamp Xid oldest/newest: %u/%u",
6698  checkPoint.oldestCommitTsXid,
6699  checkPoint.newestCommitTsXid)));
6700  if (!TransactionIdIsNormal(checkPoint.nextXid))
6701  ereport(PANIC,
6702  (errmsg("invalid next transaction ID")));
6703 
6704  /* initialize shared memory variables from the checkpoint record */
6705  ShmemVariableCache->nextXid = checkPoint.nextXid;
6706  ShmemVariableCache->nextOid = checkPoint.nextOid;
6708  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
6709  AdvanceOldestClogXid(checkPoint.oldestXid);
6710  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
6711  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
6713  checkPoint.newestCommitTsXid);
6714  XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
6715  XLogCtl->ckptXid = checkPoint.nextXid;
6716 
6717  /*
6718  * Initialize replication slots, before there's a chance to remove
6719  * required resources.
6720  */
6722 
6723  /*
6724  * Startup logical state, needs to be setup now so we have proper data
6725  * during crash recovery.
6726  */
6728 
6729  /*
6730  * Startup MultiXact. We need to do this early to be able to replay
6731  * truncations.
6732  */
6733  StartupMultiXact();
6734 
6735  /*
6736  * Ditto commit timestamps. In a standby, we do it if setting is enabled
6737  * in ControlFile; in a master we base the decision on the GUC itself.
6738  */
6741  StartupCommitTs();
6742 
6743  /*
6744  * Recover knowledge about replay progress of known replication partners.
6745  */
6747 
6748  /*
6749  * Initialize unlogged LSN. On a clean shutdown, it's restored from the
6750  * control file. On recovery, all unlogged relations are blown away, so
6751  * the unlogged LSN counter can be reset too.
6752  */
6755  else
6756  XLogCtl->unloggedLSN = 1;
6757 
6758  /*
6759  * We must replay WAL entries using the same TimeLineID they were created
6760  * under, so temporarily adopt the TLI indicated by the checkpoint (see
6761  * also xlog_redo()).
6762  */
6763  ThisTimeLineID = checkPoint.ThisTimeLineID;
6764 
6765  /*
6766  * Copy any missing timeline history files between 'now' and the recovery
6767  * target timeline from archive to pg_wal. While we don't need those files
6768  * ourselves - the history file of the recovery target timeline covers all
6769  * the previous timelines in the history too - a cascading standby server
6770  * might be interested in them. Or, if you archive the WAL from this
6771  * server to a different archive than the master, it'd be good for all the
6772  * history files to get archived there after failover, so that you can use
6773  * one of the old timelines as a PITR target. Timeline history files are
6774  * small, so it's better to copy them unnecessarily than not copy them and
6775  * regret later.
6776  */
6778 
6779  /*
6780  * Before running in recovery, scan pg_twophase and fill in its status to
6781  * be able to work on entries generated by redo. Doing a scan before
6782  * taking any recovery action has the merit to discard any 2PC files that
6783  * are newer than the first record to replay, saving from any conflicts at
6784  * replay. This avoids as well any subsequent scans when doing recovery
6785  * of the on-disk two-phase data.
6786  */
6788 
6789  lastFullPageWrites = checkPoint.fullPageWrites;
6790 
6793 
6794  if (RecPtr < checkPoint.