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

#define BACKUP_LABEL_FILE   "backup_label"
#define BACKUP_LABEL_OLD   "backup_label.old"

Definition at line 321 of file xlog.h.

Referenced by CancelBackup(), and StartupXLOG().

#define CHECKPOINT_CAUSE_TIME   0x0080 /* Elapsed time */

Definition at line 186 of file xlog.h.

Referenced by CheckpointerMain(), and LogCheckpointStart().

#define CHECKPOINT_CAUSE_XLOG   0x0040 /* XLOG consumption */

Definition at line 185 of file xlog.h.

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

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

Definition at line 176 of file xlog.h.

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

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

Definition at line 180 of file xlog.h.

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

#define CHECKPOINT_FORCE   0x0008 /* Force even if no activity */
#define CHECKPOINT_IS_SHUTDOWN   0x0001 /* Checkpoint is for shutdown */
#define CHECKPOINT_WAIT   0x0020 /* Wait for completion */
#define SYNC_METHOD_FDATASYNC   1

Definition at line 26 of file xlog.h.

Referenced by get_sync_bit(), and issue_xlog_fsync().

#define SYNC_METHOD_FSYNC   0

Definition at line 25 of file xlog.h.

Referenced by get_sync_bit(), and issue_xlog_fsync().

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

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

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

#define TABLESPACE_MAP   "tablespace_map"
#define TABLESPACE_MAP_OLD   "tablespace_map.old"

Definition at line 324 of file xlog.h.

Referenced by CancelBackup(), and StartupXLOG().

#define XLOG_INCLUDE_ORIGIN   0x01 /* include the replication origin */
#define XLOG_MARK_UNIMPORTANT   0x02 /* record not important for durability */
#define XLogArchiveCommandSet ( )    (XLogArchiveCommand[0] != '\0')

Definition at line 139 of file xlog.h.

Referenced by pgarch_ArchiverCopyLoop(), and ShutdownXLOG().

Definition at line 137 of file xlog.h.

Referenced by do_pg_stop_backup(), and sigusr1_handler().

#define XLogLogicalInfoActive ( )    (wal_level >= WAL_LEVEL_LOGICAL)

Definition at line 162 of file xlog.h.

Referenced by AssignTransactionId(), and XactLogCommitRecord().

Typedef Documentation

Enumeration Type Documentation

Enumerator
ARCHIVE_MODE_OFF 
ARCHIVE_MODE_ON 
ARCHIVE_MODE_ALWAYS 

Definition at line 115 of file xlog.h.

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

Definition at line 64 of file xlog.h.

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.

Enumerator
SESSION_BACKUP_NONE 
SESSION_BACKUP_EXCLUSIVE 
SESSION_BACKUP_NON_EXCLUSIVE 

Definition at line 303 of file xlog.h.

enum WalLevel
Enumerator
WAL_LEVEL_MINIMAL 
WAL_LEVEL_REPLICA 
WAL_LEVEL_LOGICAL 

Definition at line 124 of file xlog.h.

Function Documentation

void assign_checkpoint_completion_target ( double  newval,
void *  extra 
)

Definition at line 2240 of file xlog.c.

References CalculateCheckpointSegments(), CheckPointCompletionTarget, and newval.

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

Definition at line 2233 of file xlog.c.

References CalculateCheckpointSegments(), max_wal_size_mb, and newval.

2234 {
2237 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2210
int max_wal_size_mb
Definition: xlog.c:89
#define newval
void BootStrapXLOG ( void  )

Definition at line 4951 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, NULL, 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, CheckPoint::redo, SetCommitTsLimit(), SetMultiXactIdLimit(), SetTransactionIdLimit(), ShmemVariableCache, SizeOfXLogLongPHD, SizeOfXLogRecord, SizeOfXLogRecordDataHeaderShort, ControlFileData::state, ControlFileData::system_identifier, TemplateDbOid, CheckPoint::ThisTimeLineID, ThisTimeLineID, CheckPoint::time, ControlFileData::time, track_commit_timestamp, ControlFileData::track_commit_timestamp, TYPEALIGN, ControlFileData::unloggedLSN, WAIT_EVENT_WAL_BOOTSTRAP_SYNC, WAIT_EVENT_WAL_BOOTSTRAP_WRITE, wal_level, ControlFileData::wal_level, wal_log_hints, ControlFileData::wal_log_hints, write, WriteControlFile(), XLogRecord::xl_crc, XLogRecord::xl_info, XLogRecord::xl_prev, XLogRecord::xl_rmid, XLogRecord::xl_tot_len, XLogRecord::xl_xid, XLOG_CHECKPOINT_SHUTDOWN, XLOG_PAGE_MAGIC, XLogFileInit(), XLogSegSize, 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().

4952 {
4953  CheckPoint checkPoint;
4954  char *buffer;
4955  XLogPageHeader page;
4956  XLogLongPageHeader longpage;
4957  XLogRecord *record;
4958  char *recptr;
4959  bool use_existent;
4960  uint64 sysidentifier;
4961  char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
4962  struct timeval tv;
4963  pg_crc32c crc;
4964 
4965  /*
4966  * Select a hopefully-unique system identifier code for this installation.
4967  * We use the result of gettimeofday(), including the fractional seconds
4968  * field, as being about as unique as we can easily get. (Think not to
4969  * use random(), since it hasn't been seeded and there's no portable way
4970  * to seed it other than the system clock value...) The upper half of the
4971  * uint64 value is just the tv_sec part, while the lower half contains the
4972  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
4973  * PID for a little extra uniqueness. A person knowing this encoding can
4974  * determine the initialization time of the installation, which could
4975  * perhaps be useful sometimes.
4976  */
4977  gettimeofday(&tv, NULL);
4978  sysidentifier = ((uint64) tv.tv_sec) << 32;
4979  sysidentifier |= ((uint64) tv.tv_usec) << 12;
4980  sysidentifier |= getpid() & 0xFFF;
4981 
4982  /*
4983  * Generate a random nonce. This is used for authentication requests that
4984  * will fail because the user does not exist. The nonce is used to create
4985  * a genuine-looking password challenge for the non-existent user, in lieu
4986  * of an actual stored password.
4987  */
4988  if (!pg_backend_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
4989  ereport(PANIC,
4990  (errcode(ERRCODE_INTERNAL_ERROR),
4991  errmsg("could not generate secret authorization token")));
4992 
4993  /* First timeline ID is always 1 */
4994  ThisTimeLineID = 1;
4995 
4996  /* page buffer must be aligned suitably for O_DIRECT */
4997  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
4998  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
4999  memset(page, 0, XLOG_BLCKSZ);
5000 
5001  /*
5002  * Set up information for the initial checkpoint record
5003  *
5004  * The initial checkpoint record is written to the beginning of the WAL
5005  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5006  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5007  */
5008  checkPoint.redo = XLogSegSize + SizeOfXLogLongPHD;
5009  checkPoint.ThisTimeLineID = ThisTimeLineID;
5010  checkPoint.PrevTimeLineID = ThisTimeLineID;
5011  checkPoint.fullPageWrites = fullPageWrites;
5012  checkPoint.nextXidEpoch = 0;
5013  checkPoint.nextXid = FirstNormalTransactionId;
5014  checkPoint.nextOid = FirstBootstrapObjectId;
5015  checkPoint.nextMulti = FirstMultiXactId;
5016  checkPoint.nextMultiOffset = 0;
5017  checkPoint.oldestXid = FirstNormalTransactionId;
5018  checkPoint.oldestXidDB = TemplateDbOid;
5019  checkPoint.oldestMulti = FirstMultiXactId;
5020  checkPoint.oldestMultiDB = TemplateDbOid;
5023  checkPoint.time = (pg_time_t) time(NULL);
5025 
5026  ShmemVariableCache->nextXid = checkPoint.nextXid;
5027  ShmemVariableCache->nextOid = checkPoint.nextOid;
5029  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5030  AdvanceOldestClogXid(checkPoint.oldestXid);
5031  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5032  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5034 
5035  /* Set up the XLOG page header */
5036  page->xlp_magic = XLOG_PAGE_MAGIC;
5037  page->xlp_info = XLP_LONG_HEADER;
5038  page->xlp_tli = ThisTimeLineID;
5039  page->xlp_pageaddr = XLogSegSize;
5040  longpage = (XLogLongPageHeader) page;
5041  longpage->xlp_sysid = sysidentifier;
5042  longpage->xlp_seg_size = XLogSegSize;
5043  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5044 
5045  /* Insert the initial checkpoint record */
5046  recptr = ((char *) page + SizeOfXLogLongPHD);
5047  record = (XLogRecord *) recptr;
5048  record->xl_prev = 0;
5049  record->xl_xid = InvalidTransactionId;
5050  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5052  record->xl_rmid = RM_XLOG_ID;
5053  recptr += SizeOfXLogRecord;
5054  /* fill the XLogRecordDataHeaderShort struct */
5055  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5056  *(recptr++) = sizeof(checkPoint);
5057  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5058  recptr += sizeof(checkPoint);
5059  Assert(recptr - (char *) record == record->xl_tot_len);
5060 
5061  INIT_CRC32C(crc);
5062  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5063  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5064  FIN_CRC32C(crc);
5065  record->xl_crc = crc;
5066 
5067  /* Create first XLOG segment file */
5068  use_existent = false;
5069  openLogFile = XLogFileInit(1, &use_existent, false);
5070 
5071  /* Write the first page with the initial record */
5072  errno = 0;
5074  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5075  {
5076  /* if write didn't set errno, assume problem is no disk space */
5077  if (errno == 0)
5078  errno = ENOSPC;
5079  ereport(PANIC,
5081  errmsg("could not write bootstrap write-ahead log file: %m")));
5082  }
5084 
5086  if (pg_fsync(openLogFile) != 0)
5087  ereport(PANIC,
5089  errmsg("could not fsync bootstrap write-ahead log file: %m")));
5091 
5092  if (close(openLogFile))
5093  ereport(PANIC,
5095  errmsg("could not close bootstrap write-ahead log file: %m")));
5096 
5097  openLogFile = -1;
5098 
5099  /* Now create pg_control */
5100 
5101  memset(ControlFile, 0, sizeof(ControlFileData));
5102  /* Initialize pg_control status fields */
5103  ControlFile->system_identifier = sysidentifier;
5104  memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
5106  ControlFile->time = checkPoint.time;
5107  ControlFile->checkPoint = checkPoint.redo;
5108  ControlFile->checkPointCopy = checkPoint;
5109  ControlFile->unloggedLSN = 1;
5110 
5111  /* Set important parameter values for use when replaying WAL */
5120 
5121  /* some additional ControlFile fields are set in WriteControlFile() */
5122 
5123  WriteControlFile();
5124 
5125  /* Bootstrap the commit log, too */
5126  BootStrapCLOG();
5130 
5131  pfree(buffer);
5132 }
static void WriteControlFile(void)
Definition: xlog.c:4376
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define XLogSegSize
Definition: xlog_internal.h:92
XLogRecPtr xl_prev
Definition: xlogrecord.h:45
int max_locks_per_xact
Definition: pg_control.h:182
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
int max_prepared_xacts
Definition: pg_control.h:181
int64 pg_time_t
Definition: pgtime.h:23
pg_time_t time
Definition: pg_control.h:128
void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact)
Definition: commit_ts.c:849
uint32 oidCount
Definition: transam.h:112
#define write(a, b, c)
Definition: win32.h:14
#define SizeOfXLogRecordDataHeaderShort
Definition: xlogrecord.h:201
int max_worker_processes
Definition: pg_control.h:180
uint32 pg_crc32c
Definition: pg_crc32c.h:38
TransactionId oldestActiveXid
Definition: pg_control.h:63
int wal_level
Definition: xlog.c:104
int XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
Definition: xlog.c:3153
void BootStrapMultiXact(void)
Definition: multixact.c:1866
MultiXactId oldestMulti
Definition: pg_control.h:49
TimeLineID PrevTimeLineID
Definition: pg_control.h:39
int errcode(int sqlerrcode)
Definition: elog.c:575
RmgrId xl_rmid
Definition: xlogrecord.h:47
XLogPageHeaderData * XLogPageHeader
Definition: xlog_internal.h:57
CheckPoint checkPointCopy
Definition: pg_control.h:132
TransactionId oldestXid
Definition: pg_control.h:47
TransactionId nextXid
Definition: pg_control.h:43
pg_time_t time
Definition: pg_control.h:51
#define PANIC
Definition: elog.h:53
uint32 bootstrap_data_checksum_version
Definition: bootstrap.c:49
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:950
#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
uint32 nextXidEpoch
Definition: pg_control.h:42
bool track_commit_timestamp
Definition: commit_ts.c:103
#define TemplateDbOid
Definition: pg_database.h:80
uint32 data_checksum_version
Definition: pg_control.h:222
bool pg_backend_random(char *dst, int len)
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
XLogRecPtr unloggedLSN
Definition: pg_control.h:134
int errcode_for_file_access(void)
Definition: elog.c:598
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
#define FirstBootstrapObjectId
Definition: transam.h:93
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1235
#define FirstMultiXactId
Definition: multixact.h:24
#define ereport(elevel, rest)
Definition: elog.h:122
int max_locks_per_xact
Definition: lock.c:54
TimeLineID xlp_tli
Definition: xlog_internal.h:40
XLogRecPtr xlp_pageaddr
Definition: xlog_internal.h:41
#define SizeOfXLogRecord
Definition: xlogrecord.h:55
TransactionId newestCommitTsXid
Definition: pg_control.h:54
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:229
int MaxConnections
Definition: globals.c:124
Oid oldestMultiDB
Definition: pg_control.h:50
static int openLogFile
Definition: xlog.c:770
static ControlFileData * ControlFile
Definition: xlog.c:713
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2194
TimeLineID ThisTimeLineID
Definition: xlog.c:179
Oid nextOid
Definition: pg_control.h:44
#define TYPEALIGN(ALIGNVAL, LEN)
Definition: c.h:581
bool fullPageWrites
Definition: pg_control.h:41
bool wal_log_hints
Definition: xlog.c:98
void BootStrapCLOG(void)
Definition: clog.c:464
#define NULL
Definition: c.h:229
bool track_commit_timestamp
Definition: pg_control.h:183
#define Assert(condition)
Definition: c.h:676
#define XLP_LONG_HEADER
Definition: xlog_internal.h:79
Oid oldestXidDB
Definition: pg_control.h:48
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1211
void SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
Definition: varsup.c:288
uint8 xl_info
Definition: xlogrecord.h:46
MultiXactId nextMulti
Definition: pg_control.h:45
pg_crc32c xl_crc
Definition: xlogrecord.h:49
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:224
TransactionId xl_xid
Definition: xlogrecord.h:44
TimeLineID ThisTimeLineID
Definition: pg_control.h:38
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int max_worker_processes
Definition: globals.c:125
int pg_fsync(int fd)
Definition: fd.c:333
#define close(a)
Definition: win32.h:12
void BootStrapCommitTs(void)
Definition: commit_ts.c:523
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:73
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:78
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:36
#define offsetof(type, field)
Definition: c.h:555
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:72
void MultiXactSetNextMXact(MultiXactId nextMulti, MultiXactOffset nextMultiOffset)
Definition: multixact.c:2160
bool CheckPromoteSignal ( void  )

Definition at line 12090 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, and PROMOTE_SIGNAL_FILE.

Referenced by sigusr1_handler().

12091 {
12092  struct stat stat_buf;
12093 
12094  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0 ||
12096  return true;
12097 
12098  return false;
12099 }
#define FALLBACK_PROMOTE_SIGNAL_FILE
Definition: xlog.c:85
struct stat stat_buf
Definition: pg_standby.c:101
#define PROMOTE_SIGNAL_FILE
Definition: xlog.c:84
void CheckXLogRemoved ( XLogSegNo  segno,
TimeLineID  tli 
)

Definition at line 3765 of file xlog.c.

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

Referenced by perform_base_backup(), and XLogRead().

3766 {
3767  XLogSegNo lastRemovedSegNo;
3768 
3770  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3772 
3773  if (segno <= lastRemovedSegNo)
3774  {
3775  char filename[MAXFNAMELEN];
3776 
3777  XLogFileName(filename, tli, segno);
3778  ereport(ERROR,
3780  errmsg("requested WAL segment %s has already been removed",
3781  filename)));
3782  }
3783 }
slock_t info_lck
Definition: xlog.c:702
#define XLogFileName(fname, tli, logSegNo)
XLogSegNo lastRemovedSegNo
Definition: xlog.c:585
#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
static XLogCtlData * XLogCtl
Definition: xlog.c:705
static char * filename
Definition: pg_dumpall.c:90
int errmsg(const char *fmt,...)
Definition: elog.c:797
void CreateCheckPoint ( int  flags)

Definition at line 8533 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, NULL, VariableCacheData::oidCount, CheckPoint::oldestActiveXid, CheckPoint::oldestCommitTsXid, VariableCacheData::oldestCommitTsXid, CheckPoint::oldestMulti, CheckPoint::oldestMultiDB, CheckPoint::oldestXid, VariableCacheData::oldestXid, CheckPoint::oldestXidDB, VariableCacheData::oldestXidDB, PANIC, pfree(), pg_usleep(), PreallocXlogFiles(), ControlFileData::prevCheckPoint, CheckPoint::PrevTimeLineID, XLogCtlData::PrevTimeLineID, PROCARRAY_FLAGS_DEFAULT, ProcLastRecPtr, RecoveryInProgress(), CheckPoint::redo, RedoRecPtr, XLogCtlInsert::RedoRecPtr, XLogCtlData::RedoRecPtr, RemoveOldXlogFiles(), ShmemVariableCache, SizeOfXLogLongPHD, SizeOfXLogShortPHD, smgrpostckpt(), smgrpreckpt(), SpinLockAcquire, SpinLockRelease, START_CRIT_SECTION, ControlFileData::state, CheckPoint::ThisTimeLineID, ThisTimeLineID, CheckPoint::time, ControlFileData::time, TruncateSUBTRANS(), XLogCtlData::ulsn_lck, ControlFileData::unloggedLSN, XLogCtlData::unloggedLSN, UpdateCheckPointDistanceEstimate(), UpdateControlFile(), WALInsertLockAcquireExclusive(), WALInsertLockRelease(), XLByteToSeg, XLOG_CHECKPOINT_ONLINE, XLOG_CHECKPOINT_SHUTDOWN, XLogBeginInsert(), XLogBytePosToRecPtr(), XLogFlush(), XLogInsert(), XLogRegisterData(), XLogSegSize, and XLogStandbyInfoActive.

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

8534 {
8535  bool shutdown;
8536  CheckPoint checkPoint;
8537  XLogRecPtr recptr;
8539  uint32 freespace;
8540  XLogRecPtr PriorRedoPtr;
8541  XLogRecPtr curInsert;
8542  XLogRecPtr last_important_lsn;
8543  VirtualTransactionId *vxids;
8544  int nvxids;
8545 
8546  /*
8547  * An end-of-recovery checkpoint is really a shutdown checkpoint, just
8548  * issued at a different time.
8549  */
8551  shutdown = true;
8552  else
8553  shutdown = false;
8554 
8555  /* sanity check */
8556  if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
8557  elog(ERROR, "can't create a checkpoint during recovery");
8558 
8559  /*
8560  * Initialize InitXLogInsert working areas before entering the critical
8561  * section. Normally, this is done by the first call to
8562  * RecoveryInProgress() or LocalSetXLogInsertAllowed(), but when creating
8563  * an end-of-recovery checkpoint, the LocalSetXLogInsertAllowed call is
8564  * done below in a critical section, and InitXLogInsert cannot be called
8565  * in a critical section.
8566  */
8567  InitXLogInsert();
8568 
8569  /*
8570  * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
8571  * (This is just pro forma, since in the present system structure there is
8572  * only one process that is allowed to issue checkpoints at any given
8573  * time.)
8574  */
8575  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
8576 
8577  /*
8578  * Prepare to accumulate statistics.
8579  *
8580  * Note: because it is possible for log_checkpoints to change while a
8581  * checkpoint proceeds, we always accumulate stats, even if
8582  * log_checkpoints is currently off.
8583  */
8584  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
8586 
8587  /*
8588  * Use a critical section to force system panic if we have trouble.
8589  */
8591 
8592  if (shutdown)
8593  {
8594  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8596  ControlFile->time = (pg_time_t) time(NULL);
8598  LWLockRelease(ControlFileLock);
8599  }
8600 
8601  /*
8602  * Let smgr prepare for checkpoint; this has to happen before we determine
8603  * the REDO pointer. Note that smgr must not do anything that'd have to
8604  * be undone if we decide no checkpoint is needed.
8605  */
8606  smgrpreckpt();
8607 
8608  /* Begin filling in the checkpoint WAL record */
8609  MemSet(&checkPoint, 0, sizeof(checkPoint));
8610  checkPoint.time = (pg_time_t) time(NULL);
8611 
8612  /*
8613  * For Hot Standby, derive the oldestActiveXid before we fix the redo
8614  * pointer. This allows us to begin accumulating changes to assemble our
8615  * starting snapshot of locks and transactions.
8616  */
8617  if (!shutdown && XLogStandbyInfoActive())
8619  else
8621 
8622  /*
8623  * Get location of last important record before acquiring insert locks (as
8624  * GetLastImportantRecPtr() also locks WAL locks).
8625  */
8626  last_important_lsn = GetLastImportantRecPtr();
8627 
8628  /*
8629  * We must block concurrent insertions while examining insert state to
8630  * determine the checkpoint REDO pointer.
8631  */
8633  curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
8634 
8635  /*
8636  * If this isn't a shutdown or forced checkpoint, and if there has been no
8637  * WAL activity requiring a checkpoint, skip it. The idea here is to
8638  * avoid inserting duplicate checkpoints when the system is idle.
8639  */
8640  if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
8641  CHECKPOINT_FORCE)) == 0)
8642  {
8643  if (last_important_lsn == ControlFile->checkPoint)
8644  {
8646  LWLockRelease(CheckpointLock);
8647  END_CRIT_SECTION();
8648  ereport(DEBUG1,
8649  (errmsg("checkpoint skipped due to an idle system")));
8650  return;
8651  }
8652  }
8653 
8654  /*
8655  * An end-of-recovery checkpoint is created before anyone is allowed to
8656  * write WAL. To allow us to write the checkpoint record, temporarily
8657  * enable XLogInsertAllowed. (This also ensures ThisTimeLineID is
8658  * initialized, which we need here and in AdvanceXLInsertBuffer.)
8659  */
8660  if (flags & CHECKPOINT_END_OF_RECOVERY)
8662 
8663  checkPoint.ThisTimeLineID = ThisTimeLineID;
8664  if (flags & CHECKPOINT_END_OF_RECOVERY)
8665  checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8666  else
8667  checkPoint.PrevTimeLineID = ThisTimeLineID;
8668 
8669  checkPoint.fullPageWrites = Insert->fullPageWrites;
8670 
8671  /*
8672  * Compute new REDO record ptr = location of next XLOG record.
8673  *
8674  * NB: this is NOT necessarily where the checkpoint record itself will be,
8675  * since other backends may insert more XLOG records while we're off doing
8676  * the buffer flush work. Those XLOG records are logically after the
8677  * checkpoint, even though physically before it. Got that?
8678  */
8679  freespace = INSERT_FREESPACE(curInsert);
8680  if (freespace == 0)
8681  {
8682  if (curInsert % XLogSegSize == 0)
8683  curInsert += SizeOfXLogLongPHD;
8684  else
8685  curInsert += SizeOfXLogShortPHD;
8686  }
8687  checkPoint.redo = curInsert;
8688 
8689  /*
8690  * Here we update the shared RedoRecPtr for future XLogInsert calls; this
8691  * must be done while holding all the insertion locks.
8692  *
8693  * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
8694  * pointing past where it really needs to point. This is okay; the only
8695  * consequence is that XLogInsert might back up whole buffers that it
8696  * didn't really need to. We can't postpone advancing RedoRecPtr because
8697  * XLogInserts that happen while we are dumping buffers must assume that
8698  * their buffer changes are not included in the checkpoint.
8699  */
8700  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
8701 
8702  /*
8703  * Now we can release the WAL insertion locks, allowing other xacts to
8704  * proceed while we are flushing disk buffers.
8705  */
8707 
8708  /* Update the info_lck-protected copy of RedoRecPtr as well */
8710  XLogCtl->RedoRecPtr = checkPoint.redo;
8712 
8713  /*
8714  * If enabled, log checkpoint start. We postpone this until now so as not
8715  * to log anything if we decided to skip the checkpoint.
8716  */
8717  if (log_checkpoints)
8718  LogCheckpointStart(flags, false);
8719 
8720  TRACE_POSTGRESQL_CHECKPOINT_START(flags);
8721 
8722  /*
8723  * Get the other info we need for the checkpoint record.
8724  *
8725  * We don't need to save oldestClogXid in the checkpoint, it only matters
8726  * for the short period in which clog is being truncated, and if we crash
8727  * during that we'll redo the clog truncation and fix up oldestClogXid
8728  * there.
8729  */
8730  LWLockAcquire(XidGenLock, LW_SHARED);
8731  checkPoint.nextXid = ShmemVariableCache->nextXid;
8732  checkPoint.oldestXid = ShmemVariableCache->oldestXid;
8734  LWLockRelease(XidGenLock);
8735 
8736  LWLockAcquire(CommitTsLock, LW_SHARED);
8739  LWLockRelease(CommitTsLock);
8740 
8741  /* Increase XID epoch if we've wrapped around since last checkpoint */
8743  if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
8744  checkPoint.nextXidEpoch++;
8745 
8746  LWLockAcquire(OidGenLock, LW_SHARED);
8747  checkPoint.nextOid = ShmemVariableCache->nextOid;
8748  if (!shutdown)
8749  checkPoint.nextOid += ShmemVariableCache->oidCount;
8750  LWLockRelease(OidGenLock);
8751 
8752  MultiXactGetCheckptMulti(shutdown,
8753  &checkPoint.nextMulti,
8754  &checkPoint.nextMultiOffset,
8755  &checkPoint.oldestMulti,
8756  &checkPoint.oldestMultiDB);
8757 
8758  /*
8759  * Having constructed the checkpoint record, ensure all shmem disk buffers
8760  * and commit-log buffers are flushed to disk.
8761  *
8762  * This I/O could fail for various reasons. If so, we will fail to
8763  * complete the checkpoint, but there is no reason to force a system
8764  * panic. Accordingly, exit critical section while doing it.
8765  */
8766  END_CRIT_SECTION();
8767 
8768  /*
8769  * In some cases there are groups of actions that must all occur on one
8770  * side or the other of a checkpoint record. Before flushing the
8771  * checkpoint record we must explicitly wait for any backend currently
8772  * performing those groups of actions.
8773  *
8774  * One example is end of transaction, so we must wait for any transactions
8775  * that are currently in commit critical sections. If an xact inserted
8776  * its commit record into XLOG just before the REDO point, then a crash
8777  * restart from the REDO point would not replay that record, which means
8778  * that our flushing had better include the xact's update of pg_xact. So
8779  * we wait till he's out of his commit critical section before proceeding.
8780  * See notes in RecordTransactionCommit().
8781  *
8782  * Because we've already released the insertion locks, this test is a bit
8783  * fuzzy: it is possible that we will wait for xacts we didn't really need
8784  * to wait for. But the delay should be short and it seems better to make
8785  * checkpoint take a bit longer than to hold off insertions longer than
8786  * necessary. (In fact, the whole reason we have this issue is that xact.c
8787  * does commit record XLOG insertion and clog update as two separate steps
8788  * protected by different locks, but again that seems best on grounds of
8789  * minimizing lock contention.)
8790  *
8791  * A transaction that has not yet set delayChkpt when we look cannot be at
8792  * risk, since he's not inserted his commit record yet; and one that's
8793  * already cleared it is not at risk either, since he's done fixing clog
8794  * and we will correctly flush the update below. So we cannot miss any
8795  * xacts we need to wait for.
8796  */
8797  vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
8798  if (nvxids > 0)
8799  {
8800  do
8801  {
8802  pg_usleep(10000L); /* wait for 10 msec */
8803  } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
8804  }
8805  pfree(vxids);
8806 
8807  CheckPointGuts(checkPoint.redo, flags);
8808 
8809  /*
8810  * Take a snapshot of running transactions and write this to WAL. This
8811  * allows us to reconstruct the state of running transactions during
8812  * archive recovery, if required. Skip, if this info disabled.
8813  *
8814  * If we are shutting down, or Startup process is completing crash
8815  * recovery we don't need to write running xact data.
8816  */
8817  if (!shutdown && XLogStandbyInfoActive())
8819 
8821 
8822  /*
8823  * Now insert the checkpoint record into XLOG.
8824  */
8825  XLogBeginInsert();
8826  XLogRegisterData((char *) (&checkPoint), sizeof(checkPoint));
8827  recptr = XLogInsert(RM_XLOG_ID,
8828  shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
8830 
8831  XLogFlush(recptr);
8832 
8833  /*
8834  * We mustn't write any new WAL after a shutdown checkpoint, or it will be
8835  * overwritten at next startup. No-one should even try, this just allows
8836  * sanity-checking. In the case of an end-of-recovery checkpoint, we want
8837  * to just temporarily disable writing until the system has exited
8838  * recovery.
8839  */
8840  if (shutdown)
8841  {
8842  if (flags & CHECKPOINT_END_OF_RECOVERY)
8843  LocalXLogInsertAllowed = -1; /* return to "check" state */
8844  else
8845  LocalXLogInsertAllowed = 0; /* never again write WAL */
8846  }
8847 
8848  /*
8849  * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
8850  * = end of actual checkpoint record.
8851  */
8852  if (shutdown && checkPoint.redo != ProcLastRecPtr)
8853  ereport(PANIC,
8854  (errmsg("concurrent write-ahead log activity while database system is shutting down")));
8855 
8856  /*
8857  * Remember the prior checkpoint's redo pointer, used later to determine
8858  * the point where the log can be truncated.
8859  */
8860  PriorRedoPtr = ControlFile->checkPointCopy.redo;
8861 
8862  /*
8863  * Update the control file.
8864  */
8865  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8866  if (shutdown)
8870  ControlFile->checkPointCopy = checkPoint;
8871  ControlFile->time = (pg_time_t) time(NULL);
8872  /* crash recovery should always recover to the end of WAL */
8875 
8876  /*
8877  * Persist unloggedLSN value. It's reset on crash recovery, so this goes
8878  * unused on non-shutdown checkpoints, but seems useful to store it always
8879  * for debugging purposes.
8880  */
8884 
8886  LWLockRelease(ControlFileLock);
8887 
8888  /* Update shared-memory copy of checkpoint XID/epoch */
8890  XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
8891  XLogCtl->ckptXid = checkPoint.nextXid;
8893 
8894  /*
8895  * We are now done with critical updates; no need for system panic if we
8896  * have trouble while fooling with old log segments.
8897  */
8898  END_CRIT_SECTION();
8899 
8900  /*
8901  * Let smgr do post-checkpoint cleanup (eg, deleting old files).
8902  */
8903  smgrpostckpt();
8904 
8905  /*
8906  * Delete old log files (those no longer needed even for previous
8907  * checkpoint or the standbys in XLOG streaming).
8908  */
8909  if (PriorRedoPtr != InvalidXLogRecPtr)
8910  {
8911  XLogSegNo _logSegNo;
8912 
8913  /* Update the average distance between checkpoints. */
8915 
8916  XLByteToSeg(PriorRedoPtr, _logSegNo);
8917  KeepLogSeg(recptr, &_logSegNo);
8918  _logSegNo--;
8919  RemoveOldXlogFiles(_logSegNo, PriorRedoPtr, recptr);
8920  }
8921 
8922  /*
8923  * Make more log segments if needed. (Do this after recycling old log
8924  * segments, since that may supply some of the needed files.)
8925  */
8926  if (!shutdown)
8927  PreallocXlogFiles(recptr);
8928 
8929  /*
8930  * Truncate pg_subtrans if possible. We can throw away all data before
8931  * the oldest XMIN of any running transaction. No future transaction will
8932  * attempt to reference any pg_subtrans entry older than that (see Asserts
8933  * in subtrans.c). During recovery, though, we mustn't do this because
8934  * StartupSUBTRANS hasn't been called yet.
8935  */
8936  if (!RecoveryInProgress())
8938 
8939  /* Real work is done, but log and update stats before releasing lock. */
8940  LogCheckpointEnd(false);
8941 
8942  TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
8943  NBuffers,
8947 
8948  LWLockRelease(CheckpointLock);
8949 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8245
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8471
#define XLogSegSize
Definition: xlog_internal.h:92
static int LocalXLogInsertAllowed
Definition: xlog.c:233
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:581
static void WALInsertLockRelease(void)
Definition: xlog.c:1645
pg_time_t time
Definition: pg_control.h:128
#define XLOG_CHECKPOINT_ONLINE
Definition: pg_control.h:68
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:168
uint32 oidCount
Definition: transam.h:112
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:1914
XLogRecPtr unloggedLSN
Definition: xlog.c:588
XLogRecPtr ProcLastRecPtr
Definition: xlog.c:336
TransactionId oldestActiveXid
Definition: pg_control.h:63
void InitXLogInsert(void)
Definition: xloginsert.c:1028
TimestampTz ckpt_start_t
Definition: xlog.h:198
slock_t info_lck
Definition: xlog.c:702
#define END_CRIT_SECTION()
Definition: miscadmin.h:133
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids)
Definition: procarray.c:2254
MultiXactId oldestMulti
Definition: pg_control.h:49
TimeLineID PrevTimeLineID
Definition: xlog.c:629
TimeLineID PrevTimeLineID
Definition: pg_control.h:39
#define START_CRIT_SECTION()
Definition: miscadmin.h:131
int ckpt_segs_recycled
Definition: xlog.h:208
TransactionId oldestXid
Definition: transam.h:119
#define MemSet(start, val, len)
Definition: c.h:858
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
Definition: xlog.c:3830
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:9010
CheckPoint checkPointCopy
Definition: pg_control.h:132
XLogCtlInsert Insert
Definition: xlog.c:575
TransactionId oldestXid
Definition: pg_control.h:47
bool RecoveryInProgress(void)
Definition: xlog.c:7878
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:354
uint32 ckptXidEpoch
Definition: xlog.c:580
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:550
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2757
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#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:4646
TransactionId oldestCommitTsXid
Definition: pg_control.h:52
void pfree(void *pointer)
Definition: mcxt.c:950
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:909
#define ERROR
Definition: elog.h:43
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8386
TransactionId nextXid
Definition: transam.h:117
uint32 nextXidEpoch
Definition: pg_control.h:42
static XLogRecPtr RedoRecPtr
Definition: xlog.c:350
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:67
XLogRecPtr unloggedLSN
Definition: pg_control.h:134
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3739
uint64 XLogSegNo
Definition: xlogdefs.h:34
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:176
VariableCache ShmemVariableCache
Definition: varsup.c:34
#define InvalidTransactionId
Definition: transam.h:31
uint64 CurrBytePos
Definition: xlog.c:526
unsigned int uint32
Definition: c.h:268
XLogRecPtr RedoRecPtr
Definition: xlog.c:579
int ckpt_segs_removed
Definition: xlog.h:207
#define CHECKPOINT_FORCE
Definition: xlog.h:179
#define INSERT_FREESPACE(endptr)
Definition: xlog.c:719
#define ereport(elevel, rest)
Definition: elog.h:122
TransactionId oldestCommitTsXid
Definition: transam.h:129
static void Insert(File file)
Definition: fd.c:1044
int ckpt_bufs_written
Definition: xlog.h:204
static void LocalSetXLogInsertAllowed(void)
Definition: xlog.c:8004
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:9334
Oid oldestMultiDB
Definition: pg_control.h:50
#define XLogStandbyInfoActive()
Definition: xlog.h:159
XLogRecPtr prevCheckPoint
Definition: pg_control.h:130
static ControlFileData * ControlFile
Definition: xlog.c:713
TimeLineID ThisTimeLineID
Definition: xlog.c:179
Oid nextOid
Definition: pg_control.h:44
bool fullPageWrites
Definition: pg_control.h:41
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1315
void smgrpreckpt(void)
Definition: smgr.c:744
#define XLByteToSeg(xlrp, logSegNo)
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
Oid oldestXidDB
Definition: pg_control.h:48
TransactionId newestCommitTsXid
Definition: transam.h:130
CheckpointStatsData CheckpointStats
Definition: xlog.c:173
#define SizeOfXLogShortPHD
Definition: xlog_internal.h:55
MultiXactId nextMulti
Definition: pg_control.h:45
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1616
static XLogCtlData * XLogCtl
Definition: xlog.c:705
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
int ckpt_segs_added
Definition: xlog.h:206
slock_t ulsn_lck
Definition: xlog.c:589
TimeLineID ThisTimeLineID
Definition: pg_control.h:38
int errmsg(const char *fmt,...)
Definition: elog.c:797
TransactionId GetOldestActiveTransactionId(void)
Definition: procarray.c:2092
int NBuffers
Definition: globals.c:123
#define elog
Definition: elog.h:219
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids)
Definition: procarray.c:2299
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr RedoRecPtr
Definition: xlog.c:548
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:8368
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:175
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:167
#define SizeOfXLogLongPHD
Definition: xlog_internal.h:72
bool CreateRestartPoint ( int  flags)

Definition at line 9080 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, NULL, PreallocXlogFiles(), ControlFileData::prevCheckPoint, PROCARRAY_FLAGS_DEFAULT, RecoveryInProgress(), CheckPoint::redo, RedoRecPtr, XLogCtlInsert::RedoRecPtr, XLogCtlData::RedoRecPtr, RemoveOldXlogFiles(), SpinLockAcquire, SpinLockRelease, ControlFileData::state, CheckPoint::ThisTimeLineID, ThisTimeLineID, ControlFileData::time, timestamptz_to_str(), TruncateSUBTRANS(), UpdateCheckPointDistanceEstimate(), UpdateControlFile(), UpdateMinRecoveryPoint(), WALInsertLockAcquireExclusive(), WALInsertLockRelease(), XLByteToSeg, and XLogRecPtrIsInvalid.

Referenced by CheckpointerMain(), and ShutdownXLOG().

9081 {
9082  XLogRecPtr lastCheckPointRecPtr;
9083  XLogRecPtr lastCheckPointEndPtr;
9084  CheckPoint lastCheckPoint;
9085  XLogRecPtr PriorRedoPtr;
9086  TimestampTz xtime;
9087 
9088  /*
9089  * Acquire CheckpointLock to ensure only one restartpoint or checkpoint
9090  * happens at a time.
9091  */
9092  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
9093 
9094  /* Get a local copy of the last safe checkpoint record. */
9096  lastCheckPointRecPtr = XLogCtl->lastCheckPointRecPtr;
9097  lastCheckPointEndPtr = XLogCtl->lastCheckPointEndPtr;
9098  lastCheckPoint = XLogCtl->lastCheckPoint;
9100 
9101  /*
9102  * Check that we're still in recovery mode. It's ok if we exit recovery
9103  * mode after this check, the restart point is valid anyway.
9104  */
9105  if (!RecoveryInProgress())
9106  {
9107  ereport(DEBUG2,
9108  (errmsg("skipping restartpoint, recovery has already ended")));
9109  LWLockRelease(CheckpointLock);
9110  return false;
9111  }
9112 
9113  /*
9114  * If the last checkpoint record we've replayed is already our last
9115  * restartpoint, we can't perform a new restart point. We still update
9116  * minRecoveryPoint in that case, so that if this is a shutdown restart
9117  * point, we won't start up earlier than before. That's not strictly
9118  * necessary, but when hot standby is enabled, it would be rather weird if
9119  * the database opened up for read-only connections at a point-in-time
9120  * before the last shutdown. Such time travel is still possible in case of
9121  * immediate shutdown, though.
9122  *
9123  * We don't explicitly advance minRecoveryPoint when we do create a
9124  * restartpoint. It's assumed that flushing the buffers will do that as a
9125  * side-effect.
9126  */
9127  if (XLogRecPtrIsInvalid(lastCheckPointRecPtr) ||
9128  lastCheckPoint.redo <= ControlFile->checkPointCopy.redo)
9129  {
9130  ereport(DEBUG2,
9131  (errmsg("skipping restartpoint, already performed at %X/%X",
9132  (uint32) (lastCheckPoint.redo >> 32),
9133  (uint32) lastCheckPoint.redo)));
9134 
9136  if (flags & CHECKPOINT_IS_SHUTDOWN)
9137  {
9138  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9140  ControlFile->time = (pg_time_t) time(NULL);
9142  LWLockRelease(ControlFileLock);
9143  }
9144  LWLockRelease(CheckpointLock);
9145  return false;
9146  }
9147 
9148  /*
9149  * Update the shared RedoRecPtr so that the startup process can calculate
9150  * the number of segments replayed since last restartpoint, and request a
9151  * restartpoint if it exceeds CheckPointSegments.
9152  *
9153  * Like in CreateCheckPoint(), hold off insertions to update it, although
9154  * during recovery this is just pro forma, because no WAL insertions are
9155  * happening.
9156  */
9158  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = lastCheckPoint.redo;
9160 
9161  /* Also update the info_lck-protected copy */
9163  XLogCtl->RedoRecPtr = lastCheckPoint.redo;
9165 
9166  /*
9167  * Prepare to accumulate statistics.
9168  *
9169  * Note: because it is possible for log_checkpoints to change while a
9170  * checkpoint proceeds, we always accumulate stats, even if
9171  * log_checkpoints is currently off.
9172  */
9173  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
9175 
9176  if (log_checkpoints)
9177  LogCheckpointStart(flags, true);
9178 
9179  CheckPointGuts(lastCheckPoint.redo, flags);
9180 
9181  /*
9182  * Remember the prior checkpoint's redo pointer, used later to determine
9183  * the point at which we can truncate the log.
9184  */
9185  PriorRedoPtr = ControlFile->checkPointCopy.redo;
9186 
9187  /*
9188  * Update pg_control, using current time. Check that it still shows
9189  * IN_ARCHIVE_RECOVERY state and an older checkpoint, else do nothing;
9190  * this is a quick hack to make sure nothing really bad happens if somehow
9191  * we get here after the end-of-recovery checkpoint.
9192  */
9193  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
9195  ControlFile->checkPointCopy.redo < lastCheckPoint.redo)
9196  {
9198  ControlFile->checkPoint = lastCheckPointRecPtr;
9199  ControlFile->checkPointCopy = lastCheckPoint;
9200  ControlFile->time = (pg_time_t) time(NULL);
9201 
9202  /*
9203  * Ensure minRecoveryPoint is past the checkpoint record. Normally,
9204  * this will have happened already while writing out dirty buffers,
9205  * but not necessarily - e.g. because no buffers were dirtied. We do
9206  * this because a non-exclusive base backup uses minRecoveryPoint to
9207  * determine which WAL files must be included in the backup, and the
9208  * file (or files) containing the checkpoint record must be included,
9209  * at a minimum. Note that for an ordinary restart of recovery there's
9210  * no value in having the minimum recovery point any earlier than this
9211  * anyway, because redo will begin just after the checkpoint record.
9212  */
9213  if (ControlFile->minRecoveryPoint < lastCheckPointEndPtr)
9214  {
9215  ControlFile->minRecoveryPoint = lastCheckPointEndPtr;
9217 
9218  /* update local copy */
9221  }
9222  if (flags & CHECKPOINT_IS_SHUTDOWN)
9225  }
9226  LWLockRelease(ControlFileLock);
9227 
9228  /*
9229  * Delete old log files (those no longer needed even for previous
9230  * checkpoint/restartpoint) to prevent the disk holding the xlog from
9231  * growing full.
9232  */
9233  if (PriorRedoPtr != InvalidXLogRecPtr)
9234  {
9235  XLogRecPtr receivePtr;
9236  XLogRecPtr replayPtr;
9237  TimeLineID replayTLI;
9238  XLogRecPtr endptr;
9239  XLogSegNo _logSegNo;
9240 
9241  /* Update the average distance between checkpoints/restartpoints. */
9243 
9244  XLByteToSeg(PriorRedoPtr, _logSegNo);
9245 
9246  /*
9247  * Get the current end of xlog replayed or received, whichever is
9248  * later.
9249  */
9250  receivePtr = GetWalRcvWriteRecPtr(NULL, NULL);
9251  replayPtr = GetXLogReplayRecPtr(&replayTLI);
9252  endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
9253 
9254  KeepLogSeg(endptr, &_logSegNo);
9255  _logSegNo--;
9256 
9257  /*
9258  * Try to recycle segments on a useful timeline. If we've been
9259  * promoted since the beginning of this restartpoint, use the new
9260  * timeline chosen at end of recovery (RecoveryInProgress() sets
9261  * ThisTimeLineID in that case). If we're still in recovery, use the
9262  * timeline we're currently replaying.
9263  *
9264  * There is no guarantee that the WAL segments will be useful on the
9265  * current timeline; if recovery proceeds to a new timeline right
9266  * after this, the pre-allocated WAL segments on this timeline will
9267  * not be used, and will go wasted until recycled on the next
9268  * restartpoint. We'll live with that.
9269  */
9270  if (RecoveryInProgress())
9271  ThisTimeLineID = replayTLI;
9272 
9273  RemoveOldXlogFiles(_logSegNo, PriorRedoPtr, endptr);
9274 
9275  /*
9276  * Make more log segments if needed. (Do this after recycling old log
9277  * segments, since that may supply some of the needed files.)
9278  */
9279  PreallocXlogFiles(endptr);
9280 
9281  /*
9282  * ThisTimeLineID is normally not set when we're still in recovery.
9283  * However, recycling/preallocating segments above needed
9284  * ThisTimeLineID to determine which timeline to install the segments
9285  * on. Reset it now, to restore the normal state of affairs for
9286  * debugging purposes.
9287  */
9288  if (RecoveryInProgress())
9289  ThisTimeLineID = 0;
9290  }
9291 
9292  /*
9293  * Truncate pg_subtrans if possible. We can throw away all data before
9294  * the oldest XMIN of any running transaction. No future transaction will
9295  * attempt to reference any pg_subtrans entry older than that (see Asserts
9296  * in subtrans.c). When hot standby is disabled, though, we mustn't do
9297  * this because StartupSUBTRANS hasn't been called yet.
9298  */
9299  if (EnableHotStandby)
9301 
9302  /* Real work is done, but log and update before releasing lock. */
9303  LogCheckpointEnd(true);
9304 
9305  xtime = GetLatestXTime();
9307  (errmsg("recovery restart point at %X/%X",
9308  (uint32) (lastCheckPoint.redo >> 32), (uint32) lastCheckPoint.redo),
9309  xtime ? errdetail("last completed transaction was at log time %s",
9310  timestamptz_to_str(xtime)) : 0));
9311 
9312  LWLockRelease(CheckpointLock);
9313 
9314  /*
9315  * Finally, execute archive_cleanup_command, if any.
9316  */
9319  "archive_cleanup_command",
9320  false);
9321 
9322  return true;
9323 }
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8471
bool log_checkpoints
Definition: xlog.c:102
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TimeLineID
Definition: xlogdefs.h:45
int64 pg_time_t
Definition: pgtime.h:23
XLogRecPtr GetWalRcvWriteRecPtr(XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI)
static void WALInsertLockRelease(void)
Definition: xlog.c:1645
pg_time_t time
Definition: pg_control.h:128
TimeLineID minRecoveryPointTLI
Definition: pg_control.h:168
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
Definition: xlog.c:2682
TimestampTz ckpt_start_t
Definition: xlog.h:198
slock_t info_lck
Definition: xlog.c:702
#define MemSet(start, val, len)
Definition: c.h:858
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr PriorRedoPtr, XLogRecPtr endptr)
Definition: xlog.c:3830
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
Definition: xlog.c:9010
TimestampTz GetLatestXTime(void)
Definition: xlog.c:6066
CheckPoint checkPointCopy
Definition: pg_control.h:132
XLogCtlInsert Insert
Definition: xlog.c:575
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:7878
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:354
XLogRecPtr lastCheckPointRecPtr
Definition: xlog.c:671
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
#define SpinLockAcquire(lock)
Definition: spin.h:62
void UpdateControlFile(void)
Definition: xlog.c:4646
static void LogCheckpointEnd(bool restartpoint)
Definition: xlog.c:8386
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11098
#define DEBUG2
Definition: elog.h:24
static XLogRecPtr RedoRecPtr
Definition: xlog.c:350
static void PreallocXlogFiles(XLogRecPtr endptr)
Definition: xlog.c:3739
uint64 XLogSegNo
Definition: xlogdefs.h:34
int errdetail(const char *fmt,...)
Definition: elog.c:873
unsigned int uint32
Definition: c.h:268
XLogRecPtr RedoRecPtr
Definition: xlog.c:579
#define ereport(elevel, rest)
Definition: elog.h:122
CheckPoint lastCheckPoint
Definition: xlog.c:673
void ExecuteRecoveryCommand(char *command, char *commandName, bool failOnSignal)
Definition: xlogarchive.c:329
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define SpinLockRelease(lock)
Definition: spin.h:64
static TimeLineID minRecoveryPointTLI
Definition: xlog.c:822
#define PROCARRAY_FLAGS_DEFAULT
Definition: procarray.h:50
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9334
XLogRecPtr prevCheckPoint
Definition: pg_control.h:130
static ControlFileData * ControlFile
Definition: xlog.c:713
TimeLineID ThisTimeLineID
Definition: xlog.c:179
TransactionId GetOldestXmin(Relation rel, int flags)
Definition: procarray.c:1315
#define XLByteToSeg(xlrp, logSegNo)
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
CheckpointStatsData CheckpointStats
Definition: xlog.c:173
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1616
static XLogCtlData * XLogCtl
Definition: xlog.c:705
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
char archiveCleanupCommand[MAXPGPATH]
Definition: xlog.c:635
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:548
XLogRecPtr lastCheckPointEndPtr
Definition: xlog.c:672
XLogRecPtr checkPoint
Definition: pg_control.h:129
XLogRecPtr redo
Definition: pg_control.h:36
static void LogCheckpointStart(int flags, bool restartpoint)
Definition: xlog.c:8368
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:175
XLogRecPtr minRecoveryPoint
Definition: pg_control.h:167
static XLogRecPtr minRecoveryPoint
Definition: xlog.c:820
const char * timestamptz_to_str(TimestampTz t)
Definition: timestamp.c:1710
bool DataChecksumsEnabled ( void  )

Definition at line 4715 of file xlog.c.

References Assert, ControlFileData::data_checksum_version, and NULL.

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

4716 {
4717  Assert(ControlFile != NULL);
4718  return (ControlFile->data_checksum_version > 0);
4719 }
uint32 data_checksum_version
Definition: pg_control.h:222
static ControlFileData * ControlFile
Definition: xlog.c:713
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
void do_pg_abort_backup ( void  )

Definition at line 11078 of file xlog.c.

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

Referenced by base_backup_cleanup(), and nonexclusive_base_backup_cleanup().

11079 {
11083 
11086  {
11087  XLogCtl->Insert.forcePageWrites = false;
11088  }
11090 }
static void WALInsertLockRelease(void)
Definition: xlog.c:1645
XLogCtlInsert Insert
Definition: xlog.c:575
bool forcePageWrites
Definition: xlog.c:549
int nonExclusiveBackups
Definition: xlog.c:561
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:560
#define Assert(condition)
Definition: c.h:676
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1616
static XLogCtlData * XLogCtl
Definition: xlog.c:705
XLogRecPtr do_pg_start_backup ( const char *  backupidstr,
bool  fast,
TimeLineID starttli_p,
StringInfo  labelfile,
DIR tblspcdir,
List **  tablespaces,
StringInfo  tblspcmapfile,
bool  infotbssize,
bool  needtblspcmapfile 
)

Definition at line 10183 of file xlog.c.

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

Referenced by perform_base_backup(), and pg_start_backup().

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

Definition at line 10691 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, NULL, palloc(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, pg_localtime(), pg_stop_backup_callback(), pg_strftime(), pg_usleep(), RecoveryInProgress(), remaining, RequestXLogSwitch(), SESSION_BACKUP_NONE, sessionBackupState, SpinLockAcquire, SpinLockRelease, TABLESPACE_MAP, ThisTimeLineID, WALInsertLockAcquireExclusive(), WALInsertLockRelease(), WARNING, XLByteToPrevSeg, XLByteToSeg, XLOG_BACKUP_END, XLogArchiveIsBusy(), XLogArchivingActive, XLogArchivingAlways, XLogBeginInsert(), XLogFileName, XLogInsert(), XLogIsNeeded, XLogRegisterData(), and XLogSegSize.

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

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

Definition at line 10672 of file xlog.c.

References sessionBackupState.

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

10673 {
10674  return sessionBackupState;
10675 }
static SessionBackupState sessionBackupState
Definition: xlog.c:510
TimestampTz GetCurrentChunkReplayStartTime ( void  )

Definition at line 6096 of file xlog.c.

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

Referenced by GetReplicationApplyDelay().

6097 {
6098  TimestampTz xtime;
6099 
6101  xtime = XLogCtl->currentChunkStartTime;
6103 
6104  return xtime;
6105 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:705
TimestampTz currentChunkStartTime
Definition: xlog.c:692
XLogRecPtr GetFakeLSNForUnloggedRel ( void  )

Definition at line 4731 of file xlog.c.

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

Referenced by gistGetFakeLSN().

4732 {
4733  XLogRecPtr nextUnloggedLSN;
4734 
4735  /* increment the unloggedLSN counter, need SpinLock */
4737  nextUnloggedLSN = XLogCtl->unloggedLSN++;
4739 
4740  return nextUnloggedLSN;
4741 }
XLogRecPtr unloggedLSN
Definition: xlog.c:588
#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:705
slock_t ulsn_lck
Definition: xlog.c:589
XLogRecPtr GetFlushRecPtr ( void  )

Definition at line 8227 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(), read_local_xlog_page(), StartReplication(), WalSndWaitForWal(), XLogSendLogical(), and XLogSendPhysical().

8228 {
8232 
8233  return LogwrtResult.Flush;
8234 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:747
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:599
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:705
XLogRecPtr Flush
Definition: xlog.c:424
void GetFullPageWriteInfo ( XLogRecPtr RedoRecPtr_p,
bool doPageWrites_p 
)

Definition at line 8196 of file xlog.c.

References doPageWrites, and RedoRecPtr.

Referenced by XLogCheckBufferNeedsBackup(), and XLogInsert().

8197 {
8198  *RedoRecPtr_p = RedoRecPtr;
8199  *doPageWrites_p = doPageWrites;
8200 }
static bool doPageWrites
Definition: xlog.c:357
static XLogRecPtr RedoRecPtr
Definition: xlog.c:350
XLogRecPtr GetInsertRecPtr ( void  )

Definition at line 8211 of file xlog.c.

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

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

8212 {
8213  XLogRecPtr recptr;
8214 
8216  recptr = XLogCtl->LogwrtRqst.Write;
8218 
8219  return recptr;
8220 }
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr Write
Definition: xlog.c:417
XLogwrtRqst LogwrtRqst
Definition: xlog.c:578
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:705
XLogRecPtr GetLastImportantRecPtr ( void  )

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

8246 {
8248  int i;
8249 
8250  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
8251  {
8252  XLogRecPtr last_important;
8253 
8254  /*
8255  * Need to take a lock to prevent torn reads of the LSN, which are
8256  * possible on some of the supported platforms. WAL insert locks only
8257  * support exclusive mode, so we have to use that.
8258  */
8260  last_important = WALInsertLocks[i].l.lastImportantAt;
8261  LWLockRelease(&WALInsertLocks[i].l.lock);
8262 
8263  if (res < last_important)
8264  res = last_important;
8265  }
8266 
8267  return res;
8268 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
XLogRecPtr lastImportantAt
Definition: xlog.c:467
#define NUM_XLOGINSERT_LOCKS
Definition: xlog.c:118
WALInsertLock l
Definition: xlog.c:479
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
uint64 XLogRecPtr
Definition: xlogdefs.h:21
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
int i
static WALInsertLockPadded * WALInsertLocks
Definition: xlog.c:708
TimestampTz GetLatestXTime ( void  )

Definition at line 6066 of file xlog.c.

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

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

6067 {
6068  TimestampTz xtime;
6069 
6071  xtime = XLogCtl->recoveryLastXTime;
6073 
6074  return xtime;
6075 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz recoveryLastXTime
Definition: xlog.c:686
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:705
char* GetMockAuthenticationNonce ( void  )

Definition at line 4705 of file xlog.c.

References Assert, ControlFileData::mock_authentication_nonce, and NULL.

Referenced by scram_mock_salt().

4706 {
4707  Assert(ControlFile != NULL);
4709 }
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:229
static ControlFileData * ControlFile
Definition: xlog.c:713
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
void GetNextXidAndEpoch ( TransactionId xid,
uint32 epoch 
)

Definition at line 8296 of file xlog.c.

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

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

8297 {
8298  uint32 ckptXidEpoch;
8299  TransactionId ckptXid;
8300  TransactionId nextXid;
8301 
8302  /* Must read checkpoint info first, else have race condition */
8304  ckptXidEpoch = XLogCtl->ckptXidEpoch;
8305  ckptXid = XLogCtl->ckptXid;
8307 
8308  /* Now fetch current nextXid */
8309  nextXid = ReadNewTransactionId();
8310 
8311  /*
8312  * nextXid is certainly logically later than ckptXid. So if it's
8313  * numerically less, it must have wrapped into the next epoch.
8314  */
8315  if (nextXid < ckptXid)
8316  ckptXidEpoch++;
8317 
8318  *xid = nextXid;
8319  *epoch = ckptXidEpoch;
8320 }
TransactionId ckptXid
Definition: xlog.c:581
uint32 TransactionId
Definition: c.h:397
slock_t info_lck
Definition: xlog.c:702
uint32 ckptXidEpoch
Definition: xlog.c:580
#define SpinLockAcquire(lock)
Definition: spin.h:62
TransactionId ReadNewTransactionId(void)
Definition: varsup.c:250
unsigned int uint32
Definition: c.h:268
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:705
static const unsigned __int64 epoch
Definition: gettimeofday.c:34
XLogRecPtr GetRedoRecPtr ( void  )

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

8169 {
8170  XLogRecPtr ptr;
8171 
8172  /*
8173  * The possibly not up-to-date copy in XlogCtl is enough. Even if we
8174  * grabbed a WAL insertion lock to read the master copy, someone might
8175  * update it just after we've released the lock.
8176  */
8178  ptr = XLogCtl->RedoRecPtr;
8180 
8181  if (RedoRecPtr < ptr)
8182  RedoRecPtr = ptr;
8183 
8184  return RedoRecPtr;
8185 }
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
static XLogRecPtr RedoRecPtr
Definition: xlog.c:350
XLogRecPtr RedoRecPtr
Definition: xlog.c:579
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:705
uint64 GetSystemIdentifier ( void  )

Definition at line 4695 of file xlog.c.

References Assert, NULL, and ControlFileData::system_identifier.

Referenced by IdentifySystem(), and WalReceiverMain().

4696 {
4697  Assert(ControlFile != NULL);
4699 }
uint64 system_identifier
Definition: pg_control.h:106
static ControlFileData * ControlFile
Definition: xlog.c:713
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
XLogRecPtr GetXLogInsertRecPtr ( void  )

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

11118 {
11120  uint64 current_bytepos;
11121 
11122  SpinLockAcquire(&Insert->insertpos_lck);
11123  current_bytepos = Insert->CurrBytePos;
11124  SpinLockRelease(&Insert->insertpos_lck);
11125 
11126  return XLogBytePosToRecPtr(current_bytepos);
11127 }
slock_t insertpos_lck
Definition: xlog.c:517
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:1914
XLogCtlInsert Insert
Definition: xlog.c:575
#define SpinLockAcquire(lock)
Definition: spin.h:62
uint64 CurrBytePos
Definition: xlog.c:526
static void Insert(File file)
Definition: fd.c:1044
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:705
void GetXLogReceiptTime ( TimestampTz rtime,
bool fromStream 
)

Definition at line 6112 of file xlog.c.

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

Referenced by GetStandbyLimitTime().

6113 {
6114  /*
6115  * This must be executed in the startup process, since we don't export the
6116  * relevant state to shared memory.
6117  */
6118  Assert(InRecovery);
6119 
6120  *rtime = XLogReceiptTime;
6121  *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
6122 }
static XLogSource XLogReceiptSource
Definition: xlog.c:814
bool InRecovery
Definition: xlog.c:192
static TimestampTz XLogReceiptTime
Definition: xlog.c:813
#define Assert(condition)
Definition: c.h:676
XLogRecPtr GetXLogReplayRecPtr ( TimeLineID replayTLI)

Definition at line 11098 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(), read_local_xlog_page(), WalReceiverMain(), WalSndWaitForWal(), and XLogWalRcvSendReply().

11099 {
11100  XLogRecPtr recptr;
11101  TimeLineID tli;
11102 
11104  recptr = XLogCtl->lastReplayedEndRecPtr;
11105  tli = XLogCtl->lastReplayedTLI;
11107 
11108  if (replayTLI)
11109  *replayTLI = tli;
11110  return recptr;
11111 }
uint32 TimeLineID
Definition: xlogdefs.h:45
slock_t info_lck
Definition: xlog.c:702
#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:705
TimeLineID lastReplayedTLI
Definition: xlog.c:682
XLogRecPtr lastReplayedEndRecPtr
Definition: xlog.c:681
XLogRecPtr GetXLogWriteRecPtr ( void  )

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

11134 {
11138 
11139  return LogwrtResult.Write;
11140 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:747
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:599
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:705
XLogRecPtr Write
Definition: xlog.c:423
bool HotStandbyActive ( void  )

Definition at line 7934 of file xlog.c.

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

Referenced by XLogWalRcvSendHSFeedback().

7935 {
7936  /*
7937  * We check shared state each time only until Hot Standby is active. We
7938  * can't de-activate Hot Standby, so there's no need to keep checking
7939  * after the shared variable has once been seen true.
7940  */
7942  return true;
7943  else
7944  {
7945  /* spinlock is essential on machines with weak memory ordering! */
7949 
7950  return LocalHotStandbyActive;
7951  }
7952 }
bool SharedHotStandbyActive
Definition: xlog.c:647
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool LocalHotStandbyActive
Definition: xlog.c:221
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:705
bool HotStandbyActiveInReplay ( void  )

Definition at line 7959 of file xlog.c.

References AmStartupProcess, Assert, IsPostmasterEnvironment, and LocalHotStandbyActive.

Referenced by btree_xlog_vacuum().

7960 {
7962  return LocalHotStandbyActive;
7963 }
#define AmStartupProcess()
Definition: miscadmin.h:406
bool IsPostmasterEnvironment
Definition: globals.c:100
static bool LocalHotStandbyActive
Definition: xlog.c:221
#define Assert(condition)
Definition: c.h:676
void InitXLOGAccess ( void  )

Definition at line 8145 of file xlog.c.

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

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

8146 {
8148 
8149  /* ThisTimeLineID doesn't change so we need no lock to copy it */
8152 
8153  /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
8154  (void) GetRedoRecPtr();
8155  /* Also update our copy of doPageWrites. */
8156  doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);
8157 
8158  /* Also initialize the working areas for constructing WAL records */
8159  InitXLogInsert();
8160 }
void InitXLogInsert(void)
Definition: xloginsert.c:1028
TimeLineID ThisTimeLineID
Definition: xlog.c:628
XLogCtlInsert Insert
Definition: xlog.c:575
bool fullPageWrites
Definition: xlog.c:550
static bool doPageWrites
Definition: xlog.c:357
bool forcePageWrites
Definition: xlog.c:549
static void Insert(File file)
Definition: fd.c:1044
TimeLineID ThisTimeLineID
Definition: xlog.c:179
#define Assert(condition)
Definition: c.h:676
static XLogCtlData * XLogCtl
Definition: xlog.c:705
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:8168
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:368
void issue_xlog_fsync ( int  fd,
XLogSegNo  segno 
)

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

10094 {
10095  switch (sync_method)
10096  {
10097  case SYNC_METHOD_FSYNC:
10098  if (pg_fsync_no_writethrough(fd) != 0)
10099  ereport(PANIC,
10101  errmsg("could not fsync log file %s: %m",
10102  XLogFileNameP(ThisTimeLineID, segno))));
10103  break;
10104 #ifdef HAVE_FSYNC_WRITETHROUGH
10106  if (pg_fsync_writethrough(fd) != 0)
10107  ereport(PANIC,
10109  errmsg("could not fsync write-through log file %s: %m",
10110  XLogFileNameP(ThisTimeLineID, segno))));
10111  break;
10112 #endif
10113 #ifdef HAVE_FDATASYNC
10114  case SYNC_METHOD_FDATASYNC:
10115  if (pg_fdatasync(fd) != 0)
10116  ereport(PANIC,
10118  errmsg("could not fdatasync log file %s: %m",
10119  XLogFileNameP(ThisTimeLineID, segno))));
10120  break;
10121 #endif
10122  case SYNC_METHOD_OPEN:
10124  /* write synced it already */
10125  break;
10126  default:
10127  elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
10128  break;
10129  }
10130 }
int pg_fdatasync(int fd)
Definition: fd.c:385
#define SYNC_METHOD_FSYNC_WRITETHROUGH
Definition: xlog.h:28
int pg_fsync_writethrough(int fd)
Definition: fd.c:362
int pg_fsync_no_writethrough(int fd)
Definition: fd.c:350
#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:10136
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:179
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
bool RecoveryInProgress ( void  )

Definition at line 7878 of file xlog.c.

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

Referenced by BackgroundWriterMain(), 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_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(), WalSndShutdown(), WalSndWaitForWal(), XLogBackgroundFlush(), XLogInsertAllowed(), XLogNeedsFlush(), and XLogSendPhysical().

7879 {
7880  /*
7881  * We check shared state each time only until we leave recovery mode. We
7882  * can't re-enter recovery, so there's no need to keep checking after the
7883  * shared variable has once been seen false.
7884  */
7886  return false;
7887  else
7888  {
7889  /*
7890  * use volatile pointer to make sure we make a fresh read of the
7891  * shared variable.
7892  */
7893  volatile XLogCtlData *xlogctl = XLogCtl;
7894 
7896 
7897  /*
7898  * Initialize TimeLineID and RedoRecPtr when we discover that recovery
7899  * is finished. InitPostgres() relies upon this behaviour to ensure
7900  * that InitXLOGAccess() is called at backend startup. (If you change
7901  * this, see also LocalSetXLogInsertAllowed.)
7902  */
7904  {
7905  /*
7906  * If we just exited recovery, make sure we read TimeLineID and
7907  * RedoRecPtr after SharedRecoveryInProgress (for machines with
7908  * weak memory ordering).
7909  */
7911  InitXLOGAccess();
7912  }
7913 
7914  /*
7915  * Note: We don't need a memory barrier when we're still in recovery.
7916  * We might exit recovery immediately after return, so the caller
7917  * can't rely on 'true' meaning that we're still in recovery anyway.
7918  */
7919 
7920  return LocalRecoveryInProgress;
7921  }
7922 }
void InitXLOGAccess(void)
Definition: xlog.c:8145
bool SharedRecoveryInProgress
Definition: xlog.c:641
#define pg_memory_barrier()
Definition: atomics.h:148
static XLogCtlData * XLogCtl
Definition: xlog.c:705
static bool LocalRecoveryInProgress
Definition: xlog.c:215
bool RecoveryIsPaused ( void  )

Definition at line 5935 of file xlog.c.

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

Referenced by pg_is_wal_replay_paused(), and recoveryPausesHere().

5936 {
5937  bool recoveryPause;
5938 
5940  recoveryPause = XLogCtl->recoveryPause;
5942 
5943  return recoveryPause;
5944 }
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:694
static XLogCtlData * XLogCtl
Definition: xlog.c:705
void RemovePromoteSignalFiles ( void  )

Definition at line 12079 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, PROMOTE_SIGNAL_FILE, and unlink().

Referenced by PostmasterMain().

12080 {
12083 }
#define FALLBACK_PROMOTE_SIGNAL_FILE
Definition: xlog.c:85
#define PROMOTE_SIGNAL_FILE
Definition: xlog.c:84
int unlink(const char *filename)
void SetRecoveryPause ( bool  recoveryPause)

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

5948 {
5950  XLogCtl->recoveryPause = recoveryPause;
5952 }
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:694
static XLogCtlData * XLogCtl
Definition: xlog.c:705
void SetWalWriterSleeping ( bool  sleeping)

Definition at line 12115 of file xlog.c.

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

Referenced by WalWriterMain().

12116 {
12118  XLogCtl->WalWriterSleeping = sleeping;
12120 }
slock_t info_lck
Definition: xlog.c:702
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool WalWriterSleeping
Definition: xlog.c:654
static XLogCtlData * XLogCtl
Definition: xlog.c:705
void ShutdownXLOG ( int  code,
Datum  arg 
)

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

8327 {
8328  /* Don't be chatty in standalone mode */
8330  (errmsg("shutting down")));
8331 
8332  /*
8333  * Signal walsenders to move to stopping state.
8334  */
8336 
8337  /*
8338  * Wait for WAL senders to be in stopping state. This prevents commands
8339  * from writing new WAL.
8340  */
8342 
8343  if (RecoveryInProgress())
8345  else
8346  {
8347  /*
8348  * If archiving is enabled, rotate the last XLOG file so that all the
8349  * remaining records are archived (postmaster wakes up the archiver
8350  * process one more time at the end of shutdown). The checkpoint
8351  * record will go to the next XLOG file and won't be archived (yet).
8352  */
8354  RequestXLogSwitch(false);
8355 
8357  }
8358  ShutdownCLOG();
8359  ShutdownCommitTs();
8360  ShutdownSUBTRANS();
8362 }
bool IsPostmasterEnvironment
Definition: globals.c:100
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9411
void ShutdownSUBTRANS(void)
Definition: subtrans.c:283
void CreateCheckPoint(int flags)
Definition: xlog.c:8533
void ShutdownCLOG(void)
Definition: clog.c:575
bool CreateRestartPoint(int flags)
Definition: xlog.c:9080
#define XLogArchiveCommandSet()
Definition: xlog.h:139
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:7878
void WalSndWaitStopping(void)
Definition: walsender.c:3059
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:3033
void ShutdownCommitTs(void)
Definition: commit_ts.c:745
#define XLogArchivingActive()
Definition: xlog.h:134
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define CHECKPOINT_IMMEDIATE
Definition: xlog.h:178
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:175
void StartupXLOG ( void  )

Definition at line 6194 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, NULL, 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, ControlFileData::prevCheckPoint, 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(), ReadControlFile(), 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(), ControlFileData::state, str_time(), strlcpy(), RunningTransactionsData::subxcnt, RunningTransactionsData::subxid_overflow, SyncDataDirectory(), XLogReaderState::system_identifier, ControlFileData::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(), unlink(), UNLOGGED_RELATION_CLEANUP, UNLOGGED_RELATION_INIT, ControlFileData::unloggedLSN, XLogCtlData::unloggedLSN, UpdateControlFile(), UpdateFullPageWrites(), ValidateXLOGDirectoryStructure(), 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(), XLogSegSize, XLR_CHECK_CONSISTENCY, XLR_INFO_MASK, and XRecOffIsValid.

Referenced by InitPostgres(), and StartupProcessMain().

6195 {
6197  CheckPoint checkPoint;
6198  bool wasShutdown;
6199  bool reachedStopPoint = false;
6200  bool haveBackupLabel = false;
6201  bool haveTblspcMap = false;
6202  XLogRecPtr RecPtr,
6203  checkPointLoc,
6204  EndOfLog;
6205  TimeLineID EndOfLogTLI;
6206  TimeLineID PrevTimeLineID;
6207  XLogRecord *record;
6208  TransactionId oldestActiveXID;
6209  bool backupEndRequired = false;
6210  bool backupFromStandby = false;
6211  DBState dbstate_at_startup;
6212  XLogReaderState *xlogreader;
6213  XLogPageReadPrivate private;
6214  bool fast_promoted = false;
6215  struct stat st;
6216 
6217  /*
6218  * Read control file and check XLOG status looks valid.
6219  *
6220  * Note: in most control paths, *ControlFile is already valid and we need
6221  * not do ReadControlFile() here, but might as well do it to be sure.
6222  */
6223  ReadControlFile();
6224 
6225  if (ControlFile->state < DB_SHUTDOWNED ||
6228  ereport(FATAL,
6229  (errmsg("control file contains invalid data")));
6230 
6232  {
6233  /* This is the expected case, so don't be chatty in standalone mode */
6235  (errmsg("database system was shut down at %s",
6236  str_time(ControlFile->time))));
6237  }
6239  ereport(LOG,
6240  (errmsg("database system was shut down in recovery at %s",
6241  str_time(ControlFile->time))));
6242  else if (ControlFile->state == DB_SHUTDOWNING)
6243  ereport(LOG,
6244  (errmsg("database system shutdown was interrupted; last known up at %s",
6245  str_time(ControlFile->time))));
6246  else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
6247  ereport(LOG,
6248  (errmsg("database system was interrupted while in recovery at %s",
6250  errhint("This probably means that some data is corrupted and"
6251  " you will have to use the last backup for recovery.")));
6253  ereport(LOG,
6254  (errmsg("database system was interrupted while in recovery at log time %s",
6256  errhint("If this has occurred more than once some data might be corrupted"
6257  " and you might need to choose an earlier recovery target.")));
6258  else if (ControlFile->state == DB_IN_PRODUCTION)
6259  ereport(LOG,
6260  (errmsg("database system was interrupted; last known up at %s",
6261  str_time(ControlFile->time))));
6262 
6263  /* This is just to allow attaching to startup process with a debugger */
6264 #ifdef XLOG_REPLAY_DELAY
6266  pg_usleep(60000000L);
6267 #endif
6268 
6269  /*
6270  * Verify that pg_wal and pg_wal/archive_status exist. In cases where
6271  * someone has performed a copy for PITR, these directories may have been
6272  * excluded and need to be re-created.
6273  */
6275 
6276  /*
6277  * If we previously crashed, there might be data which we had written,
6278  * intending to fsync it, but which we had not actually fsync'd yet.
6279  * Therefore, a power failure in the near future might cause earlier
6280  * unflushed writes to be lost, even though more recent data written to
6281  * disk from here on would be persisted. To avoid that, fsync the entire
6282  * data directory.
6283  */
6284  if (ControlFile->state != DB_SHUTDOWNED &&
6287 
6288  /*
6289  * Initialize on the assumption we want to recover to the latest timeline
6290  * that's active according to pg_control.
6291  */
6295  else
6297 
6298  /*
6299  * Check for recovery control file, and if so set up state for offline
6300  * recovery
6301  */
6303 
6304  /*
6305  * Save archive_cleanup_command in shared memory so that other processes
6306  * can see it.
6307  */
6310  sizeof(XLogCtl->archiveCleanupCommand));
6311 
6313  {
6315  ereport(LOG,
6316  (errmsg("entering standby mode")));
6317  else if (recoveryTarget == RECOVERY_TARGET_XID)
6318  ereport(LOG,
6319  (errmsg("starting point-in-time recovery to XID %u",
6320  recoveryTargetXid)));
6322  ereport(LOG,
6323  (errmsg("starting point-in-time recovery to %s",
6326  ereport(LOG,
6327  (errmsg("starting point-in-time recovery to \"%s\"",
6328  recoveryTargetName)));
6329  else if (recoveryTarget == RECOVERY_TARGET_LSN)
6330  ereport(LOG,
6331  (errmsg("starting point-in-time recovery to WAL location (LSN) \"%X/%X\"",
6332  (uint32) (recoveryTargetLSN >> 32),
6335  ereport(LOG,
6336  (errmsg("starting point-in-time recovery to earliest consistent point")));
6337  else
6338  ereport(LOG,
6339  (errmsg("starting archive recovery")));
6340  }
6341 
6342  /*
6343  * Take ownership of the wakeup latch if we're going to sleep during
6344  * recovery.
6345  */
6348 
6349  /* Set up XLOG reader facility */
6350  MemSet(&private, 0, sizeof(XLogPageReadPrivate));
6351  xlogreader = XLogReaderAllocate(&XLogPageRead, &private);
6352  if (!xlogreader)
6353  ereport(ERROR,
6354  (errcode(ERRCODE_OUT_OF_MEMORY),
6355  errmsg("out of memory"),
6356  errdetail("Failed while allocating a WAL reading processor.")));
6358 
6359  /*
6360  * Allocate pages dedicated to WAL consistency checks, those had better be
6361  * aligned.
6362  */
6363  replay_image_masked = (char *) palloc(BLCKSZ);
6364  master_image_masked = (char *) palloc(BLCKSZ);
6365 
6366  if (read_backup_label(&checkPointLoc, &backupEndRequired,
6367  &backupFromStandby))
6368  {
6369  List *tablespaces = NIL;
6370 
6371  /*
6372  * Archive recovery was requested, and thanks to the backup label
6373  * file, we know how far we need to replay to reach consistency. Enter
6374  * archive recovery directly.
6375  */
6376  InArchiveRecovery = true;
6378  StandbyMode = true;
6379 
6380  /*
6381  * When a backup_label file is present, we want to roll forward from
6382  * the checkpoint it identifies, rather than using pg_control.
6383  */
6384  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 0, true);
6385  if (record != NULL)
6386  {
6387  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
6388  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
6389  ereport(DEBUG1,
6390  (errmsg("checkpoint record is at %X/%X",
6391  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6392  InRecovery = true; /* force recovery even if SHUTDOWNED */
6393 
6394  /*
6395  * Make sure that REDO location exists. This may not be the case
6396  * if there was a crash during an online backup, which left a
6397  * backup_label around that references a WAL segment that's
6398  * already been archived.
6399  */
6400  if (checkPoint.redo < checkPointLoc)
6401  {
6402  if (!ReadRecord(xlogreader, checkPoint.redo, LOG, false))
6403  ereport(FATAL,
6404  (errmsg("could not find redo location referenced by checkpoint record"),
6405  errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6406  }
6407  }
6408  else
6409  {
6410  ereport(FATAL,
6411  (errmsg("could not locate required checkpoint record"),
6412  errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6413  wasShutdown = false; /* keep compiler quiet */
6414  }
6415 
6416  /* read the tablespace_map file if present and create symlinks. */
6417  if (read_tablespace_map(&tablespaces))
6418  {
6419  ListCell *lc;
6420 
6421  foreach(lc, tablespaces)
6422  {
6423  tablespaceinfo *ti = lfirst(lc);
6424  char *linkloc;
6425 
6426  linkloc = psprintf("pg_tblspc/%s", ti->oid);
6427 
6428  /*
6429  * Remove the existing symlink if any and Create the symlink
6430  * under PGDATA.
6431  */
6432  remove_tablespace_symlink(linkloc);
6433 
6434  if (symlink(ti->path, linkloc) < 0)
6435  ereport(ERROR,
6437  errmsg("could not create symbolic link \"%s\": %m",
6438  linkloc)));
6439 
6440  pfree(ti->oid);
6441  pfree(ti->path);
6442  pfree(ti);
6443  }
6444 
6445  /* set flag to delete it later */
6446  haveTblspcMap = true;
6447  }
6448 
6449  /* set flag to delete it later */
6450  haveBackupLabel = true;
6451  }
6452  else
6453  {
6454  /*
6455  * If tablespace_map file is present without backup_label file, there
6456  * is no use of such file. There is no harm in retaining it, but it
6457  * is better to get rid of the map file so that we don't have any
6458  * redundant file in data directory and it will avoid any sort of
6459  * confusion. It seems prudent though to just rename the file out of
6460  * the way rather than delete it completely, also we ignore any error
6461  * that occurs in rename operation as even if map file is present
6462  * without backup_label file, it is harmless.
6463  */
6464  if (stat(TABLESPACE_MAP, &st) == 0)
6465  {
6468  ereport(LOG,
6469  (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
6471  errdetail("File \"%s\" was renamed to \"%s\".",
6473  else
6474  ereport(LOG,
6475  (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
6477  errdetail("Could not rename file \"%s\" to \"%s\": %m.",
6479  }
6480 
6481  /*
6482  * It's possible that archive recovery was requested, but we don't
6483  * know how far we need to replay the WAL before we reach consistency.
6484  * This can happen for example if a base backup is taken from a
6485  * running server using an atomic filesystem snapshot, without calling
6486  * pg_start/stop_backup. Or if you just kill a running master server
6487  * and put it into archive recovery by creating a recovery.conf file.
6488  *
6489  * Our strategy in that case is to perform crash recovery first,
6490  * replaying all the WAL present in pg_wal, and only enter archive
6491  * recovery after that.
6492  *
6493  * But usually we already know how far we need to replay the WAL (up
6494  * to minRecoveryPoint, up to backupEndPoint, or until we see an
6495  * end-of-backup record), and we can enter archive recovery directly.
6496  */
6502  {
6503  InArchiveRecovery = true;
6505  StandbyMode = true;
6506  }
6507 
6508  /*
6509  * Get the last valid checkpoint record. If the latest one according
6510  * to pg_control is broken, try the next-to-last one.
6511  */
6512  checkPointLoc = ControlFile->checkPoint;
6514  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 1, true);
6515  if (record != NULL)
6516  {
6517  ereport(DEBUG1,
6518  (errmsg("checkpoint record is at %X/%X",
6519  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6520  }
6521  else if (StandbyMode)
6522  {
6523  /*
6524  * The last valid checkpoint record required for a streaming
6525  * recovery exists in neither standby nor the primary.
6526  */
6527  ereport(PANIC,
6528  (errmsg("could not locate a valid checkpoint record")));
6529  }
6530  else
6531  {
6532  checkPointLoc = ControlFile->prevCheckPoint;
6533  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 2, true);
6534  if (record != NULL)
6535  {
6536  ereport(LOG,
6537  (errmsg("using previous checkpoint record at %X/%X",
6538  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6539  InRecovery = true; /* force recovery even if SHUTDOWNED */
6540  }
6541  else
6542  ereport(PANIC,
6543  (errmsg("could not locate a valid checkpoint record")));
6544  }
6545  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
6546  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
6547  }
6548 
6549  /*
6550  * Clear out any old relcache cache files. This is *necessary* if we do
6551  * any WAL replay, since that would probably result in the cache files
6552  * being out of sync with database reality. In theory we could leave them
6553  * in place if the database had been cleanly shut down, but it seems
6554  * safest to just remove them always and let them be rebuilt during the
6555  * first backend startup. These files needs to be removed from all
6556  * directories including pg_tblspc, however the symlinks are created only
6557  * after reading tablespace_map file in case of archive recovery from
6558  * backup, so needs to clear old relcache files here after creating
6559  * symlinks.
6560  */
6562 
6563  /*
6564  * If the location of the checkpoint record is not on the expected
6565  * timeline in the history of the requested timeline, we cannot proceed:
6566  * the backup is not part of the history of the requested timeline.
6567  */
6568  Assert(expectedTLEs); /* was initialized by reading checkpoint
6569  * record */
6570  if (tliOfPointInHistory(checkPointLoc, expectedTLEs) !=
6571  checkPoint.ThisTimeLineID)
6572  {
6573  XLogRecPtr switchpoint;
6574 
6575  /*
6576  * tliSwitchPoint will throw an error if the checkpoint's timeline is
6577  * not in expectedTLEs at all.
6578  */
6580  ereport(FATAL,
6581  (errmsg("requested timeline %u is not a child of this server's history",
6583  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.",
6584  (uint32) (ControlFile->checkPoint >> 32),
6587  (uint32) (switchpoint >> 32),
6588  (uint32) switchpoint)));
6589  }
6590 
6591  /*
6592  * The min recovery point should be part of the requested timeline's
6593  * history, too.
6594  */
6598  ereport(FATAL,
6599  (errmsg("requested timeline %u does not contain minimum recovery point %X/%X on timeline %u",
6601  (uint32) (ControlFile->minRecoveryPoint >> 32),
6604 
6605  LastRec = RecPtr = checkPointLoc;
6606 
6607  ereport(DEBUG1,
6608  (errmsg_internal("redo record is at %X/%X; shutdown %s",
6609  (uint32) (checkPoint.redo >> 32), (uint32) checkPoint.redo,
6610  wasShutdown ? "TRUE" : "FALSE")));
6611  ereport(DEBUG1,
6612  (errmsg_internal("next transaction ID: %u:%u; next OID: %u",
6613  checkPoint.nextXidEpoch, checkPoint.nextXid,
6614  checkPoint.nextOid)));
6615  ereport(DEBUG1,
6616  (errmsg_internal("next MultiXactId: %u; next MultiXactOffset: %u",
6617  checkPoint.nextMulti, checkPoint.nextMultiOffset)));
6618  ereport(DEBUG1,
6619  (errmsg_internal("oldest unfrozen transaction ID: %u, in database %u",
6620  checkPoint.oldestXid, checkPoint.oldestXidDB)));
6621  ereport(DEBUG1,
6622  (errmsg_internal("oldest MultiXactId: %u, in database %u",
6623  checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
6624  ereport(DEBUG1,
6625  (errmsg_internal("commit timestamp Xid oldest/newest: %u/%u",
6626  checkPoint.oldestCommitTsXid,
6627  checkPoint.newestCommitTsXid)));
6628  if (!TransactionIdIsNormal(checkPoint.nextXid))
6629  ereport(PANIC,
6630  (errmsg("invalid next transaction ID")));
6631 
6632  /* initialize shared memory variables from the checkpoint record */
6633  ShmemVariableCache->nextXid = checkPoint.nextXid;
6634  ShmemVariableCache->nextOid = checkPoint.nextOid;
6636  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
6637  AdvanceOldestClogXid(checkPoint.oldestXid);
6638  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
6639  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
6641  checkPoint.newestCommitTsXid);
6642  XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
6643  XLogCtl->ckptXid = checkPoint.nextXid;
6644 
6645  /*
6646  * Initialize replication slots, before there's a chance to remove
6647  * required resources.
6648  */
6650 
6651  /*
6652  * Startup logical state, needs to be setup now so we have proper data
6653  * during crash recovery.
6654  */
6656 
6657  /*
6658  * Startup MultiXact. We need to do this early to be able to replay
6659  * truncations.
6660  */
6661  StartupMultiXact();
6662 
6663  /*
6664  * Ditto commit timestamps. In a standby, we do it if setting is enabled
6665  * in ControlFile; in a master we base the decision on the GUC itself.
6666  */
6669  StartupCommitTs();
6670 
6671  /*
6672  * Recover knowledge about replay progress of known replication partners.
6673  */
6675 
6676  /*
6677  * Initialize unlogged LSN. On a clean shutdown, it's restored from the
6678  * control file. On recovery, all unlogged relations are blown away, so
6679  * the unlogged LSN counter can be reset too.
6680  */
6683  else
6684  XLogCtl->unloggedLSN = 1;
6685 
6686  /*
6687  * We must replay WAL entries using the same TimeLineID they were created
6688  * under, so temporarily adopt the TLI indicated by the checkpoint (see
6689  * also xlog_redo()).
6690  */
6691  ThisTimeLineID = checkPoint.ThisTimeLineID;
6692 
6693  /*
6694  * Copy any missing timeline history files between 'now' and the recovery
6695  * target timeline from archive to pg_wal. While we don't need those files
6696  * ourselves - the history file of the recovery target timeline covers all
6697  * the previous timelines in the history too - a cascading standby server
6698  * might be interested in them. Or, if you archive the WAL from this
6699  * server to a different archive than the master, it'd be good for all the
6700  * history files to get archived there after failover, so that you can use
6701  * one of the old timelines as a PITR target. Timeline history files are
6702  * small, so it's better to copy them unnecessarily than not copy them and
6703  * regret later.
6704  */
6706 
6707  /*
6708  * Before running in recovery, scan pg_twophase and fill in its status to
6709  * be able to work on entries generated by redo. Doing a scan before
6710  * taking any recovery action has the merit to discard any 2PC files that
6711  * are newer than the first record to replay, saving from any conflicts at
6712  * replay. This avoids as well any subsequent scans when doing recovery
6713  * of the on-disk two-phase data.
6714  */
6716 
6717  lastFullPageWrites = checkPoint.fullPageWrites;
6718 
6721 
6722  if (RecPtr < checkPoint.redo)
6723  ereport(PANIC,
6724  (errmsg("invalid redo in checkpoint record")));
6725 
6726  /*
6727  * Check whether we need to force recovery from WAL. If it appears to
6728  * have been a clean shutdown and we did not have a recovery.conf file,
6729  * then assume no recovery needed.
6730  */
6731  if (checkPoint.redo < RecPtr)
6732  {
6733  if (wasShutdown)
6734  ereport(PANIC,
6735  (errmsg("invalid redo record in shutdown checkpoint")));
6736  InRecovery = true;
6737  }
6738  else if (ControlFile->state != DB_SHUTDOWNED)
6739  InRecovery = true;
6740  else if (ArchiveRecoveryRequested)
6741  {
6742  /* force recovery due to presence of recovery.conf */
6743  InRecovery = true;
6744  }
6745 
6746  /* REDO */
6747  if (InRecovery)
6748  {
6749  int rmid;
6750 
6751  /*
6752  * Update pg_control to show that we are recovering and to show the
6753  * selected checkpoint as the place we are starting from. We also mark
6754  * pg_control with any minimum recovery stop point obtained from a
6755  * backup history file.
6756  */
6757  dbstate_at_startup = ControlFile->state;
6758  if (InArchiveRecovery)
6760  else
6761  {
6762  ereport(LOG,
6763  (errmsg("database system was not properly shut down; "
6764  "automatic recovery in progress")));
6766  ereport(LOG,
6767  (errmsg("crash recovery starts in timeline %u "
6768  "and has target timeline %u",
6770  recoveryTargetTLI)));
6772  }
6774  ControlFile->checkPoint = checkPointLoc;
6775  ControlFile->checkPointCopy = checkPoint;
6776  if (InArchiveRecovery)
6777  {
6778  /* initialize minRecoveryPoint if not set yet */
6779  if (ControlFile->minRecoveryPoint < checkPoint.redo)
6780  {
6781  ControlFile->minRecoveryPoint = checkPoint.redo;
6783  }
6784  }
6785 
6786  /*
6787  * Set backupStartPoint if we're starting recovery from a base backup.
6788  *
6789  * Also set backupEndPoint and use minRecoveryPoint as the backup end
6790  * location if we're starting recovery from a base backup which was
6791  * taken from a standby. In this case, the database system status in
6792  * pg_control must indicate that the database was already in recovery.
6793  * Usually that will be DB_IN_ARCHIVE_RECOVERY but also can be
6794  * DB_SHUTDOWNED_IN_RECOVERY if recovery previously was interrupted
6795  * before reaching this point; e.g. because restore_command or
6796  * primary_conninfo were faulty.
6797  *
6798  * Any other state indicates that the backup somehow became corrupted
6799  * and we can't sensibly continue with recovery.
6800  */
6801  if (haveBackupLabel)
6802  {
6803  ControlFile->backupStartPoint = checkPoint.redo;
6804  ControlFile->backupEndRequired = backupEndRequired;
6805 
6806  if (backupFromStandby)
6807  {
6808  if (dbstate_at_startup != DB_IN_ARCHIVE_RECOVERY &&
6809  dbstate_at_startup != DB_SHUTDOWNED_IN_RECOVERY)
6810  ereport(