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
 

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 }
 

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)
 

Variables

int sync_method
 
PGDLLIMPORT TimeLineID ThisTimeLineID
 
bool InRecovery
 
HotStandbyState standbyState
 
XLogRecPtr ProcLastRecPtr
 
XLogRecPtr XactLastRecEnd
 
PGDLLIMPORT XLogRecPtr XactLastCommitEnd
 
bool reachedConsistency
 
int min_wal_size
 
int max_wal_size
 
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 303 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 306 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.

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 2231 of file xlog.c.

References CalculateCheckpointSegments(), CheckPointCompletionTarget, and newval.

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

Definition at line 2224 of file xlog.c.

References CalculateCheckpointSegments(), max_wal_size, and newval.

2225 {
2226  max_wal_size = newval;
2228 }
int max_wal_size
Definition: xlog.c:89
static void CalculateCheckpointSegments(void)
Definition: xlog.c:2201
#define newval
void BootStrapXLOG ( void  )

Definition at line 4940 of file xlog.c.

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

4941 {
4942  CheckPoint checkPoint;
4943  char *buffer;
4944  XLogPageHeader page;
4945  XLogLongPageHeader longpage;
4946  XLogRecord *record;
4947  char *recptr;
4948  bool use_existent;
4949  uint64 sysidentifier;
4950  char mock_auth_nonce[MOCK_AUTH_NONCE_LEN];
4951  struct timeval tv;
4952  pg_crc32c crc;
4953 
4954  /*
4955  * Select a hopefully-unique system identifier code for this installation.
4956  * We use the result of gettimeofday(), including the fractional seconds
4957  * field, as being about as unique as we can easily get. (Think not to
4958  * use random(), since it hasn't been seeded and there's no portable way
4959  * to seed it other than the system clock value...) The upper half of the
4960  * uint64 value is just the tv_sec part, while the lower half contains the
4961  * tv_usec part (which must fit in 20 bits), plus 12 bits from our current
4962  * PID for a little extra uniqueness. A person knowing this encoding can
4963  * determine the initialization time of the installation, which could
4964  * perhaps be useful sometimes.
4965  */
4966  gettimeofday(&tv, NULL);
4967  sysidentifier = ((uint64) tv.tv_sec) << 32;
4968  sysidentifier |= ((uint64) tv.tv_usec) << 12;
4969  sysidentifier |= getpid() & 0xFFF;
4970 
4971  /*
4972  * Generate a random nonce. This is used for authentication requests
4973  * that will fail because the user does not exist. The nonce is used to
4974  * create a genuine-looking password challenge for the non-existent user,
4975  * in lieu of an actual stored password.
4976  */
4977  if (!pg_backend_random(mock_auth_nonce, MOCK_AUTH_NONCE_LEN))
4978  ereport(PANIC,
4979  (errcode(ERRCODE_INTERNAL_ERROR),
4980  errmsg("could not generation secret authorization token")));
4981 
4982  /* First timeline ID is always 1 */
4983  ThisTimeLineID = 1;
4984 
4985  /* page buffer must be aligned suitably for O_DIRECT */
4986  buffer = (char *) palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
4987  page = (XLogPageHeader) TYPEALIGN(XLOG_BLCKSZ, buffer);
4988  memset(page, 0, XLOG_BLCKSZ);
4989 
4990  /*
4991  * Set up information for the initial checkpoint record
4992  *
4993  * The initial checkpoint record is written to the beginning of the WAL
4994  * segment with logid=0 logseg=1. The very first WAL segment, 0/0, is not
4995  * used, so that we can use 0/0 to mean "before any valid WAL segment".
4996  */
4997  checkPoint.redo = XLogSegSize + SizeOfXLogLongPHD;
4998  checkPoint.ThisTimeLineID = ThisTimeLineID;
4999  checkPoint.PrevTimeLineID = ThisTimeLineID;
5000  checkPoint.fullPageWrites = fullPageWrites;
5001  checkPoint.nextXidEpoch = 0;
5002  checkPoint.nextXid = FirstNormalTransactionId;
5003  checkPoint.nextOid = FirstBootstrapObjectId;
5004  checkPoint.nextMulti = FirstMultiXactId;
5005  checkPoint.nextMultiOffset = 0;
5006  checkPoint.oldestXid = FirstNormalTransactionId;
5007  checkPoint.oldestXidDB = TemplateDbOid;
5008  checkPoint.oldestMulti = FirstMultiXactId;
5009  checkPoint.oldestMultiDB = TemplateDbOid;
5012  checkPoint.time = (pg_time_t) time(NULL);
5014 
5015  ShmemVariableCache->nextXid = checkPoint.nextXid;
5016  ShmemVariableCache->nextOid = checkPoint.nextOid;
5018  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
5019  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
5020  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
5022 
5023  /* Set up the XLOG page header */
5024  page->xlp_magic = XLOG_PAGE_MAGIC;
5025  page->xlp_info = XLP_LONG_HEADER;
5026  page->xlp_tli = ThisTimeLineID;
5027  page->xlp_pageaddr = XLogSegSize;
5028  longpage = (XLogLongPageHeader) page;
5029  longpage->xlp_sysid = sysidentifier;
5030  longpage->xlp_seg_size = XLogSegSize;
5031  longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
5032 
5033  /* Insert the initial checkpoint record */
5034  recptr = ((char *) page + SizeOfXLogLongPHD);
5035  record = (XLogRecord *) recptr;
5036  record->xl_prev = 0;
5037  record->xl_xid = InvalidTransactionId;
5038  record->xl_tot_len = SizeOfXLogRecord + SizeOfXLogRecordDataHeaderShort + sizeof(checkPoint);
5040  record->xl_rmid = RM_XLOG_ID;
5041  recptr += SizeOfXLogRecord;
5042  /* fill the XLogRecordDataHeaderShort struct */
5043  *(recptr++) = XLR_BLOCK_ID_DATA_SHORT;
5044  *(recptr++) = sizeof(checkPoint);
5045  memcpy(recptr, &checkPoint, sizeof(checkPoint));
5046  recptr += sizeof(checkPoint);
5047  Assert(recptr - (char *) record == record->xl_tot_len);
5048 
5049  INIT_CRC32C(crc);
5050  COMP_CRC32C(crc, ((char *) record) + SizeOfXLogRecord, record->xl_tot_len - SizeOfXLogRecord);
5051  COMP_CRC32C(crc, (char *) record, offsetof(XLogRecord, xl_crc));
5052  FIN_CRC32C(crc);
5053  record->xl_crc = crc;
5054 
5055  /* Create first XLOG segment file */
5056  use_existent = false;
5057  openLogFile = XLogFileInit(1, &use_existent, false);
5058 
5059  /* Write the first page with the initial record */
5060  errno = 0;
5062  if (write(openLogFile, page, XLOG_BLCKSZ) != XLOG_BLCKSZ)
5063  {
5064  /* if write didn't set errno, assume problem is no disk space */
5065  if (errno == 0)
5066  errno = ENOSPC;
5067  ereport(PANIC,
5069  errmsg("could not write bootstrap transaction log file: %m")));
5070  }
5072 
5074  if (pg_fsync(openLogFile) != 0)
5075  ereport(PANIC,
5077  errmsg("could not fsync bootstrap transaction log file: %m")));
5079 
5080  if (close(openLogFile))
5081  ereport(PANIC,
5083  errmsg("could not close bootstrap transaction log file: %m")));
5084 
5085  openLogFile = -1;
5086 
5087  /* Now create pg_control */
5088 
5089  memset(ControlFile, 0, sizeof(ControlFileData));
5090  /* Initialize pg_control status fields */
5091  ControlFile->system_identifier = sysidentifier;
5092  memcpy(ControlFile->mock_authentication_nonce, mock_auth_nonce, MOCK_AUTH_NONCE_LEN);
5094  ControlFile->time = checkPoint.time;
5095  ControlFile->checkPoint = checkPoint.redo;
5096  ControlFile->checkPointCopy = checkPoint;
5097  ControlFile->unloggedLSN = 1;
5098 
5099  /* Set important parameter values for use when replaying WAL */
5108 
5109  /* some additional ControlFile fields are set in WriteControlFile() */
5110 
5111  WriteControlFile();
5112 
5113  /* Bootstrap the commit log, too */
5114  BootStrapCLOG();
5118 
5119  pfree(buffer);
5120 }
static void WriteControlFile(void)
Definition: xlog.c:4371
#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:837
uint32 oidCount
Definition: transam.h:112
#define write(a, b, c)
Definition: win32.h:19
#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:3144
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:48
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
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:98
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:1205
#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:762
static ControlFileData * ControlFile
Definition: xlog.c:709
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:463
#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:1181
void SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
Definition: varsup.c:267
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:17
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 12029 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, and PROMOTE_SIGNAL_FILE.

Referenced by sigusr1_handler().

12030 {
12031  struct stat stat_buf;
12032 
12033  if (stat(PROMOTE_SIGNAL_FILE, &stat_buf) == 0 ||
12035  return true;
12036 
12037  return false;
12038 }
#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 3756 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().

3757 {
3758  XLogSegNo lastRemovedSegNo;
3759 
3761  lastRemovedSegNo = XLogCtl->lastRemovedSegNo;
3763 
3764  if (segno <= lastRemovedSegNo)
3765  {
3766  char filename[MAXFNAMELEN];
3767 
3768  XLogFileName(filename, tli, segno);
3769  ereport(ERROR,
3771  errmsg("requested WAL segment %s has already been removed",
3772  filename)));
3773  }
3774 }
slock_t info_lck
Definition: xlog.c:698
#define XLogFileName(fname, tli, logSegNo)
XLogSegNo lastRemovedSegNo
Definition: xlog.c:580
#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:701
static char * filename
Definition: pg_dumpall.c:87
int errmsg(const char *fmt,...)
Definition: elog.c:797
void CreateCheckPoint ( int  flags)

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

8500 {
8501  bool shutdown;
8502  CheckPoint checkPoint;
8503  XLogRecPtr recptr;
8505  uint32 freespace;
8506  XLogRecPtr PriorRedoPtr;
8507  XLogRecPtr curInsert;
8508  XLogRecPtr last_important_lsn;
8509  VirtualTransactionId *vxids;
8510  int nvxids;
8511 
8512  /*
8513  * An end-of-recovery checkpoint is really a shutdown checkpoint, just
8514  * issued at a different time.
8515  */
8517  shutdown = true;
8518  else
8519  shutdown = false;
8520 
8521  /* sanity check */
8522  if (RecoveryInProgress() && (flags & CHECKPOINT_END_OF_RECOVERY) == 0)
8523  elog(ERROR, "can't create a checkpoint during recovery");
8524 
8525  /*
8526  * Initialize InitXLogInsert working areas before entering the critical
8527  * section. Normally, this is done by the first call to
8528  * RecoveryInProgress() or LocalSetXLogInsertAllowed(), but when creating
8529  * an end-of-recovery checkpoint, the LocalSetXLogInsertAllowed call is
8530  * done below in a critical section, and InitXLogInsert cannot be called
8531  * in a critical section.
8532  */
8533  InitXLogInsert();
8534 
8535  /*
8536  * Acquire CheckpointLock to ensure only one checkpoint happens at a time.
8537  * (This is just pro forma, since in the present system structure there is
8538  * only one process that is allowed to issue checkpoints at any given
8539  * time.)
8540  */
8541  LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
8542 
8543  /*
8544  * Prepare to accumulate statistics.
8545  *
8546  * Note: because it is possible for log_checkpoints to change while a
8547  * checkpoint proceeds, we always accumulate stats, even if
8548  * log_checkpoints is currently off.
8549  */
8550  MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
8552 
8553  /*
8554  * Use a critical section to force system panic if we have trouble.
8555  */
8557 
8558  if (shutdown)
8559  {
8560  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8562  ControlFile->time = (pg_time_t) time(NULL);
8564  LWLockRelease(ControlFileLock);
8565  }
8566 
8567  /*
8568  * Let smgr prepare for checkpoint; this has to happen before we determine
8569  * the REDO pointer. Note that smgr must not do anything that'd have to
8570  * be undone if we decide no checkpoint is needed.
8571  */
8572  smgrpreckpt();
8573 
8574  /* Begin filling in the checkpoint WAL record */
8575  MemSet(&checkPoint, 0, sizeof(checkPoint));
8576  checkPoint.time = (pg_time_t) time(NULL);
8577 
8578  /*
8579  * For Hot Standby, derive the oldestActiveXid before we fix the redo
8580  * pointer. This allows us to begin accumulating changes to assemble our
8581  * starting snapshot of locks and transactions.
8582  */
8583  if (!shutdown && XLogStandbyInfoActive())
8585  else
8587 
8588  /*
8589  * Get location of last important record before acquiring insert locks (as
8590  * GetLastImportantRecPtr() also locks WAL locks).
8591  */
8592  last_important_lsn = GetLastImportantRecPtr();
8593 
8594  /*
8595  * We must block concurrent insertions while examining insert state to
8596  * determine the checkpoint REDO pointer.
8597  */
8599  curInsert = XLogBytePosToRecPtr(Insert->CurrBytePos);
8600 
8601  /*
8602  * If this isn't a shutdown or forced checkpoint, and if there has been no
8603  * WAL activity requiring a checkpoint, skip it. The idea here is to
8604  * avoid inserting duplicate checkpoints when the system is idle.
8605  */
8606  if ((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
8607  CHECKPOINT_FORCE)) == 0)
8608  {
8609  if (last_important_lsn == ControlFile->checkPoint)
8610  {
8612  LWLockRelease(CheckpointLock);
8613  END_CRIT_SECTION();
8614  ereport(DEBUG1,
8615  (errmsg("checkpoint skipped due to an idle system")));
8616  return;
8617  }
8618  }
8619 
8620  /*
8621  * An end-of-recovery checkpoint is created before anyone is allowed to
8622  * write WAL. To allow us to write the checkpoint record, temporarily
8623  * enable XLogInsertAllowed. (This also ensures ThisTimeLineID is
8624  * initialized, which we need here and in AdvanceXLInsertBuffer.)
8625  */
8626  if (flags & CHECKPOINT_END_OF_RECOVERY)
8628 
8629  checkPoint.ThisTimeLineID = ThisTimeLineID;
8630  if (flags & CHECKPOINT_END_OF_RECOVERY)
8631  checkPoint.PrevTimeLineID = XLogCtl->PrevTimeLineID;
8632  else
8633  checkPoint.PrevTimeLineID = ThisTimeLineID;
8634 
8635  checkPoint.fullPageWrites = Insert->fullPageWrites;
8636 
8637  /*
8638  * Compute new REDO record ptr = location of next XLOG record.
8639  *
8640  * NB: this is NOT necessarily where the checkpoint record itself will be,
8641  * since other backends may insert more XLOG records while we're off doing
8642  * the buffer flush work. Those XLOG records are logically after the
8643  * checkpoint, even though physically before it. Got that?
8644  */
8645  freespace = INSERT_FREESPACE(curInsert);
8646  if (freespace == 0)
8647  {
8648  if (curInsert % XLogSegSize == 0)
8649  curInsert += SizeOfXLogLongPHD;
8650  else
8651  curInsert += SizeOfXLogShortPHD;
8652  }
8653  checkPoint.redo = curInsert;
8654 
8655  /*
8656  * Here we update the shared RedoRecPtr for future XLogInsert calls; this
8657  * must be done while holding all the insertion locks.
8658  *
8659  * Note: if we fail to complete the checkpoint, RedoRecPtr will be left
8660  * pointing past where it really needs to point. This is okay; the only
8661  * consequence is that XLogInsert might back up whole buffers that it
8662  * didn't really need to. We can't postpone advancing RedoRecPtr because
8663  * XLogInserts that happen while we are dumping buffers must assume that
8664  * their buffer changes are not included in the checkpoint.
8665  */
8666  RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
8667 
8668  /*
8669  * Now we can release the WAL insertion locks, allowing other xacts to
8670  * proceed while we are flushing disk buffers.
8671  */
8673 
8674  /* Update the info_lck-protected copy of RedoRecPtr as well */
8676  XLogCtl->RedoRecPtr = checkPoint.redo;
8678 
8679  /*
8680  * If enabled, log checkpoint start. We postpone this until now so as not
8681  * to log anything if we decided to skip the checkpoint.
8682  */
8683  if (log_checkpoints)
8684  LogCheckpointStart(flags, false);
8685 
8686  TRACE_POSTGRESQL_CHECKPOINT_START(flags);
8687 
8688  /*
8689  * Get the other info we need for the checkpoint record.
8690  */
8691  LWLockAcquire(XidGenLock, LW_SHARED);
8692  checkPoint.nextXid = ShmemVariableCache->nextXid;
8693  checkPoint.oldestXid = ShmemVariableCache->oldestXid;
8695  LWLockRelease(XidGenLock);
8696 
8697  LWLockAcquire(CommitTsLock, LW_SHARED);
8700  LWLockRelease(CommitTsLock);
8701 
8702  /* Increase XID epoch if we've wrapped around since last checkpoint */
8704  if (checkPoint.nextXid < ControlFile->checkPointCopy.nextXid)
8705  checkPoint.nextXidEpoch++;
8706 
8707  LWLockAcquire(OidGenLock, LW_SHARED);
8708  checkPoint.nextOid = ShmemVariableCache->nextOid;
8709  if (!shutdown)
8710  checkPoint.nextOid += ShmemVariableCache->oidCount;
8711  LWLockRelease(OidGenLock);
8712 
8713  MultiXactGetCheckptMulti(shutdown,
8714  &checkPoint.nextMulti,
8715  &checkPoint.nextMultiOffset,
8716  &checkPoint.oldestMulti,
8717  &checkPoint.oldestMultiDB);
8718 
8719  /*
8720  * Having constructed the checkpoint record, ensure all shmem disk buffers
8721  * and commit-log buffers are flushed to disk.
8722  *
8723  * This I/O could fail for various reasons. If so, we will fail to
8724  * complete the checkpoint, but there is no reason to force a system
8725  * panic. Accordingly, exit critical section while doing it.
8726  */
8727  END_CRIT_SECTION();
8728 
8729  /*
8730  * In some cases there are groups of actions that must all occur on one
8731  * side or the other of a checkpoint record. Before flushing the
8732  * checkpoint record we must explicitly wait for any backend currently
8733  * performing those groups of actions.
8734  *
8735  * One example is end of transaction, so we must wait for any transactions
8736  * that are currently in commit critical sections. If an xact inserted
8737  * its commit record into XLOG just before the REDO point, then a crash
8738  * restart from the REDO point would not replay that record, which means
8739  * that our flushing had better include the xact's update of pg_xact. So
8740  * we wait till he's out of his commit critical section before proceeding.
8741  * See notes in RecordTransactionCommit().
8742  *
8743  * Because we've already released the insertion locks, this test is a bit
8744  * fuzzy: it is possible that we will wait for xacts we didn't really need
8745  * to wait for. But the delay should be short and it seems better to make
8746  * checkpoint take a bit longer than to hold off insertions longer than
8747  * necessary. (In fact, the whole reason we have this issue is that xact.c
8748  * does commit record XLOG insertion and clog update as two separate steps
8749  * protected by different locks, but again that seems best on grounds of
8750  * minimizing lock contention.)
8751  *
8752  * A transaction that has not yet set delayChkpt when we look cannot be at
8753  * risk, since he's not inserted his commit record yet; and one that's
8754  * already cleared it is not at risk either, since he's done fixing clog
8755  * and we will correctly flush the update below. So we cannot miss any
8756  * xacts we need to wait for.
8757  */
8758  vxids = GetVirtualXIDsDelayingChkpt(&nvxids);
8759  if (nvxids > 0)
8760  {
8761  do
8762  {
8763  pg_usleep(10000L); /* wait for 10 msec */
8764  } while (HaveVirtualXIDsDelayingChkpt(vxids, nvxids));
8765  }
8766  pfree(vxids);
8767 
8768  CheckPointGuts(checkPoint.redo, flags);
8769 
8770  /*
8771  * Take a snapshot of running transactions and write this to WAL. This
8772  * allows us to reconstruct the state of running transactions during
8773  * archive recovery, if required. Skip, if this info disabled.
8774  *
8775  * If we are shutting down, or Startup process is completing crash
8776  * recovery we don't need to write running xact data.
8777  */
8778  if (!shutdown && XLogStandbyInfoActive())
8780 
8782 
8783  /*
8784  * Now insert the checkpoint record into XLOG.
8785  */
8786  XLogBeginInsert();
8787  XLogRegisterData((char *) (&checkPoint), sizeof(checkPoint));
8788  recptr = XLogInsert(RM_XLOG_ID,
8789  shutdown ? XLOG_CHECKPOINT_SHUTDOWN :
8791 
8792  XLogFlush(recptr);
8793 
8794  /*
8795  * We mustn't write any new WAL after a shutdown checkpoint, or it will be
8796  * overwritten at next startup. No-one should even try, this just allows
8797  * sanity-checking. In the case of an end-of-recovery checkpoint, we want
8798  * to just temporarily disable writing until the system has exited
8799  * recovery.
8800  */
8801  if (shutdown)
8802  {
8803  if (flags & CHECKPOINT_END_OF_RECOVERY)
8804  LocalXLogInsertAllowed = -1; /* return to "check" state */
8805  else
8806  LocalXLogInsertAllowed = 0; /* never again write WAL */
8807  }
8808 
8809  /*
8810  * We now have ProcLastRecPtr = start of actual checkpoint record, recptr
8811  * = end of actual checkpoint record.
8812  */
8813  if (shutdown && checkPoint.redo != ProcLastRecPtr)
8814  ereport(PANIC,
8815  (errmsg("concurrent transaction log activity while database system is shutting down")));
8816 
8817  /*
8818  * Remember the prior checkpoint's redo pointer, used later to determine
8819  * the point where the log can be truncated.
8820  */
8821  PriorRedoPtr = ControlFile->checkPointCopy.redo;
8822 
8823  /*
8824  * Update the control file.
8825  */
8826  LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
8827  if (shutdown)
8831  ControlFile->checkPointCopy = checkPoint;
8832  ControlFile->time = (pg_time_t) time(NULL);
8833  /* crash recovery should always recover to the end of WAL */
8836 
8837  /*
8838  * Persist unloggedLSN value. It's reset on crash recovery, so this goes
8839  * unused on non-shutdown checkpoints, but seems useful to store it always
8840  * for debugging purposes.
8841  */
8845 
8847  LWLockRelease(ControlFileLock);
8848 
8849  /* Update shared-memory copy of checkpoint XID/epoch */
8851  XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
8852  XLogCtl->ckptXid = checkPoint.nextXid;
8854 
8855  /*
8856  * We are now done with critical updates; no need for system panic if we
8857  * have trouble while fooling with old log segments.
8858  */
8859  END_CRIT_SECTION();
8860 
8861  /*
8862  * Let smgr do post-checkpoint cleanup (eg, deleting old files).
8863  */
8864  smgrpostckpt();
8865 
8866  /*
8867  * Delete old log files (those no longer needed even for previous
8868  * checkpoint or the standbys in XLOG streaming).
8869  */
8870  if (PriorRedoPtr != InvalidXLogRecPtr)
8871  {
8872  XLogSegNo _logSegNo;
8873 
8874  /* Update the average distance between checkpoints. */
8876 
8877  XLByteToSeg(PriorRedoPtr, _logSegNo);
8878  KeepLogSeg(recptr, &_logSegNo);
8879  _logSegNo--;
8880  RemoveOldXlogFiles(_logSegNo, PriorRedoPtr, recptr);
8881  }
8882 
8883  /*
8884  * Make more log segments if needed. (Do this after recycling old log
8885  * segments, since that may supply some of the needed files.)
8886  */
8887  if (!shutdown)
8888  PreallocXlogFiles(recptr);
8889 
8890  /*
8891  * Truncate pg_subtrans if possible. We can throw away all data before
8892  * the oldest XMIN of any running transaction. No future transaction will
8893  * attempt to reference any pg_subtrans entry older than that (see Asserts
8894  * in subtrans.c). During recovery, though, we mustn't do this because
8895  * StartupSUBTRANS hasn't been called yet.
8896  */
8897  if (!RecoveryInProgress())
8899 
8900  /* Real work is done, but log and update stats before releasing lock. */
8901  LogCheckpointEnd(false);
8902 
8903  TRACE_POSTGRESQL_CHECKPOINT_DONE(CheckpointStats.ckpt_bufs_written,
8904  NBuffers,
8908 
8909  LWLockRelease(CheckpointLock);
8910 }
XLogRecPtr GetLastImportantRecPtr(void)
Definition: xlog.c:8222
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
Definition: xlog.c:8437
#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:576
static void WALInsertLockRelease(void)
Definition: xlog.c:1636
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:1569
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:1905
XLogRecPtr unloggedLSN
Definition: xlog.c:584
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:698
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids)
Definition: procarray.c:2232
MultiXactId oldestMulti
Definition: pg_control.h:48
TimeLineID PrevTimeLineID
Definition: xlog.c:625
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:3821
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:8971
CheckPoint checkPointCopy
Definition: pg_control.h:135
XLogCtlInsert Insert
Definition: xlog.c:570
TransactionId oldestXid
Definition: pg_control.h:46
bool RecoveryInProgress(void)
Definition: xlog.c:7855
void TruncateSUBTRANS(TransactionId oldestXact)
Definition: subtrans.c:341
uint32 ckptXidEpoch
Definition: xlog.c:575
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:544
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2748
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:4635
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:8352
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:3730
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:520
unsigned int uint32
Definition: c.h:268
XLogRecPtr RedoRecPtr
Definition: xlog.c:574
int ckpt_segs_removed
Definition: xlog.h:208
#define CHECKPOINT_FORCE
Definition: xlog.h:180
#define INSERT_FREESPACE(endptr)
Definition: xlog.c:715
#define ereport(elevel, rest)
Definition: elog.h:122
TransactionId oldestCommitTsXid
Definition: transam.h:129
static void Insert(File file)
Definition: fd.c:1007
int ckpt_bufs_written
Definition: xlog.h:205
static void LocalSetXLogInsertAllowed(void)
Definition: xlog.c:7981
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:37
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
Definition: xlog.c:9295
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:709
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:1307
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:1607
static XLogCtlData * XLogCtl
Definition: xlog.c:701
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:585
TimeLineID ThisTimeLineID
Definition: pg_control.h:37
int errmsg(const char *fmt,...)
Definition: elog.c:797
TransactionId GetOldestActiveTransactionId(void)
Definition: procarray.c:2078
int NBuffers
Definition: globals.c:122
#define elog
Definition: elog.h:219
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids)
Definition: procarray.c:2277
void XLogBeginInsert(void)
Definition: xloginsert.c:120
XLogRecPtr RedoRecPtr
Definition: xlog.c:542
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:8334
#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 9041 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().

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

Definition at line 4704 of file xlog.c.

References Assert, ControlFileData::data_checksum_version, and NULL.

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

4705 {
4706  Assert(ControlFile != NULL);
4707  return (ControlFile->data_checksum_version > 0);
4708 }
uint32 data_checksum_version
Definition: pg_control.h:225
static ControlFileData * ControlFile
Definition: xlog.c:709
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void do_pg_abort_backup ( void  )

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

11018 {
11022 
11025  {
11026  XLogCtl->Insert.forcePageWrites = false;
11027  }
11029 }
static void WALInsertLockRelease(void)
Definition: xlog.c:1636
XLogCtlInsert Insert
Definition: xlog.c:570
bool forcePageWrites
Definition: xlog.c:543
int nonExclusiveBackups
Definition: xlog.c:556
ExclusiveBackupState exclusiveBackupState
Definition: xlog.c:555
#define Assert(condition)
Definition: c.h:675
static void WALInsertLockAcquireExclusive(void)
Definition: xlog.c:1607
static XLogCtlData * XLogCtl
Definition: xlog.c:701
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 10139 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(), 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().

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

References AllocateFile(), Assert, BACKUP_LABEL_FILE, backup_started_in_recovery, BackupHistoryFileName, BackupHistoryFilePath, BoolGetDatum, CHECK_FOR_INTERRUPTS, CleanupBackupHistory(), 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(), SpinLockAcquire, SpinLockRelease, TABLESPACE_MAP, ThisTimeLineID, unlink(), 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().

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

Definition at line 6084 of file xlog.c.

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

Referenced by GetReplicationApplyDelay().

6085 {
6086  TimestampTz xtime;
6087 
6089  xtime = XLogCtl->currentChunkStartTime;
6091 
6092  return xtime;
6093 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:698
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:701
TimestampTz currentChunkStartTime
Definition: xlog.c:688
XLogRecPtr GetFakeLSNForUnloggedRel ( void  )

Definition at line 4720 of file xlog.c.

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

Referenced by gistGetFakeLSN().

4721 {
4722  XLogRecPtr nextUnloggedLSN;
4723 
4724  /* increment the unloggedLSN counter, need SpinLock */
4726  nextUnloggedLSN = XLogCtl->unloggedLSN++;
4728 
4729  return nextUnloggedLSN;
4730 }
XLogRecPtr unloggedLSN
Definition: xlog.c:584
#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:701
slock_t ulsn_lck
Definition: xlog.c:585
XLogRecPtr GetFlushRecPtr ( void  )

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

8205 {
8209 
8210  return LogwrtResult.Flush;
8211 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:739
slock_t info_lck
Definition: xlog.c:698
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:595
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:701
XLogRecPtr Flush
Definition: xlog.c:424
void GetFullPageWriteInfo ( XLogRecPtr RedoRecPtr_p,
bool doPageWrites_p 
)

Definition at line 8173 of file xlog.c.

References doPageWrites, and RedoRecPtr.

Referenced by XLogCheckBufferNeedsBackup(), and XLogInsert().

8174 {
8175  *RedoRecPtr_p = RedoRecPtr;
8176  *doPageWrites_p = doPageWrites;
8177 }
static bool doPageWrites
Definition: xlog.c:357
static XLogRecPtr RedoRecPtr
Definition: xlog.c:350
XLogRecPtr GetInsertRecPtr ( void  )

Definition at line 8188 of file xlog.c.

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

Referenced by CheckpointerMain(), and IsCheckpointOnSchedule().

8189 {
8190  XLogRecPtr recptr;
8191 
8193  recptr = XLogCtl->LogwrtRqst.Write;
8195 
8196  return recptr;
8197 }
slock_t info_lck
Definition: xlog.c:698
#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:573
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:701
XLogRecPtr GetLastImportantRecPtr ( void  )

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

8223 {
8225  int i;
8226 
8227  for (i = 0; i < NUM_XLOGINSERT_LOCKS; i++)
8228  {
8229  XLogRecPtr last_important;
8230 
8231  /*
8232  * Need to take a lock to prevent torn reads of the LSN, which are
8233  * possible on some of the supported platforms. WAL insert locks only
8234  * support exclusive mode, so we have to use that.
8235  */
8237  last_important = WALInsertLocks[i].l.lastImportantAt;
8238  LWLockRelease(&WALInsertLocks[i].l.lock);
8239 
8240  if (res < last_important)
8241  res = last_important;
8242  }
8243 
8244  return res;
8245 }
#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:704
TimestampTz GetLatestXTime ( void  )

Definition at line 6054 of file xlog.c.

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

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

6055 {
6056  TimestampTz xtime;
6057 
6059  xtime = XLogCtl->recoveryLastXTime;
6061 
6062  return xtime;
6063 }
int64 TimestampTz
Definition: timestamp.h:39
slock_t info_lck
Definition: xlog.c:698
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz recoveryLastXTime
Definition: xlog.c:682
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:701
char* GetMockAuthenticationNonce ( void  )

Definition at line 4694 of file xlog.c.

References Assert, ControlFileData::mock_authentication_nonce, and NULL.

Referenced by scram_MockSalt().

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

Definition at line 8273 of file xlog.c.

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

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

8274 {
8275  uint32 ckptXidEpoch;
8276  TransactionId ckptXid;
8277  TransactionId nextXid;
8278 
8279  /* Must read checkpoint info first, else have race condition */
8281  ckptXidEpoch = XLogCtl->ckptXidEpoch;
8282  ckptXid = XLogCtl->ckptXid;
8284 
8285  /* Now fetch current nextXid */
8286  nextXid = ReadNewTransactionId();
8287 
8288  /*
8289  * nextXid is certainly logically later than ckptXid. So if it's
8290  * numerically less, it must have wrapped into the next epoch.
8291  */
8292  if (nextXid < ckptXid)
8293  ckptXidEpoch++;
8294 
8295  *xid = nextXid;
8296  *epoch = ckptXidEpoch;
8297 }
TransactionId ckptXid
Definition: xlog.c:576
uint32 TransactionId
Definition: c.h:397
slock_t info_lck
Definition: xlog.c:698
uint32 ckptXidEpoch
Definition: xlog.c:575
#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:701
static const unsigned __int64 epoch
Definition: gettimeofday.c:34
XLogRecPtr GetRedoRecPtr ( void  )

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

8146 {
8147  XLogRecPtr ptr;
8148 
8149  /*
8150  * The possibly not up-to-date copy in XlogCtl is enough. Even if we
8151  * grabbed a WAL insertion lock to read the master copy, someone might
8152  * update it just after we've released the lock.
8153  */
8155  ptr = XLogCtl->RedoRecPtr;
8157 
8158  if (RedoRecPtr < ptr)
8159  RedoRecPtr = ptr;
8160 
8161  return RedoRecPtr;
8162 }
slock_t info_lck
Definition: xlog.c:698
#define SpinLockAcquire(lock)
Definition: spin.h:62
static XLogRecPtr RedoRecPtr
Definition: xlog.c:350
XLogRecPtr RedoRecPtr
Definition: xlog.c:574
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
static XLogCtlData * XLogCtl
Definition: xlog.c:701
uint64 GetSystemIdentifier ( void  )

Definition at line 4684 of file xlog.c.

References Assert, NULL, and ControlFileData::system_identifier.

Referenced by IdentifySystem(), and WalReceiverMain().

4685 {
4686  Assert(ControlFile != NULL);
4688 }
uint64 system_identifier
Definition: pg_control.h:109
static ControlFileData * ControlFile
Definition: xlog.c:709
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
XLogRecPtr GetXLogInsertRecPtr ( void  )

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

11057 {
11059  uint64 current_bytepos;
11060 
11061  SpinLockAcquire(&Insert->insertpos_lck);
11062  current_bytepos = Insert->CurrBytePos;
11063  SpinLockRelease(&Insert->insertpos_lck);
11064 
11065  return XLogBytePosToRecPtr(current_bytepos);
11066 }
slock_t insertpos_lck
Definition: xlog.c:511
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
Definition: xlog.c:1905
XLogCtlInsert Insert
Definition: xlog.c:570
#define SpinLockAcquire(lock)
Definition: spin.h:62
uint64 CurrBytePos
Definition: xlog.c:520
static void Insert(File file)
Definition: fd.c:1007
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:701
void GetXLogReceiptTime ( TimestampTz rtime,
bool fromStream 
)

Definition at line 6100 of file xlog.c.

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

Referenced by GetStandbyLimitTime().

6101 {
6102  /*
6103  * This must be executed in the startup process, since we don't export the
6104  * relevant state to shared memory.
6105  */
6106  Assert(InRecovery);
6107 
6108  *rtime = XLogReceiptTime;
6109  *fromStream = (XLogReceiptSource == XLOG_FROM_STREAM);
6110 }
static XLogSource XLogReceiptSource
Definition: xlog.c:806
bool InRecovery
Definition: xlog.c:192
static TimestampTz XLogReceiptTime
Definition: xlog.c:805
#define Assert(condition)
Definition: c.h:675
XLogRecPtr GetXLogReplayRecPtr ( TimeLineID replayTLI)

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

11038 {
11039  XLogRecPtr recptr;
11040  TimeLineID tli;
11041 
11043  recptr = XLogCtl->lastReplayedEndRecPtr;
11044  tli = XLogCtl->lastReplayedTLI;
11046 
11047  if (replayTLI)
11048  *replayTLI = tli;
11049  return recptr;
11050 }
uint32 TimeLineID
Definition: xlogdefs.h:45
slock_t info_lck
Definition: xlog.c:698
#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:701
TimeLineID lastReplayedTLI
Definition: xlog.c:678
XLogRecPtr lastReplayedEndRecPtr
Definition: xlog.c:677
XLogRecPtr GetXLogWriteRecPtr ( void  )

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

11073 {
11077 
11078  return LogwrtResult.Write;
11079 }
static XLogwrtResult LogwrtResult
Definition: xlog.c:739
slock_t info_lck
Definition: xlog.c:698
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogwrtResult LogwrtResult
Definition: xlog.c:595
#define SpinLockRelease(lock)
Definition: spin.h:64
static XLogCtlData * XLogCtl
Definition: xlog.c:701
XLogRecPtr Write
Definition: xlog.c:423
bool HotStandbyActive ( void  )

Definition at line 7911 of file xlog.c.

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

Referenced by XLogWalRcvSendHSFeedback().

7912 {
7913  /*
7914  * We check shared state each time only until Hot Standby is active. We
7915  * can't de-activate Hot Standby, so there's no need to keep checking
7916  * after the shared variable has once been seen true.
7917  */
7919  return true;
7920  else
7921  {
7922  /* spinlock is essential on machines with weak memory ordering! */
7926 
7927  return LocalHotStandbyActive;
7928  }
7929 }
bool SharedHotStandbyActive
Definition: xlog.c:643
slock_t info_lck
Definition: xlog.c:698
#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:701
bool HotStandbyActiveInReplay ( void  )

Definition at line 7936 of file xlog.c.

References AmStartupProcess, Assert, IsPostmasterEnvironment, and LocalHotStandbyActive.

Referenced by btree_xlog_vacuum().

7937 {
7939  return LocalHotStandbyActive;
7940 }
#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 8122 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().

8123 {
8125 
8126  /* ThisTimeLineID doesn't change so we need no lock to copy it */
8129 
8130  /* Use GetRedoRecPtr to copy the RedoRecPtr safely */
8131  (void) GetRedoRecPtr();
8132  /* Also update our copy of doPageWrites. */
8133  doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);
8134 
8135  /* Also initialize the working areas for constructing WAL records */
8136  InitXLogInsert();
8137 }
void InitXLogInsert(void)
Definition: xloginsert.c:1029
TimeLineID ThisTimeLineID
Definition: xlog.c:624
XLogCtlInsert Insert
Definition: xlog.c:570
bool fullPageWrites
Definition: xlog.c:544
static bool doPageWrites
Definition: xlog.c:357
bool forcePageWrites
Definition: xlog.c:543
static void Insert(File file)
Definition: fd.c:1007
TimeLineID ThisTimeLineID
Definition: xlog.c:179
#define Assert(condition)
Definition: c.h:675
static XLogCtlData * XLogCtl
Definition: xlog.c:701
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:8145
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:365
void issue_xlog_fsync ( int  fd,
XLogSegNo  segno 
)

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

10050 {
10051  switch (sync_method)
10052  {
10053  case SYNC_METHOD_FSYNC:
10054  if (pg_fsync_no_writethrough(fd) != 0)
10055  ereport(PANIC,
10057  errmsg("could not fsync log file %s: %m",
10058  XLogFileNameP(ThisTimeLineID, segno))));
10059  break;
10060 #ifdef HAVE_FSYNC_WRITETHROUGH
10062  if (pg_fsync_writethrough(fd) != 0)
10063  ereport(PANIC,
10065  errmsg("could not fsync write-through log file %s: %m",
10066  XLogFileNameP(ThisTimeLineID, segno))));
10067  break;
10068 #endif
10069 #ifdef HAVE_FDATASYNC
10070  case SYNC_METHOD_FDATASYNC:
10071  if (pg_fdatasync(fd) != 0)
10072  ereport(PANIC,
10074  errmsg("could not fdatasync log file %s: %m",
10075  XLogFileNameP(ThisTimeLineID, segno))));
10076  break;
10077 #endif
10078  case SYNC_METHOD_OPEN:
10080  /* write synced it already */
10081  break;
10082  default:
10083  elog(PANIC, "unrecognized wal_sync_method: %d", sync_method);
10084  break;
10085  }
10086 }
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:10092
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 7855 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(), 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(), XlogReadTwoPhaseData(), and XLogSendPhysical().

7856 {
7857  /*
7858  * We check shared state each time only until we leave recovery mode. We
7859  * can't re-enter recovery, so there's no need to keep checking after the
7860  * shared variable has once been seen false.
7861  */
7863  return false;
7864  else
7865  {
7866  /*
7867  * use volatile pointer to make sure we make a fresh read of the
7868  * shared variable.
7869  */
7870  volatile XLogCtlData *xlogctl = XLogCtl;
7871 
7873 
7874  /*
7875  * Initialize TimeLineID and RedoRecPtr when we discover that recovery
7876  * is finished. InitPostgres() relies upon this behaviour to ensure
7877  * that InitXLOGAccess() is called at backend startup. (If you change
7878  * this, see also LocalSetXLogInsertAllowed.)
7879  */
7881  {
7882  /*
7883  * If we just exited recovery, make sure we read TimeLineID and
7884  * RedoRecPtr after SharedRecoveryInProgress (for machines with
7885  * weak memory ordering).
7886  */
7888  InitXLOGAccess();
7889  }
7890 
7891  /*
7892  * Note: We don't need a memory barrier when we're still in recovery.
7893  * We might exit recovery immediately after return, so the caller
7894  * can't rely on 'true' meaning that we're still in recovery anyway.
7895  */
7896 
7897  return LocalRecoveryInProgress;
7898  }
7899 }
void InitXLOGAccess(void)
Definition: xlog.c:8122
bool SharedRecoveryInProgress
Definition: xlog.c:637
#define pg_memory_barrier()
Definition: atomics.h:147
static XLogCtlData * XLogCtl
Definition: xlog.c:701
static bool LocalRecoveryInProgress
Definition: xlog.c:215
bool RecoveryIsPaused ( void  )

Definition at line 5923 of file xlog.c.

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

Referenced by pg_is_wal_replay_paused(), and recoveryPausesHere().

5924 {
5925  bool recoveryPause;
5926 
5928  recoveryPause = XLogCtl->recoveryPause;
5930 
5931  return recoveryPause;
5932 }
slock_t info_lck
Definition: xlog.c:698
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:690
static XLogCtlData * XLogCtl
Definition: xlog.c:701
void RemovePromoteSignalFiles ( void  )

Definition at line 12018 of file xlog.c.

References FALLBACK_PROMOTE_SIGNAL_FILE, PROMOTE_SIGNAL_FILE, and unlink().

Referenced by PostmasterMain().

12019 {
12022 }
#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 5935 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().

5936 {
5938  XLogCtl->recoveryPause = recoveryPause;
5940 }
slock_t info_lck
Definition: xlog.c:698
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool recoveryPause
Definition: xlog.c:690
static XLogCtlData * XLogCtl
Definition: xlog.c:701
void SetWalWriterSleeping ( bool  sleeping)

Definition at line 12054 of file xlog.c.

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

Referenced by WalWriterMain().

12055 {
12057  XLogCtl->WalWriterSleeping = sleeping;
12059 }
slock_t info_lck
Definition: xlog.c:698
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
bool WalWriterSleeping
Definition: xlog.c:650
static XLogCtlData * XLogCtl
Definition: xlog.c:701
void ShutdownXLOG ( int  code,
Datum  arg 
)

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

8304 {
8305  /* Don't be chatty in standalone mode */
8307  (errmsg("shutting down")));
8308 
8309  if (RecoveryInProgress())
8311  else
8312  {
8313  /*
8314  * If archiving is enabled, rotate the last XLOG file so that all the
8315  * remaining records are archived (postmaster wakes up the archiver
8316  * process one more time at the end of shutdown). The checkpoint
8317  * record will go to the next XLOG file and won't be archived (yet).
8318  */
8320  RequestXLogSwitch(false);
8321 
8323  }
8324  ShutdownCLOG();
8325  ShutdownCommitTs();
8326  ShutdownSUBTRANS();
8328 }
bool IsPostmasterEnvironment
Definition: globals.c:99
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
Definition: xlog.c:9372
void ShutdownSUBTRANS(void)
Definition: subtrans.c:270
void CreateCheckPoint(int flags)
Definition: xlog.c:8499
void ShutdownCLOG(void)
Definition: clog.c:574
bool CreateRestartPoint(int flags)
Definition: xlog.c:9041
#define XLogArchiveCommandSet()
Definition: xlog.h:139
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:7855
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 6182 of file xlog.c.

References 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(), 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().

6183 {
6185  CheckPoint checkPoint;
6186  bool wasShutdown;
6187  bool reachedStopPoint = false;
6188  bool haveBackupLabel = false;
6189  bool haveTblspcMap = false;
6190  XLogRecPtr RecPtr,
6191  checkPointLoc,
6192  EndOfLog;
6193  TimeLineID EndOfLogTLI;
6194  TimeLineID PrevTimeLineID;
6195  XLogRecord *record;
6196  TransactionId oldestActiveXID;
6197  bool backupEndRequired = false;
6198  bool backupFromStandby = false;
6199  DBState dbstate_at_startup;
6200  XLogReaderState *xlogreader;
6201  XLogPageReadPrivate private;
6202  bool fast_promoted = false;
6203  struct stat st;
6204 
6205  /*
6206  * Read control file and check XLOG status looks valid.
6207  *
6208  * Note: in most control paths, *ControlFile is already valid and we need
6209  * not do ReadControlFile() here, but might as well do it to be sure.
6210  */
6211  ReadControlFile();
6212 
6213  if (ControlFile->state < DB_SHUTDOWNED ||
6216  ereport(FATAL,
6217  (errmsg("control file contains invalid data")));
6218 
6220  {
6221  /* This is the expected case, so don't be chatty in standalone mode */
6223  (errmsg("database system was shut down at %s",
6224  str_time(ControlFile->time))));
6225  }
6227  ereport(LOG,
6228  (errmsg("database system was shut down in recovery at %s",
6229  str_time(ControlFile->time))));
6230  else if (ControlFile->state == DB_SHUTDOWNING)
6231  ereport(LOG,
6232  (errmsg("database system shutdown was interrupted; last known up at %s",
6233  str_time(ControlFile->time))));
6234  else if (ControlFile->state == DB_IN_CRASH_RECOVERY)
6235  ereport(LOG,
6236  (errmsg("database system was interrupted while in recovery at %s",
6238  errhint("This probably means that some data is corrupted and"
6239  " you will have to use the last backup for recovery.")));
6241  ereport(LOG,
6242  (errmsg("database system was interrupted while in recovery at log time %s",
6244  errhint("If this has occurred more than once some data might be corrupted"
6245  " and you might need to choose an earlier recovery target.")));
6246  else if (ControlFile->state == DB_IN_PRODUCTION)
6247  ereport(LOG,
6248  (errmsg("database system was interrupted; last known up at %s",
6249  str_time(ControlFile->time))));
6250 
6251  /* This is just to allow attaching to startup process with a debugger */
6252 #ifdef XLOG_REPLAY_DELAY
6254  pg_usleep(60000000L);
6255 #endif
6256 
6257  /*
6258  * Verify that pg_wal and pg_wal/archive_status exist. In cases where
6259  * someone has performed a copy for PITR, these directories may have been
6260  * excluded and need to be re-created.
6261  */
6263 
6264  /*
6265  * If we previously crashed, there might be data which we had written,
6266  * intending to fsync it, but which we had not actually fsync'd yet.
6267  * Therefore, a power failure in the near future might cause earlier
6268  * unflushed writes to be lost, even though more recent data written to
6269  * disk from here on would be persisted. To avoid that, fsync the entire
6270  * data directory.
6271  */
6272  if (ControlFile->state != DB_SHUTDOWNED &&
6275 
6276  /*
6277  * Initialize on the assumption we want to recover to the latest timeline
6278  * that's active according to pg_control.
6279  */
6283  else
6285 
6286  /*
6287  * Check for recovery control file, and if so set up state for offline
6288  * recovery
6289  */
6291 
6292  /*
6293  * Save archive_cleanup_command in shared memory so that other processes
6294  * can see it.
6295  */
6298  sizeof(XLogCtl->archiveCleanupCommand));
6299 
6301  {
6303  ereport(LOG,
6304  (errmsg("entering standby mode")));
6305  else if (recoveryTarget == RECOVERY_TARGET_XID)
6306  ereport(LOG,
6307  (errmsg("starting point-in-time recovery to XID %u",
6308  recoveryTargetXid)));
6310  ereport(LOG,
6311  (errmsg("starting point-in-time recovery to %s",
6314  ereport(LOG,
6315  (errmsg("starting point-in-time recovery to \"%s\"",
6316  recoveryTargetName)));
6317  else if (recoveryTarget == RECOVERY_TARGET_LSN)
6318  ereport(LOG,
6319  (errmsg("starting point-in-time recovery to WAL position (LSN) \"%X/%X\"",
6320  (uint32) (recoveryTargetLSN >> 32),
6323  ereport(LOG,
6324  (errmsg("starting point-in-time recovery to earliest consistent point")));
6325  else
6326  ereport(LOG,
6327  (errmsg("starting archive recovery")));
6328  }
6329 
6330  /*
6331  * Take ownership of the wakeup latch if we're going to sleep during
6332  * recovery.
6333  */
6336 
6337  /* Set up XLOG reader facility */
6338  MemSet(&private, 0, sizeof(XLogPageReadPrivate));
6339  xlogreader = XLogReaderAllocate(&XLogPageRead, &private);
6340  if (!xlogreader)
6341  ereport(ERROR,
6342  (errcode(ERRCODE_OUT_OF_MEMORY),
6343  errmsg("out of memory"),
6344  errdetail("Failed while allocating a WAL reading processor.")));
6346 
6347  /*
6348  * Allocate pages dedicated to WAL consistency checks, those had better
6349  * be aligned.
6350  */
6351  replay_image_masked = (char *) palloc(BLCKSZ);
6352  master_image_masked = (char *) palloc(BLCKSZ);
6353 
6354  if (read_backup_label(&checkPointLoc, &backupEndRequired,
6355  &backupFromStandby))
6356  {
6357  List *tablespaces = NIL;
6358 
6359  /*
6360  * Archive recovery was requested, and thanks to the backup label
6361  * file, we know how far we need to replay to reach consistency. Enter
6362  * archive recovery directly.
6363  */
6364  InArchiveRecovery = true;
6366  StandbyMode = true;
6367 
6368  /*
6369  * When a backup_label file is present, we want to roll forward from
6370  * the checkpoint it identifies, rather than using pg_control.
6371  */
6372  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 0, true);
6373  if (record != NULL)
6374  {
6375  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
6376  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
6377  ereport(DEBUG1,
6378  (errmsg("checkpoint record is at %X/%X",
6379  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6380  InRecovery = true; /* force recovery even if SHUTDOWNED */
6381 
6382  /*
6383  * Make sure that REDO location exists. This may not be the case
6384  * if there was a crash during an online backup, which left a
6385  * backup_label around that references a WAL segment that's
6386  * already been archived.
6387  */
6388  if (checkPoint.redo < checkPointLoc)
6389  {
6390  if (!ReadRecord(xlogreader, checkPoint.redo, LOG, false))
6391  ereport(FATAL,
6392  (errmsg("could not find redo location referenced by checkpoint record"),
6393  errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6394  }
6395  }
6396  else
6397  {
6398  ereport(FATAL,
6399  (errmsg("could not locate required checkpoint record"),
6400  errhint("If you are not restoring from a backup, try removing the file \"%s/backup_label\".", DataDir)));
6401  wasShutdown = false; /* keep compiler quiet */
6402  }
6403 
6404  /* read the tablespace_map file if present and create symlinks. */
6405  if (read_tablespace_map(&tablespaces))
6406  {
6407  ListCell *lc;
6408 
6409  foreach(lc, tablespaces)
6410  {
6411  tablespaceinfo *ti = lfirst(lc);
6412  char *linkloc;
6413 
6414  linkloc = psprintf("pg_tblspc/%s", ti->oid);
6415 
6416  /*
6417  * Remove the existing symlink if any and Create the symlink
6418  * under PGDATA.
6419  */
6420  remove_tablespace_symlink(linkloc);
6421 
6422  if (symlink(ti->path, linkloc) < 0)
6423  ereport(ERROR,
6425  errmsg("could not create symbolic link \"%s\": %m",
6426  linkloc)));
6427 
6428  pfree(ti->oid);
6429  pfree(ti->path);
6430  pfree(ti);
6431  }
6432 
6433  /* set flag to delete it later */
6434  haveTblspcMap = true;
6435  }
6436 
6437  /* set flag to delete it later */
6438  haveBackupLabel = true;
6439  }
6440  else
6441  {
6442  /*
6443  * If tablespace_map file is present without backup_label file, there
6444  * is no use of such file. There is no harm in retaining it, but it
6445  * is better to get rid of the map file so that we don't have any
6446  * redundant file in data directory and it will avoid any sort of
6447  * confusion. It seems prudent though to just rename the file out of
6448  * the way rather than delete it completely, also we ignore any error
6449  * that occurs in rename operation as even if map file is present
6450  * without backup_label file, it is harmless.
6451  */
6452  if (stat(TABLESPACE_MAP, &st) == 0)
6453  {
6456  ereport(LOG,
6457  (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
6459  errdetail("File \"%s\" was renamed to \"%s\".",
6461  else
6462  ereport(LOG,
6463  (errmsg("ignoring file \"%s\" because no file \"%s\" exists",
6465  errdetail("Could not rename file \"%s\" to \"%s\": %m.",
6467  }
6468 
6469  /*
6470  * It's possible that archive recovery was requested, but we don't
6471  * know how far we need to replay the WAL before we reach consistency.
6472  * This can happen for example if a base backup is taken from a
6473  * running server using an atomic filesystem snapshot, without calling
6474  * pg_start/stop_backup. Or if you just kill a running master server
6475  * and put it into archive recovery by creating a recovery.conf file.
6476  *
6477  * Our strategy in that case is to perform crash recovery first,
6478  * replaying all the WAL present in pg_wal, and only enter archive
6479  * recovery after that.
6480  *
6481  * But usually we already know how far we need to replay the WAL (up
6482  * to minRecoveryPoint, up to backupEndPoint, or until we see an
6483  * end-of-backup record), and we can enter archive recovery directly.
6484  */
6490  {
6491  InArchiveRecovery = true;
6493  StandbyMode = true;
6494  }
6495 
6496  /*
6497  * Get the last valid checkpoint record. If the latest one according
6498  * to pg_control is broken, try the next-to-last one.
6499  */
6500  checkPointLoc = ControlFile->checkPoint;
6502  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 1, true);
6503  if (record != NULL)
6504  {
6505  ereport(DEBUG1,
6506  (errmsg("checkpoint record is at %X/%X",
6507  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6508  }
6509  else if (StandbyMode)
6510  {
6511  /*
6512  * The last valid checkpoint record required for a streaming
6513  * recovery exists in neither standby nor the primary.
6514  */
6515  ereport(PANIC,
6516  (errmsg("could not locate a valid checkpoint record")));
6517  }
6518  else
6519  {
6520  checkPointLoc = ControlFile->prevCheckPoint;
6521  record = ReadCheckpointRecord(xlogreader, checkPointLoc, 2, true);
6522  if (record != NULL)
6523  {
6524  ereport(LOG,
6525  (errmsg("using previous checkpoint record at %X/%X",
6526  (uint32) (checkPointLoc >> 32), (uint32) checkPointLoc)));
6527  InRecovery = true; /* force recovery even if SHUTDOWNED */
6528  }
6529  else
6530  ereport(PANIC,
6531  (errmsg("could not locate a valid checkpoint record")));
6532  }
6533  memcpy(&checkPoint, XLogRecGetData(xlogreader), sizeof(CheckPoint));
6534  wasShutdown = ((record->xl_info & ~XLR_INFO_MASK) == XLOG_CHECKPOINT_SHUTDOWN);
6535  }
6536 
6537  /*
6538  * Clear out any old relcache cache files. This is *necessary* if we do
6539  * any WAL replay, since that would probably result in the cache files
6540  * being out of sync with database reality. In theory we could leave them
6541  * in place if the database had been cleanly shut down, but it seems
6542  * safest to just remove them always and let them be rebuilt during the
6543  * first backend startup. These files needs to be removed from all
6544  * directories including pg_tblspc, however the symlinks are created only
6545  * after reading tablespace_map file in case of archive recovery from
6546  * backup, so needs to clear old relcache files here after creating
6547  * symlinks.
6548  */
6550 
6551  /*
6552  * If the location of the checkpoint record is not on the expected
6553  * timeline in the history of the requested timeline, we cannot proceed:
6554  * the backup is not part of the history of the requested timeline.
6555  */
6556  Assert(expectedTLEs); /* was initialized by reading checkpoint
6557  * record */
6558  if (tliOfPointInHistory(checkPointLoc, expectedTLEs) !=
6559  checkPoint.ThisTimeLineID)
6560  {
6561  XLogRecPtr switchpoint;
6562 
6563  /*
6564  * tliSwitchPoint will throw an error if the checkpoint's timeline is
6565  * not in expectedTLEs at all.
6566  */
6568  ereport(FATAL,
6569  (errmsg("requested timeline %u is not a child of this server's history",
6571  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.",
6572  (uint32) (ControlFile->checkPoint >> 32),
6575  (uint32) (switchpoint >> 32),
6576  (uint32) switchpoint)));
6577  }
6578 
6579  /*
6580  * The min recovery point should be part of the requested timeline's
6581  * history, too.
6582  */
6586  ereport(FATAL,
6587  (errmsg("requested timeline %u does not contain minimum recovery point %X/%X on timeline %u",
6589  (uint32) (ControlFile->minRecoveryPoint >> 32),
6592 
6593  LastRec = RecPtr = checkPointLoc;
6594 
6595  ereport(DEBUG1,
6596  (errmsg_internal("redo record is at %X/%X; shutdown %s",
6597  (uint32) (checkPoint.redo >> 32), (uint32) checkPoint.redo,
6598  wasShutdown ? "TRUE" : "FALSE")));
6599  ereport(DEBUG1,
6600  (errmsg_internal("next transaction ID: %u:%u; next OID: %u",
6601  checkPoint.nextXidEpoch, checkPoint.nextXid,
6602  checkPoint.nextOid)));
6603  ereport(DEBUG1,
6604  (errmsg_internal("next MultiXactId: %u; next MultiXactOffset: %u",
6605  checkPoint.nextMulti, checkPoint.nextMultiOffset)));
6606  ereport(DEBUG1,
6607  (errmsg_internal("oldest unfrozen transaction ID: %u, in database %u",
6608  checkPoint.oldestXid, checkPoint.oldestXidDB)));
6609  ereport(DEBUG1,
6610  (errmsg_internal("oldest MultiXactId: %u, in database %u",
6611  checkPoint.oldestMulti, checkPoint.oldestMultiDB)));
6612  ereport(DEBUG1,
6613  (errmsg_internal("commit timestamp Xid oldest/newest: %u/%u",
6614  checkPoint.oldestCommitTsXid,
6615  checkPoint.newestCommitTsXid)));
6616  if (!TransactionIdIsNormal(checkPoint.nextXid))
6617  ereport(PANIC,
6618  (errmsg("invalid next transaction ID")));
6619 
6620  /* initialize shared memory variables from the checkpoint record */
6621  ShmemVariableCache->nextXid = checkPoint.nextXid;
6622  ShmemVariableCache->nextOid = checkPoint.nextOid;
6624  MultiXactSetNextMXact(checkPoint.nextMulti, checkPoint.nextMultiOffset);
6625  SetTransactionIdLimit(checkPoint.oldestXid, checkPoint.oldestXidDB);
6626  SetMultiXactIdLimit(checkPoint.oldestMulti, checkPoint.oldestMultiDB, true);
6628  checkPoint.newestCommitTsXid);
6629  XLogCtl->ckptXidEpoch = checkPoint.nextXidEpoch;
6630  XLogCtl->ckptXid = checkPoint.nextXid;
6631 
6632  /*
6633  * Initialize replication slots, before there's a chance to remove
6634  * required resources.
6635  */
6637 
6638  /*
6639  * Startup logical state, needs to be setup now so we have proper data
6640  * during crash recovery.
6641  */
6643 
6644  /*
6645  * Startup MultiXact. We need to do this early to be able to replay
6646  * truncations.
6647  */
6648  StartupMultiXact();
6649 
6650  /*
6651  * Ditto commit timestamps. In a standby, we do it if setting is enabled
6652  * in ControlFile; in a master we base the decision on the GUC itself.
6653  */
6656  StartupCommitTs();
6657 
6658  /*
6659  * Recover knowledge about replay progress of known replication partners.
6660  */
6662 
6663  /*
6664  * Initialize unlogged LSN. On a clean shutdown, it's restored from the
6665  * control file. On recovery, all unlogged relations are blown away, so
6666  * the unlogged LSN counter can be reset too.
6667  */
6670  else
6671  XLogCtl->unloggedLSN = 1;
6672 
6673  /*
6674  * We must replay WAL entries using the same TimeLineID they were created
6675  * under, so temporarily adopt the TLI indicated by the checkpoint (see
6676  * also xlog_redo()).
6677  */
6678  ThisTimeLineID = checkPoint.ThisTimeLineID;
6679 
6680  /*
6681  * Copy any missing timeline history files between 'now' and the recovery
6682  * target timeline from archive to pg_wal. While we don't need those
6683  * files ourselves - the history file of the recovery target timeline
6684  * covers all the previous timelines in the history too - a cascading
6685  * standby server might be interested in them. Or, if you archive the WAL
6686  * from this server to a different archive than the master, it'd be good
6687  * for all the history files to get archived there after failover, so that
6688  * you can use one of the old timelines as a PITR target. Timeline history
6689  * files are small, so it's better to copy them unnecessarily than not
6690  * copy them and regret later.
6691  */
6693 
6694  lastFullPageWrites = checkPoint.fullPageWrites;
6695 
6698 
6699  if (RecPtr < checkPoint.redo)
6700  ereport(PANIC,
6701  (errmsg("invalid redo in checkpoint record")));
6702 
6703  /*
6704  * Check whether we need to force recovery from WAL. If it appears to
6705  * have been a clean shutdown and we did not have a recovery.conf file,
6706  * then assume no recovery needed.
6707  */
6708  if (checkPoint.redo < RecPtr)
6709  {
6710  if (wasShutdown)
6711  ereport(PANIC,
6712  (errmsg("invalid redo record in shutdown checkpoint")));
6713  InRecovery = true;
6714  }
6715  else if (ControlFile->state != DB_SHUTDOWNED)
6716  InRecovery = true;
6717  else if (ArchiveRecoveryRequested)
6718  {
6719  /* force recovery due to presence of recovery.conf */
6720  InRecovery = true;
6721  }
6722 
6723  /* REDO */
6724  if (InRecovery)
6725  {
6726  int rmid;
6727 
6728  /*
6729  * Update pg_control to show that we are recovering and to show the
6730  * selected checkpoint as the place we are starting from. We also mark
6731  * pg_control with any minimum recovery stop point obtained from a
6732  * backup history file.
6733  */
6734  dbstate_at_startup = ControlFile->state;
6735  if (InArchiveRecovery)
6737  else
6738  {
6739  ereport(LOG,
6740  (errmsg("database system was not properly shut down; "
6741  "automatic recovery in progress")));
6743  ereport(LOG,
6744  (errmsg("crash recovery starts in timeline %u "
6745  "and has target timeline %u",
6747  recoveryTargetTLI)));
6749  }
6751  ControlFile->checkPoint = checkPointLoc;
6752  ControlFile->checkPointCopy = checkPoint;
6753  if (InArchiveRecovery)
6754  {
6755  /* initialize minRecoveryPoint if not set yet */
6756  if (ControlFile->minRecoveryPoint < checkPoint.redo)
6757  {
6758  ControlFile->minRecoveryPoint = checkPoint.redo;
6760  }
6761  }
6762 
6763  /*
6764  * Set backupStartPoint if we're starting recovery from a base backup.
6765  *
6766  * Also set backupEndPoint and use minRecoveryPoint as the backup end
6767  * location if we're starting recovery from a base backup which was
6768  * taken from a standby. In this case, the database system status in
6769  * pg_control must indicate that the database was already in recovery.
6770  * Usually that will be DB_IN_ARCHIVE_RECOVERY but also can be
6771  * DB_SHUTDOWNED_IN_RECOVERY if recovery previously was interrupted
6772  * before reaching this point; e.g. because restore_command or
6773  * primary_conninfo were faulty.
6774  *
6775  * Any other state indicates that the backup somehow became corrupted
6776  * and we can't sensibly continue with recovery.
6777  */
6778  if (haveBackupLabel)
6779  {
6780  ControlFile->backupStartPoint = checkPoint.redo;
6781  ControlFile->backupEndRequired = backupEndRequired;
6782 
6783  if (backupFromStandby)
6784  {
6785  if (dbstate_at_startup != DB_IN_ARCHIVE_RECOVERY &&
6786  dbstate_at_startup != DB_SHUTDOWNED_IN_RECOVERY)
6787  ereport(FATAL,
6788  (errmsg("backup_label contains data inconsistent with control file"),
6789  errhint("This means that the backup is corrupted and you will "
6790  "have to use another backup for recovery.")));
6792  }
6793  }
6794  ControlFile->time = (pg_time_t) time(NULL);
6795  /* No need to hold ControlFileLock yet, we aren't up far enough */
6797 
6798  /* initialize our local copy of minRecoveryPoint */
6801 
6802  /*
6803  * Reset pgstat data, because it may be invalid after recovery.
6804  */
6805  pgstat_reset_all();
6806 
6807  /*
6808  * If there was a backup label file, it's done its job and the info
6809  * has now been propagated into pg_control. We must get rid of the
6810  * label file so that if we crash during recovery, we'll pick up at
6811  * the latest recovery restartpoint instead of going all the way back
6812  * to the backup start point. It seems prudent though to just rename
6813  * the file out of the way rather than delete it completely.
6814  */
6815  if (haveBackupLabel)
6816  {
6819  }
6820 
6821  /*
6822  * If there was a tablespace_map file, it's done its job and the
6823  * symlinks have been created. We must get rid of the map file so
6824  * that if we crash during recovery, we don't create symlinks again.
6825  * It seems prudent though to just rename the file out of the way
6826  * rather than delete it completely.
6827  */
6828  if (haveTblspcMap)
6829  {
6832  }
6833 
6834  /* Check that the GUCs used to generate the WAL allow recovery */
6836 
6837  /*
6838  * We're in recovery, so unlogged relations may be trashed and must be
6839  * reset. This should be done BEFORE allowing Hot Standby
6840  * connections, so that read-only backends don't try to read whatever
6841  * garbage is left over from before.
6842  */
6844 
6845  /*
6846  * Likewise, delete any saved transaction snapshot files that got left
6847  * behind by crashed backends.
6848  */
6850 
6851  /*
6852  * Initialize for Hot Standby, if enabled. We won't let backends in
6853  * yet, not until we've reached the min recovery point specified in
6854  * control file and we've established a recovery snapshot from a
6855  * running-xacts WAL record.
6856  */
6858  {
6859  TransactionId *xids;
6860  int nxids;
6861 
6862  ereport(DEBUG1,
6863  (errmsg("initializing for hot standby")));
6864 
6866 
6867  if (wasShutdown)
6868  oldestActiveXID = PrescanPreparedTransactions(&xids, &nxids);
6869  else
6870  oldestActiveXID = checkPoint.oldestActiveXid;
6871  Assert(TransactionIdIsValid(oldestActiveXID));
6872 
6873  /* Tell procarray about the range of xids it has to deal with */
6875 
6876  /*
6877  * Startup commit log and subtrans only. MultiXact and commit
6878  * timestamp have already been started up and other SLRUs are not
6879  * maintained during recovery and need not be started yet.
6880  */
6881  StartupCLOG();
6882  StartupSUBTRANS(oldestActiveXID);
6883 
6884  /*
6885  * If we're beginning at a shutdown checkpoint, we know that
6886  * nothing was running on the master at this point. So fake-up an
6887  * empty running-xacts record and use that here and now. Recover
6888  * additional standby state for prepared transactions.
6889  */
6890  if (wasShu