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

Referenced by CancelBackup(), and StartupXLOG().

#define CHECKPOINT_CAUSE_TIME   0x0080 /* Elapsed time */

Definition at line 187 of file xlog.h.

Referenced by CheckpointerMain(), and LogCheckpointStart().

#define CHECKPOINT_CAUSE_XLOG   0x0040 /* XLOG consumption */

Definition at line 186 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 181 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 325 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 sigusr1_handler().

#define XLogLogicalInfoActive ( )    (wal_level >= WAL_LEVEL_LOGICAL)

Definition at line 162 of file xlog.h.

Referenced by AssignTransactionId(), RecoverPreparedTransactions(), 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 304 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 2241 of file xlog.c.

References CalculateCheckpointSegments(), CheckPointCompletionTarget, and newval.

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

Definition at line 2234 of file xlog.c.

References CalculateCheckpointSegments(), max_wal_size_mb, and newval.

2235 {
2238 }
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2211
int max_wal_size_mb
Definition: xlog.c:89
#define newval
void BootStrapXLOG ( void  )

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

4948 {
4949  CheckPoint checkPoint;
4950  char *buffer;
4951  XLogPageHeader page;
4952  XLogLongPageHeader longpage;
4953  XLogRecord *record;
4954  char *recptr;
4955  bool use_existent;
4956  uint64 sysidentifier;
4957  char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
4958  struct timeval tv;
4959  pg_crc32c crc;
4960 
4961  /*
4962  * Select a hopefully-unique system identifier code for this installation.
4963  * We use the result of gettimeofday(), including the fractional seconds
4964  * field, as being about as unique as we can easily get. (Think not to
4965  * use random(), since it hasn't been seeded and there's no portable way
4966  * to seed it other than the system clock value...) The upper half of the
4967  * uint64 value is just the tv_sec part, while the lower half contains the
4968  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
4969  * PID for a little extra uniqueness. A person knowing this encoding can
4970  * determine the initialization time of the installation, which could
4971  * perhaps be useful sometimes.
4972  */
4973  gettimeofday(&tv, NULL);
4974  sysidentifier = ((uint64) tv.tv_sec) << 32;
4975  sysidentifier |= ((uint64) tv.tv_usec) << 12;
4976  sysidentifier |= getpid() & 0xFFF;
4977 
4978  /*
4979  * Generate a random nonce. This is used for authentication requests
4980  * that will fail because the user does not exist. The nonce is used to
4981  * create a genuine-looking password challenge for the non-existent user,
4982  * in lieu of an actual stored password.
4983  */
4984  if (!pg_backend_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
4985  ereport(PANIC,
4986  (errcode(ERRCODE_INTERNAL_ERROR),
4987  errmsg("could not generate secret authorization token")));
4988 
4989  /* First timeline ID is always 1 */
4990  ThisTimeLineID = 1;
4991 
4992  /* page buffer must be aligned suitably for O_DIRECT */
4993  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
4994  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
4995  memset(page, 0, XLOG_BLCKSZ);
4996 
4997  /*
4998  * Set up information for the initial checkpoint record
4999  *
5000  * The initial checkpoint record is written to the beginning of the WAL
5001  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
5002  * used, so that we can use 0/0 to mean "before any valid WAL segment".
5003  */
5004  checkPoint.redo = XLogSegSize + SizeOfXLogLongPHD;
5005  checkPoint.ThisTimeLineID = ThisTimeLineID;
5006  checkPoint.PrevTimeLineID = ThisTimeLineID;
5007  checkPoint.fullPageWrites = fullPageWrites;
5008  checkPoint.nextXidEpoch = 0;
5009  checkPoint.nextXid = FirstNormalTransactionId;
5010  checkPoint.nextOid = FirstBootstrapObjectId;
5011  checkPoint.nextMulti = FirstMultiXactId;
5012  checkPoint.nextMultiOffset = 0;
5013  checkPoint.oldestXid = FirstNormalTransactionId;
5014  checkPoint.oldestXidDB = TemplateDbOid;
5015  checkPoint.oldestMulti = FirstMultiXactId;
5016  checkPoint.oldestMultiDB = TemplateDbOid;
5019  checkPoint.time = (pg_time_t) time(NULL);
5021 
5022  ShmemVariableCache->nextXid = checkPoint.nextXid;
5023  ShmemVariableCache->nextOid = checkPoint.nextOid;
5025  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5026  AdvanceOldestClogXid(checkPoint.oldestXid);
5027  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5028  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5030 
5031  /* Set up the XLOG page header */
5032  page->xlp_magic = XLOG_PAGE_MAGIC;
5033  page->xlp_info = XLP_LONG_HEADER;
5034  page->xlp_tli = ThisTimeLineID;
5035  page->xlp_pageaddr = XLogSegSize;
5036  longpage = (XLogLongPageHeader) page;
5037  longpage->xlp_sysid = sysidentifier;
5038  longpage->xlp_seg_size = XLogSegSize;
5039  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5040 
5041  /* Insert the initial checkpoint record */
5042  recptr = ((char *) page + SizeOfXLogLongPHD);
5043  record = (XLogRecord *) recptr;
5044  record->xl_prev = 0;
5045  record->xl_xid = InvalidTransactionId;
5046  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5048  record->xl_rmid = RM_XLOG_ID;
5049  recptr += SizeOfXLogRecord;
5050  /* fill the XLogRecordDataHeaderShort struct */
5051  *(recptr++) = (char) XLR_BLOCK_ID_DATA_SHORT;
5052  *(recptr++) = sizeof(checkPoint);
5053  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5054  recptr += sizeof(checkPoint);
5055  Assert(recptr - (char *) record == record->xl_tot_len);
5056 
5057  INIT_CRC32C(crc);
5058  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5059  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5060  FIN_CRC32C(crc);
5061  record->xl_crc = crc;
5062 
5063  /* Create first XLOG segment file */
5064  use_existent = false;
5065  openLogFile = XLogFileInit(1, &use_existent, false);
5066 
5067  /* Write the first page with the initial record */
5068  errno = 0;
5070  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5071  {
5072  /* if write didn't set errno, assume problem is no disk space */
5073  if (errno == 0)
5074  errno = ENOSPC;
5075  ereport(PANIC,
5077  errmsg("could not write bootstrap transaction log file: %m")));
5078  }
5080 
5082  if (pg_fsync(openLogFile) != 0)
5083  ereport(PANIC,
5085  errmsg("could not fsync bootstrap transaction log file: %m")));
5087 
5088  if (close(openLogFile))
5089  ereport(PANIC,
5091  errmsg("could not close bootstrap transaction log file: %m")));
5092 
5093  openLogFile = -1;
5094 
5095  /* Now create pg_control */
5096 
5097  memset(ControlFile, 0, sizeof(ControlFileData));
5098  /* Initialize pg_control status fields */
5099  ControlFile->system_identifier = sysidentifier;
5100  memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
5102  ControlFile->time = checkPoint.time;
5103  ControlFile->checkPoint = checkPoint.redo;
5104  ControlFile->checkPointCopy = checkPoint;
5105  ControlFile->unloggedLSN = 1;
5106 
5107  /* Set important parameter values for use when replaying WAL */
5116 
5117  /* some additional ControlFile fields are set in WriteControlFile() */
5118 
5119  WriteControlFile();
5120 
5121  /* Bootstrap the commit log, too */
5122  BootStrapCLOG();
5126 
5127  pfree(buffer);
5128 }
static void WriteControlFile(void)
Definition: xlog.c:4378
#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:185
int gettimeofday(struct timeval *tp, struct timezone *tzp)
Definition: gettimeofday.c:105
int max_prepared_xacts
Definition: pg_control.h:184
int64 pg_time_t
Definition: pgtime.h:23
pg_time_t time
Definition: pg_control.h:131
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:200
int max_worker_processes
Definition: pg_control.h:183
uint32 pg_crc32c
Definition: pg_crc32c.h:38
TransactionId oldestActiveXid
Definition: pg_control.h:62
int wal_level
Definition: xlog.c:104
int XLogFileInit(XLogSegNo logsegno, bool *use_existent, bool use_lock)
Definition: xlog.c:3154
void BootStrapMultiXact(void)
Definition: multixact.c:1866
MultiXactId oldestMulti
Definition: pg_control.h:48
TimeLineID PrevTimeLineID
Definition: pg_control.h:38
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:135
TransactionId oldestXid
Definition: pg_control.h:46
TransactionId nextXid
Definition: pg_control.h:42
pg_time_t time
Definition: pg_control.h:50
#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:23
bool fullPageWrites
Definition: xlog.c:97
void BootStrapSUBTRANS(void)
Definition: subtrans.c:199
MultiXactOffset nextMultiOffset
Definition: pg_control.h:45
void AdvanceOldestClogXid(TransactionId oldest_datfrozenxid)
Definition: varsup.c:271
TransactionId oldestCommitTsXid
Definition: pg_control.h:51
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:109
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:41
bool track_commit_timestamp
Definition: commit_ts.c:103
#define TemplateDbOid
Definition: pg_database.h:80
uint32 data_checksum_version
Definition: pg_control.h:225
bool pg_backend_random(char *dst, int len)
#define XLOG_CHECKPOINT_SHUTDOWN
Definition: pg_control.h:66
XLogRecPtr unloggedLSN
Definition: pg_control.h:137
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:1232
#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:53
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:232
int MaxConnections
Definition: globals.c:123
Oid oldestMultiDB
Definition: pg_control.h:49
static int openLogFile
Definition: xlog.c:772
static ControlFileData * ControlFile
Definition: xlog.c:715
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
Definition: multixact.c:2194
TimeLineID ThisTimeLineID
Definition: xlog.c:179
Oid nextOid
Definition: pg_control.h:43
#define TYPEALIGN(ALIGNVAL, LEN)
Definition: c.h:581
bool fullPageWrites
Definition: pg_control.h:40
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:186
#define Assert(condition)
Definition: c.h:675
#define XLP_LONG_HEADER
Definition: xlog_internal.h:79
Oid oldestXidDB
Definition: pg_control.h:47
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1208
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:44
pg_crc32c xl_crc
Definition: xlogrecord.h:49
#define XLR_BLOCK_ID_DATA_SHORT
Definition: xlogrecord.h:223
TransactionId xl_xid
Definition: xlogrecord.h:44
TimeLineID ThisTimeLineID
Definition: pg_control.h:37
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
int max_worker_processes
Definition: globals.c:124
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:132
XLogRecPtr redo
Definition: pg_control.h:35
#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 12069 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, and PROMOTE_SIGNAL_FILE.

Referenced by sigusr1_handler().

12070 {
12071  struct stat stat_buf;
12072 
12073  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0 ||
12075  return true;
12076 
12077  return false;
12078 }
#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 3766 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().

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

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

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

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

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

Definition at line 4711 of file xlog.c.

References Assert, ControlFileData::data_checksum_version, and NULL.

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

4712 {
4713  Assert(ControlFile != NULL);
4714  return (ControlFile->data_checksum_version > 0);
4715 }
uint32 data_checksum_version
Definition: pg_control.h:225
static ControlFileData * ControlFile
Definition: xlog.c:715
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void do_pg_abort_backup ( void  )

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

11058 {
11062 
11065  {
11066  XLogCtl->Insert.forcePageWrites = false;
11067  }
11069 }
static void WALInsertLockRelease(void)
Definition: xlog.c:1646
XLogCtlInsert Insert
Definition: xlog.c:576
bool forcePageWrites
Definition: xlog.c:549
int nonExclusiveBackups
Definition: xlog.c:562
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:561
#define Assert(condition)
Definition: c.h:675
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1617
static XLogCtlData * XLogCtl
Definition: xlog.c:707
XLogRecPtr do_pg_start_backup ( const char *  backupidstr,
bool  fast,
TimeLineID starttli_p,
StringInfo  labelfile,
DIR tblspcdir,
List **  tablespaces,
StringInfo  tblspcmapfile,
bool  infotbssize,
bool  needtblspcmapfile 
)

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

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

Definition at line 10674 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, XLogBeginInsert(), XLogFileName, XLogInsert(), XLogIsNeeded, XLogRegisterData(), and XLogSegSize.

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

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

Definition at line 10655 of file xlog.c.

References sessionBackupState.

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

10656 {
10657  return sessionBackupState;
10658 }
static SessionBackupState sessionBackupState
Definition: xlog.c:510
TimestampTz GetCurrentChunkReplayStartTime ( void  )

Definition at line 6092 of file xlog.c.

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

Referenced by GetReplicationApplyDelay().

6093 {
6094  TimestampTz xtime;
6095 
6097  xtime = XLogCtl->currentChunkStartTime;
6099 
6100  return xtime;
6101 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
TimestampTz currentChunkStartTime
Definition: xlog.c:694
XLogRecPtr GetFakeLSNForUnloggedRel ( void  )

Definition at line 4727 of file xlog.c.

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

Referenced by gistGetFakeLSN().

4728 {
4729  XLogRecPtr nextUnloggedLSN;
4730 
4731  /* increment the unloggedLSN counter, need SpinLock */
4733  nextUnloggedLSN = XLogCtl->unloggedLSN++;
4735 
4736  return nextUnloggedLSN;
4737 }
XLogRecPtr unloggedLSN
Definition: xlog.c:590
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:707
slock_t ulsn_lck
Definition: xlog.c:591
XLogRecPtr GetFlushRecPtr ( void  )

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

8224 {
8228 
8229  return LogwrtResult.Flush;
8230 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:749
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:601
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
XLogRecPtr Flush
Definition: xlog.c:424
void GetFullPageWriteInfo ( XLogRecPtr RedoRecPtr_p,
bool doPageWrites_p 
)

Definition at line 8192 of file xlog.c.

References doPageWrites, and RedoRecPtr.

Referenced by XLogCheckBufferNeedsBackup(), and XLogInsert().

8193 {
8194  *RedoRecPtr_p = RedoRecPtr;
8195  *doPageWrites_p = doPageWrites;
8196 }
static bool doPageWrites
Definition: xlog.c:357
static XLogRecPtr RedoRecPtr
Definition: xlog.c:350
XLogRecPtr GetInsertRecPtr ( void  )

Definition at line 8207 of file xlog.c.

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

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

8208 {
8209  XLogRecPtr recptr;
8210 
8212  recptr = XLogCtl->LogwrtRqst.Write;
8214 
8215  return recptr;
8216 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr Write
Definition: xlog.c:417
XLogwrtRqst LogwrtRqst
Definition: xlog.c:579
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:707
XLogRecPtr GetLastImportantRecPtr ( void  )

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

8242 {
8244  int i;
8245 
8246  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
8247  {
8248  XLogRecPtr last_important;
8249 
8250  /*
8251  * Need to take a lock to prevent torn reads of the LSN, which are
8252  * possible on some of the supported platforms. WAL insert locks only
8253  * support exclusive mode, so we have to use that.
8254  */
8256  last_important = WALInsertLocks[i].l.lastImportantAt;
8257  LWLockRelease(&WALInsertLocks[i].l.lock);
8258 
8259  if (res < last_important)
8260  res = last_important;
8261  }
8262 
8263  return res;
8264 }
#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:710
TimestampTz GetLatestXTime ( void  )

Definition at line 6062 of file xlog.c.

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

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

6063 {
6064  TimestampTz xtime;
6065 
6067  xtime = XLogCtl->recoveryLastXTime;
6069 
6070  return xtime;
6071 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz recoveryLastXTime
Definition: xlog.c:688
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
char* GetMockAuthenticationNonce ( void  )

Definition at line 4701 of file xlog.c.

References Assert, ControlFileData::mock_authentication_nonce, and NULL.

Referenced by scram_MockSalt().

4702 {
4703  Assert(ControlFile != NULL);
4705 }
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
Definition: pg_control.h:232
static ControlFileData * ControlFile
Definition: xlog.c:715
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void GetNextXidAndEpoch ( TransactionId xid,
uint32 epoch 
)

Definition at line 8292 of file xlog.c.

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

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

8293 {
8294  uint32 ckptXidEpoch;
8295  TransactionId ckptXid;
8296  TransactionId nextXid;
8297 
8298  /* Must read checkpoint info first, else have race condition */
8300  ckptXidEpoch = XLogCtl->ckptXidEpoch;
8301  ckptXid = XLogCtl->ckptXid;
8303 
8304  /* Now fetch current nextXid */
8305  nextXid = ReadNewTransactionId();
8306 
8307  /*
8308  * nextXid is certainly logically later than ckptXid. So if it's
8309  * numerically less, it must have wrapped into the next epoch.
8310  */
8311  if (nextXid < ckptXid)
8312  ckptXidEpoch++;
8313 
8314  *xid = nextXid;
8315  *epoch = ckptXidEpoch;
8316 }
TransactionId ckptXid
Definition: xlog.c:582
uint32 TransactionId
Definition: c.h:397
slock_t info_lck
Definition: xlog.c:704
uint32 ckptXidEpoch
Definition: xlog.c:581
#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:707
static const unsigned __int64 epoch
Definition: gettimeofday.c:34
XLogRecPtr GetRedoRecPtr ( void  )

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

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

Definition at line 4691 of file xlog.c.

References Assert, NULL, and ControlFileData::system_identifier.

Referenced by IdentifySystem(), and WalReceiverMain().

4692 {
4693  Assert(ControlFile != NULL);
4695 }
uint64 system_identifier
Definition: pg_control.h:109
static ControlFileData * ControlFile
Definition: xlog.c:715
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
XLogRecPtr GetXLogInsertRecPtr ( void  )

Definition at line 11096 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_location(), and ReplicationSlotReserveWal().

11097 {
11099  uint64 current_bytepos;
11100 
11101  SpinLockAcquire(&Insert->insertpos_lck);
11102  current_bytepos = Insert->CurrBytePos;
11103  SpinLockRelease(&Insert->insertpos_lck);
11104 
11105  return XLogBytePosToRecPtr(current_bytepos);
11106 }
slock_t insertpos_lck
Definition: xlog.c:517
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:1915
XLogCtlInsert Insert
Definition: xlog.c:576
#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:707
void GetXLogReceiptTime ( TimestampTz rtime,
bool fromStream 
)

Definition at line 6108 of file xlog.c.

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

Referenced by GetStandbyLimitTime().

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

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

11078 {
11079  XLogRecPtr recptr;
11080  TimeLineID tli;
11081 
11083  recptr = XLogCtl->lastReplayedEndRecPtr;
11084  tli = XLogCtl->lastReplayedTLI;
11086 
11087  if (replayTLI)
11088  *replayTLI = tli;
11089  return recptr;
11090 }
uint32 TimeLineID
Definition: xlogdefs.h:45
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:707
TimeLineID lastReplayedTLI
Definition: xlog.c:684
XLogRecPtr lastReplayedEndRecPtr
Definition: xlog.c:683
XLogRecPtr GetXLogWriteRecPtr ( void  )

Definition at line 11112 of file xlog.c.

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

Referenced by pg_attribute_noreturn(), and pg_current_wal_location().

11113 {
11117 
11118  return LogwrtResult.Write;
11119 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:749
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:601
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
XLogRecPtr Write
Definition: xlog.c:423
bool HotStandbyActive ( void  )

Definition at line 7930 of file xlog.c.

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

Referenced by XLogWalRcvSendHSFeedback().

7931 {
7932  /*
7933  * We check shared state each time only until Hot Standby is active. We
7934  * can't de-activate Hot Standby, so there's no need to keep checking
7935  * after the shared variable has once been seen true.
7936  */
7938  return true;
7939  else
7940  {
7941  /* spinlock is essential on machines with weak memory ordering! */
7945 
7946  return LocalHotStandbyActive;
7947  }
7948 }
bool SharedHotStandbyActive
Definition: xlog.c:649
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
static bool LocalHotStandbyActive
Definition: xlog.c:221
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:707
bool HotStandbyActiveInReplay ( void  )

Definition at line 7955 of file xlog.c.

References AmStartupProcess, Assert, IsPostmasterEnvironment, and LocalHotStandbyActive.

Referenced by btree_xlog_vacuum().

7956 {
7958  return LocalHotStandbyActive;
7959 }
#define AmStartupProcess()
Definition: miscadmin.h:403
bool IsPostmasterEnvironment
Definition: globals.c:99
static bool LocalHotStandbyActive
Definition: xlog.c:221
#define Assert(condition)
Definition: c.h:675
void InitXLOGAccess ( void  )

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

8142 {
8144 
8145  /* ThisTimeLineID doesn't change so we need no lock to copy it */
8148 
8149  /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
8150  (void) GetRedoRecPtr();
8151  /* Also update our copy of doPageWrites. */
8152  doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);
8153 
8154  /* Also initialize the working areas for constructing WAL records */
8155  InitXLogInsert();
8156 }
void InitXLogInsert(void)
Definition: xloginsert.c:1029
TimeLineID ThisTimeLineID
Definition: xlog.c:630
XLogCtlInsert Insert
Definition: xlog.c:576
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:675
static XLogCtlData * XLogCtl
Definition: xlog.c:707
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:8164
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:365
void issue_xlog_fsync ( int  fd,
XLogSegNo  segno 
)

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

10078 {
10079  switch (sync_method)
10080  {
10081  case SYNC_METHOD_FSYNC:
10082  if (pg_fsync_no_writethrough(fd) != 0)
10083  ereport(PANIC,
10085  errmsg("could not fsync log file %s: %m",
10086  XLogFileNameP(ThisTimeLineID, segno))));
10087  break;
10088 #ifdef HAVE_FSYNC_WRITETHROUGH
10090  if (pg_fsync_writethrough(fd) != 0)
10091  ereport(PANIC,
10093  errmsg("could not fsync write-through log file %s: %m",
10094  XLogFileNameP(ThisTimeLineID, segno))));
10095  break;
10096 #endif
10097 #ifdef HAVE_FDATASYNC
10098  case SYNC_METHOD_FDATASYNC:
10099  if (pg_fdatasync(fd) != 0)
10100  ereport(PANIC,
10102  errmsg("could not fdatasync log file %s: %m",
10103  XLogFileNameP(ThisTimeLineID, segno))));
10104  break;
10105 #endif
10106  case SYNC_METHOD_OPEN:
10108  /* write synced it already */
10109  break;
10110  default:
10111  elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
10112  break;
10113  }
10114 }
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:10120
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 7874 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_location(), pg_current_wal_insert_location(), pg_current_wal_location(), 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(), standard_ProcessUtility(), StartLogicalReplication(), StartTransaction(), TransactionIdIsInProgress(), TruncateMultiXact(), UpdateFullPageWrites(), WalReceiverMain(), WalSndShutdown(), WalSndWaitForWal(), XLogBackgroundFlush(), XLogInsertAllowed(), XLogNeedsFlush(), and XLogSendPhysical().

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

Definition at line 5931 of file xlog.c.

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

Referenced by pg_is_wal_replay_paused(), and recoveryPausesHere().

5932 {
5933  bool recoveryPause;
5934 
5936  recoveryPause = XLogCtl->recoveryPause;
5938 
5939  return recoveryPause;
5940 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:696
static XLogCtlData * XLogCtl
Definition: xlog.c:707
void RemovePromoteSignalFiles ( void  )

Definition at line 12058 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, PROMOTE_SIGNAL_FILE, and unlink().

Referenced by PostmasterMain().

12059 {
12062 }
#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 5943 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().

5944 {
5946  XLogCtl->recoveryPause = recoveryPause;
5948 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:696
static XLogCtlData * XLogCtl
Definition: xlog.c:707
void SetWalWriterSleeping ( bool  sleeping)

Definition at line 12094 of file xlog.c.

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

Referenced by WalWriterMain().

12095 {
12097  XLogCtl->WalWriterSleeping = sleeping;
12099 }
slock_t info_lck
Definition: xlog.c:704
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool WalWriterSleeping
Definition: xlog.c:656
static XLogCtlData * XLogCtl
Definition: xlog.c:707
void ShutdownXLOG ( int  code,
Datum  arg 
)

Definition at line 8322 of file xlog.c.

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

Referenced by CheckpointerMain(), and InitPostgres().

8323 {
8324  /* Don't be chatty in standalone mode */
8326  (errmsg("shutting down")));
8327 
8328  if (RecoveryInProgress())
8330  else
8331  {
8332  /*
8333  * If archiving is enabled, rotate the last XLOG file so that all the
8334  * remaining records are archived (postmaster wakes up the archiver
8335  * process one more time at the end of shutdown). The checkpoint
8336  * record will go to the next XLOG file and won't be archived (yet).
8337  */
8339  RequestXLogSwitch(false);
8340 
8342  }
8343  ShutdownCLOG();
8344  ShutdownCommitTs();
8345  ShutdownSUBTRANS();
8347 }
bool IsPostmasterEnvironment
Definition: globals.c:99
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9396
void ShutdownSUBTRANS(void)
Definition: subtrans.c:270
void CreateCheckPoint(int flags)
Definition: xlog.c:8518
void ShutdownCLOG(void)
Definition: clog.c:575
bool CreateRestartPoint(int flags)
Definition: xlog.c:9065
#define XLogArchiveCommandSet()
Definition: xlog.h:139
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:7874
void ShutdownMultiXact(void)
Definition: multixact.c:2105
#define ereport(elevel, rest)
Definition: elog.h:122
#define NOTICE
Definition: elog.h:37
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:179
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:175
void StartupXLOG ( void  )

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

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